@womp/spark-agent 0.1.0 → 0.3.1
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/.env.example +4 -0
- package/README.md +303 -49
- package/dist/agent-tools.d.ts +30 -0
- package/dist/agent-tools.js +189 -0
- package/dist/agent.d.ts +34 -7
- package/dist/agent.js +223 -158
- package/dist/browser.d.ts +2 -0
- package/dist/browser.js +2 -0
- package/dist/capabilities/account.d.ts +216 -0
- package/dist/capabilities/account.js +63 -0
- package/dist/capabilities/asset-imports.d.ts +55 -0
- package/dist/capabilities/asset-imports.js +117 -0
- package/dist/capabilities/assets.d.ts +29 -0
- package/dist/capabilities/assets.js +48 -0
- package/dist/capabilities/flow.d.ts +29 -0
- package/dist/capabilities/flow.js +52 -0
- package/dist/capabilities/geometry.d.ts +48 -0
- package/dist/capabilities/geometry.js +51 -0
- package/dist/capabilities/knowledge.d.ts +11 -0
- package/dist/capabilities/knowledge.js +23 -0
- package/dist/capabilities/openscad-instructions.d.ts +1 -0
- package/dist/capabilities/openscad-instructions.js +81 -0
- package/dist/capabilities/openscad.d.ts +54 -0
- package/dist/capabilities/openscad.js +34 -0
- package/dist/capabilities/operations.d.ts +104 -0
- package/dist/capabilities/operations.js +145 -0
- package/dist/capabilities/scene-draft.d.ts +404 -0
- package/dist/capabilities/scene-draft.js +1 -0
- package/dist/capabilities/scene.d.ts +28 -0
- package/dist/capabilities/scene.js +51 -0
- package/dist/capabilities.d.ts +67 -0
- package/dist/capabilities.js +25 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +24 -0
- package/dist/client.d.ts +43 -0
- package/dist/client.js +159 -0
- package/dist/context.d.ts +15 -0
- package/dist/context.js +266 -0
- package/dist/execution-lifetime.d.ts +32 -0
- package/dist/execution-lifetime.js +113 -0
- package/dist/executor.d.ts +6 -1
- package/dist/generated/account-declarations.d.ts +1 -0
- package/dist/generated/account-declarations.js +3 -0
- package/dist/generated/asset-import-declarations.d.ts +1 -0
- package/dist/generated/asset-import-declarations.js +3 -0
- package/dist/generated/assets-declarations.d.ts +1 -0
- package/dist/generated/assets-declarations.js +3 -0
- package/dist/generated/flow-declarations.d.ts +1 -0
- package/dist/generated/flow-declarations.js +3 -0
- package/dist/generated/geometry-declarations.d.ts +1 -0
- package/dist/generated/geometry-declarations.js +3 -0
- package/dist/generated/kakapo-declarations.d.ts +1 -0
- package/dist/generated/kakapo-declarations.js +3 -0
- package/dist/generated/knowledge-declarations.d.ts +1 -0
- package/dist/generated/knowledge-declarations.js +3 -0
- package/dist/generated/openscad-declarations.d.ts +1 -0
- package/dist/generated/openscad-declarations.js +3 -0
- package/dist/generated/operations-declarations.d.ts +1 -0
- package/dist/generated/operations-declarations.js +3 -0
- package/dist/generated/scene-declarations.d.ts +1 -0
- package/dist/generated/scene-declarations.js +3 -0
- package/dist/index.d.ts +7 -6
- package/dist/index.js +5 -3
- package/dist/kakapo-capability-api.d.ts +18 -0
- package/dist/kakapo-capability-api.js +1 -0
- package/dist/kakapo-capability.d.ts +6 -0
- package/dist/kakapo-capability.js +50 -0
- package/dist/kakapo-scene-skill.d.ts +1 -0
- package/dist/kakapo-scene-skill.js +54 -0
- package/dist/kakapo.d.ts +5 -0
- package/dist/kakapo.js +3 -0
- package/dist/local-transport.d.ts +11 -0
- package/dist/local-transport.js +15 -0
- package/dist/model-history.d.ts +5 -0
- package/dist/model-history.js +34 -0
- package/dist/model-options.d.ts +4 -0
- package/dist/model-options.js +25 -0
- package/dist/models.d.ts +3 -15
- package/dist/models.js +2 -16
- package/dist/native-executor.d.ts +5 -0
- package/dist/native-executor.js +92 -0
- package/dist/pricing.d.ts +3 -0
- package/dist/pricing.js +70 -0
- package/dist/prompt.d.ts +1 -1
- package/dist/prompt.js +19 -209
- package/dist/quickjs-executor.d.ts +13 -0
- package/dist/quickjs-executor.js +309 -0
- package/dist/runtime.d.ts +16 -5
- package/dist/runtime.js +61 -10
- package/dist/server/artifacts.d.ts +17 -0
- package/dist/server/artifacts.js +36 -0
- package/dist/server/demo-account.d.ts +3 -0
- package/dist/server/demo-account.js +38 -0
- package/dist/server/executor.d.ts +17 -0
- package/dist/server/executor.js +35 -0
- package/dist/server/express.d.ts +13 -0
- package/dist/server/express.js +159 -0
- package/dist/server/index.d.ts +8 -0
- package/dist/server/index.js +5 -0
- package/dist/server/service.d.ts +41 -0
- package/dist/server/service.js +402 -0
- package/dist/server/standalone.d.ts +9 -0
- package/dist/server/standalone.js +85 -0
- package/dist/server/store.d.ts +16 -0
- package/dist/server/store.js +70 -0
- package/dist/server/types.d.ts +53 -0
- package/dist/server/types.js +1 -0
- package/dist/types.d.ts +3 -27
- package/dist/ui.d.ts +224 -0
- package/dist/ui.js +71 -0
- package/dist/womp-scene-api.d.ts +195 -3
- package/dist/womp-scene-api.js +102 -73
- package/package.json +66 -10
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { once } from "node:events";
|
|
2
|
+
import express from "express";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { SPARK_RUN_STATUSES } from "../ui.js";
|
|
5
|
+
import { SparkServiceError } from "./service.js";
|
|
6
|
+
const reasoningEffortSchema = z.enum(["low", "medium", "high", "xhigh", "max"]);
|
|
7
|
+
const messageSchema = z.object({
|
|
8
|
+
id: z.string().min(1),
|
|
9
|
+
role: z.enum(["system", "user", "assistant"]),
|
|
10
|
+
metadata: z.unknown().optional(),
|
|
11
|
+
parts: z.array(z.unknown()),
|
|
12
|
+
});
|
|
13
|
+
const submitSchema = z.object({
|
|
14
|
+
trigger: z.enum(["submit-message", "regenerate-message"]),
|
|
15
|
+
message: messageSchema,
|
|
16
|
+
messageId: z.string().optional(),
|
|
17
|
+
settings: z.object({
|
|
18
|
+
modelId: z.string().min(1),
|
|
19
|
+
reasoningEffort: reasoningEffortSchema,
|
|
20
|
+
}),
|
|
21
|
+
});
|
|
22
|
+
function parseSequence(value) {
|
|
23
|
+
if (typeof value !== "string" || /^\d+$/u.test(value) === false)
|
|
24
|
+
return 0;
|
|
25
|
+
const sequence = Number(value);
|
|
26
|
+
return Number.isSafeInteger(sequence) ? sequence : 0;
|
|
27
|
+
}
|
|
28
|
+
function encodeFilename(value) {
|
|
29
|
+
return encodeURIComponent(value).replace(/[!'()*]/gu, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
30
|
+
}
|
|
31
|
+
async function write(response, value) {
|
|
32
|
+
if (response.write(value))
|
|
33
|
+
return;
|
|
34
|
+
await once(response, "drain");
|
|
35
|
+
}
|
|
36
|
+
export function createSparkAgentRouter(options) {
|
|
37
|
+
const router = express.Router();
|
|
38
|
+
const resolveOwnerId = options.resolveOwnerId ?? (() => "local");
|
|
39
|
+
const heartbeatMs = options.heartbeatMs ?? 15_000;
|
|
40
|
+
router.use(express.json({ limit: options.jsonLimit ?? "25mb" }));
|
|
41
|
+
router.get("/conversations", async (request, response) => {
|
|
42
|
+
const ownerId = await resolveOwnerId(request);
|
|
43
|
+
response.json({ conversations: await options.service.listConversations(ownerId) });
|
|
44
|
+
});
|
|
45
|
+
router.post("/conversations", async (request, response) => {
|
|
46
|
+
const ownerId = await resolveOwnerId(request);
|
|
47
|
+
const body = z.object({
|
|
48
|
+
id: z.string().min(1).optional(),
|
|
49
|
+
title: z.string().max(200).optional(),
|
|
50
|
+
}).parse(request.body ?? {});
|
|
51
|
+
const conversation = await options.service.createConversation(ownerId, body);
|
|
52
|
+
response.status(201).json({ conversation });
|
|
53
|
+
});
|
|
54
|
+
router.get("/conversations/:conversationId", async (request, response) => {
|
|
55
|
+
const ownerId = await resolveOwnerId(request);
|
|
56
|
+
const conversation = await options.service.getConversation(ownerId, request.params.conversationId);
|
|
57
|
+
response.json({ conversation });
|
|
58
|
+
});
|
|
59
|
+
router.post("/conversations/:conversationId/messages", async (request, response) => {
|
|
60
|
+
const ownerId = await resolveOwnerId(request);
|
|
61
|
+
const body = submitSchema.parse(request.body);
|
|
62
|
+
const run = await options.service.submitMessage({
|
|
63
|
+
ownerId,
|
|
64
|
+
conversationId: request.params.conversationId,
|
|
65
|
+
trigger: body.trigger,
|
|
66
|
+
message: body.message,
|
|
67
|
+
messageId: body.messageId,
|
|
68
|
+
settings: body.settings,
|
|
69
|
+
});
|
|
70
|
+
response.status(202).json({ run });
|
|
71
|
+
});
|
|
72
|
+
router.get("/conversations/:conversationId/active-run", async (request, response) => {
|
|
73
|
+
const ownerId = await resolveOwnerId(request);
|
|
74
|
+
const run = await options.service.getActiveRun(ownerId, request.params.conversationId);
|
|
75
|
+
if (run === undefined) {
|
|
76
|
+
response.status(204).end();
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
response.json({ run });
|
|
80
|
+
});
|
|
81
|
+
router.get("/runs/:runId", async (request, response) => {
|
|
82
|
+
const ownerId = await resolveOwnerId(request);
|
|
83
|
+
response.json({ run: await options.service.getRun(ownerId, request.params.runId) });
|
|
84
|
+
});
|
|
85
|
+
router.post("/runs/:runId/cancel", async (request, response) => {
|
|
86
|
+
const ownerId = await resolveOwnerId(request);
|
|
87
|
+
response.json({ run: await options.service.cancelRun(ownerId, request.params.runId) });
|
|
88
|
+
});
|
|
89
|
+
router.get("/runs/:runId/stream", async (request, response) => {
|
|
90
|
+
const ownerId = await resolveOwnerId(request);
|
|
91
|
+
await options.service.getRun(ownerId, request.params.runId);
|
|
92
|
+
const abortController = new AbortController();
|
|
93
|
+
response.on("close", () => abortController.abort());
|
|
94
|
+
response.status(200);
|
|
95
|
+
response.set({
|
|
96
|
+
"Cache-Control": "no-cache, no-transform",
|
|
97
|
+
Connection: "keep-alive",
|
|
98
|
+
"Content-Type": "text/event-stream; charset=utf-8",
|
|
99
|
+
"X-Accel-Buffering": "no",
|
|
100
|
+
});
|
|
101
|
+
response.flushHeaders();
|
|
102
|
+
const chunks = options.service.streamRun(ownerId, request.params.runId, parseSequence(request.query.after ?? request.get("Last-Event-ID")), abortController.signal);
|
|
103
|
+
let pending = chunks.next();
|
|
104
|
+
try {
|
|
105
|
+
while (abortController.signal.aborted === false) {
|
|
106
|
+
let heartbeatTimer;
|
|
107
|
+
const next = await Promise.race([
|
|
108
|
+
pending.then((result) => ({ type: "chunk", result })),
|
|
109
|
+
new Promise((resolve) => {
|
|
110
|
+
heartbeatTimer = setTimeout(() => resolve({ type: "heartbeat" }), heartbeatMs);
|
|
111
|
+
}),
|
|
112
|
+
]);
|
|
113
|
+
if (heartbeatTimer !== undefined)
|
|
114
|
+
clearTimeout(heartbeatTimer);
|
|
115
|
+
if (next.type === "heartbeat") {
|
|
116
|
+
await write(response, ": ping\n\n");
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (next.result.done)
|
|
120
|
+
break;
|
|
121
|
+
const chunk = next.result.value;
|
|
122
|
+
await write(response, `id: ${chunk.sequence}\ndata: ${JSON.stringify(chunk)}\n\n`);
|
|
123
|
+
pending = chunks.next();
|
|
124
|
+
}
|
|
125
|
+
await write(response, "data: [DONE]\n\n");
|
|
126
|
+
}
|
|
127
|
+
finally {
|
|
128
|
+
await chunks.return(undefined);
|
|
129
|
+
response.end();
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
if (options.artifactStore !== undefined) {
|
|
133
|
+
router.get("/artifacts/:artifactId", async (request, response) => {
|
|
134
|
+
const ownerId = await resolveOwnerId(request);
|
|
135
|
+
const artifact = await options.artifactStore?.get(ownerId, request.params.artifactId);
|
|
136
|
+
if (artifact === undefined)
|
|
137
|
+
throw new SparkServiceError(404, "Artifact not found.");
|
|
138
|
+
response.set({
|
|
139
|
+
"Cache-Control": "private, max-age=3600",
|
|
140
|
+
"Content-Disposition": `inline; filename*=UTF-8''${encodeFilename(artifact.name ?? artifact.id)}`,
|
|
141
|
+
"Content-Type": artifact.mediaType,
|
|
142
|
+
});
|
|
143
|
+
response.send(Buffer.from(artifact.data));
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
router.use((error, _request, response, _next) => {
|
|
147
|
+
if (error instanceof SparkServiceError) {
|
|
148
|
+
response.status(error.statusCode).json({ error: error.message });
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
if (error instanceof z.ZodError) {
|
|
152
|
+
response.status(400).json({ error: "Invalid request.", issues: error.issues });
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
response.status(500).json({ error: "Internal Spark Agent error." });
|
|
156
|
+
});
|
|
157
|
+
return router;
|
|
158
|
+
}
|
|
159
|
+
export { SPARK_RUN_STATUSES };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { MemorySparkArtifactStore } from "./artifacts.js";
|
|
2
|
+
export type { SparkArtifactStore, StoredSparkArtifact } from "./artifacts.js";
|
|
3
|
+
export { createSparkRunExecutor, type ResolvedSparkModel, type SparkRunExecutorOptions, } from "./executor.js";
|
|
4
|
+
export { SparkAgentService, SparkServiceError } from "./service.js";
|
|
5
|
+
export type { SubmitSparkMessageInput } from "./service.js";
|
|
6
|
+
export { MemorySparkAgentStore } from "./store.js";
|
|
7
|
+
export { createStandaloneSparkAgentApp, type StandaloneSparkAgentOptions, } from "./standalone.js";
|
|
8
|
+
export type { SparkAgentStore, SparkConversation, SparkConversationSummary, SparkRun, SparkRunExecutionContext, SparkRunExecutor, SparkRunSettings, } from "./types.js";
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { MemorySparkArtifactStore } from "./artifacts.js";
|
|
2
|
+
export { createSparkRunExecutor, } from "./executor.js";
|
|
3
|
+
export { SparkAgentService, SparkServiceError } from "./service.js";
|
|
4
|
+
export { MemorySparkAgentStore } from "./store.js";
|
|
5
|
+
export { createStandaloneSparkAgentApp, } from "./standalone.js";
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { type SparkUIMessage, type StoredSparkChunk } from "../ui.js";
|
|
2
|
+
import type { SparkAgentStore, SparkConversation, SparkConversationSummary, SparkRun, SparkRunExecutor, SparkRunSettings } from "./types.js";
|
|
3
|
+
export declare class SparkServiceError extends Error {
|
|
4
|
+
readonly statusCode: number;
|
|
5
|
+
constructor(statusCode: number, message: string);
|
|
6
|
+
}
|
|
7
|
+
export type SubmitSparkMessageInput = {
|
|
8
|
+
ownerId: string;
|
|
9
|
+
conversationId: string;
|
|
10
|
+
trigger: "submit-message" | "regenerate-message";
|
|
11
|
+
message: SparkUIMessage;
|
|
12
|
+
messageId?: string;
|
|
13
|
+
settings: SparkRunSettings;
|
|
14
|
+
};
|
|
15
|
+
export declare class SparkAgentService {
|
|
16
|
+
private readonly store;
|
|
17
|
+
private readonly executeRun;
|
|
18
|
+
private readonly controllers;
|
|
19
|
+
private readonly listeners;
|
|
20
|
+
constructor(options: {
|
|
21
|
+
store: SparkAgentStore;
|
|
22
|
+
executeRun: SparkRunExecutor;
|
|
23
|
+
});
|
|
24
|
+
createConversation(ownerId: string, input?: {
|
|
25
|
+
id?: string;
|
|
26
|
+
title?: string;
|
|
27
|
+
}): Promise<SparkConversation>;
|
|
28
|
+
listConversations(ownerId: string): Promise<SparkConversationSummary[]>;
|
|
29
|
+
getConversation(ownerId: string, id: string): Promise<SparkConversation>;
|
|
30
|
+
getRun(ownerId: string, id: string): Promise<SparkRun>;
|
|
31
|
+
getActiveRun(ownerId: string, conversationId: string): Promise<SparkRun | undefined>;
|
|
32
|
+
submitMessage(input: SubmitSparkMessageInput): Promise<SparkRun>;
|
|
33
|
+
cancelRun(ownerId: string, runId: string): Promise<SparkRun>;
|
|
34
|
+
streamRun(ownerId: string, runId: string, afterSequence: number, signal: AbortSignal): AsyncGenerator<StoredSparkChunk>;
|
|
35
|
+
private runInBackground;
|
|
36
|
+
private finishRun;
|
|
37
|
+
private materializeMessage;
|
|
38
|
+
private appendStatus;
|
|
39
|
+
private appendChunk;
|
|
40
|
+
private wakeRun;
|
|
41
|
+
}
|
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
import { readUIMessageStream, validateUIMessages } from "ai";
|
|
2
|
+
import { sparkDataPartSchemas, sparkMessageMetadataSchema, } from "../ui.js";
|
|
3
|
+
const TERMINAL_STATUSES = new Set([
|
|
4
|
+
"completed",
|
|
5
|
+
"failed",
|
|
6
|
+
"cancelled",
|
|
7
|
+
"incomplete",
|
|
8
|
+
]);
|
|
9
|
+
export class SparkServiceError extends Error {
|
|
10
|
+
statusCode;
|
|
11
|
+
constructor(statusCode, message) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.name = "SparkServiceError";
|
|
14
|
+
this.statusCode = statusCode;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
function now() {
|
|
18
|
+
return new Date().toISOString();
|
|
19
|
+
}
|
|
20
|
+
function messageText(message) {
|
|
21
|
+
return message.parts
|
|
22
|
+
.filter((part) => part.type === "text")
|
|
23
|
+
.map(({ text }) => text)
|
|
24
|
+
.join(" ")
|
|
25
|
+
.trim();
|
|
26
|
+
}
|
|
27
|
+
function titleFor(message) {
|
|
28
|
+
const text = messageText(message).replace(/\s+/gu, " ");
|
|
29
|
+
if (text.length === 0)
|
|
30
|
+
return "New build";
|
|
31
|
+
return text.length > 44 ? `${text.slice(0, 44)}…` : text;
|
|
32
|
+
}
|
|
33
|
+
function chunkStream(chunks) {
|
|
34
|
+
return new ReadableStream({
|
|
35
|
+
start(controller) {
|
|
36
|
+
for (const chunk of chunks)
|
|
37
|
+
controller.enqueue(chunk);
|
|
38
|
+
controller.close();
|
|
39
|
+
},
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
function normalizeUserMessage(message) {
|
|
43
|
+
if (message.role !== "user") {
|
|
44
|
+
throw new SparkServiceError(400, "A new chat message must have the user role.");
|
|
45
|
+
}
|
|
46
|
+
for (const part of message.parts) {
|
|
47
|
+
if (part.type === "text")
|
|
48
|
+
continue;
|
|
49
|
+
if (part.type === "file" &&
|
|
50
|
+
part.mediaType.startsWith("image/") &&
|
|
51
|
+
part.url.startsWith(`data:${part.mediaType};base64,`)) {
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
if (part.type === "file") {
|
|
55
|
+
throw new SparkServiceError(400, "Only inline image attachments are supported.");
|
|
56
|
+
}
|
|
57
|
+
throw new SparkServiceError(400, `User message part ${part.type} is not supported.`);
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
...message,
|
|
61
|
+
metadata: {
|
|
62
|
+
createdAt: message.metadata?.createdAt ?? now(),
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
export class SparkAgentService {
|
|
67
|
+
store;
|
|
68
|
+
executeRun;
|
|
69
|
+
controllers = new Map();
|
|
70
|
+
listeners = new Map();
|
|
71
|
+
constructor(options) {
|
|
72
|
+
this.store = options.store;
|
|
73
|
+
this.executeRun = options.executeRun;
|
|
74
|
+
}
|
|
75
|
+
async createConversation(ownerId, input) {
|
|
76
|
+
const createdAt = now();
|
|
77
|
+
const conversation = {
|
|
78
|
+
id: input?.id ?? crypto.randomUUID(),
|
|
79
|
+
ownerId,
|
|
80
|
+
title: input?.title?.trim() || "New build",
|
|
81
|
+
messages: [],
|
|
82
|
+
createdAt,
|
|
83
|
+
updatedAt: createdAt,
|
|
84
|
+
};
|
|
85
|
+
await this.store.createConversation(conversation);
|
|
86
|
+
return conversation;
|
|
87
|
+
}
|
|
88
|
+
async listConversations(ownerId) {
|
|
89
|
+
return this.store.listConversations(ownerId);
|
|
90
|
+
}
|
|
91
|
+
async getConversation(ownerId, id) {
|
|
92
|
+
const conversation = await this.store.getConversation(id);
|
|
93
|
+
if (conversation === undefined || conversation.ownerId !== ownerId) {
|
|
94
|
+
throw new SparkServiceError(404, "Conversation not found.");
|
|
95
|
+
}
|
|
96
|
+
return conversation;
|
|
97
|
+
}
|
|
98
|
+
async getRun(ownerId, id) {
|
|
99
|
+
const run = await this.store.getRun(id);
|
|
100
|
+
if (run === undefined)
|
|
101
|
+
throw new SparkServiceError(404, "Run not found.");
|
|
102
|
+
await this.getConversation(ownerId, run.conversationId);
|
|
103
|
+
return run;
|
|
104
|
+
}
|
|
105
|
+
async getActiveRun(ownerId, conversationId) {
|
|
106
|
+
const conversation = await this.getConversation(ownerId, conversationId);
|
|
107
|
+
if (conversation.activeRunId === undefined)
|
|
108
|
+
return undefined;
|
|
109
|
+
const run = await this.store.getRun(conversation.activeRunId);
|
|
110
|
+
if (run === undefined || TERMINAL_STATUSES.has(run.status))
|
|
111
|
+
return undefined;
|
|
112
|
+
return run;
|
|
113
|
+
}
|
|
114
|
+
async submitMessage(input) {
|
|
115
|
+
const conversation = await this.getConversation(input.ownerId, input.conversationId);
|
|
116
|
+
const activeRun = conversation.activeRunId === undefined
|
|
117
|
+
? undefined
|
|
118
|
+
: await this.store.getRun(conversation.activeRunId);
|
|
119
|
+
if (activeRun !== undefined && TERMINAL_STATUSES.has(activeRun.status) === false) {
|
|
120
|
+
throw new SparkServiceError(409, "This conversation already has an active run.");
|
|
121
|
+
}
|
|
122
|
+
let inputMessage;
|
|
123
|
+
if (input.trigger === "regenerate-message") {
|
|
124
|
+
const targetId = input.messageId ?? input.message.id;
|
|
125
|
+
const targetIndex = conversation.messages.findIndex(({ id }) => id === targetId);
|
|
126
|
+
if (targetIndex < 0 || conversation.messages[targetIndex]?.role !== "assistant") {
|
|
127
|
+
throw new SparkServiceError(400, "The assistant message to regenerate was not found.");
|
|
128
|
+
}
|
|
129
|
+
conversation.messages = conversation.messages.slice(0, targetIndex);
|
|
130
|
+
const previous = conversation.messages.at(-1);
|
|
131
|
+
if (previous === undefined || previous.role !== "user") {
|
|
132
|
+
throw new SparkServiceError(400, "Regeneration requires a preceding user message.");
|
|
133
|
+
}
|
|
134
|
+
inputMessage = previous;
|
|
135
|
+
}
|
|
136
|
+
else {
|
|
137
|
+
inputMessage = normalizeUserMessage(input.message);
|
|
138
|
+
if (conversation.messages.some(({ id }) => id === inputMessage.id)) {
|
|
139
|
+
throw new SparkServiceError(409, "This message was already submitted.");
|
|
140
|
+
}
|
|
141
|
+
conversation.messages.push(inputMessage);
|
|
142
|
+
}
|
|
143
|
+
const validatedMessages = await validateUIMessages({
|
|
144
|
+
messages: conversation.messages,
|
|
145
|
+
metadataSchema: sparkMessageMetadataSchema,
|
|
146
|
+
dataSchemas: sparkDataPartSchemas,
|
|
147
|
+
});
|
|
148
|
+
conversation.messages = validatedMessages;
|
|
149
|
+
if (conversation.messages.filter(({ role }) => role === "user").length === 1) {
|
|
150
|
+
conversation.title = titleFor(inputMessage);
|
|
151
|
+
}
|
|
152
|
+
const runId = crypto.randomUUID();
|
|
153
|
+
const createdAt = now();
|
|
154
|
+
const run = {
|
|
155
|
+
id: runId,
|
|
156
|
+
conversationId: conversation.id,
|
|
157
|
+
inputMessageId: inputMessage.id,
|
|
158
|
+
assistantMessageId: crypto.randomUUID(),
|
|
159
|
+
status: "queued",
|
|
160
|
+
settings: input.settings,
|
|
161
|
+
createdAt,
|
|
162
|
+
updatedAt: createdAt,
|
|
163
|
+
};
|
|
164
|
+
conversation.activeRunId = run.id;
|
|
165
|
+
conversation.updatedAt = createdAt;
|
|
166
|
+
await this.store.saveConversation(conversation);
|
|
167
|
+
await this.store.createRun(run);
|
|
168
|
+
await this.appendChunk(run, {
|
|
169
|
+
type: "start",
|
|
170
|
+
messageId: run.assistantMessageId,
|
|
171
|
+
messageMetadata: {
|
|
172
|
+
createdAt,
|
|
173
|
+
runId: run.id,
|
|
174
|
+
runStatus: "queued",
|
|
175
|
+
modelId: run.settings.modelId,
|
|
176
|
+
},
|
|
177
|
+
});
|
|
178
|
+
await this.appendStatus(run, "queued");
|
|
179
|
+
const controller = new AbortController();
|
|
180
|
+
this.controllers.set(run.id, controller);
|
|
181
|
+
void this.runInBackground(run, conversation, controller);
|
|
182
|
+
return run;
|
|
183
|
+
}
|
|
184
|
+
async cancelRun(ownerId, runId) {
|
|
185
|
+
const run = await this.getRun(ownerId, runId);
|
|
186
|
+
if (TERMINAL_STATUSES.has(run.status))
|
|
187
|
+
return run;
|
|
188
|
+
await this.appendStatus(run, "cancelled");
|
|
189
|
+
this.controllers.get(run.id)?.abort(new Error("Run cancelled by the user."));
|
|
190
|
+
const completedAt = now();
|
|
191
|
+
const cancelled = {
|
|
192
|
+
...run,
|
|
193
|
+
status: "cancelled",
|
|
194
|
+
updatedAt: completedAt,
|
|
195
|
+
completedAt,
|
|
196
|
+
};
|
|
197
|
+
await this.store.saveRun(cancelled);
|
|
198
|
+
this.wakeRun(run.id);
|
|
199
|
+
return cancelled;
|
|
200
|
+
}
|
|
201
|
+
async *streamRun(ownerId, runId, afterSequence, signal) {
|
|
202
|
+
await this.getRun(ownerId, runId);
|
|
203
|
+
const queue = [];
|
|
204
|
+
let wake;
|
|
205
|
+
let notification = 0;
|
|
206
|
+
const listener = (chunk) => {
|
|
207
|
+
if (chunk !== undefined)
|
|
208
|
+
queue.push(chunk);
|
|
209
|
+
notification += 1;
|
|
210
|
+
wake?.();
|
|
211
|
+
wake = undefined;
|
|
212
|
+
};
|
|
213
|
+
const runListeners = this.listeners.get(runId) ?? new Set();
|
|
214
|
+
runListeners.add(listener);
|
|
215
|
+
this.listeners.set(runId, runListeners);
|
|
216
|
+
let lastSequence = afterSequence;
|
|
217
|
+
try {
|
|
218
|
+
const stored = await this.store.listRunChunks(runId, afterSequence);
|
|
219
|
+
queue.push(...stored);
|
|
220
|
+
queue.sort((left, right) => left.sequence - right.sequence);
|
|
221
|
+
while (signal.aborted === false) {
|
|
222
|
+
while (queue.length > 0) {
|
|
223
|
+
const chunk = queue.shift();
|
|
224
|
+
if (chunk === undefined || chunk.sequence <= lastSequence)
|
|
225
|
+
continue;
|
|
226
|
+
lastSequence = chunk.sequence;
|
|
227
|
+
yield chunk;
|
|
228
|
+
}
|
|
229
|
+
const observedNotification = notification;
|
|
230
|
+
const run = await this.store.getRun(runId);
|
|
231
|
+
if (run === undefined || TERMINAL_STATUSES.has(run.status))
|
|
232
|
+
return;
|
|
233
|
+
if (notification !== observedNotification || queue.length > 0)
|
|
234
|
+
continue;
|
|
235
|
+
await new Promise((resolve) => {
|
|
236
|
+
const onAbort = () => {
|
|
237
|
+
wake = undefined;
|
|
238
|
+
resolve();
|
|
239
|
+
};
|
|
240
|
+
wake = () => {
|
|
241
|
+
signal.removeEventListener("abort", onAbort);
|
|
242
|
+
wake = undefined;
|
|
243
|
+
resolve();
|
|
244
|
+
};
|
|
245
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
246
|
+
if (notification !== observedNotification || queue.length > 0)
|
|
247
|
+
wake?.();
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
finally {
|
|
252
|
+
runListeners.delete(listener);
|
|
253
|
+
if (runListeners.size === 0)
|
|
254
|
+
this.listeners.delete(runId);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
async runInBackground(run, conversation, controller) {
|
|
258
|
+
const startedAt = now();
|
|
259
|
+
run = {
|
|
260
|
+
...run,
|
|
261
|
+
status: "running",
|
|
262
|
+
startedAt,
|
|
263
|
+
updatedAt: startedAt,
|
|
264
|
+
};
|
|
265
|
+
await this.store.saveRun(run);
|
|
266
|
+
const runningChunk = {
|
|
267
|
+
type: "data-run-status",
|
|
268
|
+
id: `run-status-${run.id}`,
|
|
269
|
+
data: { runId: run.id, status: "running" },
|
|
270
|
+
};
|
|
271
|
+
await this.appendChunk(run, runningChunk);
|
|
272
|
+
try {
|
|
273
|
+
const execution = await this.executeRun({
|
|
274
|
+
ownerId: conversation.ownerId,
|
|
275
|
+
conversationId: conversation.id,
|
|
276
|
+
runId: run.id,
|
|
277
|
+
assistantMessageId: run.assistantMessageId,
|
|
278
|
+
uiMessages: conversation.messages,
|
|
279
|
+
settings: run.settings,
|
|
280
|
+
signal: controller.signal,
|
|
281
|
+
});
|
|
282
|
+
const consume = (async () => {
|
|
283
|
+
for await (const chunk of execution.stream) {
|
|
284
|
+
if (chunk.type === "start")
|
|
285
|
+
continue;
|
|
286
|
+
await this.appendChunk(run, chunk);
|
|
287
|
+
}
|
|
288
|
+
})();
|
|
289
|
+
let executionError;
|
|
290
|
+
let result;
|
|
291
|
+
try {
|
|
292
|
+
result = await execution.result;
|
|
293
|
+
}
|
|
294
|
+
catch (error) {
|
|
295
|
+
executionError = error;
|
|
296
|
+
}
|
|
297
|
+
await consume;
|
|
298
|
+
if (executionError !== undefined)
|
|
299
|
+
throw executionError;
|
|
300
|
+
if (controller.signal.aborted) {
|
|
301
|
+
await this.finishRun(run, conversation, "cancelled");
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
const status = result?.status ?? "incomplete";
|
|
305
|
+
await this.appendStatus(run, status);
|
|
306
|
+
await this.finishRun(run, conversation, status);
|
|
307
|
+
}
|
|
308
|
+
catch (error) {
|
|
309
|
+
if (controller.signal.aborted) {
|
|
310
|
+
await this.finishRun(run, conversation, "cancelled");
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
314
|
+
const failedChunk = {
|
|
315
|
+
type: "data-run-status",
|
|
316
|
+
id: `run-status-${run.id}`,
|
|
317
|
+
data: { runId: run.id, status: "failed", error: message },
|
|
318
|
+
};
|
|
319
|
+
await this.appendChunk(run, { type: "error", errorText: message });
|
|
320
|
+
await this.appendChunk(run, failedChunk);
|
|
321
|
+
await this.finishRun(run, conversation, "failed", message);
|
|
322
|
+
}
|
|
323
|
+
finally {
|
|
324
|
+
this.controllers.delete(run.id);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
async finishRun(run, conversation, status, error) {
|
|
328
|
+
const completedAt = now();
|
|
329
|
+
const storedChunks = await this.store.listRunChunks(run.id, 0);
|
|
330
|
+
const chunks = storedChunks.map(({ chunk }) => chunk);
|
|
331
|
+
const assistant = await this.materializeMessage(run, chunks, status, completedAt, error);
|
|
332
|
+
if (assistant !== undefined) {
|
|
333
|
+
await this.appendChunk(run, {
|
|
334
|
+
type: "message-metadata",
|
|
335
|
+
messageMetadata: assistant.metadata,
|
|
336
|
+
});
|
|
337
|
+
const existingIndex = conversation.messages.findIndex(({ id }) => id === assistant.id);
|
|
338
|
+
if (existingIndex >= 0)
|
|
339
|
+
conversation.messages[existingIndex] = assistant;
|
|
340
|
+
else
|
|
341
|
+
conversation.messages.push(assistant);
|
|
342
|
+
}
|
|
343
|
+
conversation.activeRunId = undefined;
|
|
344
|
+
conversation.updatedAt = completedAt;
|
|
345
|
+
await this.store.saveConversation(conversation);
|
|
346
|
+
await this.store.saveRun({
|
|
347
|
+
...run,
|
|
348
|
+
status,
|
|
349
|
+
...(error === undefined ? {} : { error }),
|
|
350
|
+
updatedAt: completedAt,
|
|
351
|
+
completedAt,
|
|
352
|
+
});
|
|
353
|
+
this.wakeRun(run.id);
|
|
354
|
+
}
|
|
355
|
+
async materializeMessage(run, chunks, status, completedAt, error) {
|
|
356
|
+
let message;
|
|
357
|
+
try {
|
|
358
|
+
for await (const current of readUIMessageStream({
|
|
359
|
+
stream: chunkStream(chunks),
|
|
360
|
+
terminateOnError: false,
|
|
361
|
+
})) {
|
|
362
|
+
message = current;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
catch {
|
|
366
|
+
return undefined;
|
|
367
|
+
}
|
|
368
|
+
if (message === undefined)
|
|
369
|
+
return undefined;
|
|
370
|
+
return {
|
|
371
|
+
...message,
|
|
372
|
+
id: run.assistantMessageId,
|
|
373
|
+
metadata: {
|
|
374
|
+
createdAt: message.metadata?.createdAt ?? run.createdAt,
|
|
375
|
+
completedAt,
|
|
376
|
+
durationMs: message.metadata?.durationMs ??
|
|
377
|
+
Math.max(0, Date.parse(completedAt) - Date.parse(run.startedAt ?? run.createdAt)),
|
|
378
|
+
runId: run.id,
|
|
379
|
+
runStatus: status,
|
|
380
|
+
modelId: run.settings.modelId,
|
|
381
|
+
...(message.metadata?.usage === undefined ? {} : { usage: message.metadata.usage }),
|
|
382
|
+
...(error === undefined ? {} : { error }),
|
|
383
|
+
},
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
async appendStatus(run, status) {
|
|
387
|
+
await this.appendChunk(run, {
|
|
388
|
+
type: "data-run-status",
|
|
389
|
+
id: `run-status-${run.id}`,
|
|
390
|
+
data: { runId: run.id, status },
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
async appendChunk(run, chunk) {
|
|
394
|
+
const stored = await this.store.appendRunChunk(run.id, run.conversationId, chunk);
|
|
395
|
+
for (const listener of this.listeners.get(run.id) ?? [])
|
|
396
|
+
listener(stored);
|
|
397
|
+
}
|
|
398
|
+
wakeRun(runId) {
|
|
399
|
+
for (const listener of this.listeners.get(runId) ?? [])
|
|
400
|
+
listener();
|
|
401
|
+
}
|
|
402
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type Express } from "express";
|
|
2
|
+
export type StandaloneSparkAgentOptions = {
|
|
3
|
+
openAiApiKey?: string;
|
|
4
|
+
anthropicApiKey?: string;
|
|
5
|
+
kakapoUrl: string;
|
|
6
|
+
apiBasePath?: string;
|
|
7
|
+
developmentProfile?: "demo-account";
|
|
8
|
+
};
|
|
9
|
+
export declare function createStandaloneSparkAgentApp(options: StandaloneSparkAgentOptions): Express;
|