@womp/spark-agent 11.0.0 → 11.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/CHANGELOG.md CHANGED
@@ -4,6 +4,44 @@ Notable changes to `@womp/spark-agent`, newest first. Versions follow
4
4
  [Semantic Versioning](https://semver.org/). Add an entry with each version bump; describe what
5
5
  changed for hosts and users, and how to migrate across breaking changes.
6
6
 
7
+ ## 11.2.0 — 2026-10-15
8
+
9
+ The agent can measure scene parts for 3D printing and price them for the user.
10
+
11
+ ### Added
12
+
13
+ - `womp.printing.estimate({ objectIds, material, quantity?, hollowWallMm? })` (skill
14
+ `print-estimate`) measures the parts the objects belong to in the engine and answers their size in
15
+ mm, the share of thin walls, and per-piece price, discount, total, production days, weight and
16
+ volume. With `hollowWallMm` it also prices the hollow print, which needs Pro.
17
+ - `createPrintCapability` and `PrintHost` (`@womp/spark-agent/capabilities`), and
18
+ `createSdkPrintHost`, `requestPrintContext` and `PrintPricing` (`@womp/spark-agent/kakapo`). The
19
+ host supplies `price`; crow prices through swan's
20
+ `POST /i/agent/thread/:threadId/printing/estimate`.
21
+
22
+ ### Changed
23
+
24
+ - The OpenSCAD wall-thickness check measures through the same `requestPrintContext`; its results
25
+ are unchanged.
26
+
27
+ ## 11.1.0 — 2026-10-15
28
+
29
+ A flow run can take the conversation's files for its Image and 3D Mesh inputs.
30
+
31
+ ### Added
32
+
33
+ - `womp.flowRuns.run({ inputs })` takes `{ artifacts: [ref] }` for an Image (`viewer.images`) or
34
+ 3D Mesh (`viewer.meshes`) input that `describe()` lists: 1 to 16 refs from `womp.assets.list`,
35
+ each `{ id, mediaType, name? }` and nothing else. A malformed one is refused before the host is
36
+ called. The host turns each ref into a file of the flow; the flow-runs skill tells the model how,
37
+ and that Text inputs take a string.
38
+
39
+ ### Host migration
40
+
41
+ - A `FlowRunsHost.start` may now receive `{ artifacts }` input values. A host that does not
42
+ resolve them should refuse them; crow resolves them through swan's
43
+ `POST /i/agent/thread/:threadId/flow-run/file` and starts the run with `{ flowAssetIds }`.
44
+
7
45
  ## 11.0.0 — 2026-10-14
8
46
 
9
47
  Mesh Wompify is a skill the agent runs from a chat message, with a goal it sets itself, instead of
package/README.md CHANGED
@@ -63,6 +63,11 @@ Shared SDK scene adapters apply each edit directly to the scene and save it; not
63
63
  or replayed. An edit that fails after it began throws `SceneOperationError`, whose `operation`
64
64
  reports whether the edit was committed, rolled back or left uncertain.
65
65
 
66
+ `createPrintCapability(createSdkPrintHost({ editor, price }))` offers `womp.printing.estimate`:
67
+ the engine measures the parts (`set_3dp_context`) and the host's `price` prices the measurement for
68
+ the run's user, as swan's print estimate does. A host that serializes the engine's print context with
69
+ other wall-thickness checks passes its own `requestPrintContext`.
70
+
66
71
  ### Persistence and run lifecycle
67
72
 
68
73
  Persist the user message before starting a run. Supply `persistence.beforeToolCall`,
@@ -103,4 +103,6 @@ export type FlowRunsHost = {
103
103
  };
104
104
  export declare const FLOW_RUN_WAIT_MAX_SECONDS = 60;
105
105
  export declare const FLOW_RUN_WAIT_DEFAULT_SECONDS = 30;
106
+ /** Most files one Image / 3D Mesh input takes (swan's FLOW_INPUT_FILES_MAX). */
107
+ export declare const FLOW_RUN_INPUT_FILES_MAX = 16;
106
108
  export declare function createFlowRunsCapability(host: FlowRunsHost): SparkCapability<WompFlowRunsApi>;
@@ -7,9 +7,27 @@ const FLOW_RUN_WAIT_INLINE_MAX_SECONDS = 45;
7
7
  const runId = z
8
8
  .string()
9
9
  .regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i, "Use a runId returned by run().");
10
+ /** Most files one Image / 3D Mesh input takes (swan's FLOW_INPUT_FILES_MAX). */
11
+ export const FLOW_RUN_INPUT_FILES_MAX = 16;
12
+ const artifactRef = z
13
+ .object({ id: z.string().min(1), mediaType: z.string().min(1), name: z.string().optional() })
14
+ .strict();
15
+ /** An Image / 3D Mesh input: the conversation's files, as womp.assets.list returns them. */
16
+ const filesInput = z.object({ artifacts: z.array(artifactRef).min(1).max(FLOW_RUN_INPUT_FILES_MAX) }).strict();
17
+ const inputValue = z.json().superRefine((value, ctx) => {
18
+ if (typeof value !== "object" || value === null || Array.isArray(value) || !("artifacts" in value))
19
+ return;
20
+ const files = filesInput.safeParse(value);
21
+ if (!files.success) {
22
+ ctx.addIssue({
23
+ code: "custom",
24
+ message: `A file input is { artifacts: [ref] }: 1 to ${FLOW_RUN_INPUT_FILES_MAX} refs from womp.assets.list (id, mediaType, name), nothing else.`,
25
+ });
26
+ }
27
+ });
10
28
  const runOptions = z
11
29
  .object({
12
- inputs: z.record(z.string().min(1).max(200), z.json()).optional(),
30
+ inputs: z.record(z.string().min(1).max(200), inputValue).optional(),
13
31
  copy: z.boolean().optional(),
14
32
  deleteCopy: z.boolean().optional(),
15
33
  })
@@ -25,6 +43,7 @@ export function createFlowRunsCapability(host) {
25
43
  description: "Run the user's saved Flow (AI Nodes) pipeline on their project, follow the run, and report its result.",
26
44
  instructions: `Use womp.flowRuns to run the user's saved Flow pipeline. No canvas needs to be open.
27
45
  A run operates on the user's real flow: the input values you pass are written into the flow and become its saved values. describe() lists the inputs by node id with their current values, and the output nodes. Pass only input node ids it lists.
46
+ Input values by typeId: base.input.string (a Text node) takes a string, such as a prompt. viewer.images (an Image node) and viewer.meshes (a 3D Mesh node) take files from this conversation: { artifacts: [ref] }, each ref an item's artifact from womp.assets.list (an attachment or a generated output), images for an Image node and 3D models for a 3D Mesh node. Never pass a url or recreate a file's value from describe(); a file the user has not shared here cannot be passed.
28
47
  Only one run of a flow can be live. run() starts the run and returns at once. For a short flow, call wait(runId) and then report the result.
29
48
  To leave the user's flow untouched, pass copy: true. The run then happens on a new copy of the project, placed in the user's "Flow runs" folder: the input values, outputs and any scene changes land on the copy, and the user's flow, its saved values and its scene are not changed. Use it when the user wants to try values without changing their flow, or when their flow is busy. A copy run does not lock the scene. run() returns the copy's projectUrl; give it to the user so they can open the result.
30
49
  To keep only the result of a copy run, also pass deleteCopy: true: the copy is deleted when the run ends, whether it completed, failed or was cancelled. Use it when the user wants the outputs, not the project; do not give them that run's projectUrl, which stops working (status() then returns projectUrl null).
@@ -41,6 +60,7 @@ While a run is live on this project (not a copy run), womp.scene.access is refus
41
60
  'const started = await womp.flowRuns.run({ inputs: { "input-node-id": 123 } }); print(await womp.flowRuns.wait(started.runId, 60));',
42
61
  'const started = await womp.flowRuns.run({ inputs: { "input-node-id": 123 }, copy: true }); print(started.projectUrl);',
43
62
  'const started = await womp.flowRuns.run({ inputs: { "input-node-id": 123 }, copy: true, deleteCopy: true }); print(await womp.flowRuns.wait(started.runId, 60));',
63
+ 'const { items } = await womp.assets.list({ kind: "image" }); const started = await womp.flowRuns.run({ inputs: { "image-node-id": { artifacts: [items[0].artifact] }, "text-node-id": "a red ceramic vase" }, copy: true }); print(started);',
44
64
  ],
45
65
  },
46
66
  ],
@@ -17,7 +17,7 @@ export function createFlowCapability(host, catalog) {
17
17
  Read the current graph and flow-graphs-reference before writing. Supply the complete edited s-expression document and the latest revision. Preserve unrelated nodes and stable node IDs. Omitting a node deletes it; empty source clears the graph.
18
18
  Existing node configuration, edge identity, layout, runtime metadata, and generated outputs are retained for unchanged node identities/types. Scalar inputs represented in source are replaced by your document. The host retains preservedInputs for those same nodes. Non-private preserved inputs can be explicitly replaced in the document; never recreate asset objects or cached values as JSON strings. Private settings remain editor-owned: preserve existing private connections unchanged between retained nodes and do not introduce new private literals or connections.
19
19
  If read returns source null, explain the diagnostics. Do not replace an unreadable graph as though it were empty.
20
- Build the requested graph from the catalog's nodes even when an input cannot be expressed in source, such as a conversation upload or an editor-owned image: leave that input unconnected and tell the user which node input to set in the editor.
20
+ Build the requested graph from the catalog's nodes even when an input cannot be expressed in source, such as a conversation upload or an editor-owned image: leave that input unconnected and tell the user which node input to set in the editor. An unconnected Image or 3D Mesh node can instead take one of this conversation's files when the flow runs (womp.flowRuns).
21
21
  The Flow canvas must be open. If unavailable, tell the user to open Flow or Split in a project, or Nodes in the sidebar, and wait for their next message. Never claim a graph was created after a failed call.
22
22
  Writes validate types, preserve the runner lifecycle, and await commit. They edit the graph; they do not report that generation jobs completed. Repair compiler errors in this same conversation with a fresh read. On committed/unknown receipts after failure, inspect the graph before retrying; do not replay blindly.`,
23
23
  declarations: WOMP_FLOW_DECLARATIONS,
@@ -0,0 +1,52 @@
1
+ import type { SparkCapability, SparkInvocationContext } from "../capabilities.js";
2
+ export type PrintEstimateRequest = {
3
+ /** Scene objects to print together; each is measured with the part (top-level union) it belongs to. */
4
+ objectIds: number[];
5
+ /** Print material id, e.g. "resin-white". */
6
+ material: string;
7
+ quantity?: number;
8
+ /** Also price a hollow print with walls this thick, in mm. Hollow prints need Pro. */
9
+ hollowWallMm?: number;
10
+ };
11
+ export type PrintPrice = {
12
+ /** USD per piece before discounts. */
13
+ unitPrice: number;
14
+ /** USD off per piece, for this user's plan and the quantity. */
15
+ discount: number;
16
+ /** USD for the whole quantity after discounts. */
17
+ total: number;
18
+ productionDays: number;
19
+ /** The printed part, without support material. */
20
+ weightGrams: number;
21
+ volumeCm3: number;
22
+ supportVolumeCm3: number;
23
+ };
24
+ export type PrintEstimateUnavailableReason = "context_busy" | "timeout" | "connection_lost" | "send_failed" | "invalid_response" | "unknown_material" | "pricing_unavailable";
25
+ export type PrintEstimate = {
26
+ status: "estimated";
27
+ /** The parts that were measured. */
28
+ objectIds: number[];
29
+ material: string;
30
+ quantity: number;
31
+ sizeMm: {
32
+ width: number;
33
+ height: number;
34
+ depth: number;
35
+ };
36
+ /** Share of the walls, in percent, thinner than the engine's printable minimum. */
37
+ thinWallPercentage: number;
38
+ solid: PrintPrice;
39
+ hollow?: PrintPrice & {
40
+ wallMm: number;
41
+ };
42
+ } | {
43
+ status: "unavailable";
44
+ reason: PrintEstimateUnavailableReason;
45
+ };
46
+ export type WompPrintApi = {
47
+ estimate(request: PrintEstimateRequest): Promise<PrintEstimate>;
48
+ };
49
+ export interface PrintHost {
50
+ estimate(request: Required<Omit<PrintEstimateRequest, "hollowWallMm">> & Pick<PrintEstimateRequest, "hollowWallMm">, context: SparkInvocationContext): Promise<PrintEstimate>;
51
+ }
52
+ export declare function createPrintCapability(host: PrintHost): SparkCapability<WompPrintApi>;
@@ -0,0 +1,44 @@
1
+ import { z } from "zod";
2
+ import { WOMP_PRINT_DECLARATIONS } from "../generated/print-declarations.js";
3
+ const estimateSchema = z.strictObject({
4
+ objectIds: z.array(z.number().int().positive()).min(1).max(50),
5
+ material: z.string().min(1),
6
+ quantity: z.number().int().min(1).max(1000).default(1),
7
+ hollowWallMm: z.number().positive().max(50).optional(),
8
+ });
9
+ export function createPrintCapability(host) {
10
+ return {
11
+ skills: [
12
+ {
13
+ name: "print-estimate",
14
+ version: "1",
15
+ description: "Measure scene parts for 3D printing: size, weight, thin walls, and the price for this user.",
16
+ instructions: `Estimate measures the parts in the engine at their current scene size and prices them the way
17
+ the print panel does, with this user's plan discounts. Sizes are in mm, volumes in cm3, weights in grams and
18
+ money in USD. unitPrice and discount are per piece; total is the whole quantity after discounts.
19
+ Each object id is measured with the part it belongs to, and objectIds in the answer are those parts.
20
+ Pass hollowWallMm only when the user wants a hollow print or asks what hollow would cost; hollow needs Pro.
21
+ thinWallPercentage is the share of the walls thinner than the printable minimum; above 5 the print may fail.
22
+ Material ids: resin-white (White), resin-clear (Clear), resin-black (Black), polyjet (Full color),
23
+ resin-paint (Resin painted), chrome, chrome-paint, aluminum, stainless-steel, titanium, nylon-white,
24
+ nylon-black, nylon-glass, rubber, tpu. unknown_material means the id is not priced; do not guess a price.
25
+ context_busy means another print measurement is running; try again after it finishes.
26
+ Prices are estimates for the geometry as measured: the final price is computed again at checkout.`,
27
+ declarations: WOMP_PRINT_DECLARATIONS,
28
+ examples: [
29
+ 'print(await womp.printing.estimate({ objectIds: [12], material: "resin-white" }));',
30
+ 'const result = await womp.printing.estimate({ objectIds: [12, 15], material: "nylon-black", quantity: 4, hollowWallMm: 2.5 }); print(result);',
31
+ ],
32
+ },
33
+ ],
34
+ createApi: (context) => ({
35
+ estimate: async (input) => {
36
+ context.signal.throwIfAborted();
37
+ const request = estimateSchema.parse(input);
38
+ const result = await host.estimate(request, context);
39
+ context.signal.throwIfAborted();
40
+ return result;
41
+ },
42
+ }),
43
+ };
44
+ }
@@ -13,6 +13,8 @@ export type { OperationsHost, OperationType, OperationModel, OperationCatalog, O
13
13
  export type { AccountHost, AccountRead, AccountSection, AccountScope, AccountResult, AccountSnapshot, AccountPage, AccountProfile, AccountTeam, AccountCreditBalance, AccountSubscription, AccountBilling, AccountOrderItem, AccountOrder, AccountProject, AccountNotification, AccountWorkflow, WompAccountApi, } from "./capabilities/account.js";
14
14
  export type { KnowledgeAnswer, KnowledgeHost, WompKnowledgeApi, } from "./capabilities/knowledge.js";
15
15
  export { createOpenScadCapability } from "./capabilities/openscad.js";
16
+ export { createPrintCapability } from "./capabilities/print.js";
17
+ export type { PrintEstimate, PrintEstimateRequest, PrintEstimateUnavailableReason, PrintHost, PrintPrice, WompPrintApi, } from "./capabilities/print.js";
16
18
  export { createGeometryCapability } from "./capabilities/geometry.js";
17
19
  export type { SceneHealthHost } from "./capabilities/scene.js";
18
20
  export { createFlowCapability } from "./capabilities/flow.js";
@@ -4,6 +4,7 @@ export { createAccountCapability } from "./capabilities/account.js";
4
4
  export { createOperationsCapability } from "./capabilities/operations.js";
5
5
  export { createAssetsCapability } from "./capabilities/assets.js";
6
6
  export { createOpenScadCapability } from "./capabilities/openscad.js";
7
+ export { createPrintCapability } from "./capabilities/print.js";
7
8
  export { createGeometryCapability } from "./capabilities/geometry.js";
8
9
  export { createFlowCapability } from "./capabilities/flow.js";
9
10
  export { createFlowRunsCapability, FLOW_RUN_WAIT_DEFAULT_SECONDS, FLOW_RUN_WAIT_MAX_SECONDS, } from "./capabilities/flow-runs.js";
@@ -0,0 +1 @@
1
+ export declare const WOMP_PRINT_DECLARATIONS = "declare const womp: { printing: {\n\"estimate\": ((request: {\n\"objectIds\": Array<number>;\n\"material\": string;\n\"quantity\"?: undefined | number;\n\"hollowWallMm\"?: undefined | number;\n}) => Promise<{\n\"status\": \"estimated\";\n\"objectIds\": Array<number>;\n\"material\": string;\n\"quantity\": number;\n\"sizeMm\": {\n\"width\": number;\n\"height\": number;\n\"depth\": number;\n};\n\"thinWallPercentage\": number;\n\"solid\": {\n\"unitPrice\": number;\n\"discount\": number;\n\"total\": number;\n\"productionDays\": number;\n\"weightGrams\": number;\n\"volumeCm3\": number;\n\"supportVolumeCm3\": number;\n};\n\"hollow\"?: undefined | {\n\"unitPrice\": number;\n\"discount\": number;\n\"total\": number;\n\"productionDays\": number;\n\"weightGrams\": number;\n\"volumeCm3\": number;\n\"supportVolumeCm3\": number;\n} & {\n\"wallMm\": number;\n};\n} | {\n\"status\": \"unavailable\";\n\"reason\": \"context_busy\" | \"timeout\" | \"connection_lost\" | \"send_failed\" | \"invalid_response\" | \"unknown_material\" | \"pricing_unavailable\";\n}>);\n} };\ndeclare function print(...values: unknown[]): void;\ndeclare function emitImage(ref: { id: string; mediaType: string; name?: string }, options?: { inspect?: boolean }): Promise<void>;\ndeclare function emitFile(ref: { id: string; mediaType: string; name?: string }): Promise<void>;\n";
@@ -0,0 +1,3 @@
1
+ // Generated by scripts/generate-skill-declarations.mjs.
2
+ // prettier-ignore
3
+ export const WOMP_PRINT_DECLARATIONS = "declare const womp: { printing: {\n\"estimate\": ((request: {\n\"objectIds\": Array<number>;\n\"material\": string;\n\"quantity\"?: undefined | number;\n\"hollowWallMm\"?: undefined | number;\n}) => Promise<{\n\"status\": \"estimated\";\n\"objectIds\": Array<number>;\n\"material\": string;\n\"quantity\": number;\n\"sizeMm\": {\n\"width\": number;\n\"height\": number;\n\"depth\": number;\n};\n\"thinWallPercentage\": number;\n\"solid\": {\n\"unitPrice\": number;\n\"discount\": number;\n\"total\": number;\n\"productionDays\": number;\n\"weightGrams\": number;\n\"volumeCm3\": number;\n\"supportVolumeCm3\": number;\n};\n\"hollow\"?: undefined | {\n\"unitPrice\": number;\n\"discount\": number;\n\"total\": number;\n\"productionDays\": number;\n\"weightGrams\": number;\n\"volumeCm3\": number;\n\"supportVolumeCm3\": number;\n} & {\n\"wallMm\": number;\n};\n} | {\n\"status\": \"unavailable\";\n\"reason\": \"context_busy\" | \"timeout\" | \"connection_lost\" | \"send_failed\" | \"invalid_response\" | \"unknown_material\" | \"pricing_unavailable\";\n}>);\n} };\ndeclare function print(...values: unknown[]): void;\ndeclare function emitImage(ref: { id: string; mediaType: string; name?: string }, options?: { inspect?: boolean }): Promise<void>;\ndeclare function emitFile(ref: { id: string; mediaType: string; name?: string }): Promise<void>;\n";
package/dist/kakapo.d.ts CHANGED
@@ -6,6 +6,8 @@ export type { WompSceneApi, WompSceneApiContext } from "./womp-scene-api.js";
6
6
  export { createSdkGeometryHost, type SdkGeometryHostOptions, } from "./sdk-geometry-host.js";
7
7
  export { createSdkOpenScadHost, type SdkOpenScadHostOptions, } from "./sdk-openscad-host.js";
8
8
  export { createSdkSceneHealthHost } from "./sdk-scene-health-host.js";
9
+ export { createSdkPrintHost, type PrintPricing, type PrintPricingResult, type PrintQuote, type SdkPrintHostOptions, } from "./sdk-print-host.js";
10
+ export { requestPrintContext, type PrintContextRequest, type PrintContextResult, type PrintMeasurement, } from "./print.js";
9
11
  export * from "./scene-health.js";
10
12
  export * from "./repair-state.js";
11
13
  export { createSdkMaterialsHost, type SdkMaterialsHostOptions } from "./sdk-materials-host.js";
package/dist/kakapo.js CHANGED
@@ -4,6 +4,8 @@ export { createWompSceneApi, NodeType, OperationType, PrimitiveTypeValue, } from
4
4
  export { createSdkGeometryHost, } from "./sdk-geometry-host.js";
5
5
  export { createSdkOpenScadHost, } from "./sdk-openscad-host.js";
6
6
  export { createSdkSceneHealthHost } from "./sdk-scene-health-host.js";
7
+ export { createSdkPrintHost, } from "./sdk-print-host.js";
8
+ export { requestPrintContext, } from "./print.js";
7
9
  export * from "./scene-health.js";
8
10
  export * from "./repair-state.js";
9
11
  export { createSdkMaterialsHost } from "./sdk-materials-host.js";
@@ -1,4 +1,6 @@
1
- import { type KakapoAPI } from "@womp/kakapo-sdk";
1
+ import type { KakapoAPI } from "@womp/kakapo-sdk";
2
+ import { type PrintThickness } from "./print.js";
3
+ export type { PrintThickness } from "./print.js";
2
4
  export declare const OPENSCAD_VALIDATION_UNITS_PER_SCENE_UNIT = 25;
3
5
  export declare const MAX_THIN_PERCENTAGE = 5;
4
6
  export declare const MAX_PRINTABILITY_REPAIR_ATTEMPTS = 4;
@@ -35,29 +37,6 @@ export type OpenScadCompileResponse = {
35
37
  }[];
36
38
  boundingBox?: OpenScadBoundingBox;
37
39
  };
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
40
  export type OpenScadPrintabilityResult = {
62
41
  status: "passed" | "failed" | "unavailable";
63
42
  objectIds: number[];
package/dist/openscad.js CHANGED
@@ -1,4 +1,4 @@
1
- import { KakapoError, KakapoRpcError, KakapoTimeoutError, } from "@womp/kakapo-sdk";
1
+ import { parsePrintThickness, requestPrintContext, } from "./print.js";
2
2
  export const OPENSCAD_VALIDATION_UNITS_PER_SCENE_UNIT = 25;
3
3
  export const MAX_THIN_PERCENTAGE = 5;
4
4
  export const MAX_PRINTABILITY_REPAIR_ATTEMPTS = 4;
@@ -93,89 +93,21 @@ export function toOpenScadCompileResponse(value) {
93
93
  result.boundingBox = bounds;
94
94
  return result;
95
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
96
  export async function requestOpenScadPrintability(options) {
112
- const token = options.api.newToken();
113
- let ack;
114
- options.onSubmissionStarted?.();
115
- try {
116
- ack = await options.api.rpc("set_3dp_context", [
117
- JSON.stringify({
118
- object_ids: options.objectIds,
119
- holes_ids: [],
120
- thickness: 0,
121
- hollow: false,
122
- token,
123
- }),
124
- ]);
125
- }
126
- catch (error) {
127
- const knownUnsent = error instanceof KakapoError &&
128
- (error.code === "NOT_CONNECTED" || error.code === "SEND_FAILED");
129
- const explicitRejection = error instanceof KakapoRpcError;
130
- if (knownUnsent === false && explicitRejection === false) {
131
- options.onPendingCompletion?.(waitForPendingToken(options.api, token));
132
- }
133
- return {
134
- status: "unavailable",
135
- objectIds: options.objectIds,
136
- maxThinPercentage: MAX_THIN_PERCENTAGE,
137
- reason: error instanceof KakapoTimeoutError
138
- ? "timeout"
139
- : knownUnsent || explicitRejection
140
- ? "send_failed"
141
- : "connection_lost",
142
- };
143
- }
144
- if (ack !== "success")
145
- return {
146
- status: "unavailable",
147
- objectIds: options.objectIds,
148
- maxThinPercentage: MAX_THIN_PERCENTAGE,
149
- reason: "send_failed",
150
- };
151
- let response;
152
- try {
153
- response = await options.api.waitForToken(token, 20_000);
154
- }
155
- catch (error) {
156
- if (error instanceof KakapoTimeoutError) {
157
- options.onPendingCompletion?.(waitForPendingToken(options.api, token));
158
- }
159
- return {
160
- status: "unavailable",
161
- objectIds: options.objectIds,
162
- maxThinPercentage: MAX_THIN_PERCENTAGE,
163
- reason: error instanceof KakapoTimeoutError ? "timeout" : "connection_lost",
164
- };
165
- }
166
- const thickness = isRecord(response)
167
- ? parseThickness(response.thickness)
97
+ const unavailable = (reason) => ({
98
+ status: "unavailable",
99
+ objectIds: options.objectIds,
100
+ maxThinPercentage: MAX_THIN_PERCENTAGE,
101
+ reason,
102
+ });
103
+ const result = await requestPrintContext({ ...options, thickness: 0 });
104
+ if (result.status === "unavailable")
105
+ return unavailable(result.reason);
106
+ const thickness = isRecord(result.response)
107
+ ? parsePrintThickness(result.response.thickness, options.objectIds)
168
108
  : undefined;
169
- if (thickness === undefined ||
170
- thickness.object_ids.length !== options.objectIds.length ||
171
- thickness.object_ids.some((id) => options.objectIds.includes(id) === false)) {
172
- return {
173
- status: "unavailable",
174
- objectIds: options.objectIds,
175
- maxThinPercentage: MAX_THIN_PERCENTAGE,
176
- reason: "invalid_response",
177
- };
178
- }
109
+ if (thickness === undefined)
110
+ return unavailable("invalid_response");
179
111
  return {
180
112
  status: thickness.average.thin <= MAX_THIN_PERCENTAGE ? "passed" : "failed",
181
113
  objectIds: options.objectIds,
@@ -184,19 +116,6 @@ export async function requestOpenScadPrintability(options) {
184
116
  thickness,
185
117
  };
186
118
  }
187
- async function waitForPendingToken(api, token) {
188
- for (;;) {
189
- try {
190
- await api.waitForToken(token, 20_000);
191
- return;
192
- }
193
- catch (error) {
194
- if (error instanceof KakapoTimeoutError)
195
- continue;
196
- throw error;
197
- }
198
- }
199
- }
200
119
  export async function requestTurnOpenScadPrintability(options) {
201
120
  options.signal.throwIfAborted();
202
121
  const result = await requestOpenScadPrintability(options);
@@ -0,0 +1,61 @@
1
+ import { type KakapoAPI } from "@womp/kakapo-sdk";
2
+ export type PrintThickness = {
3
+ average: {
4
+ fine: number;
5
+ good: number;
6
+ thin: number;
7
+ };
8
+ object_ids: number[];
9
+ x: {
10
+ fine: number;
11
+ good: number;
12
+ thin: number;
13
+ };
14
+ y: {
15
+ fine: number;
16
+ good: number;
17
+ thin: number;
18
+ };
19
+ z: {
20
+ fine: number;
21
+ good: number;
22
+ thin: number;
23
+ };
24
+ };
25
+ export type PrintMetrics = {
26
+ solid: number;
27
+ support: number;
28
+ ground_area: number;
29
+ outer_surface_area: number;
30
+ };
31
+ /** The engine's `set_3dp_context` answer, in scene units. */
32
+ export type PrintMeasurement = {
33
+ dimensions: {
34
+ width: number;
35
+ height: number;
36
+ depth: number;
37
+ };
38
+ metrics: PrintMetrics;
39
+ solid_metrics: PrintMetrics;
40
+ thickness: PrintThickness;
41
+ };
42
+ export type PrintContextUnavailableReason = "send_failed" | "connection_lost" | "timeout" | "invalid_response" | "context_busy";
43
+ export type PrintContextResult = {
44
+ status: "available";
45
+ response: unknown;
46
+ } | {
47
+ status: "unavailable";
48
+ reason: PrintContextUnavailableReason;
49
+ };
50
+ export type PrintContextRequest = {
51
+ api: KakapoAPI;
52
+ objectIds: number[];
53
+ /** Wall thickness in mm to hollow at; 0 measures the parts solid. */
54
+ thickness: number;
55
+ onSubmissionStarted?: () => void;
56
+ onPendingCompletion?: (completion: Promise<void>) => void;
57
+ };
58
+ /** Measures parts for printing with the engine's `set_3dp_context`. */
59
+ export declare function requestPrintContext(options: PrintContextRequest): Promise<PrintContextResult>;
60
+ export declare function parsePrintThickness(value: unknown, objectIds: number[]): PrintThickness | undefined;
61
+ export declare function parsePrintMeasurement(value: unknown, objectIds: number[]): PrintMeasurement | undefined;
package/dist/print.js ADDED
@@ -0,0 +1,134 @@
1
+ import { KakapoError, KakapoRpcError, KakapoTimeoutError, } from "@womp/kakapo-sdk";
2
+ function isRecord(value) {
3
+ return (typeof value === "object" &&
4
+ value !== null &&
5
+ Array.isArray(value) === false);
6
+ }
7
+ function number(value) {
8
+ return typeof value === "number" && Number.isFinite(value)
9
+ ? value
10
+ : undefined;
11
+ }
12
+ async function waitForPendingToken(api, token) {
13
+ for (;;) {
14
+ try {
15
+ await api.waitForToken(token, 20_000);
16
+ return;
17
+ }
18
+ catch (error) {
19
+ if (error instanceof KakapoTimeoutError)
20
+ continue;
21
+ throw error;
22
+ }
23
+ }
24
+ }
25
+ /** Measures parts for printing with the engine's `set_3dp_context`. */
26
+ export async function requestPrintContext(options) {
27
+ const token = options.api.newToken();
28
+ let ack;
29
+ options.onSubmissionStarted?.();
30
+ try {
31
+ ack = await options.api.rpc("set_3dp_context", [
32
+ JSON.stringify({
33
+ object_ids: options.objectIds,
34
+ holes_ids: [],
35
+ thickness: options.thickness,
36
+ hollow: options.thickness > 0,
37
+ token,
38
+ }),
39
+ ]);
40
+ }
41
+ catch (error) {
42
+ const knownUnsent = error instanceof KakapoError &&
43
+ (error.code === "NOT_CONNECTED" || error.code === "SEND_FAILED");
44
+ const explicitRejection = error instanceof KakapoRpcError;
45
+ if (knownUnsent === false && explicitRejection === false) {
46
+ options.onPendingCompletion?.(waitForPendingToken(options.api, token));
47
+ }
48
+ return {
49
+ status: "unavailable",
50
+ reason: error instanceof KakapoTimeoutError
51
+ ? "timeout"
52
+ : knownUnsent || explicitRejection
53
+ ? "send_failed"
54
+ : "connection_lost",
55
+ };
56
+ }
57
+ if (ack !== "success")
58
+ return { status: "unavailable", reason: "send_failed" };
59
+ try {
60
+ return {
61
+ status: "available",
62
+ response: await options.api.waitForToken(token, 20_000),
63
+ };
64
+ }
65
+ catch (error) {
66
+ if (error instanceof KakapoTimeoutError) {
67
+ options.onPendingCompletion?.(waitForPendingToken(options.api, token));
68
+ }
69
+ return {
70
+ status: "unavailable",
71
+ reason: error instanceof KakapoTimeoutError ? "timeout" : "connection_lost",
72
+ };
73
+ }
74
+ }
75
+ export function parsePrintThickness(value, objectIds) {
76
+ if (isRecord(value) === false || Array.isArray(value.object_ids) === false)
77
+ return undefined;
78
+ if (value.object_ids.some((id) => number(id) === undefined))
79
+ return undefined;
80
+ for (const axis of ["average", "x", "y", "z"]) {
81
+ const band = value[axis];
82
+ if (isRecord(band) === false ||
83
+ number(band.fine) === undefined ||
84
+ number(band.good) === undefined ||
85
+ number(band.thin) === undefined)
86
+ return undefined;
87
+ }
88
+ if (value.object_ids.length !== objectIds.length ||
89
+ value.object_ids.some((id) => objectIds.includes(id) === false))
90
+ return undefined;
91
+ return value;
92
+ }
93
+ function parseMetrics(value) {
94
+ if (isRecord(value) === false)
95
+ return undefined;
96
+ const solid = number(value.solid);
97
+ const support = number(value.support);
98
+ const groundArea = number(value.ground_area);
99
+ const outerSurfaceArea = number(value.outer_surface_area);
100
+ return solid === undefined ||
101
+ support === undefined ||
102
+ groundArea === undefined ||
103
+ outerSurfaceArea === undefined
104
+ ? undefined
105
+ : {
106
+ solid,
107
+ support,
108
+ ground_area: groundArea,
109
+ outer_surface_area: outerSurfaceArea,
110
+ };
111
+ }
112
+ export function parsePrintMeasurement(value, objectIds) {
113
+ if (isRecord(value) === false || isRecord(value.dimensions) === false)
114
+ return undefined;
115
+ const width = number(value.dimensions.width);
116
+ const height = number(value.dimensions.height);
117
+ const depth = number(value.dimensions.depth);
118
+ const metrics = parseMetrics(value.metrics);
119
+ const solidMetrics = parseMetrics(value.solid_metrics);
120
+ const thickness = parsePrintThickness(value.thickness, objectIds);
121
+ if (width === undefined ||
122
+ height === undefined ||
123
+ depth === undefined ||
124
+ metrics === undefined ||
125
+ solidMetrics === undefined ||
126
+ thickness === undefined)
127
+ return undefined;
128
+ return {
129
+ dimensions: { width, height, depth },
130
+ metrics,
131
+ solid_metrics: solidMetrics,
132
+ thickness,
133
+ };
134
+ }
@@ -0,0 +1,41 @@
1
+ import type { PrintHost, SparkInvocationContext } from "./capabilities.js";
2
+ import { type PrintContextRequest, type PrintContextResult, type PrintMeasurement } from "./print.js";
3
+ import type { SdkSceneEditor } from "./sdk-scene-host.js";
4
+ /** One priced variant, as swan's print estimate answers it. */
5
+ export type PrintQuote = {
6
+ unitPrice: number;
7
+ discount: number;
8
+ prodDays: number;
9
+ params: {
10
+ mass: {
11
+ solid: number;
12
+ };
13
+ properties: {
14
+ solid: number;
15
+ support: number;
16
+ };
17
+ };
18
+ };
19
+ export type PrintPricingResult = {
20
+ status: "priced";
21
+ solid: PrintQuote;
22
+ hollow?: PrintQuote;
23
+ } | {
24
+ status: "unavailable";
25
+ reason: "unknown_material" | "pricing_unavailable";
26
+ };
27
+ /** Prices an engine measurement for the run's user. */
28
+ export type PrintPricing = (request: {
29
+ material: string;
30
+ quantity: number;
31
+ /** The wall thickness in mm the measurement was hollowed at. */
32
+ thickness?: number;
33
+ measurement: PrintMeasurement;
34
+ }, context: SparkInvocationContext) => Promise<PrintPricingResult>;
35
+ export type SdkPrintHostOptions = {
36
+ editor: SdkSceneEditor;
37
+ price: PrintPricing;
38
+ /** Supply this when the host serializes the engine's print context. */
39
+ requestPrintContext?: (request: PrintContextRequest) => Promise<PrintContextResult>;
40
+ };
41
+ export declare function createSdkPrintHost(options: SdkPrintHostOptions): PrintHost;
@@ -0,0 +1,75 @@
1
+ import { parsePrintMeasurement, requestPrintContext, } from "./print.js";
2
+ import { getSdkSceneAreaId } from "./scene-health.js";
3
+ /** Millimetres in one scene unit. */
4
+ const MM_PER_SCENE_UNIT = 25;
5
+ function partId(api, objectId) {
6
+ const areaId = Number(getSdkSceneAreaId(api, objectId));
7
+ if (api.getNode(areaId).kind !== "union")
8
+ throw new Error(`Object ${objectId} is not in a printable part.`);
9
+ return areaId;
10
+ }
11
+ function price(quote, quantity) {
12
+ const round = (value) => Math.round(value * 100) / 100;
13
+ return {
14
+ unitPrice: round(quote.unitPrice),
15
+ discount: round(quote.discount),
16
+ total: round(Math.max(0, quote.unitPrice - quote.discount) * quantity),
17
+ productionDays: quote.prodDays,
18
+ weightGrams: round(quote.params.mass.solid),
19
+ volumeCm3: round(quote.params.properties.solid),
20
+ supportVolumeCm3: round(quote.params.properties.support),
21
+ };
22
+ }
23
+ export function createSdkPrintHost(options) {
24
+ return {
25
+ estimate: async (request, context) => {
26
+ const thickness = request.hollowWallMm ?? 0;
27
+ const measured = await options.editor.read(context, async (api, beginSettlement) => {
28
+ const objectIds = [
29
+ ...new Set(request.objectIds.map((id) => partId(api, id))),
30
+ ];
31
+ context.reportStatus("running", "Measuring for print...");
32
+ const result = await (options.requestPrintContext ?? requestPrintContext)({
33
+ api,
34
+ objectIds,
35
+ thickness,
36
+ onSubmissionStarted: beginSettlement,
37
+ });
38
+ return { objectIds, result };
39
+ });
40
+ context.signal.throwIfAborted();
41
+ const unavailable = (reason) => ({ status: "unavailable", reason });
42
+ if (measured.result.status === "unavailable")
43
+ return unavailable(measured.result.reason);
44
+ const measurement = parsePrintMeasurement(measured.result.response, measured.objectIds);
45
+ if (measurement === undefined)
46
+ return unavailable("invalid_response");
47
+ const priced = await options.price({
48
+ material: request.material,
49
+ quantity: request.quantity,
50
+ ...(thickness > 0 ? { thickness } : {}),
51
+ measurement,
52
+ }, context);
53
+ context.signal.throwIfAborted();
54
+ if (priced.status === "unavailable")
55
+ return unavailable(priced.reason);
56
+ const mm = (value) => Math.round(value * MM_PER_SCENE_UNIT * 10) / 10;
57
+ return {
58
+ status: "estimated",
59
+ objectIds: measured.objectIds,
60
+ material: request.material,
61
+ quantity: request.quantity,
62
+ sizeMm: {
63
+ width: mm(measurement.dimensions.width),
64
+ height: mm(measurement.dimensions.height),
65
+ depth: mm(measurement.dimensions.depth),
66
+ },
67
+ thinWallPercentage: Math.round(measurement.thickness.average.thin * 10) / 10,
68
+ solid: price(priced.solid, request.quantity),
69
+ ...(priced.hollow !== undefined && thickness > 0
70
+ ? { hollow: { ...price(priced.hollow, request.quantity), wallMm: thickness } }
71
+ : {}),
72
+ };
73
+ },
74
+ };
75
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@womp/spark-agent",
3
- "version": "11.0.0",
3
+ "version": "11.2.0",
4
4
  "description": "Portable skills-based AI agent with local and durable chat transports for Womp",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",