@womp/spark-agent 1.0.1 → 2.0.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 (47) hide show
  1. package/README.md +37 -19
  2. package/dist/capabilities/scene-draft.d.ts +2 -404
  3. package/dist/capabilities/scene.d.ts +1 -1
  4. package/dist/capabilities/scene.js +13 -4
  5. package/dist/cli.js +19 -2
  6. package/dist/client.js +15 -15
  7. package/dist/coordinates.d.ts +23 -0
  8. package/dist/coordinates.js +132 -0
  9. package/dist/generated/scene-declarations.d.ts +1 -1
  10. package/dist/generated/scene-declarations.js +1 -1
  11. package/dist/index.d.ts +2 -0
  12. package/dist/index.js +2 -0
  13. package/dist/kakapo.d.ts +4 -5
  14. package/dist/kakapo.js +2 -6
  15. package/dist/pricing.js +9 -29
  16. package/dist/runtime.d.ts +16 -36
  17. package/dist/runtime.js +132 -139
  18. package/dist/scene-environment.d.ts +25 -0
  19. package/dist/scene-environment.js +76 -0
  20. package/dist/scene-metadata.d.ts +6 -0
  21. package/dist/scene-metadata.js +65 -0
  22. package/dist/scene-operations.d.ts +47 -0
  23. package/dist/scene-operations.js +126 -0
  24. package/dist/sdk-scene-host.d.ts +309 -0
  25. package/dist/sdk-scene-host.js +201 -0
  26. package/dist/sdk-scene-screenshot.d.ts +7 -0
  27. package/dist/sdk-scene-screenshot.js +17 -0
  28. package/dist/server/demo-scene-materials.d.ts +3 -0
  29. package/dist/server/demo-scene-materials.js +18 -0
  30. package/dist/server/express.js +2 -4
  31. package/dist/server/fixtures/materials/matte-blue.json +14 -0
  32. package/dist/server/fixtures/materials/polished-copper.json +14 -0
  33. package/dist/server/index.d.ts +2 -1
  34. package/dist/server/index.js +2 -1
  35. package/dist/server/service.d.ts +4 -0
  36. package/dist/server/service.js +26 -2
  37. package/dist/server/sqlite-store.d.ts +29 -0
  38. package/dist/server/sqlite-store.js +200 -0
  39. package/dist/server/standalone.d.ts +5 -1
  40. package/dist/server/standalone.js +78 -21
  41. package/dist/server/store.js +3 -1
  42. package/dist/types.d.ts +1 -1
  43. package/dist/womp-scene-api.d.ts +283 -0
  44. package/dist/womp-scene-api.js +974 -0
  45. package/package.json +7 -9
  46. package/dist/kakapo-capability.d.ts +0 -45
  47. package/dist/kakapo-capability.js +0 -169
package/dist/runtime.js CHANGED
@@ -1,7 +1,8 @@
1
- import { KakapoAPI } from "@womp/kakapo-sdk";
2
- import { createSceneApi } from "@womp/scene-api";
3
- import { createKakapoSceneStore, createKakapoTransaction, } from "@womp/scene-api/adapters/kakapo";
1
+ import { KakapoAPI, KakapoSceneCommitError } from "@womp/kakapo-sdk";
4
2
  import { QuickJSJavaScriptExecutor } from "./quickjs-executor.js";
3
+ import { createWompSceneApi } from "./womp-scene-api.js";
4
+ import { writeMaterialMetadata } from "./scene-metadata.js";
5
+ import { captureSdkSceneScreenshot } from "./sdk-scene-screenshot.js";
5
6
  function safeValue(value) {
6
7
  if (value instanceof Uint8Array)
7
8
  return { bytes: value.byteLength };
@@ -14,73 +15,15 @@ function safeValue(value) {
14
15
  return String(value);
15
16
  }
16
17
  }
17
- /**
18
- * Kakapo has no library-material concept, so `pending` stays absent -- the
19
- * "backing with no queue" case `@womp/scene-api`'s `MaterialCatalog` documents.
20
- * `nodeSetMaterialId` with a NAME still fails loudly rather than silently
21
- * dropping the assignment.
22
- */
23
- const KAKAPO_MATERIAL_CATALOG = {
24
- listSuperMaterialNames: () => [],
25
- };
26
- export async function composeKakapoSceneSeams(engine, fonts) {
27
- // Prefetched because `listFonts()` is an async RPC while the seam's
28
- // `listFontFamilies` is synchronous.
29
- const resolved = fonts ?? (await engine.listFonts());
30
- let captured;
31
- await engine.editScene((scene) => {
32
- captured = scene;
33
- });
34
- if (captured === undefined) {
35
- throw new Error("engine.editScene() resolved without invoking its callback.");
36
- }
37
- const edit = captured;
38
- return {
39
- store: createKakapoSceneStore(edit, engine, { fonts: resolved }),
40
- transaction: createKakapoTransaction(engine),
41
- scene: () => edit.getScene(),
42
- };
43
- }
44
- /**
45
- * `createSceneApi` returns `Record<string, unknown>` (its `SceneScriptApi`), so
46
- * naming it as the draft the capability declares takes one cast. It is not a
47
- * blind one: `test/kakapo-capability.test.ts`'s "the generated skill documents
48
- * the exact executable draft surface" asserts set equality between
49
- * `WompSceneDraft`'s members and the functions this object actually exposes, in
50
- * both directions, so a drift on either side fails a test rather than surfacing
51
- * as a `TypeError` inside a model-authored script.
52
- */
53
- export function asSceneDraft(api) {
54
- return api;
55
- }
56
- /**
57
- * Records every WRITE method invoked on `store`, in call order, once the call
58
- * has succeeded -- the `sdkCalls` the old per-call `sceneCall` wrapper
59
- * reported. Read methods (`get*`/`list*`/`child*`) were never routed through it
60
- * either, and are excluded so `sdkCalls` says what the script CHANGED rather
61
- * than what it merely inspected. Ported from `@womp/spark-agent-host`.
62
- */
63
- function trackedStore(store, calls) {
64
- const readPrefixes = ["get", "list", "child"];
65
- return new Proxy(store, {
66
- get(target, property, receiver) {
67
- const value = Reflect.get(target, property, receiver);
68
- if (typeof value !== "function" || typeof property !== "string")
69
- return value;
70
- if (readPrefixes.some((prefix) => property.startsWith(prefix)))
71
- return value.bind(target);
72
- return (...args) => {
73
- const result = value.apply(target, args);
74
- calls.push(property);
75
- return result;
76
- };
77
- },
78
- });
79
- }
80
18
  export class KakapoRuntime {
81
19
  api;
20
+ rootId = 0;
21
+ defaultMaterialId;
82
22
  calls = [];
83
- seams;
23
+ materialIds = new Set();
24
+ createdIds = new Set();
25
+ editOrdinals = new WeakMap();
26
+ fonts = [];
84
27
  executor;
85
28
  eventSink;
86
29
  constructor(url, executorOrEventSink, eventSink) {
@@ -104,21 +47,15 @@ export class KakapoRuntime {
104
47
  }
105
48
  async connect() {
106
49
  await this.sdkCall("connect", [], () => this.api.connect());
107
- const fonts = await this.sdkCall("listFonts", [], () => this.api.listFonts());
108
- this.seams = await composeKakapoSceneSeams(this.api, fonts);
50
+ this.fonts = await this.sdkCall("listFonts", [], () => this.api.listFonts());
51
+ this.rootId = 0;
109
52
  }
110
53
  disconnect() {
111
54
  this.api.disconnect();
112
55
  }
113
56
  async sdkCall(method, args, action) {
114
57
  const callId = crypto.randomUUID();
115
- this.emit({
116
- type: "sdk-call",
117
- callId,
118
- method,
119
- status: "running",
120
- args: safeValue(args),
121
- });
58
+ this.emit({ type: "sdk-call", callId, method, status: "running", args: safeValue(args) });
122
59
  try {
123
60
  const value = await action();
124
61
  this.calls.push(method);
@@ -142,43 +79,103 @@ export class KakapoRuntime {
142
79
  throw error;
143
80
  }
144
81
  }
145
- requireSeams(caller) {
146
- if (this.seams === undefined) {
147
- throw new Error(`${caller}: connect() must resolve before the scene can be reached.`);
82
+ sceneCall(method, args, action) {
83
+ const callId = crypto.randomUUID();
84
+ this.emit({ type: "sdk-call", callId, method, status: "running", args: safeValue(args) });
85
+ try {
86
+ const value = action();
87
+ this.calls.push(method);
88
+ this.emit({ type: "sdk-call", callId, method, status: "complete", result: safeValue(value) });
89
+ return value;
90
+ }
91
+ catch (error) {
92
+ this.emit({
93
+ type: "sdk-call",
94
+ callId,
95
+ method,
96
+ status: "error",
97
+ error: error instanceof Error ? error.message : String(error),
98
+ });
99
+ throw error;
148
100
  }
149
- return this.seams;
150
101
  }
151
- sceneApi(seams, print) {
152
- return createSceneApi({
153
- store: trackedStore(seams.store, this.calls),
154
- transaction: seams.transaction,
155
- catalog: KAKAPO_MATERIAL_CATALOG,
102
+ requireNode(id) {
103
+ this.api.getNode(id);
104
+ }
105
+ sceneApi(scene, print) {
106
+ return createWompSceneApi({
107
+ scene,
108
+ engine: this.api,
109
+ rootId: this.rootId,
110
+ getDefaultMaterialId: () => {
111
+ if (this.defaultMaterialId !== undefined)
112
+ return this.defaultMaterialId;
113
+ const material = this.sceneCall("createMaterial", [], () => scene.createMaterial({
114
+ color: { x: 189 / 255, y: 189 / 255, z: 189 / 255 },
115
+ roughness: 0.22,
116
+ }));
117
+ this.defaultMaterialId = material.id;
118
+ this.materialIds.add(material.id);
119
+ writeMaterialMetadata(scene, material.id, { name: "Default Material", tier: 0 });
120
+ return material.id;
121
+ },
122
+ fonts: this.fonts,
123
+ requireNode: (id) => this.requireNode(id),
124
+ trackNode: (id) => this.createdIds.add(id),
125
+ trackMaterial: (id) => this.materialIds.add(id),
126
+ untrackMaterial: (id) => {
127
+ this.materialIds.delete(id);
128
+ },
129
+ listMaterialIds: () => this.api.listMaterials().map(({ id }) => id),
130
+ requireMaterial: (id) => {
131
+ this.api.getMaterial(id);
132
+ },
133
+ call: (method, args, action) => this.sceneCall(method, args, action),
134
+ callAsync: (method, args, action) => this.sdkCall(method, args, action),
156
135
  print,
157
136
  });
158
137
  }
159
- async screenshot(input) {
160
- let targetId;
161
- if (input.targetId !== undefined) {
162
- let target = this.api.getNode(input.targetId);
163
- while (target.parentId !== null && target.parentId !== 0) {
164
- target = this.api.getNode(target.parentId);
165
- }
166
- targetId = target.kind === "union" || target.kind === "group" ? target.id : input.targetId;
167
- }
168
- const view = input.view ?? "isometric";
169
- const image = await this.sdkCall("captureScreenshot", [{ targetId, view }], () => this.api.captureScreenshot({ targetId, view, timeoutMs: 30_000 }));
170
- const screenshot = {
171
- data: image.data,
172
- mediaType: image.mediaType,
173
- width: image.width,
174
- height: image.height,
175
- view,
176
- targetId: image.targetId,
138
+ async inspect() {
139
+ await this.api.refreshScene();
140
+ return { revision: await this.api.getSceneRevision(), scene: this.api.getScene() };
141
+ }
142
+ async edit(callback, expectedRevision, context) {
143
+ let changed = false;
144
+ const ordinal = this.editOrdinals.get(context) ?? 0;
145
+ this.editOrdinals.set(context, ordinal + 1);
146
+ const receipt = {
147
+ id: `${context.runId}:${context.toolCallId}:scene.edit:${ordinal}`,
148
+ capability: "scene",
149
+ operation: "edit",
177
150
  };
178
- return screenshot;
151
+ let value;
152
+ try {
153
+ value = await this.api.editScene(async (scene) => {
154
+ context.signal.throwIfAborted();
155
+ if ((await this.api.getSceneRevision()) !== expectedRevision) {
156
+ throw new Error("Scene changed since inspection. Read the scene again before editing.");
157
+ }
158
+ const result = await callback(this.sceneApi(scene, () => undefined));
159
+ context.signal.throwIfAborted();
160
+ changed = (await this.api.getSceneRevision()) !== expectedRevision;
161
+ return result;
162
+ });
163
+ }
164
+ catch (error) {
165
+ await context.recordReceipt({
166
+ ...receipt,
167
+ status: error instanceof KakapoSceneCommitError ? error.outcome : "rolled_back",
168
+ });
169
+ throw error;
170
+ }
171
+ if (changed)
172
+ await context.recordReceipt({ ...receipt, status: "committed" });
173
+ return value;
174
+ }
175
+ async screenshot(input) {
176
+ return this.sdkCall("captureScreenshot", [input], () => captureSdkSceneScreenshot(this.api, input));
179
177
  }
180
178
  async execute(code, purpose) {
181
- const seams = this.requireSeams("execute");
182
179
  this.calls = [];
183
180
  const logs = [];
184
181
  this.emit({ type: "javascript", code, purpose });
@@ -193,15 +190,11 @@ export class KakapoRuntime {
193
190
  warn: (...values) => consoleFacade.log("WARN", ...values),
194
191
  error: (...values) => consoleFacade.log("ERROR", ...values),
195
192
  };
196
- let value;
197
- const globals = {
198
- ...this.sceneApi(seams, (...values) => consoleFacade.log(...values)),
199
- console: consoleFacade,
200
- };
201
- const failure = await seams.transaction.run(async () => {
202
- value = await this.executor.execute(code, globals, 60_000);
203
- });
204
- if (failure === null) {
193
+ try {
194
+ const value = await this.api.editScene((scene) => {
195
+ const api = this.sceneApi(scene, (...values) => consoleFacade.log(...values));
196
+ return this.executor.execute(code, { ...api, console: consoleFacade }, 60_000);
197
+ });
205
198
  const result = {
206
199
  ok: true,
207
200
  purpose,
@@ -219,30 +212,30 @@ export class KakapoRuntime {
219
212
  });
220
213
  return result;
221
214
  }
222
- const transactionError = `Transaction rolled back; no scene changes were applied. ${failure.message}`;
223
- this.emit({
224
- type: "console",
225
- text: `Execution error: ${transactionError}`,
226
- });
227
- const result = {
228
- ok: false,
229
- purpose,
230
- value: null,
231
- logs,
232
- sdkCalls: [...this.calls],
233
- error: transactionError,
234
- rolledBack: true,
235
- };
236
- this.emit({
237
- type: "execution-result",
238
- ok: result.ok,
239
- purpose: result.purpose,
240
- value: result.value,
241
- logs: result.logs,
242
- sdkCalls: result.sdkCalls,
243
- error: result.error,
244
- rolledBack: result.rolledBack,
245
- });
246
- return result;
215
+ catch (error) {
216
+ const message = error instanceof Error ? error.message : String(error);
217
+ const transactionError = `Transaction rolled back; no scene changes were applied. ${message}`;
218
+ this.emit({ type: "console", text: `Execution error: ${transactionError}` });
219
+ const result = {
220
+ ok: false,
221
+ purpose,
222
+ value: null,
223
+ logs,
224
+ sdkCalls: [...this.calls],
225
+ error: transactionError,
226
+ rolledBack: true,
227
+ };
228
+ this.emit({
229
+ type: "execution-result",
230
+ ok: result.ok,
231
+ purpose: result.purpose,
232
+ value: result.value,
233
+ logs: result.logs,
234
+ sdkCalls: result.sdkCalls,
235
+ error: result.error,
236
+ rolledBack: result.rolledBack,
237
+ });
238
+ return result;
239
+ }
247
240
  }
248
241
  }
@@ -0,0 +1,25 @@
1
+ import type { SceneEdit, Vec2, Vec3 } from "@womp/kakapo-sdk";
2
+ export type SceneHdr = {
3
+ id: string;
4
+ name: string;
5
+ defaultExposure: number;
6
+ };
7
+ export declare function createSceneEnvironment(scene: SceneEdit, hdrs: readonly SceneHdr[] | undefined, print: (...values: unknown[]) => void): {
8
+ scenePropertiesRead: () => {
9
+ hdr_name: string | undefined;
10
+ hdr_multiplier: number | undefined;
11
+ hdr_orientation: Vec2 | undefined;
12
+ backdrop_color1: Vec3 | undefined;
13
+ backdrop_color2: Vec3 | undefined;
14
+ backdrop_grad_offset: Vec2 | undefined;
15
+ };
16
+ listHDRs: () => string[];
17
+ setHdrName: (name: string) => void;
18
+ setHdrMultiplier: (multiplier: number) => void;
19
+ setHdrOrientation: (orientation: Vec2) => void;
20
+ setBackgroundColor: (color: {
21
+ r: number;
22
+ g: number;
23
+ b: number;
24
+ }) => void;
25
+ };
@@ -0,0 +1,76 @@
1
+ import { metadataObject } from "./scene-metadata.js";
2
+ function finite(value, label) {
3
+ if (!Number.isFinite(value))
4
+ throw new Error(`${label} must be a finite number`);
5
+ return value;
6
+ }
7
+ function publicColor(value) {
8
+ const color = metadataObject(value);
9
+ if (typeof color.x !== "number")
10
+ return undefined;
11
+ return {
12
+ x: Math.round(color.x * 255),
13
+ y: Math.round(Number(color.y ?? 0) * 255),
14
+ z: Math.round(Number(color.z ?? 0) * 255),
15
+ };
16
+ }
17
+ function vector2(value) {
18
+ const vector = metadataObject(value);
19
+ if (typeof vector.x !== "number" || typeof vector.y !== "number")
20
+ return undefined;
21
+ return { x: vector.x, y: vector.y };
22
+ }
23
+ export function createSceneEnvironment(scene, hdrs, print) {
24
+ const catalog = () => {
25
+ if (!hdrs)
26
+ throw new Error("The HDR catalog is unavailable in this host");
27
+ return hdrs;
28
+ };
29
+ const write = (values) => {
30
+ scene.patchSceneProperties(Object.entries(values).map(([key, value]) => ({
31
+ op: "add",
32
+ path: `/${key}`,
33
+ value,
34
+ })));
35
+ };
36
+ return {
37
+ scenePropertiesRead: () => {
38
+ const properties = scene.getSceneProperties();
39
+ return {
40
+ hdr_name: typeof properties.hdr_name === "string" ? properties.hdr_name : undefined,
41
+ hdr_multiplier: typeof properties.hdr_multiplier === "number"
42
+ ? properties.hdr_multiplier * 10 : undefined,
43
+ hdr_orientation: vector2(properties.hdr_orientation),
44
+ backdrop_color1: publicColor(properties.backdrop_color1),
45
+ backdrop_color2: publicColor(properties.backdrop_color2),
46
+ backdrop_grad_offset: vector2(properties.backdrop_grad_offset),
47
+ };
48
+ },
49
+ listHDRs: () => catalog().map(({ name }) => name),
50
+ setHdrName: (name) => {
51
+ const hdr = catalog().find((entry) => entry.name === name || entry.id === name);
52
+ if (!hdr)
53
+ throw new Error(`Unknown HDR: ${name}. Use listHDRs() to select an available HDR`);
54
+ const exposure = finite(hdr.defaultExposure, "HDR default exposure");
55
+ write({ hdr_name: hdr.id, hdr_multiplier: exposure / 10 });
56
+ print(`Set HDR name to: ${hdr.id}\nApplied default luminance: ${exposure}`);
57
+ },
58
+ setHdrMultiplier: (multiplier) => {
59
+ write({ hdr_multiplier: finite(multiplier, "HDR multiplier") / 10 });
60
+ print(`Set HDR multiplier to: ${multiplier}`);
61
+ },
62
+ setHdrOrientation: (orientation) => {
63
+ const x = finite(orientation?.x, "HDR orientation.x");
64
+ const y = finite(orientation?.y, "HDR orientation.y");
65
+ write({ hdr_orientation: { x, y } });
66
+ print(`Set HDR orientation to: (${x}, ${y})`);
67
+ },
68
+ setBackgroundColor: (color) => {
69
+ const r = finite(color?.r, "Background red");
70
+ const g = finite(color?.g, "Background green");
71
+ const b = finite(color?.b, "Background blue");
72
+ write({ backdrop_color1: { x: r / 255, y: g / 255, z: b / 255 } });
73
+ print(`Set background color to: (${r}, ${g}, ${b})`);
74
+ },
75
+ };
76
+ }
@@ -0,0 +1,6 @@
1
+ import type { JsonValue, SceneEdit } from "@womp/kakapo-sdk";
2
+ export declare function metadataObject(value: unknown): Record<string, JsonValue>;
3
+ export declare function readMaterialMetadata(scene: SceneEdit, id: number): Record<string, JsonValue>;
4
+ export declare function writeMaterialMetadata(scene: SceneEdit, id: number, changes: Record<string, JsonValue>): void;
5
+ export declare function removeMaterialMetadata(scene: SceneEdit, id: number): void;
6
+ export declare function shiftCurvePointMetadata(scene: SceneEdit, curveId: number, index: number, direction: 1 | -1): void;
@@ -0,0 +1,65 @@
1
+ export function metadataObject(value) {
2
+ return value !== null && typeof value === "object" && !Array.isArray(value)
3
+ ? value
4
+ : {};
5
+ }
6
+ export function readMaterialMetadata(scene, id) {
7
+ return metadataObject(metadataObject(scene.getSceneExt().materialsExt)[String(id)]);
8
+ }
9
+ export function writeMaterialMetadata(scene, id, changes) {
10
+ const materials = metadataObject(scene.getSceneExt().materialsExt);
11
+ scene.patchSceneExt([{
12
+ op: "add",
13
+ path: "/materialsExt",
14
+ value: { ...materials, [id]: { ...metadataObject(materials[String(id)]), ...changes } },
15
+ }]);
16
+ }
17
+ export function removeMaterialMetadata(scene, id) {
18
+ const materials = metadataObject(scene.getSceneExt().materialsExt);
19
+ if (!Object.hasOwn(materials, id))
20
+ return;
21
+ scene.patchSceneExt([{ op: "remove", path: `/materialsExt/${id}` }]);
22
+ }
23
+ export function shiftCurvePointMetadata(scene, curveId, index, direction) {
24
+ const shift = (value) => {
25
+ const result = {};
26
+ for (const [key, entry] of Object.entries(metadataObject(value))) {
27
+ const position = Number(key);
28
+ if (!Number.isInteger(position) || position < 0 || String(position) !== key) {
29
+ result[key] = entry;
30
+ continue;
31
+ }
32
+ if (direction === -1 && position === index)
33
+ continue;
34
+ result[position >= index ? position + direction : position] = entry;
35
+ }
36
+ return result;
37
+ };
38
+ const ext = scene.getSceneExt();
39
+ const curve = metadataObject(ext[String(curveId)]);
40
+ const points = shift(curve.pointsExt);
41
+ if (direction === 1) {
42
+ points[index] = {
43
+ locked: false,
44
+ libraryId: metadataObject(points[String(Math.max(0, index - 1))]).libraryId ?? -1,
45
+ name: `Point ${index + 1}`,
46
+ };
47
+ }
48
+ scene.patchSceneExt([{ op: "add", path: `/${curveId}`, value: { ...curve, pointsExt: points } }]);
49
+ const users = metadataObject(ext.perUserExt);
50
+ const updatedUsers = { ...users };
51
+ let changed = false;
52
+ for (const [userId, value] of Object.entries(users)) {
53
+ const user = metadataObject(value);
54
+ if (!Object.hasOwn(user, curveId))
55
+ continue;
56
+ const userCurve = metadataObject(user[String(curveId)]);
57
+ const userPoints = shift(userCurve.pointsExt);
58
+ if (direction === 1)
59
+ userPoints[index] = { selected: false };
60
+ updatedUsers[userId] = { ...user, [curveId]: { ...userCurve, pointsExt: userPoints } };
61
+ changed = true;
62
+ }
63
+ if (changed)
64
+ scene.patchSceneExt([{ op: "add", path: "/perUserExt", value: updatedUsers }]);
65
+ }
@@ -0,0 +1,47 @@
1
+ import { type JsonValue, type KakapoAPI, type SceneEdit, type SceneSaveResult } from "@womp/kakapo-sdk";
2
+ export type SceneEditResult = {
3
+ value: JsonValue;
4
+ } | {
5
+ empty: true;
6
+ };
7
+ export type SceneOperation = {
8
+ id: string;
9
+ targetKey: string;
10
+ expectedRevision: string;
11
+ resultRevision?: string;
12
+ revision: number;
13
+ status: "started" | "prepared" | "committed" | "rolled_back" | "unknown";
14
+ result?: SceneEditResult;
15
+ changed?: boolean;
16
+ error?: string;
17
+ save?: SceneSaveResult | {
18
+ status: "unknown" | "requested";
19
+ };
20
+ completedAt?: string;
21
+ };
22
+ export interface SceneOperationStore {
23
+ getSceneOperation(targetKey: string, id: string): Promise<SceneOperation | undefined>;
24
+ createSceneOperation(operation: SceneOperation): Promise<boolean>;
25
+ saveSceneOperation(operation: SceneOperation): Promise<SceneOperation>;
26
+ }
27
+ /** Resolve a journaled edit from a fresh renderer snapshot without executing its JavaScript. */
28
+ export declare function recoverSceneOperation(options: {
29
+ api: KakapoAPI;
30
+ store: SceneOperationStore;
31
+ targetKey: string;
32
+ id: string;
33
+ assertActive(): void | Promise<void>;
34
+ }): Promise<SceneOperation | undefined>;
35
+ /** The host owns connection/target validation and execution exclusivity. Never replays an existing edit. */
36
+ export declare function executeSceneOperation<T>(options: {
37
+ api: KakapoAPI;
38
+ store: SceneOperationStore;
39
+ operation: Pick<SceneOperation, "id" | "targetKey" | "expectedRevision">;
40
+ assertEditable(): void | Promise<void>;
41
+ edit(draft: SceneEdit): T | Promise<T>;
42
+ prepareCommit?(operation: SceneOperation): Promise<void>;
43
+ saveToRenderer?: boolean;
44
+ }): Promise<{
45
+ value: T;
46
+ operation: SceneOperation;
47
+ }>;
@@ -0,0 +1,126 @@
1
+ import { KakapoSceneCommitError } from "@womp/kakapo-sdk";
2
+ import { metadataObject } from "./scene-metadata.js";
3
+ function savedResult(value) {
4
+ if (value === undefined)
5
+ return { empty: true };
6
+ const active = new Set();
7
+ const validate = (item) => {
8
+ if (item === null || typeof item === "string" || typeof item === "boolean")
9
+ return;
10
+ if (typeof item === "number" && Number.isFinite(item))
11
+ return;
12
+ if (typeof item !== "object" || item === null ||
13
+ (!Array.isArray(item) && Object.getPrototypeOf(item) !== Object.prototype && Object.getPrototypeOf(item) !== null))
14
+ throw new Error("scene.edit must return JSON data or undefined");
15
+ if (active.has(item))
16
+ throw new Error("scene.edit cannot return cyclic data");
17
+ active.add(item);
18
+ for (const nested of Object.values(item))
19
+ validate(nested);
20
+ active.delete(item);
21
+ };
22
+ validate(value);
23
+ return { value: JSON.parse(JSON.stringify(value)) };
24
+ }
25
+ function resultValue(operation) {
26
+ if (!operation.result)
27
+ throw new Error("The saved scene operation result is missing");
28
+ return ("value" in operation.result ? structuredClone(operation.result.value) : undefined);
29
+ }
30
+ function committedIds(ext) {
31
+ const ids = metadataObject(ext.spark).committedSceneEdits;
32
+ return Array.isArray(ids) ? ids.filter((id) => typeof id === "string") : [];
33
+ }
34
+ function complete(operation, status) {
35
+ return { ...operation, status, completedAt: operation.completedAt ?? new Date().toISOString() };
36
+ }
37
+ /** Resolve a journaled edit from a fresh renderer snapshot without executing its JavaScript. */
38
+ export async function recoverSceneOperation(options) {
39
+ await options.assertActive();
40
+ const previous = await options.store.getSceneOperation(options.targetKey, options.id);
41
+ if (!previous || previous.status === "committed" || previous.status === "rolled_back")
42
+ return previous;
43
+ await options.api.refreshScene();
44
+ const ext = options.api.getSceneExt();
45
+ const revision = await options.api.getSceneRevision();
46
+ await options.assertActive();
47
+ const matches = previous.resultRevision !== undefined &&
48
+ previous.resultRevision === revision && committedIds(ext).includes(previous.id);
49
+ if ((previous.changed === false || matches) && previous.result) {
50
+ return options.store.saveSceneOperation(complete(previous, "committed"));
51
+ }
52
+ return previous;
53
+ }
54
+ /** The host owns connection/target validation and execution exclusivity. Never replays an existing edit. */
55
+ export async function executeSceneOperation(options) {
56
+ const { api, store, operation: identity } = options;
57
+ const savesScene = options.saveToRenderer === true;
58
+ await options.assertEditable();
59
+ const previous = await store.getSceneOperation(identity.targetKey, identity.id);
60
+ if (previous) {
61
+ if (previous.expectedRevision !== identity.expectedRevision)
62
+ throw new Error("Scene operation identity was reused with a different revision");
63
+ if ((previous.save !== undefined) !== savesScene)
64
+ throw new Error("Scene operation identity was reused with a different save policy");
65
+ if (previous.status === "committed")
66
+ return { value: resultValue(previous), operation: previous };
67
+ if (previous.status === "rolled_back")
68
+ throw new Error(previous.error ?? "Scene operation was rolled back");
69
+ const recovered = await recoverSceneOperation({
70
+ api, store, targetKey: identity.targetKey, id: identity.id, assertActive: options.assertEditable,
71
+ });
72
+ if (recovered?.status === "committed")
73
+ return { value: resultValue(recovered), operation: recovered };
74
+ throw new Error("Scene edit outcome is uncertain. Inspect the scene before making a new edit; this operation was not replayed.");
75
+ }
76
+ let operation = {
77
+ ...identity, revision: 0, status: "started",
78
+ ...(savesScene ? { save: { status: "unknown" } } : {}),
79
+ };
80
+ if (!await store.createSceneOperation(operation))
81
+ throw new Error("Scene operation is already in progress");
82
+ try {
83
+ const edit = async (draft) => {
84
+ await options.assertEditable();
85
+ if (await api.getSceneRevision() !== identity.expectedRevision)
86
+ throw new Error("Scene changed since inspection. Read the scene again before editing.");
87
+ const result = savedResult(await options.edit(draft));
88
+ await options.assertEditable();
89
+ const changed = await api.getSceneRevision() !== identity.expectedRevision;
90
+ if (changed) {
91
+ const spark = metadataObject(draft.getSceneExt().spark);
92
+ const ids = [...committedIds(api.getSceneExt()), identity.id].slice(-64);
93
+ draft.patchSceneExt([{ op: "add", path: "/spark", value: { ...spark, committedSceneEdits: ids } }]);
94
+ }
95
+ operation = await store.saveSceneOperation({
96
+ ...operation, status: "prepared", result, changed,
97
+ ...(changed ? { resultRevision: await api.getSceneRevision() } : {}),
98
+ ...(savesScene && !changed ? { save: { status: "not_needed" } } : {}),
99
+ });
100
+ await options.assertEditable();
101
+ if (changed)
102
+ await options.prepareCommit?.(operation);
103
+ await options.assertEditable();
104
+ };
105
+ if (options.saveToRenderer) {
106
+ const committed = await api.editSceneAndSave(edit);
107
+ operation = { ...operation, save: committed.save };
108
+ }
109
+ else {
110
+ await api.editScene(edit);
111
+ }
112
+ }
113
+ catch (error) {
114
+ const status = error instanceof KakapoSceneCommitError ? error.outcome
115
+ : "rolled_back";
116
+ await store.saveSceneOperation({
117
+ ...(status === "rolled_back" ? complete(operation, status) : { ...operation, status }),
118
+ error: error instanceof Error ? error.message : String(error),
119
+ ...(operation.save && status === "rolled_back" ? { save: { status: "not_needed" } } : {}),
120
+ });
121
+ throw error;
122
+ }
123
+ // Recovery requires both the operation marker and the exact prepared scene revision.
124
+ operation = await store.saveSceneOperation(complete(operation, "committed"));
125
+ return { value: resultValue(operation), operation };
126
+ }