@womp/spark-agent 5.2.2 → 5.3.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 (58) hide show
  1. package/README.md +430 -423
  2. package/dist/agent-run.d.ts +1 -1
  3. package/dist/agent-tools.js +30 -12
  4. package/dist/capabilities/geometry.js +14 -14
  5. package/dist/capabilities/materials.d.ts +45 -0
  6. package/dist/capabilities/materials.js +89 -0
  7. package/dist/capabilities/openscad-instructions.js +77 -77
  8. package/dist/capabilities/operations.js +28 -28
  9. package/dist/capabilities/scene.d.ts +21 -0
  10. package/dist/capabilities/scene.js +82 -82
  11. package/dist/capabilities.d.ts +1 -0
  12. package/dist/capabilities.js +1 -0
  13. package/dist/error-diagnostics.d.ts +24 -0
  14. package/dist/error-diagnostics.js +53 -0
  15. package/dist/generated/materials-declarations.d.ts +1 -0
  16. package/dist/generated/materials-declarations.js +3 -0
  17. package/dist/geometry/schemas/backend-schema.json +3393 -3393
  18. package/dist/geometry/schemas/flowir-dialect.json +1023 -1023
  19. package/dist/geometry.js +6 -6
  20. package/dist/kakapo.d.ts +1 -0
  21. package/dist/kakapo.js +1 -0
  22. package/dist/materials/composition.d.ts +64 -0
  23. package/dist/materials/composition.js +121 -0
  24. package/dist/materials/graph.d.ts +79 -0
  25. package/dist/materials/graph.js +335 -0
  26. package/dist/materials/inspection.d.ts +40 -0
  27. package/dist/materials/inspection.js +54 -0
  28. package/dist/materials/recipes.d.ts +12 -0
  29. package/dist/materials/recipes.js +284 -0
  30. package/dist/materials/reference.d.ts +2 -0
  31. package/dist/materials/reference.js +97 -0
  32. package/dist/materials/shaping.d.ts +294 -0
  33. package/dist/materials/shaping.js +184 -0
  34. package/dist/materials/structure.d.ts +2 -0
  35. package/dist/materials/structure.js +12 -0
  36. package/dist/materials/surface-recipes.d.ts +78 -0
  37. package/dist/materials/surface-recipes.js +193 -0
  38. package/dist/materials/types.d.ts +222 -0
  39. package/dist/materials/types.js +1 -0
  40. package/dist/models.d.ts +7 -0
  41. package/dist/models.js +8 -0
  42. package/dist/pricing.js +5 -0
  43. package/dist/prompt.d.ts +1 -1
  44. package/dist/prompt.js +72 -72
  45. package/dist/scene-operations.d.ts +3 -2
  46. package/dist/scene-operations.js +19 -11
  47. package/dist/sdk-geometry-host.js +3 -1
  48. package/dist/sdk-materials-host.d.ts +9 -0
  49. package/dist/sdk-materials-host.js +360 -0
  50. package/dist/sdk-openscad-host.js +3 -1
  51. package/dist/sdk-scene-host.d.ts +6 -1
  52. package/dist/sdk-scene-host.js +19 -3
  53. package/dist/server/fixtures/materials/matte-blue.json +14 -14
  54. package/dist/server/fixtures/materials/polished-copper.json +14 -14
  55. package/dist/server/sqlite-store.js +37 -37
  56. package/dist/server/standalone.js +6 -1
  57. package/dist/ui.d.ts +50 -6
  58. package/package.json +139 -139
package/README.md CHANGED
@@ -1,423 +1,430 @@
1
- # @womp/spark-agent
2
-
3
- Portable AI agent for Womp applications and Kakapo scenes with model-authored JavaScript.
4
-
5
- Spark Agent uses AI SDK 7 `UIMessage` and `UIMessageChunk` as its public chat protocol. Generated
6
- JavaScript uses the host's executor and capabilities. Native browser execution and isolated QuickJS
7
- execution use the same model loop. The host owns conversations, artifacts, authorization, and connections.
8
-
9
- ## Requirements
10
-
11
- ### Migrating to 5.0
12
-
13
- - Replace scene capability `read`/`edit` with `access(callback)`. Inspect the current draft
14
- through `scene.nodes({ ids, name, type, parentId, offset, limit })`, not a `nodes` array.
15
- Results default to 100, with a maximum page size of 1,000.
16
- - Update custom scene hosts to `SceneHost.access` and SDK adapters to `acquireAccess`.
17
- `onCommitted` receives the acknowledged scene; keep host access suspended until synchronization succeeds.
18
- - Remove scene revision arguments from Geometry/OpenSCAD writes. Current parameters and overrides
19
- are prepared inside protected access. Hosts must still enforce connection/project ownership.
20
- - Screenshot calls without options capture the current native viewport. Explicit `camera`
21
- position/target, projection, `horizontalFovDegrees` and `orthographicWidth` are supported;
22
- remove `targetId` and `view` presets. Camera distances use current project units.
23
- - Scene health is explicitly requested through `scene.health()`, not automatically after each edit.
24
- - This release requires Kakapo SDK 0.7.0. Native and QuickJS executors now allow 100,000 host calls
25
- per execution. Receipts, cancellation, timeout limits and uncertain-outcome handling remain enforced.
26
-
27
- ### Runtime
28
-
29
- - Node.js 22.13 or newer
30
- - AI SDK 7
31
- - `@ai-sdk/react` 4 for React clients
32
-
33
- ```bash
34
- npm install @womp/spark-agent
35
- ```
36
-
37
- ## Run a prompt from the command line
38
-
39
- With the Spark server already running:
40
-
41
- ```sh
42
- yarn agent-run --prompt "Make a cube" --model gpt-5.6-luna --reasoning max
43
- ```
44
-
45
- Use `--conversation <id>` to continue a thread and `--output <new-directory>` to save
46
- `result.json`, `transcript.json` and original run artifacts under `artifacts/`.
47
- For local runs, use the git-ignored `.spark/` directory, with a fresh subdirectory per run:
48
-
49
- ```sh
50
- yarn agent-run --prompt "Make rainbow-colored boxes" --output .spark/agent-runs/rainbow-boxes
51
- yarn agent-run --prompt "Model this object using both views" --image front.png --image side.jpg --output .spark/agent-runs/reference-model
52
- ```
53
-
54
- Repeat `--image <path>` for local PNG, JPEG, WebP or GIF references, in argument order.
55
- The required prompt and all images are sent in one user message. Files, format signatures,
56
- and the full JSON request size (including base64 overhead) are checked before contacting the server.
57
- The CLI uses the server's default 25 MiB request limit; a custom server or provider may impose
58
- stricter limits. Images are never resized, and remote URLs are not accepted.
59
- With `--output`, original bytes are saved under `inputs/`; `input.json` and the result's `input`
60
- field list ordered original filenames, MIME types and relative paths. The submitted message in
61
- `transcript.json` uses those paths instead of inline data. Generated artifacts stay in `artifacts/`.
62
-
63
- Without output, artifacts remain server references. The CLI never clears the scene or
64
- takes extra screenshots. Defaults are `gpt-6-astra`, `high`, and
65
- `--api http://127.0.0.1:8787/agent`; unsupported settings are rejected.
66
-
67
- Progress goes to stderr; one JSON result goes to stdout. Use `yarn --silent agent-run`
68
- or the installed `agent-run` executable when parsing stdout (Yarn otherwise adds banners).
69
- Usage comes from the provider, with per-step USD estimates; missing usage is not estimated.
70
- Exit codes: 0 completed, 1 run/transport/export failure, 2 invalid arguments,
71
- 3 requires user action (continue in the UI), 130 interrupted. Interrupts attempt to cancel
72
- only this invocation's run; a failed cancellation is reported and the run may still be active.
73
- Output directories must not already exist. Artifact manifests include IDs, media types,
74
- server URLs and relative paths; failed downloads retain their references and report errors.
75
- Legacy inline base64 uploads in transcripts are replaced with `[inline data omitted]`.
76
-
77
- ## Package entry points
78
-
79
- - `@womp/spark-agent` — browser-safe model loop, two tools, persistence hooks, and shared contracts
80
- - `@womp/spark-agent/browser` — native JavaScript executor and local chat transport
81
- - `@womp/spark-agent/capabilities` — capability composition and skill contracts
82
- - `@womp/spark-agent/kakapo` — direct Kakapo runtime and scene capability
83
- - `@womp/spark-agent/quickjs` — optional isolated JavaScript executor
84
- - `@womp/spark-agent/ui` — browser-safe UI message types, schemas, and model catalog
85
- - `@womp/spark-agent/client` — `SparkChatTransport` and HTTP client types
86
- - `@womp/spark-agent/server` — run service, store interfaces, executor, and development stores
87
- - `@womp/spark-agent/express` — mountable Express 5 router
88
-
89
- The root, `/browser`, `/ui`, `/capabilities`, and `/client` entry points do not import QuickJS,
90
- Kakapo, Express, or React at runtime.
91
-
92
- ## Running in a host application
93
-
94
- `runSparkAgent` accepts a configured model, model messages, an executor, a capability composition,
95
- and an artifact resolver. It exposes exactly `read_skill` and `execute_javascript` to the model.
96
- Skills carry instructions, declarations, and JavaScript examples. The native executor runs in the
97
- page realm; it is not a sandbox and cannot interrupt a synchronous infinite loop.
98
-
99
- Compose only supported capabilities with `composeCapabilities({ scene, account, ... })`. Each
100
- capability supplies its skills and `createApi(context)`; the returned API is bound under `womp`.
101
- Every invocation receives a cancellation signal and an awaited `recordReceipt` hook. Capabilities
102
- own their transactions and must check cancellation at their commit boundary.
103
-
104
- For a real user interaction, call `context.waitForUser(label, async signal => ...)` outside mutation
105
- locks. The run stays active with `requires_action` progress and resumes the same invocation after
106
- input. Native and QuickJS executors exclude this wait from their execution budget; service work
107
- continues to consume time, and QuickJS guest computation still counts even if an interaction was
108
- not awaited. Abort settles the wait and late answers cannot revive it. The UI host must also reject
109
- competing requests for a shared dialog and match callbacks to the original interaction identity.
110
- Custom executors must honor the optional host-owned `userWait` argument to `execute`.
111
-
112
- Persist the user message before starting a run. Supply `persistence.beforeToolCall`,
113
- `persistence.recordReceipt`, and `persistence.afterToolCall` for awaited storage barriers.
114
- Supply `persistence.saveMessage` to save the canonical UI message at each model-step boundary and
115
- at termination, including reasoning and provider metadata. Spark awaits each checkpoint before the
116
- next model request. Consume the run's stream while awaiting its result; the result settles after
117
- the terminal checkpoint. A host run owner must keep consuming when a view detaches.
118
- A failed barrier aborts the loop. The default model-step limit is 100; a limit returns
119
- `status: "incomplete"`. A host must not automatically restart to bypass that limit.
120
- A generation that ends on any other non-`stop` reason (`length`, `content-filter`, `error`,
121
- `other`) rejects the result and ends the run `failed`: its error names the unified reason and the
122
- provider's raw one, and its diagnostics carry the unified reason as `code`.
123
-
124
- Spark does not estimate or limit input tokens or automatically shorten conversation history.
125
- The provider enforces its context limit; rejections follow the normal provider-error path.
126
-
127
- Screenshot and file APIs return serializable artifact references. `emitImage` and `emitFile` resolve
128
- them through the host's artifact resolver. Keep references resolvable when reloading history, and
129
- pass `createSparkTools(...)` to AI SDK's `convertToModelMessages` to reconstruct multimodal results.
130
- `emitImage(artifact, { inspect: false })` displays an image without adding its bytes to model input,
131
- including restored history. Inspection is enabled by default.
132
- Kakapo skill declarations are generated from its actual typed API during the build and packaged as
133
- JavaScript strings; they do not need filesystem or Markdown loading in the browser.
134
-
135
- ## Local frontend
136
-
137
- `LocalSparkChatTransport` accepts a host callback returning a `SparkAgentRun` from `runSparkAgent`.
138
- The callback receives the standard AI SDK chat request, including its messages and abort signal.
139
- It persists the initiating message, resolves the model and capabilities, and starts the shared loop.
140
- Keep ownership of the active run outside the React renderer. Local browser runs end when the page
141
- closes; `reconnectToStream` returns `null`.
142
-
143
- ## Remote frontend
144
-
145
- ```tsx
146
- import { useChat } from "@ai-sdk/react";
147
- import { SparkChatTransport } from "@womp/spark-agent/client";
148
- import {
149
- sparkDataPartSchemas,
150
- sparkMessageMetadataSchema,
151
- type SparkUIMessage,
152
- } from "@womp/spark-agent/ui";
153
-
154
- const transport = new SparkChatTransport({ api: "/agent" });
155
-
156
- const chat = useChat<SparkUIMessage>({
157
- id: conversationId,
158
- messages: initialMessages,
159
- transport,
160
- resume: true,
161
- messageMetadataSchema: sparkMessageMetadataSchema,
162
- dataPartSchemas: sparkDataPartSchemas,
163
- });
164
- ```
165
-
166
- Render `message.parts`. Standard AI SDK parts represent text, reasoning, files, tool inputs, tool
167
- outputs, approvals, and step boundaries. Spark adds typed `data-console`, `data-artifact`,
168
- `data-run-status`, `data-step-metrics`, and `data-execution-receipt` parts. Receipts are emitted before
169
- their storage barrier, keeping known effects visible even when saving the tool result fails.
170
- Hosts can consume `data-tool-input-label` once the tool's label field is complete, while the
171
- remaining input is still streaming.
172
-
173
- An explicit Stop action must cancel the durable run before stopping local observation:
174
-
175
- ```ts
176
- await transport.cancelRun(conversationId);
177
- await chat.stop();
178
- ```
179
-
180
- Closing or reloading the page only detaches the SSE subscriber. It does not cancel the run.
181
-
182
- ## HTTP and SSE
183
-
184
- `SparkChatTransport` hides the durable run lifecycle from `useChat`:
185
-
186
- ```text
187
- POST /agent/conversations/:conversationId/messages
188
- PATCH /agent/conversations/:conversationId/settings
189
- GET /agent/runs/:runId/stream?after=0
190
- POST /agent/runs/:runId/cancel
191
- ```
192
-
193
- Conversation settings contain `modelId` and `reasoningEffort`. The standalone UI saves selector
194
- changes immediately through `transport.saveConversationSettings(id, settings)` and restores them
195
- per thread. Older threads fall back to their last recorded model (or the default) and medium effort;
196
- unsupported choices fall back to supported settings. Assistant footers show the model recorded on
197
- that turn, independently of the selector.
198
-
199
- Custom stores must implement `saveConversationSettings` as a settings-only update, and preserve
200
- stored settings during `saveConversation` so streaming history saves cannot overwrite preferences.
201
- The built-in memory and SQLite stores implement this contract.
202
-
203
- The SSE response contains ordered persistence envelopes around standard AI SDK chunks:
204
-
205
- ```ts
206
- type StoredSparkChunk = {
207
- sequence: number;
208
- conversationId: string;
209
- runId: string;
210
- createdAt: string;
211
- chunk: SparkUIMessageChunk;
212
- };
213
- ```
214
-
215
- The transport unwraps each envelope and returns the contained `UIMessageChunk` to `useChat`.
216
- Active assistant messages are replayed from sequence zero when reconnecting because `useChat`
217
- reconstructs the in-progress message from the resumed stream.
218
-
219
- ## Embedding in an Express backend
220
-
221
- Spark does not call `listen()` when imported. The host owns its HTTP server and mounts the router:
222
-
223
- ```ts
224
- import { createSparkAgentRouter } from "@womp/spark-agent/express";
225
- import { SparkAgentService, createSparkRunExecutor } from "@womp/spark-agent/server";
226
-
227
- const service = new SparkAgentService({
228
- store,
229
- executeRun: createSparkRunExecutor({
230
- resolveModel,
231
- createHost,
232
- }),
233
- });
234
-
235
- app.use(
236
- "/agent",
237
- userAccess,
238
- createSparkAgentRouter({
239
- service,
240
- artifactStore,
241
- resolveOwnerId: (request) => request.user.id,
242
- }),
243
- );
244
- ```
245
-
246
- `MemorySparkAgentStore` and `MemorySparkArtifactStore` are development implementations. Production
247
- hosts must supply durable implementations backed by their database/object storage and must preserve
248
- the ordering contract of `appendRunChunk()`.
249
-
250
- `SparkAgentServiceOptions.endOrphanedRuns` defaults to `false`. Enable it only when one process
251
- owns the store: a message or Stop then ends unfinished runs not held by that process. On a shared
252
- store, enabling it could end another process's live run.
253
-
254
- Custom stores can implement `releaseActiveRun(conversationId, runId, updatedAt)` to clear the active
255
- run only if its ID still matches. Memory and SQLite stores implement it. Without it, the service
256
- serializes read-and-save release against its own submissions.
257
-
258
- ## Standalone development server
259
-
260
- The package includes a local server bound to `127.0.0.1:8787`:
261
-
262
- ```bash
263
- spark-agent
264
- ```
265
-
266
- Configure the process with:
267
-
268
- - `OPENAI_API_KEY`
269
- - `ANTHROPIC_API_KEY`
270
- - `GEMINI_API_KEY`
271
- - `KAKAPO_URL` (defaults to `ws://127.0.0.1:5502`)
272
- - `PORT` (defaults to `8787`)
273
- - `SPARK_STORAGE_PATH` (defaults to `.spark/spark.sqlite`)
274
- - `SPARK_SCENE_IDENTITY` (optional stable identity for the scene behind `KAKAPO_URL`)
275
-
276
- The CLI automatically loads `.env` from its working directory when the file exists. Copy
277
- `.env.example` to `.env`, then add the provider key you intend to use. Existing process environment
278
- variables take precedence over values loaded from the file.
279
-
280
- For repository development, `yarn dev` starts the Express server and Vite demo together. Open
281
- `http://127.0.0.1:5173`.
282
-
283
- Standalone scene edits use the existing `scene_state_patch` command followed by `save_scene` after
284
- the patch is acknowledged. The durable operation journal records the separate mutation and save
285
- outcomes. A failed or unknown save stops that operation with an explicit error, retaining any
286
- applied work without replay. The two commands are not an atomic transaction, and a renderer save
287
- acknowledgement proves only renderer-local history, not durable backend storage.
288
-
289
- The standalone server persists conversations, run streams, and screenshot bytes in SQLite. Only
290
- one local process can execute against a database. After a terminated process is replaced, startup
291
- preserves recorded output and marks abandoned queued/running runs incomplete without replaying
292
- scene edits. Pending approvals remain pending; startup does not resume abandoned runs.
293
- Node 22 reports an experimental warning for its built-in SQLite module.
294
-
295
- Set `SPARK_SCENE_IDENTITY` only when the host can verify that the value names the same durable
296
- scene across renderer reconnects. Without it, Spark uses a process-scoped identity and does not
297
- authorize interrupted scene mutations to continue after a server restart.
298
-
299
- `createStandaloneSparkAgentApp(options)` is asynchronous. Await it before listening, and call
300
- `await app.dispose()` on shutdown to settle active runs and release storage ownership.
301
-
302
- When using a sibling `kakapo-sdk` dependency, run `yarn build` in `../kakapo-sdk` before installing
303
- Spark dependencies. Replace local dependencies with registry versions before publishing.
304
-
305
- For the explicit fictional account profile, use `yarn dev:demo-account` or
306
- `spark-agent --profile demo-account`. It adds the `account` skill and `womp.account.read`
307
- beside the real local Kakapo scene API. Profile reads identify themselves as fictional fixtures;
308
- credits, billing, orders, and other account services report unavailable. The default composition
309
- omits account entirely. Neither profile supplies fake generation jobs, imports, or billing permission.
310
- Embedded development servers can select `developmentProfile: "demo-account"` explicitly.
311
-
312
- The same profile supplies two actual local material resources: `Development: Matte Blue` and
313
- `Development: Polished Copper`. They are bundled JSON files under `src/server/fixtures/materials`
314
- and imported through the normal SDK draft, not simulated scene effects. In `scene.edit`, await
315
- `api.materialImport(name)`, then assign its numeric ID. The default profile has no library service.
316
-
317
- ## Run cost estimates
318
-
319
- Prompt caching is enabled for every listed model: Claude Opus 5 and Fable 5 use
320
- automatic 5-minute caching, and GPT-6 Astra uses implicit caching with a 30-minute TTL.
321
- The providers manage the cache as message history grows across tool steps; no local
322
- response cache is used. Cache hits require matching prefixes, sufficient prompt length,
323
- and an unexpired entry. Cache writes can cost more than uncached input, while subsequent
324
- cache reads are cheaper. The UI displays actual reported reads/writes, not assumed savings.
325
- See [Claude caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching)
326
- and [OpenAI caching](https://developers.openai.com/api/docs/guides/prompt-caching).
327
- Restart the server after changing these settings; existing runs keep their original configuration.
328
-
329
- The chat displays estimated API token cost in USD, updated after every completed model step.
330
- Hover or focus the amount to inspect uncached input, cache reads/writes, and output costs. Output usage
331
- already includes reasoning tokens. Image input is included in the provider's input token count.
332
-
333
- `src/pricing.ts` contains standard direct API rates verified on September 9, 2026:
334
-
335
- | Model | Input / 1M | Cache read / 1M | Cache write / 1M | Output / 1M |
336
- | -------------- | ---------- | --------------- | --------------------- | ----------- |
337
- | GPT-6 Astra | $10 | $1 | $12.50 | $50 |
338
- | Claude Opus 5 | $5 | $0.50 | $6.25 (5m), $10 (1h) | $25 |
339
- | Claude Fable 5 | $10 | $1 | $12.50 (5m), $20 (1h) | $50 |
340
-
341
- Astra requests above 272,000 input tokens use 2x input/cache rates and 1.5x output rates.
342
- This threshold is applied to each request before summing run costs. Claude's full context uses
343
- standard rates. Sources: [Astra pricing](https://developers.openai.com/api/docs/models/gpt-6-astra),
344
- [Claude pricing](https://platform.claude.com/docs/en/about-claude/pricing).
345
-
346
- Each `data-step-metrics` part stores a `cost` snapshot with the model, rate date, source, token
347
- categories, rates, and amounts. The UI sums those stored amounts, so reconnection does not double
348
- count steps and future price changes do not reprice recorded runs. Update the rate table and its
349
- verification date when provider pricing changes.
350
-
351
- The unfinished step is excluded until its usage arrives. Cancelled/failed runs show a partial
352
- estimate. Missing usage, unknown models, missing cache TTLs, or provider sub-inferences without
353
- separate attribution are marked unavailable, never silently priced as zero. Historical runs
354
- without step pricing remain unavailable. Estimates exclude taxes, negotiated discounts, and scene
355
- hosting; the provider bill is authoritative. Spark requests OpenAI's standard service tier.
356
-
357
- ## Execution security
358
-
359
- The standalone host uses a fresh QuickJS runtime for each JavaScript execution. It has no Node.js
360
- or browser globals and receives only the composed capability APIs. Imports, filesystem access,
361
- network APIs, and host environment variables are not exposed. QuickJS limits memory, stack size,
362
- execution time, source size, host calls, and data crossing the host bridge. Browser hosts can instead
363
- choose native page execution, with the page-global access and interruption limitations described above.
364
- Both executors allow 100,000 host calls per execution by default; the counter resets for each
365
- execution. QuickJS supports overriding this through `maxHostCalls`. Cancellation, timeouts,
366
- and the other execution limits still apply.
367
-
368
- QuickJS isolates generated code from the JavaScript host API; it is not an operating-system security
369
- boundary. Multi-tenant deployments must additionally isolate workers, authorize every Kakapo
370
- session and tool call, enforce quotas, and avoid passing privileged functions through the runtime
371
- bridge.
372
-
373
- ## Validation
374
-
375
- ```bash
376
- yarn build
377
- yarn typecheck
378
- yarn test
379
- yarn web:build
380
- ```
381
-
382
- ## Release procedure
383
-
384
- Releases use a manual package publication; no separate release service is required.
385
-
386
- Versions follow **MAJOR.MINOR.PATCH** (for example, `4.4.0`):
387
-
388
- - **Major:** breaking changes.
389
- - **Minor:** backward-compatible new features.
390
- - **Patch:** backward-compatible bug fixes.
391
-
392
- ### Publishing
393
-
394
- 1. Choose an unused package version after checking `npm view @womp/spark-agent versions --json`.
395
- Update `package.json` and record public API changes and migration notes. Use a new minor version
396
- for incompatible changes while the package is below 1.0.
397
- 2. On a supported Node version, run `yarn install --frozen-lockfile`, `yarn typecheck`, `yarn test`,
398
- and `yarn web:build`. Do not bypass dependency engine checks. Commit the release changes and
399
- record the commit used to build the package.
400
- 3. Run `yarn pack --filename spark-agent-release.tgz`. Inspect the archive contents and install
401
- that archive in the consuming application. Verify packaged declarations and skills, browser
402
- import boundaries, the production build, and the applicable integration cases without source
403
- aliases. Keep the archive outside Git and do not rebuild or change it after verification.
404
- 4. Publish the verified archive with `npm publish ./spark-agent-release.tgz --access public`.
405
- If the response is uncertain, inspect the registry's version and integrity before retrying.
406
- Verify the published version and archive integrity, then tag the recorded commit as `v<version>`
407
- and push the release commit and tag. An already published version cannot be replaced; corrections
408
- need a new version.
409
- 5. In the consuming application, use `yarn add @womp/spark-agent@<version> --exact`. Commit its
410
- manifest and lockfile together, and verify a clean frozen-lockfile installation and production
411
- build. Remove the temporary archive dependency. Application deployment and merge requirements
412
- remain separate from package publication.
413
-
414
- ## Layout
415
-
416
- - `src/agent.ts` — AI SDK stream and Spark tool orchestration
417
- - `src/ui.ts` — browser-safe protocol types and validation schemas
418
- - `src/client.ts` — durable `ChatTransport` implementation
419
- - `src/server/` — service, storage contracts, Express adapter, artifacts, and standalone composition
420
- - `src/runtime.ts` — Kakapo scene connections and edit transactions
421
- - `src/quickjs-executor.ts` — isolated JavaScript execution and host bridge
422
- - `src/womp-scene-api.ts` — Womp-compatible Kakapo scene API
423
- - `web/src/App.tsx` — reference `useChat<SparkUIMessage>` application
1
+ # @womp/spark-agent
2
+
3
+ Portable AI agent for Womp applications and Kakapo scenes with model-authored JavaScript.
4
+
5
+ Spark Agent uses AI SDK 7 `UIMessage` and `UIMessageChunk` as its public chat protocol. Generated
6
+ JavaScript uses the host's executor and capabilities. Native browser execution and isolated QuickJS
7
+ execution use the same model loop. The host owns conversations, artifacts, authorization, and connections.
8
+
9
+ ## Requirements
10
+
11
+ ### Migrating to 5.0
12
+
13
+ - Replace scene capability `read`/`edit` with `access(callback)`. Inspect the current draft
14
+ through `scene.nodes({ ids, name, type, parentId, offset, limit })`, not a `nodes` array.
15
+ Results default to 100, with a maximum page size of 1,000.
16
+ - Update custom scene hosts to `SceneHost.access` and SDK adapters to `acquireAccess`.
17
+ `onCommitted` receives the acknowledged scene; keep host access suspended until synchronization succeeds.
18
+ - Remove scene revision arguments from Geometry/OpenSCAD writes. Current parameters and overrides
19
+ are prepared inside protected access. Hosts must still enforce connection/project ownership.
20
+ - Screenshot calls without options capture the current native viewport. Explicit `camera`
21
+ position/target, projection, `horizontalFovDegrees` and `orthographicWidth` are supported;
22
+ remove `targetId` and `view` presets. Camera distances use current project units.
23
+ - Scene health is explicitly requested through `scene.health()`, not automatically after each edit.
24
+ - This release requires Kakapo SDK 0.7.0. Native and QuickJS executors now allow 100,000 host calls
25
+ per execution. Receipts, cancellation, timeout limits and uncertain-outcome handling remain enforced.
26
+
27
+ ### Runtime
28
+
29
+ - Node.js 22.13 or newer
30
+ - AI SDK 7
31
+ - `@ai-sdk/react` 4 for React clients
32
+
33
+ ```bash
34
+ npm install @womp/spark-agent
35
+ ```
36
+
37
+ ## Run a prompt from the command line
38
+
39
+ With the Spark server already running:
40
+
41
+ ```sh
42
+ yarn agent-run --prompt "Make a cube" --model gpt-5.6-luna --reasoning max
43
+ ```
44
+
45
+ Use `--conversation <id>` to continue a thread and `--output <new-directory>` to save
46
+ `result.json`, `transcript.json` and original run artifacts under `artifacts/`.
47
+ For local runs, use the git-ignored `.spark/` directory, with a fresh subdirectory per run:
48
+
49
+ ```sh
50
+ yarn agent-run --prompt "Make rainbow-colored boxes" --output .spark/agent-runs/rainbow-boxes
51
+ yarn agent-run --prompt "Model this object using both views" --image front.png --image side.jpg --output .spark/agent-runs/reference-model
52
+ ```
53
+
54
+ Repeat `--image <path>` for local PNG, JPEG, WebP or GIF references, in argument order.
55
+ The required prompt and all images are sent in one user message. Files, format signatures,
56
+ and the full JSON request size (including base64 overhead) are checked before contacting the server.
57
+ The CLI uses the server's default 25 MiB request limit; a custom server or provider may impose
58
+ stricter limits. Images are never resized, and remote URLs are not accepted.
59
+ With `--output`, original bytes are saved under `inputs/`; `input.json` and the result's `input`
60
+ field list ordered original filenames, MIME types and relative paths. The submitted message in
61
+ `transcript.json` uses those paths instead of inline data. Generated artifacts stay in `artifacts/`.
62
+
63
+ Without output, artifacts remain server references. The CLI never clears the scene or
64
+ takes extra screenshots. Defaults are `gpt-6-astra`, `high`, and
65
+ `--api http://127.0.0.1:8787/agent`; unsupported settings are rejected.
66
+
67
+ Progress goes to stderr; one JSON result goes to stdout. Use `yarn --silent agent-run`
68
+ or the installed `agent-run` executable when parsing stdout (Yarn otherwise adds banners).
69
+ Usage comes from the provider, with per-step USD estimates; missing usage is not estimated.
70
+ Exit codes: 0 completed, 1 run/transport/export failure, 2 invalid arguments,
71
+ 3 requires user action (continue in the UI), 130 interrupted. Interrupts attempt to cancel
72
+ only this invocation's run; a failed cancellation is reported and the run may still be active.
73
+ Output directories must not already exist. Artifact manifests include IDs, media types,
74
+ server URLs and relative paths; failed downloads retain their references and report errors.
75
+ Legacy inline base64 uploads in transcripts are replaced with `[inline data omitted]`.
76
+
77
+ ## Package entry points
78
+
79
+ - `@womp/spark-agent` — browser-safe model loop, two tools, persistence hooks, and shared contracts
80
+ - `@womp/spark-agent/browser` — native JavaScript executor and local chat transport
81
+ - `@womp/spark-agent/capabilities` — capability composition and skill contracts
82
+ - `@womp/spark-agent/kakapo` — direct Kakapo runtime and scene capability
83
+ - `@womp/spark-agent/quickjs` — optional isolated JavaScript executor
84
+ - `@womp/spark-agent/ui` — browser-safe UI message types, schemas, and model catalog
85
+ - `@womp/spark-agent/client` — `SparkChatTransport` and HTTP client types
86
+ - `@womp/spark-agent/server` — run service, store interfaces, executor, and development stores
87
+ - `@womp/spark-agent/express` — mountable Express 5 router
88
+
89
+ The root, `/browser`, `/ui`, `/capabilities`, and `/client` entry points do not import QuickJS,
90
+ Kakapo, Express, or React at runtime.
91
+
92
+ ## Running in a host application
93
+
94
+ `runSparkAgent` accepts a configured model, model messages, an executor, a capability composition,
95
+ and an artifact resolver. It exposes exactly `read_skill` and `execute_javascript` to the model.
96
+ Skills carry instructions, declarations, and JavaScript examples. The native executor runs in the
97
+ page realm; it is not a sandbox and cannot interrupt a synchronous infinite loop.
98
+
99
+ Compose only supported capabilities with `composeCapabilities({ scene, account, ... })`. Each
100
+ capability supplies its skills and `createApi(context)`; the returned API is bound under `womp`.
101
+ Every invocation receives a cancellation signal and an awaited `recordReceipt` hook. Capabilities
102
+ own their transactions and must check cancellation at their commit boundary.
103
+
104
+ For a real user interaction, call `context.waitForUser(label, async signal => ...)` outside mutation
105
+ locks. The run stays active with `requires_action` progress and resumes the same invocation after
106
+ input. Native and QuickJS executors exclude this wait from their execution budget; service work
107
+ continues to consume time, and QuickJS guest computation still counts even if an interaction was
108
+ not awaited. Abort settles the wait and late answers cannot revive it. The UI host must also reject
109
+ competing requests for a shared dialog and match callbacks to the original interaction identity.
110
+ Custom executors must honor the optional host-owned `userWait` argument to `execute`.
111
+
112
+ Persist the user message before starting a run. Supply `persistence.beforeToolCall`,
113
+ `persistence.recordReceipt`, and `persistence.afterToolCall` for awaited storage barriers.
114
+ Supply `persistence.saveMessage` to save the canonical UI message at each model-step boundary and
115
+ at termination, including reasoning and provider metadata. Spark awaits each checkpoint before the
116
+ next model request. Consume the run's stream while awaiting its result; the result settles after
117
+ the terminal checkpoint. A host run owner must keep consuming when a view detaches.
118
+ A failed barrier aborts the loop. The default model-step limit is 100; a limit returns
119
+ `status: "incomplete"`. A host must not automatically restart to bypass that limit.
120
+ A generation that ends on any other non-`stop` reason (`length`, `content-filter`, `error`,
121
+ `other`) rejects the result and ends the run `failed`: its error names the unified reason and the
122
+ provider's raw one, and its diagnostics carry the unified reason as `code`.
123
+
124
+ Spark does not estimate or limit input tokens or automatically shorten conversation history.
125
+ The provider enforces its context limit; rejections follow the normal provider-error path.
126
+
127
+ Screenshot and file APIs return serializable artifact references. `emitImage` and `emitFile` resolve
128
+ them through the host's artifact resolver. Keep references resolvable when reloading history, and
129
+ pass `createSparkTools(...)` to AI SDK's `convertToModelMessages` to reconstruct multimodal results.
130
+ `emitImage(artifact, { inspect: false })` displays an image without adding its bytes to model input,
131
+ including restored history. Inspection is enabled by default.
132
+ Kakapo skill declarations are generated from its actual typed API during the build and packaged as
133
+ JavaScript strings; they do not need filesystem or Markdown loading in the browser.
134
+
135
+ ## Local frontend
136
+
137
+ `LocalSparkChatTransport` accepts a host callback returning a `SparkAgentRun` from `runSparkAgent`.
138
+ The callback receives the standard AI SDK chat request, including its messages and abort signal.
139
+ It persists the initiating message, resolves the model and capabilities, and starts the shared loop.
140
+ Keep ownership of the active run outside the React renderer. Local browser runs end when the page
141
+ closes; `reconnectToStream` returns `null`.
142
+
143
+ ## Remote frontend
144
+
145
+ ```tsx
146
+ import { useChat } from "@ai-sdk/react";
147
+ import { SparkChatTransport } from "@womp/spark-agent/client";
148
+ import {
149
+ sparkDataPartSchemas,
150
+ sparkMessageMetadataSchema,
151
+ type SparkUIMessage,
152
+ } from "@womp/spark-agent/ui";
153
+
154
+ const transport = new SparkChatTransport({ api: "/agent" });
155
+
156
+ const chat = useChat<SparkUIMessage>({
157
+ id: conversationId,
158
+ messages: initialMessages,
159
+ transport,
160
+ resume: true,
161
+ messageMetadataSchema: sparkMessageMetadataSchema,
162
+ dataPartSchemas: sparkDataPartSchemas,
163
+ });
164
+ ```
165
+
166
+ Render `message.parts`. Standard AI SDK parts represent text, reasoning, files, tool inputs, tool
167
+ outputs, approvals, and step boundaries. Spark adds typed `data-console`, `data-artifact`,
168
+ `data-run-status`, `data-step-metrics`, and `data-execution-receipt` parts. Receipts are emitted before
169
+ their storage barrier, keeping known effects visible even when saving the tool result fails.
170
+ Hosts can consume `data-tool-input-label` once the tool's label field is complete, while the
171
+ remaining input is still streaming.
172
+
173
+ An explicit Stop action must cancel the durable run before stopping local observation:
174
+
175
+ ```ts
176
+ await transport.cancelRun(conversationId);
177
+ await chat.stop();
178
+ ```
179
+
180
+ Closing or reloading the page only detaches the SSE subscriber. It does not cancel the run.
181
+
182
+ ## HTTP and SSE
183
+
184
+ `SparkChatTransport` hides the durable run lifecycle from `useChat`:
185
+
186
+ ```text
187
+ POST /agent/conversations/:conversationId/messages
188
+ PATCH /agent/conversations/:conversationId/settings
189
+ GET /agent/runs/:runId/stream?after=0
190
+ POST /agent/runs/:runId/cancel
191
+ ```
192
+
193
+ Conversation settings contain `modelId` and `reasoningEffort`. The standalone UI saves selector
194
+ changes immediately through `transport.saveConversationSettings(id, settings)` and restores them
195
+ per thread. Older threads fall back to their last recorded model (or the default) and medium effort;
196
+ unsupported choices fall back to supported settings. Assistant footers show the model recorded on
197
+ that turn, independently of the selector.
198
+
199
+ Custom stores must implement `saveConversationSettings` as a settings-only update, and preserve
200
+ stored settings during `saveConversation` so streaming history saves cannot overwrite preferences.
201
+ The built-in memory and SQLite stores implement this contract.
202
+
203
+ The SSE response contains ordered persistence envelopes around standard AI SDK chunks:
204
+
205
+ ```ts
206
+ type StoredSparkChunk = {
207
+ sequence: number;
208
+ conversationId: string;
209
+ runId: string;
210
+ createdAt: string;
211
+ chunk: SparkUIMessageChunk;
212
+ };
213
+ ```
214
+
215
+ The transport unwraps each envelope and returns the contained `UIMessageChunk` to `useChat`.
216
+ Active assistant messages are replayed from sequence zero when reconnecting because `useChat`
217
+ reconstructs the in-progress message from the resumed stream.
218
+
219
+ ## Embedding in an Express backend
220
+
221
+ Spark does not call `listen()` when imported. The host owns its HTTP server and mounts the router:
222
+
223
+ ```ts
224
+ import { createSparkAgentRouter } from "@womp/spark-agent/express";
225
+ import { SparkAgentService, createSparkRunExecutor } from "@womp/spark-agent/server";
226
+
227
+ const service = new SparkAgentService({
228
+ store,
229
+ executeRun: createSparkRunExecutor({
230
+ resolveModel,
231
+ createHost,
232
+ }),
233
+ });
234
+
235
+ app.use(
236
+ "/agent",
237
+ userAccess,
238
+ createSparkAgentRouter({
239
+ service,
240
+ artifactStore,
241
+ resolveOwnerId: (request) => request.user.id,
242
+ }),
243
+ );
244
+ ```
245
+
246
+ `MemorySparkAgentStore` and `MemorySparkArtifactStore` are development implementations. Production
247
+ hosts must supply durable implementations backed by their database/object storage and must preserve
248
+ the ordering contract of `appendRunChunk()`.
249
+
250
+ `SparkAgentServiceOptions.endOrphanedRuns` defaults to `false`. Enable it only when one process
251
+ owns the store: a message or Stop then ends unfinished runs not held by that process. On a shared
252
+ store, enabling it could end another process's live run.
253
+
254
+ Custom stores can implement `releaseActiveRun(conversationId, runId, updatedAt)` to clear the active
255
+ run only if its ID still matches. Memory and SQLite stores implement it. Without it, the service
256
+ serializes read-and-save release against its own submissions.
257
+
258
+ ## Standalone development server
259
+
260
+ The package includes a local server bound to `127.0.0.1:8787`:
261
+
262
+ ```bash
263
+ spark-agent
264
+ ```
265
+
266
+ Configure the process with:
267
+
268
+ - `OPENAI_API_KEY`
269
+ - `ANTHROPIC_API_KEY`
270
+ - `GEMINI_API_KEY`
271
+ - `KAKAPO_URL` (defaults to `ws://127.0.0.1:5502`)
272
+ - `PORT` (defaults to `8787`)
273
+ - `SPARK_STORAGE_PATH` (defaults to `.spark/spark.sqlite`)
274
+ - `SPARK_SCENE_IDENTITY` (optional stable identity for the scene behind `KAKAPO_URL`)
275
+
276
+ The CLI automatically loads `.env` from its working directory when the file exists. Copy
277
+ `.env.example` to `.env`, then add the provider key you intend to use. Existing process environment
278
+ variables take precedence over values loaded from the file.
279
+
280
+ For repository development, `yarn dev` starts the Express server and Vite demo together. Open
281
+ `http://127.0.0.1:5173`.
282
+
283
+ Shared SDK scene adapters can omit `operations` to use direct edit/save with
284
+ per-invocation outcomes and conversation receipts. This path does not persist a scene
285
+ journal, recover uncertain edits, or reuse previous operation results. Validation,
286
+ settlement, and the host's save policy still apply; geometry/OpenSCAD refund repair
287
+ attempts only after confirmed rollback. Hosts that supply `operations` retain their
288
+ existing journal and recovery behavior.
289
+
290
+ Standalone scene edits use the existing `scene_state_patch` command followed by `save_scene` after
291
+ the patch is acknowledged. The durable operation journal records the separate mutation and save
292
+ outcomes. A failed or unknown save stops that operation with an explicit error, retaining any
293
+ applied work without replay. The two commands are not an atomic transaction, and a renderer save
294
+ acknowledgement proves only renderer-local history, not durable backend storage.
295
+
296
+ The standalone server persists conversations, run streams, and screenshot bytes in SQLite. Only
297
+ one local process can execute against a database. After a terminated process is replaced, startup
298
+ preserves recorded output and marks abandoned queued/running runs incomplete without replaying
299
+ scene edits. Pending approvals remain pending; startup does not resume abandoned runs.
300
+ Node 22 reports an experimental warning for its built-in SQLite module.
301
+
302
+ Set `SPARK_SCENE_IDENTITY` only when the host can verify that the value names the same durable
303
+ scene across renderer reconnects. Without it, Spark uses a process-scoped identity and does not
304
+ authorize interrupted scene mutations to continue after a server restart.
305
+
306
+ `createStandaloneSparkAgentApp(options)` is asynchronous. Await it before listening, and call
307
+ `await app.dispose()` on shutdown to settle active runs and release storage ownership.
308
+
309
+ When using a sibling `kakapo-sdk` dependency, run `yarn build` in `../kakapo-sdk` before installing
310
+ Spark dependencies. Replace local dependencies with registry versions before publishing.
311
+
312
+ For the explicit fictional account profile, use `yarn dev:demo-account` or
313
+ `spark-agent --profile demo-account`. It adds the `account` skill and `womp.account.read`
314
+ beside the real local Kakapo scene API. Profile reads identify themselves as fictional fixtures;
315
+ credits, billing, orders, and other account services report unavailable. The default composition
316
+ omits account entirely. Neither profile supplies fake generation jobs, imports, or billing permission.
317
+ Embedded development servers can select `developmentProfile: "demo-account"` explicitly.
318
+
319
+ The same profile supplies two actual local material resources: `Development: Matte Blue` and
320
+ `Development: Polished Copper`. They are bundled JSON files under `src/server/fixtures/materials`
321
+ and imported through the normal SDK draft, not simulated scene effects. In `scene.edit`, await
322
+ `api.materialImport(name)`, then assign its numeric ID. The default profile has no library service.
323
+
324
+ ## Run cost estimates
325
+
326
+ Prompt caching is enabled for every listed model: Claude Opus 5 and Fable 5 use
327
+ automatic 5-minute caching, and GPT-6 Astra uses implicit caching with a 30-minute TTL.
328
+ The providers manage the cache as message history grows across tool steps; no local
329
+ response cache is used. Cache hits require matching prefixes, sufficient prompt length,
330
+ and an unexpired entry. Cache writes can cost more than uncached input, while subsequent
331
+ cache reads are cheaper. The UI displays actual reported reads/writes, not assumed savings.
332
+ See [Claude caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching)
333
+ and [OpenAI caching](https://developers.openai.com/api/docs/guides/prompt-caching).
334
+ Restart the server after changing these settings; existing runs keep their original configuration.
335
+
336
+ The chat displays estimated API token cost in USD, updated after every completed model step.
337
+ Hover or focus the amount to inspect uncached input, cache reads/writes, and output costs. Output usage
338
+ already includes reasoning tokens. Image input is included in the provider's input token count.
339
+
340
+ `src/pricing.ts` contains standard direct API rates verified on September 9, 2026:
341
+
342
+ | Model | Input / 1M | Cache read / 1M | Cache write / 1M | Output / 1M |
343
+ | -------------- | ---------- | --------------- | --------------------- | ----------- |
344
+ | GPT-6 Astra | $10 | $1 | $12.50 | $50 |
345
+ | Claude Opus 5 | $5 | $0.50 | $6.25 (5m), $10 (1h) | $25 |
346
+ | Claude Fable 5 | $10 | $1 | $12.50 (5m), $20 (1h) | $50 |
347
+
348
+ Astra requests above 272,000 input tokens use 2x input/cache rates and 1.5x output rates.
349
+ This threshold is applied to each request before summing run costs. Claude's full context uses
350
+ standard rates. Sources: [Astra pricing](https://developers.openai.com/api/docs/models/gpt-6-astra),
351
+ [Claude pricing](https://platform.claude.com/docs/en/about-claude/pricing).
352
+
353
+ Each `data-step-metrics` part stores a `cost` snapshot with the model, rate date, source, token
354
+ categories, rates, and amounts. The UI sums those stored amounts, so reconnection does not double
355
+ count steps and future price changes do not reprice recorded runs. Update the rate table and its
356
+ verification date when provider pricing changes.
357
+
358
+ The unfinished step is excluded until its usage arrives. Cancelled/failed runs show a partial
359
+ estimate. Missing usage, unknown models, missing cache TTLs, or provider sub-inferences without
360
+ separate attribution are marked unavailable, never silently priced as zero. Historical runs
361
+ without step pricing remain unavailable. Estimates exclude taxes, negotiated discounts, and scene
362
+ hosting; the provider bill is authoritative. Spark requests OpenAI's standard service tier.
363
+
364
+ ## Execution security
365
+
366
+ The standalone host uses a fresh QuickJS runtime for each JavaScript execution. It has no Node.js
367
+ or browser globals and receives only the composed capability APIs. Imports, filesystem access,
368
+ network APIs, and host environment variables are not exposed. QuickJS limits memory, stack size,
369
+ execution time, source size, host calls, and data crossing the host bridge. Browser hosts can instead
370
+ choose native page execution, with the page-global access and interruption limitations described above.
371
+ Both executors allow 100,000 host calls per execution by default; the counter resets for each
372
+ execution. QuickJS supports overriding this through `maxHostCalls`. Cancellation, timeouts,
373
+ and the other execution limits still apply.
374
+
375
+ QuickJS isolates generated code from the JavaScript host API; it is not an operating-system security
376
+ boundary. Multi-tenant deployments must additionally isolate workers, authorize every Kakapo
377
+ session and tool call, enforce quotas, and avoid passing privileged functions through the runtime
378
+ bridge.
379
+
380
+ ## Validation
381
+
382
+ ```bash
383
+ yarn build
384
+ yarn typecheck
385
+ yarn test
386
+ yarn web:build
387
+ ```
388
+
389
+ ## Release procedure
390
+
391
+ Releases use a manual package publication; no separate release service is required.
392
+
393
+ Versions follow **MAJOR.MINOR.PATCH** (for example, `4.4.0`):
394
+
395
+ - **Major:** breaking changes.
396
+ - **Minor:** backward-compatible new features.
397
+ - **Patch:** backward-compatible bug fixes.
398
+
399
+ ### Publishing
400
+
401
+ 1. Choose an unused package version after checking `npm view @womp/spark-agent versions --json`.
402
+ Update `package.json` and record public API changes and migration notes. Use a new minor version
403
+ for incompatible changes while the package is below 1.0.
404
+ 2. On a supported Node version, run `yarn install --frozen-lockfile`, `yarn typecheck`, `yarn test`,
405
+ and `yarn web:build`. Do not bypass dependency engine checks. Commit the release changes and
406
+ record the commit used to build the package.
407
+ 3. Run `yarn pack --filename spark-agent-release.tgz`. Inspect the archive contents and install
408
+ that archive in the consuming application. Verify packaged declarations and skills, browser
409
+ import boundaries, the production build, and the applicable integration cases without source
410
+ aliases. Keep the archive outside Git and do not rebuild or change it after verification.
411
+ 4. Publish the verified archive with `npm publish ./spark-agent-release.tgz --access public`.
412
+ If the response is uncertain, inspect the registry's version and integrity before retrying.
413
+ Verify the published version and archive integrity, then tag the recorded commit as `v<version>`
414
+ and push the release commit and tag. An already published version cannot be replaced; corrections
415
+ need a new version.
416
+ 5. In the consuming application, use `yarn add @womp/spark-agent@<version> --exact`. Commit its
417
+ manifest and lockfile together, and verify a clean frozen-lockfile installation and production
418
+ build. Remove the temporary archive dependency. Application deployment and merge requirements
419
+ remain separate from package publication.
420
+
421
+ ## Layout
422
+
423
+ - `src/agent.ts` — AI SDK stream and Spark tool orchestration
424
+ - `src/ui.ts` — browser-safe protocol types and validation schemas
425
+ - `src/client.ts` — durable `ChatTransport` implementation
426
+ - `src/server/` — service, storage contracts, Express adapter, artifacts, and standalone composition
427
+ - `src/runtime.ts` — Kakapo scene connections and edit transactions
428
+ - `src/quickjs-executor.ts` — isolated JavaScript execution and host bridge
429
+ - `src/womp-scene-api.ts` — Womp-compatible Kakapo scene API
430
+ - `web/src/App.tsx` — reference `useChat<SparkUIMessage>` application