@womp/spark-agent 1.0.1 → 2.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 +42 -19
- package/dist/capabilities/health.d.ts +9 -0
- package/dist/capabilities/health.js +27 -0
- package/dist/capabilities/scene-draft.d.ts +2 -404
- package/dist/capabilities/scene.d.ts +1 -1
- package/dist/capabilities/scene.js +13 -4
- package/dist/capabilities.d.ts +3 -1
- package/dist/capabilities.js +1 -0
- package/dist/cli.js +20 -2
- package/dist/client.js +15 -15
- package/dist/coordinates.d.ts +23 -0
- package/dist/coordinates.js +132 -0
- package/dist/generated/health-declarations.d.ts +1 -0
- package/dist/generated/health-declarations.js +3 -0
- package/dist/generated/scene-declarations.d.ts +1 -1
- package/dist/generated/scene-declarations.js +1 -1
- package/dist/geometry/backendRegistry.d.ts +37 -0
- package/dist/geometry/backendRegistry.js +61 -0
- package/dist/geometry/common.d.ts +26 -0
- package/dist/geometry/common.js +78 -0
- package/dist/geometry/compiler.d.ts +35 -0
- package/dist/geometry/compiler.js +115 -0
- package/dist/geometry/graph.d.ts +39 -0
- package/dist/geometry/graph.js +32 -0
- package/dist/geometry/index.d.ts +9 -0
- package/dist/geometry/index.js +12 -0
- package/dist/geometry/lift.d.ts +7 -0
- package/dist/geometry/lift.js +376 -0
- package/dist/geometry/lower.d.ts +9 -0
- package/dist/geometry/lower.js +363 -0
- package/dist/geometry/parameters.d.ts +23 -0
- package/dist/geometry/parameters.js +46 -0
- package/dist/geometry/schemas/backend-schema.json +3394 -0
- package/dist/geometry/schemas/flowir-dialect.json +976 -0
- package/dist/geometry/writeParamData.d.ts +18 -0
- package/dist/geometry/writeParamData.js +47 -0
- package/dist/geometry.d.ts +10 -0
- package/dist/geometry.js +19 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/kakapo.d.ts +9 -5
- package/dist/kakapo.js +7 -6
- package/dist/openscad.d.ts +85 -0
- package/dist/openscad.js +223 -0
- package/dist/pricing.js +9 -29
- package/dist/repair-state.d.ts +50 -0
- package/dist/repair-state.js +96 -0
- package/dist/runtime.d.ts +16 -36
- package/dist/runtime.js +132 -139
- package/dist/scene-environment.d.ts +25 -0
- package/dist/scene-environment.js +76 -0
- package/dist/scene-health.d.ts +49 -0
- package/dist/scene-health.js +176 -0
- package/dist/scene-metadata.d.ts +6 -0
- package/dist/scene-metadata.js +65 -0
- package/dist/scene-operations.d.ts +47 -0
- package/dist/scene-operations.js +126 -0
- package/dist/sdk-geometry-host.d.ts +12 -0
- package/dist/sdk-geometry-host.js +306 -0
- package/dist/sdk-openscad-host.d.ts +14 -0
- package/dist/sdk-openscad-host.js +296 -0
- package/dist/sdk-openscad-renderer.d.ts +11 -0
- package/dist/sdk-openscad-renderer.js +71 -0
- package/dist/sdk-scene-health-host.d.ts +4 -0
- package/dist/sdk-scene-health-host.js +13 -0
- package/dist/sdk-scene-host.d.ts +312 -0
- package/dist/sdk-scene-host.js +202 -0
- package/dist/sdk-scene-screenshot.d.ts +7 -0
- package/dist/sdk-scene-screenshot.js +17 -0
- package/dist/server/demo-scene-materials.d.ts +3 -0
- package/dist/server/demo-scene-materials.js +18 -0
- package/dist/server/express.js +2 -4
- package/dist/server/fixtures/materials/matte-blue.json +14 -0
- package/dist/server/fixtures/materials/polished-copper.json +14 -0
- package/dist/server/index.d.ts +2 -1
- package/dist/server/index.js +2 -1
- package/dist/server/service.d.ts +4 -0
- package/dist/server/service.js +26 -2
- package/dist/server/sqlite-store.d.ts +31 -0
- package/dist/server/sqlite-store.js +224 -0
- package/dist/server/standalone.d.ts +14 -1
- package/dist/server/standalone.js +160 -27
- package/dist/server/store.js +3 -1
- package/dist/types.d.ts +1 -1
- package/dist/womp-scene-api.d.ts +283 -0
- package/dist/womp-scene-api.js +974 -0
- package/package.json +22 -10
- package/dist/kakapo-capability.d.ts +0 -45
- package/dist/kakapo-capability.js +0 -169
package/dist/server/index.d.ts
CHANGED
|
@@ -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 {
|
|
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";
|
package/dist/server/index.js
CHANGED
|
@@ -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 {
|
|
5
|
+
export { SqliteSparkStore } from "./sqlite-store.js";
|
|
6
|
+
export { createStandaloneSparkAgentApp, } from "./standalone.js";
|
package/dist/server/service.d.ts
CHANGED
|
@@ -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>;
|
package/dist/server/service.js
CHANGED
|
@@ -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
|
-
|
|
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
|
|
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,31 @@
|
|
|
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 RepairStateStore } from "../repair-state.js";
|
|
6
|
+
import type { SparkAgentStore, SparkConversation, SparkConversationSummary, SparkRun } from "./types.js";
|
|
7
|
+
/** Local development storage. Execution ownership belongs to the host service. */
|
|
8
|
+
export declare class SqliteSparkStore implements SparkAgentStore, SparkArtifactStore, SceneOperationStore {
|
|
9
|
+
private readonly artifactBaseUrl;
|
|
10
|
+
private readonly database;
|
|
11
|
+
private ownershipToken;
|
|
12
|
+
constructor(path: string, artifactBaseUrl?: string);
|
|
13
|
+
repairStateStore(targetKey: string): RepairStateStore;
|
|
14
|
+
close(): void;
|
|
15
|
+
claimExecutionOwnership(): void;
|
|
16
|
+
listInterruptedRuns(): Promise<SparkRun[]>;
|
|
17
|
+
getSceneOperation(targetKey: string, id: string): Promise<SceneOperation | undefined>;
|
|
18
|
+
createSceneOperation(operation: SceneOperation): Promise<boolean>;
|
|
19
|
+
saveSceneOperation(operation: SceneOperation): Promise<SceneOperation>;
|
|
20
|
+
createConversation(value: SparkConversation): Promise<void>;
|
|
21
|
+
getConversation(id: string): Promise<SparkConversation | undefined>;
|
|
22
|
+
listConversations(ownerId: string): Promise<SparkConversationSummary[]>;
|
|
23
|
+
saveConversation(value: SparkConversation): Promise<void>;
|
|
24
|
+
createRun(value: SparkRun): Promise<void>;
|
|
25
|
+
getRun(id: string): Promise<SparkRun | undefined>;
|
|
26
|
+
saveRun(value: SparkRun): Promise<void>;
|
|
27
|
+
appendRunChunk(runId: string, conversationId: string, chunk: StoredSparkChunk["chunk"]): Promise<StoredSparkChunk>;
|
|
28
|
+
listRunChunks(runId: string, afterSequence: number): Promise<StoredSparkChunk[]>;
|
|
29
|
+
write(ownerId: string, image: ExecutionScreenshot): Promise<SparkArtifact>;
|
|
30
|
+
get(ownerId: string, id: string): Promise<StoredSparkArtifact | undefined>;
|
|
31
|
+
}
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import { mkdirSync } from "node:fs";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { DatabaseSync } from "node:sqlite";
|
|
4
|
+
import { emptyRepairState, } from "../repair-state.js";
|
|
5
|
+
const completedSceneOperationLimit = 128;
|
|
6
|
+
/** Local development storage. Execution ownership belongs to the host service. */
|
|
7
|
+
export class SqliteSparkStore {
|
|
8
|
+
artifactBaseUrl;
|
|
9
|
+
database;
|
|
10
|
+
ownershipToken;
|
|
11
|
+
constructor(path, artifactBaseUrl = "/agent/artifacts") {
|
|
12
|
+
this.artifactBaseUrl = artifactBaseUrl;
|
|
13
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
14
|
+
this.database = new DatabaseSync(path);
|
|
15
|
+
const version = this.database.prepare("PRAGMA user_version").get()?.user_version;
|
|
16
|
+
if (version !== 0 && version !== 1 && version !== 2 && version !== 3 && version !== 4) {
|
|
17
|
+
this.database.close();
|
|
18
|
+
throw new Error(`Unsupported Spark database version: ${version}`);
|
|
19
|
+
}
|
|
20
|
+
this.database.exec(`
|
|
21
|
+
PRAGMA busy_timeout = 5000;
|
|
22
|
+
PRAGMA journal_mode = WAL;
|
|
23
|
+
PRAGMA synchronous = FULL;
|
|
24
|
+
PRAGMA foreign_keys = ON;
|
|
25
|
+
CREATE TABLE IF NOT EXISTS conversations (
|
|
26
|
+
id TEXT PRIMARY KEY, owner_id TEXT NOT NULL, updated_at TEXT NOT NULL, data TEXT NOT NULL
|
|
27
|
+
);
|
|
28
|
+
CREATE INDEX IF NOT EXISTS conversation_owner ON conversations(owner_id, updated_at);
|
|
29
|
+
CREATE TABLE IF NOT EXISTS runs (
|
|
30
|
+
id TEXT PRIMARY KEY, conversation_id TEXT NOT NULL, data TEXT NOT NULL
|
|
31
|
+
);
|
|
32
|
+
CREATE TABLE IF NOT EXISTS chunks (
|
|
33
|
+
run_id TEXT NOT NULL REFERENCES runs(id), sequence INTEGER NOT NULL, data TEXT NOT NULL,
|
|
34
|
+
PRIMARY KEY (run_id, sequence)
|
|
35
|
+
);
|
|
36
|
+
CREATE TABLE IF NOT EXISTS artifacts (
|
|
37
|
+
id TEXT PRIMARY KEY, owner_id TEXT NOT NULL, metadata TEXT NOT NULL, bytes BLOB NOT NULL
|
|
38
|
+
);
|
|
39
|
+
CREATE TABLE IF NOT EXISTS execution_owner (
|
|
40
|
+
singleton INTEGER PRIMARY KEY CHECK (singleton = 1), pid INTEGER NOT NULL, token TEXT NOT NULL
|
|
41
|
+
);
|
|
42
|
+
CREATE TABLE IF NOT EXISTS scene_operations (
|
|
43
|
+
target_key TEXT NOT NULL, id TEXT NOT NULL, revision INTEGER NOT NULL, data TEXT NOT NULL,
|
|
44
|
+
PRIMARY KEY (target_key, id)
|
|
45
|
+
);
|
|
46
|
+
CREATE TABLE IF NOT EXISTS repair_states (
|
|
47
|
+
target_key TEXT PRIMARY KEY, revision INTEGER NOT NULL, data TEXT NOT NULL
|
|
48
|
+
);
|
|
49
|
+
PRAGMA user_version = 4;
|
|
50
|
+
`);
|
|
51
|
+
}
|
|
52
|
+
repairStateStore(targetKey) {
|
|
53
|
+
return {
|
|
54
|
+
read: async () => {
|
|
55
|
+
const row = this.database.prepare("SELECT data FROM repair_states WHERE target_key = ?").get(targetKey);
|
|
56
|
+
return row
|
|
57
|
+
? JSON.parse(String(row.data))
|
|
58
|
+
: emptyRepairState();
|
|
59
|
+
},
|
|
60
|
+
compareAndSwap: async (expectedRevision, next) => {
|
|
61
|
+
const stored = { ...next, revision: expectedRevision + 1 };
|
|
62
|
+
if (expectedRevision === 0) {
|
|
63
|
+
const inserted = this.database.prepare("INSERT OR IGNORE INTO repair_states VALUES (?, ?, ?)").run(targetKey, stored.revision, JSON.stringify(stored));
|
|
64
|
+
if (inserted.changes === 1)
|
|
65
|
+
return true;
|
|
66
|
+
}
|
|
67
|
+
const updated = this.database.prepare("UPDATE repair_states SET revision = ?, data = ? WHERE target_key = ? AND revision = ?").run(stored.revision, JSON.stringify(stored), targetKey, expectedRevision);
|
|
68
|
+
return updated.changes === 1;
|
|
69
|
+
},
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
close() {
|
|
73
|
+
if (this.ownershipToken) {
|
|
74
|
+
this.database.prepare("DELETE FROM execution_owner WHERE token = ?").run(this.ownershipToken);
|
|
75
|
+
this.ownershipToken = undefined;
|
|
76
|
+
}
|
|
77
|
+
this.database.close();
|
|
78
|
+
}
|
|
79
|
+
claimExecutionOwnership() {
|
|
80
|
+
if (this.ownershipToken)
|
|
81
|
+
return;
|
|
82
|
+
this.database.exec("BEGIN IMMEDIATE");
|
|
83
|
+
try {
|
|
84
|
+
const owner = this.database.prepare("SELECT pid FROM execution_owner WHERE singleton = 1").get();
|
|
85
|
+
if (owner) {
|
|
86
|
+
let alive = true;
|
|
87
|
+
try {
|
|
88
|
+
process.kill(Number(owner.pid), 0);
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
if (!(error instanceof Error) || !("code" in error) || error.code !== "ESRCH")
|
|
92
|
+
throw error;
|
|
93
|
+
alive = false;
|
|
94
|
+
}
|
|
95
|
+
if (alive)
|
|
96
|
+
throw new Error(`Spark storage is already owned by process ${owner.pid}`);
|
|
97
|
+
}
|
|
98
|
+
const token = crypto.randomUUID();
|
|
99
|
+
this.database.prepare("INSERT OR REPLACE INTO execution_owner VALUES (1, ?, ?)")
|
|
100
|
+
.run(process.pid, token);
|
|
101
|
+
this.database.exec("COMMIT");
|
|
102
|
+
this.ownershipToken = token;
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
this.database.exec("ROLLBACK");
|
|
106
|
+
throw error;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
async listInterruptedRuns() {
|
|
110
|
+
if (!this.ownershipToken)
|
|
111
|
+
throw new Error("Claim execution ownership before recovering runs");
|
|
112
|
+
return this.database.prepare("SELECT data FROM runs WHERE json_extract(data, '$.status') IN ('queued', 'running')").all().map((row) => JSON.parse(String(row.data)));
|
|
113
|
+
}
|
|
114
|
+
async getSceneOperation(targetKey, id) {
|
|
115
|
+
const row = this.database.prepare("SELECT data FROM scene_operations WHERE target_key = ? AND id = ?").get(targetKey, id);
|
|
116
|
+
return row ? JSON.parse(String(row.data)) : undefined;
|
|
117
|
+
}
|
|
118
|
+
async createSceneOperation(operation) {
|
|
119
|
+
const result = this.database.prepare("INSERT OR IGNORE INTO scene_operations VALUES (?, ?, ?, ?)").run(operation.targetKey, operation.id, operation.revision, JSON.stringify(operation));
|
|
120
|
+
return result.changes === 1;
|
|
121
|
+
}
|
|
122
|
+
async saveSceneOperation(operation) {
|
|
123
|
+
const next = { ...operation, revision: operation.revision + 1 };
|
|
124
|
+
this.database.exec("BEGIN IMMEDIATE");
|
|
125
|
+
try {
|
|
126
|
+
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);
|
|
127
|
+
if (result.changes !== 1)
|
|
128
|
+
throw new Error("Scene operation changed concurrently or is missing");
|
|
129
|
+
if (next.status === "committed" || next.status === "rolled_back") {
|
|
130
|
+
this.database.prepare(`
|
|
131
|
+
DELETE FROM scene_operations WHERE rowid IN (
|
|
132
|
+
SELECT rowid FROM scene_operations
|
|
133
|
+
WHERE target_key = ? AND json_extract(data, '$.status') IN ('committed', 'rolled_back')
|
|
134
|
+
ORDER BY COALESCE(json_extract(data, '$.completedAt'), '') DESC
|
|
135
|
+
LIMIT -1 OFFSET ?
|
|
136
|
+
)
|
|
137
|
+
`).run(next.targetKey, completedSceneOperationLimit);
|
|
138
|
+
}
|
|
139
|
+
this.database.exec("COMMIT");
|
|
140
|
+
return next;
|
|
141
|
+
}
|
|
142
|
+
catch (error) {
|
|
143
|
+
this.database.exec("ROLLBACK");
|
|
144
|
+
throw error;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
async createConversation(value) {
|
|
148
|
+
this.database.prepare("INSERT INTO conversations VALUES (?, ?, ?, ?)")
|
|
149
|
+
.run(value.id, value.ownerId, value.updatedAt, JSON.stringify(value));
|
|
150
|
+
}
|
|
151
|
+
async getConversation(id) {
|
|
152
|
+
const row = this.database.prepare("SELECT data FROM conversations WHERE id = ?").get(id);
|
|
153
|
+
return row ? JSON.parse(String(row.data)) : undefined;
|
|
154
|
+
}
|
|
155
|
+
async listConversations(ownerId) {
|
|
156
|
+
return this.database.prepare("SELECT data FROM conversations WHERE owner_id = ? ORDER BY updated_at DESC").all(ownerId).map((row) => {
|
|
157
|
+
const { messages, ...conversation } = JSON.parse(String(row.data));
|
|
158
|
+
return { ...conversation, messageCount: messages.length };
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
async saveConversation(value) {
|
|
162
|
+
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);
|
|
163
|
+
if (result.changes === 0)
|
|
164
|
+
throw new Error(`Conversation ${value.id} does not exist.`);
|
|
165
|
+
}
|
|
166
|
+
async createRun(value) {
|
|
167
|
+
this.database.prepare("INSERT INTO runs VALUES (?, ?, ?)")
|
|
168
|
+
.run(value.id, value.conversationId, JSON.stringify(value));
|
|
169
|
+
}
|
|
170
|
+
async getRun(id) {
|
|
171
|
+
const row = this.database.prepare("SELECT data FROM runs WHERE id = ?").get(id);
|
|
172
|
+
return row ? JSON.parse(String(row.data)) : undefined;
|
|
173
|
+
}
|
|
174
|
+
async saveRun(value) {
|
|
175
|
+
const result = this.database.prepare("UPDATE runs SET conversation_id = ?, data = ? WHERE id = ?").run(value.conversationId, JSON.stringify(value), value.id);
|
|
176
|
+
if (result.changes === 0)
|
|
177
|
+
throw new Error(`Run ${value.id} does not exist.`);
|
|
178
|
+
}
|
|
179
|
+
async appendRunChunk(runId, conversationId, chunk) {
|
|
180
|
+
this.database.exec("BEGIN IMMEDIATE");
|
|
181
|
+
try {
|
|
182
|
+
const run = this.database.prepare("SELECT conversation_id FROM runs WHERE id = ?").get(runId);
|
|
183
|
+
if (!run || run.conversation_id !== conversationId)
|
|
184
|
+
throw new Error("Run target does not match.");
|
|
185
|
+
const sequence = Number(this.database.prepare("SELECT COALESCE(MAX(sequence), 0) + 1 AS next FROM chunks WHERE run_id = ?").get(runId)?.next);
|
|
186
|
+
const stored = {
|
|
187
|
+
sequence, runId, conversationId, chunk: structuredClone(chunk), createdAt: new Date().toISOString(),
|
|
188
|
+
};
|
|
189
|
+
this.database.prepare("INSERT INTO chunks VALUES (?, ?, ?)")
|
|
190
|
+
.run(runId, sequence, JSON.stringify(stored));
|
|
191
|
+
this.database.exec("COMMIT");
|
|
192
|
+
return stored;
|
|
193
|
+
}
|
|
194
|
+
catch (error) {
|
|
195
|
+
this.database.exec("ROLLBACK");
|
|
196
|
+
throw error;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
async listRunChunks(runId, afterSequence) {
|
|
200
|
+
if (!await this.getRun(runId))
|
|
201
|
+
throw new Error(`Run ${runId} does not exist.`);
|
|
202
|
+
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)));
|
|
203
|
+
}
|
|
204
|
+
async write(ownerId, image) {
|
|
205
|
+
const id = crypto.randomUUID();
|
|
206
|
+
const artifact = {
|
|
207
|
+
id, url: `${this.artifactBaseUrl.replace(/\/$/u, "")}/${id}`,
|
|
208
|
+
mediaType: image.mediaType, name: `spark-${image.view}.jpg`,
|
|
209
|
+
width: image.width, height: image.height,
|
|
210
|
+
metadata: { view: image.view, targetId: image.targetId },
|
|
211
|
+
};
|
|
212
|
+
this.database.prepare("INSERT INTO artifacts VALUES (?, ?, ?, ?)")
|
|
213
|
+
.run(id, ownerId, JSON.stringify(artifact), image.data);
|
|
214
|
+
return artifact;
|
|
215
|
+
}
|
|
216
|
+
async get(ownerId, id) {
|
|
217
|
+
const row = this.database.prepare("SELECT metadata, bytes FROM artifacts WHERE id = ? AND owner_id = ?").get(id, ownerId);
|
|
218
|
+
if (!row)
|
|
219
|
+
return undefined;
|
|
220
|
+
if (!(row.bytes instanceof Uint8Array))
|
|
221
|
+
throw new Error(`Invalid artifact bytes: ${id}`);
|
|
222
|
+
return { ...JSON.parse(String(row.metadata)), ownerId, data: row.bytes.slice() };
|
|
223
|
+
}
|
|
224
|
+
}
|
|
@@ -1,9 +1,22 @@
|
|
|
1
1
|
import { type Express } from "express";
|
|
2
|
+
import { KakapoAPI } from "@womp/kakapo-sdk";
|
|
2
3
|
export type StandaloneSparkAgentOptions = {
|
|
3
4
|
openAiApiKey?: string;
|
|
4
5
|
anthropicApiKey?: string;
|
|
5
6
|
kakapoUrl: string;
|
|
6
7
|
apiBasePath?: string;
|
|
7
8
|
developmentProfile?: "demo-account";
|
|
9
|
+
storagePath?: string;
|
|
10
|
+
/** Stable host-verified identity for the scene behind kakapoUrl. */
|
|
11
|
+
sceneIdentity?: string;
|
|
12
|
+
logger?: Pick<Console, "info" | "warn">;
|
|
8
13
|
};
|
|
9
|
-
export
|
|
14
|
+
export type StandaloneSparkAgentApp = Express & {
|
|
15
|
+
dispose(): Promise<void>;
|
|
16
|
+
};
|
|
17
|
+
export declare function checkStandaloneServices(api: Pick<KakapoAPI, "listFonts" | "validateOpenScad">): Promise<{
|
|
18
|
+
fonts: import("@womp/kakapo-sdk").FontFamily[];
|
|
19
|
+
fontsAvailable: boolean;
|
|
20
|
+
openScadStatus: string;
|
|
21
|
+
}>;
|
|
22
|
+
export declare function createStandaloneSparkAgentApp(options: StandaloneSparkAgentOptions): Promise<StandaloneSparkAgentApp>;
|
|
@@ -2,40 +2,154 @@ import { createAnthropic } from "@ai-sdk/anthropic";
|
|
|
2
2
|
import { createOpenAI } from "@ai-sdk/openai";
|
|
3
3
|
import express from "express";
|
|
4
4
|
import { getSparkModel, SPARK_MODELS } from "../models.js";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
5
|
+
import { KakapoAPI, KakapoRpcError } from "@womp/kakapo-sdk";
|
|
6
|
+
import { captureSdkSceneScreenshot } from "../sdk-scene-screenshot.js";
|
|
7
|
+
import { composeCapabilities, createAccountCapability, createGeometryCapability, createOpenScadCapability, createSceneCapability, createSceneHealthCapability, } from "../capabilities.js";
|
|
8
|
+
import { loadDemoSceneMaterials } from "./demo-scene-materials.js";
|
|
7
9
|
import { createDemoAccountHost } from "./demo-account.js";
|
|
8
|
-
import {
|
|
10
|
+
import { createSdkSceneEditor, createSdkSceneHost, } from "../sdk-scene-host.js";
|
|
11
|
+
import { createSdkGeometryHost } from "../sdk-geometry-host.js";
|
|
12
|
+
import { createSdkOpenScadHost } from "../sdk-openscad-host.js";
|
|
13
|
+
import { createSdkSceneHealthHost } from "../sdk-scene-health-host.js";
|
|
14
|
+
import { geometryReference } from "../geometry.js";
|
|
15
|
+
import { getSdkSceneAreaIds, hasSceneResourcePressure, readStableSdkSceneHealth, } from "../scene-health.js";
|
|
9
16
|
import { QuickJSJavaScriptExecutor } from "../quickjs-executor.js";
|
|
10
17
|
import { sparkModelOptions } from "../model-options.js";
|
|
11
|
-
import { MemorySparkArtifactStore } from "./artifacts.js";
|
|
12
18
|
import { createSparkRunExecutor } from "./executor.js";
|
|
13
19
|
import { createSparkAgentRouter } from "./express.js";
|
|
14
20
|
import { SparkAgentService } from "./service.js";
|
|
15
|
-
import {
|
|
16
|
-
export function
|
|
21
|
+
import { SqliteSparkStore } from "./sqlite-store.js";
|
|
22
|
+
export async function checkStandaloneServices(api) {
|
|
23
|
+
const [fonts, openScad] = await Promise.allSettled([
|
|
24
|
+
api.listFonts(),
|
|
25
|
+
api.validateOpenScad("// Spark capability check"),
|
|
26
|
+
]);
|
|
27
|
+
const openScadStatus = openScad.status === "fulfilled"
|
|
28
|
+
? "available"
|
|
29
|
+
: openScad.reason instanceof KakapoRpcError &&
|
|
30
|
+
openScad.reason.rpcCode === -32601
|
|
31
|
+
? "unsupported"
|
|
32
|
+
: "unverified";
|
|
33
|
+
return {
|
|
34
|
+
fonts: fonts.status === "fulfilled" ? fonts.value : [],
|
|
35
|
+
fontsAvailable: fonts.status === "fulfilled",
|
|
36
|
+
openScadStatus,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
export async function createStandaloneSparkAgentApp(options) {
|
|
40
|
+
const logger = options.logger ?? console;
|
|
41
|
+
const configuredSceneIdentity = options.sceneIdentity?.trim() || undefined;
|
|
42
|
+
const sceneIdentity = configuredSceneIdentity ?? `session:${crypto.randomUUID()}`;
|
|
43
|
+
if (configuredSceneIdentity === undefined) {
|
|
44
|
+
logger.warn("Spark scene identity is unavailable; interrupted scene mutations will not be resumed across server restarts.");
|
|
45
|
+
}
|
|
46
|
+
let loggedCatalog;
|
|
17
47
|
const apiBasePath = options.apiBasePath ?? "/agent";
|
|
18
|
-
const store = new
|
|
19
|
-
|
|
48
|
+
const store = new SqliteSparkStore(options.storagePath ?? ".spark/spark.sqlite", `${apiBasePath}/artifacts`);
|
|
49
|
+
try {
|
|
50
|
+
store.claimExecutionOwnership();
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
store.close();
|
|
54
|
+
throw error;
|
|
55
|
+
}
|
|
56
|
+
const artifactStore = store;
|
|
20
57
|
const executeRun = createSparkRunExecutor({
|
|
21
58
|
createHost: async (context) => {
|
|
22
|
-
const
|
|
59
|
+
const api = new KakapoAPI({
|
|
60
|
+
url: options.kakapoUrl,
|
|
61
|
+
requestTimeoutMs: 30_000,
|
|
62
|
+
});
|
|
23
63
|
try {
|
|
24
|
-
|
|
64
|
+
context.signal.throwIfAborted();
|
|
65
|
+
await api.connect();
|
|
66
|
+
context.signal.throwIfAborted();
|
|
67
|
+
const support = await checkStandaloneServices(api);
|
|
68
|
+
const services = {
|
|
69
|
+
fonts: support.fonts,
|
|
70
|
+
...(options.developmentProfile === "demo-account"
|
|
71
|
+
? await loadDemoSceneMaterials()
|
|
72
|
+
: {}),
|
|
73
|
+
};
|
|
74
|
+
const targetKey = `${context.ownerId}:${sceneIdentity}`;
|
|
75
|
+
const editorOptions = {
|
|
76
|
+
targetKey,
|
|
77
|
+
operations: store,
|
|
78
|
+
saveToRenderer: true,
|
|
79
|
+
withConnection: async (invocation, action) => {
|
|
80
|
+
invocation.signal.throwIfAborted();
|
|
81
|
+
if (!api.isConnected)
|
|
82
|
+
throw new Error("The Kakapo connection was interrupted; reconnect before continuing");
|
|
83
|
+
return action(api, () => { }, invocation);
|
|
84
|
+
},
|
|
85
|
+
assertEditable: () => {
|
|
86
|
+
if (!api.isConnected)
|
|
87
|
+
throw new Error("The Kakapo connection is unavailable");
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
const editor = createSdkSceneEditor(editorOptions);
|
|
91
|
+
const repairs = store.repairStateStore(`${targetKey}:${context.runId}`);
|
|
92
|
+
let latestHealth;
|
|
93
|
+
const onHealth = (health) => {
|
|
94
|
+
latestHealth = health;
|
|
95
|
+
};
|
|
96
|
+
const canGrow = () => latestHealth === undefined ||
|
|
97
|
+
hasSceneResourcePressure(latestHealth) === false;
|
|
98
|
+
const sceneHost = createSdkSceneHost({
|
|
99
|
+
...editorOptions,
|
|
100
|
+
editor,
|
|
101
|
+
onSceneCommitted: async (_operation, api) => {
|
|
102
|
+
const sceneHealth = await readStableSdkSceneHealth(api, getSdkSceneAreaIds(api), context.signal);
|
|
103
|
+
onHealth(sceneHealth);
|
|
104
|
+
return { sceneHealth };
|
|
105
|
+
},
|
|
106
|
+
services: async () => services,
|
|
107
|
+
screenshot: async (settings, invocation) => {
|
|
108
|
+
invocation.signal.throwIfAborted();
|
|
109
|
+
const image = await captureSdkSceneScreenshot(api, settings);
|
|
110
|
+
invocation.signal.throwIfAborted();
|
|
111
|
+
return artifactStore.write(context.ownerId, image);
|
|
112
|
+
},
|
|
113
|
+
});
|
|
114
|
+
const capabilityBindings = {
|
|
115
|
+
scene: createSceneCapability(sceneHost),
|
|
116
|
+
health: createSceneHealthCapability(createSdkSceneHealthHost(editor, onHealth)),
|
|
117
|
+
geometry: createGeometryCapability(createSdkGeometryHost({
|
|
118
|
+
editor,
|
|
119
|
+
repairs,
|
|
120
|
+
canGrow,
|
|
121
|
+
onHealth,
|
|
122
|
+
}), geometryReference()),
|
|
123
|
+
...(support.openScadStatus !== "unsupported"
|
|
124
|
+
? {
|
|
125
|
+
openscad: createOpenScadCapability(createSdkOpenScadHost({ editor, repairs, canGrow, onHealth })),
|
|
126
|
+
}
|
|
127
|
+
: {}),
|
|
128
|
+
...(options.developmentProfile === "demo-account"
|
|
129
|
+
? { account: createAccountCapability(createDemoAccountHost()) }
|
|
130
|
+
: {}),
|
|
131
|
+
};
|
|
132
|
+
const capabilities = composeCapabilities(capabilityBindings);
|
|
133
|
+
const catalog = `${Object.keys(capabilityBindings).join(",")}\n${capabilities.skills.map(({ name }) => name).join(",")}`;
|
|
134
|
+
if (catalog !== loggedCatalog) {
|
|
135
|
+
logger.info(`Spark capabilities enabled: ${Object.keys(capabilityBindings).join(", ")}`);
|
|
136
|
+
logger.info(`Spark skills enabled: ${capabilities.skills
|
|
137
|
+
.map(({ name }) => name)
|
|
138
|
+
.join(", ")}`);
|
|
139
|
+
loggedCatalog = catalog;
|
|
140
|
+
}
|
|
141
|
+
if (support.fontsAvailable === false) {
|
|
142
|
+
logger.warn("Spark font discovery is unavailable; the scene binding will use an empty font catalog.");
|
|
143
|
+
}
|
|
144
|
+
if (support.openScadStatus === "unsupported") {
|
|
145
|
+
logger.warn("Spark OpenSCAD validation is unavailable; the parametric-parts skill is disabled.");
|
|
146
|
+
}
|
|
147
|
+
if (support.openScadStatus === "unverified") {
|
|
148
|
+
logger.warn("Spark OpenSCAD validation could not be verified; the parametric-parts skill remains enabled and will report service errors when used.");
|
|
149
|
+
}
|
|
25
150
|
return {
|
|
26
151
|
executor: new QuickJSJavaScriptExecutor(),
|
|
27
|
-
capabilities
|
|
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
|
-
})),
|
|
35
|
-
...(options.developmentProfile === "demo-account"
|
|
36
|
-
? { account: createAccountCapability(createDemoAccountHost()) }
|
|
37
|
-
: {}),
|
|
38
|
-
}),
|
|
152
|
+
capabilities,
|
|
39
153
|
artifacts: {
|
|
40
154
|
resolve: async (ref) => {
|
|
41
155
|
const stored = await artifactStore.get(context.ownerId, ref.id);
|
|
@@ -45,11 +159,11 @@ export function createStandaloneSparkAgentApp(options) {
|
|
|
45
159
|
return { artifact, data };
|
|
46
160
|
},
|
|
47
161
|
},
|
|
48
|
-
dispose: () =>
|
|
162
|
+
dispose: () => api.disconnect(),
|
|
49
163
|
};
|
|
50
164
|
}
|
|
51
165
|
catch (error) {
|
|
52
|
-
|
|
166
|
+
api.disconnect();
|
|
53
167
|
throw error;
|
|
54
168
|
}
|
|
55
169
|
},
|
|
@@ -59,7 +173,8 @@ export function createStandaloneSparkAgentApp(options) {
|
|
|
59
173
|
throw new Error(`Unsupported Spark model: ${settings.modelId}`);
|
|
60
174
|
}
|
|
61
175
|
if (selected.provider === "anthropic") {
|
|
62
|
-
if (options.anthropicApiKey?.trim() === "" ||
|
|
176
|
+
if (options.anthropicApiKey?.trim() === "" ||
|
|
177
|
+
options.anthropicApiKey === undefined) {
|
|
63
178
|
throw new Error("ANTHROPIC_API_KEY is required for this model.");
|
|
64
179
|
}
|
|
65
180
|
return {
|
|
@@ -69,7 +184,8 @@ export function createStandaloneSparkAgentApp(options) {
|
|
|
69
184
|
maxOutputTokens: 48_000,
|
|
70
185
|
};
|
|
71
186
|
}
|
|
72
|
-
if (options.openAiApiKey?.trim() === "" ||
|
|
187
|
+
if (options.openAiApiKey?.trim() === "" ||
|
|
188
|
+
options.openAiApiKey === undefined) {
|
|
73
189
|
throw new Error("OPENAI_API_KEY is required for this model.");
|
|
74
190
|
}
|
|
75
191
|
return {
|
|
@@ -81,11 +197,28 @@ export function createStandaloneSparkAgentApp(options) {
|
|
|
81
197
|
},
|
|
82
198
|
});
|
|
83
199
|
const service = new SparkAgentService({ store, executeRun });
|
|
200
|
+
try {
|
|
201
|
+
for (const run of await store.listInterruptedRuns())
|
|
202
|
+
await service.recoverInterruptedRun(run.id);
|
|
203
|
+
}
|
|
204
|
+
catch (error) {
|
|
205
|
+
store.close();
|
|
206
|
+
throw error;
|
|
207
|
+
}
|
|
84
208
|
const app = express();
|
|
85
209
|
app.disable("x-powered-by");
|
|
86
210
|
app.get("/health", (_request, response) => {
|
|
87
211
|
response.json({ status: "ok" });
|
|
88
212
|
});
|
|
89
213
|
app.use(apiBasePath, createSparkAgentRouter({ service, artifactStore }));
|
|
90
|
-
return app
|
|
214
|
+
return Object.assign(app, {
|
|
215
|
+
async dispose() {
|
|
216
|
+
try {
|
|
217
|
+
await service.close();
|
|
218
|
+
}
|
|
219
|
+
finally {
|
|
220
|
+
store.close();
|
|
221
|
+
}
|
|
222
|
+
},
|
|
223
|
+
});
|
|
91
224
|
}
|
package/dist/server/store.js
CHANGED
|
@@ -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
|
|
66
|
+
return chunks
|
|
67
|
+
.filter(({ sequence }) => sequence > afterSequence)
|
|
68
|
+
.map(copy);
|
|
67
69
|
}
|
|
68
70
|
}
|