@womp/spark-agent 2.0.0 → 2.1.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/README.md +5 -0
- package/dist/capabilities/health.d.ts +9 -0
- package/dist/capabilities/health.js +27 -0
- package/dist/capabilities.d.ts +3 -1
- package/dist/capabilities.js +1 -0
- package/dist/cli.js +1 -0
- package/dist/generated/health-declarations.d.ts +1 -0
- package/dist/generated/health-declarations.js +3 -0
- package/dist/geometry/backendRegistry.d.ts +37 -0
- package/dist/geometry/backendRegistry.js +61 -0
- package/dist/geometry/common.d.ts +26 -0
- package/dist/geometry/common.js +78 -0
- package/dist/geometry/compiler.d.ts +35 -0
- package/dist/geometry/compiler.js +115 -0
- package/dist/geometry/graph.d.ts +39 -0
- package/dist/geometry/graph.js +32 -0
- package/dist/geometry/index.d.ts +9 -0
- package/dist/geometry/index.js +12 -0
- package/dist/geometry/lift.d.ts +7 -0
- package/dist/geometry/lift.js +376 -0
- package/dist/geometry/lower.d.ts +9 -0
- package/dist/geometry/lower.js +363 -0
- package/dist/geometry/parameters.d.ts +23 -0
- package/dist/geometry/parameters.js +46 -0
- package/dist/geometry/schemas/backend-schema.json +3394 -0
- package/dist/geometry/schemas/flowir-dialect.json +976 -0
- package/dist/geometry/writeParamData.d.ts +18 -0
- package/dist/geometry/writeParamData.js +47 -0
- package/dist/geometry.d.ts +10 -0
- package/dist/geometry.js +19 -0
- package/dist/kakapo.d.ts +6 -1
- package/dist/kakapo.js +5 -0
- package/dist/openscad.d.ts +85 -0
- package/dist/openscad.js +223 -0
- package/dist/repair-state.d.ts +50 -0
- package/dist/repair-state.js +96 -0
- package/dist/scene-health.d.ts +49 -0
- package/dist/scene-health.js +176 -0
- package/dist/sdk-geometry-host.d.ts +12 -0
- package/dist/sdk-geometry-host.js +306 -0
- package/dist/sdk-openscad-host.d.ts +14 -0
- package/dist/sdk-openscad-host.js +296 -0
- package/dist/sdk-openscad-renderer.d.ts +11 -0
- package/dist/sdk-openscad-renderer.js +71 -0
- package/dist/sdk-scene-health-host.d.ts +4 -0
- package/dist/sdk-scene-health-host.js +13 -0
- package/dist/sdk-scene-host.d.ts +5 -2
- package/dist/sdk-scene-host.js +6 -5
- package/dist/server/sqlite-store.d.ts +2 -0
- package/dist/server/sqlite-store.js +55 -31
- package/dist/server/standalone.d.ts +9 -0
- package/dist/server/standalone.js +91 -15
- package/package.json +17 -3
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { getOpenScadGroundedPosition, MAX_PRINTABILITY_REPAIR_ATTEMPTS, requestStableOpenScadPrintability, toOpenScadCompileResponse, } from "./openscad.js";
|
|
3
|
+
import { waitForOpenScadRenderer } from "./sdk-openscad-renderer.js";
|
|
4
|
+
import { createGeometryRepairTracker, createRepairTracker, } from "./repair-state.js";
|
|
5
|
+
import { getSdkSceneAreaId, hasGeometryOverflow, readStableSdkSceneHealth, unverifiedSceneHealth, } from "./scene-health.js";
|
|
6
|
+
const compileMetadata = z.object({
|
|
7
|
+
error: z.string(),
|
|
8
|
+
params: z.array(z.object({ name: z.string() })),
|
|
9
|
+
});
|
|
10
|
+
function linkedObjectIds(api, scriptId) {
|
|
11
|
+
return api
|
|
12
|
+
.listNodes({ kind: "openScad" })
|
|
13
|
+
.filter((node) => node.kind === "openScad" && node.scriptId === scriptId)
|
|
14
|
+
.map((node) => node.id);
|
|
15
|
+
}
|
|
16
|
+
export function createSdkOpenScadHost(options) {
|
|
17
|
+
const editor = options.editor;
|
|
18
|
+
const geometryRepairs = createGeometryRepairTracker(options.repairs, "openscad.geometry");
|
|
19
|
+
const printabilityRepairs = createRepairTracker(options.repairs, "openscad.printability", MAX_PRINTABILITY_REPAIR_ATTEMPTS, (status) => status === "unavailable" ? undefined : status === "failed");
|
|
20
|
+
const pendingTargets = new Set();
|
|
21
|
+
const resolveTarget = async (api, objectId) => {
|
|
22
|
+
const revision = await api.getSceneRevision();
|
|
23
|
+
const node = objectId === 0 ? undefined : api.getNode(objectId);
|
|
24
|
+
if (objectId === 0 || node?.kind === "union" || node?.kind === "group") {
|
|
25
|
+
return {
|
|
26
|
+
target: {
|
|
27
|
+
kind: "container",
|
|
28
|
+
objectId,
|
|
29
|
+
parentId: node?.parentId ?? 0,
|
|
30
|
+
title: node?.name ?? "",
|
|
31
|
+
source: null,
|
|
32
|
+
params: {},
|
|
33
|
+
revision,
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
if (node?.kind !== "openScad")
|
|
38
|
+
throw new Error("The target must be an OpenSCAD part or an Area/Group.");
|
|
39
|
+
const script = api.getOpenScadScript(node.scriptId);
|
|
40
|
+
let rendererBounds;
|
|
41
|
+
try {
|
|
42
|
+
rendererBounds = await api.getNodeBoundingBox(objectId);
|
|
43
|
+
}
|
|
44
|
+
catch { }
|
|
45
|
+
return {
|
|
46
|
+
target: {
|
|
47
|
+
kind: "part",
|
|
48
|
+
objectId,
|
|
49
|
+
parentId: node.parentId ?? 0,
|
|
50
|
+
source: script.source,
|
|
51
|
+
title: script.name || node.name || "OpenSCAD part",
|
|
52
|
+
params: structuredClone(node.params ?? {}),
|
|
53
|
+
revision,
|
|
54
|
+
},
|
|
55
|
+
repairKey: `script:${node.scriptId}`,
|
|
56
|
+
rendererBounds,
|
|
57
|
+
};
|
|
58
|
+
};
|
|
59
|
+
const write = async (source, targetId, creating, invocation) => {
|
|
60
|
+
invocation.signal.throwIfAborted();
|
|
61
|
+
const resolved = await editor.read(invocation, (api) => resolveTarget(api, targetId));
|
|
62
|
+
const { target } = resolved;
|
|
63
|
+
const pendingKey = resolved.repairKey ?? `container:${targetId}`;
|
|
64
|
+
if (pendingTargets.has(pendingKey))
|
|
65
|
+
throw new Error("This part is still being compiled or checked. Await its current update first.");
|
|
66
|
+
pendingTargets.add(pendingKey);
|
|
67
|
+
let objectId = creating ? undefined : targetId;
|
|
68
|
+
let operationId = "";
|
|
69
|
+
let operationRepairKey = resolved.repairKey;
|
|
70
|
+
try {
|
|
71
|
+
if (target.revision !== source.expectedRevision)
|
|
72
|
+
throw new Error("The scene changed. Read it again before editing.");
|
|
73
|
+
if (target.kind !== (creating ? "container" : "part"))
|
|
74
|
+
throw new Error(creating
|
|
75
|
+
? "Creation requires a parent container ID."
|
|
76
|
+
: "Update requires an existing OpenSCAD object ID.");
|
|
77
|
+
let repairingGeometry = false;
|
|
78
|
+
if (creating === false) {
|
|
79
|
+
if (resolved.repairKey === undefined)
|
|
80
|
+
throw new Error("The OpenSCAD repair target is unavailable.");
|
|
81
|
+
repairingGeometry = await geometryRepairs.isPending(resolved.repairKey);
|
|
82
|
+
await geometryRepairs.assertCanWrite(resolved.repairKey);
|
|
83
|
+
if (repairingGeometry === false)
|
|
84
|
+
await printabilityRepairs.assertCanWrite(resolved.repairKey);
|
|
85
|
+
}
|
|
86
|
+
if (creating && options.canGrow?.() === false)
|
|
87
|
+
throw new Error("OpenSCAD creation is disabled because scene memory is low.");
|
|
88
|
+
const params = z
|
|
89
|
+
.record(z.string(), z.json())
|
|
90
|
+
.parse({ ...target.params, ...source.params });
|
|
91
|
+
invocation.reportStatus("running", "Compiling the parametric part...");
|
|
92
|
+
let rawValidation;
|
|
93
|
+
try {
|
|
94
|
+
rawValidation = await editor.read(invocation, (api) => api.validateOpenScad(source.source, params));
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
invocation.signal.throwIfAborted();
|
|
98
|
+
}
|
|
99
|
+
const response = toOpenScadCompileResponse(rawValidation);
|
|
100
|
+
const metadataAvailable = compileMetadata.safeParse(rawValidation).success;
|
|
101
|
+
const validation = response && (response.error || metadataAvailable)
|
|
102
|
+
? {
|
|
103
|
+
status: response.error ? "invalid" : "valid",
|
|
104
|
+
error: response.error || undefined,
|
|
105
|
+
warnings: response.warnings,
|
|
106
|
+
}
|
|
107
|
+
: {
|
|
108
|
+
status: "unavailable",
|
|
109
|
+
warnings: [
|
|
110
|
+
"OpenSCAD validation is unavailable; compilation and parameter validity could not be confirmed.",
|
|
111
|
+
],
|
|
112
|
+
};
|
|
113
|
+
if (validation.status === "invalid" ||
|
|
114
|
+
(creating &&
|
|
115
|
+
(validation.status !== "valid" ||
|
|
116
|
+
response?.boundingBox === undefined))) {
|
|
117
|
+
if (creating && response?.boundingBox === undefined)
|
|
118
|
+
validation.warnings.push("The part was not added because validated placement bounds are unavailable.");
|
|
119
|
+
return {
|
|
120
|
+
status: "rejected",
|
|
121
|
+
objectId,
|
|
122
|
+
revision: target.revision,
|
|
123
|
+
validation,
|
|
124
|
+
repairAttempts: 0,
|
|
125
|
+
repairLimit: MAX_PRINTABILITY_REPAIR_ATTEMPTS,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
const validNames = new Set(response && metadataAvailable
|
|
129
|
+
? response.params.map((param) => param.name)
|
|
130
|
+
: Object.keys(params));
|
|
131
|
+
const nextParams = Object.fromEntries(Object.entries(params).filter(([name]) => validNames.has(name)));
|
|
132
|
+
const receiptTarget = {
|
|
133
|
+
parentId: target.parentId,
|
|
134
|
+
};
|
|
135
|
+
if (objectId !== undefined)
|
|
136
|
+
receiptTarget.objectId = objectId;
|
|
137
|
+
let affectedObjectIds = [];
|
|
138
|
+
let sceneHealth;
|
|
139
|
+
const applied = await editor.edit({
|
|
140
|
+
capability: "openscad",
|
|
141
|
+
operation: creating ? "create" : "update",
|
|
142
|
+
target: () => receiptTarget,
|
|
143
|
+
}, async (_api, draft, id) => {
|
|
144
|
+
operationId = id;
|
|
145
|
+
if (creating === false) {
|
|
146
|
+
if (resolved.repairKey === undefined)
|
|
147
|
+
throw new Error("The OpenSCAD repair target is unavailable.");
|
|
148
|
+
await geometryRepairs.reserve(resolved.repairKey, id);
|
|
149
|
+
if (repairingGeometry === false)
|
|
150
|
+
await printabilityRepairs.reserve(resolved.repairKey, id);
|
|
151
|
+
const node = draft.getNode(targetId);
|
|
152
|
+
if (node.kind !== "openScad")
|
|
153
|
+
throw new Error("The OpenSCAD target no longer exists.");
|
|
154
|
+
affectedObjectIds = linkedObjectIds(draft, node.scriptId);
|
|
155
|
+
draft.updateOpenScadScript(node.scriptId, {
|
|
156
|
+
name: source.title,
|
|
157
|
+
source: source.source,
|
|
158
|
+
});
|
|
159
|
+
draft.setNodeName(targetId, source.title);
|
|
160
|
+
draft.setOpenScadScript(targetId, node.scriptId, nextParams);
|
|
161
|
+
return { objectId: targetId, repairKey: resolved.repairKey };
|
|
162
|
+
}
|
|
163
|
+
if (options.canGrow?.() === false)
|
|
164
|
+
throw new Error("OpenSCAD creation is disabled because scene memory is low.");
|
|
165
|
+
let parentId = targetId;
|
|
166
|
+
if (targetId === 0 || draft.getNode(targetId).kind === "group")
|
|
167
|
+
parentId = draft.createNode({
|
|
168
|
+
kind: "union",
|
|
169
|
+
parentId: targetId,
|
|
170
|
+
name: "Area",
|
|
171
|
+
}).id;
|
|
172
|
+
const script = draft.createOpenScadScript(source.title, source.source);
|
|
173
|
+
operationRepairKey = `script:${script.id}`;
|
|
174
|
+
const node = draft.createNode({
|
|
175
|
+
kind: "openScad",
|
|
176
|
+
parentId,
|
|
177
|
+
name: source.title,
|
|
178
|
+
properties: {
|
|
179
|
+
scriptId: script.id,
|
|
180
|
+
params: nextParams,
|
|
181
|
+
transform: {
|
|
182
|
+
position: getOpenScadGroundedPosition(response?.boundingBox),
|
|
183
|
+
},
|
|
184
|
+
},
|
|
185
|
+
});
|
|
186
|
+
objectId = node.id;
|
|
187
|
+
affectedObjectIds = [node.id];
|
|
188
|
+
Object.assign(receiptTarget, { objectId: node.id, parentId });
|
|
189
|
+
return { objectId: node.id, repairKey: operationRepairKey };
|
|
190
|
+
}, source.expectedRevision, invocation, async (operation, api) => {
|
|
191
|
+
if (objectId === undefined)
|
|
192
|
+
return;
|
|
193
|
+
const areaIds = [
|
|
194
|
+
...new Set(affectedObjectIds.map((id) => getSdkSceneAreaId(api, id))),
|
|
195
|
+
];
|
|
196
|
+
try {
|
|
197
|
+
const rendererReady = response?.boundingBox === undefined ||
|
|
198
|
+
(creating === false && resolved.rendererBounds === undefined)
|
|
199
|
+
? false
|
|
200
|
+
: await waitForOpenScadRenderer({
|
|
201
|
+
api,
|
|
202
|
+
objectId,
|
|
203
|
+
expectedBounds: response.boundingBox,
|
|
204
|
+
baselineBounds: resolved.rendererBounds,
|
|
205
|
+
signal: invocation.signal,
|
|
206
|
+
});
|
|
207
|
+
sceneHealth = rendererReady
|
|
208
|
+
? await readStableSdkSceneHealth(api, areaIds, invocation.signal)
|
|
209
|
+
: unverifiedSceneHealth(areaIds, "The renderer did not confirm the committed OpenSCAD geometry before health checks.");
|
|
210
|
+
}
|
|
211
|
+
catch (error) {
|
|
212
|
+
sceneHealth = unverifiedSceneHealth(areaIds, `OpenSCAD renderer checks stopped after the edit committed: ${String(error)}`);
|
|
213
|
+
}
|
|
214
|
+
options.onHealth?.(sceneHealth);
|
|
215
|
+
if (operationRepairKey === undefined)
|
|
216
|
+
return;
|
|
217
|
+
const recorded = await geometryRepairs.record(operationRepairKey, operation.id, sceneHealth);
|
|
218
|
+
return {
|
|
219
|
+
sceneHealth,
|
|
220
|
+
affectedObjectIds,
|
|
221
|
+
geometryRepairAttempts: recorded.repairAttempts,
|
|
222
|
+
geometryRepairLimit: recorded.repairLimit,
|
|
223
|
+
};
|
|
224
|
+
});
|
|
225
|
+
objectId = applied.value.objectId;
|
|
226
|
+
try {
|
|
227
|
+
await options.onSelect?.(objectId);
|
|
228
|
+
}
|
|
229
|
+
catch { }
|
|
230
|
+
const revision = applied.operation.resultRevision ?? source.expectedRevision;
|
|
231
|
+
if (sceneHealth?.status === "unverified" ||
|
|
232
|
+
(sceneHealth !== undefined && hasGeometryOverflow(sceneHealth))) {
|
|
233
|
+
await printabilityRepairs.refund(applied.value.repairKey, operationId);
|
|
234
|
+
return {
|
|
235
|
+
status: "applied",
|
|
236
|
+
objectId,
|
|
237
|
+
revision,
|
|
238
|
+
validation,
|
|
239
|
+
repairAttempts: 0,
|
|
240
|
+
repairLimit: MAX_PRINTABILITY_REPAIR_ATTEMPTS,
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
invocation.reportStatus("running", "Checking wall thickness...");
|
|
244
|
+
const printability = await editor.read(invocation, (api, beginSettlement) => (options.requestPrintability ?? requestStableOpenScadPrintability)({
|
|
245
|
+
api,
|
|
246
|
+
expectedRevision: revision,
|
|
247
|
+
signal: invocation.signal,
|
|
248
|
+
onSubmissionStarted: beginSettlement,
|
|
249
|
+
objectIds: [
|
|
250
|
+
...new Set(affectedObjectIds.map((id) => Number(getSdkSceneAreaId(api, id)))),
|
|
251
|
+
],
|
|
252
|
+
}));
|
|
253
|
+
invocation.signal.throwIfAborted();
|
|
254
|
+
if (printability.reason === "context_busy") {
|
|
255
|
+
const refunded = await printabilityRepairs.refund(applied.value.repairKey, operationId);
|
|
256
|
+
return {
|
|
257
|
+
status: "applied",
|
|
258
|
+
objectId,
|
|
259
|
+
revision,
|
|
260
|
+
validation,
|
|
261
|
+
printability,
|
|
262
|
+
repairAttempts: refunded.repairAttempts,
|
|
263
|
+
repairLimit: refunded.repairLimit,
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
const recorded = await printabilityRepairs.record(applied.value.repairKey, operationId, printability.status);
|
|
267
|
+
return {
|
|
268
|
+
status: "applied",
|
|
269
|
+
objectId,
|
|
270
|
+
revision,
|
|
271
|
+
validation,
|
|
272
|
+
printability,
|
|
273
|
+
repairAttempts: recorded.repairAttempts,
|
|
274
|
+
repairLimit: recorded.repairLimit,
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
catch (error) {
|
|
278
|
+
if (creating === false && operationId !== "") {
|
|
279
|
+
const operation = await editor.getOperation(operationId);
|
|
280
|
+
if (operation?.status === "rolled_back") {
|
|
281
|
+
await geometryRepairs.refund(resolved.repairKey, operationId);
|
|
282
|
+
await printabilityRepairs.refund(resolved.repairKey, operationId);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
throw error;
|
|
286
|
+
}
|
|
287
|
+
finally {
|
|
288
|
+
pendingTargets.delete(pendingKey);
|
|
289
|
+
}
|
|
290
|
+
};
|
|
291
|
+
return {
|
|
292
|
+
read: (objectId, invocation) => editor.read(invocation, async (api) => (await resolveTarget(api, objectId)).target),
|
|
293
|
+
create: (source, invocation) => write(source, source.parentId, true, invocation),
|
|
294
|
+
update: (source, invocation) => write(source, source.objectId, false, invocation),
|
|
295
|
+
};
|
|
296
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { KakapoAPI } from "@womp/kakapo-sdk";
|
|
2
|
+
import type { OpenScadBoundingBox } from "./openscad.js";
|
|
3
|
+
export declare function waitForOpenScadRenderer(options: {
|
|
4
|
+
api: KakapoAPI;
|
|
5
|
+
objectId: number;
|
|
6
|
+
expectedBounds: OpenScadBoundingBox;
|
|
7
|
+
baselineBounds?: OpenScadBoundingBox;
|
|
8
|
+
signal: AbortSignal;
|
|
9
|
+
timeoutMs?: number;
|
|
10
|
+
pollIntervalMs?: number;
|
|
11
|
+
}): Promise<boolean>;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
const OPENSCAD_RENDERER_WAIT_MS = 15_000;
|
|
2
|
+
const OPENSCAD_RENDERER_POLL_MS = 250;
|
|
3
|
+
function boundsMatch(actual, expected) {
|
|
4
|
+
const size = Math.max(expected.max.x - expected.min.x, expected.max.y - expected.min.y, expected.max.z - expected.min.z);
|
|
5
|
+
const tolerance = Math.max(size * 0.0001, 0.001);
|
|
6
|
+
return ["min", "max"].every((edge) => ["x", "y", "z"].every((axis) => Math.abs(actual[edge][axis] - expected[edge][axis]) <= tolerance));
|
|
7
|
+
}
|
|
8
|
+
function getBoundsBeforeDeadline(options) {
|
|
9
|
+
const remaining = options.deadline - Date.now();
|
|
10
|
+
if (remaining <= 0)
|
|
11
|
+
return Promise.resolve(undefined);
|
|
12
|
+
options.signal.throwIfAborted();
|
|
13
|
+
return new Promise((resolve, reject) => {
|
|
14
|
+
let settled = false;
|
|
15
|
+
const finish = (action) => {
|
|
16
|
+
if (settled)
|
|
17
|
+
return;
|
|
18
|
+
settled = true;
|
|
19
|
+
clearTimeout(timeout);
|
|
20
|
+
options.signal.removeEventListener("abort", onAbort);
|
|
21
|
+
action();
|
|
22
|
+
};
|
|
23
|
+
const onAbort = () => finish(() => reject(options.signal.reason ?? new Error("The operation was aborted.")));
|
|
24
|
+
const timeout = setTimeout(() => finish(() => resolve(undefined)), remaining);
|
|
25
|
+
options.signal.addEventListener("abort", onAbort, { once: true });
|
|
26
|
+
if (options.signal.aborted) {
|
|
27
|
+
onAbort();
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
void options.api.getNodeBoundingBox(options.objectId).then((bounds) => finish(() => resolve(bounds)), () => finish(() => resolve(undefined)));
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
function waitForPoll(signal, milliseconds) {
|
|
34
|
+
signal.throwIfAborted();
|
|
35
|
+
return new Promise((resolve, reject) => {
|
|
36
|
+
const onAbort = () => {
|
|
37
|
+
clearTimeout(timeout);
|
|
38
|
+
reject(signal.reason ?? new Error("The operation was aborted."));
|
|
39
|
+
};
|
|
40
|
+
const timeout = setTimeout(() => {
|
|
41
|
+
signal.removeEventListener("abort", onAbort);
|
|
42
|
+
resolve();
|
|
43
|
+
}, milliseconds);
|
|
44
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
45
|
+
if (signal.aborted)
|
|
46
|
+
onAbort();
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
export async function waitForOpenScadRenderer(options) {
|
|
50
|
+
const deadline = Date.now() + (options.timeoutMs ?? OPENSCAD_RENDERER_WAIT_MS);
|
|
51
|
+
if (options.baselineBounds !== undefined &&
|
|
52
|
+
boundsMatch(options.baselineBounds, options.expectedBounds))
|
|
53
|
+
return false;
|
|
54
|
+
do {
|
|
55
|
+
const actual = await getBoundsBeforeDeadline({
|
|
56
|
+
api: options.api,
|
|
57
|
+
objectId: options.objectId,
|
|
58
|
+
signal: options.signal,
|
|
59
|
+
deadline,
|
|
60
|
+
});
|
|
61
|
+
options.signal.throwIfAborted();
|
|
62
|
+
if (Date.now() >= deadline)
|
|
63
|
+
return false;
|
|
64
|
+
if (actual !== undefined && boundsMatch(actual, options.expectedBounds))
|
|
65
|
+
return true;
|
|
66
|
+
const remaining = deadline - Date.now();
|
|
67
|
+
if (remaining <= 0)
|
|
68
|
+
return false;
|
|
69
|
+
await waitForPoll(options.signal, Math.min(options.pollIntervalMs ?? OPENSCAD_RENDERER_POLL_MS, remaining));
|
|
70
|
+
} while (true);
|
|
71
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { SceneHealthHost } from "./capabilities.js";
|
|
2
|
+
import { type SdkSceneEditor } from "./sdk-scene-host.js";
|
|
3
|
+
import type { SceneHealth } from "./scene-health.js";
|
|
4
|
+
export declare function createSdkSceneHealthHost(editor: SdkSceneEditor, onHealth?: (health: SceneHealth) => void): SceneHealthHost;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { getSdkSceneAreaId, getSdkSceneAreaIds, readStableSdkSceneHealth, } from "./scene-health.js";
|
|
2
|
+
export function createSdkSceneHealthHost(editor, onHealth) {
|
|
3
|
+
return {
|
|
4
|
+
read: (objectIds, context) => editor.read(context, async (api) => {
|
|
5
|
+
const areaIds = objectIds.length > 0
|
|
6
|
+
? objectIds.map((id) => getSdkSceneAreaId(api, id))
|
|
7
|
+
: getSdkSceneAreaIds(api);
|
|
8
|
+
const health = await readStableSdkSceneHealth(api, [...new Set(areaIds)], context.signal);
|
|
9
|
+
onHealth?.(health);
|
|
10
|
+
return health;
|
|
11
|
+
}),
|
|
12
|
+
};
|
|
13
|
+
}
|
package/dist/sdk-scene-host.d.ts
CHANGED
|
@@ -35,8 +35,9 @@ export type SdkSceneEditIdentity = {
|
|
|
35
35
|
target?: Record<string, unknown> | (() => Record<string, unknown>);
|
|
36
36
|
};
|
|
37
37
|
export type SdkSceneEditor = {
|
|
38
|
-
|
|
39
|
-
|
|
38
|
+
getOperation(operationId: string): Promise<SceneOperation | undefined>;
|
|
39
|
+
read<T>(context: SparkInvocationContext, action: (api: KakapoAPI, beginSettlement: () => void) => T | Promise<T>): Promise<T>;
|
|
40
|
+
edit<T>(identity: SdkSceneEditIdentity, callback: (api: KakapoAPI, draft: SceneEdit, operationId: string) => T | Promise<T>, expectedRevision: string, context: SparkInvocationContext, afterCommitted?: (operation: SceneOperation, api: KakapoAPI) => Promise<Record<string, unknown> | void>): Promise<{
|
|
40
41
|
value: T;
|
|
41
42
|
operation: SceneOperation;
|
|
42
43
|
}>;
|
|
@@ -304,6 +305,8 @@ export declare function createSdkSceneDraft(api: KakapoAPI, scene: SceneEdit, se
|
|
|
304
305
|
};
|
|
305
306
|
export declare function createSdkSceneEditor(options: SdkSceneEditorOptions): SdkSceneEditor;
|
|
306
307
|
export declare function createSdkSceneHost(options: SdkSceneEditorOptions & {
|
|
308
|
+
editor?: SdkSceneEditor;
|
|
307
309
|
services(api: KakapoAPI, context: SparkInvocationContext): Promise<SdkSceneServices>;
|
|
308
310
|
screenshot(options: SceneScreenshotOptions, context: SparkInvocationContext): Promise<ArtifactRef>;
|
|
311
|
+
onSceneCommitted?(operation: SceneOperation, api: KakapoAPI): Promise<Record<string, unknown> | void>;
|
|
309
312
|
}): SceneHost;
|
package/dist/sdk-scene-host.js
CHANGED
|
@@ -59,11 +59,12 @@ export function createSdkSceneDraft(api, scene, services) {
|
|
|
59
59
|
export function createSdkSceneEditor(options) {
|
|
60
60
|
const ordinals = new WeakMap();
|
|
61
61
|
return {
|
|
62
|
-
|
|
62
|
+
getOperation: (operationId) => options.operations.getSceneOperation(options.targetKey, operationId),
|
|
63
|
+
read: (context, action) => options.withConnection(context, async (api, beginSettlement, activeContext = context) => {
|
|
63
64
|
activeContext.signal.throwIfAborted();
|
|
64
65
|
await api.refreshScene();
|
|
65
66
|
activeContext.signal.throwIfAborted();
|
|
66
|
-
return action(api);
|
|
67
|
+
return action(api, beginSettlement);
|
|
67
68
|
}),
|
|
68
69
|
edit: (identity, callback, expectedRevision, context, afterCommitted) => {
|
|
69
70
|
const operationKey = `${identity.capability}.${identity.operation}`;
|
|
@@ -104,7 +105,7 @@ export function createSdkSceneEditor(options) {
|
|
|
104
105
|
activeContext.signal.throwIfAborted();
|
|
105
106
|
await options.assertEditable(activeContext);
|
|
106
107
|
},
|
|
107
|
-
edit: (draft) => callback(api, draft),
|
|
108
|
+
edit: (draft) => callback(api, draft, id),
|
|
108
109
|
prepareCommit: async (operation) => {
|
|
109
110
|
await activeContext.recordReceipt({
|
|
110
111
|
...receipt(),
|
|
@@ -155,7 +156,7 @@ export function createSdkSceneEditor(options) {
|
|
|
155
156
|
};
|
|
156
157
|
}
|
|
157
158
|
export function createSdkSceneHost(options) {
|
|
158
|
-
const editor = createSdkSceneEditor(options);
|
|
159
|
+
const editor = options.editor ?? createSdkSceneEditor(options);
|
|
159
160
|
return {
|
|
160
161
|
read: (context) => editor.read(context, async (api) => {
|
|
161
162
|
const scene = api.getScene();
|
|
@@ -194,7 +195,7 @@ export function createSdkSceneHost(options) {
|
|
|
194
195
|
finally {
|
|
195
196
|
active = false;
|
|
196
197
|
}
|
|
197
|
-
}, expectedRevision, context)
|
|
198
|
+
}, expectedRevision, context, options.onSceneCommitted)
|
|
198
199
|
.then(({ value }) => value),
|
|
199
200
|
screenshot: options.screenshot,
|
|
200
201
|
};
|
|
@@ -2,6 +2,7 @@ import type { ExecutionScreenshot } from "../types.js";
|
|
|
2
2
|
import type { SparkArtifact, StoredSparkChunk } from "../ui.js";
|
|
3
3
|
import type { SparkArtifactStore, StoredSparkArtifact } from "./artifacts.js";
|
|
4
4
|
import type { SceneOperation, SceneOperationStore } from "../scene-operations.js";
|
|
5
|
+
import { type RepairStateStore } from "../repair-state.js";
|
|
5
6
|
import type { SparkAgentStore, SparkConversation, SparkConversationSummary, SparkRun } from "./types.js";
|
|
6
7
|
/** Local development storage. Execution ownership belongs to the host service. */
|
|
7
8
|
export declare class SqliteSparkStore implements SparkAgentStore, SparkArtifactStore, SceneOperationStore {
|
|
@@ -9,6 +10,7 @@ export declare class SqliteSparkStore implements SparkAgentStore, SparkArtifactS
|
|
|
9
10
|
private readonly database;
|
|
10
11
|
private ownershipToken;
|
|
11
12
|
constructor(path: string, artifactBaseUrl?: string);
|
|
13
|
+
repairStateStore(targetKey: string): RepairStateStore;
|
|
12
14
|
close(): void;
|
|
13
15
|
claimExecutionOwnership(): void;
|
|
14
16
|
listInterruptedRuns(): Promise<SparkRun[]>;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { mkdirSync } from "node:fs";
|
|
2
2
|
import { dirname } from "node:path";
|
|
3
3
|
import { DatabaseSync } from "node:sqlite";
|
|
4
|
+
import { emptyRepairState, } from "../repair-state.js";
|
|
4
5
|
const completedSceneOperationLimit = 128;
|
|
5
6
|
/** Local development storage. Execution ownership belongs to the host service. */
|
|
6
7
|
export class SqliteSparkStore {
|
|
@@ -12,39 +13,62 @@ export class SqliteSparkStore {
|
|
|
12
13
|
mkdirSync(dirname(path), { recursive: true });
|
|
13
14
|
this.database = new DatabaseSync(path);
|
|
14
15
|
const version = this.database.prepare("PRAGMA user_version").get()?.user_version;
|
|
15
|
-
if (version !== 0 && version !== 1 && version !== 2 && version !== 3) {
|
|
16
|
+
if (version !== 0 && version !== 1 && version !== 2 && version !== 3 && version !== 4) {
|
|
16
17
|
this.database.close();
|
|
17
18
|
throw new Error(`Unsupported Spark database version: ${version}`);
|
|
18
19
|
}
|
|
19
|
-
this.database.exec(`
|
|
20
|
-
PRAGMA busy_timeout = 5000;
|
|
21
|
-
PRAGMA journal_mode = WAL;
|
|
22
|
-
PRAGMA synchronous = FULL;
|
|
23
|
-
PRAGMA foreign_keys = ON;
|
|
24
|
-
CREATE TABLE IF NOT EXISTS conversations (
|
|
25
|
-
id TEXT PRIMARY KEY, owner_id TEXT NOT NULL, updated_at TEXT NOT NULL, data TEXT NOT NULL
|
|
26
|
-
);
|
|
27
|
-
CREATE INDEX IF NOT EXISTS conversation_owner ON conversations(owner_id, updated_at);
|
|
28
|
-
CREATE TABLE IF NOT EXISTS runs (
|
|
29
|
-
id TEXT PRIMARY KEY, conversation_id TEXT NOT NULL, data TEXT NOT NULL
|
|
30
|
-
);
|
|
31
|
-
CREATE TABLE IF NOT EXISTS chunks (
|
|
32
|
-
run_id TEXT NOT NULL REFERENCES runs(id), sequence INTEGER NOT NULL, data TEXT NOT NULL,
|
|
33
|
-
PRIMARY KEY (run_id, sequence)
|
|
34
|
-
);
|
|
35
|
-
CREATE TABLE IF NOT EXISTS artifacts (
|
|
36
|
-
id TEXT PRIMARY KEY, owner_id TEXT NOT NULL, metadata TEXT NOT NULL, bytes BLOB NOT NULL
|
|
37
|
-
);
|
|
38
|
-
CREATE TABLE IF NOT EXISTS execution_owner (
|
|
39
|
-
singleton INTEGER PRIMARY KEY CHECK (singleton = 1), pid INTEGER NOT NULL, token TEXT NOT NULL
|
|
40
|
-
);
|
|
20
|
+
this.database.exec(`
|
|
21
|
+
PRAGMA busy_timeout = 5000;
|
|
22
|
+
PRAGMA journal_mode = WAL;
|
|
23
|
+
PRAGMA synchronous = FULL;
|
|
24
|
+
PRAGMA foreign_keys = ON;
|
|
25
|
+
CREATE TABLE IF NOT EXISTS conversations (
|
|
26
|
+
id TEXT PRIMARY KEY, owner_id TEXT NOT NULL, updated_at TEXT NOT NULL, data TEXT NOT NULL
|
|
27
|
+
);
|
|
28
|
+
CREATE INDEX IF NOT EXISTS conversation_owner ON conversations(owner_id, updated_at);
|
|
29
|
+
CREATE TABLE IF NOT EXISTS runs (
|
|
30
|
+
id TEXT PRIMARY KEY, conversation_id TEXT NOT NULL, data TEXT NOT NULL
|
|
31
|
+
);
|
|
32
|
+
CREATE TABLE IF NOT EXISTS chunks (
|
|
33
|
+
run_id TEXT NOT NULL REFERENCES runs(id), sequence INTEGER NOT NULL, data TEXT NOT NULL,
|
|
34
|
+
PRIMARY KEY (run_id, sequence)
|
|
35
|
+
);
|
|
36
|
+
CREATE TABLE IF NOT EXISTS artifacts (
|
|
37
|
+
id TEXT PRIMARY KEY, owner_id TEXT NOT NULL, metadata TEXT NOT NULL, bytes BLOB NOT NULL
|
|
38
|
+
);
|
|
39
|
+
CREATE TABLE IF NOT EXISTS execution_owner (
|
|
40
|
+
singleton INTEGER PRIMARY KEY CHECK (singleton = 1), pid INTEGER NOT NULL, token TEXT NOT NULL
|
|
41
|
+
);
|
|
41
42
|
CREATE TABLE IF NOT EXISTS scene_operations (
|
|
42
43
|
target_key TEXT NOT NULL, id TEXT NOT NULL, revision INTEGER NOT NULL, data TEXT NOT NULL,
|
|
43
44
|
PRIMARY KEY (target_key, id)
|
|
44
45
|
);
|
|
45
|
-
|
|
46
|
+
CREATE TABLE IF NOT EXISTS repair_states (
|
|
47
|
+
target_key TEXT PRIMARY KEY, revision INTEGER NOT NULL, data TEXT NOT NULL
|
|
48
|
+
);
|
|
49
|
+
PRAGMA user_version = 4;
|
|
46
50
|
`);
|
|
47
51
|
}
|
|
52
|
+
repairStateStore(targetKey) {
|
|
53
|
+
return {
|
|
54
|
+
read: async () => {
|
|
55
|
+
const row = this.database.prepare("SELECT data FROM repair_states WHERE target_key = ?").get(targetKey);
|
|
56
|
+
return row
|
|
57
|
+
? JSON.parse(String(row.data))
|
|
58
|
+
: emptyRepairState();
|
|
59
|
+
},
|
|
60
|
+
compareAndSwap: async (expectedRevision, next) => {
|
|
61
|
+
const stored = { ...next, revision: expectedRevision + 1 };
|
|
62
|
+
if (expectedRevision === 0) {
|
|
63
|
+
const inserted = this.database.prepare("INSERT OR IGNORE INTO repair_states VALUES (?, ?, ?)").run(targetKey, stored.revision, JSON.stringify(stored));
|
|
64
|
+
if (inserted.changes === 1)
|
|
65
|
+
return true;
|
|
66
|
+
}
|
|
67
|
+
const updated = this.database.prepare("UPDATE repair_states SET revision = ?, data = ? WHERE target_key = ? AND revision = ?").run(stored.revision, JSON.stringify(stored), targetKey, expectedRevision);
|
|
68
|
+
return updated.changes === 1;
|
|
69
|
+
},
|
|
70
|
+
};
|
|
71
|
+
}
|
|
48
72
|
close() {
|
|
49
73
|
if (this.ownershipToken) {
|
|
50
74
|
this.database.prepare("DELETE FROM execution_owner WHERE token = ?").run(this.ownershipToken);
|
|
@@ -103,13 +127,13 @@ export class SqliteSparkStore {
|
|
|
103
127
|
if (result.changes !== 1)
|
|
104
128
|
throw new Error("Scene operation changed concurrently or is missing");
|
|
105
129
|
if (next.status === "committed" || next.status === "rolled_back") {
|
|
106
|
-
this.database.prepare(`
|
|
107
|
-
DELETE FROM scene_operations WHERE rowid IN (
|
|
108
|
-
SELECT rowid FROM scene_operations
|
|
109
|
-
WHERE target_key = ? AND json_extract(data, '$.status') IN ('committed', 'rolled_back')
|
|
110
|
-
ORDER BY COALESCE(json_extract(data, '$.completedAt'), '') DESC
|
|
111
|
-
LIMIT -1 OFFSET ?
|
|
112
|
-
)
|
|
130
|
+
this.database.prepare(`
|
|
131
|
+
DELETE FROM scene_operations WHERE rowid IN (
|
|
132
|
+
SELECT rowid FROM scene_operations
|
|
133
|
+
WHERE target_key = ? AND json_extract(data, '$.status') IN ('committed', 'rolled_back')
|
|
134
|
+
ORDER BY COALESCE(json_extract(data, '$.completedAt'), '') DESC
|
|
135
|
+
LIMIT -1 OFFSET ?
|
|
136
|
+
)
|
|
113
137
|
`).run(next.targetKey, completedSceneOperationLimit);
|
|
114
138
|
}
|
|
115
139
|
this.database.exec("COMMIT");
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type Express } from "express";
|
|
2
|
+
import { KakapoAPI } from "@womp/kakapo-sdk";
|
|
2
3
|
export type StandaloneSparkAgentOptions = {
|
|
3
4
|
openAiApiKey?: string;
|
|
4
5
|
anthropicApiKey?: string;
|
|
@@ -6,8 +7,16 @@ export type StandaloneSparkAgentOptions = {
|
|
|
6
7
|
apiBasePath?: string;
|
|
7
8
|
developmentProfile?: "demo-account";
|
|
8
9
|
storagePath?: string;
|
|
10
|
+
/** Stable host-verified identity for the scene behind kakapoUrl. */
|
|
11
|
+
sceneIdentity?: string;
|
|
12
|
+
logger?: Pick<Console, "info" | "warn">;
|
|
9
13
|
};
|
|
10
14
|
export type StandaloneSparkAgentApp = Express & {
|
|
11
15
|
dispose(): Promise<void>;
|
|
12
16
|
};
|
|
17
|
+
export declare function checkStandaloneServices(api: Pick<KakapoAPI, "listFonts" | "validateOpenScad">): Promise<{
|
|
18
|
+
fonts: import("@womp/kakapo-sdk").FontFamily[];
|
|
19
|
+
fontsAvailable: boolean;
|
|
20
|
+
openScadStatus: string;
|
|
21
|
+
}>;
|
|
13
22
|
export declare function createStandaloneSparkAgentApp(options: StandaloneSparkAgentOptions): Promise<StandaloneSparkAgentApp>;
|