@womp/spark-agent 0.3.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,50 +1,169 @@
1
+ // The Kakapo-backed `SceneHost`: `@womp/scene-api` over one Kakapo engine
2
+ // session, and the ONLY optimistic-concurrency guard this package publishes.
3
+ //
4
+ // It had a sibling until this task: a `scene-editing` v1 capability over
5
+ // `KakapoRuntime.inspect()`/`.edit()`, with its own revision check that hashed
6
+ // OUTSIDE any transaction and its own receipt ladder that disagreed with this
7
+ // one. Two guards, one skill version apart, one of them tested, is the exact
8
+ // duplication this migration exists to remove -- so v1 is gone rather than
9
+ // routed through here, along with `kakapo-capability-api.ts`,
10
+ // `kakapo-scene-skill.ts` and the `KAKAPO_DECLARATIONS` the generator built from
11
+ // them. `server/standalone.ts` serves v2 through this host.
1
12
  import { z } from "zod";
2
- import { KAKAPO_DECLARATIONS } from "./generated/kakapo-declarations.js";
3
- import { KAKAPO_SCENE_INSTRUCTIONS } from "./kakapo-scene-skill.js";
13
+ import { createSceneApi, kakapoSceneRevision } from "@womp/scene-api";
14
+ import { asSceneDraft, composeKakapoSceneSeams } from "./runtime.js";
4
15
  const screenshotSchema = z.object({
5
16
  targetId: z.number().int().optional(),
6
17
  view: z.enum(["front", "back", "left", "right", "top", "bottom", "isometric"]).optional(),
7
18
  });
8
- export function createKakapoSceneCapability(runtime, writeScreenshot) {
19
+ /**
20
+ * The library-side `SceneHost`: `@womp/scene-api` over a Kakapo engine session,
21
+ * with the same three methods swan-frontend's `createBrowserSceneHost` has.
22
+ *
23
+ * WHY BOTH `read` AND `edit` RUN INSIDE A TRANSACTION. `KakapoAPI.editScene`
24
+ * calls `refreshScene()` before it hands out a draft (kakapo-sdk api.ts:197-231)
25
+ * and serializes on `transactionTail`, so entering one is what makes a revision
26
+ * mean "the engine's current scene" rather than "whatever the client last
27
+ * cached". A `read()` that skipped it would hash a stale cache and then have
28
+ * its own revision rejected by the very next `edit()`. The empty draft a read
29
+ * opens sends no patch, because `editScene` only patches when the JSON diff is
30
+ * non-empty. This is also the parity the browser host has, where `read` goes
31
+ * through the same `sceneMutations.run` queue every mutation does.
32
+ *
33
+ * WHY THE STALENESS CHECK IS INSIDE THE TRANSACTION AND NOT AT ENTRY. It is
34
+ * checked against the freshly refreshed draft, immediately before the callback's
35
+ * first write, so it compares the expectation against the document the write
36
+ * will actually land on, and a mismatch rolls the transaction back rather than
37
+ * leaving a partial edit behind. swan-frontend does the same thing through
38
+ * `sceneAccess`'s `beforeWrite` hook, and the message is its message verbatim --
39
+ * it is what the MODEL reads and reacts to.
40
+ */
41
+ export function createKakapoSceneHost(engine, options) {
42
+ const unitMultiplier = options.unitMultiplier ?? 1;
43
+ const projectId = options.projectId ?? 0;
44
+ let pending;
45
+ // Lazily, and only once: `createKakapoSceneStore` needs a `SceneEdit`, which
46
+ // only `editScene()` can hand out, and this factory is synchronous.
47
+ //
48
+ // A REJECTION IS NOT CACHED. Priming touches the network twice (`listFonts`
49
+ // and the empty `editScene`), so a transient failure there must not poison the
50
+ // host for the rest of the run -- the next call retries. The `catch` clears
51
+ // `pending` and rethrows; it never swallows.
52
+ const seamsOf = () => {
53
+ pending ??= composeKakapoSceneSeams(engine).catch((error) => {
54
+ pending = undefined;
55
+ throw error;
56
+ });
57
+ return pending;
58
+ };
59
+ const sceneApi = (seams, print = () => undefined) => createSceneApi({
60
+ store: seams.store,
61
+ transaction: seams.transaction,
62
+ // Kakapo has no library-material concept, so `pending` stays absent --
63
+ // the "backing with no queue" case `MaterialCatalog` documents.
64
+ catalog: { listSuperMaterialNames: () => [] },
65
+ print,
66
+ unitMultiplier,
67
+ // `enableCurveV3` is deliberately not an option: Kakapo has no V1/V2
68
+ // curve concept at all, so the package default of `true` is the only
69
+ // correct value here (adapters/kakapo-store.ts's O3).
70
+ });
71
+ /** `transaction.run` reports failure rather than throwing it. */
72
+ const runOrThrow = async (seams, body) => {
73
+ const failure = await seams.transaction.run(body);
74
+ if (failure !== null)
75
+ throw failure;
76
+ };
9
77
  return {
10
- skills: [
11
- {
12
- name: "scene-editing",
13
- version: "1",
14
- description: "Inspect and edit the local Kakapo scene, then capture its rendered result.",
15
- instructions: KAKAPO_SCENE_INSTRUCTIONS,
16
- declarations: KAKAPO_DECLARATIONS,
17
- examples: [
18
- "const current = await womp.scene.read(); print(current);",
19
- "const current = await womp.scene.read(); await womp.scene.edit((scene) => { const area = scene.nodeCreate(scene.NodeType.Union, 0); const part = scene.nodeCreate(scene.NodeType.Primitive, area); scene.nodeSetName(part, 'Body'); return part; }, current.revision); await emitImage(await womp.scene.screenshot({}));",
20
- ],
21
- },
22
- ],
23
- createApi: (context) => ({
24
- read: async () => {
78
+ async read(context) {
79
+ context.signal.throwIfAborted();
80
+ const seams = await seamsOf();
81
+ let snapshot;
82
+ await runOrThrow(seams, async () => {
25
83
  context.signal.throwIfAborted();
26
- const { revision, scene } = await runtime.inspect();
27
- return {
28
- revision,
29
- nodes: Object.values(scene.nodes).map(({ id, name, kind, parentId }) => ({
84
+ const api = sceneApi(seams);
85
+ snapshot = {
86
+ revision: kakapoSceneRevision(seams.scene()),
87
+ projectId,
88
+ unitMultiplier,
89
+ nodes: api.nodeList().map((id) => ({
30
90
  id,
31
- name,
32
- kind,
33
- parentId,
91
+ name: api.nodeGetName(id),
92
+ type: api.nodeGetType(id),
93
+ parentId: api.nodeGetParentId(id),
34
94
  })),
35
95
  };
36
- },
37
- edit: (callback, expectedRevision) => {
38
- if (typeof callback !== "function")
39
- throw new Error("scene.edit requires a callback.");
40
- return runtime.edit(callback, z.string().min(1).parse(expectedRevision), context);
41
- },
42
- screenshot: async (input) => {
96
+ });
97
+ if (snapshot === undefined) {
98
+ throw new Error("read(): the scene transaction resolved without producing a snapshot.");
99
+ }
100
+ return snapshot;
101
+ },
102
+ async edit(callback, expectedRevision, context) {
103
+ context.signal.throwIfAborted();
104
+ if (typeof callback !== "function")
105
+ throw new Error("scene.edit requires a callback.");
106
+ const seams = await seamsOf();
107
+ const receipt = {
108
+ id: crypto.randomUUID(),
109
+ capability: "scene",
110
+ operation: "edit",
111
+ details: { expectedRevision },
112
+ };
113
+ let entered = false;
114
+ let changed = false;
115
+ let value;
116
+ const failure = await seams.transaction.run(async () => {
43
117
  context.signal.throwIfAborted();
44
- const image = await runtime.screenshot(screenshotSchema.parse(input));
118
+ if (kakapoSceneRevision(seams.scene()) !== expectedRevision) {
119
+ throw new Error("The scene changed. Read it again before editing.");
120
+ }
121
+ entered = true;
122
+ value = await callback(asSceneDraft(sceneApi(seams)));
45
123
  context.signal.throwIfAborted();
46
- return writeScreenshot(image);
47
- },
48
- }),
124
+ changed = kakapoSceneRevision(seams.scene()) !== expectedRevision;
125
+ });
126
+ if (failure !== null) {
127
+ await context.recordReceipt({
128
+ ...receipt,
129
+ status: entered ? "unknown" : "rolled_back",
130
+ });
131
+ throw failure;
132
+ }
133
+ await context.recordReceipt({
134
+ ...receipt,
135
+ status: changed ? "committed" : "rolled_back",
136
+ });
137
+ return value;
138
+ },
139
+ async screenshot(settings, context) {
140
+ context.signal.throwIfAborted();
141
+ const input = screenshotSchema.parse(settings);
142
+ let targetId;
143
+ if (input.targetId !== undefined) {
144
+ let target = engine.getNode(input.targetId);
145
+ while (target.parentId !== null && target.parentId !== 0) {
146
+ target = engine.getNode(target.parentId);
147
+ }
148
+ targetId = target.kind === "union" || target.kind === "group" ? target.id : input.targetId;
149
+ }
150
+ const view = input.view ?? "isometric";
151
+ // Never composed into a scene transaction: a capture is a renderer read,
152
+ // and the renderer refuses one behind a dirty draft.
153
+ const image = await engine.captureScreenshot({
154
+ targetId,
155
+ view,
156
+ timeoutMs: 30_000,
157
+ });
158
+ context.signal.throwIfAborted();
159
+ return options.saveImage({
160
+ data: image.data,
161
+ mediaType: image.mediaType,
162
+ width: image.width,
163
+ height: image.height,
164
+ view,
165
+ targetId: image.targetId,
166
+ }, context);
167
+ },
49
168
  };
50
169
  }
package/dist/kakapo.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { KakapoRuntime } from "./runtime.js";
2
- export { createKakapoSceneCapability } from "./kakapo-capability.js";
3
- export type { KakapoSceneApi } from "./kakapo-capability-api.js";
4
- export { createWompSceneApi, NodeType, OperationType, PrimitiveTypeValue, } from "./womp-scene-api.js";
5
- export type { WompSceneApi, WompSceneApiContext } from "./womp-scene-api.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";
package/dist/kakapo.js CHANGED
@@ -1,3 +1,7 @@
1
1
  export { KakapoRuntime } from "./runtime.js";
2
- export { createKakapoSceneCapability } from "./kakapo-capability.js";
3
- export { createWompSceneApi, NodeType, OperationType, PrimitiveTypeValue, } from "./womp-scene-api.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";
package/dist/pricing.js CHANGED
@@ -1,23 +1,36 @@
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, read: 1, write: 12.5, output: 50, longContext: 272_000,
4
+ input: 10,
5
+ read: 1,
6
+ write: 12.5,
7
+ output: 50,
8
+ longContext: 272_000,
5
9
  source: "https://developers.openai.com/api/docs/models/gpt-6-astra",
6
10
  },
7
11
  "claude-opus-5": {
8
- input: 5, read: 0.5, write: 6.25, output: 25,
12
+ input: 5,
13
+ read: 0.5,
14
+ write: 6.25,
15
+ output: 25,
9
16
  source: "https://platform.claude.com/docs/en/models/opus-5/overview",
10
17
  },
11
18
  "claude-fable-5": {
12
- input: 10, read: 1, write: 12.5, output: 50,
19
+ input: 10,
20
+ read: 1,
21
+ write: 12.5,
22
+ output: 50,
13
23
  source: "https://platform.claude.com/docs/en/about-claude/pricing",
14
24
  },
15
25
  };
16
26
  export function calculateStepCost(modelId, usage) {
17
27
  const price = PRICES[modelId];
18
28
  const result = {
19
- modelId, pricingDate: "2026-09-09", source: price?.source,
20
- totalUsd: null, lines: [],
29
+ modelId,
30
+ pricingDate: "2026-09-09",
31
+ source: price?.source,
32
+ totalUsd: null,
33
+ lines: [],
21
34
  };
22
35
  const unavailable = (reason) => ({ ...result, reason });
23
36
  if (price === undefined)
@@ -44,9 +57,13 @@ export function calculateStepCost(modelId, usage) {
44
57
  }
45
58
  const fiveMinute = cache.ephemeral_5m_input_tokens;
46
59
  const oneHour = cache.ephemeral_1h_input_tokens;
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) {
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) {
50
67
  return unavailable("Cache write duration was not reported completely.");
51
68
  }
52
69
  hourWrite = oneHour;
@@ -55,7 +72,10 @@ export function calculateStepCost(modelId, usage) {
55
72
  const inputMultiplier = longContext ? 2 : 1;
56
73
  const outputMultiplier = longContext ? 1.5 : 1;
57
74
  const line = (label, tokens, usdPerMillion) => ({
58
- label, tokens, usdPerMillion, usd: tokens * usdPerMillion / 1_000_000,
75
+ label,
76
+ tokens,
77
+ usdPerMillion,
78
+ usd: (tokens * usdPerMillion) / 1_000_000,
59
79
  });
60
80
  result.lines = [
61
81
  line("Uncached input", uncached, price.input * inputMultiplier),
package/dist/runtime.d.ts CHANGED
@@ -1,17 +1,43 @@
1
- import { KakapoAPI, type ScreenshotView } from "@womp/kakapo-sdk";
1
+ import { KakapoAPI, type FontFamily, type Scene } from "@womp/kakapo-sdk";
2
+ import type { ScreenshotView } from "@womp/kakapo-sdk";
3
+ import type { SceneStore, SceneTransaction } from "@womp/scene-api";
4
+ import { type KakapoEngine } from "@womp/scene-api/adapters/kakapo";
2
5
  import type { JavaScriptExecutor } from "./executor.js";
3
6
  import type { ExecutionResult, ExecutionScreenshot, SparkRuntimeEventSink, SparkRuntime } from "./types.js";
4
- import { type WompSceneApi } from "./womp-scene-api.js";
5
- import type { SparkInvocationContext } from "./capabilities.js";
7
+ import type { WompSceneDraft } from "./capabilities/scene-draft.js";
8
+ /**
9
+ * The `@womp/scene-api` seams over one Kakapo engine session, built once and
10
+ * reused for every read and every transaction.
11
+ *
12
+ * WHY `editScene` IS OPENED AND IMMEDIATELY CLOSED. `createKakapoSceneStore`
13
+ * needs a `SceneEdit`, and the only way to obtain one from a Kakapo engine is
14
+ * inside `editScene()`'s callback. The handle stays usable for every later
15
+ * transaction because its closures re-read the engine's current scene at call
16
+ * time rather than capturing a document eagerly -- which is also why `scene()`
17
+ * below is a fresh read each call and not a cached snapshot. Same construction
18
+ * as `@womp/spark-agent-host`'s `KakapoSparkRuntime.connect()`.
19
+ */
20
+ export type KakapoSceneSeams = {
21
+ store: SceneStore;
22
+ transaction: SceneTransaction;
23
+ /** The engine's CURRENT scene document, for `kakapoSceneRevision`. */
24
+ scene(): Scene;
25
+ };
26
+ export declare function composeKakapoSceneSeams(engine: KakapoEngine, fonts?: FontFamily[]): Promise<KakapoSceneSeams>;
27
+ /**
28
+ * `createSceneApi` returns `Record<string, unknown>` (its `SceneScriptApi`), so
29
+ * naming it as the draft the capability declares takes one cast. It is not a
30
+ * blind one: `test/kakapo-capability.test.ts`'s "the generated skill documents
31
+ * the exact executable draft surface" asserts set equality between
32
+ * `WompSceneDraft`'s members and the functions this object actually exposes, in
33
+ * both directions, so a drift on either side fails a test rather than surfacing
34
+ * as a `TypeError` inside a model-authored script.
35
+ */
36
+ export declare function asSceneDraft(api: Record<string, unknown>): WompSceneDraft;
6
37
  export declare class KakapoRuntime implements SparkRuntime {
7
38
  readonly api: KakapoAPI;
8
- rootId: number;
9
- defaultMaterialId: number | undefined;
10
39
  private calls;
11
- private readonly materialIds;
12
- private readonly materialNames;
13
- private readonly createdIds;
14
- private fonts;
40
+ private seams;
15
41
  private readonly executor;
16
42
  private eventSink;
17
43
  constructor(url: string);
@@ -23,15 +49,8 @@ export declare class KakapoRuntime implements SparkRuntime {
23
49
  connect(): Promise<void>;
24
50
  disconnect(): void;
25
51
  private sdkCall;
26
- private sceneCall;
27
- private requireNode;
52
+ private requireSeams;
28
53
  private sceneApi;
29
- inspect(): Promise<{
30
- revision: string;
31
- scene: import("@womp/kakapo-sdk").Scene;
32
- }>;
33
- private sceneRevision;
34
- edit<T>(callback: (draft: WompSceneApi) => Promise<T> | T, expectedRevision: string, context: SparkInvocationContext): Promise<T>;
35
54
  screenshot(input: {
36
55
  targetId?: number;
37
56
  view?: ScreenshotView;