@womp/spark-agent 9.5.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 CHANGED
@@ -4,6 +4,54 @@ Notable changes to `@womp/spark-agent`, newest first. Versions follow
4
4
  [Semantic Versioning](https://semver.org/). Add an entry with each version bump; describe what
5
5
  changed for hosts and users, and how to migrate across breaking changes.
6
6
 
7
+ ## 10.0.0 — 2026-10-13
8
+
9
+ The agent sets and changes a goal itself, from what the user says in chat, instead of proposing one
10
+ and waiting for the user to confirm it.
11
+
12
+ ### Added
13
+
14
+ - The `goal({ action, title?, conditions?, tries?, credits? })` tool, offered whenever the service
15
+ has `evaluateGoal`:
16
+ - `set` starts a goal at once with the calling run as its first try, with 5 tries, and 2,000
17
+ credits where the host has `readGoalCredits`, unless the call gives others. A goal the
18
+ conversation already has ends: as done if it was complete, replaced otherwise.
19
+ - `change` gives the goal new conditions, tries or credits. A condition whose words did not change
20
+ keeps what the checks found for it, in the goal and in `goal.tries`. If every measurable
21
+ condition is then already verified, the goal is complete at once.
22
+ - `continue` has a goal that stopped go on, with `GOAL_MORE_TRIES` (3) more tries if it had used
23
+ its tries.
24
+ - `remove` ends the goal, and the run goes on as an ordinary turn.
25
+ A goal that is set, changed or continued goes on with the calling run as its next try, unless it
26
+ is complete or still at a limit. Only a turn the user started may call the tool to effect, not a
27
+ try the service started, and not for a Wompify goal.
28
+ - The tool's result (`SparkGoalResult`) carries the goal's limits and `ended`
29
+ (`SparkGoalSummary`): the title, outcome, tries, credits and checks of the goal the call ended.
30
+ It stays in the conversation as the `tool-goal` part's output, for hosts to show past goals.
31
+ - `SparkAgentServiceOptions.onGoalChange`, called when a `goal` call changes what its run works
32
+ for or ends a goal, before the agent goes on. A change it refuses is undone.
33
+ - `SparkRunExecutionContext.handleGoal` and `SparkAgentOptions.handleGoal` (`SparkGoalHandler`)
34
+ carry the tool to the agent.
35
+
36
+ ### Removed
37
+
38
+ - The `propose_goal` tool, `SparkAgentServiceOptions.confirmGoal` and `onGoalStart`,
39
+ `SparkGoalOffer`, `sparkGoalDecisionSchema`, `sparkGoalProposalSchema` and their types, and the
40
+ wait in `requires_action` for the user's answer.
41
+ - The `data-goal-proposal` part and `sparkGoalProposalPartSchema`. A conversation that holds one no
42
+ longer validates.
43
+ - `GOAL_CONFIRMATION_DEFAULTS`.
44
+ - The standalone server's `POST /goal-proposals/:toolCallId`.
45
+
46
+ ### Migration
47
+
48
+ - Remove `confirmGoal` and the confirmation UI. Show a goal from the conversation's goal state, and
49
+ past goals from the `ended` of the `tool-goal` parts.
50
+ - A host that counted a goal's spending from `onGoalStart` does it from `onGoalChange`, which also
51
+ says when a run stops working for a goal.
52
+ - A host that offered `propose_goal` to some runs only passes or drops `handleGoal` the same way.
53
+ - A host that stores tool calls by name must accept `goal`.
54
+
7
55
  ## 9.5.0 — 2026-10-13
8
56
 
9
57
  ### Added
package/README.md CHANGED
@@ -149,17 +149,17 @@ Conversation settings contain `modelId` and `reasoningEffort`; save them with
149
149
  `transport.saveConversationSettings(id, settings)`. The goal endpoint accepts `set`, `pause`,
150
150
  `resume`, `clear`, and `update_budget` commands.
151
151
 
152
- A goal starts from an ordinary message, when the agent proposes one. A host that sets
153
- `SparkAgentServiceOptions.confirmGoal` (with `evaluateGoal`) gives the agent the `propose_goal`
154
- tool: it calls it before building when the request sets constraints a result can be measured
155
- against, with a title and the conditions, each marked `measurable` or left to the user's review.
156
- The run then waits in `requires_action` while `confirmGoal` shows the proposal, which the
157
- assistant message stores as a `data-goal-proposal` part, and resolves the user's answer: `{ kind: "goal", maxTurns,
158
- creditBudget }`, `{ kind: "once" }`, or `{ kind: "unanswered" }` when the host stops waiting. A
159
- confirmed goal starts with that run as its first try; the service evaluates each measurable
160
- condition after every try and records the result on `goal.conditions`. Any other answer leaves an
161
- ordinary turn. The part then carries the `outcome`: `started`, `declined`, `unanswered`, or `active`
162
- when a goal was already running. `onGoalStart` tells a host that counts a goal's spending when one starts.
152
+ A goal starts from an ordinary message, when the agent sets one, and changes when the user asks in
153
+ chat. A service with `evaluateGoal` gives the agent the `goal` tool. With `set` it starts a goal
154
+ before building, when the request sets constraints a result can be measured against, from a title
155
+ and the conditions, each marked `measurable` or left to the user's review. The goal starts at once,
156
+ with that run as its first try and with 5 tries and 2,000 credits unless the call gives others; the
157
+ service evaluates each measurable condition after every try and records the result on
158
+ `goal.conditions`. `change` gives the goal new conditions or limits, `continue` has a stopped goal
159
+ go on, and `remove` ends it; after a change the goal goes on in that turn. A `set` over an existing
160
+ goal ends that one, and the call's result keeps its summary as `ended`. `onGoalChange` tells a host
161
+ that counts a goal's spending when a run starts or stops working for one. A host leaves
162
+ `handleGoal` out of the run it executes to withhold the tool.
163
163
 
164
164
  The SSE response contains ordered persistence envelopes around standard AI SDK chunks:
165
165
 
@@ -43,7 +43,7 @@ export declare function runAgent(options: RunOptions): Promise<{
43
43
  } | undefined;
44
44
  conversationId: string | null;
45
45
  runId: string | null;
46
- status: "completed" | "queued" | "running" | "requires_action" | "failed" | "cancelled" | "incomplete";
46
+ status: "running" | "completed" | "queued" | "requires_action" | "failed" | "cancelled" | "incomplete";
47
47
  finalAnswer: string;
48
48
  durationMs: number | null;
49
49
  steps: number;
@@ -1,21 +1,15 @@
1
1
  import { type Tool } from "ai";
2
2
  import type { ExecutionReceipt, SparkArtifactResolver, SparkCapabilities } from "./capabilities.js";
3
3
  import type { JavaScriptExecutor } from "./executor.js";
4
- import { type SparkGoalOutcome, type SparkGoalProposal } from "./goals.js";
4
+ import { type SparkGoalRequest, type SparkGoalResult } from "./goals.js";
5
5
  import type { SparkUIMessage, SparkUIMessageChunk, SparkUITools } from "./ui.js";
6
6
  export type SparkToolCall = {
7
7
  id: string;
8
- name: "read_skill" | "execute_javascript" | "propose_goal";
8
+ name: "read_skill" | "execute_javascript" | "goal";
9
9
  input: unknown;
10
10
  };
11
- /**
12
- * Shows the user a goal the model proposed and waits for their answer, starting
13
- * the goal for this run when they confirm it.
14
- */
15
- export type SparkGoalOffer = (proposal: SparkGoalProposal, call: {
16
- toolCallId: string;
17
- signal: AbortSignal;
18
- }) => Promise<SparkGoalOutcome>;
11
+ /** Carries out a `goal` call for the run that made it. */
12
+ export type SparkGoalHandler = (request: SparkGoalRequest) => Promise<SparkGoalResult>;
19
13
  export interface SparkPersistence {
20
14
  beforeToolCall(call: SparkToolCall): Promise<void>;
21
15
  recordReceipt(callId: string, receipt: ExecutionReceipt): Promise<void>;
@@ -31,8 +25,8 @@ export type SparkToolOptions = {
31
25
  controller: AbortController;
32
26
  persistence?: SparkPersistence;
33
27
  executionTimeoutMs?: number;
34
- /** Present when the host can ask the user: the model then has `propose_goal`. */
35
- proposeGoal?: SparkGoalOffer;
28
+ /** Present when the host runs goals: the model then has `goal`. */
29
+ handleGoal?: SparkGoalHandler;
36
30
  write(chunk: SparkUIMessageChunk): void;
37
31
  };
38
32
  type SparkTool<Name extends keyof SparkUITools> = Tool<SparkUITools[Name]["input"], SparkUITools[Name]["output"]>;
@@ -40,7 +34,7 @@ type SparkCoreTools = {
40
34
  [Name in "read_skill" | "execute_javascript"]: SparkTool<Name>;
41
35
  };
42
36
  export type SparkTools = SparkCoreTools | (SparkCoreTools & {
43
- propose_goal: SparkTool<"propose_goal">;
37
+ goal: SparkTool<"goal">;
44
38
  });
45
39
  export declare function createSparkTools(options: SparkToolOptions): SparkTools;
46
40
  export {};
@@ -3,7 +3,7 @@ import { z } from "zod";
3
3
  import { boundedResultText, canonicalJsonValue } from "./bounded-output.js";
4
4
  import { completedInputString } from "./tool-input-label.js";
5
5
  import { UserWait } from "./execution-lifetime.js";
6
- import { sparkGoalProposalSchema } from "./goals.js";
6
+ import { GOAL_DEFAULT_CAPS, GOAL_MORE_TRIES, sparkGoalRequestSchema } from "./goals.js";
7
7
  function errorMessage(error) {
8
8
  return error instanceof Error ? error.message : String(error);
9
9
  }
@@ -22,13 +22,30 @@ const artifactRefSchema = z.object({
22
22
  mediaType: z.string().min(1),
23
23
  name: z.string().optional(),
24
24
  });
25
- /** What the model is told a proposal came to, and so what to do next. */
26
- const GOAL_OUTCOMES = {
27
- started: "The user confirmed the goal. Build it now, and verify every measurable condition with tool results before you finish. An independent check follows each try and sends back what is still unmet.",
28
- declined: "The user chose a single try. Carry out the request as usual and do not propose a goal for it again.",
29
- unanswered: "The user has not answered. Build nothing: say that you are waiting for their answer, and stop.",
30
- active: "A goal is already running in this conversation. Keep working toward it.",
31
- };
25
+ /** What the model is told a `goal` call did, and so what to do next. */
26
+ function goalResultText({ goal, tries, credits }) {
27
+ const limits = [
28
+ tries === undefined ? undefined : `${tries} ${tries === 1 ? "try" : "tries"}`,
29
+ credits === undefined ? undefined : `${credits.toLocaleString("en-US")} credits`,
30
+ ].filter(Boolean).join(" and ");
31
+ const upTo = limits ? `, up to ${limits}` : "";
32
+ switch (goal) {
33
+ case "started":
34
+ return `The goal is set and running${upTo}. Tell the user in one line that you set a goal from their message, its limits, and that they can tell you to stop or change anything. Then build it, and verify every measurable condition with tool results before you finish. An independent check follows each try and sends back what is still unmet.`;
35
+ case "running":
36
+ return `The goal is running${upTo}, with this turn as its next try. Confirm to the user in one line what changed, then keep working toward it.`;
37
+ case "done":
38
+ return "With this change every measurable condition is already verified, so the goal is done. Tell the user in one line.";
39
+ case "limited":
40
+ return `The goal is at its limit${upTo}, so it is not running. Tell the user in one line, and that it goes on when they ask for more.`;
41
+ case "removed":
42
+ return "The goal is removed. Tell the user in one line, and carry out their request as an ordinary turn.";
43
+ case "refused":
44
+ return "The goal cannot be set or changed in this turn: only the user's own message can do that, and not for a goal Wompify runs. Keep working toward the current goal.";
45
+ case "missing":
46
+ return "This conversation has no goal to change.";
47
+ }
48
+ }
32
49
  export function createSparkTools(options) {
33
50
  const { controller, persistence } = options;
34
51
  const executionTimeoutMs = options.executionTimeoutMs ?? 60_000;
@@ -84,35 +101,19 @@ export function createSparkTools(options) {
84
101
  onInputAvailable: ({ toolCallId }) => { inputs.delete(toolCallId); },
85
102
  };
86
103
  };
87
- const { proposeGoal } = options;
104
+ const { handleGoal } = options;
88
105
  return {
89
- ...(proposeGoal === undefined ? {} : {
90
- propose_goal: tool({
91
- description: "Offer to run the user's request as a goal: work that repeats until an independent check verifies its conditions. Call it once, before building or generating anything, when the request sets a constraint the finished result passes or fails by measurement: a size, a count, a limit, a fit to something real, a clearance, an angle, a weight, a price, or a physical requirement such as being one piece, resting on the ground or parts not intersecting. Do not call it for a question, a small direct edit, a request that only describes what to make, or while a goal is running. It shows the user the conditions and waits for their answer.",
92
- inputSchema: sparkGoalProposalSchema.extend({
93
- title: sparkGoalProposalSchema.shape.title.describe("Two to four words in sentence case naming what is being made."),
94
- conditions: sparkGoalProposalSchema.shape.conditions.describe("Only constraints the user stated or directly implied, never your own, each marked measurable. The description of what to make is not a list of constraints: leave out its parts and features, and any instruction about how to work, what to check or what to render. State each as a fact about the finished result in a few words of the user's language, with its number and unit: \"Height is 120 mm\", not \"Make it 120 mm tall\". Split compound constraints. If the user asked for a look, style, feel or quality that takes judgement, add it as one condition that is not measurable, left to their review."),
95
- }),
96
- execute: (input, { toolCallId }) => execute({ id: toolCallId, name: "propose_goal", input }, async () => {
97
- const status = (status, label) => options.write({ type: "data-run-status", data: { runId: options.runId, status, label } });
98
- // The message keeps the proposal, and then what became of it, under one id.
99
- const store = (outcome) => options.write({
100
- type: "data-goal-proposal", id: `goal-proposal-${toolCallId}`,
101
- data: { ...input, toolCallId, ...(outcome ? { outcome } : {}) },
102
- });
103
- store();
104
- status("requires_action", "Waiting for your answer");
105
- try {
106
- const goal = await proposeGoal(input, { toolCallId, signal: controller.signal });
107
- store(goal);
108
- return { goal };
109
- }
110
- finally {
111
- if (!controller.signal.aborted)
112
- status("running", "Continuing after user input");
113
- }
106
+ ...(handleGoal === undefined ? {} : {
107
+ goal: tool({
108
+ description: "Manage the conversation's goal: work that repeats, without the user, until an independent check verifies its conditions. Call it only for what the user's own message asks. set: start a goal for the request, once, before building or generating anything, when the request sets a constraint the finished result passes or fails by measurement: a size, a count, a limit, a fit to something real, a clearance, an angle, a weight, a price, or a physical requirement such as being one piece, resting on the ground or parts not intersecting. Do not set one for a question, a small direct edit, or a request that only describes what to make. The goal starts at once, with this turn as its first try, and ends a goal already there, so use it for a new request and not to adjust the current one. change: the user asked to add, drop or alter a condition, or for other limits. continue: the user asked to keep going with a goal that stopped. remove: the user wants the request done without a goal.",
109
+ inputSchema: sparkGoalRequestSchema.extend({
110
+ title: sparkGoalRequestSchema.shape.title.describe("For set: two to four words in sentence case naming what is being made."),
111
+ conditions: sparkGoalRequestSchema.shape.conditions.describe("For set, and for change when the conditions change: the full list. Only constraints the user stated or directly implied, never your own, each marked measurable. The description of what to make is not a list of constraints: leave out its parts and features, and any instruction about how to work, what to check or what to render. State each as a fact about the finished result in a few words of the user's language, with its number and unit: \"Height is 120 mm\", not \"Make it 120 mm tall\". Split compound constraints. If the user asked for a look, style, feel or quality that takes judgement, add it as one condition that is not measurable, left to their review. Keep a condition's words as they are when it does not change."),
112
+ tries: sparkGoalRequestSchema.shape.tries.describe(`For set or change: the most tries the goal may take, when the user gave a number. A new goal otherwise gets ${GOAL_DEFAULT_CAPS.tries}, and continue adds ${GOAL_MORE_TRIES} to one that used its tries.`),
113
+ credits: sparkGoalRequestSchema.shape.credits.describe(`For set or change: the most credits the goal may spend, when the user gave a number. A new goal otherwise gets ${GOAL_DEFAULT_CAPS.credits.toLocaleString("en-US")}.`),
114
114
  }),
115
- toModelOutput: ({ output }) => ({ type: "text", value: GOAL_OUTCOMES[output.goal] }),
115
+ execute: (input, { toolCallId }) => execute({ id: toolCallId, name: "goal", input }, () => handleGoal(input)),
116
+ toModelOutput: ({ output }) => ({ type: "text", value: goalResultText(output) }),
116
117
  }),
117
118
  }),
118
119
  read_skill: tool({
package/dist/agent.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { streamText, type LanguageModel, type ModelMessage } from "ai";
2
- import { type SparkGoalOffer, type SparkPersistence } from "./agent-tools.js";
2
+ import { type SparkGoalHandler, type SparkPersistence } from "./agent-tools.js";
3
3
  import type { SparkArtifactResolver, SparkCapabilities } from "./capabilities.js";
4
4
  import type { JavaScriptExecutor } from "./executor.js";
5
5
  import { type SparkCompactionLimits } from "./compaction.js";
@@ -34,8 +34,8 @@ export type SparkAgentOptions = {
34
34
  maxOutputTokens?: number;
35
35
  executionTimeoutMs?: number;
36
36
  persistence?: SparkPersistence;
37
- /** Gives the model `propose_goal`; absent, it has no way to offer a goal. */
38
- proposeGoal?: SparkGoalOffer;
37
+ /** Gives the model `goal`; absent, it has no way to set or change a goal. */
38
+ handleGoal?: SparkGoalHandler;
39
39
  prepareMessages?(messages: ModelMessage[]): Promise<ModelMessage[]>;
40
40
  /** The model's context window, which caps when `history` is compacted. Absent: `contextWindowFor(modelId)`. */
41
41
  contextWindow?: number;
package/dist/client.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { ChatRequestOptions, ChatTransport, UIMessageChunk } from "ai";
2
2
  import type { SparkRunSettings } from "./server/types.js";
3
3
  import type { SparkGoal, SparkGoalCommand } from "./goals.js";
4
- export type { SparkGoal, SparkGoalCommand, SparkGoalCondition, SparkGoalDecision, SparkGoalProposal, SparkGoalTry } from "./goals.js";
4
+ export type { SparkGoal, SparkGoalCommand, SparkGoalCondition, SparkGoalTry } from "./goals.js";
5
5
  import type { SparkConversation, SparkConversationSummary, SparkRun } from "./server/types.js";
6
6
  import type { SparkUIMessage } from "./ui.js";
7
7
  export type { SparkConversation, SparkConversationSummary, SparkRun, SparkRunSettings, } from "./server/types.js";
package/dist/goals.d.ts CHANGED
@@ -22,56 +22,63 @@ export type SparkGoalTry = {
22
22
  /** In the order of the goal's conditions; a condition left to the user has no result. */
23
23
  conditions: Pick<SparkGoalCondition, "met" | "reason">[];
24
24
  };
25
- /** The goal the agent proposes for a request, for the user to confirm before it starts. */
26
- export declare const sparkGoalProposalSchema: z.ZodObject<{
27
- title: z.ZodString;
28
- conditions: z.ZodArray<z.ZodObject<{
29
- text: z.ZodString;
30
- measurable: z.ZodBoolean;
31
- }, z.core.$strip>>;
32
- }, z.core.$strip>;
33
- export type SparkGoalProposal = z.infer<typeof sparkGoalProposalSchema>;
34
- /**
35
- * How the user answered a proposed goal: run it with these caps, try the request
36
- * once, or nothing in the time the host waits.
37
- */
38
- export declare const sparkGoalDecisionSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
39
- creditBudget: z.ZodOptional<z.ZodNumber>;
40
- maxTurns: z.ZodOptional<z.ZodNumber>;
41
- kind: z.ZodLiteral<"goal">;
42
- }, z.core.$strip>, z.ZodObject<{
43
- kind: z.ZodLiteral<"once">;
44
- }, z.core.$strip>, z.ZodObject<{
45
- kind: z.ZodLiteral<"unanswered">;
46
- }, z.core.$strip>], "kind">;
47
- export type SparkGoalDecision = z.infer<typeof sparkGoalDecisionSchema>;
48
- /** What became of a proposal, as the agent is told: `active` when a goal was already running. */
49
- export declare const SPARK_GOAL_OUTCOMES: readonly ["started", "declined", "unanswered", "active"];
50
- export type SparkGoalOutcome = (typeof SPARK_GOAL_OUTCOMES)[number];
25
+ /** The caps of a goal the agent sets, unless the user asked for others. */
26
+ export declare const GOAL_DEFAULT_CAPS: {
27
+ readonly tries: 5;
28
+ readonly credits: 2000;
29
+ };
30
+ /** The tries a goal that used its tries gets when the user has it keep going. */
31
+ export declare const GOAL_MORE_TRIES = 3;
51
32
  /**
52
- * A proposal as its message stores it: the `propose_goal` call that made it, and
53
- * its outcome once there is one. Without an outcome it is waiting for the user
54
- * while its run is, and was left unanswered once that run has ended.
33
+ * What the agent asks with the `goal` tool, for the user. `set` starts a goal
34
+ * from `title` and `conditions`, at once, with the asking run as its first try;
35
+ * a goal the conversation already has ends. `change` gives the goal new
36
+ * `conditions`, `tries` or `credits`. `continue` has a goal that stopped go on.
37
+ * `remove` ends the goal. After a change the goal goes on, with the asking run
38
+ * as its next try.
55
39
  */
56
- export declare const sparkGoalProposalPartSchema: z.ZodObject<{
57
- title: z.ZodString;
58
- conditions: z.ZodArray<z.ZodObject<{
40
+ export declare const sparkGoalRequestSchema: z.ZodObject<{
41
+ action: z.ZodEnum<{
42
+ set: "set";
43
+ remove: "remove";
44
+ change: "change";
45
+ continue: "continue";
46
+ }>;
47
+ title: z.ZodOptional<z.ZodString>;
48
+ conditions: z.ZodOptional<z.ZodArray<z.ZodObject<{
59
49
  text: z.ZodString;
60
50
  measurable: z.ZodBoolean;
61
- }, z.core.$strip>>;
62
- toolCallId: z.ZodString;
63
- outcome: z.ZodOptional<z.ZodEnum<{
64
- active: "active";
65
- unanswered: "unanswered";
66
- started: "started";
67
- declined: "declined";
68
- }>>;
51
+ }, z.core.$strip>>>;
52
+ tries: z.ZodOptional<z.ZodNumber>;
53
+ credits: z.ZodOptional<z.ZodNumber>;
69
54
  }, z.core.$strip>;
70
- export type SparkGoalProposalPart = z.infer<typeof sparkGoalProposalPartSchema>;
71
- /** The caps a goal confirmation offers before the user changes them. */
72
- export declare const GOAL_CONFIRMATION_DEFAULTS: {
73
- readonly tries: 5;
74
- readonly credits: 2000;
55
+ export type SparkGoalRequest = z.infer<typeof sparkGoalRequestSchema>;
56
+ /**
57
+ * What a `goal` call did. `started`: a goal is set and running. `running`: the
58
+ * goal goes on with the change. `done`: with the change every measurable
59
+ * condition is already verified. `limited`: the goal is at its tries or credit
60
+ * limit and does not run. `removed`: the goal is gone. `refused`: nothing
61
+ * changed, since only a turn the user started may change a goal, and not one
62
+ * Wompify runs. `missing`: there is no goal to change.
63
+ */
64
+ export type SparkGoalOutcome = "started" | "running" | "done" | "limited" | "removed" | "refused" | "missing";
65
+ /** A goal that ended, as the chat keeps it once the conversation has moved on. */
66
+ export type SparkGoalSummary = {
67
+ title: string;
68
+ outcome: "done" | "replaced" | "removed";
69
+ /** The tries it finished. */
70
+ tries: number;
71
+ credits?: number;
72
+ /** Of its `measured` conditions, how many its last check found met. */
73
+ passed: number;
74
+ measured: number;
75
+ };
76
+ /** A `goal` call's result: the goal's limits where it has a goal, and the goal the call ended. */
77
+ export type SparkGoalResult = {
78
+ goal: SparkGoalOutcome;
79
+ tries?: number;
80
+ credits?: number;
81
+ ended?: SparkGoalSummary;
75
82
  };
76
83
  export type SparkGoal = {
77
84
  id: string;
package/dist/goals.js CHANGED
@@ -15,33 +15,25 @@ const goalCaps = {
15
15
  creditBudget: z.number().int().positive().max(1_000_000_000).optional(),
16
16
  maxTurns: z.number().int().min(1).max(100).optional(),
17
17
  };
18
- /** The goal the agent proposes for a request, for the user to confirm before it starts. */
19
- export const sparkGoalProposalSchema = z.object({
20
- title: z.string().trim().min(1).max(80),
21
- conditions: z.array(sparkGoalConditionSchema).min(1).max(MAX_GOAL_CONDITIONS),
22
- });
23
- /**
24
- * How the user answered a proposed goal: run it with these caps, try the request
25
- * once, or nothing in the time the host waits.
26
- */
27
- export const sparkGoalDecisionSchema = z.discriminatedUnion("kind", [
28
- z.object({ kind: z.literal("goal"), ...goalCaps }),
29
- z.object({ kind: z.literal("once") }),
30
- z.object({ kind: z.literal("unanswered") }),
31
- ]);
32
- /** What became of a proposal, as the agent is told: `active` when a goal was already running. */
33
- export const SPARK_GOAL_OUTCOMES = ["started", "declined", "unanswered", "active"];
18
+ /** The caps of a goal the agent sets, unless the user asked for others. */
19
+ export const GOAL_DEFAULT_CAPS = { tries: 5, credits: 2_000 };
20
+ /** The tries a goal that used its tries gets when the user has it keep going. */
21
+ export const GOAL_MORE_TRIES = 3;
34
22
  /**
35
- * A proposal as its message stores it: the `propose_goal` call that made it, and
36
- * its outcome once there is one. Without an outcome it is waiting for the user
37
- * while its run is, and was left unanswered once that run has ended.
23
+ * What the agent asks with the `goal` tool, for the user. `set` starts a goal
24
+ * from `title` and `conditions`, at once, with the asking run as its first try;
25
+ * a goal the conversation already has ends. `change` gives the goal new
26
+ * `conditions`, `tries` or `credits`. `continue` has a goal that stopped go on.
27
+ * `remove` ends the goal. After a change the goal goes on, with the asking run
28
+ * as its next try.
38
29
  */
39
- export const sparkGoalProposalPartSchema = sparkGoalProposalSchema.extend({
40
- toolCallId: z.string().min(1),
41
- outcome: z.enum(SPARK_GOAL_OUTCOMES).optional(),
30
+ export const sparkGoalRequestSchema = z.object({
31
+ action: z.enum(["set", "change", "continue", "remove"]),
32
+ title: z.string().trim().min(1).max(80).optional(),
33
+ conditions: z.array(sparkGoalConditionSchema).min(1).max(MAX_GOAL_CONDITIONS).optional(),
34
+ tries: goalCaps.maxTurns,
35
+ credits: goalCaps.creditBudget,
42
36
  });
43
- /** The caps a goal confirmation offers before the user changes them. */
44
- export const GOAL_CONFIRMATION_DEFAULTS = { tries: 5, credits: 2_000 };
45
37
  export const sparkGoalCommandSchema = z.discriminatedUnion("action", [
46
38
  z.object({
47
39
  action: z.literal("set"),
@@ -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;
package/dist/ui.d.ts CHANGED
@@ -3,8 +3,8 @@ export { sparkErrorDiagnostics, sparkErrorDiagnosticsSchema, type SparkErrorDiag
3
3
  import type { InferUIMessageChunk, UIMessage } from "ai";
4
4
  import type { SceneScreenshotOptions } from "./capabilities/scene.js";
5
5
  import { z } from "zod";
6
- export type { SparkGoal, SparkGoalCommand, SparkGoalCondition, SparkGoalDecision, SparkGoalOutcome, SparkGoalProposal, SparkGoalProposalPart, SparkGoalTry } from "./goals.js";
7
- import { type SparkGoalOutcome, type SparkGoalProposal, type SparkGoalProposalPart } from "./goals.js";
6
+ export type { SparkGoal, SparkGoalCommand, SparkGoalCondition, SparkGoalOutcome, SparkGoalRequest, SparkGoalResult, SparkGoalSummary, SparkGoalTry } from "./goals.js";
7
+ import type { SparkGoalRequest, SparkGoalResult } from "./goals.js";
8
8
  import type { ExecutionReceipt, SparkSkill } from "./capabilities.js";
9
9
  export { DEFAULT_MODEL_ID, getSparkModel, REASONING_EFFORT_LABELS, resolveReasoningEffort, SPARK_MODELS, } from "./models.js";
10
10
  export type { ModelProvider, ReasoningEffort, SparkModel } from "./models.js";
@@ -92,7 +92,6 @@ export type SparkDataParts = {
92
92
  };
93
93
  selection: SparkSelectionData;
94
94
  compaction: SparkCompaction;
95
- "goal-proposal": SparkGoalProposalPart;
96
95
  "flow-run-result": SparkFlowRunResult;
97
96
  };
98
97
  /** Editor node IDs selected when a user message was sent; never rendered as chat text. */
@@ -157,12 +156,10 @@ export type SparkUITools = {
157
156
  skills: SkillReadResult[];
158
157
  };
159
158
  };
160
- /** Offered only by hosts that can ask the user; see `SparkGoalOffer`. */
161
- propose_goal: {
162
- input: SparkGoalProposal;
163
- output: {
164
- goal: SparkGoalOutcome;
165
- };
159
+ /** Offered only by hosts that run goals; see `SparkGoalHandler`. */
160
+ goal: {
161
+ input: SparkGoalRequest;
162
+ output: SparkGoalResult;
166
163
  };
167
164
  };
168
165
  export type SkillReadResult = ({
@@ -197,9 +194,9 @@ export declare const sparkMessageMetadataSchema: z.ZodObject<{
197
194
  durationMs: z.ZodOptional<z.ZodNumber>;
198
195
  runId: z.ZodOptional<z.ZodString>;
199
196
  runStatus: z.ZodOptional<z.ZodEnum<{
197
+ running: "running";
200
198
  completed: "completed";
201
199
  queued: "queued";
202
- running: "running";
203
200
  requires_action: "requires_action";
204
201
  failed: "failed";
205
202
  cancelled: "cancelled";
@@ -322,9 +319,9 @@ export declare const sparkDataPartSchemas: {
322
319
  readonly "run-status": z.ZodObject<{
323
320
  runId: z.ZodString;
324
321
  status: z.ZodEnum<{
322
+ running: "running";
325
323
  completed: "completed";
326
324
  queued: "queued";
327
- running: "running";
328
325
  requires_action: "requires_action";
329
326
  failed: "failed";
330
327
  cancelled: "cancelled";
@@ -408,25 +405,6 @@ export declare const sparkDataPartSchemas: {
408
405
  tokensAfter: z.ZodNumber;
409
406
  createdAt: z.ZodString;
410
407
  }, z.core.$strip>;
411
- /**
412
- * The goal the agent proposed in this message, for hosts to show: as the
413
- * confirmation while it waits, and as the goal once it started. The model
414
- * reads the proposal from its `propose_goal` call, not from this part.
415
- */
416
- readonly "goal-proposal": z.ZodObject<{
417
- title: z.ZodString;
418
- conditions: z.ZodArray<z.ZodObject<{
419
- text: z.ZodString;
420
- measurable: z.ZodBoolean;
421
- }, z.core.$strip>>;
422
- toolCallId: z.ZodString;
423
- outcome: z.ZodOptional<z.ZodEnum<{
424
- active: "active";
425
- unanswered: "unanswered";
426
- started: "started";
427
- declined: "declined";
428
- }>>;
429
- }, z.core.$strip>;
430
408
  /**
431
409
  * A finished flow run, as an event. Hosts attach it to a user message, render
432
410
  * it as an event and not as that user's text; the model reads it as text
@@ -460,4 +438,4 @@ export declare const sparkDataPartSchemas: {
460
438
  }, z.core.$strip>;
461
439
  };
462
440
  export { parseWompifyCommand, WOMPIFY_PRESETS, wompifyPrompt, wompifyContextSchema, type WompifyRequest, type WompifyContext } from "./wompify.js";
463
- export { DEFAULT_GOAL_CREDITS, GOAL_CONFIRMATION_DEFAULTS, sparkGoalProposalPartSchema, sparkGoalProposalSchema } from "./goals.js";
441
+ export { DEFAULT_GOAL_CREDITS } from "./goals.js";
package/dist/ui.js CHANGED
@@ -1,7 +1,6 @@
1
1
  import { sparkErrorDiagnosticsSchema } from "./error-diagnostics.js";
2
2
  export { sparkErrorDiagnostics, sparkErrorDiagnosticsSchema, } from "./error-diagnostics.js";
3
3
  import { z } from "zod";
4
- import { sparkGoalProposalPartSchema } from "./goals.js";
5
4
  export { DEFAULT_MODEL_ID, getSparkModel, REASONING_EFFORT_LABELS, resolveReasoningEffort, SPARK_MODELS, } from "./models.js";
6
5
  export const SPARK_RUN_STATUSES = [
7
6
  "queued",
@@ -123,12 +122,6 @@ export const sparkDataPartSchemas = {
123
122
  tokensAfter: z.number().int().nonnegative(),
124
123
  createdAt: z.string().datetime(),
125
124
  }),
126
- /**
127
- * The goal the agent proposed in this message, for hosts to show: as the
128
- * confirmation while it waits, and as the goal once it started. The model
129
- * reads the proposal from its `propose_goal` call, not from this part.
130
- */
131
- "goal-proposal": sparkGoalProposalPartSchema,
132
125
  /**
133
126
  * A finished flow run, as an event. Hosts attach it to a user message, render
134
127
  * it as an event and not as that user's text; the model reads it as text
@@ -137,4 +130,4 @@ export const sparkDataPartSchemas = {
137
130
  "flow-run-result": flowRunResultSchema,
138
131
  };
139
132
  export { parseWompifyCommand, WOMPIFY_PRESETS, wompifyPrompt, wompifyContextSchema } from "./wompify.js";
140
- export { DEFAULT_GOAL_CREDITS, GOAL_CONFIRMATION_DEFAULTS, sparkGoalProposalPartSchema, sparkGoalProposalSchema } from "./goals.js";
133
+ export { DEFAULT_GOAL_CREDITS } from "./goals.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@womp/spark-agent",
3
- "version": "9.5.0",
3
+ "version": "10.0.0",
4
4
  "description": "Portable skills-based AI agent with local and durable chat transports for Womp",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",