@womp/spark-agent 5.0.1 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,11 +1,11 @@
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
-
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
9
  ## Requirements
10
10
 
11
11
  ### Migrating to 5.0
@@ -25,221 +25,221 @@ execution use the same model loop. The host owns conversations, artifacts, autho
25
25
  per execution. Receipts, cancellation, timeout limits and uncertain-outcome handling remain enforced.
26
26
 
27
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
-
121
- Spark does not estimate or limit input tokens or automatically shorten conversation history.
122
- The provider enforces its context limit; rejections follow the normal provider-error path.
123
-
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
+
121
+ Spark does not estimate or limit input tokens or automatically shorten conversation history.
122
+ The provider enforces its context limit; rejections follow the normal provider-error path.
123
+
124
124
  Screenshot and file APIs return serializable artifact references. `emitImage` and `emitFile` resolve
125
125
  them through the host's artifact resolver. Keep references resolvable when reloading history, and
126
126
  pass `createSparkTools(...)` to AI SDK's `convertToModelMessages` to reconstruct multimodal results.
127
127
  `emitImage(artifact, { inspect: false })` displays an image without adding its bytes to model input,
128
128
  including restored history. Inspection is enabled by default.
129
- Kakapo skill declarations are generated from its actual typed API during the build and packaged as
130
- JavaScript strings; they do not need filesystem or Markdown loading in the browser.
131
-
132
- ## Local frontend
133
-
134
- `LocalSparkChatTransport` accepts a host callback returning a `SparkAgentRun` from `runSparkAgent`.
135
- The callback receives the standard AI SDK chat request, including its messages and abort signal.
136
- It persists the initiating message, resolves the model and capabilities, and starts the shared loop.
137
- Keep ownership of the active run outside the React renderer. Local browser runs end when the page
138
- closes; `reconnectToStream` returns `null`.
139
-
140
- ## Remote frontend
141
-
142
- ```tsx
143
- import { useChat } from "@ai-sdk/react";
144
- import { SparkChatTransport } from "@womp/spark-agent/client";
145
- import {
146
- sparkDataPartSchemas,
147
- sparkMessageMetadataSchema,
148
- type SparkUIMessage,
149
- } from "@womp/spark-agent/ui";
150
-
151
- const transport = new SparkChatTransport({ api: "/agent" });
152
-
153
- const chat = useChat<SparkUIMessage>({
154
- id: conversationId,
155
- messages: initialMessages,
156
- transport,
157
- resume: true,
158
- messageMetadataSchema: sparkMessageMetadataSchema,
159
- dataPartSchemas: sparkDataPartSchemas,
160
- });
161
- ```
162
-
163
- Render `message.parts`. Standard AI SDK parts represent text, reasoning, files, tool inputs, tool
129
+ Kakapo skill declarations are generated from its actual typed API during the build and packaged as
130
+ JavaScript strings; they do not need filesystem or Markdown loading in the browser.
131
+
132
+ ## Local frontend
133
+
134
+ `LocalSparkChatTransport` accepts a host callback returning a `SparkAgentRun` from `runSparkAgent`.
135
+ The callback receives the standard AI SDK chat request, including its messages and abort signal.
136
+ It persists the initiating message, resolves the model and capabilities, and starts the shared loop.
137
+ Keep ownership of the active run outside the React renderer. Local browser runs end when the page
138
+ closes; `reconnectToStream` returns `null`.
139
+
140
+ ## Remote frontend
141
+
142
+ ```tsx
143
+ import { useChat } from "@ai-sdk/react";
144
+ import { SparkChatTransport } from "@womp/spark-agent/client";
145
+ import {
146
+ sparkDataPartSchemas,
147
+ sparkMessageMetadataSchema,
148
+ type SparkUIMessage,
149
+ } from "@womp/spark-agent/ui";
150
+
151
+ const transport = new SparkChatTransport({ api: "/agent" });
152
+
153
+ const chat = useChat<SparkUIMessage>({
154
+ id: conversationId,
155
+ messages: initialMessages,
156
+ transport,
157
+ resume: true,
158
+ messageMetadataSchema: sparkMessageMetadataSchema,
159
+ dataPartSchemas: sparkDataPartSchemas,
160
+ });
161
+ ```
162
+
163
+ Render `message.parts`. Standard AI SDK parts represent text, reasoning, files, tool inputs, tool
164
164
  outputs, approvals, and step boundaries. Spark adds typed `data-console`, `data-artifact`,
165
165
  `data-run-status`, `data-step-metrics`, and `data-execution-receipt` parts. Receipts are emitted before
166
166
  their storage barrier, keeping known effects visible even when saving the tool result fails.
167
167
  Hosts can consume `data-tool-input-label` once the tool's label field is complete, while the
168
168
  remaining input is still streaming.
169
-
170
- An explicit Stop action must cancel the durable run before stopping local observation:
171
-
172
- ```ts
173
- await transport.cancelRun(conversationId);
174
- await chat.stop();
175
- ```
176
-
177
- Closing or reloading the page only detaches the SSE subscriber. It does not cancel the run.
178
-
179
- ## HTTP and SSE
180
-
181
- `SparkChatTransport` hides the durable run lifecycle from `useChat`:
182
-
183
- ```text
184
- POST /agent/conversations/:conversationId/messages
185
- PATCH /agent/conversations/:conversationId/settings
186
- GET /agent/runs/:runId/stream?after=0
187
- POST /agent/runs/:runId/cancel
188
- ```
189
-
190
- Conversation settings contain `modelId` and `reasoningEffort`. The standalone UI saves selector
191
- changes immediately through `transport.saveConversationSettings(id, settings)` and restores them
192
- per thread. Older threads fall back to their last recorded model (or the default) and medium effort;
193
- unsupported choices fall back to supported settings. Assistant footers show the model recorded on
194
- that turn, independently of the selector.
195
-
196
- Custom stores must implement `saveConversationSettings` as a settings-only update, and preserve
197
- stored settings during `saveConversation` so streaming history saves cannot overwrite preferences.
169
+
170
+ An explicit Stop action must cancel the durable run before stopping local observation:
171
+
172
+ ```ts
173
+ await transport.cancelRun(conversationId);
174
+ await chat.stop();
175
+ ```
176
+
177
+ Closing or reloading the page only detaches the SSE subscriber. It does not cancel the run.
178
+
179
+ ## HTTP and SSE
180
+
181
+ `SparkChatTransport` hides the durable run lifecycle from `useChat`:
182
+
183
+ ```text
184
+ POST /agent/conversations/:conversationId/messages
185
+ PATCH /agent/conversations/:conversationId/settings
186
+ GET /agent/runs/:runId/stream?after=0
187
+ POST /agent/runs/:runId/cancel
188
+ ```
189
+
190
+ Conversation settings contain `modelId` and `reasoningEffort`. The standalone UI saves selector
191
+ changes immediately through `transport.saveConversationSettings(id, settings)` and restores them
192
+ per thread. Older threads fall back to their last recorded model (or the default) and medium effort;
193
+ unsupported choices fall back to supported settings. Assistant footers show the model recorded on
194
+ that turn, independently of the selector.
195
+
196
+ Custom stores must implement `saveConversationSettings` as a settings-only update, and preserve
197
+ stored settings during `saveConversation` so streaming history saves cannot overwrite preferences.
198
198
  The built-in memory and SQLite stores implement this contract.
199
-
200
- The SSE response contains ordered persistence envelopes around standard AI SDK chunks:
201
-
202
- ```ts
203
- type StoredSparkChunk = {
204
- sequence: number;
205
- conversationId: string;
206
- runId: string;
207
- createdAt: string;
208
- chunk: SparkUIMessageChunk;
209
- };
210
- ```
211
-
212
- The transport unwraps each envelope and returns the contained `UIMessageChunk` to `useChat`.
213
- Active assistant messages are replayed from sequence zero when reconnecting because `useChat`
214
- reconstructs the in-progress message from the resumed stream.
215
-
216
- ## Embedding in an Express backend
217
-
218
- Spark does not call `listen()` when imported. The host owns its HTTP server and mounts the router:
219
-
220
- ```ts
221
- import { createSparkAgentRouter } from "@womp/spark-agent/express";
222
- import { SparkAgentService, createSparkRunExecutor } from "@womp/spark-agent/server";
223
-
224
- const service = new SparkAgentService({
225
- store,
226
- executeRun: createSparkRunExecutor({
227
- resolveModel,
228
- createHost,
229
- }),
230
- });
231
-
232
- app.use(
233
- "/agent",
234
- userAccess,
235
- createSparkAgentRouter({
236
- service,
237
- artifactStore,
238
- resolveOwnerId: (request) => request.user.id,
239
- }),
240
- );
241
- ```
242
-
199
+
200
+ The SSE response contains ordered persistence envelopes around standard AI SDK chunks:
201
+
202
+ ```ts
203
+ type StoredSparkChunk = {
204
+ sequence: number;
205
+ conversationId: string;
206
+ runId: string;
207
+ createdAt: string;
208
+ chunk: SparkUIMessageChunk;
209
+ };
210
+ ```
211
+
212
+ The transport unwraps each envelope and returns the contained `UIMessageChunk` to `useChat`.
213
+ Active assistant messages are replayed from sequence zero when reconnecting because `useChat`
214
+ reconstructs the in-progress message from the resumed stream.
215
+
216
+ ## Embedding in an Express backend
217
+
218
+ Spark does not call `listen()` when imported. The host owns its HTTP server and mounts the router:
219
+
220
+ ```ts
221
+ import { createSparkAgentRouter } from "@womp/spark-agent/express";
222
+ import { SparkAgentService, createSparkRunExecutor } from "@womp/spark-agent/server";
223
+
224
+ const service = new SparkAgentService({
225
+ store,
226
+ executeRun: createSparkRunExecutor({
227
+ resolveModel,
228
+ createHost,
229
+ }),
230
+ });
231
+
232
+ app.use(
233
+ "/agent",
234
+ userAccess,
235
+ createSparkAgentRouter({
236
+ service,
237
+ artifactStore,
238
+ resolveOwnerId: (request) => request.user.id,
239
+ }),
240
+ );
241
+ ```
242
+
243
243
  `MemorySparkAgentStore` and `MemorySparkArtifactStore` are development implementations. Production
244
244
  hosts must supply durable implementations backed by their database/object storage and must preserve
245
245
  the ordering contract of `appendRunChunk()`.
@@ -251,131 +251,131 @@ store, enabling it could end another process's live run.
251
251
  Custom stores can implement `releaseActiveRun(conversationId, runId, updatedAt)` to clear the active
252
252
  run only if its ID still matches. Memory and SQLite stores implement it. Without it, the service
253
253
  serializes read-and-save release against its own submissions.
254
-
255
- ## Standalone development server
256
-
257
- The package includes a local server bound to `127.0.0.1:8787`:
258
-
259
- ```bash
260
- spark-agent
261
- ```
262
-
263
- Configure the process with:
264
-
265
- - `OPENAI_API_KEY`
266
- - `ANTHROPIC_API_KEY`
267
- - `GEMINI_API_KEY`
268
- - `KAKAPO_URL` (defaults to `ws://127.0.0.1:5502`)
269
- - `PORT` (defaults to `8787`)
270
- - `SPARK_STORAGE_PATH` (defaults to `.spark/spark.sqlite`)
271
- - `SPARK_SCENE_IDENTITY` (optional stable identity for the scene behind `KAKAPO_URL`)
272
-
273
- The CLI automatically loads `.env` from its working directory when the file exists. Copy
274
- `.env.example` to `.env`, then add the provider key you intend to use. Existing process environment
275
- variables take precedence over values loaded from the file.
276
-
277
- For repository development, `yarn dev` starts the Express server and Vite demo together. Open
278
- `http://127.0.0.1:5173`.
279
-
280
- Standalone scene edits use the existing `scene_state_patch` command followed by `save_scene` after
281
- the patch is acknowledged. The durable operation journal records the separate mutation and save
282
- outcomes. A failed or unknown save stops that operation with an explicit error, retaining any
283
- applied work without replay. The two commands are not an atomic transaction, and a renderer save
284
- acknowledgement proves only renderer-local history, not durable backend storage.
285
-
286
- The standalone server persists conversations, run streams, and screenshot bytes in SQLite. Only
287
- one local process can execute against a database. After a terminated process is replaced, startup
288
- preserves recorded output and marks abandoned queued/running runs incomplete without replaying
254
+
255
+ ## Standalone development server
256
+
257
+ The package includes a local server bound to `127.0.0.1:8787`:
258
+
259
+ ```bash
260
+ spark-agent
261
+ ```
262
+
263
+ Configure the process with:
264
+
265
+ - `OPENAI_API_KEY`
266
+ - `ANTHROPIC_API_KEY`
267
+ - `GEMINI_API_KEY`
268
+ - `KAKAPO_URL` (defaults to `ws://127.0.0.1:5502`)
269
+ - `PORT` (defaults to `8787`)
270
+ - `SPARK_STORAGE_PATH` (defaults to `.spark/spark.sqlite`)
271
+ - `SPARK_SCENE_IDENTITY` (optional stable identity for the scene behind `KAKAPO_URL`)
272
+
273
+ The CLI automatically loads `.env` from its working directory when the file exists. Copy
274
+ `.env.example` to `.env`, then add the provider key you intend to use. Existing process environment
275
+ variables take precedence over values loaded from the file.
276
+
277
+ For repository development, `yarn dev` starts the Express server and Vite demo together. Open
278
+ `http://127.0.0.1:5173`.
279
+
280
+ Standalone scene edits use the existing `scene_state_patch` command followed by `save_scene` after
281
+ the patch is acknowledged. The durable operation journal records the separate mutation and save
282
+ outcomes. A failed or unknown save stops that operation with an explicit error, retaining any
283
+ applied work without replay. The two commands are not an atomic transaction, and a renderer save
284
+ acknowledgement proves only renderer-local history, not durable backend storage.
285
+
286
+ The standalone server persists conversations, run streams, and screenshot bytes in SQLite. Only
287
+ one local process can execute against a database. After a terminated process is replaced, startup
288
+ preserves recorded output and marks abandoned queued/running runs incomplete without replaying
289
289
  scene edits. Pending approvals remain pending; startup does not resume abandoned runs.
290
290
  Node 22 reports an experimental warning for its built-in SQLite module.
291
-
292
- Set `SPARK_SCENE_IDENTITY` only when the host can verify that the value names the same durable
293
- scene across renderer reconnects. Without it, Spark uses a process-scoped identity and does not
294
- authorize interrupted scene mutations to continue after a server restart.
295
-
296
- `createStandaloneSparkAgentApp(options)` is asynchronous. Await it before listening, and call
297
- `await app.dispose()` on shutdown to settle active runs and release storage ownership.
298
-
291
+
292
+ Set `SPARK_SCENE_IDENTITY` only when the host can verify that the value names the same durable
293
+ scene across renderer reconnects. Without it, Spark uses a process-scoped identity and does not
294
+ authorize interrupted scene mutations to continue after a server restart.
295
+
296
+ `createStandaloneSparkAgentApp(options)` is asynchronous. Await it before listening, and call
297
+ `await app.dispose()` on shutdown to settle active runs and release storage ownership.
298
+
299
299
  When using a sibling `kakapo-sdk` dependency, run `yarn build` in `../kakapo-sdk` before installing
300
300
  Spark dependencies. Replace local dependencies with registry versions before publishing.
301
-
302
- For the explicit fictional account profile, use `yarn dev:demo-account` or
303
- `spark-agent --profile demo-account`. It adds the `account` skill and `womp.account.read`
304
- beside the real local Kakapo scene API. Profile reads identify themselves as fictional fixtures;
305
- credits, billing, orders, and other account services report unavailable. The default composition
306
- omits account entirely. Neither profile supplies fake generation jobs, imports, or billing permission.
307
- Embedded development servers can select `developmentProfile: "demo-account"` explicitly.
308
-
309
- The same profile supplies two actual local material resources: `Development: Matte Blue` and
310
- `Development: Polished Copper`. They are bundled JSON files under `src/server/fixtures/materials`
311
- and imported through the normal SDK draft, not simulated scene effects. In `scene.edit`, await
312
- `api.materialImport(name)`, then assign its numeric ID. The default profile has no library service.
313
-
314
- ## Run cost estimates
315
-
316
- Prompt caching is enabled for every listed model: Claude Opus 5 and Fable 5 use
317
- automatic 5-minute caching, and GPT-6 Astra uses implicit caching with a 30-minute TTL.
318
- The providers manage the cache as message history grows across tool steps; no local
319
- response cache is used. Cache hits require matching prefixes, sufficient prompt length,
320
- and an unexpired entry. Cache writes can cost more than uncached input, while subsequent
321
- cache reads are cheaper. The UI displays actual reported reads/writes, not assumed savings.
322
- See [Claude caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching)
323
- and [OpenAI caching](https://developers.openai.com/api/docs/guides/prompt-caching).
324
- Restart the server after changing these settings; existing runs keep their original configuration.
325
-
326
- The chat displays estimated API token cost in USD, updated after every completed model step.
327
- Hover or focus the amount to inspect uncached input, cache reads/writes, and output costs. Output usage
328
- already includes reasoning tokens. Image input is included in the provider's input token count.
329
-
330
- `src/pricing.ts` contains standard direct API rates verified on September 9, 2026:
331
-
332
- | Model | Input / 1M | Cache read / 1M | Cache write / 1M | Output / 1M |
333
- | -------------- | ---------- | --------------- | --------------------- | ----------- |
334
- | GPT-6 Astra | $10 | $1 | $12.50 | $50 |
335
- | Claude Opus 5 | $5 | $0.50 | $6.25 (5m), $10 (1h) | $25 |
336
- | Claude Fable 5 | $10 | $1 | $12.50 (5m), $20 (1h) | $50 |
337
-
338
- Astra requests above 272,000 input tokens use 2x input/cache rates and 1.5x output rates.
339
- This threshold is applied to each request before summing run costs. Claude's full context uses
340
- standard rates. Sources: [Astra pricing](https://developers.openai.com/api/docs/models/gpt-6-astra),
341
- [Claude pricing](https://platform.claude.com/docs/en/about-claude/pricing).
342
-
343
- Each `data-step-metrics` part stores a `cost` snapshot with the model, rate date, source, token
344
- categories, rates, and amounts. The UI sums those stored amounts, so reconnection does not double
345
- count steps and future price changes do not reprice recorded runs. Update the rate table and its
346
- verification date when provider pricing changes.
347
-
348
- The unfinished step is excluded until its usage arrives. Cancelled/failed runs show a partial
349
- estimate. Missing usage, unknown models, missing cache TTLs, or provider sub-inferences without
350
- separate attribution are marked unavailable, never silently priced as zero. Historical runs
351
- without step pricing remain unavailable. Estimates exclude taxes, negotiated discounts, and scene
352
- hosting; the provider bill is authoritative. Spark requests OpenAI's standard service tier.
353
-
354
- ## Execution security
355
-
356
- The standalone host uses a fresh QuickJS runtime for each JavaScript execution. It has no Node.js
357
- or browser globals and receives only the composed capability APIs. Imports, filesystem access,
358
- network APIs, and host environment variables are not exposed. QuickJS limits memory, stack size,
359
- execution time, source size, host calls, and data crossing the host bridge. Browser hosts can instead
301
+
302
+ For the explicit fictional account profile, use `yarn dev:demo-account` or
303
+ `spark-agent --profile demo-account`. It adds the `account` skill and `womp.account.read`
304
+ beside the real local Kakapo scene API. Profile reads identify themselves as fictional fixtures;
305
+ credits, billing, orders, and other account services report unavailable. The default composition
306
+ omits account entirely. Neither profile supplies fake generation jobs, imports, or billing permission.
307
+ Embedded development servers can select `developmentProfile: "demo-account"` explicitly.
308
+
309
+ The same profile supplies two actual local material resources: `Development: Matte Blue` and
310
+ `Development: Polished Copper`. They are bundled JSON files under `src/server/fixtures/materials`
311
+ and imported through the normal SDK draft, not simulated scene effects. In `scene.edit`, await
312
+ `api.materialImport(name)`, then assign its numeric ID. The default profile has no library service.
313
+
314
+ ## Run cost estimates
315
+
316
+ Prompt caching is enabled for every listed model: Claude Opus 5 and Fable 5 use
317
+ automatic 5-minute caching, and GPT-6 Astra uses implicit caching with a 30-minute TTL.
318
+ The providers manage the cache as message history grows across tool steps; no local
319
+ response cache is used. Cache hits require matching prefixes, sufficient prompt length,
320
+ and an unexpired entry. Cache writes can cost more than uncached input, while subsequent
321
+ cache reads are cheaper. The UI displays actual reported reads/writes, not assumed savings.
322
+ See [Claude caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching)
323
+ and [OpenAI caching](https://developers.openai.com/api/docs/guides/prompt-caching).
324
+ Restart the server after changing these settings; existing runs keep their original configuration.
325
+
326
+ The chat displays estimated API token cost in USD, updated after every completed model step.
327
+ Hover or focus the amount to inspect uncached input, cache reads/writes, and output costs. Output usage
328
+ already includes reasoning tokens. Image input is included in the provider's input token count.
329
+
330
+ `src/pricing.ts` contains standard direct API rates verified on September 9, 2026:
331
+
332
+ | Model | Input / 1M | Cache read / 1M | Cache write / 1M | Output / 1M |
333
+ | -------------- | ---------- | --------------- | --------------------- | ----------- |
334
+ | GPT-6 Astra | $10 | $1 | $12.50 | $50 |
335
+ | Claude Opus 5 | $5 | $0.50 | $6.25 (5m), $10 (1h) | $25 |
336
+ | Claude Fable 5 | $10 | $1 | $12.50 (5m), $20 (1h) | $50 |
337
+
338
+ Astra requests above 272,000 input tokens use 2x input/cache rates and 1.5x output rates.
339
+ This threshold is applied to each request before summing run costs. Claude's full context uses
340
+ standard rates. Sources: [Astra pricing](https://developers.openai.com/api/docs/models/gpt-6-astra),
341
+ [Claude pricing](https://platform.claude.com/docs/en/about-claude/pricing).
342
+
343
+ Each `data-step-metrics` part stores a `cost` snapshot with the model, rate date, source, token
344
+ categories, rates, and amounts. The UI sums those stored amounts, so reconnection does not double
345
+ count steps and future price changes do not reprice recorded runs. Update the rate table and its
346
+ verification date when provider pricing changes.
347
+
348
+ The unfinished step is excluded until its usage arrives. Cancelled/failed runs show a partial
349
+ estimate. Missing usage, unknown models, missing cache TTLs, or provider sub-inferences without
350
+ separate attribution are marked unavailable, never silently priced as zero. Historical runs
351
+ without step pricing remain unavailable. Estimates exclude taxes, negotiated discounts, and scene
352
+ hosting; the provider bill is authoritative. Spark requests OpenAI's standard service tier.
353
+
354
+ ## Execution security
355
+
356
+ The standalone host uses a fresh QuickJS runtime for each JavaScript execution. It has no Node.js
357
+ or browser globals and receives only the composed capability APIs. Imports, filesystem access,
358
+ network APIs, and host environment variables are not exposed. QuickJS limits memory, stack size,
359
+ execution time, source size, host calls, and data crossing the host bridge. Browser hosts can instead
360
360
  choose native page execution, with the page-global access and interruption limitations described above.
361
361
  Both executors allow 100,000 host calls per execution by default; the counter resets for each
362
362
  execution. QuickJS supports overriding this through `maxHostCalls`. Cancellation, timeouts,
363
363
  and the other execution limits still apply.
364
-
365
- QuickJS isolates generated code from the JavaScript host API; it is not an operating-system security
366
- boundary. Multi-tenant deployments must additionally isolate workers, authorize every Kakapo
367
- session and tool call, enforce quotas, and avoid passing privileged functions through the runtime
368
- bridge.
369
-
370
- ## Validation
371
-
372
- ```bash
373
- yarn build
374
- yarn typecheck
375
- yarn test
376
- yarn web:build
377
- ```
378
-
364
+
365
+ QuickJS isolates generated code from the JavaScript host API; it is not an operating-system security
366
+ boundary. Multi-tenant deployments must additionally isolate workers, authorize every Kakapo
367
+ session and tool call, enforce quotas, and avoid passing privileged functions through the runtime
368
+ bridge.
369
+
370
+ ## Validation
371
+
372
+ ```bash
373
+ yarn build
374
+ yarn typecheck
375
+ yarn test
376
+ yarn web:build
377
+ ```
378
+
379
379
  ## Release procedure
380
380
 
381
381
  Releases use a manual package publication; no separate release service is required.
@@ -387,34 +387,34 @@ Versions follow **MAJOR.MINOR.PATCH** (for example, `4.4.0`):
387
387
  - **Patch:** backward-compatible bug fixes.
388
388
 
389
389
  ### Publishing
390
-
391
- 1. Choose an unused package version after checking `npm view @womp/spark-agent versions --json`.
392
- Update `package.json` and record public API changes and migration notes. Use a new minor version
393
- for incompatible changes while the package is below 1.0.
394
- 2. On a supported Node version, run `yarn install --frozen-lockfile`, `yarn typecheck`, `yarn test`,
395
- and `yarn web:build`. Do not bypass dependency engine checks. Commit the release changes and
396
- record the commit used to build the package.
397
- 3. Run `yarn pack --filename spark-agent-release.tgz`. Inspect the archive contents and install
398
- that archive in the consuming application. Verify packaged declarations and skills, browser
399
- import boundaries, the production build, and the applicable integration cases without source
400
- aliases. Keep the archive outside Git and do not rebuild or change it after verification.
401
- 4. Publish the verified archive with `npm publish ./spark-agent-release.tgz --access public`.
402
- If the response is uncertain, inspect the registry's version and integrity before retrying.
403
- Verify the published version and archive integrity, then tag the recorded commit as `v<version>`
404
- and push the release commit and tag. An already published version cannot be replaced; corrections
405
- need a new version.
406
- 5. In the consuming application, use `yarn add @womp/spark-agent@<version> --exact`. Commit its
407
- manifest and lockfile together, and verify a clean frozen-lockfile installation and production
408
- build. Remove the temporary archive dependency. Application deployment and merge requirements
409
- remain separate from package publication.
410
-
411
- ## Layout
412
-
413
- - `src/agent.ts` — AI SDK stream and Spark tool orchestration
414
- - `src/ui.ts` — browser-safe protocol types and validation schemas
415
- - `src/client.ts` — durable `ChatTransport` implementation
416
- - `src/server/` — service, storage contracts, Express adapter, artifacts, and standalone composition
417
- - `src/runtime.ts` — Kakapo scene connections and edit transactions
418
- - `src/quickjs-executor.ts` — isolated JavaScript execution and host bridge
419
- - `src/womp-scene-api.ts` — Womp-compatible Kakapo scene API
420
- - `web/src/App.tsx` — reference `useChat<SparkUIMessage>` application
390
+
391
+ 1. Choose an unused package version after checking `npm view @womp/spark-agent versions --json`.
392
+ Update `package.json` and record public API changes and migration notes. Use a new minor version
393
+ for incompatible changes while the package is below 1.0.
394
+ 2. On a supported Node version, run `yarn install --frozen-lockfile`, `yarn typecheck`, `yarn test`,
395
+ and `yarn web:build`. Do not bypass dependency engine checks. Commit the release changes and
396
+ record the commit used to build the package.
397
+ 3. Run `yarn pack --filename spark-agent-release.tgz`. Inspect the archive contents and install
398
+ that archive in the consuming application. Verify packaged declarations and skills, browser
399
+ import boundaries, the production build, and the applicable integration cases without source
400
+ aliases. Keep the archive outside Git and do not rebuild or change it after verification.
401
+ 4. Publish the verified archive with `npm publish ./spark-agent-release.tgz --access public`.
402
+ If the response is uncertain, inspect the registry's version and integrity before retrying.
403
+ Verify the published version and archive integrity, then tag the recorded commit as `v<version>`
404
+ and push the release commit and tag. An already published version cannot be replaced; corrections
405
+ need a new version.
406
+ 5. In the consuming application, use `yarn add @womp/spark-agent@<version> --exact`. Commit its
407
+ manifest and lockfile together, and verify a clean frozen-lockfile installation and production
408
+ build. Remove the temporary archive dependency. Application deployment and merge requirements
409
+ remain separate from package publication.
410
+
411
+ ## Layout
412
+
413
+ - `src/agent.ts` — AI SDK stream and Spark tool orchestration
414
+ - `src/ui.ts` — browser-safe protocol types and validation schemas
415
+ - `src/client.ts` — durable `ChatTransport` implementation
416
+ - `src/server/` — service, storage contracts, Express adapter, artifacts, and standalone composition
417
+ - `src/runtime.ts` — Kakapo scene connections and edit transactions
418
+ - `src/quickjs-executor.ts` — isolated JavaScript execution and host bridge
419
+ - `src/womp-scene-api.ts` — Womp-compatible Kakapo scene API
420
+ - `web/src/App.tsx` — reference `useChat<SparkUIMessage>` application