@womp/spark-agent 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +37 -19
  2. package/dist/agent.js +1 -1
  3. package/dist/capabilities/scene-draft.d.ts +2 -404
  4. package/dist/capabilities/scene.d.ts +1 -1
  5. package/dist/capabilities/scene.js +13 -4
  6. package/dist/cli.js +19 -2
  7. package/dist/client.js +15 -15
  8. package/dist/context.d.ts +1 -1
  9. package/dist/context.js +6 -4
  10. package/dist/coordinates.d.ts +23 -0
  11. package/dist/coordinates.js +132 -0
  12. package/dist/generated/scene-declarations.d.ts +1 -1
  13. package/dist/generated/scene-declarations.js +1 -1
  14. package/dist/index.d.ts +2 -0
  15. package/dist/index.js +2 -0
  16. package/dist/kakapo.d.ts +4 -5
  17. package/dist/kakapo.js +2 -6
  18. package/dist/pricing.js +9 -29
  19. package/dist/runtime.d.ts +16 -36
  20. package/dist/runtime.js +132 -139
  21. package/dist/scene-environment.d.ts +25 -0
  22. package/dist/scene-environment.js +76 -0
  23. package/dist/scene-metadata.d.ts +6 -0
  24. package/dist/scene-metadata.js +65 -0
  25. package/dist/scene-operations.d.ts +47 -0
  26. package/dist/scene-operations.js +126 -0
  27. package/dist/sdk-scene-host.d.ts +309 -0
  28. package/dist/sdk-scene-host.js +201 -0
  29. package/dist/sdk-scene-screenshot.d.ts +7 -0
  30. package/dist/sdk-scene-screenshot.js +17 -0
  31. package/dist/server/demo-scene-materials.d.ts +3 -0
  32. package/dist/server/demo-scene-materials.js +18 -0
  33. package/dist/server/express.js +2 -4
  34. package/dist/server/fixtures/materials/matte-blue.json +14 -0
  35. package/dist/server/fixtures/materials/polished-copper.json +14 -0
  36. package/dist/server/index.d.ts +2 -1
  37. package/dist/server/index.js +2 -1
  38. package/dist/server/service.d.ts +4 -0
  39. package/dist/server/service.js +26 -2
  40. package/dist/server/sqlite-store.d.ts +29 -0
  41. package/dist/server/sqlite-store.js +200 -0
  42. package/dist/server/standalone.d.ts +5 -1
  43. package/dist/server/standalone.js +78 -21
  44. package/dist/server/store.js +3 -1
  45. package/dist/types.d.ts +1 -1
  46. package/dist/womp-scene-api.d.ts +283 -0
  47. package/dist/womp-scene-api.js +974 -0
  48. package/package.json +7 -9
  49. package/dist/kakapo-capability.d.ts +0 -45
  50. package/dist/kakapo-capability.js +0 -169
@@ -0,0 +1,18 @@
1
+ import { readFile } from "node:fs/promises";
2
+ /** Actual local material resources, explicitly labeled as development assets. */
3
+ export async function loadDemoSceneMaterials() {
4
+ const materials = new Map();
5
+ for (const filename of ["matte-blue.json", "polished-copper.json"]) {
6
+ const material = JSON.parse(await readFile(new URL(`./fixtures/materials/${filename}`, import.meta.url), "utf8"));
7
+ materials.set(material.name.toLowerCase(), material);
8
+ }
9
+ return {
10
+ superMaterialNames: [...materials.values()].map(({ name }) => name),
11
+ loadSuperMaterial: async (name) => {
12
+ const material = materials.get(name.trim().toLowerCase());
13
+ if (!material)
14
+ throw new Error(`Unknown development material: ${name}. Use listSuperMaterials() to see the local fixture catalog.`);
15
+ return { ...structuredClone(material), tier: 0, libraryId: -1 };
16
+ },
17
+ };
18
+ }
@@ -44,12 +44,10 @@ export function createSparkAgentRouter(options) {
44
44
  });
45
45
  router.post("/conversations", async (request, response) => {
46
46
  const ownerId = await resolveOwnerId(request);
47
- const body = z
48
- .object({
47
+ const body = z.object({
49
48
  id: z.string().min(1).optional(),
50
49
  title: z.string().max(200).optional(),
51
- })
52
- .parse(request.body ?? {});
50
+ }).parse(request.body ?? {});
53
51
  const conversation = await options.service.createConversation(ownerId, body);
54
52
  response.status(201).json({ conversation });
55
53
  });
@@ -0,0 +1,14 @@
1
+ {
2
+ "name": "Development: Matte Blue",
3
+ "resource": {
4
+ "data": {
5
+ "color.x": 0.08,
6
+ "color.y": 0.3,
7
+ "color.z": 0.8,
8
+ "roughness": 0.85,
9
+ "metalness": 0,
10
+ "index_of_refraction": 1.5
11
+ },
12
+ "shaders": []
13
+ }
14
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "name": "Development: Polished Copper",
3
+ "resource": {
4
+ "data": {
5
+ "color.x": 0.955,
6
+ "color.y": 0.638,
7
+ "color.z": 0.538,
8
+ "roughness": 0.18,
9
+ "metalness": 1,
10
+ "index_of_refraction": 1.5
11
+ },
12
+ "shaders": []
13
+ }
14
+ }
@@ -4,5 +4,6 @@ export { createSparkRunExecutor, type ResolvedSparkModel, type SparkRunExecutorO
4
4
  export { SparkAgentService, SparkServiceError } from "./service.js";
5
5
  export type { SubmitSparkMessageInput } from "./service.js";
6
6
  export { MemorySparkAgentStore } from "./store.js";
7
- export { createStandaloneSparkAgentApp, type StandaloneSparkAgentOptions } from "./standalone.js";
7
+ export { SqliteSparkStore } from "./sqlite-store.js";
8
+ export { createStandaloneSparkAgentApp, type StandaloneSparkAgentOptions, type StandaloneSparkAgentApp, } from "./standalone.js";
8
9
  export type { SparkAgentStore, SparkConversation, SparkConversationSummary, SparkRun, SparkRunExecutionContext, SparkRunExecutor, SparkRunSettings, } from "./types.js";
@@ -2,4 +2,5 @@ export { MemorySparkArtifactStore } from "./artifacts.js";
2
2
  export { createSparkRunExecutor, } from "./executor.js";
3
3
  export { SparkAgentService, SparkServiceError } from "./service.js";
4
4
  export { MemorySparkAgentStore } from "./store.js";
5
- export { createStandaloneSparkAgentApp } from "./standalone.js";
5
+ export { SqliteSparkStore } from "./sqlite-store.js";
6
+ export { createStandaloneSparkAgentApp, } from "./standalone.js";
@@ -17,6 +17,7 @@ export declare class SparkAgentService {
17
17
  private readonly executeRun;
18
18
  private readonly controllers;
19
19
  private readonly listeners;
20
+ private readonly executions;
20
21
  constructor(options: {
21
22
  store: SparkAgentStore;
22
23
  executeRun: SparkRunExecutor;
@@ -29,6 +30,9 @@ export declare class SparkAgentService {
29
30
  getConversation(ownerId: string, id: string): Promise<SparkConversation>;
30
31
  getRun(ownerId: string, id: string): Promise<SparkRun>;
31
32
  getActiveRun(ownerId: string, conversationId: string): Promise<SparkRun | undefined>;
33
+ /** The host must establish exclusive ownership before recovering abandoned runs. */
34
+ recoverInterruptedRun(runId: string): Promise<void>;
35
+ close(): Promise<void>;
32
36
  submitMessage(input: SubmitSparkMessageInput): Promise<SparkRun>;
33
37
  cancelRun(ownerId: string, runId: string): Promise<SparkRun>;
34
38
  streamRun(ownerId: string, runId: string, afterSequence: number, signal: AbortSignal): AsyncGenerator<StoredSparkChunk>;
@@ -68,6 +68,7 @@ export class SparkAgentService {
68
68
  executeRun;
69
69
  controllers = new Map();
70
70
  listeners = new Map();
71
+ executions = new Set();
71
72
  constructor(options) {
72
73
  this.store = options.store;
73
74
  this.executeRun = options.executeRun;
@@ -111,6 +112,24 @@ export class SparkAgentService {
111
112
  return undefined;
112
113
  return run;
113
114
  }
115
+ /** The host must establish exclusive ownership before recovering abandoned runs. */
116
+ async recoverInterruptedRun(runId) {
117
+ if (this.controllers.has(runId))
118
+ throw new Error("Cannot recover a live run");
119
+ const run = await this.store.getRun(runId);
120
+ if (!run || (run.status !== "queued" && run.status !== "running"))
121
+ return;
122
+ const conversation = await this.store.getConversation(run.conversationId);
123
+ if (!conversation)
124
+ throw new Error(`Conversation missing for run ${runId}`);
125
+ await this.appendStatus(run, "incomplete");
126
+ await this.finishRun(run, conversation, "incomplete");
127
+ }
128
+ async close() {
129
+ for (const controller of this.controllers.values())
130
+ controller.abort(new Error("Standalone host is shutting down"));
131
+ await Promise.all([...this.executions]);
132
+ }
114
133
  async submitMessage(input) {
115
134
  const conversation = await this.getConversation(input.ownerId, input.conversationId);
116
135
  const activeRun = conversation.activeRunId === undefined
@@ -178,7 +197,11 @@ export class SparkAgentService {
178
197
  await this.appendStatus(run, "queued");
179
198
  const controller = new AbortController();
180
199
  this.controllers.set(run.id, controller);
181
- void this.runInBackground(run, conversation, controller);
200
+ const execution = this.runInBackground(run, conversation, controller);
201
+ this.executions.add(execution);
202
+ void execution.finally(() => this.executions.delete(execution)).catch((error) => {
203
+ console.error("Spark run persistence failed", error);
204
+ });
182
205
  return run;
183
206
  }
184
207
  async cancelRun(ownerId, runId) {
@@ -340,7 +363,8 @@ export class SparkAgentService {
340
363
  else
341
364
  conversation.messages.push(assistant);
342
365
  }
343
- conversation.activeRunId = undefined;
366
+ if (conversation.activeRunId === run.id)
367
+ conversation.activeRunId = undefined;
344
368
  conversation.updatedAt = completedAt;
345
369
  await this.store.saveConversation(conversation);
346
370
  await this.store.saveRun({
@@ -0,0 +1,29 @@
1
+ import type { ExecutionScreenshot } from "../types.js";
2
+ import type { SparkArtifact, StoredSparkChunk } from "../ui.js";
3
+ import type { SparkArtifactStore, StoredSparkArtifact } from "./artifacts.js";
4
+ import type { SceneOperation, SceneOperationStore } from "../scene-operations.js";
5
+ import type { SparkAgentStore, SparkConversation, SparkConversationSummary, SparkRun } from "./types.js";
6
+ /** Local development storage. Execution ownership belongs to the host service. */
7
+ export declare class SqliteSparkStore implements SparkAgentStore, SparkArtifactStore, SceneOperationStore {
8
+ private readonly artifactBaseUrl;
9
+ private readonly database;
10
+ private ownershipToken;
11
+ constructor(path: string, artifactBaseUrl?: string);
12
+ close(): void;
13
+ claimExecutionOwnership(): void;
14
+ listInterruptedRuns(): Promise<SparkRun[]>;
15
+ getSceneOperation(targetKey: string, id: string): Promise<SceneOperation | undefined>;
16
+ createSceneOperation(operation: SceneOperation): Promise<boolean>;
17
+ saveSceneOperation(operation: SceneOperation): Promise<SceneOperation>;
18
+ createConversation(value: SparkConversation): Promise<void>;
19
+ getConversation(id: string): Promise<SparkConversation | undefined>;
20
+ listConversations(ownerId: string): Promise<SparkConversationSummary[]>;
21
+ saveConversation(value: SparkConversation): Promise<void>;
22
+ createRun(value: SparkRun): Promise<void>;
23
+ getRun(id: string): Promise<SparkRun | undefined>;
24
+ saveRun(value: SparkRun): Promise<void>;
25
+ appendRunChunk(runId: string, conversationId: string, chunk: StoredSparkChunk["chunk"]): Promise<StoredSparkChunk>;
26
+ listRunChunks(runId: string, afterSequence: number): Promise<StoredSparkChunk[]>;
27
+ write(ownerId: string, image: ExecutionScreenshot): Promise<SparkArtifact>;
28
+ get(ownerId: string, id: string): Promise<StoredSparkArtifact | undefined>;
29
+ }
@@ -0,0 +1,200 @@
1
+ import { mkdirSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import { DatabaseSync } from "node:sqlite";
4
+ const completedSceneOperationLimit = 128;
5
+ /** Local development storage. Execution ownership belongs to the host service. */
6
+ export class SqliteSparkStore {
7
+ artifactBaseUrl;
8
+ database;
9
+ ownershipToken;
10
+ constructor(path, artifactBaseUrl = "/agent/artifacts") {
11
+ this.artifactBaseUrl = artifactBaseUrl;
12
+ mkdirSync(dirname(path), { recursive: true });
13
+ this.database = new DatabaseSync(path);
14
+ const version = this.database.prepare("PRAGMA user_version").get()?.user_version;
15
+ if (version !== 0 && version !== 1 && version !== 2 && version !== 3) {
16
+ this.database.close();
17
+ throw new Error(`Unsupported Spark database version: ${version}`);
18
+ }
19
+ this.database.exec(`
20
+ PRAGMA busy_timeout = 5000;
21
+ PRAGMA journal_mode = WAL;
22
+ PRAGMA synchronous = FULL;
23
+ PRAGMA foreign_keys = ON;
24
+ CREATE TABLE IF NOT EXISTS conversations (
25
+ id TEXT PRIMARY KEY, owner_id TEXT NOT NULL, updated_at TEXT NOT NULL, data TEXT NOT NULL
26
+ );
27
+ CREATE INDEX IF NOT EXISTS conversation_owner ON conversations(owner_id, updated_at);
28
+ CREATE TABLE IF NOT EXISTS runs (
29
+ id TEXT PRIMARY KEY, conversation_id TEXT NOT NULL, data TEXT NOT NULL
30
+ );
31
+ CREATE TABLE IF NOT EXISTS chunks (
32
+ run_id TEXT NOT NULL REFERENCES runs(id), sequence INTEGER NOT NULL, data TEXT NOT NULL,
33
+ PRIMARY KEY (run_id, sequence)
34
+ );
35
+ CREATE TABLE IF NOT EXISTS artifacts (
36
+ id TEXT PRIMARY KEY, owner_id TEXT NOT NULL, metadata TEXT NOT NULL, bytes BLOB NOT NULL
37
+ );
38
+ CREATE TABLE IF NOT EXISTS execution_owner (
39
+ singleton INTEGER PRIMARY KEY CHECK (singleton = 1), pid INTEGER NOT NULL, token TEXT NOT NULL
40
+ );
41
+ CREATE TABLE IF NOT EXISTS scene_operations (
42
+ target_key TEXT NOT NULL, id TEXT NOT NULL, revision INTEGER NOT NULL, data TEXT NOT NULL,
43
+ PRIMARY KEY (target_key, id)
44
+ );
45
+ PRAGMA user_version = 3;
46
+ `);
47
+ }
48
+ close() {
49
+ if (this.ownershipToken) {
50
+ this.database.prepare("DELETE FROM execution_owner WHERE token = ?").run(this.ownershipToken);
51
+ this.ownershipToken = undefined;
52
+ }
53
+ this.database.close();
54
+ }
55
+ claimExecutionOwnership() {
56
+ if (this.ownershipToken)
57
+ return;
58
+ this.database.exec("BEGIN IMMEDIATE");
59
+ try {
60
+ const owner = this.database.prepare("SELECT pid FROM execution_owner WHERE singleton = 1").get();
61
+ if (owner) {
62
+ let alive = true;
63
+ try {
64
+ process.kill(Number(owner.pid), 0);
65
+ }
66
+ catch (error) {
67
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ESRCH")
68
+ throw error;
69
+ alive = false;
70
+ }
71
+ if (alive)
72
+ throw new Error(`Spark storage is already owned by process ${owner.pid}`);
73
+ }
74
+ const token = crypto.randomUUID();
75
+ this.database.prepare("INSERT OR REPLACE INTO execution_owner VALUES (1, ?, ?)")
76
+ .run(process.pid, token);
77
+ this.database.exec("COMMIT");
78
+ this.ownershipToken = token;
79
+ }
80
+ catch (error) {
81
+ this.database.exec("ROLLBACK");
82
+ throw error;
83
+ }
84
+ }
85
+ async listInterruptedRuns() {
86
+ if (!this.ownershipToken)
87
+ throw new Error("Claim execution ownership before recovering runs");
88
+ return this.database.prepare("SELECT data FROM runs WHERE json_extract(data, '$.status') IN ('queued', 'running')").all().map((row) => JSON.parse(String(row.data)));
89
+ }
90
+ async getSceneOperation(targetKey, id) {
91
+ const row = this.database.prepare("SELECT data FROM scene_operations WHERE target_key = ? AND id = ?").get(targetKey, id);
92
+ return row ? JSON.parse(String(row.data)) : undefined;
93
+ }
94
+ async createSceneOperation(operation) {
95
+ const result = this.database.prepare("INSERT OR IGNORE INTO scene_operations VALUES (?, ?, ?, ?)").run(operation.targetKey, operation.id, operation.revision, JSON.stringify(operation));
96
+ return result.changes === 1;
97
+ }
98
+ async saveSceneOperation(operation) {
99
+ const next = { ...operation, revision: operation.revision + 1 };
100
+ this.database.exec("BEGIN IMMEDIATE");
101
+ try {
102
+ const result = this.database.prepare("UPDATE scene_operations SET revision = ?, data = ? WHERE target_key = ? AND id = ? AND revision = ?").run(next.revision, JSON.stringify(next), operation.targetKey, operation.id, operation.revision);
103
+ if (result.changes !== 1)
104
+ throw new Error("Scene operation changed concurrently or is missing");
105
+ if (next.status === "committed" || next.status === "rolled_back") {
106
+ this.database.prepare(`
107
+ DELETE FROM scene_operations WHERE rowid IN (
108
+ SELECT rowid FROM scene_operations
109
+ WHERE target_key = ? AND json_extract(data, '$.status') IN ('committed', 'rolled_back')
110
+ ORDER BY COALESCE(json_extract(data, '$.completedAt'), '') DESC
111
+ LIMIT -1 OFFSET ?
112
+ )
113
+ `).run(next.targetKey, completedSceneOperationLimit);
114
+ }
115
+ this.database.exec("COMMIT");
116
+ return next;
117
+ }
118
+ catch (error) {
119
+ this.database.exec("ROLLBACK");
120
+ throw error;
121
+ }
122
+ }
123
+ async createConversation(value) {
124
+ this.database.prepare("INSERT INTO conversations VALUES (?, ?, ?, ?)")
125
+ .run(value.id, value.ownerId, value.updatedAt, JSON.stringify(value));
126
+ }
127
+ async getConversation(id) {
128
+ const row = this.database.prepare("SELECT data FROM conversations WHERE id = ?").get(id);
129
+ return row ? JSON.parse(String(row.data)) : undefined;
130
+ }
131
+ async listConversations(ownerId) {
132
+ return this.database.prepare("SELECT data FROM conversations WHERE owner_id = ? ORDER BY updated_at DESC").all(ownerId).map((row) => {
133
+ const { messages, ...conversation } = JSON.parse(String(row.data));
134
+ return { ...conversation, messageCount: messages.length };
135
+ });
136
+ }
137
+ async saveConversation(value) {
138
+ const result = this.database.prepare("UPDATE conversations SET owner_id = ?, updated_at = ?, data = ? WHERE id = ?").run(value.ownerId, value.updatedAt, JSON.stringify(value), value.id);
139
+ if (result.changes === 0)
140
+ throw new Error(`Conversation ${value.id} does not exist.`);
141
+ }
142
+ async createRun(value) {
143
+ this.database.prepare("INSERT INTO runs VALUES (?, ?, ?)")
144
+ .run(value.id, value.conversationId, JSON.stringify(value));
145
+ }
146
+ async getRun(id) {
147
+ const row = this.database.prepare("SELECT data FROM runs WHERE id = ?").get(id);
148
+ return row ? JSON.parse(String(row.data)) : undefined;
149
+ }
150
+ async saveRun(value) {
151
+ const result = this.database.prepare("UPDATE runs SET conversation_id = ?, data = ? WHERE id = ?").run(value.conversationId, JSON.stringify(value), value.id);
152
+ if (result.changes === 0)
153
+ throw new Error(`Run ${value.id} does not exist.`);
154
+ }
155
+ async appendRunChunk(runId, conversationId, chunk) {
156
+ this.database.exec("BEGIN IMMEDIATE");
157
+ try {
158
+ const run = this.database.prepare("SELECT conversation_id FROM runs WHERE id = ?").get(runId);
159
+ if (!run || run.conversation_id !== conversationId)
160
+ throw new Error("Run target does not match.");
161
+ const sequence = Number(this.database.prepare("SELECT COALESCE(MAX(sequence), 0) + 1 AS next FROM chunks WHERE run_id = ?").get(runId)?.next);
162
+ const stored = {
163
+ sequence, runId, conversationId, chunk: structuredClone(chunk), createdAt: new Date().toISOString(),
164
+ };
165
+ this.database.prepare("INSERT INTO chunks VALUES (?, ?, ?)")
166
+ .run(runId, sequence, JSON.stringify(stored));
167
+ this.database.exec("COMMIT");
168
+ return stored;
169
+ }
170
+ catch (error) {
171
+ this.database.exec("ROLLBACK");
172
+ throw error;
173
+ }
174
+ }
175
+ async listRunChunks(runId, afterSequence) {
176
+ if (!await this.getRun(runId))
177
+ throw new Error(`Run ${runId} does not exist.`);
178
+ return this.database.prepare("SELECT data FROM chunks WHERE run_id = ? AND sequence > ? ORDER BY sequence").all(runId, afterSequence).map((row) => JSON.parse(String(row.data)));
179
+ }
180
+ async write(ownerId, image) {
181
+ const id = crypto.randomUUID();
182
+ const artifact = {
183
+ id, url: `${this.artifactBaseUrl.replace(/\/$/u, "")}/${id}`,
184
+ mediaType: image.mediaType, name: `spark-${image.view}.jpg`,
185
+ width: image.width, height: image.height,
186
+ metadata: { view: image.view, targetId: image.targetId },
187
+ };
188
+ this.database.prepare("INSERT INTO artifacts VALUES (?, ?, ?, ?)")
189
+ .run(id, ownerId, JSON.stringify(artifact), image.data);
190
+ return artifact;
191
+ }
192
+ async get(ownerId, id) {
193
+ const row = this.database.prepare("SELECT metadata, bytes FROM artifacts WHERE id = ? AND owner_id = ?").get(id, ownerId);
194
+ if (!row)
195
+ return undefined;
196
+ if (!(row.bytes instanceof Uint8Array))
197
+ throw new Error(`Invalid artifact bytes: ${id}`);
198
+ return { ...JSON.parse(String(row.metadata)), ownerId, data: row.bytes.slice() };
199
+ }
200
+ }
@@ -5,5 +5,9 @@ export type StandaloneSparkAgentOptions = {
5
5
  kakapoUrl: string;
6
6
  apiBasePath?: string;
7
7
  developmentProfile?: "demo-account";
8
+ storagePath?: string;
8
9
  };
9
- export declare function createStandaloneSparkAgentApp(options: StandaloneSparkAgentOptions): Express;
10
+ export type StandaloneSparkAgentApp = Express & {
11
+ dispose(): Promise<void>;
12
+ };
13
+ export declare function createStandaloneSparkAgentApp(options: StandaloneSparkAgentOptions): Promise<StandaloneSparkAgentApp>;
@@ -1,37 +1,75 @@
1
1
  import { createAnthropic } from "@ai-sdk/anthropic";
2
2
  import { createOpenAI } from "@ai-sdk/openai";
3
+ import { createHash } from "node:crypto";
3
4
  import express from "express";
4
5
  import { getSparkModel, SPARK_MODELS } from "../models.js";
5
- import { KakapoRuntime } from "../runtime.js";
6
+ import { KakapoAPI } from "@womp/kakapo-sdk";
7
+ import { captureSdkSceneScreenshot } from "../sdk-scene-screenshot.js";
6
8
  import { composeCapabilities, createAccountCapability, createSceneCapability, } from "../capabilities.js";
9
+ import { loadDemoSceneMaterials } from "./demo-scene-materials.js";
7
10
  import { createDemoAccountHost } from "./demo-account.js";
8
- import { createKakapoSceneHost } from "../kakapo-capability.js";
11
+ import { createSdkSceneHost } from "../sdk-scene-host.js";
9
12
  import { QuickJSJavaScriptExecutor } from "../quickjs-executor.js";
10
13
  import { sparkModelOptions } from "../model-options.js";
11
- import { MemorySparkArtifactStore } from "./artifacts.js";
12
14
  import { createSparkRunExecutor } from "./executor.js";
13
15
  import { createSparkAgentRouter } from "./express.js";
14
16
  import { SparkAgentService } from "./service.js";
15
- import { MemorySparkAgentStore } from "./store.js";
16
- export function createStandaloneSparkAgentApp(options) {
17
+ import { SqliteSparkStore } from "./sqlite-store.js";
18
+ export async function createStandaloneSparkAgentApp(options) {
17
19
  const apiBasePath = options.apiBasePath ?? "/agent";
18
- const store = new MemorySparkAgentStore();
19
- const artifactStore = new MemorySparkArtifactStore(`${apiBasePath}/artifacts`);
20
+ const store = new SqliteSparkStore(options.storagePath ?? ".spark/spark.sqlite", `${apiBasePath}/artifacts`);
21
+ try {
22
+ store.claimExecutionOwnership();
23
+ }
24
+ catch (error) {
25
+ store.close();
26
+ throw error;
27
+ }
28
+ const artifactStore = store;
20
29
  const executeRun = createSparkRunExecutor({
21
30
  createHost: async (context) => {
22
- const runtime = new KakapoRuntime(options.kakapoUrl);
31
+ const api = new KakapoAPI({
32
+ url: options.kakapoUrl,
33
+ requestTimeoutMs: 30_000,
34
+ });
23
35
  try {
24
- await runtime.connect();
36
+ context.signal.throwIfAborted();
37
+ await api.connect();
38
+ context.signal.throwIfAborted();
39
+ const services = {
40
+ fonts: await api.listFonts(),
41
+ ...(options.developmentProfile === "demo-account"
42
+ ? await loadDemoSceneMaterials()
43
+ : {}),
44
+ };
45
+ const sceneHost = createSdkSceneHost({
46
+ targetKey: `${context.ownerId}:${createHash("sha256")
47
+ .update(options.kakapoUrl)
48
+ .digest("hex")}`,
49
+ operations: store,
50
+ saveToRenderer: true,
51
+ withConnection: async (invocation, action) => {
52
+ invocation.signal.throwIfAborted();
53
+ if (!api.isConnected)
54
+ throw new Error("The Kakapo connection was interrupted; reconnect before continuing");
55
+ return action(api, () => { }, invocation);
56
+ },
57
+ assertEditable: () => {
58
+ if (!api.isConnected)
59
+ throw new Error("The Kakapo connection is unavailable");
60
+ },
61
+ services: async () => services,
62
+ screenshot: async (settings, invocation) => {
63
+ invocation.signal.throwIfAborted();
64
+ const image = await captureSdkSceneScreenshot(api, settings);
65
+ invocation.signal.throwIfAborted();
66
+ return artifactStore.write(context.ownerId, image);
67
+ },
68
+ });
25
69
  return {
26
70
  executor: new QuickJSJavaScriptExecutor(),
27
71
  capabilities: composeCapabilities({
28
- // The unified surface: the same `SceneHost` contract, the same
29
- // `scene-editing` v2 skill and the same `@womp/scene-api` functions
30
- // the browser runs on, rather than this package's retired second
31
- // scene layer.
32
- scene: createSceneCapability(createKakapoSceneHost(runtime.api, {
33
- saveImage: (image) => artifactStore.write(context.ownerId, image),
34
- })),
72
+ scene: createSceneCapability(sceneHost),
35
73
  ...(options.developmentProfile === "demo-account"
36
74
  ? { account: createAccountCapability(createDemoAccountHost()) }
37
75
  : {}),
@@ -45,11 +83,11 @@ export function createStandaloneSparkAgentApp(options) {
45
83
  return { artifact, data };
46
84
  },
47
85
  },
48
- dispose: () => runtime.disconnect(),
86
+ dispose: () => api.disconnect(),
49
87
  };
50
88
  }
51
89
  catch (error) {
52
- runtime.disconnect();
90
+ api.disconnect();
53
91
  throw error;
54
92
  }
55
93
  },
@@ -59,7 +97,8 @@ export function createStandaloneSparkAgentApp(options) {
59
97
  throw new Error(`Unsupported Spark model: ${settings.modelId}`);
60
98
  }
61
99
  if (selected.provider === "anthropic") {
62
- if (options.anthropicApiKey?.trim() === "" || options.anthropicApiKey === undefined) {
100
+ if (options.anthropicApiKey?.trim() === "" ||
101
+ options.anthropicApiKey === undefined) {
63
102
  throw new Error("ANTHROPIC_API_KEY is required for this model.");
64
103
  }
65
104
  return {
@@ -69,7 +108,8 @@ export function createStandaloneSparkAgentApp(options) {
69
108
  maxOutputTokens: 48_000,
70
109
  };
71
110
  }
72
- if (options.openAiApiKey?.trim() === "" || options.openAiApiKey === undefined) {
111
+ if (options.openAiApiKey?.trim() === "" ||
112
+ options.openAiApiKey === undefined) {
73
113
  throw new Error("OPENAI_API_KEY is required for this model.");
74
114
  }
75
115
  return {
@@ -81,11 +121,28 @@ export function createStandaloneSparkAgentApp(options) {
81
121
  },
82
122
  });
83
123
  const service = new SparkAgentService({ store, executeRun });
124
+ try {
125
+ for (const run of await store.listInterruptedRuns())
126
+ await service.recoverInterruptedRun(run.id);
127
+ }
128
+ catch (error) {
129
+ store.close();
130
+ throw error;
131
+ }
84
132
  const app = express();
85
133
  app.disable("x-powered-by");
86
134
  app.get("/health", (_request, response) => {
87
135
  response.json({ status: "ok" });
88
136
  });
89
137
  app.use(apiBasePath, createSparkAgentRouter({ service, artifactStore }));
90
- return app;
138
+ return Object.assign(app, {
139
+ async dispose() {
140
+ try {
141
+ await service.close();
142
+ }
143
+ finally {
144
+ store.close();
145
+ }
146
+ },
147
+ });
91
148
  }
@@ -63,6 +63,8 @@ export class MemorySparkAgentStore {
63
63
  const chunks = this.chunks.get(runId);
64
64
  if (chunks === undefined)
65
65
  throw new Error(`Run ${runId} does not exist.`);
66
- return chunks.filter(({ sequence }) => sequence > afterSequence).map(copy);
66
+ return chunks
67
+ .filter(({ sequence }) => sequence > afterSequence)
68
+ .map(copy);
67
69
  }
68
70
  }
package/dist/types.d.ts CHANGED
@@ -20,7 +20,7 @@ export type ExecutionScreenshot = {
20
20
  mediaType: "image/jpeg";
21
21
  width: number;
22
22
  height: number;
23
- view: ScreenshotView;
23
+ view: ScreenshotView | "current";
24
24
  targetId: number;
25
25
  };
26
26
  export type ExecutionResult = {