@womp/spark-agent 1.0.1 → 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.
Files changed (89) hide show
  1. package/README.md +42 -19
  2. package/dist/capabilities/health.d.ts +9 -0
  3. package/dist/capabilities/health.js +27 -0
  4. package/dist/capabilities/scene-draft.d.ts +2 -404
  5. package/dist/capabilities/scene.d.ts +1 -1
  6. package/dist/capabilities/scene.js +13 -4
  7. package/dist/capabilities.d.ts +3 -1
  8. package/dist/capabilities.js +1 -0
  9. package/dist/cli.js +20 -2
  10. package/dist/client.js +15 -15
  11. package/dist/coordinates.d.ts +23 -0
  12. package/dist/coordinates.js +132 -0
  13. package/dist/generated/health-declarations.d.ts +1 -0
  14. package/dist/generated/health-declarations.js +3 -0
  15. package/dist/generated/scene-declarations.d.ts +1 -1
  16. package/dist/generated/scene-declarations.js +1 -1
  17. package/dist/geometry/backendRegistry.d.ts +37 -0
  18. package/dist/geometry/backendRegistry.js +61 -0
  19. package/dist/geometry/common.d.ts +26 -0
  20. package/dist/geometry/common.js +78 -0
  21. package/dist/geometry/compiler.d.ts +35 -0
  22. package/dist/geometry/compiler.js +115 -0
  23. package/dist/geometry/graph.d.ts +39 -0
  24. package/dist/geometry/graph.js +32 -0
  25. package/dist/geometry/index.d.ts +9 -0
  26. package/dist/geometry/index.js +12 -0
  27. package/dist/geometry/lift.d.ts +7 -0
  28. package/dist/geometry/lift.js +376 -0
  29. package/dist/geometry/lower.d.ts +9 -0
  30. package/dist/geometry/lower.js +363 -0
  31. package/dist/geometry/parameters.d.ts +23 -0
  32. package/dist/geometry/parameters.js +46 -0
  33. package/dist/geometry/schemas/backend-schema.json +3394 -0
  34. package/dist/geometry/schemas/flowir-dialect.json +976 -0
  35. package/dist/geometry/writeParamData.d.ts +18 -0
  36. package/dist/geometry/writeParamData.js +47 -0
  37. package/dist/geometry.d.ts +10 -0
  38. package/dist/geometry.js +19 -0
  39. package/dist/index.d.ts +2 -0
  40. package/dist/index.js +2 -0
  41. package/dist/kakapo.d.ts +9 -5
  42. package/dist/kakapo.js +7 -6
  43. package/dist/openscad.d.ts +85 -0
  44. package/dist/openscad.js +223 -0
  45. package/dist/pricing.js +9 -29
  46. package/dist/repair-state.d.ts +50 -0
  47. package/dist/repair-state.js +96 -0
  48. package/dist/runtime.d.ts +16 -36
  49. package/dist/runtime.js +132 -139
  50. package/dist/scene-environment.d.ts +25 -0
  51. package/dist/scene-environment.js +76 -0
  52. package/dist/scene-health.d.ts +49 -0
  53. package/dist/scene-health.js +176 -0
  54. package/dist/scene-metadata.d.ts +6 -0
  55. package/dist/scene-metadata.js +65 -0
  56. package/dist/scene-operations.d.ts +47 -0
  57. package/dist/scene-operations.js +126 -0
  58. package/dist/sdk-geometry-host.d.ts +12 -0
  59. package/dist/sdk-geometry-host.js +306 -0
  60. package/dist/sdk-openscad-host.d.ts +14 -0
  61. package/dist/sdk-openscad-host.js +296 -0
  62. package/dist/sdk-openscad-renderer.d.ts +11 -0
  63. package/dist/sdk-openscad-renderer.js +71 -0
  64. package/dist/sdk-scene-health-host.d.ts +4 -0
  65. package/dist/sdk-scene-health-host.js +13 -0
  66. package/dist/sdk-scene-host.d.ts +312 -0
  67. package/dist/sdk-scene-host.js +202 -0
  68. package/dist/sdk-scene-screenshot.d.ts +7 -0
  69. package/dist/sdk-scene-screenshot.js +17 -0
  70. package/dist/server/demo-scene-materials.d.ts +3 -0
  71. package/dist/server/demo-scene-materials.js +18 -0
  72. package/dist/server/express.js +2 -4
  73. package/dist/server/fixtures/materials/matte-blue.json +14 -0
  74. package/dist/server/fixtures/materials/polished-copper.json +14 -0
  75. package/dist/server/index.d.ts +2 -1
  76. package/dist/server/index.js +2 -1
  77. package/dist/server/service.d.ts +4 -0
  78. package/dist/server/service.js +26 -2
  79. package/dist/server/sqlite-store.d.ts +31 -0
  80. package/dist/server/sqlite-store.js +224 -0
  81. package/dist/server/standalone.d.ts +14 -1
  82. package/dist/server/standalone.js +160 -27
  83. package/dist/server/store.js +3 -1
  84. package/dist/types.d.ts +1 -1
  85. package/dist/womp-scene-api.d.ts +283 -0
  86. package/dist/womp-scene-api.js +974 -0
  87. package/package.json +22 -10
  88. package/dist/kakapo-capability.d.ts +0 -45
  89. package/dist/kakapo-capability.js +0 -169
@@ -0,0 +1,18 @@
1
+ import type { GeometryGraph } from "./graph.js";
2
+ import type { BackendRegistry, BackendValue, GraphExt } from "./backendRegistry.js";
3
+ /**
4
+ * Build a map from IR param name → value-node backend ID by inspecting
5
+ * a graph for value nodes connected to GroupInputParam nodes.
6
+ */
7
+ export declare function buildParamMap(graph: GeometryGraph, graphExt: GraphExt, gipTypeId: number | null, valueTypeIds: Map<number, string>): Map<string, string>;
8
+ /**
9
+ * Migrate user-set param values from an old graph's instance data to a new
10
+ * graph produced by `lower`. Params are matched by name (derived from
11
+ * graphExt); values for removed or renamed params are dropped, and new params
12
+ * keep the defaults already baked into the new graph by `lower`.
13
+ */
14
+ export declare function writeParamData(oldGraph: GeometryGraph, oldGraphExt: GraphExt, newGraph: GeometryGraph, newGraphExt: GraphExt, prevInstanceData: Record<string, {
15
+ inputs: Record<string, BackendValue>;
16
+ }>, backendRegistry: BackendRegistry): Record<string, {
17
+ inputs: Record<string, BackendValue>;
18
+ }>;
@@ -0,0 +1,47 @@
1
+ import { buildIncomingMap, resolveParamTypeIds, titleToAstName, } from "./common.js";
2
+ /**
3
+ * Build a map from IR param name → value-node backend ID by inspecting
4
+ * a graph for value nodes connected to GroupInputParam nodes.
5
+ */
6
+ export function buildParamMap(graph, graphExt, gipTypeId, valueTypeIds) {
7
+ const nodes = graph.nodes;
8
+ const incoming = buildIncomingMap(graph.connections);
9
+ const paramMap = new Map();
10
+ for (const [bid, node] of Object.entries(nodes)) {
11
+ if (!valueTypeIds.has(node.type_id))
12
+ continue;
13
+ const edges = incoming.get(bid);
14
+ const gipEdge = edges?.find((e) => {
15
+ const src = nodes[e.fromBid];
16
+ return src && src.type_id === gipTypeId && e.toPort === 0;
17
+ });
18
+ if (!gipEdge)
19
+ continue;
20
+ const extName = graphExt.nodes?.[gipEdge.fromBid]?.name;
21
+ if (!extName)
22
+ continue;
23
+ paramMap.set(titleToAstName(extName), bid);
24
+ }
25
+ return paramMap;
26
+ }
27
+ /**
28
+ * Migrate user-set param values from an old graph's instance data to a new
29
+ * graph produced by `lower`. Params are matched by name (derived from
30
+ * graphExt); values for removed or renamed params are dropped, and new params
31
+ * keep the defaults already baked into the new graph by `lower`.
32
+ */
33
+ export function writeParamData(oldGraph, oldGraphExt, newGraph, newGraphExt, prevInstanceData, backendRegistry) {
34
+ const { gipTypeId, valueTypeIds } = resolveParamTypeIds(backendRegistry);
35
+ const oldParamMap = buildParamMap(oldGraph, oldGraphExt, gipTypeId, valueTypeIds);
36
+ const newParamMap = buildParamMap(newGraph, newGraphExt, gipTypeId, valueTypeIds);
37
+ const result = {};
38
+ for (const [name, newBid] of newParamMap) {
39
+ const oldBid = oldParamMap.get(name);
40
+ if (oldBid &&
41
+ prevInstanceData[oldBid] &&
42
+ oldGraph.nodes[oldBid]?.type_id === newGraph.nodes[newBid]?.type_id) {
43
+ result[newBid] = prevInstanceData[oldBid];
44
+ }
45
+ }
46
+ return result;
47
+ }
@@ -0,0 +1,10 @@
1
+ export { backendRegistry, compileGeometry, flowirRegistry, migrateGraphExt, readEditableGeometry, } from "./geometry/compiler.js";
2
+ export { createGeoNodesRegistry, loadGeoNodesDialect, } from "./geometry/index.js";
3
+ export type { GeometryGraph, GraphData } from "./geometry/graph.js";
4
+ export { graphDataSchema, geometryGraphSchema, graphExtSchema, } from "./geometry/graph.js";
5
+ export { migrateParameterOverrides, readParameterOverrides, } from "./geometry/parameters.js";
6
+ export type { BackendNodeSchema, BackendPort, BackendValue, GraphExt, } from "./geometry/backendRegistry.js";
7
+ export declare function geometryReference(): {
8
+ rules: string;
9
+ catalog: string;
10
+ };
@@ -0,0 +1,19 @@
1
+ import * as flowir from "@womp/flowir";
2
+ import { flowirRegistry } from "./geometry/compiler.js";
3
+ export { backendRegistry, compileGeometry, flowirRegistry, migrateGraphExt, readEditableGeometry, } from "./geometry/compiler.js";
4
+ export { createGeoNodesRegistry, loadGeoNodesDialect, } from "./geometry/index.js";
5
+ export { graphDataSchema, geometryGraphSchema, graphExtSchema, } from "./geometry/graph.js";
6
+ export { migrateParameterOverrides, readParameterOverrides, } from "./geometry/parameters.js";
7
+ let reference;
8
+ export function geometryReference() {
9
+ reference ??= {
10
+ rules: `Write one statement per line:
11
+ param Float width = 20.0 min=1 max=100 step=1
12
+ node box Primitive Type=Box Position=Vec3(0.0,0.0,0.0) Rotation=Vec3(0.0,0.0,0.0) Size=width Blend=0.0 Roundness=0.0
13
+ out Geometry=box.Geometry
14
+ Use decimal components in Vec3 parameter/constant literals, e.g. Vec3(20.0,20.0,20.0). Output name is case-sensitive: Geometry.
15
+ ${flowir.renderDslRulesBlock()}`,
16
+ catalog: flowir.renderSchemaBlock(flowirRegistry.getSchema()),
17
+ };
18
+ return reference;
19
+ }
package/dist/index.d.ts CHANGED
@@ -3,6 +3,8 @@ export { createSparkTools, type SparkPersistence, type SparkToolCall } from "./a
3
3
  export { convertSparkMessages } from "./model-history.js";
4
4
  export { prepareSparkContext, estimateSparkContextTokens, SparkContextLimitError, type SparkContextPolicy, } from "./context.js";
5
5
  export * from "./capabilities.js";
6
+ export { createSdkSceneEditor, createSdkSceneHost, type SdkSceneEditor, type SdkSceneEditorOptions, type SdkSceneEditIdentity, type SdkSceneServices, } from "./sdk-scene-host.js";
7
+ export { recoverSceneOperation, type SceneOperation, type SceneOperationStore } from "./scene-operations.js";
6
8
  export type { JavaScriptExecutor, JavaScriptGlobals, JavaScriptUserWait } from "./executor.js";
7
9
  export { DEFAULT_MODEL_ID, getSparkModel, REASONING_EFFORT_LABELS, resolveReasoningEffort, SPARK_MODELS, } from "./models.js";
8
10
  export type { ModelProvider, ReasoningEffort, SparkModel } from "./models.js";
package/dist/index.js CHANGED
@@ -3,5 +3,7 @@ export { createSparkTools } from "./agent-tools.js";
3
3
  export { convertSparkMessages } from "./model-history.js";
4
4
  export { prepareSparkContext, estimateSparkContextTokens, SparkContextLimitError, } from "./context.js";
5
5
  export * from "./capabilities.js";
6
+ export { createSdkSceneEditor, createSdkSceneHost, } from "./sdk-scene-host.js";
7
+ export { recoverSceneOperation } from "./scene-operations.js";
6
8
  export { DEFAULT_MODEL_ID, getSparkModel, REASONING_EFFORT_LABELS, resolveReasoningEffort, SPARK_MODELS, } from "./models.js";
7
9
  export { SPARK_AGENT_PROMPT } from "./prompt.js";
package/dist/kakapo.d.ts CHANGED
@@ -1,6 +1,10 @@
1
1
  export { KakapoRuntime } from "./runtime.js";
2
- export { createKakapoSceneHost } from "./kakapo-capability.js";
3
- export type { KakapoSceneHostOptions } from "./kakapo-capability.js";
4
- export type { KakapoSceneSeams } from "./runtime.js";
5
- export { LightType, NodeType, OperationType, PrimitiveType } from "@womp/scene-api";
6
- export type { WompSceneDraft } from "./capabilities/scene-draft.js";
2
+ export { createSdkSceneDraft, createSdkSceneEditor, createSdkSceneHost, type SdkSceneEditor, type SdkSceneEditorOptions, type SdkSceneEditIdentity, type SdkSceneServices, } from "./sdk-scene-host.js";
3
+ export type { SceneOperation, SceneOperationStore, } from "./scene-operations.js";
4
+ export { createWompSceneApi, NodeType, OperationType, PrimitiveTypeValue, } from "./womp-scene-api.js";
5
+ export type { WompSceneApi, WompSceneApiContext } from "./womp-scene-api.js";
6
+ export { createSdkGeometryHost, type SdkGeometryHostOptions, } from "./sdk-geometry-host.js";
7
+ export { createSdkOpenScadHost, type SdkOpenScadHostOptions, } from "./sdk-openscad-host.js";
8
+ export { createSdkSceneHealthHost } from "./sdk-scene-health-host.js";
9
+ export * from "./scene-health.js";
10
+ export * from "./repair-state.js";
package/dist/kakapo.js CHANGED
@@ -1,7 +1,8 @@
1
1
  export { KakapoRuntime } from "./runtime.js";
2
- export { createKakapoSceneHost } from "./kakapo-capability.js";
3
- // The scene surface itself now comes from `@womp/scene-api`, which owns the
4
- // enum tables and the coordinate conversion this entry point used to re-export
5
- // from a second copy of them. `PrimitiveTypeValue` is gone with that copy; its
6
- // replacement is `PrimitiveType`, with the same on-disk values.
7
- export { LightType, NodeType, OperationType, PrimitiveType } from "@womp/scene-api";
2
+ export { createSdkSceneDraft, createSdkSceneEditor, createSdkSceneHost, } from "./sdk-scene-host.js";
3
+ export { createWompSceneApi, NodeType, OperationType, PrimitiveTypeValue, } from "./womp-scene-api.js";
4
+ export { createSdkGeometryHost, } from "./sdk-geometry-host.js";
5
+ export { createSdkOpenScadHost, } from "./sdk-openscad-host.js";
6
+ export { createSdkSceneHealthHost } from "./sdk-scene-health-host.js";
7
+ export * from "./scene-health.js";
8
+ export * from "./repair-state.js";
@@ -0,0 +1,85 @@
1
+ import { type KakapoAPI } from "@womp/kakapo-sdk";
2
+ export declare const OPENSCAD_VALIDATION_UNITS_PER_SCENE_UNIT = 25;
3
+ export declare const MAX_THIN_PERCENTAGE = 5;
4
+ export declare const MAX_PRINTABILITY_REPAIR_ATTEMPTS = 4;
5
+ export type OpenScadCompileRequest = {
6
+ source: string;
7
+ params: Record<string, unknown>;
8
+ };
9
+ export type Vector3 = {
10
+ x: number;
11
+ y: number;
12
+ z: number;
13
+ };
14
+ export type OpenScadParamSpec = {
15
+ name: string;
16
+ default_value: unknown;
17
+ value: unknown;
18
+ min?: number;
19
+ max?: number;
20
+ step?: number;
21
+ enum_options?: unknown[];
22
+ };
23
+ export type OpenScadBoundingBox = {
24
+ min: Vector3;
25
+ max: Vector3;
26
+ };
27
+ export type OpenScadCompileResponse = {
28
+ version: number;
29
+ error: string;
30
+ warnings: string[];
31
+ params: OpenScadParamSpec[];
32
+ materials: {
33
+ material_id: number;
34
+ color: Vector3;
35
+ }[];
36
+ boundingBox?: OpenScadBoundingBox;
37
+ };
38
+ export type PrintThickness = {
39
+ average: {
40
+ fine: number;
41
+ good: number;
42
+ thin: number;
43
+ };
44
+ object_ids: number[];
45
+ x: {
46
+ fine: number;
47
+ good: number;
48
+ thin: number;
49
+ };
50
+ y: {
51
+ fine: number;
52
+ good: number;
53
+ thin: number;
54
+ };
55
+ z: {
56
+ fine: number;
57
+ good: number;
58
+ thin: number;
59
+ };
60
+ };
61
+ export type OpenScadPrintabilityResult = {
62
+ status: "passed" | "failed" | "unavailable";
63
+ objectIds: number[];
64
+ maxThinPercentage: number;
65
+ thinPercentage?: number;
66
+ thickness?: PrintThickness;
67
+ reason?: "send_failed" | "connection_lost" | "timeout" | "invalid_response" | "scene_changed" | "context_busy";
68
+ };
69
+ export type OpenScadPrintabilityRequest = {
70
+ api: KakapoAPI;
71
+ objectIds: number[];
72
+ expectedRevision: string;
73
+ signal: AbortSignal;
74
+ onSubmissionStarted?: () => void;
75
+ onPendingCompletion?: (completion: Promise<void>) => void;
76
+ };
77
+ export declare function getOpenScadGroundedPosition(bounds?: OpenScadBoundingBox): Vector3;
78
+ export declare function toOpenScadCompileResponse(value: unknown): OpenScadCompileResponse | undefined;
79
+ export declare function requestOpenScadPrintability(options: {
80
+ api: KakapoAPI;
81
+ objectIds: number[];
82
+ onSubmissionStarted?: () => void;
83
+ onPendingCompletion?: (completion: Promise<void>) => void;
84
+ }): Promise<OpenScadPrintabilityResult>;
85
+ export declare function requestStableOpenScadPrintability(options: OpenScadPrintabilityRequest): Promise<OpenScadPrintabilityResult>;
@@ -0,0 +1,223 @@
1
+ import { KakapoError, KakapoRpcError, KakapoTimeoutError, } from "@womp/kakapo-sdk";
2
+ export const OPENSCAD_VALIDATION_UNITS_PER_SCENE_UNIT = 25;
3
+ export const MAX_THIN_PERCENTAGE = 5;
4
+ export const MAX_PRINTABILITY_REPAIR_ATTEMPTS = 4;
5
+ function isRecord(value) {
6
+ return (typeof value === "object" &&
7
+ value !== null &&
8
+ Array.isArray(value) === false);
9
+ }
10
+ function number(value) {
11
+ return typeof value === "number" && Number.isFinite(value)
12
+ ? value
13
+ : undefined;
14
+ }
15
+ function vector(value) {
16
+ if (isRecord(value) === false)
17
+ return undefined;
18
+ const x = number(value.x);
19
+ const y = number(value.y);
20
+ const z = number(value.z);
21
+ return x === undefined || y === undefined || z === undefined
22
+ ? undefined
23
+ : { x, y, z };
24
+ }
25
+ function boundingBox(value) {
26
+ if (isRecord(value) === false)
27
+ return undefined;
28
+ const min = vector(value.min);
29
+ const max = vector(value.max);
30
+ if (min === undefined || max === undefined)
31
+ return undefined;
32
+ if (min.x > max.x || min.y > max.y || min.z > max.z)
33
+ return undefined;
34
+ const scale = 1 / OPENSCAD_VALIDATION_UNITS_PER_SCENE_UNIT;
35
+ return {
36
+ min: { x: min.x * scale, y: min.y * scale, z: min.z * scale },
37
+ max: { x: max.x * scale, y: max.y * scale, z: max.z * scale },
38
+ };
39
+ }
40
+ export function getOpenScadGroundedPosition(bounds) {
41
+ if (bounds === undefined)
42
+ return { x: 0, y: 0, z: 0 };
43
+ return {
44
+ x: -(bounds.min.x + bounds.max.x) / 2,
45
+ y: -bounds.min.y,
46
+ z: -(bounds.min.z + bounds.max.z) / 2,
47
+ };
48
+ }
49
+ export function toOpenScadCompileResponse(value) {
50
+ if (isRecord(value) === false)
51
+ return undefined;
52
+ const params = Array.isArray(value.params)
53
+ ? value.params.flatMap((item) => {
54
+ if (isRecord(item) === false || typeof item.name !== "string")
55
+ return [];
56
+ const result = {
57
+ name: item.name,
58
+ default_value: item.default_value,
59
+ value: item.value,
60
+ };
61
+ for (const key of ["min", "max", "step"]) {
62
+ const parsed = number(item[key]);
63
+ if (parsed !== undefined)
64
+ result[key] = parsed;
65
+ }
66
+ if (Array.isArray(item.enum_options))
67
+ result.enum_options = item.enum_options;
68
+ return [result];
69
+ })
70
+ : [];
71
+ const materials = Array.isArray(value.materials)
72
+ ? value.materials.flatMap((item) => {
73
+ if (isRecord(item) === false)
74
+ return [];
75
+ const material_id = number(item.material_id);
76
+ const color = vector(item.color);
77
+ return material_id === undefined || color === undefined
78
+ ? []
79
+ : [{ material_id, color }];
80
+ })
81
+ : [];
82
+ const result = {
83
+ version: number(value.version) ?? 1,
84
+ error: typeof value.error === "string" ? value.error : "",
85
+ warnings: Array.isArray(value.warnings)
86
+ ? value.warnings.filter((item) => typeof item === "string")
87
+ : [],
88
+ params,
89
+ materials,
90
+ };
91
+ const bounds = boundingBox(value.bounding_box);
92
+ if (bounds !== undefined)
93
+ result.boundingBox = bounds;
94
+ return result;
95
+ }
96
+ function parseThickness(value) {
97
+ if (isRecord(value) === false || Array.isArray(value.object_ids) === false)
98
+ return undefined;
99
+ if (value.object_ids.some((id) => number(id) === undefined))
100
+ return undefined;
101
+ for (const axis of ["average", "x", "y", "z"]) {
102
+ const band = value[axis];
103
+ if (isRecord(band) === false ||
104
+ number(band.fine) === undefined ||
105
+ number(band.good) === undefined ||
106
+ number(band.thin) === undefined)
107
+ return undefined;
108
+ }
109
+ return value;
110
+ }
111
+ function sceneChangedResult(objectIds) {
112
+ return {
113
+ status: "unavailable",
114
+ objectIds,
115
+ maxThinPercentage: MAX_THIN_PERCENTAGE,
116
+ reason: "scene_changed",
117
+ };
118
+ }
119
+ export async function requestOpenScadPrintability(options) {
120
+ const token = options.api.newToken();
121
+ let ack;
122
+ options.onSubmissionStarted?.();
123
+ try {
124
+ ack = await options.api.rpc("set_3dp_context", [
125
+ JSON.stringify({
126
+ object_ids: options.objectIds,
127
+ holes_ids: [],
128
+ thickness: 0,
129
+ hollow: false,
130
+ token,
131
+ }),
132
+ ]);
133
+ }
134
+ catch (error) {
135
+ const knownUnsent = error instanceof KakapoError &&
136
+ (error.code === "NOT_CONNECTED" || error.code === "SEND_FAILED");
137
+ const explicitRejection = error instanceof KakapoRpcError;
138
+ if (knownUnsent === false && explicitRejection === false) {
139
+ options.onPendingCompletion?.(waitForPendingToken(options.api, token));
140
+ }
141
+ return {
142
+ status: "unavailable",
143
+ objectIds: options.objectIds,
144
+ maxThinPercentage: MAX_THIN_PERCENTAGE,
145
+ reason: error instanceof KakapoTimeoutError
146
+ ? "timeout"
147
+ : knownUnsent || explicitRejection
148
+ ? "send_failed"
149
+ : "connection_lost",
150
+ };
151
+ }
152
+ if (ack !== "success")
153
+ return {
154
+ status: "unavailable",
155
+ objectIds: options.objectIds,
156
+ maxThinPercentage: MAX_THIN_PERCENTAGE,
157
+ reason: "send_failed",
158
+ };
159
+ let response;
160
+ try {
161
+ response = await options.api.waitForToken(token, 20_000);
162
+ }
163
+ catch (error) {
164
+ if (error instanceof KakapoTimeoutError) {
165
+ options.onPendingCompletion?.(waitForPendingToken(options.api, token));
166
+ }
167
+ return {
168
+ status: "unavailable",
169
+ objectIds: options.objectIds,
170
+ maxThinPercentage: MAX_THIN_PERCENTAGE,
171
+ reason: error instanceof KakapoTimeoutError ? "timeout" : "connection_lost",
172
+ };
173
+ }
174
+ const thickness = isRecord(response)
175
+ ? parseThickness(response.thickness)
176
+ : undefined;
177
+ if (thickness === undefined ||
178
+ thickness.object_ids.length !== options.objectIds.length ||
179
+ thickness.object_ids.some((id) => options.objectIds.includes(id) === false)) {
180
+ return {
181
+ status: "unavailable",
182
+ objectIds: options.objectIds,
183
+ maxThinPercentage: MAX_THIN_PERCENTAGE,
184
+ reason: "invalid_response",
185
+ };
186
+ }
187
+ return {
188
+ status: thickness.average.thin <= MAX_THIN_PERCENTAGE ? "passed" : "failed",
189
+ objectIds: options.objectIds,
190
+ maxThinPercentage: MAX_THIN_PERCENTAGE,
191
+ thinPercentage: thickness.average.thin,
192
+ thickness,
193
+ };
194
+ }
195
+ async function waitForPendingToken(api, token) {
196
+ for (;;) {
197
+ try {
198
+ await api.waitForToken(token, 20_000);
199
+ return;
200
+ }
201
+ catch (error) {
202
+ if (error instanceof KakapoTimeoutError)
203
+ continue;
204
+ throw error;
205
+ }
206
+ }
207
+ }
208
+ export async function requestStableOpenScadPrintability(options) {
209
+ options.signal.throwIfAborted();
210
+ const initialRevision = await options.api.getSceneRevision();
211
+ options.signal.throwIfAborted();
212
+ if (initialRevision !== options.expectedRevision)
213
+ return sceneChangedResult(options.objectIds);
214
+ const result = await requestOpenScadPrintability(options);
215
+ if (result.reason === "timeout" || result.reason === "connection_lost")
216
+ return result;
217
+ options.signal.throwIfAborted();
218
+ await options.api.refreshScene();
219
+ options.signal.throwIfAborted();
220
+ if ((await options.api.getSceneRevision()) !== options.expectedRevision)
221
+ return sceneChangedResult(options.objectIds);
222
+ return result;
223
+ }
package/dist/pricing.js CHANGED
@@ -1,36 +1,23 @@
1
1
  // Standard, global, direct API rates in USD per million tokens, checked 2026-09-09.
2
2
  const PRICES = {
3
3
  "gpt-6-astra": {
4
- input: 10,
5
- read: 1,
6
- write: 12.5,
7
- output: 50,
8
- longContext: 272_000,
4
+ input: 10, read: 1, write: 12.5, output: 50, longContext: 272_000,
9
5
  source: "https://developers.openai.com/api/docs/models/gpt-6-astra",
10
6
  },
11
7
  "claude-opus-5": {
12
- input: 5,
13
- read: 0.5,
14
- write: 6.25,
15
- output: 25,
8
+ input: 5, read: 0.5, write: 6.25, output: 25,
16
9
  source: "https://platform.claude.com/docs/en/models/opus-5/overview",
17
10
  },
18
11
  "claude-fable-5": {
19
- input: 10,
20
- read: 1,
21
- write: 12.5,
22
- output: 50,
12
+ input: 10, read: 1, write: 12.5, output: 50,
23
13
  source: "https://platform.claude.com/docs/en/about-claude/pricing",
24
14
  },
25
15
  };
26
16
  export function calculateStepCost(modelId, usage) {
27
17
  const price = PRICES[modelId];
28
18
  const result = {
29
- modelId,
30
- pricingDate: "2026-09-09",
31
- source: price?.source,
32
- totalUsd: null,
33
- lines: [],
19
+ modelId, pricingDate: "2026-09-09", source: price?.source,
20
+ totalUsd: null, lines: [],
34
21
  };
35
22
  const unavailable = (reason) => ({ ...result, reason });
36
23
  if (price === undefined)
@@ -57,13 +44,9 @@ export function calculateStepCost(modelId, usage) {
57
44
  }
58
45
  const fiveMinute = cache.ephemeral_5m_input_tokens;
59
46
  const oneHour = cache.ephemeral_1h_input_tokens;
60
- if (typeof fiveMinute !== "number" ||
61
- typeof oneHour !== "number" ||
62
- Number.isSafeInteger(fiveMinute) === false ||
63
- Number.isSafeInteger(oneHour) === false ||
64
- fiveMinute < 0 ||
65
- oneHour < 0 ||
66
- fiveMinute + oneHour !== write) {
47
+ if (typeof fiveMinute !== "number" || typeof oneHour !== "number" ||
48
+ Number.isSafeInteger(fiveMinute) === false || Number.isSafeInteger(oneHour) === false ||
49
+ fiveMinute < 0 || oneHour < 0 || fiveMinute + oneHour !== write) {
67
50
  return unavailable("Cache write duration was not reported completely.");
68
51
  }
69
52
  hourWrite = oneHour;
@@ -72,10 +55,7 @@ export function calculateStepCost(modelId, usage) {
72
55
  const inputMultiplier = longContext ? 2 : 1;
73
56
  const outputMultiplier = longContext ? 1.5 : 1;
74
57
  const line = (label, tokens, usdPerMillion) => ({
75
- label,
76
- tokens,
77
- usdPerMillion,
78
- usd: (tokens * usdPerMillion) / 1_000_000,
58
+ label, tokens, usdPerMillion, usd: tokens * usdPerMillion / 1_000_000,
79
59
  });
80
60
  result.lines = [
81
61
  line("Uncached input", uncached, price.input * inputMultiplier),
@@ -0,0 +1,50 @@
1
+ import { type SceneHealth } from "./scene-health.js";
2
+ export type RepairReservation = {
3
+ operationId: string;
4
+ status: "reserved" | "committed" | "refunded";
5
+ };
6
+ export type RepairTargetState = {
7
+ attempts: number;
8
+ failed: boolean;
9
+ lastVerifiedFailure?: string;
10
+ reservations: Record<string, RepairReservation>;
11
+ };
12
+ export type RepairStateSnapshot = {
13
+ schemaVersion: 1;
14
+ revision: number;
15
+ targets: Record<string, RepairTargetState>;
16
+ };
17
+ export interface RepairStateStore {
18
+ read(): Promise<RepairStateSnapshot>;
19
+ compareAndSwap(expectedRevision: number, next: RepairStateSnapshot): Promise<boolean>;
20
+ }
21
+ export declare function emptyRepairState(): RepairStateSnapshot;
22
+ export declare function createMemoryRepairStateStore(initial?: RepairStateSnapshot): RepairStateStore;
23
+ export declare function createGeometryRepairTracker(store: RepairStateStore, namespace: string): {
24
+ isPending(target: string): Promise<boolean>;
25
+ assertCanWrite(target: string): Promise<void>;
26
+ reserve(target: string, operationId: string): Promise<void>;
27
+ record(target: string, operationId: string, result: SceneHealth): Promise<{
28
+ result: SceneHealth;
29
+ repairAttempts: number;
30
+ repairLimit: number;
31
+ }>;
32
+ refund(target: string, operationId: string): Promise<{
33
+ repairAttempts: number;
34
+ repairLimit: number;
35
+ }>;
36
+ };
37
+ export declare function createRepairTracker<T>(store: RepairStateStore, namespace: string, limit: number, failed: (result: T) => boolean | undefined): {
38
+ isPending(target: string): Promise<boolean>;
39
+ assertCanWrite(target: string): Promise<void>;
40
+ reserve(target: string, operationId: string): Promise<void>;
41
+ record(target: string, operationId: string, result: T): Promise<{
42
+ result: T;
43
+ repairAttempts: number;
44
+ repairLimit: number;
45
+ }>;
46
+ refund(target: string, operationId: string): Promise<{
47
+ repairAttempts: number;
48
+ repairLimit: number;
49
+ }>;
50
+ };