@womp/spark-agent 9.5.0 → 10.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.
@@ -116,31 +116,71 @@ async function intentFixtures(testCase, controller) {
116
116
  };
117
117
  const files = new Map();
118
118
  const assets = [];
119
- const messages = [];
120
- const addFile = async (image, messageId, source) => {
119
+ const jobs = [];
120
+ const history = [];
121
+ const addFile = async (image, id, messageId, source) => {
121
122
  const loaded = await loadImage(image);
122
- const id = `${source}-${messageId}-${files.size + 1}`;
123
- files.set(id, { artifact: { id, url: `fixture://${id}`, mediaType: loaded.mediaType, name: loaded.name }, data: loaded.data });
124
- assets.push({ artifact: { id, mediaType: loaded.mediaType, name: loaded.name }, messageId, kind: "image", source });
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
- for (const image of turn.generated ?? [])
131
- await addFile(image, messageId, "generated");
132
- messages.push({ role: "assistant", content: turn.text });
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 content = [];
136
- for (const image of turn.images ?? []) {
137
- const loaded = await addFile(image, messageId, "uploaded");
138
- content.push({ type: "file", data: loaded.data, mediaType: loaded.mediaType, filename: loaded.name });
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
- content.push({ type: "text", text: turn.text });
142
- messages.push({ role: "user", content });
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
- return { jobs: [], nextFrom: null };
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) => missing("operations.read", `No job ${messageId}.`),
286
- wait: async (messageId) => missing("operations.wait", `No job ${messageId}.`),
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
- messages,
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
- messages: fixtures.messages,
487
+ history: fixtures.history,
440
488
  capabilities: fixtures.capabilities,
441
489
  executor: fixtures.executor,
442
490
  artifacts: fixtures.artifacts,
@@ -15,7 +15,7 @@ export function createSparkRunExecutor(options) {
15
15
  runId: context.runId,
16
16
  messageId: context.assistantMessageId,
17
17
  signal: context.signal,
18
- proposeGoal: context.proposeGoal,
18
+ handleGoal: context.handleGoal,
19
19
  });
20
20
  return { stream: run.stream, result: run.result.finally(() => host.dispose()) };
21
21
  }
@@ -12,8 +12,8 @@ export declare const goalVerdictSchema: z.ZodObject<{
12
12
  }, z.core.$strip>>>;
13
13
  verdict: z.ZodEnum<{
14
14
  met: "met";
15
- blocked: "blocked";
16
15
  continue: "continue";
16
+ blocked: "blocked";
17
17
  }>;
18
18
  reason: z.ZodString;
19
19
  }, z.core.$strip>;
@@ -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, sparkGoalDecisionSchema, sparkGoalProposalSchema, type SparkGoal, type SparkGoalCommand, type SparkGoalCondition, type SparkGoalDecision, type SparkGoalProposal, type SparkGoalTry } from "../goals.js";
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";
@@ -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, sparkGoalDecisionSchema, sparkGoalProposalSchema } from "../goals.js";
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";
@@ -1,5 +1,5 @@
1
1
  import { type SparkUIMessage, type StoredSparkChunk } from "../ui.js";
2
- import { type SparkGoal, type SparkGoalCommand, type SparkGoalDecision, type SparkGoalProposal } from "../goals.js";
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
- * Shows the user a goal the agent proposed and resolves their answer. With it
17
- * and `evaluateGoal`, the agent has `propose_goal`; the run waits here, and a
18
- * confirmed goal starts with that run as its first try.
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
- confirmGoal?(input: {
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: SparkGoal;
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>;
@@ -67,8 +61,7 @@ export declare class SparkAgentService {
67
61
  private readonly store;
68
62
  private readonly executeRun;
69
63
  private readonly evaluateGoal?;
70
- private readonly confirmGoal?;
71
- private readonly onGoalStart?;
64
+ private readonly onGoalChange?;
72
65
  private readonly readGoalCredits?;
73
66
  private readonly continuationSettings?;
74
67
  private closing;
@@ -116,8 +109,16 @@ export declare class SparkAgentService {
116
109
  cancelRun(ownerId: string, runId: string): Promise<SparkRun>;
117
110
  streamRun(ownerId: string, runId: string, afterSequence: number, signal: AbortSignal): AsyncGenerator<StoredSparkChunk>;
118
111
  private runInBackground;
119
- /** Starts the goal the user confirmed, with the run that proposed it as its first try. */
120
- private startGoal;
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;
121
122
  private refreshGoalCredits;
122
123
  private pauseRunGoal;
123
124
  private advanceGoal;
@@ -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, sparkGoalDecisionSchema } from "../goals.js";
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([
@@ -92,6 +92,31 @@ function goalContinuationText(goal) {
92
92
  + (wompifyContextSchema.safeParse(goal.settings.wompify).success
93
93
  ? "\nKeep refining the existing reconstruction at the same detail level. Compare it with the reference and improve the remaining shape and color discrepancies." : "");
94
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
+ }
95
120
  /** The goal's conditions with what this evaluation found for each measurable one. */
96
121
  function judgedConditions(goal, evaluation) {
97
122
  if (!goal.conditions || !evaluation?.conditions)
@@ -108,8 +133,7 @@ export class SparkAgentService {
108
133
  store;
109
134
  executeRun;
110
135
  evaluateGoal;
111
- confirmGoal;
112
- onGoalStart;
136
+ onGoalChange;
113
137
  readGoalCredits;
114
138
  continuationSettings;
115
139
  closing = false;
@@ -128,8 +152,7 @@ export class SparkAgentService {
128
152
  this.store = options.store;
129
153
  this.executeRun = options.executeRun;
130
154
  this.evaluateGoal = options.evaluateGoal;
131
- this.confirmGoal = options.confirmGoal;
132
- this.onGoalStart = options.onGoalStart;
155
+ this.onGoalChange = options.onGoalChange;
133
156
  this.readGoalCredits = options.readGoalCredits;
134
157
  this.continuationSettings = options.continuationSettings;
135
158
  this.endOrphanedRuns = options.endOrphanedRuns ?? false;
@@ -184,30 +207,17 @@ export class SparkAgentService {
184
207
  if (command.action === "update_budget") {
185
208
  if (!current || current.id !== command.goalId)
186
209
  throw new SparkServiceError(409, "The goal changed. Refresh and try again.");
187
- if (current.status === "completed")
188
- throw new SparkServiceError(409, "This goal is already complete.");
189
- if (wompifyContextSchema.safeParse(current.settings.wompify).success)
190
- throw new SparkServiceError(409, "Wompify caps are set by the detail level.");
210
+ const goal = await this.withCaps(ownerId, current, command);
191
211
  if (command.creditBudget === undefined && command.maxTurns === undefined)
192
212
  throw new SparkServiceError(400, "Give a credit cap or a tries cap to change.");
193
- const goal = await this.refreshGoalCredits(ownerId, {
194
- ...current,
195
- ...(command.creditBudget === undefined ? {} : { creditBudget: command.creditBudget }),
196
- ...(command.maxTurns === undefined ? {} : { maxTurns: command.maxTurns }),
197
- });
198
- if (command.creditBudget !== undefined && command.creditBudget < goal.creditsUsed)
199
- throw new SparkServiceError(409, "The cap cannot be lower than credits already used and pending. Refresh and try again.");
200
- if (command.maxTurns !== undefined && command.maxTurns < goal.turns)
201
- throw new SparkServiceError(409, "The tries cap cannot be lower than the tries already used. Refresh and try again.");
202
- if (goal.creditBudget !== undefined && goal.creditsUsed >= goal.creditBudget) {
213
+ if (atGoalLimit(goal, "credits")) {
203
214
  goal.status = "budget_limited";
204
215
  goal.lastReason = "The goal reached its credit budget.";
205
216
  }
206
- else if (goal.status === "budget_limited" && (goal.maxTurns === undefined || goal.turns < goal.maxTurns)) {
217
+ else if (goal.status === "budget_limited" && !atGoalLimit(goal, "tries")) {
207
218
  goal.status = "paused";
208
219
  goal.lastReason = "Ready to resume.";
209
220
  }
210
- goal.updatedAt = now();
211
221
  await this.store.saveConversationGoal(conversationId, goal);
212
222
  return { goal };
213
223
  }
@@ -531,19 +541,10 @@ export class SparkAgentService {
531
541
  data: { runId: run.id, status: "running" },
532
542
  };
533
543
  await this.appendChunk(run, runningChunk);
534
- const proposeGoal = this.confirmGoal && this.evaluateGoal && this.store.saveConversationGoal && (async (proposal, call) => {
535
- if (run.goalId)
536
- return "active";
537
- const decision = sparkGoalDecisionSchema.parse(await this.confirmGoal({
538
- ownerId: conversation.ownerId, conversationId: conversation.id, runId: run.id, toolCallId: call.toolCallId, proposal, signal: call.signal,
539
- }));
540
- if (decision.kind !== "goal")
541
- return decision.kind === "once" ? "declined" : "unanswered";
542
- const started = await this.startGoal(run, proposal, decision);
543
- if (!started)
544
- return "active";
545
- run = started;
546
- 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;
547
548
  });
548
549
  const execution = await this.executeRun({
549
550
  ownerId: conversation.ownerId,
@@ -553,7 +554,7 @@ export class SparkAgentService {
553
554
  uiMessages: conversation.messages,
554
555
  settings: run.settings,
555
556
  goal: conversation.goal?.status === "active" ? conversation.goal : undefined,
556
- ...(proposeGoal ? { proposeGoal } : {}),
557
+ ...(handleGoal ? { handleGoal } : {}),
557
558
  signal: AbortSignal.any([controller.signal, unsaved.signal]),
558
559
  });
559
560
  // A chunk that cannot be stored aborts the execution, and the stream is
@@ -625,34 +626,108 @@ export class SparkAgentService {
625
626
  this.controllers.delete(run.id);
626
627
  }
627
628
  }
628
- /** Starts the goal the user confirmed, with the run that proposed it as its first try. */
629
- async startGoal(run, proposal, caps) {
630
- if (caps.creditBudget !== undefined && !this.readGoalCredits)
631
- throw new SparkServiceError(501, "This host does not support credit budgets.");
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) {
632
637
  return this.inConversationTurn(run.conversationId, async () => {
633
638
  const conversation = await this.store.getConversation(run.conversationId);
634
- if (!conversation || conversation.activeRunId !== run.id || conversation.goal?.status === "active")
635
- return undefined;
636
- const request = conversation.messages.find(({ id }) => id === run.inputMessageId);
637
- const createdAt = now();
638
- const goal = {
639
- id: crypto.randomUUID(), objective: (request ? messageText(request) : "").slice(0, MAX_GOAL_LENGTH) || proposal.title, ...proposal,
640
- status: "active", settings: run.settings, createdAt, updatedAt: createdAt, turns: 0, runId: run.id,
641
- ...(caps.maxTurns ? { maxTurns: caps.maxTurns } : {}),
642
- ...(caps.creditBudget ? { creditBudget: caps.creditBudget, creditsUsed: 0 } : {}),
643
- };
644
- const started = { ...run, goalId: goal.id };
645
- await this.store.saveConversationGoal(conversation.id, goal);
646
- try {
647
- await this.onGoalStart?.({ ownerId: conversation.ownerId, run: started, goal });
648
- await this.store.saveRun(started);
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";
649
665
  }
650
- catch (error) {
651
- await this.store.saveConversationGoal(conversation.id, conversation.goal);
652
- throw error;
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
+ }
653
690
  }
654
- return started;
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 }),
655
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() };
656
731
  }
657
732
  async refreshGoalCredits(ownerId, goal) {
658
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 { type SparkGoal } from "../goals.js";
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." });
@@ -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 { SparkGoalOffer } from "../agent-tools.js";
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 host can ask the user to confirm a goal; the executor hands it to the agent. */
43
- proposeGoal?: SparkGoalOffer;
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;