@womp/spark-agent 9.4.0 → 10.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.
- package/CHANGELOG.md +74 -0
- package/README.md +11 -11
- package/dist/agent-run.d.ts +1 -1
- package/dist/agent-tools.d.ts +7 -13
- package/dist/agent-tools.js +36 -35
- package/dist/agent.d.ts +3 -3
- package/dist/capabilities/flow-runs.d.ts +9 -0
- package/dist/capabilities/flow-runs.js +1 -0
- package/dist/capabilities.d.ts +1 -1
- package/dist/client.d.ts +1 -1
- package/dist/generated/flow-runs-declarations.d.ts +1 -1
- package/dist/generated/flow-runs-declarations.js +1 -1
- package/dist/goals.d.ts +52 -45
- package/dist/goals.js +16 -24
- package/dist/intent-bench.js +69 -21
- package/dist/model-history.js +5 -1
- package/dist/server/executor.js +1 -1
- package/dist/server/goal-evaluator.d.ts +1 -1
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.js +1 -1
- package/dist/server/service.d.ts +27 -19
- package/dist/server/service.js +137 -60
- package/dist/server/standalone.d.ts +1 -1
- package/dist/server/standalone.js +0 -21
- package/dist/server/types.d.ts +3 -3
- package/dist/ui.d.ts +67 -27
- package/dist/ui.js +32 -6
- package/package.json +1 -1
package/dist/intent-bench.js
CHANGED
|
@@ -116,31 +116,71 @@ async function intentFixtures(testCase, controller) {
|
|
|
116
116
|
};
|
|
117
117
|
const files = new Map();
|
|
118
118
|
const assets = [];
|
|
119
|
-
const
|
|
120
|
-
const
|
|
119
|
+
const jobs = [];
|
|
120
|
+
const history = [];
|
|
121
|
+
const addFile = async (image, id, messageId, source) => {
|
|
121
122
|
const loaded = await loadImage(image);
|
|
122
|
-
const
|
|
123
|
-
files.set(id, { artifact: {
|
|
124
|
-
assets.push({ artifact
|
|
125
|
-
return loaded;
|
|
123
|
+
const artifact = { id, mediaType: loaded.mediaType, name: loaded.name };
|
|
124
|
+
files.set(id, { artifact: { ...artifact, url: `fixture://${id}` }, data: loaded.data });
|
|
125
|
+
assets.push({ artifact, messageId, kind: "image", source });
|
|
126
|
+
return { artifact, loaded };
|
|
126
127
|
};
|
|
128
|
+
// Stored as Swan and Crow store it, so Spark's own conversion builds the model input: an
|
|
129
|
+
// earlier generation is replayed as its execute_javascript call and completed result.
|
|
127
130
|
for (const [index, turn] of testCase.turns.entries()) {
|
|
128
131
|
const messageId = 1001 + index;
|
|
129
132
|
if (turn.role === "assistant") {
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
+
const parts = [];
|
|
134
|
+
if (turn.generated?.length) {
|
|
135
|
+
const outputs = [];
|
|
136
|
+
for (const [n, image] of turn.generated.entries())
|
|
137
|
+
outputs.push((await addFile(image, `message:${messageId}:history:${7000 + index}:generated:${n}`, messageId, "generated")).artifact);
|
|
138
|
+
const job = { messageId, operationId: 8000 + index, type: "text-to-image", status: "completed", outputs };
|
|
139
|
+
jobs.push(job);
|
|
140
|
+
const asked = testCase.turns.slice(0, index).reverse().find((item) => item.role === "user")?.text ?? "";
|
|
141
|
+
const key = `history-image-${messageId}`;
|
|
142
|
+
const purpose = "Generating the image";
|
|
143
|
+
const result = { status: "completed", job };
|
|
144
|
+
parts.push({
|
|
145
|
+
type: "tool-execute_javascript",
|
|
146
|
+
toolCallId: `call-${key}`,
|
|
147
|
+
state: "output-available",
|
|
148
|
+
input: {
|
|
149
|
+
purpose,
|
|
150
|
+
code: `const result = await womp.operations.generate(${JSON.stringify({ key, type: "text-to-image", prompt: asked })});\nprint(result);`,
|
|
151
|
+
},
|
|
152
|
+
output: {
|
|
153
|
+
version: 2,
|
|
154
|
+
ok: true,
|
|
155
|
+
purpose,
|
|
156
|
+
value: null,
|
|
157
|
+
logs: [JSON.stringify(result)],
|
|
158
|
+
receipts: [{
|
|
159
|
+
id: `history:call-${key}:${key}`,
|
|
160
|
+
capability: "operations",
|
|
161
|
+
operation: "start",
|
|
162
|
+
status: "submitted",
|
|
163
|
+
target: { requestId: `spark:generation:${key}`, messageId },
|
|
164
|
+
details: { type: "text-to-image" },
|
|
165
|
+
}],
|
|
166
|
+
artifacts: [],
|
|
167
|
+
},
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
parts.push({ type: "text", text: turn.text });
|
|
171
|
+
history.push({ id: `message-${messageId}`, role: "assistant", parts });
|
|
133
172
|
continue;
|
|
134
173
|
}
|
|
135
|
-
const
|
|
136
|
-
for (const image of turn.images ?? []) {
|
|
137
|
-
const loaded = await addFile(image, messageId, "uploaded");
|
|
138
|
-
|
|
174
|
+
const parts = [];
|
|
175
|
+
for (const [n, image] of (turn.images ?? []).entries()) {
|
|
176
|
+
const { loaded } = await addFile(image, `uploaded-${messageId}-${n + 1}`, messageId, "uploaded");
|
|
177
|
+
parts.push({ type: "file", url: `data:${loaded.mediaType};base64,${Buffer.from(loaded.data).toString("base64")}`, mediaType: loaded.mediaType, filename: loaded.name });
|
|
139
178
|
}
|
|
140
179
|
if (turn.text)
|
|
141
|
-
|
|
142
|
-
|
|
180
|
+
parts.push({ type: "text", text: turn.text });
|
|
181
|
+
history.push({ id: `message-${messageId}`, role: "user", parts });
|
|
143
182
|
}
|
|
183
|
+
const job = (messageId, call) => structuredClone(jobs.find((item) => item.messageId === messageId) ?? refuse(call, `No job ${messageId}.`));
|
|
144
184
|
const screenshot = { id: "scene-screenshot", mediaType: "image/png", name: "scene.png" };
|
|
145
185
|
files.set(screenshot.id, { artifact: { ...screenshot, url: "fixture://scene-screenshot" }, data: solidPng([228, 228, 228]) });
|
|
146
186
|
// An empty scene: the root group and the default material. Materials are prepared for
|
|
@@ -277,13 +317,21 @@ async function intentFixtures(testCase, controller) {
|
|
|
277
317
|
confirmationRequired: false,
|
|
278
318
|
};
|
|
279
319
|
},
|
|
280
|
-
list: async () => {
|
|
320
|
+
list: async (options) => {
|
|
281
321
|
note("operations.list");
|
|
282
|
-
|
|
322
|
+
const from = options.from ?? 0;
|
|
323
|
+
const page = jobs.slice(from, from + (options.count ?? 20));
|
|
324
|
+
return { jobs: structuredClone(page), nextFrom: from + page.length < jobs.length ? from + page.length : null };
|
|
283
325
|
},
|
|
284
326
|
start: async (request) => decide(GENERATION_ROUTES[request.type], `operations.generate:${request.type}`, request),
|
|
285
|
-
read: async (messageId) =>
|
|
286
|
-
|
|
327
|
+
read: async (messageId) => {
|
|
328
|
+
note("operations.read");
|
|
329
|
+
return job(messageId, "operations.read");
|
|
330
|
+
},
|
|
331
|
+
wait: async (messageId) => {
|
|
332
|
+
note("operations.wait");
|
|
333
|
+
return { job: job(messageId, "operations.wait"), timedOut: false };
|
|
334
|
+
},
|
|
287
335
|
}),
|
|
288
336
|
account: createAccountCapability({ read: async () => missing("account.read", "Account information is unavailable right now.") }),
|
|
289
337
|
knowledge: createKnowledgeCapability({ search: async () => missing("knowledge.search", "Help search is unavailable right now.") }),
|
|
@@ -372,7 +420,7 @@ async function intentFixtures(testCase, controller) {
|
|
|
372
420
|
return file;
|
|
373
421
|
},
|
|
374
422
|
},
|
|
375
|
-
|
|
423
|
+
history,
|
|
376
424
|
messageId: String(1000 + testCase.turns.length),
|
|
377
425
|
executor: {
|
|
378
426
|
execute: (...args) => {
|
|
@@ -436,7 +484,7 @@ export async function runIntentCase(options) {
|
|
|
436
484
|
try {
|
|
437
485
|
const run = runSparkAgent({
|
|
438
486
|
...options.model,
|
|
439
|
-
|
|
487
|
+
history: fixtures.history,
|
|
440
488
|
capabilities: fixtures.capabilities,
|
|
441
489
|
executor: fixtures.executor,
|
|
442
490
|
artifacts: fixtures.artifacts,
|
package/dist/model-history.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { asSchema, convertToModelMessages } from "ai";
|
|
2
2
|
import { applyCompaction } from "./compaction.js";
|
|
3
|
-
import { sparkDataPartSchemas } from "./ui.js";
|
|
3
|
+
import { flowRunResultText, sparkDataPartSchemas } from "./ui.js";
|
|
4
4
|
function record(value) {
|
|
5
5
|
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
6
6
|
? value
|
|
@@ -60,6 +60,10 @@ export async function convertSparkMessages(messages, tools, options = {}) {
|
|
|
60
60
|
return convertToModelMessages(history, {
|
|
61
61
|
tools,
|
|
62
62
|
convertDataPart: (part) => {
|
|
63
|
+
if (part.type === "data-flow-run-result") {
|
|
64
|
+
const result = sparkDataPartSchemas["flow-run-result"].safeParse(part.data);
|
|
65
|
+
return result.success ? { type: "text", text: flowRunResultText(result.data) } : undefined;
|
|
66
|
+
}
|
|
63
67
|
if (part.type !== "data-selection")
|
|
64
68
|
return undefined;
|
|
65
69
|
const selection = sparkDataPartSchemas.selection.safeParse(part.data);
|
package/dist/server/executor.js
CHANGED
|
@@ -15,7 +15,7 @@ export function createSparkRunExecutor(options) {
|
|
|
15
15
|
runId: context.runId,
|
|
16
16
|
messageId: context.assistantMessageId,
|
|
17
17
|
signal: context.signal,
|
|
18
|
-
|
|
18
|
+
handleGoal: context.handleGoal,
|
|
19
19
|
});
|
|
20
20
|
return { stream: run.stream, result: run.result.finally(() => host.dispose()) };
|
|
21
21
|
}
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export { MemorySparkArtifactStore } from "./artifacts.js";
|
|
2
2
|
export { WompifyCreditCapReachedError } from "../wompify.js";
|
|
3
3
|
export { createSparkGoalEvaluator, GOAL_REFERENCE_IMAGES, type SparkGoalEvaluator, type SparkGoalEvaluation } from "./goal-evaluator.js";
|
|
4
|
-
export { sparkGoalCommandSchema,
|
|
4
|
+
export { sparkGoalCommandSchema, type SparkGoal, type SparkGoalCommand, type SparkGoalCondition, type SparkGoalTry } from "../goals.js";
|
|
5
5
|
export type { SparkArtifactStore, StoredSparkArtifact } from "./artifacts.js";
|
|
6
6
|
export { createSparkRunExecutor, type ResolvedSparkModel, type SparkRunExecutorOptions, } from "./executor.js";
|
|
7
7
|
export { DEFAULT_ENDING_RETRY_DELAYS_MS, RUN_INTERRUPTED_ERROR, RUN_NOT_SAVED_ERROR, SparkAgentService, SparkServiceError, } from "./service.js";
|
package/dist/server/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export { MemorySparkArtifactStore } from "./artifacts.js";
|
|
2
2
|
export { WompifyCreditCapReachedError } from "../wompify.js";
|
|
3
3
|
export { createSparkGoalEvaluator, GOAL_REFERENCE_IMAGES } from "./goal-evaluator.js";
|
|
4
|
-
export { sparkGoalCommandSchema
|
|
4
|
+
export { sparkGoalCommandSchema } from "../goals.js";
|
|
5
5
|
export { createSparkRunExecutor, } from "./executor.js";
|
|
6
6
|
export { DEFAULT_ENDING_RETRY_DELAYS_MS, RUN_INTERRUPTED_ERROR, RUN_NOT_SAVED_ERROR, SparkAgentService, SparkServiceError, } from "./service.js";
|
|
7
7
|
export { MemorySparkAgentStore } from "./store.js";
|
package/dist/server/service.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type SparkUIMessage, type StoredSparkChunk } from "../ui.js";
|
|
2
|
-
import { type SparkGoal, type SparkGoalCommand, type
|
|
2
|
+
import { type SparkGoal, type SparkGoalCommand, type SparkGoalSummary } from "../goals.js";
|
|
3
3
|
import { type SparkGoalEvaluator } from "./goal-evaluator.js";
|
|
4
4
|
import type { SparkAgentStore, SparkConversation, SparkConversationSummary, SparkRun, SparkRunExecutor, SparkRunSettings } from "./types.js";
|
|
5
5
|
/** Why a run ended when its progress could not be stored. */
|
|
@@ -13,23 +13,17 @@ export type SparkAgentServiceOptions = {
|
|
|
13
13
|
executeRun: SparkRunExecutor;
|
|
14
14
|
evaluateGoal?: SparkGoalEvaluator;
|
|
15
15
|
/**
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
16
|
+
* Called when the agent's `goal` call changes what its run works for, or ends
|
|
17
|
+
* a goal: `goal` is the goal the run now works for, if any, and `ended` the
|
|
18
|
+
* goal the call ended. It runs once the change is stored and before the agent
|
|
19
|
+
* goes on, for a host that counts what a goal spends. A change it refuses is
|
|
20
|
+
* undone.
|
|
19
21
|
*/
|
|
20
|
-
|
|
21
|
-
ownerId: string;
|
|
22
|
-
conversationId: string;
|
|
23
|
-
runId: string;
|
|
24
|
-
toolCallId: string;
|
|
25
|
-
proposal: SparkGoalProposal;
|
|
26
|
-
signal: AbortSignal;
|
|
27
|
-
}): Promise<SparkGoalDecision>;
|
|
28
|
-
/** Called once a confirmed goal is stored and before the agent goes on, for a host that counts what a goal spends. A goal it refuses does not start. */
|
|
29
|
-
onGoalStart?(input: {
|
|
22
|
+
onGoalChange?(input: {
|
|
30
23
|
ownerId: string;
|
|
31
24
|
run: SparkRun;
|
|
32
|
-
goal
|
|
25
|
+
goal?: SparkGoal;
|
|
26
|
+
ended?: SparkGoalSummary;
|
|
33
27
|
}): Promise<void>;
|
|
34
28
|
/** Charged and pending credits, including evaluations; reject if unavailable. */
|
|
35
29
|
readGoalCredits?(ownerId: string, goal: SparkGoal): Promise<number>;
|
|
@@ -55,13 +49,19 @@ export type SubmitSparkMessageInput = {
|
|
|
55
49
|
message: SparkUIMessage;
|
|
56
50
|
messageId?: string;
|
|
57
51
|
settings: SparkRunSettings;
|
|
52
|
+
/**
|
|
53
|
+
* Accept the host-only `data-flow-run-result` part on this message. Set only
|
|
54
|
+
* by host code, e.g. a follow-up the host starts itself. Never copy it from a
|
|
55
|
+
* request body: the express router builds this input field by field and does
|
|
56
|
+
* not set it.
|
|
57
|
+
*/
|
|
58
|
+
hostParts?: boolean;
|
|
58
59
|
};
|
|
59
60
|
export declare class SparkAgentService {
|
|
60
61
|
private readonly store;
|
|
61
62
|
private readonly executeRun;
|
|
62
63
|
private readonly evaluateGoal?;
|
|
63
|
-
private readonly
|
|
64
|
-
private readonly onGoalStart?;
|
|
64
|
+
private readonly onGoalChange?;
|
|
65
65
|
private readonly readGoalCredits?;
|
|
66
66
|
private readonly continuationSettings?;
|
|
67
67
|
private closing;
|
|
@@ -109,8 +109,16 @@ export declare class SparkAgentService {
|
|
|
109
109
|
cancelRun(ownerId: string, runId: string): Promise<SparkRun>;
|
|
110
110
|
streamRun(ownerId: string, runId: string, afterSequence: number, signal: AbortSignal): AsyncGenerator<StoredSparkChunk>;
|
|
111
111
|
private runInBackground;
|
|
112
|
-
/**
|
|
113
|
-
|
|
112
|
+
/**
|
|
113
|
+
* What the `goal` tool does for the run that called it. Only a turn the user
|
|
114
|
+
* started may set or change a goal, since its conditions and limits are what
|
|
115
|
+
* hold the service's own tries; and a Wompify goal is not the agent's to
|
|
116
|
+
* change. A goal that is set, changed or continued goes on with this run as
|
|
117
|
+
* its next try, unless the change completes it or it is still at a limit.
|
|
118
|
+
*/
|
|
119
|
+
private applyGoalRequest;
|
|
120
|
+
/** `current` with these caps and its credits read again. A cap below what the goal has used is refused. */
|
|
121
|
+
private withCaps;
|
|
114
122
|
private refreshGoalCredits;
|
|
115
123
|
private pauseRunGoal;
|
|
116
124
|
private advanceGoal;
|
package/dist/server/service.js
CHANGED
|
@@ -2,7 +2,7 @@ import { sparkErrorDiagnostics } from "../error-diagnostics.js";
|
|
|
2
2
|
import { validateUIMessages } from "ai";
|
|
3
3
|
import { foldAllChunks } from "./message-fold.js";
|
|
4
4
|
import { sparkDataPartSchemas, sparkMessageMetadataSchema, } from "../ui.js";
|
|
5
|
-
import { MAX_GOAL_LENGTH, sparkGoalCommandSchema
|
|
5
|
+
import { GOAL_DEFAULT_CAPS, GOAL_MORE_TRIES, MAX_GOAL_LENGTH, sparkGoalCommandSchema } from "../goals.js";
|
|
6
6
|
import { goalVerdictSchema } from "./goal-evaluator.js";
|
|
7
7
|
import { wompifyContextSchema, WompifyCreditCapReachedError } from "../wompify.js";
|
|
8
8
|
const TERMINAL_STATUSES = new Set([
|
|
@@ -52,7 +52,7 @@ function titleFor(message) {
|
|
|
52
52
|
return "New build";
|
|
53
53
|
return text.length > 44 ? `${text.slice(0, 44)}…` : text;
|
|
54
54
|
}
|
|
55
|
-
function normalizeUserMessage(message) {
|
|
55
|
+
function normalizeUserMessage(message, options = {}) {
|
|
56
56
|
if (message.role !== "user") {
|
|
57
57
|
throw new SparkServiceError(400, "A new chat message must have the user role.");
|
|
58
58
|
}
|
|
@@ -60,6 +60,8 @@ function normalizeUserMessage(message) {
|
|
|
60
60
|
// The data schemas are checked with the rest of the message (validateUIMessages).
|
|
61
61
|
if (part.type === "text" || part.type === "data-selection")
|
|
62
62
|
continue;
|
|
63
|
+
if (part.type === "data-flow-run-result" && options.hostParts === true)
|
|
64
|
+
continue;
|
|
63
65
|
if (part.type === "file" &&
|
|
64
66
|
part.mediaType.startsWith("image/") &&
|
|
65
67
|
part.url.startsWith(`data:${part.mediaType};base64,`)) {
|
|
@@ -90,6 +92,31 @@ function goalContinuationText(goal) {
|
|
|
90
92
|
+ (wompifyContextSchema.safeParse(goal.settings.wompify).success
|
|
91
93
|
? "\nKeep refining the existing reconstruction at the same detail level. Compare it with the reference and improve the remaining shape and color discrepancies." : "");
|
|
92
94
|
}
|
|
95
|
+
/** Whether the goal has used its tries, or its credits. */
|
|
96
|
+
function atGoalLimit(goal, limit) {
|
|
97
|
+
return limit === "tries"
|
|
98
|
+
? goal.maxTurns !== undefined && goal.turns >= goal.maxTurns
|
|
99
|
+
: goal.creditBudget !== undefined && (goal.creditsUsed ?? 0) >= goal.creditBudget;
|
|
100
|
+
}
|
|
101
|
+
/** `goal` with new conditions. A condition whose words are unchanged keeps what the checks found for it. */
|
|
102
|
+
function withConditions(goal, conditions) {
|
|
103
|
+
const before = goal.conditions ?? [];
|
|
104
|
+
const kept = conditions.map(({ text, measurable }) => before.findIndex((condition) => condition.text === text && condition.measurable === measurable));
|
|
105
|
+
return {
|
|
106
|
+
...goal,
|
|
107
|
+
conditions: conditions.map((condition, index) => ({ ...before[kept[index]], ...condition })),
|
|
108
|
+
...(goal.tries ? { tries: goal.tries.map((check) => ({ ...check, conditions: kept.map((index) => check.conditions[index] ?? {}) })) } : {}),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
/** What the chat keeps of a goal that ended. */
|
|
112
|
+
function goalSummary(goal, outcome) {
|
|
113
|
+
const measured = goal.conditions?.filter((condition) => condition.measurable) ?? [];
|
|
114
|
+
return {
|
|
115
|
+
title: goal.title ?? goal.objective, outcome, tries: goal.turns,
|
|
116
|
+
...(goal.creditsUsed === undefined ? {} : { credits: goal.creditsUsed }),
|
|
117
|
+
passed: measured.filter((condition) => condition.met).length, measured: measured.length,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
93
120
|
/** The goal's conditions with what this evaluation found for each measurable one. */
|
|
94
121
|
function judgedConditions(goal, evaluation) {
|
|
95
122
|
if (!goal.conditions || !evaluation?.conditions)
|
|
@@ -106,8 +133,7 @@ export class SparkAgentService {
|
|
|
106
133
|
store;
|
|
107
134
|
executeRun;
|
|
108
135
|
evaluateGoal;
|
|
109
|
-
|
|
110
|
-
onGoalStart;
|
|
136
|
+
onGoalChange;
|
|
111
137
|
readGoalCredits;
|
|
112
138
|
continuationSettings;
|
|
113
139
|
closing = false;
|
|
@@ -126,8 +152,7 @@ export class SparkAgentService {
|
|
|
126
152
|
this.store = options.store;
|
|
127
153
|
this.executeRun = options.executeRun;
|
|
128
154
|
this.evaluateGoal = options.evaluateGoal;
|
|
129
|
-
this.
|
|
130
|
-
this.onGoalStart = options.onGoalStart;
|
|
155
|
+
this.onGoalChange = options.onGoalChange;
|
|
131
156
|
this.readGoalCredits = options.readGoalCredits;
|
|
132
157
|
this.continuationSettings = options.continuationSettings;
|
|
133
158
|
this.endOrphanedRuns = options.endOrphanedRuns ?? false;
|
|
@@ -182,30 +207,17 @@ export class SparkAgentService {
|
|
|
182
207
|
if (command.action === "update_budget") {
|
|
183
208
|
if (!current || current.id !== command.goalId)
|
|
184
209
|
throw new SparkServiceError(409, "The goal changed. Refresh and try again.");
|
|
185
|
-
|
|
186
|
-
throw new SparkServiceError(409, "This goal is already complete.");
|
|
187
|
-
if (wompifyContextSchema.safeParse(current.settings.wompify).success)
|
|
188
|
-
throw new SparkServiceError(409, "Wompify caps are set by the detail level.");
|
|
210
|
+
const goal = await this.withCaps(ownerId, current, command);
|
|
189
211
|
if (command.creditBudget === undefined && command.maxTurns === undefined)
|
|
190
212
|
throw new SparkServiceError(400, "Give a credit cap or a tries cap to change.");
|
|
191
|
-
|
|
192
|
-
...current,
|
|
193
|
-
...(command.creditBudget === undefined ? {} : { creditBudget: command.creditBudget }),
|
|
194
|
-
...(command.maxTurns === undefined ? {} : { maxTurns: command.maxTurns }),
|
|
195
|
-
});
|
|
196
|
-
if (command.creditBudget !== undefined && command.creditBudget < goal.creditsUsed)
|
|
197
|
-
throw new SparkServiceError(409, "The cap cannot be lower than credits already used and pending. Refresh and try again.");
|
|
198
|
-
if (command.maxTurns !== undefined && command.maxTurns < goal.turns)
|
|
199
|
-
throw new SparkServiceError(409, "The tries cap cannot be lower than the tries already used. Refresh and try again.");
|
|
200
|
-
if (goal.creditBudget !== undefined && goal.creditsUsed >= goal.creditBudget) {
|
|
213
|
+
if (atGoalLimit(goal, "credits")) {
|
|
201
214
|
goal.status = "budget_limited";
|
|
202
215
|
goal.lastReason = "The goal reached its credit budget.";
|
|
203
216
|
}
|
|
204
|
-
else if (goal.status === "budget_limited" && (goal
|
|
217
|
+
else if (goal.status === "budget_limited" && !atGoalLimit(goal, "tries")) {
|
|
205
218
|
goal.status = "paused";
|
|
206
219
|
goal.lastReason = "Ready to resume.";
|
|
207
220
|
}
|
|
208
|
-
goal.updatedAt = now();
|
|
209
221
|
await this.store.saveConversationGoal(conversationId, goal);
|
|
210
222
|
return { goal };
|
|
211
223
|
}
|
|
@@ -351,7 +363,7 @@ export class SparkAgentService {
|
|
|
351
363
|
inputMessage = previous;
|
|
352
364
|
}
|
|
353
365
|
else {
|
|
354
|
-
inputMessage = normalizeUserMessage(input.message);
|
|
366
|
+
inputMessage = normalizeUserMessage(input.message, { hostParts: input.hostParts === true });
|
|
355
367
|
if (goalContinuation)
|
|
356
368
|
inputMessage.metadata = { ...inputMessage.metadata, goalContinuation: true };
|
|
357
369
|
if (conversation.messages.some(({ id }) => id === inputMessage.id)) {
|
|
@@ -529,19 +541,10 @@ export class SparkAgentService {
|
|
|
529
541
|
data: { runId: run.id, status: "running" },
|
|
530
542
|
};
|
|
531
543
|
await this.appendChunk(run, runningChunk);
|
|
532
|
-
const
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
ownerId: conversation.ownerId, conversationId: conversation.id, runId: run.id, toolCallId: call.toolCallId, proposal, signal: call.signal,
|
|
537
|
-
}));
|
|
538
|
-
if (decision.kind !== "goal")
|
|
539
|
-
return decision.kind === "once" ? "declined" : "unanswered";
|
|
540
|
-
const started = await this.startGoal(run, proposal, decision);
|
|
541
|
-
if (!started)
|
|
542
|
-
return "active";
|
|
543
|
-
run = started;
|
|
544
|
-
return "started";
|
|
544
|
+
const handleGoal = this.evaluateGoal && this.store.saveConversationGoal && (async (request) => {
|
|
545
|
+
const applied = await this.applyGoalRequest(run, request);
|
|
546
|
+
run = applied.run;
|
|
547
|
+
return applied.result;
|
|
545
548
|
});
|
|
546
549
|
const execution = await this.executeRun({
|
|
547
550
|
ownerId: conversation.ownerId,
|
|
@@ -551,7 +554,7 @@ export class SparkAgentService {
|
|
|
551
554
|
uiMessages: conversation.messages,
|
|
552
555
|
settings: run.settings,
|
|
553
556
|
goal: conversation.goal?.status === "active" ? conversation.goal : undefined,
|
|
554
|
-
...(
|
|
557
|
+
...(handleGoal ? { handleGoal } : {}),
|
|
555
558
|
signal: AbortSignal.any([controller.signal, unsaved.signal]),
|
|
556
559
|
});
|
|
557
560
|
// A chunk that cannot be stored aborts the execution, and the stream is
|
|
@@ -623,34 +626,108 @@ export class SparkAgentService {
|
|
|
623
626
|
this.controllers.delete(run.id);
|
|
624
627
|
}
|
|
625
628
|
}
|
|
626
|
-
/**
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
629
|
+
/**
|
|
630
|
+
* What the `goal` tool does for the run that called it. Only a turn the user
|
|
631
|
+
* started may set or change a goal, since its conditions and limits are what
|
|
632
|
+
* hold the service's own tries; and a Wompify goal is not the agent's to
|
|
633
|
+
* change. A goal that is set, changed or continued goes on with this run as
|
|
634
|
+
* its next try, unless the change completes it or it is still at a limit.
|
|
635
|
+
*/
|
|
636
|
+
applyGoalRequest(run, request) {
|
|
630
637
|
return this.inConversationTurn(run.conversationId, async () => {
|
|
631
638
|
const conversation = await this.store.getConversation(run.conversationId);
|
|
632
|
-
if (!conversation || conversation.activeRunId !== run.id
|
|
633
|
-
|
|
634
|
-
const
|
|
635
|
-
const
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
639
|
+
if (!conversation || conversation.activeRunId !== run.id)
|
|
640
|
+
throw new SparkServiceError(409, "This run no longer holds its conversation.");
|
|
641
|
+
const current = conversation.goal;
|
|
642
|
+
const message = conversation.messages.find(({ id }) => id === run.inputMessageId);
|
|
643
|
+
if (message?.metadata?.goalContinuation || (current && wompifyContextSchema.safeParse(current.settings.wompify).success))
|
|
644
|
+
return { result: { goal: "refused" }, run };
|
|
645
|
+
const caps = { maxTurns: request.tries, creditBudget: request.credits };
|
|
646
|
+
let goal;
|
|
647
|
+
let ended;
|
|
648
|
+
let outcome = "running";
|
|
649
|
+
if (request.action === "set") {
|
|
650
|
+
if (!request.title || !request.conditions)
|
|
651
|
+
throw new SparkServiceError(400, "A goal needs a title and conditions.");
|
|
652
|
+
if (caps.creditBudget !== undefined && !this.readGoalCredits)
|
|
653
|
+
throw new SparkServiceError(501, "This host does not support credit budgets.");
|
|
654
|
+
const createdAt = now();
|
|
655
|
+
goal = {
|
|
656
|
+
id: crypto.randomUUID(), objective: (message ? messageText(message) : "").slice(0, MAX_GOAL_LENGTH) || request.title,
|
|
657
|
+
title: request.title, conditions: request.conditions,
|
|
658
|
+
status: "active", settings: run.settings, createdAt, updatedAt: createdAt, turns: 0, runId: run.id,
|
|
659
|
+
maxTurns: caps.maxTurns ?? GOAL_DEFAULT_CAPS.tries,
|
|
660
|
+
...(this.readGoalCredits ? { creditBudget: caps.creditBudget ?? GOAL_DEFAULT_CAPS.credits, creditsUsed: 0 } : {}),
|
|
661
|
+
};
|
|
662
|
+
if (current)
|
|
663
|
+
ended = goalSummary(current, current.status === "completed" ? "done" : "replaced");
|
|
664
|
+
outcome = "started";
|
|
647
665
|
}
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
666
|
+
else {
|
|
667
|
+
if (!current || current.status === "completed")
|
|
668
|
+
return { result: { goal: "missing" }, run };
|
|
669
|
+
if (request.action === "remove") {
|
|
670
|
+
ended = goalSummary(current, "removed");
|
|
671
|
+
outcome = "removed";
|
|
672
|
+
}
|
|
673
|
+
else {
|
|
674
|
+
if (request.action === "change" && !request.conditions && caps.maxTurns === undefined && caps.creditBudget === undefined)
|
|
675
|
+
throw new SparkServiceError(400, "Give the conditions, tries or credits to change.");
|
|
676
|
+
goal = request.action === "change" && request.conditions ? withConditions(current, request.conditions) : current;
|
|
677
|
+
goal = await this.withCaps(conversation.ownerId, goal, request.action === "continue" && atGoalLimit(goal, "tries") ? { maxTurns: goal.turns + GOAL_MORE_TRIES } : caps);
|
|
678
|
+
const measured = goal.conditions?.filter((condition) => condition.measurable) ?? [];
|
|
679
|
+
if (request.conditions && measured.length > 0 && measured.every((condition) => condition.met)) {
|
|
680
|
+
goal = { ...goal, status: "completed", lastReason: "Every measurable condition is verified." };
|
|
681
|
+
outcome = "done";
|
|
682
|
+
}
|
|
683
|
+
else if (atGoalLimit(goal, "tries") || atGoalLimit(goal, "credits")) {
|
|
684
|
+
goal = { ...goal, status: "budget_limited", lastReason: `The goal reached its ${atGoalLimit(goal, "tries") ? "turn" : "credit"} budget.` };
|
|
685
|
+
outcome = "limited";
|
|
686
|
+
}
|
|
687
|
+
else
|
|
688
|
+
goal = { ...goal, status: "active", runId: run.id, idleTurns: 0 };
|
|
689
|
+
}
|
|
651
690
|
}
|
|
652
|
-
|
|
691
|
+
const { goalId: _goalId, ...unbound } = run;
|
|
692
|
+
const working = goal?.status === "active" ? { ...unbound, goalId: goal.id } : unbound;
|
|
693
|
+
await this.store.saveConversationGoal(conversation.id, goal);
|
|
694
|
+
if (working.goalId !== run.goalId || ended) {
|
|
695
|
+
try {
|
|
696
|
+
await this.onGoalChange?.({ ownerId: conversation.ownerId, run: working, ...(working.goalId ? { goal } : {}), ...(ended ? { ended } : {}) });
|
|
697
|
+
await this.store.saveRun(working);
|
|
698
|
+
}
|
|
699
|
+
catch (error) {
|
|
700
|
+
await this.store.saveConversationGoal(conversation.id, current);
|
|
701
|
+
throw error;
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
return {
|
|
705
|
+
result: {
|
|
706
|
+
goal: outcome,
|
|
707
|
+
...(goal?.maxTurns === undefined ? {} : { tries: goal.maxTurns }),
|
|
708
|
+
...(goal?.creditBudget === undefined ? {} : { credits: goal.creditBudget }),
|
|
709
|
+
...(ended ? { ended } : {}),
|
|
710
|
+
},
|
|
711
|
+
run: working,
|
|
712
|
+
};
|
|
713
|
+
});
|
|
714
|
+
}
|
|
715
|
+
/** `current` with these caps and its credits read again. A cap below what the goal has used is refused. */
|
|
716
|
+
async withCaps(ownerId, current, caps) {
|
|
717
|
+
if (current.status === "completed")
|
|
718
|
+
throw new SparkServiceError(409, "This goal is already complete.");
|
|
719
|
+
if (wompifyContextSchema.safeParse(current.settings.wompify).success)
|
|
720
|
+
throw new SparkServiceError(409, "Wompify caps are set by the detail level.");
|
|
721
|
+
const goal = await this.refreshGoalCredits(ownerId, {
|
|
722
|
+
...current,
|
|
723
|
+
...(caps.creditBudget === undefined ? {} : { creditBudget: caps.creditBudget }),
|
|
724
|
+
...(caps.maxTurns === undefined ? {} : { maxTurns: caps.maxTurns }),
|
|
653
725
|
});
|
|
726
|
+
if (caps.creditBudget !== undefined && caps.creditBudget < goal.creditsUsed)
|
|
727
|
+
throw new SparkServiceError(409, "The cap cannot be lower than credits already used and pending. Refresh and try again.");
|
|
728
|
+
if (caps.maxTurns !== undefined && caps.maxTurns < goal.turns)
|
|
729
|
+
throw new SparkServiceError(409, "The tries cap cannot be lower than the tries already used. Refresh and try again.");
|
|
730
|
+
return { ...goal, updatedAt: now() };
|
|
654
731
|
}
|
|
655
732
|
async refreshGoalCredits(ownerId, goal) {
|
|
656
733
|
if (goal.creditBudget === undefined)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type Express } from "express";
|
|
2
2
|
import { KakapoAPI } from "@womp/kakapo-sdk";
|
|
3
|
-
import {
|
|
3
|
+
import type { SparkGoal } from "../goals.js";
|
|
4
4
|
import type { SparkAgentStore } from "./types.js";
|
|
5
5
|
export type StandaloneSparkAgentOptions = {
|
|
6
6
|
openAiApiKey?: string;
|
|
@@ -19,7 +19,6 @@ import { QuickJSJavaScriptExecutor } from "../quickjs-executor.js";
|
|
|
19
19
|
import { sparkModelOptions } from "../model-options.js";
|
|
20
20
|
import { createSparkRunExecutor } from "./executor.js";
|
|
21
21
|
import { createSparkGoalEvaluator } from "./goal-evaluator.js";
|
|
22
|
-
import { sparkGoalDecisionSchema } from "../goals.js";
|
|
23
22
|
import { createSparkAgentRouter } from "./express.js";
|
|
24
23
|
import { SparkAgentService } from "./service.js";
|
|
25
24
|
import { SqliteSparkStore } from "./sqlite-store.js";
|
|
@@ -237,16 +236,9 @@ export async function createStandaloneSparkAgentApp(options) {
|
|
|
237
236
|
}
|
|
238
237
|
let clearingScene = false;
|
|
239
238
|
let activeRuns = 0;
|
|
240
|
-
/** The goal proposals runs are waiting on, by the tool call that made them. */
|
|
241
|
-
const goalAnswers = new Map();
|
|
242
239
|
const service = new SparkAgentService({
|
|
243
240
|
store,
|
|
244
241
|
evaluateGoal: createSparkGoalEvaluator({ resolveModel, resolveImage: (ownerId, artifactId) => artifactStore.get(ownerId, artifactId) }),
|
|
245
|
-
// The run waits until the UI answers on the route below, or the run is stopped.
|
|
246
|
-
confirmGoal: ({ toolCallId, signal }) => new Promise((resolve, reject) => {
|
|
247
|
-
goalAnswers.set(toolCallId, resolve);
|
|
248
|
-
signal.addEventListener("abort", () => { goalAnswers.delete(toolCallId); reject(signal.reason); }, { once: true });
|
|
249
|
-
}),
|
|
250
242
|
readGoalCredits: (_ownerId, goal) => estimateGoalCredits(store, goal),
|
|
251
243
|
executeRun: async (context) => {
|
|
252
244
|
if (clearingScene)
|
|
@@ -314,19 +306,6 @@ export async function createStandaloneSparkAgentApp(options) {
|
|
|
314
306
|
clearingScene = false;
|
|
315
307
|
}
|
|
316
308
|
});
|
|
317
|
-
app.post(`${apiBasePath}/goal-proposals/:toolCallId`, express.json(), (request, response) => {
|
|
318
|
-
const answer = sparkGoalDecisionSchema.safeParse(request.body);
|
|
319
|
-
const resolve = goalAnswers.get(request.params.toolCallId);
|
|
320
|
-
if (!answer.success || answer.data.kind === "unanswered")
|
|
321
|
-
response.status(400).json({ error: "Answer with a goal or a single try." });
|
|
322
|
-
else if (!resolve)
|
|
323
|
-
response.status(404).json({ error: "This goal proposal is no longer waiting for an answer." });
|
|
324
|
-
else {
|
|
325
|
-
goalAnswers.delete(request.params.toolCallId);
|
|
326
|
-
resolve(answer.data);
|
|
327
|
-
response.status(204).end();
|
|
328
|
-
}
|
|
329
|
-
});
|
|
330
309
|
app.use(apiBasePath, (request, response, next) => {
|
|
331
310
|
if (clearingScene && request.method === "POST" && request.path.endsWith("/messages")) {
|
|
332
311
|
response.status(409).json({ error: "The scene is being cleared. Try again when it finishes." });
|
package/dist/server/types.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import type { SparkAgentRun } from "../agent.js";
|
|
|
3
3
|
import type { ReasoningEffort } from "../models.js";
|
|
4
4
|
import type { SparkRunStatus, SparkUIMessage, StoredSparkChunk } from "../ui.js";
|
|
5
5
|
import type { SparkGoal } from "../goals.js";
|
|
6
|
-
import type {
|
|
6
|
+
import type { SparkGoalHandler } from "../agent-tools.js";
|
|
7
7
|
export type SparkConversation = {
|
|
8
8
|
id: string;
|
|
9
9
|
ownerId: string;
|
|
@@ -39,8 +39,8 @@ export type SparkRun = {
|
|
|
39
39
|
};
|
|
40
40
|
export type SparkRunExecutionContext = {
|
|
41
41
|
goal?: SparkGoal;
|
|
42
|
-
/** Set when the
|
|
43
|
-
|
|
42
|
+
/** Set when the service runs goals; the executor hands it to the agent, which then has `goal`. */
|
|
43
|
+
handleGoal?: SparkGoalHandler;
|
|
44
44
|
ownerId: string;
|
|
45
45
|
conversationId: string;
|
|
46
46
|
runId: string;
|