@womp/spark-agent 0.1.0 → 0.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 (113) hide show
  1. package/.env.example +4 -0
  2. package/README.md +295 -49
  3. package/dist/agent-tools.d.ts +30 -0
  4. package/dist/agent-tools.js +189 -0
  5. package/dist/agent.d.ts +34 -7
  6. package/dist/agent.js +223 -158
  7. package/dist/browser.d.ts +2 -0
  8. package/dist/browser.js +2 -0
  9. package/dist/capabilities/account.d.ts +216 -0
  10. package/dist/capabilities/account.js +63 -0
  11. package/dist/capabilities/asset-imports.d.ts +55 -0
  12. package/dist/capabilities/asset-imports.js +117 -0
  13. package/dist/capabilities/assets.d.ts +29 -0
  14. package/dist/capabilities/assets.js +48 -0
  15. package/dist/capabilities/flow.d.ts +29 -0
  16. package/dist/capabilities/flow.js +52 -0
  17. package/dist/capabilities/geometry.d.ts +48 -0
  18. package/dist/capabilities/geometry.js +51 -0
  19. package/dist/capabilities/knowledge.d.ts +11 -0
  20. package/dist/capabilities/knowledge.js +23 -0
  21. package/dist/capabilities/openscad-instructions.d.ts +1 -0
  22. package/dist/capabilities/openscad-instructions.js +81 -0
  23. package/dist/capabilities/openscad.d.ts +54 -0
  24. package/dist/capabilities/openscad.js +34 -0
  25. package/dist/capabilities/operations.d.ts +104 -0
  26. package/dist/capabilities/operations.js +145 -0
  27. package/dist/capabilities/scene-draft.d.ts +404 -0
  28. package/dist/capabilities/scene-draft.js +1 -0
  29. package/dist/capabilities/scene.d.ts +28 -0
  30. package/dist/capabilities/scene.js +51 -0
  31. package/dist/capabilities.d.ts +67 -0
  32. package/dist/capabilities.js +25 -0
  33. package/dist/cli.d.ts +2 -0
  34. package/dist/cli.js +24 -0
  35. package/dist/client.d.ts +43 -0
  36. package/dist/client.js +159 -0
  37. package/dist/context.d.ts +15 -0
  38. package/dist/context.js +264 -0
  39. package/dist/execution-lifetime.d.ts +32 -0
  40. package/dist/execution-lifetime.js +113 -0
  41. package/dist/executor.d.ts +6 -1
  42. package/dist/generated/account-declarations.d.ts +1 -0
  43. package/dist/generated/account-declarations.js +3 -0
  44. package/dist/generated/asset-import-declarations.d.ts +1 -0
  45. package/dist/generated/asset-import-declarations.js +3 -0
  46. package/dist/generated/assets-declarations.d.ts +1 -0
  47. package/dist/generated/assets-declarations.js +3 -0
  48. package/dist/generated/flow-declarations.d.ts +1 -0
  49. package/dist/generated/flow-declarations.js +3 -0
  50. package/dist/generated/geometry-declarations.d.ts +1 -0
  51. package/dist/generated/geometry-declarations.js +3 -0
  52. package/dist/generated/kakapo-declarations.d.ts +1 -0
  53. package/dist/generated/kakapo-declarations.js +3 -0
  54. package/dist/generated/knowledge-declarations.d.ts +1 -0
  55. package/dist/generated/knowledge-declarations.js +3 -0
  56. package/dist/generated/openscad-declarations.d.ts +1 -0
  57. package/dist/generated/openscad-declarations.js +3 -0
  58. package/dist/generated/operations-declarations.d.ts +1 -0
  59. package/dist/generated/operations-declarations.js +3 -0
  60. package/dist/generated/scene-declarations.d.ts +1 -0
  61. package/dist/generated/scene-declarations.js +3 -0
  62. package/dist/index.d.ts +7 -6
  63. package/dist/index.js +5 -3
  64. package/dist/kakapo-capability-api.d.ts +18 -0
  65. package/dist/kakapo-capability-api.js +1 -0
  66. package/dist/kakapo-capability.d.ts +6 -0
  67. package/dist/kakapo-capability.js +50 -0
  68. package/dist/kakapo-scene-skill.d.ts +1 -0
  69. package/dist/kakapo-scene-skill.js +54 -0
  70. package/dist/kakapo.d.ts +5 -0
  71. package/dist/kakapo.js +3 -0
  72. package/dist/local-transport.d.ts +11 -0
  73. package/dist/local-transport.js +15 -0
  74. package/dist/model-history.d.ts +5 -0
  75. package/dist/model-history.js +34 -0
  76. package/dist/model-options.d.ts +4 -0
  77. package/dist/model-options.js +25 -0
  78. package/dist/models.d.ts +3 -15
  79. package/dist/models.js +2 -16
  80. package/dist/native-executor.d.ts +5 -0
  81. package/dist/native-executor.js +92 -0
  82. package/dist/pricing.d.ts +3 -0
  83. package/dist/pricing.js +70 -0
  84. package/dist/prompt.d.ts +1 -1
  85. package/dist/prompt.js +19 -209
  86. package/dist/quickjs-executor.d.ts +13 -0
  87. package/dist/quickjs-executor.js +309 -0
  88. package/dist/runtime.d.ts +16 -5
  89. package/dist/runtime.js +61 -10
  90. package/dist/server/artifacts.d.ts +17 -0
  91. package/dist/server/artifacts.js +36 -0
  92. package/dist/server/demo-account.d.ts +3 -0
  93. package/dist/server/demo-account.js +38 -0
  94. package/dist/server/executor.d.ts +17 -0
  95. package/dist/server/executor.js +35 -0
  96. package/dist/server/express.d.ts +13 -0
  97. package/dist/server/express.js +159 -0
  98. package/dist/server/index.d.ts +8 -0
  99. package/dist/server/index.js +5 -0
  100. package/dist/server/service.d.ts +41 -0
  101. package/dist/server/service.js +402 -0
  102. package/dist/server/standalone.d.ts +9 -0
  103. package/dist/server/standalone.js +85 -0
  104. package/dist/server/store.d.ts +16 -0
  105. package/dist/server/store.js +70 -0
  106. package/dist/server/types.d.ts +53 -0
  107. package/dist/server/types.js +1 -0
  108. package/dist/types.d.ts +3 -27
  109. package/dist/ui.d.ts +224 -0
  110. package/dist/ui.js +71 -0
  111. package/dist/womp-scene-api.d.ts +195 -3
  112. package/dist/womp-scene-api.js +102 -73
  113. package/package.json +66 -10
package/.env.example ADDED
@@ -0,0 +1,4 @@
1
+ OPENAI_API_KEY=
2
+ ANTHROPIC_API_KEY=
3
+ KAKAPO_URL=ws://127.0.0.1:5502
4
+ PORT=8787
package/README.md CHANGED
@@ -1,87 +1,333 @@
1
1
  # @womp/spark-agent
2
2
 
3
- Local browser workspace for controlling Kakapo with model-authored JavaScript.
3
+ Portable AI agent for Womp applications and Kakapo scenes with model-authored JavaScript.
4
4
 
5
- The agent runs in the tab, calls OpenAI through the AI SDK, and connects directly to Kakapo through
6
- `@womp/kakapo-sdk`. Scene access is restricted to a private build root. Top-level `createNode()` calls are
7
- automatically parented to that root, and the native screenshot tool frames the build for visual
8
- inspection.
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.
9
8
 
10
- ## Run
9
+ ## Requirements
11
10
 
12
- Install the reusable core from npm:
11
+ - Node.js 22 or newer
12
+ - AI SDK 7
13
+ - `@ai-sdk/react` 4 for React clients
13
14
 
14
15
  ```bash
15
- yarn add @womp/spark-agent @womp/kakapo-sdk
16
+ npm install @womp/spark-agent
16
17
  ```
17
18
 
18
- The package entrypoint exports only the environment-neutral agent core. It does not import React,
19
- Vite, browser storage, or the browser JavaScript executor.
19
+ ## Package entry points
20
20
 
21
- ## Browser test application
21
+ - `@womp/spark-agent` — browser-safe model loop, two tools, persistence hooks, and shared contracts
22
+ - `@womp/spark-agent/browser` — native JavaScript executor and local chat transport
23
+ - `@womp/spark-agent/capabilities` — capability composition and skill contracts
24
+ - `@womp/spark-agent/kakapo` — direct Kakapo runtime and scene capability
25
+ - `@womp/spark-agent/quickjs` — optional isolated JavaScript executor
26
+ - `@womp/spark-agent/ui` — browser-safe UI message types, schemas, and model catalog
27
+ - `@womp/spark-agent/client` — `SparkChatTransport` and HTTP client types
28
+ - `@womp/spark-agent/server` — run service, store interfaces, executor, and development stores
29
+ - `@womp/spark-agent/express` — mountable Express 5 router
22
30
 
23
- Requirements:
31
+ The root, `/browser`, `/ui`, `/capabilities`, and `/client` entry points do not import QuickJS,
32
+ Kakapo, Express, or React at runtime.
24
33
 
25
- - Node.js 20 or newer
26
- - `D:/Womp/kakapo/kakapo_app.exe` listening on `ws://127.0.0.1:5502`
27
- - `VITE_OPENAI_API_KEY` or `VITE_ANTHROPIC_API_KEY` in the repository root `.env`, or a key entered in Runtime settings
34
+ ## Running in a host application
35
+
36
+ `runSparkAgent` accepts a configured model, model messages, an executor, a capability composition,
37
+ and an artifact resolver. It exposes exactly `read_skill` and `execute_javascript` to the model.
38
+ Skills carry instructions, declarations, and JavaScript examples. The native executor runs in the
39
+ page realm; it is not a sandbox and cannot interrupt a synchronous infinite loop.
40
+
41
+ Compose only supported capabilities with `composeCapabilities({ scene, account, ... })`. Each
42
+ capability supplies its skills and `createApi(context)`; the returned API is bound under `womp`.
43
+ Every invocation receives a cancellation signal and an awaited `recordReceipt` hook. Capabilities
44
+ own their transactions and must check cancellation at their commit boundary.
45
+
46
+ For a real user interaction, call `context.waitForUser(label, async signal => ...)` outside mutation
47
+ locks. The run stays active with `requires_action` progress and resumes the same invocation after
48
+ input. Native and QuickJS executors exclude this wait from their execution budget; service work
49
+ continues to consume time, and QuickJS guest computation still counts even if an interaction was
50
+ not awaited. Abort settles the wait and late answers cannot revive it. The UI host must also reject
51
+ competing requests for a shared dialog and match callbacks to the original interaction identity.
52
+ Custom executors must honor the optional host-owned `userWait` argument to `execute`.
53
+
54
+ Persist the user message before starting a run. Supply `persistence.beforeToolCall`,
55
+ `persistence.recordReceipt`, and `persistence.afterToolCall` for awaited storage barriers.
56
+ Supply `persistence.saveMessage` to save the canonical UI message at each model-step boundary and
57
+ at termination, including reasoning and provider metadata. Spark awaits each checkpoint before the
58
+ next model request. Consume the run's stream while awaiting its result; the result settles after
59
+ the terminal checkpoint. A host run owner must keep consuming when a view detaches.
60
+ A failed barrier aborts the loop. The default model-step limit is 100; a limit returns
61
+ `status: "incomplete"`. A host must not automatically restart to bypass that limit.
62
+
63
+ Before each model request Spark applies an estimated input budget (`maxInputTokens`, default 64,000).
64
+ It first removes duplicate skill bodies and execution observations, then abbreviates older skill reads
65
+ while retaining the latest workflow/reference pair. The agent must read an abbreviated skill again
66
+ before using its API. Older completed scripts can be shortened only when their committed receipts and
67
+ results remain available and their inputs are not tied to provider reasoning/signatures. Requests,
68
+ tool pairs, targets, artifacts, receipts, errors, and unresolved work remain in context; persisted
69
+ history is never shortened. If this cannot fit, the run returns `incomplete` with `context-limit` and
70
+ an actionable explanation, without another model request or automatic replay.
71
+
72
+ When older successful execution results contain images, their binary content can be omitted from model
73
+ input while preserving artifact references, receipts, and observations. The latest visual result,
74
+ user-provided media, failed/uncertain results, and provider-owned content remain intact. The agent can
75
+ inspect an older artifact again with `emitImage` or `emitFile`; stored history retains the full result.
76
+ Call metadata copied by the SDK onto local tool results is preserved during this trimming; it does not
77
+ prevent compaction of the host-produced image bytes. Original model calls and signatures are unchanged.
78
+
79
+ Token sizing is approximate (UTF-8 text bytes / 3 plus an 8,192-token allowance per image/file and
80
+ 2,048 for tool schemas/framing). This is an application input budget, not provider capacity metadata.
81
+ Hosts should choose it alongside the selected model's output budget and verify their deployed models;
82
+ the estimate cannot guarantee a provider accepts every document or image size.
83
+
84
+ Screenshot and file APIs return serializable artifact references. `emitImage` and `emitFile` resolve
85
+ them through the host's artifact resolver. Keep references resolvable when reloading history, and
86
+ pass `createSparkTools(...)` to AI SDK's `convertToModelMessages` to reconstruct multimodal results.
87
+ Kakapo skill declarations are generated from its actual typed API during the build and packaged as
88
+ JavaScript strings; they do not need filesystem or Markdown loading in the browser.
89
+
90
+ ## Local frontend
91
+
92
+ `LocalSparkChatTransport` accepts a host callback returning a `SparkAgentRun` from `runSparkAgent`.
93
+ The callback receives the standard AI SDK chat request, including its messages and abort signal.
94
+ It persists the initiating message, resolves the model and capabilities, and starts the shared loop.
95
+ Keep ownership of the active run outside the React renderer. Local browser runs end when the page
96
+ closes; `reconnectToStream` returns `null`.
97
+
98
+ ## Remote frontend
99
+
100
+ ```tsx
101
+ import { useChat } from "@ai-sdk/react";
102
+ import { SparkChatTransport } from "@womp/spark-agent/client";
103
+ import {
104
+ sparkDataPartSchemas,
105
+ sparkMessageMetadataSchema,
106
+ type SparkUIMessage,
107
+ } from "@womp/spark-agent/ui";
108
+
109
+ const transport = new SparkChatTransport({ api: "/agent" });
110
+
111
+ const chat = useChat<SparkUIMessage>({
112
+ id: conversationId,
113
+ messages: initialMessages,
114
+ transport,
115
+ resume: true,
116
+ messageMetadataSchema: sparkMessageMetadataSchema,
117
+ dataPartSchemas: sparkDataPartSchemas,
118
+ });
119
+ ```
120
+
121
+ Render `message.parts`. Standard AI SDK parts represent text, reasoning, files, tool inputs, tool
122
+ outputs, approvals, and step boundaries. Spark adds typed `data-console`, `data-artifact`,
123
+ `data-run-status`, `data-step-metrics`, and `data-execution-receipt` parts. Receipts are emitted before
124
+ their storage barrier, keeping known effects visible even when saving the tool result fails.
125
+
126
+ An explicit Stop action must cancel the durable run before stopping local observation:
127
+
128
+ ```ts
129
+ await transport.cancelRun(conversationId);
130
+ await chat.stop();
131
+ ```
132
+
133
+ Closing or reloading the page only detaches the SSE subscriber. It does not cancel the run.
134
+
135
+ ## HTTP and SSE
136
+
137
+ `SparkChatTransport` hides the durable run lifecycle from `useChat`:
138
+
139
+ ```text
140
+ POST /agent/conversations/:conversationId/messages
141
+ GET /agent/runs/:runId/stream?after=0
142
+ POST /agent/runs/:runId/cancel
143
+ ```
144
+
145
+ The SSE response contains ordered persistence envelopes around standard AI SDK chunks:
146
+
147
+ ```ts
148
+ type StoredSparkChunk = {
149
+ sequence: number;
150
+ conversationId: string;
151
+ runId: string;
152
+ createdAt: string;
153
+ chunk: SparkUIMessageChunk;
154
+ };
155
+ ```
156
+
157
+ The transport unwraps each envelope and returns the contained `UIMessageChunk` to `useChat`.
158
+ Active assistant messages are replayed from sequence zero when reconnecting because `useChat`
159
+ reconstructs the in-progress message from the resumed stream.
160
+
161
+ ## Embedding in an Express backend
162
+
163
+ Spark does not call `listen()` when imported. The host owns its HTTP server and mounts the router:
164
+
165
+ ```ts
166
+ import { createSparkAgentRouter } from "@womp/spark-agent/express";
167
+ import { SparkAgentService, createSparkRunExecutor } from "@womp/spark-agent/server";
168
+
169
+ const service = new SparkAgentService({
170
+ store,
171
+ executeRun: createSparkRunExecutor({
172
+ resolveModel,
173
+ createHost,
174
+ }),
175
+ });
176
+
177
+ app.use(
178
+ "/agent",
179
+ userAccess,
180
+ createSparkAgentRouter({
181
+ service,
182
+ artifactStore,
183
+ resolveOwnerId: (request) => request.user.id,
184
+ }),
185
+ );
186
+ ```
187
+
188
+ `MemorySparkAgentStore` and `MemorySparkArtifactStore` are development implementations. Production
189
+ hosts must supply durable implementations backed by their database/object storage and must preserve
190
+ the ordering contract of `appendRunChunk()`.
191
+
192
+ ## Standalone development server
193
+
194
+ The package includes a local server bound to `127.0.0.1:8787`:
28
195
 
29
196
  ```bash
30
- yarn install
31
- yarn dev
197
+ spark-agent
32
198
  ```
33
199
 
34
- Open `http://127.0.0.1:5173`.
200
+ Configure the process with:
201
+
202
+ - `OPENAI_API_KEY`
203
+ - `ANTHROPIC_API_KEY`
204
+ - `KAKAPO_URL` (defaults to `ws://127.0.0.1:5502`)
205
+ - `PORT` (defaults to `8787`)
206
+
207
+ The CLI automatically loads `.env` from its working directory when the file exists. Copy
208
+ `.env.example` to `.env`, then add the provider key you intend to use. Existing process environment
209
+ variables take precedence over values loaded from the file.
210
+
211
+ For repository development, `yarn dev` starts the Express server and Vite demo together. Open
212
+ `http://127.0.0.1:5173`.
213
+
214
+ For the explicit fictional account profile, use `yarn dev:demo-account` or
215
+ `spark-agent --profile demo-account`. It adds the `account` skill and `womp.account.read`
216
+ beside the real local Kakapo scene API. Profile reads identify themselves as fictional fixtures;
217
+ credits, billing, orders, and other account services report unavailable. The default composition
218
+ omits account entirely. Neither profile supplies fake generation jobs, imports, or billing permission.
219
+ Embedded development servers can select `developmentProfile: "demo-account"` explicitly.
220
+
221
+ ## Run cost estimates
35
222
 
36
- ## Browser workspace
223
+ Prompt caching is enabled for every listed model: Claude Opus 5 and Fable 5 use
224
+ automatic 5-minute caching, and GPT-6 Astra uses implicit caching with a 30-minute TTL.
225
+ The providers manage the cache as message history grows across tool steps; no local
226
+ response cache is used. Cache hits require matching prefixes, sufficient prompt length,
227
+ and an unexpired entry. Cache writes can cost more than uncached input, while subsequent
228
+ cache reads are cheaper. The UI displays actual reported reads/writes, not assumed savings.
229
+ See [Claude caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching)
230
+ and [OpenAI caching](https://developers.openai.com/api/docs/guides/prompt-caching).
231
+ Restart the server after changing these settings; existing runs keep their original configuration.
37
232
 
38
- The workspace provides:
233
+ The chat displays estimated API token cost in USD, updated after every completed model step.
234
+ Hover or focus the amount to inspect uncached input, cache reads/writes, and output costs. Output usage
235
+ already includes reasoning tokens. Image input is included in the provider's input token count.
39
236
 
40
- - local threads with search, fork, and delete actions;
41
- - model and reasoning controls;
42
- - pasted and uploaded reference images;
43
- - streamed assistant messages and reasoning summaries;
44
- - formatted JavaScript execution and result traces;
45
- - native Kakapo screenshots inline with the execution timeline.
237
+ `src/pricing.ts` contains standard direct API rates verified on September 9, 2026:
46
238
 
47
- Threads and images are stored in IndexedDB. Model and runtime preferences use browser storage. An API
48
- key entered in Runtime settings is kept in session storage and is not stored with threads.
239
+ | Model | Input / 1M | Cache read / 1M | Cache write / 1M | Output / 1M |
240
+ | -------------- | ---------- | --------------- | --------------------- | ----------- |
241
+ | GPT-6 Astra | $10 | $1 | $12.50 | $50 |
242
+ | Claude Opus 5 | $5 | $0.50 | $6.25 (5m), $10 (1h) | $25 |
243
+ | Claude Fable 5 | $10 | $1 | $12.50 (5m), $20 (1h) | $50 |
49
244
 
50
- ## Core package
245
+ Astra requests above 272,000 input tokens use 2x input/cache rates and 1.5x output rates.
246
+ This threshold is applied to each request before summing run costs. Claude's full context uses
247
+ standard rates. Sources: [Astra pricing](https://developers.openai.com/api/docs/models/gpt-6-astra),
248
+ [Claude pricing](https://platform.claude.com/docs/en/about-claude/pricing).
51
249
 
52
- The environment-neutral agent is under `src/`. It accepts a language model, a scene runtime, a
53
- JavaScript executor, byte-based images, and an event sink. The browser supplies those dependencies in
54
- `web/src/api.ts`; a server can supply its own credentials, isolated executor, and durable event sink
55
- without importing React or browser storage.
250
+ Each `data-step-metrics` part stores a `cost` snapshot with the model, rate date, source, token
251
+ categories, rates, and amounts. The UI sums those stored amounts, so reconnection does not double
252
+ count steps and future price changes do not reprice recorded runs. Update the rate table and its
253
+ verification date when provider pricing changes.
56
254
 
57
- ## Agent execution
255
+ The unfinished step is excluded until its usage arrives. Cancelled/failed runs show a partial
256
+ estimate. Missing usage, unknown models, missing cache TTLs, or provider sub-inferences without
257
+ separate attribution are marked unavailable, never silently priced as zero. Historical runs
258
+ without step pricing remain unavailable. Estimates exclude taxes, negotiated discounts, and scene
259
+ hosting; the provider bill is authoritative. Spark requests OpenAI's standard service tier.
58
260
 
59
- The model has two tools:
261
+ ## Execution security
60
262
 
61
- - `executeJavaScript` runs code against the scoped `@womp/kakapo-sdk` facade;
62
- - `screenshot` moves Kakapo's native camera, frames a target bounding box, and returns the rendered
63
- image to the model.
263
+ The standalone host uses a fresh QuickJS runtime for each JavaScript execution. It has no Node.js
264
+ or browser globals and receives only the composed capability APIs. Imports, filesystem access,
265
+ network APIs, and host environment variables are not exposed. QuickJS limits memory, stack size,
266
+ execution time, source size, host calls, and data crossing the host bridge. Browser hosts can instead
267
+ choose native page execution, with the page-global access and interruption limitations described above.
64
268
 
65
- Node, material, transform, inspection, and refresh operations are SDK calls made from JavaScript.
66
- The private build root is runtime state and is not exposed as a generated-code variable.
269
+ QuickJS isolates generated code from the JavaScript host API; it is not an operating-system security
270
+ boundary. Multi-tenant deployments must additionally isolate workers, authorize every Kakapo
271
+ session and tool call, enforce quotas, and avoid passing privileged functions through the runtime
272
+ bridge.
67
273
 
68
274
  ## Validation
69
275
 
70
276
  ```bash
71
277
  yarn build
72
278
  yarn typecheck
73
- yarn lint
74
279
  yarn test
75
280
  yarn web:build
76
281
  ```
77
282
 
283
+ ## Release procedure
284
+
285
+ Releases use a manual package publication; no separate release service is required.
286
+
287
+ ### Migration to 0.3
288
+
289
+ - The package root is browser-safe. Import `KakapoRuntime`, `createWompSceneApi`, and its enums
290
+ from `/kakapo`, and `QuickJSJavaScriptExecutor` from `/quickjs`.
291
+ - `runSparkAgent` takes the host's selected model, executor, capability composition, artifact
292
+ resolver, and persistence hooks. The host owns connection setup and disposal. The model sees
293
+ only `read_skill` and `execute_javascript`; domain methods live under the supplied `womp` APIs.
294
+ - Replace fixed scene/screenshot tool history with the host's history adapter. Use
295
+ `convertSparkMessages` when rebuilding model input from current Spark UI messages so artifact
296
+ references become model-visible content. Preserve old records; do not replay historical tools.
297
+ - Custom server executors receive `uiMessages` and convert them using their actual capability
298
+ tools. `SparkRunExecutionContext.modelMessages` has been removed.
299
+ - Custom JavaScript executors must honor cancellation and host-owned user waits. Callback-based
300
+ scene edits and artifact references work with both the native and QuickJS executors.
301
+
302
+ ### Publishing
303
+
304
+ 1. Choose an unused package version after checking `npm view @womp/spark-agent versions --json`.
305
+ Update `package.json` and record public API changes and migration notes. Use a new minor version
306
+ for incompatible changes while the package is below 1.0.
307
+ 2. On a supported Node version, run `yarn install --frozen-lockfile`, `yarn typecheck`, `yarn test`,
308
+ and `yarn web:build`. Do not bypass dependency engine checks. Commit the release changes and
309
+ record the commit used to build the package.
310
+ 3. Run `yarn pack --filename spark-agent-release.tgz`. Inspect the archive contents and install
311
+ that archive in the consuming application. Verify packaged declarations and skills, browser
312
+ import boundaries, the production build, and the applicable integration cases without source
313
+ aliases. Keep the archive outside Git and do not rebuild or change it after verification.
314
+ 4. Publish the verified archive with `npm publish ./spark-agent-release.tgz --access public`.
315
+ If the response is uncertain, inspect the registry's version and integrity before retrying.
316
+ Verify the published version and archive integrity, then tag the recorded commit as `v<version>`
317
+ and push the release commit and tag. An already published version cannot be replaced; corrections
318
+ need a new version.
319
+ 5. In the consuming application, use `yarn add @womp/spark-agent@<version> --exact`. Commit its
320
+ manifest and lockfile together, and verify a clean frozen-lockfile installation and production
321
+ build. Remove the temporary archive dependency. Application deployment and merge requirements
322
+ remain separate from package publication.
323
+
78
324
  ## Layout
79
325
 
80
- - `src/agent.ts` — environment-neutral model loop and tool orchestration
81
- - `src/runtime.ts` — Kakapo scene runtime and atomic JavaScript transactions
82
- - `src/womp-scene-api.ts` — Womp-compatible scene API
83
- - `src/prompt.ts` — JavaScript agent instructions and SDK reference
84
- - `src/coordinates.ts` — Womp basis, units, rotations, and goop conversion
85
- - `web/src/api.ts` — browser model, image, runtime, and event adapters
86
- - `web/src/browser-executor.ts` — local generated-JavaScript executor
87
- - `web/src/App.tsx` — local chat, persistence, traces, screenshots, and streaming UI
326
+ - `src/agent.ts` — AI SDK stream and Spark tool orchestration
327
+ - `src/ui.ts` — browser-safe protocol types and validation schemas
328
+ - `src/client.ts` — durable `ChatTransport` implementation
329
+ - `src/server/` — service, storage contracts, Express adapter, artifacts, and standalone composition
330
+ - `src/runtime.ts` — Kakapo scene connections and edit transactions
331
+ - `src/quickjs-executor.ts` — isolated JavaScript execution and host bridge
332
+ - `src/womp-scene-api.ts` — Womp-compatible Kakapo scene API
333
+ - `web/src/App.tsx` — reference `useChat<SparkUIMessage>` application
@@ -0,0 +1,30 @@
1
+ import { type Tool } from "ai";
2
+ import type { ExecutionReceipt, SparkArtifactResolver, SparkCapabilities } from "./capabilities.js";
3
+ import type { JavaScriptExecutor } from "./executor.js";
4
+ import type { SparkUIMessage, SparkUIMessageChunk, SparkUITools } from "./ui.js";
5
+ export type SparkToolCall = {
6
+ id: string;
7
+ name: "read_skill" | "execute_javascript";
8
+ input: unknown;
9
+ };
10
+ export interface SparkPersistence {
11
+ beforeToolCall(call: SparkToolCall): Promise<void>;
12
+ recordReceipt(callId: string, receipt: ExecutionReceipt): Promise<void>;
13
+ afterToolCall(call: SparkToolCall, output: unknown): Promise<void>;
14
+ /** Canonical UI snapshot, awaited at each model step and at run termination. */
15
+ saveMessage?(message: SparkUIMessage): Promise<void>;
16
+ }
17
+ export type SparkToolOptions = {
18
+ runId: string;
19
+ capabilities: SparkCapabilities;
20
+ executor: JavaScriptExecutor;
21
+ artifacts: SparkArtifactResolver;
22
+ controller: AbortController;
23
+ persistence?: SparkPersistence;
24
+ executionTimeoutMs?: number;
25
+ write(chunk: SparkUIMessageChunk): void;
26
+ };
27
+ export type SparkTools = {
28
+ [Name in keyof SparkUITools]: Tool<SparkUITools[Name]["input"], SparkUITools[Name]["output"]>;
29
+ };
30
+ export declare function createSparkTools(options: SparkToolOptions): SparkTools;
@@ -0,0 +1,189 @@
1
+ import { tool } from "ai";
2
+ import { z } from "zod";
3
+ import { UserWait } from "./execution-lifetime.js";
4
+ function errorMessage(error) {
5
+ return error instanceof Error ? error.message : String(error);
6
+ }
7
+ function jsonValue(value) {
8
+ const json = JSON.stringify(value);
9
+ if (json === undefined)
10
+ return null;
11
+ if (new TextEncoder().encode(json).byteLength > 1024 * 1024) {
12
+ throw new Error("Output exceeded the 1048576 byte limit. Filter the result before printing it.");
13
+ }
14
+ return JSON.parse(json);
15
+ }
16
+ const artifactRefSchema = z.object({
17
+ id: z.string().min(1),
18
+ mediaType: z.string().min(1),
19
+ name: z.string().optional(),
20
+ });
21
+ export function createSparkTools(options) {
22
+ const { controller, persistence } = options;
23
+ const persist = async (action) => {
24
+ if (action === undefined)
25
+ return;
26
+ try {
27
+ await action();
28
+ }
29
+ catch (error) {
30
+ // A failed storage barrier must stop the loop, rather than become a retryable tool error.
31
+ controller.abort(error);
32
+ throw error;
33
+ }
34
+ };
35
+ const execute = async (call, action) => {
36
+ controller.signal.throwIfAborted();
37
+ await persist(persistence && (() => persistence.beforeToolCall(call)));
38
+ controller.signal.throwIfAborted();
39
+ const output = await action();
40
+ await persist(persistence && (() => persistence.afterToolCall(call, output)));
41
+ controller.signal.throwIfAborted();
42
+ return output;
43
+ };
44
+ return {
45
+ read_skill: tool({
46
+ description: "Read a skill from the available directory, including instructions, TypeScript API declarations, and JavaScript examples.",
47
+ inputSchema: z.object({ name: z.string().min(1).max(160) }),
48
+ execute: (input, { toolCallId }) => execute({ id: toolCallId, name: "read_skill", input }, async () => {
49
+ const skill = options.capabilities.skills.find(({ name }) => name === input.name);
50
+ if (skill === undefined) {
51
+ return {
52
+ ok: false,
53
+ error: `Skill unavailable: ${input.name}`,
54
+ available: options.capabilities.skills.map(({ name }) => name),
55
+ };
56
+ }
57
+ return { ok: true, ...skill };
58
+ }),
59
+ }),
60
+ execute_javascript: tool({
61
+ description: "Run an async JavaScript body against the APIs discovered through skills. Use print, emitImage, and emitFile for output. Each call has a fresh local scope; capabilities own their commit boundaries.",
62
+ inputSchema: z.object({
63
+ purpose: z.string().min(1).max(240),
64
+ code: z.string().min(1).max(60_000),
65
+ }),
66
+ execute: (input, { toolCallId }) => execute({ id: toolCallId, name: "execute_javascript", input }, async () => {
67
+ const invocation = new AbortController();
68
+ const signal = AbortSignal.any([controller.signal, invocation.signal]);
69
+ const userWait = new UserWait();
70
+ const logs = [];
71
+ const receipts = [];
72
+ const artifacts = [];
73
+ const pending = new Set();
74
+ let outputBytes = 0;
75
+ const track = (promise) => {
76
+ pending.add(promise);
77
+ // Registered writes are joined below even when the script omits await.
78
+ void promise.catch(() => undefined);
79
+ return promise;
80
+ };
81
+ const context = {
82
+ runId: options.runId,
83
+ toolCallId,
84
+ signal,
85
+ waitForUser: (label, action) => userWait.wait(signal, async () => {
86
+ context.reportStatus("requires_action", label);
87
+ try {
88
+ return await action(signal);
89
+ }
90
+ finally {
91
+ if (signal.aborted === false)
92
+ context.reportStatus("running", "Continuing after user input");
93
+ }
94
+ }),
95
+ recordReceipt: (receipt) => {
96
+ receipts.push(receipt);
97
+ options.write({
98
+ type: "data-execution-receipt",
99
+ id: receipt.id,
100
+ data: { toolCallId, receipt },
101
+ });
102
+ return track(persist(persistence && (() => persistence.recordReceipt(toolCallId, receipt))));
103
+ },
104
+ reportStatus: (status, label) => {
105
+ signal.throwIfAborted();
106
+ options.write({
107
+ type: "data-run-status",
108
+ data: { runId: options.runId, status, label },
109
+ });
110
+ },
111
+ };
112
+ const emit = (reference, kind) => track((async () => {
113
+ signal.throwIfAborted();
114
+ const ref = artifactRefSchema.parse(reference);
115
+ const { artifact } = await options.artifacts.resolve(ref);
116
+ signal.throwIfAborted();
117
+ if (kind === "image" && artifact.mediaType.startsWith("image/") === false) {
118
+ throw new Error(`Artifact ${ref.id} is not an image.`);
119
+ }
120
+ artifacts.push({ kind, artifact });
121
+ options.write({ type: "file", url: artifact.url, mediaType: artifact.mediaType });
122
+ })());
123
+ try {
124
+ const value = await options.executor.execute(input.code, {
125
+ womp: options.capabilities.createApi(context),
126
+ print: (...values) => {
127
+ signal.throwIfAborted();
128
+ const text = values
129
+ .map((value) => typeof value === "string" ? value : JSON.stringify(jsonValue(value)))
130
+ .join(" ");
131
+ outputBytes += new TextEncoder().encode(text).byteLength;
132
+ if (outputBytes > 1024 * 1024)
133
+ throw new Error("Printed output exceeded the 1048576 byte limit.");
134
+ logs.push(text);
135
+ options.write({ type: "data-console", data: { stream: "stdout", text } });
136
+ },
137
+ emitImage: (ref) => emit(ref, "image"),
138
+ emitFile: (ref) => emit(ref, "file"),
139
+ }, options.executionTimeoutMs ?? 60_000, signal, userWait);
140
+ await Promise.all(pending);
141
+ signal.throwIfAborted();
142
+ return {
143
+ version: 2,
144
+ ok: true,
145
+ purpose: input.purpose,
146
+ value: jsonValue(value),
147
+ logs,
148
+ receipts,
149
+ artifacts,
150
+ };
151
+ }
152
+ catch (error) {
153
+ invocation.abort(error);
154
+ await Promise.allSettled(pending);
155
+ return {
156
+ version: 2,
157
+ ok: false,
158
+ purpose: input.purpose,
159
+ value: null,
160
+ logs,
161
+ receipts,
162
+ artifacts,
163
+ error: errorMessage(error),
164
+ };
165
+ }
166
+ finally {
167
+ invocation.abort(new Error("JavaScript invocation ended."));
168
+ }
169
+ }),
170
+ toModelOutput: async ({ output }) => {
171
+ const images = await Promise.all(output.artifacts
172
+ .filter(({ kind }) => kind === "image")
173
+ .map(async ({ artifact }) => {
174
+ const resolved = await options.artifacts.resolve(artifact);
175
+ return {
176
+ type: "file",
177
+ data: { type: "data", data: resolved.data },
178
+ mediaType: resolved.artifact.mediaType,
179
+ filename: resolved.artifact.name,
180
+ };
181
+ }));
182
+ return {
183
+ type: "content",
184
+ value: [{ type: "text", text: JSON.stringify(output) }, ...images],
185
+ };
186
+ },
187
+ }),
188
+ };
189
+ }
package/dist/agent.d.ts CHANGED
@@ -1,11 +1,38 @@
1
- import { type LanguageModel } from "ai";
2
- import { type ModelProvider } from "./models.js";
3
- import type { SparkRunInput, SparkRuntime } from "./types.js";
1
+ import { streamText, type LanguageModel, type ModelMessage } from "ai";
2
+ import { type SparkPersistence } from "./agent-tools.js";
3
+ import type { SparkArtifactResolver, SparkCapabilities } from "./capabilities.js";
4
+ import type { JavaScriptExecutor } from "./executor.js";
5
+ import type { SparkUIMessageChunk } from "./ui.js";
6
+ export type SparkAgentResult = {
7
+ text: string;
8
+ steps: number;
9
+ usage: unknown;
10
+ status: "completed" | "incomplete";
11
+ finishReason: string;
12
+ };
4
13
  export type SparkAgentOptions = {
5
- input: SparkRunInput;
14
+ messages: ModelMessage[];
6
15
  model: LanguageModel;
7
16
  modelId: string;
8
- provider: ModelProvider;
9
- runtime: SparkRuntime;
17
+ providerOptions?: Parameters<typeof streamText>[0]["providerOptions"];
18
+ capabilities: SparkCapabilities;
19
+ executor: JavaScriptExecutor;
20
+ artifacts: SparkArtifactResolver;
21
+ runId: string;
22
+ messageId: string;
23
+ signal?: AbortSignal;
24
+ context?: string;
25
+ instructions?: string;
26
+ maxSteps?: number;
27
+ maxOutputTokens?: number;
28
+ /** Estimated input budget, including instructions and tool framing. Defaults to 64,000. */
29
+ maxInputTokens?: number;
30
+ executionTimeoutMs?: number;
31
+ persistence?: SparkPersistence;
32
+ prepareMessages?(messages: ModelMessage[]): Promise<ModelMessage[]>;
33
+ };
34
+ export type SparkAgentRun = {
35
+ stream: ReadableStream<SparkUIMessageChunk>;
36
+ result: Promise<SparkAgentResult>;
10
37
  };
11
- export declare function runSparkAgent(options: SparkAgentOptions): Promise<void>;
38
+ export declare function runSparkAgent(options: SparkAgentOptions): SparkAgentRun;