@narumitw/pi-goal 0.13.1 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +2 -2
  2. package/src/goal.ts +745 -703
package/src/goal.ts CHANGED
@@ -1,29 +1,21 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { defineTool, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
2
  import {
4
3
  isContextOverflow,
5
4
  type AssistantMessage as PiAssistantMessage,
6
5
  type Usage,
7
6
  } from "@earendil-works/pi-ai";
7
+ import { defineTool, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
8
8
  import { Type } from "typebox";
9
9
  import {
10
10
  assistantUsageTokens,
11
11
  checkpointGoalActiveTime,
12
- cumulativeAssistantTokens,
13
12
  currentTokenTotal,
14
13
  formatDuration,
15
14
  formatTokenCount,
16
- isNonNegativeFiniteNumber,
17
15
  nonNegativeFiniteNumber,
18
- normalizeTokenBudget,
19
16
  updateGoalUsage,
20
17
  } from "./accounting.js";
21
- import {
22
- completeGoalArguments,
23
- parseCommand,
24
- parseTokenBudget,
25
- validateObjective,
26
- } from "./command.js";
18
+ import { completeGoalArguments, parseCommand, validateObjective } from "./command.js";
27
19
  import {
28
20
  type ActiveGoal,
29
21
  clearLegacyPersistedGoal,
@@ -41,11 +33,12 @@ import {
41
33
 
42
34
  type AgentStopReason = "stop" | "length" | "toolUse" | "error" | "aborted";
43
35
 
44
- // This module intentionally retains the shared lifecycle state machine: every
45
- // Pi hook and goal tool coordinates the same goal, continuation, retry, stale-
46
- // turn guard, and budget single-flight state. Pure command, prompt, accounting,
47
- // and persistence logic lives in focused modules; splitting the remaining
48
- // handlers would create ambiguous mutable-state ownership.
36
+ // Per-factory GoalRuntime owns mutable goal/continuation/budget/recovery state
37
+ // so concurrent in-process AgentSessions cannot clobber each other. Pure helpers
38
+ // live at module scope (single source of truth). registerGoalRuntime still keeps
39
+ // the orchestration handlers together so mutable ownership does not fragment
40
+ // across files; a file-size split is deferred until that ownership boundary is
41
+ // stable under isolation tests.
49
42
 
50
43
  interface GoalCompleteDetails {
51
44
  goal: string;
@@ -136,222 +129,234 @@ const RETRYABLE_GOAL_ERROR_PATTERNS = [
136
129
  /timed? out|timeout|terminated|websocket.?(?:closed|error)|ended without|stream ended before message_stop|http2 request did not get a response|retry delay/i,
137
130
  /context[_\s-]*length[_\s-]*exceeded|input exceeds the context window/i,
138
131
  ] as const;
139
- let activeGoal: ActiveGoal | undefined;
140
- let completionStatusTimer: NodeJS.Timeout | undefined;
141
- let extensionApi: ExtensionAPI | undefined;
142
- let continuationIntent: ContinuationTicket | undefined;
143
- let continuationDelivery: ContinuationTicket | undefined;
144
- let goalRecovery: GoalRecovery | undefined;
145
- let budgetWrapUp: BudgetWrapUp | undefined;
146
- let staleGoalToolCallsBlocked = false;
147
- const cancelledContinuationMarkers = new Set<string>();
148
-
149
- const goalCompleteTool = defineTool({
150
- name: "goal_complete",
151
- label: "Goal Complete",
152
- description:
153
- "Mark the active /goal as complete after all required work is done and verified, using the current goal_id stale-turn guard. Do not use for partial progress, blockers, failing, or unverified work.",
154
- promptSnippet:
155
- "Mark the active /goal as complete after fully finishing and verifying it, with the current goal_id",
156
- promptGuidelines: [
157
- "When a /goal is active, keep working until the goal is complete; do not stop with only a plan or partial progress.",
158
- "Before calling goal_complete, audit the active goal requirement by requirement against the current files, command output, tests, or external state.",
159
- "Pass the exact goal_id shown in the current /goal prompt; never reuse a goal_id from an older, stopped, replaced, or cleared turn.",
160
- "Call goal_complete only after the requested goal is fully implemented, verified, and no known required work remains; otherwise keep working.",
161
- ],
162
- parameters: Type.Object({
163
- goal_id: Type.String({
164
- description:
165
- "The exact goal_id shown in the current active /goal prompt. Used only to reject stale completion calls from older turns.",
166
- }),
167
- summary: Type.String({
168
- description:
169
- "State what was completed and what evidence verified it. Do not use this tool to report partial progress, blockers, failures, or remaining work.",
132
+
133
+ interface GoalRuntime {
134
+ readonly pi: ExtensionAPI;
135
+ activeGoal?: ActiveGoal;
136
+ completionStatusTimer?: NodeJS.Timeout;
137
+ continuationIntent?: ContinuationTicket;
138
+ continuationDelivery?: ContinuationTicket;
139
+ goalRecovery?: GoalRecovery;
140
+ budgetWrapUp?: BudgetWrapUp;
141
+ staleGoalToolCallsBlocked: boolean;
142
+ cancelledContinuationMarkers: Set<string>;
143
+ }
144
+
145
+ function createGoalRuntime(pi: ExtensionAPI): GoalRuntime {
146
+ return {
147
+ pi,
148
+ staleGoalToolCallsBlocked: false,
149
+ cancelledContinuationMarkers: new Set(),
150
+ };
151
+ }
152
+
153
+ function registerGoalRuntime(pi: ExtensionAPI) {
154
+ const runtime = createGoalRuntime(pi);
155
+
156
+ const goalCompleteTool = defineTool({
157
+ name: "goal_complete",
158
+ label: "Goal Complete",
159
+ description:
160
+ "Mark the active /goal as complete after all required work is done and verified, using the current goal_id stale-turn guard. Do not use for partial progress, blockers, failing, or unverified work.",
161
+ promptSnippet:
162
+ "Mark the active /goal as complete after fully finishing and verifying it, with the current goal_id",
163
+ promptGuidelines: [
164
+ "When a /goal is active, keep working until the goal is complete; do not stop with only a plan or partial progress.",
165
+ "Before calling goal_complete, audit the active goal requirement by requirement against the current files, command output, tests, or external state.",
166
+ "Pass the exact goal_id shown in the current /goal prompt; never reuse a goal_id from an older, stopped, replaced, or cleared turn.",
167
+ "Call goal_complete only after the requested goal is fully implemented, verified, and no known required work remains; otherwise keep working.",
168
+ ],
169
+ parameters: Type.Object({
170
+ goal_id: Type.String({
171
+ description:
172
+ "The exact goal_id shown in the current active /goal prompt. Used only to reject stale completion calls from older turns.",
173
+ }),
174
+ summary: Type.String({
175
+ description:
176
+ "State what was completed and what evidence verified it. Do not use this tool to report partial progress, blockers, failures, or remaining work.",
177
+ }),
170
178
  }),
171
- }),
172
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
173
- const completedGoal = activeGoal;
174
- const goal = completedGoal?.text ?? "unknown goal";
175
- const requestedGoalId = typeof params.goal_id === "string" ? params.goal_id.trim() : "";
176
- const summary = typeof params.summary === "string" ? params.summary.trim() : "";
179
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
180
+ const completedGoal = runtime.activeGoal;
181
+ const goal = completedGoal?.text ?? "unknown goal";
182
+ const requestedGoalId = typeof params.goal_id === "string" ? params.goal_id.trim() : "";
183
+ const summary = typeof params.summary === "string" ? params.summary.trim() : "";
184
+
185
+ if (!completedGoal) {
186
+ const rejection = "Goal completion rejected: no active goal.";
187
+ ctx.ui.notify(rejection, "warning");
188
+
189
+ return {
190
+ content: [{ type: "text", text: rejection }],
191
+ details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
192
+ };
193
+ }
177
194
 
178
- if (!completedGoal) {
179
- const rejection = "Goal completion rejected: no active goal.";
180
- ctx.ui.notify(rejection, "warning");
195
+ const completingDuringBudgetWrapUp =
196
+ completedGoal.status === "budget_limited" &&
197
+ runtime.budgetWrapUp?.goalId === completedGoal.id &&
198
+ runtime.budgetWrapUp.delivered;
199
+ const staleGoalRejection = goalIdRejectionReason(completedGoal, requestedGoalId);
200
+ if (staleGoalRejection) {
201
+ const rejection = `Goal completion rejected: ${staleGoalRejection}.`;
202
+ ctx.ui.notify(rejection, "warning");
203
+ if (completingDuringBudgetWrapUp) {
204
+ updateGoalUsage(completedGoal, ctx);
205
+ persistGoal(completedGoal);
206
+ updateStatus(ctx, completedGoal);
207
+ clearBudgetWrapUp();
208
+ }
181
209
 
182
- return {
183
- content: [{ type: "text", text: rejection }],
184
- details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
185
- };
186
- }
210
+ return {
211
+ content: [{ type: "text", text: rejection }],
212
+ details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
213
+ terminate: completingDuringBudgetWrapUp || undefined,
214
+ };
215
+ }
216
+ if (completedGoal.status !== "active" && !completingDuringBudgetWrapUp) {
217
+ const rejection = `Goal completion rejected: goal is ${completedGoal.status}, not active.`;
218
+ ctx.ui.notify(rejection, "warning");
219
+
220
+ return {
221
+ content: [{ type: "text", text: rejection }],
222
+ details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
223
+ };
224
+ }
187
225
 
188
- const completingDuringBudgetWrapUp =
189
- completedGoal.status === "budget_limited" &&
190
- budgetWrapUp?.goalId === completedGoal.id &&
191
- budgetWrapUp.delivered;
192
- const staleGoalRejection = goalIdRejectionReason(completedGoal, requestedGoalId);
193
- if (staleGoalRejection) {
194
- const rejection = `Goal completion rejected: ${staleGoalRejection}.`;
195
- ctx.ui.notify(rejection, "warning");
196
- if (completingDuringBudgetWrapUp) {
226
+ const rejectionReason = !summary
227
+ ? "summary is empty"
228
+ : isContradictoryCompletionSummary(summary)
229
+ ? "summary says the goal is not complete"
230
+ : undefined;
231
+ if (rejectionReason) {
197
232
  updateGoalUsage(completedGoal, ctx);
198
233
  persistGoal(completedGoal);
199
234
  updateStatus(ctx, completedGoal);
200
- clearBudgetWrapUp();
235
+ const rejection = `Goal completion rejected: ${rejectionReason}.`;
236
+ ctx.ui.notify(rejection, "warning");
237
+ if (completingDuringBudgetWrapUp) clearBudgetWrapUp();
238
+
239
+ return {
240
+ content: [
241
+ {
242
+ type: "text",
243
+ text: rejection,
244
+ },
245
+ ],
246
+ details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
247
+ terminate: completingDuringBudgetWrapUp || undefined,
248
+ };
201
249
  }
202
250
 
203
- return {
204
- content: [{ type: "text", text: rejection }],
205
- details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
206
- terminate: completingDuringBudgetWrapUp || undefined,
207
- };
208
- }
209
- if (completedGoal.status !== "active" && !completingDuringBudgetWrapUp) {
210
- const rejection = `Goal completion rejected: goal is ${completedGoal.status}, not active.`;
211
- ctx.ui.notify(rejection, "warning");
212
-
213
- return {
214
- content: [{ type: "text", text: rejection }],
215
- details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
216
- };
217
- }
251
+ runtime.activeGoal = transitionGoal(completedGoal, "complete");
252
+ updateGoalUsage(runtime.activeGoal, ctx);
253
+ persistGoal(runtime.activeGoal);
218
254
 
219
- const rejectionReason = !summary
220
- ? "summary is empty"
221
- : isContradictoryCompletionSummary(summary)
222
- ? "summary says the goal is not complete"
223
- : undefined;
224
- if (rejectionReason) {
225
- updateGoalUsage(completedGoal, ctx);
226
- persistGoal(completedGoal);
227
- updateStatus(ctx, completedGoal);
228
- const rejection = `Goal completion rejected: ${rejectionReason}.`;
229
- ctx.ui.notify(rejection, "warning");
230
- if (completingDuringBudgetWrapUp) clearBudgetWrapUp();
255
+ ctx.ui.setStatus(STATUS_KEY, formatStatus(runtime.activeGoal));
256
+ clearActiveGoal(ctx);
257
+ showCompletionStatus(ctx);
258
+ ctx.ui.notify(`Goal complete: ${goal}`, "info");
231
259
 
232
260
  return {
233
- content: [
234
- {
235
- type: "text",
236
- text: rejection,
237
- },
238
- ],
261
+ content: [{ type: "text", text: `Goal complete: ${summary}` }],
239
262
  details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
240
- terminate: completingDuringBudgetWrapUp || undefined,
263
+ terminate: true,
241
264
  };
242
- }
265
+ },
266
+ });
243
267
 
244
- activeGoal = transitionGoal(completedGoal, "complete");
245
- updateGoalUsage(activeGoal, ctx);
246
- persistGoal(activeGoal);
268
+ const goalBlockedTool = defineTool({
269
+ name: "goal_blocked",
270
+ label: "Goal Blocked",
271
+ description:
272
+ "Stop the active /goal only at a true impasse after the same blocker recurs for at least three consecutive goal turns, with the current goal_id and concrete evidence that user or external action is required. Do not use for ordinary clarification, uncertainty, or recoverable failures.",
273
+ promptSnippet:
274
+ "Mark the active /goal blocked only after the same blocker recurs for three consecutive goal turns",
275
+ promptGuidelines: [
276
+ "Use goal_blocked only for a true impasse after the same blocker recurs for at least three consecutive goal turns and concrete evidence shows user or external action is required.",
277
+ "After a blocked goal is resumed, start a fresh three-turn blocker audit before using goal_blocked again.",
278
+ "Do not use goal_blocked for ordinary clarification, incomplete work, uncertainty, difficult tasks, or recoverable tool/provider failures.",
279
+ "Pass goal_blocked the exact current goal_id; never reuse a goal_id from an older, stopped, replaced, or cleared goal turn.",
280
+ ],
281
+ parameters: Type.Object({
282
+ goal_id: Type.String({
283
+ description: "The exact goal_id shown in the current active /goal prompt.",
284
+ }),
285
+ reason: Type.String({
286
+ minLength: 1,
287
+ maxLength: MAX_BLOCKER_REASON_LENGTH,
288
+ description: "The specific user or external action required to unblock the goal.",
289
+ }),
290
+ evidence: Type.String({
291
+ minLength: 1,
292
+ maxLength: MAX_BLOCKER_EVIDENCE_LENGTH,
293
+ description: "Concrete evidence from the repeated attempts that proves the impasse.",
294
+ }),
295
+ repeated_turns: Type.Integer({
296
+ minimum: 3,
297
+ description: "Number of separate turns spent trying to resolve this same blocker.",
298
+ }),
299
+ }),
300
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
301
+ const blockedGoal = runtime.activeGoal;
302
+ const goal = blockedGoal?.text ?? "unknown goal";
303
+ const requestedGoalId = typeof params.goal_id === "string" ? params.goal_id.trim() : "";
304
+ const reason = typeof params.reason === "string" ? params.reason.trim() : "";
305
+ const evidence = typeof params.evidence === "string" ? params.evidence.trim() : "";
306
+ const repeatedTurns =
307
+ typeof params.repeated_turns === "number" ? params.repeated_turns : Number.NaN;
308
+ const reject = (rejectionReason: string) => {
309
+ const rejection = `goal_blocked rejected: ${rejectionReason}.`;
310
+ ctx.ui.notify(rejection, "warning");
311
+ return {
312
+ content: [{ type: "text" as const, text: rejection }],
313
+ details: {
314
+ goal,
315
+ goal_id: requestedGoalId,
316
+ reason: reason.slice(0, MAX_BLOCKER_REASON_LENGTH),
317
+ evidence: evidence.slice(0, MAX_BLOCKER_EVIDENCE_LENGTH),
318
+ repeated_turns: Number.isFinite(repeatedTurns) ? repeatedTurns : 0,
319
+ } satisfies GoalBlockedDetails,
320
+ };
321
+ };
247
322
 
248
- ctx.ui.setStatus(STATUS_KEY, formatStatus(activeGoal));
249
- clearActiveGoal(ctx);
250
- showCompletionStatus(ctx);
251
- ctx.ui.notify(`Goal complete: ${goal}`, "info");
323
+ if (!blockedGoal) return reject("no active goal");
324
+ const staleGoalRejection = goalIdRejectionReason(blockedGoal, requestedGoalId);
325
+ if (staleGoalRejection) return reject(staleGoalRejection);
326
+ if (blockedGoal.status !== "active") {
327
+ return reject(`goal is ${blockedGoal.status}, not active`);
328
+ }
329
+ if (!reason) return reject("reason is empty");
330
+ if (reason.length > MAX_BLOCKER_REASON_LENGTH) return reject("reason is too long");
331
+ if (!evidence) return reject("evidence is empty");
332
+ if (evidence.length > MAX_BLOCKER_EVIDENCE_LENGTH) return reject("evidence is too long");
333
+ if (!Number.isInteger(repeatedTurns)) return reject("repeated_turns must be a whole number");
334
+ if (repeatedTurns < 3) return reject("repeated_turns must be at least 3");
335
+
336
+ updateGoalUsage(blockedGoal, ctx);
337
+ cancelContinuationWork();
338
+ clearBudgetWrapUp();
339
+ clearGoalRecoveryForGoal(blockedGoal.id);
340
+ blockStaleGoalToolCalls();
341
+ runtime.activeGoal = transitionGoal(blockedGoal, "blocked");
342
+ persistGoal(runtime.activeGoal);
343
+ updateStatus(ctx, runtime.activeGoal);
344
+ ctx.ui.notify(`Goal blocked: ${truncateNotification(reason)}`, "warning");
252
345
 
253
- return {
254
- content: [{ type: "text", text: `Goal complete: ${summary}` }],
255
- details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
256
- terminate: true,
257
- };
258
- },
259
- });
260
-
261
- const goalBlockedTool = defineTool({
262
- name: "goal_blocked",
263
- label: "Goal Blocked",
264
- description:
265
- "Stop the active /goal only at a true impasse after the same blocker recurs for at least three consecutive goal turns, with the current goal_id and concrete evidence that user or external action is required. Do not use for ordinary clarification, uncertainty, or recoverable failures.",
266
- promptSnippet:
267
- "Mark the active /goal blocked only after the same blocker recurs for three consecutive goal turns",
268
- promptGuidelines: [
269
- "Use goal_blocked only for a true impasse after the same blocker recurs for at least three consecutive goal turns and concrete evidence shows user or external action is required.",
270
- "After a blocked goal is resumed, start a fresh three-turn blocker audit before using goal_blocked again.",
271
- "Do not use goal_blocked for ordinary clarification, incomplete work, uncertainty, difficult tasks, or recoverable tool/provider failures.",
272
- "Pass goal_blocked the exact current goal_id; never reuse a goal_id from an older, stopped, replaced, or cleared goal turn.",
273
- ],
274
- parameters: Type.Object({
275
- goal_id: Type.String({
276
- description: "The exact goal_id shown in the current active /goal prompt.",
277
- }),
278
- reason: Type.String({
279
- minLength: 1,
280
- maxLength: MAX_BLOCKER_REASON_LENGTH,
281
- description: "The specific user or external action required to unblock the goal.",
282
- }),
283
- evidence: Type.String({
284
- minLength: 1,
285
- maxLength: MAX_BLOCKER_EVIDENCE_LENGTH,
286
- description: "Concrete evidence from the repeated attempts that proves the impasse.",
287
- }),
288
- repeated_turns: Type.Integer({
289
- minimum: 3,
290
- description: "Number of separate turns spent trying to resolve this same blocker.",
291
- }),
292
- }),
293
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
294
- const blockedGoal = activeGoal;
295
- const goal = blockedGoal?.text ?? "unknown goal";
296
- const requestedGoalId = typeof params.goal_id === "string" ? params.goal_id.trim() : "";
297
- const reason = typeof params.reason === "string" ? params.reason.trim() : "";
298
- const evidence = typeof params.evidence === "string" ? params.evidence.trim() : "";
299
- const repeatedTurns =
300
- typeof params.repeated_turns === "number" ? params.repeated_turns : Number.NaN;
301
- const reject = (rejectionReason: string) => {
302
- const rejection = `goal_blocked rejected: ${rejectionReason}.`;
303
- ctx.ui.notify(rejection, "warning");
304
346
  return {
305
- content: [{ type: "text" as const, text: rejection }],
347
+ content: [{ type: "text", text: `Goal blocked: ${reason}` }],
306
348
  details: {
307
349
  goal,
308
350
  goal_id: requestedGoalId,
309
- reason: reason.slice(0, MAX_BLOCKER_REASON_LENGTH),
310
- evidence: evidence.slice(0, MAX_BLOCKER_EVIDENCE_LENGTH),
311
- repeated_turns: Number.isFinite(repeatedTurns) ? repeatedTurns : 0,
351
+ reason,
352
+ evidence,
353
+ repeated_turns: repeatedTurns,
312
354
  } satisfies GoalBlockedDetails,
355
+ terminate: true,
313
356
  };
314
- };
315
-
316
- if (!blockedGoal) return reject("no active goal");
317
- const staleGoalRejection = goalIdRejectionReason(blockedGoal, requestedGoalId);
318
- if (staleGoalRejection) return reject(staleGoalRejection);
319
- if (blockedGoal.status !== "active") {
320
- return reject(`goal is ${blockedGoal.status}, not active`);
321
- }
322
- if (!reason) return reject("reason is empty");
323
- if (reason.length > MAX_BLOCKER_REASON_LENGTH) return reject("reason is too long");
324
- if (!evidence) return reject("evidence is empty");
325
- if (evidence.length > MAX_BLOCKER_EVIDENCE_LENGTH) return reject("evidence is too long");
326
- if (!Number.isInteger(repeatedTurns)) return reject("repeated_turns must be a whole number");
327
- if (repeatedTurns < 3) return reject("repeated_turns must be at least 3");
328
-
329
- updateGoalUsage(blockedGoal, ctx);
330
- cancelContinuationWork();
331
- clearBudgetWrapUp();
332
- clearGoalRecoveryForGoal(blockedGoal.id);
333
- blockStaleGoalToolCalls();
334
- activeGoal = transitionGoal(blockedGoal, "blocked");
335
- persistGoal(activeGoal);
336
- updateStatus(ctx, activeGoal);
337
- ctx.ui.notify(`Goal blocked: ${truncateNotification(reason)}`, "warning");
338
-
339
- return {
340
- content: [{ type: "text", text: `Goal blocked: ${reason}` }],
341
- details: {
342
- goal,
343
- goal_id: requestedGoalId,
344
- reason,
345
- evidence,
346
- repeated_turns: repeatedTurns,
347
- } satisfies GoalBlockedDetails,
348
- terminate: true,
349
- };
350
- },
351
- });
357
+ },
358
+ });
352
359
 
353
- export default function goal(pi: ExtensionAPI) {
354
- extensionApi = pi;
355
360
  pi.registerTool(goalCompleteTool);
356
361
  pi.registerTool(goalBlockedTool);
357
362
 
@@ -373,16 +378,16 @@ export default function goal(pi: ExtensionAPI) {
373
378
  pauseGoal(ctx);
374
379
  return;
375
380
  case "resume":
376
- await resumeGoal(pi, ctx);
381
+ await resumeGoal(runtime.pi, ctx);
377
382
  return;
378
383
  case "clear":
379
384
  clearGoal(ctx);
380
385
  return;
381
386
  case "edit":
382
- await editGoal(result.objective ?? "", result.tokenBudget, pi, ctx);
387
+ await editGoal(result.objective ?? "", result.tokenBudget, runtime.pi, ctx);
383
388
  return;
384
389
  case "start":
385
- await startGoal(result.objective ?? "", result.tokenBudget, pi, ctx);
390
+ await startGoal(result.objective ?? "", result.tokenBudget, runtime.pi, ctx);
386
391
  return;
387
392
  }
388
393
  },
@@ -394,21 +399,21 @@ export default function goal(pi: ExtensionAPI) {
394
399
  clearGoalRecovery();
395
400
  clearBudgetWrapUp();
396
401
  clearStaleGoalToolCallBlock();
397
- activeGoal = loadGoalFromSession(ctx);
398
- if (activeGoal) {
399
- if (activeGoal.status === "active") {
400
- updateGoalUsage(activeGoal, ctx);
401
- if (limitActiveGoalForBudget(pi, ctx, false)) return;
402
+ runtime.activeGoal = loadGoalFromSession(ctx);
403
+ if (runtime.activeGoal) {
404
+ if (runtime.activeGoal.status === "active") {
405
+ updateGoalUsage(runtime.activeGoal, ctx);
406
+ if (limitActiveGoalForBudget(ctx, false)) return;
402
407
  }
403
- persistGoal(activeGoal);
404
- updateStatus(ctx, activeGoal);
408
+ persistGoal(runtime.activeGoal);
409
+ updateStatus(ctx, runtime.activeGoal);
405
410
  } else ctx.ui.setStatus(STATUS_KEY, undefined);
406
411
  });
407
412
 
408
413
  pi.on("session_shutdown", (_event, ctx) => {
409
- if (activeGoal) {
410
- updateGoalUsage(activeGoal, ctx, false);
411
- persistGoal(activeGoal);
414
+ if (runtime.activeGoal) {
415
+ updateGoalUsage(runtime.activeGoal, ctx, false);
416
+ persistGoal(runtime.activeGoal);
412
417
  }
413
418
  clearContinuationTracking();
414
419
  clearGoalRecovery();
@@ -419,39 +424,39 @@ export default function goal(pi: ExtensionAPI) {
419
424
  });
420
425
 
421
426
  pi.on("session_before_compact", (event, ctx) => {
422
- if (activeGoal?.status === "budget_limited") {
427
+ if (runtime.activeGoal?.status === "budget_limited") {
423
428
  if ((event as { willRetry?: boolean }).willRetry === true) return { cancel: true as const };
424
429
  return;
425
430
  }
426
- if (!activeGoal || activeGoal.status !== "active") return;
427
- updateGoalUsage(activeGoal, ctx);
431
+ if (runtime.activeGoal?.status !== "active") return;
432
+ updateGoalUsage(runtime.activeGoal, ctx);
428
433
  cancelContinuationWork();
429
- persistGoal(activeGoal);
430
- updateStatus(ctx, activeGoal);
431
- if (limitActiveGoalForBudget(pi, ctx, false)) return { cancel: true as const };
434
+ persistGoal(runtime.activeGoal);
435
+ updateStatus(ctx, runtime.activeGoal);
436
+ if (limitActiveGoalForBudget(ctx, false)) return { cancel: true as const };
432
437
  });
433
438
 
434
439
  pi.on("session_compact", (event, ctx) => {
435
- if (!activeGoal || activeGoal.status !== "active") {
440
+ if (runtime.activeGoal?.status !== "active") {
436
441
  clearGoalRecovery();
437
442
  return;
438
443
  }
439
444
 
440
445
  const restoredGoal = loadGoalFromSession(ctx);
441
- if (restoredGoal?.id === activeGoal.id) activeGoal = restoredGoal;
442
- updateGoalUsage(activeGoal, ctx);
443
- persistGoal(activeGoal);
444
- updateStatus(ctx, activeGoal);
445
- if (limitActiveGoalForBudget(pi, ctx, false)) return;
446
-
447
- const wasPiRetry = isPiOwnedCompactionRetry(event, activeGoal.id);
448
- clearGoalRecoveryForGoal(activeGoal.id);
446
+ if (restoredGoal?.id === runtime.activeGoal.id) runtime.activeGoal = restoredGoal;
447
+ updateGoalUsage(runtime.activeGoal, ctx);
448
+ persistGoal(runtime.activeGoal);
449
+ updateStatus(ctx, runtime.activeGoal);
450
+ if (limitActiveGoalForBudget(ctx, false)) return;
451
+
452
+ const wasPiRetry = isPiOwnedCompactionRetry(event, runtime.activeGoal.id);
453
+ clearGoalRecoveryForGoal(runtime.activeGoal.id);
449
454
  if (wasPiRetry) return;
450
- requestContinuation(activeGoal);
455
+ requestContinuation(runtime.activeGoal);
451
456
  // Manual compaction does not emit agent_settled. This common dispatcher is
452
457
  // therefore the narrow fallback; threshold compaction leaves the intent for
453
458
  // agent_settled when Pi is still busy.
454
- dispatchContinuationIfSettled(pi, ctx);
459
+ dispatchContinuationIfSettled(ctx);
455
460
  });
456
461
 
457
462
  pi.on("input", (event) => {
@@ -472,8 +477,8 @@ export default function goal(pi: ExtensionAPI) {
472
477
 
473
478
  pi.on("tool_call", (event, ctx) => {
474
479
  if (
475
- activeGoal?.status === "budget_limited" &&
476
- budgetWrapUp?.goalId === activeGoal.id &&
480
+ runtime.activeGoal?.status === "budget_limited" &&
481
+ runtime.budgetWrapUp?.goalId === runtime.activeGoal.id &&
477
482
  event.toolName !== "goal_complete"
478
483
  ) {
479
484
  // A blocked tool result would normally trigger another model call. Abort the
@@ -484,8 +489,8 @@ export default function goal(pi: ExtensionAPI) {
484
489
  reason: "Goal token budget is exhausted; only goal_complete is allowed during wrap-up.",
485
490
  };
486
491
  }
487
- if (!staleGoalToolCallsBlocked) return;
488
- if (!activeGoal || !blocksStaleGoalToolCalls(activeGoal.status)) {
492
+ if (!runtime.staleGoalToolCallsBlocked) return;
493
+ if (!runtime.activeGoal || !blocksStaleGoalToolCalls(runtime.activeGoal.status)) {
489
494
  clearStaleGoalToolCallBlock();
490
495
  return;
491
496
  }
@@ -497,72 +502,75 @@ export default function goal(pi: ExtensionAPI) {
497
502
 
498
503
  pi.on("tool_execution_end", (_event, ctx) => {
499
504
  if (
500
- activeGoal?.status === "budget_limited" &&
501
- budgetWrapUp?.goalId === activeGoal.id &&
502
- !budgetWrapUp.delivered
505
+ runtime.activeGoal?.status === "budget_limited" &&
506
+ runtime.budgetWrapUp?.goalId === runtime.activeGoal.id &&
507
+ !runtime.budgetWrapUp.delivered
503
508
  ) {
504
- queueBudgetWrapUp(pi, ctx, activeGoal);
509
+ queueBudgetWrapUp(ctx, runtime.activeGoal);
505
510
  return;
506
511
  }
507
- if (!activeGoal || activeGoal.status !== "active") return;
512
+ if (runtime.activeGoal?.status !== "active") return;
508
513
 
509
514
  // AgentSession persists assistant message_end before tool execution events,
510
515
  // so the completed assistant call's usage is authoritative at this boundary.
511
- updateGoalUsage(activeGoal, ctx);
512
- persistGoal(activeGoal);
513
- updateStatus(ctx, activeGoal);
514
- limitActiveGoalForBudget(pi, ctx, true);
516
+ updateGoalUsage(runtime.activeGoal, ctx);
517
+ persistGoal(runtime.activeGoal);
518
+ updateStatus(ctx, runtime.activeGoal);
519
+ limitActiveGoalForBudget(ctx, true);
515
520
  });
516
521
 
517
522
  pi.on("before_agent_start", (event) => {
518
523
  markContinuationStarted(event.prompt);
519
- if (!activeGoal || activeGoal.status !== "active") return;
524
+ if (runtime.activeGoal?.status !== "active") return;
520
525
 
521
526
  return {
522
- systemPrompt: `${event.systemPrompt}\n\n${buildGoalSystemPrompt(activeGoal)}`,
527
+ systemPrompt: `${event.systemPrompt}\n\n${buildGoalSystemPrompt(runtime.activeGoal)}`,
523
528
  };
524
529
  });
525
530
 
526
531
  pi.on("agent_end", (event, ctx) => {
527
- if (!activeGoal) return;
528
- if (activeGoal.status === "budget_limited" && budgetWrapUp?.goalId === activeGoal.id) {
529
- updateGoalUsage(activeGoal, ctx);
530
- persistGoal(activeGoal);
531
- updateStatus(ctx, activeGoal);
532
+ if (!runtime.activeGoal) return;
533
+ if (
534
+ runtime.activeGoal.status === "budget_limited" &&
535
+ runtime.budgetWrapUp?.goalId === runtime.activeGoal.id
536
+ ) {
537
+ updateGoalUsage(runtime.activeGoal, ctx);
538
+ persistGoal(runtime.activeGoal);
539
+ updateStatus(ctx, runtime.activeGoal);
532
540
  clearBudgetWrapUp();
533
541
  return;
534
542
  }
535
- if (activeGoal.status !== "active") return;
543
+ if (runtime.activeGoal.status !== "active") return;
536
544
 
537
- const goalId = activeGoal.id;
545
+ const goalId = runtime.activeGoal.id;
538
546
  const alreadyAwaitingContinuation = hasContinuationWorkForGoal(goalId);
539
547
  const finalAssistant = findFinalAssistantMessage(event.messages);
540
548
 
541
- if (!alreadyAwaitingContinuation) activeGoal = incrementGoal(activeGoal);
542
- updateGoalUsage(activeGoal, ctx);
549
+ if (!alreadyAwaitingContinuation) runtime.activeGoal = incrementGoal(runtime.activeGoal);
550
+ updateGoalUsage(runtime.activeGoal, ctx);
543
551
 
544
552
  if (finalAssistant?.stopReason === "aborted") {
545
553
  clearGoalRecoveryForGoal(goalId);
546
- stopGoalAfterAgentEnd(ctx, activeGoal, finalAssistant, "paused");
554
+ stopGoalAfterAgentEnd(ctx, runtime.activeGoal, finalAssistant, "paused");
547
555
  return;
548
556
  }
549
557
 
550
558
  if (finalAssistant?.stopReason === "error") {
551
559
  if (isRetryableGoalInterruption(finalAssistant)) {
552
- if (limitActiveGoalForBudget(pi, ctx, false)) return;
553
- goalRecovery = {
560
+ if (limitActiveGoalForBudget(ctx, false)) return;
561
+ runtime.goalRecovery = {
554
562
  goalId,
555
563
  kind: isGoalContextOverflow(finalAssistant) ? "compaction_retry" : "provider_retry",
556
564
  };
557
565
  cancelContinuationWork();
558
- persistGoal(activeGoal);
559
- updateStatus(ctx, activeGoal);
566
+ persistGoal(runtime.activeGoal);
567
+ updateStatus(ctx, runtime.activeGoal);
560
568
  return;
561
569
  }
562
570
  clearGoalRecoveryForGoal(goalId);
563
571
  stopGoalAfterAgentEnd(
564
572
  ctx,
565
- activeGoal,
573
+ runtime.activeGoal,
566
574
  finalAssistant,
567
575
  isUsageLimitedGoalInterruption(finalAssistant) ? "usage_limited" : "blocked",
568
576
  );
@@ -571,237 +579,512 @@ export default function goal(pi: ExtensionAPI) {
571
579
 
572
580
  clearGoalRecoveryForGoal(goalId);
573
581
 
574
- if (limitActiveGoalForBudget(pi, ctx, false)) return;
582
+ if (limitActiveGoalForBudget(ctx, false)) return;
575
583
 
576
- persistGoal(activeGoal);
577
- updateStatus(ctx, activeGoal);
584
+ persistGoal(runtime.activeGoal);
585
+ updateStatus(ctx, runtime.activeGoal);
578
586
 
579
- const currentGoal = activeGoal;
587
+ const currentGoal = runtime.activeGoal;
580
588
  if (!currentGoal || currentGoal.id !== goalId || currentGoal.status !== "active") return;
581
589
  requestContinuation(currentGoal);
582
590
  });
583
591
 
584
592
  pi.on("agent_settled", (_event, ctx) => {
585
- dispatchContinuationIfSettled(pi, ctx);
593
+ dispatchContinuationIfSettled(ctx);
586
594
  });
587
- }
588
595
 
589
- async function startGoal(
590
- objective: string,
591
- tokenBudget: number | undefined,
592
- pi: ExtensionAPI,
593
- ctx: StatusContext,
594
- ) {
595
- const validationError = validateObjective(objective);
596
- if (validationError) {
597
- ctx.ui.notify(validationError, "warning");
598
- return;
599
- }
596
+ async function startGoal(
597
+ objective: string,
598
+ tokenBudget: number | undefined,
599
+ pi: ExtensionAPI,
600
+ ctx: StatusContext,
601
+ ) {
602
+ const validationError = validateObjective(objective);
603
+ if (validationError) {
604
+ ctx.ui.notify(validationError, "warning");
605
+ return;
606
+ }
607
+
608
+ const existingGoal = runtime.activeGoal?.status !== "complete" ? runtime.activeGoal : undefined;
609
+ if (existingGoal) {
610
+ const shouldReplace = await ctx.ui.confirm(
611
+ "Replace goal?",
612
+ `Current goal: ${existingGoal.text}\n\nNew goal: ${objective}`,
613
+ );
614
+ if (!shouldReplace) {
615
+ ctx.ui.notify(`Goal kept: ${existingGoal.text}`, "info");
616
+ return;
617
+ }
618
+ }
600
619
 
601
- const existingGoal = activeGoal?.status !== "complete" ? activeGoal : undefined;
602
- if (existingGoal) {
603
- const shouldReplace = await ctx.ui.confirm(
604
- "Replace goal?",
605
- `Current goal: ${existingGoal.text}\n\nNew goal: ${objective}`,
620
+ cancelContinuationWork();
621
+ clearGoalRecovery();
622
+ clearBudgetWrapUp();
623
+ clearStaleGoalToolCallBlock();
624
+ runtime.activeGoal = createGoal(objective, tokenBudget, currentTokenTotal(ctx));
625
+ persistGoal(runtime.activeGoal);
626
+ updateStatus(ctx, runtime.activeGoal);
627
+ const startedGoal = runtime.activeGoal;
628
+ const sent = await sendGoalPrompt(pi, ctx, startedGoal);
629
+ if (!sent) {
630
+ if (runtime.activeGoal?.id === startedGoal.id) {
631
+ if (existingGoal) {
632
+ updateGoalUsage(existingGoal, ctx);
633
+ if (existingGoal.status === "active") {
634
+ abortCurrentTurn(ctx);
635
+ runtime.activeGoal = transitionGoal(existingGoal, "paused");
636
+ blockStaleGoalToolCalls();
637
+ } else {
638
+ runtime.activeGoal = existingGoal;
639
+ if (blocksStaleGoalToolCalls(runtime.activeGoal.status)) blockStaleGoalToolCalls();
640
+ else clearStaleGoalToolCallBlock();
641
+ }
642
+ persistGoal(runtime.activeGoal);
643
+ updateStatus(ctx, runtime.activeGoal);
644
+ } else {
645
+ clearActiveGoal(ctx);
646
+ }
647
+ }
648
+ return;
649
+ }
650
+ ctx.ui.notify(
651
+ existingGoal ? `Goal replaced: ${objective}` : `Goal started: ${objective}`,
652
+ "info",
606
653
  );
607
- if (!shouldReplace) {
608
- ctx.ui.notify(`Goal kept: ${existingGoal.text}`, "info");
654
+ }
655
+
656
+ function pauseGoal(ctx: StatusContext) {
657
+ if (!runtime.activeGoal) {
658
+ ctx.ui.notify("No active goal.", "info");
659
+ return;
660
+ }
661
+ if (runtime.activeGoal.status !== "active") {
662
+ ctx.ui.notify(
663
+ `Goal is ${runtime.activeGoal.status}; only active goals can be paused.`,
664
+ "warning",
665
+ );
609
666
  return;
610
667
  }
668
+ updateGoalUsage(runtime.activeGoal, ctx);
669
+ cancelContinuationWork();
670
+ clearBudgetWrapUp();
671
+ blockStaleGoalToolCalls();
672
+ abortCurrentTurn(ctx);
673
+ runtime.activeGoal = transitionGoal(runtime.activeGoal, "paused");
674
+ persistGoal(runtime.activeGoal);
675
+ updateStatus(ctx, runtime.activeGoal);
676
+ ctx.ui.notify(`Goal paused: ${runtime.activeGoal.text}`, "info");
611
677
  }
612
678
 
613
- cancelContinuationWork();
614
- clearGoalRecovery();
615
- clearBudgetWrapUp();
616
- clearStaleGoalToolCallBlock();
617
- activeGoal = createGoal(objective, tokenBudget, currentTokenTotal(ctx));
618
- persistGoal(activeGoal);
619
- updateStatus(ctx, activeGoal);
620
- const startedGoal = activeGoal;
621
- const sent = await sendGoalPrompt(pi, ctx, startedGoal);
622
- if (!sent) {
623
- if (activeGoal?.id === startedGoal.id) {
624
- if (existingGoal) {
625
- updateGoalUsage(existingGoal, ctx);
626
- if (existingGoal.status === "active") {
627
- abortCurrentTurn(ctx);
628
- activeGoal = transitionGoal(existingGoal, "paused");
629
- blockStaleGoalToolCalls();
630
- } else {
631
- activeGoal = existingGoal;
632
- if (blocksStaleGoalToolCalls(activeGoal.status)) blockStaleGoalToolCalls();
633
- else clearStaleGoalToolCallBlock();
634
- }
635
- persistGoal(activeGoal);
636
- updateStatus(ctx, activeGoal);
637
- } else {
638
- clearActiveGoal(ctx);
679
+ async function resumeGoal(pi: ExtensionAPI, ctx: StatusContext) {
680
+ if (!runtime.activeGoal) {
681
+ ctx.ui.notify("No active goal.", "info");
682
+ return;
683
+ }
684
+ if (!isResumableGoalStatus(runtime.activeGoal.status)) {
685
+ ctx.ui.notify(
686
+ `Goal is ${runtime.activeGoal.status}; only paused, blocked, usage-limited, or budget-limited goals can be resumed.`,
687
+ "warning",
688
+ );
689
+ return;
690
+ }
691
+ if (
692
+ runtime.activeGoal.tokenBudget !== undefined &&
693
+ runtime.activeGoal.tokensUsed >= runtime.activeGoal.tokenBudget
694
+ ) {
695
+ ctx.ui.notify(
696
+ `Goal token budget is still reached: ${formatBudget(runtime.activeGoal)}`,
697
+ "warning",
698
+ );
699
+ return;
700
+ }
701
+ const stoppedGoal = runtime.activeGoal;
702
+ const stoppedStatus = stoppedGoal.status;
703
+ cancelContinuationWork();
704
+ clearGoalRecovery();
705
+ clearBudgetWrapUp();
706
+ clearStaleGoalToolCallBlock();
707
+ runtime.activeGoal = transitionGoal(nextGoalInstance(runtime.activeGoal), "active");
708
+ persistGoal(runtime.activeGoal);
709
+ updateStatus(ctx, runtime.activeGoal);
710
+ if (runtime.activeGoal.status !== "active") {
711
+ ctx.ui.notify(
712
+ `Goal token budget is still reached: ${formatBudget(runtime.activeGoal)}`,
713
+ "warning",
714
+ );
715
+ return;
716
+ }
717
+ const resumedGoal = runtime.activeGoal;
718
+ const sent = await sendResumePrompt(pi, ctx, resumedGoal, stoppedStatus);
719
+ if (!sent) {
720
+ if (runtime.activeGoal?.id === resumedGoal.id && runtime.activeGoal.status === "active") {
721
+ runtime.activeGoal = stoppedGoal;
722
+ persistGoal(runtime.activeGoal);
723
+ updateStatus(ctx, runtime.activeGoal);
724
+ if (blocksStaleGoalToolCalls(runtime.activeGoal.status)) blockStaleGoalToolCalls();
639
725
  }
726
+ return;
640
727
  }
641
- return;
728
+ ctx.ui.notify(
729
+ `Goal resumed from ${stoppedStatusLabel(stoppedStatus)}: ${resumedGoal.text}`,
730
+ "info",
731
+ );
642
732
  }
643
- ctx.ui.notify(existingGoal ? `Goal replaced: ${objective}` : `Goal started: ${objective}`, "info");
644
- }
645
733
 
646
- function pauseGoal(ctx: StatusContext) {
647
- if (!activeGoal) {
648
- ctx.ui.notify("No active goal.", "info");
649
- return;
734
+ function clearGoal(ctx: StatusContext) {
735
+ if (!runtime.activeGoal) {
736
+ ctx.ui.notify("No active goal.", "info");
737
+ cancelContinuationWork();
738
+ clearGoalRecovery();
739
+ clearBudgetWrapUp();
740
+ clearStaleGoalToolCallBlock();
741
+ clearPersistedGoal(ctx.cwd);
742
+ ctx.ui.setStatus(STATUS_KEY, undefined);
743
+ return;
744
+ }
745
+
746
+ const stoppedGoal = runtime.activeGoal.text;
747
+ clearActiveGoal(ctx);
748
+ ctx.ui.notify(`Goal cleared: ${stoppedGoal}`, "warning");
650
749
  }
651
- if (activeGoal.status !== "active") {
652
- ctx.ui.notify(`Goal is ${activeGoal.status}; only active goals can be paused.`, "warning");
653
- return;
750
+
751
+ async function editGoal(
752
+ objective: string,
753
+ tokenBudget: number | undefined,
754
+ pi: ExtensionAPI,
755
+ ctx: StatusContext,
756
+ ) {
757
+ const validationError = validateObjective(objective);
758
+ if (validationError) {
759
+ ctx.ui.notify(validationError, "warning");
760
+ return;
761
+ }
762
+ if (!runtime.activeGoal) {
763
+ ctx.ui.notify("No active goal. Use /goal <objective> to start one.", "warning");
764
+ return;
765
+ }
766
+
767
+ updateGoalUsage(runtime.activeGoal, ctx);
768
+ const previousGoal = { ...runtime.activeGoal };
769
+ cancelContinuationWork();
770
+ clearGoalRecovery();
771
+ clearBudgetWrapUp();
772
+ const previousStatus = runtime.activeGoal.status;
773
+ runtime.activeGoal = transitionGoal(
774
+ {
775
+ ...nextGoalInstance(runtime.activeGoal),
776
+ text: objective,
777
+ tokenBudget: tokenBudget ?? runtime.activeGoal.tokenBudget,
778
+ },
779
+ editedGoalStatus(previousStatus),
780
+ );
781
+ persistGoal(runtime.activeGoal);
782
+ updateStatus(ctx, runtime.activeGoal);
783
+ const editedGoal = runtime.activeGoal;
784
+ if (!editedGoal) return;
785
+ if (editedGoal.status === "active") {
786
+ clearStaleGoalToolCallBlock();
787
+ const sent = await sendObjectiveUpdatedPrompt(pi, ctx, editedGoal);
788
+ if (!sent) {
789
+ if (runtime.activeGoal?.id === editedGoal.id) {
790
+ if (previousStatus === "active") {
791
+ abortCurrentTurn(ctx);
792
+ runtime.activeGoal = transitionGoal(previousGoal, "paused");
793
+ blockStaleGoalToolCalls();
794
+ } else {
795
+ runtime.activeGoal = previousGoal;
796
+ if (blocksStaleGoalToolCalls(runtime.activeGoal.status)) blockStaleGoalToolCalls();
797
+ else clearStaleGoalToolCallBlock();
798
+ }
799
+ persistGoal(runtime.activeGoal);
800
+ updateStatus(ctx, runtime.activeGoal);
801
+ }
802
+ return;
803
+ }
804
+ } else if (blocksStaleGoalToolCalls(editedGoal.status)) {
805
+ blockStaleGoalToolCalls();
806
+ } else {
807
+ clearStaleGoalToolCallBlock();
808
+ }
809
+ ctx.ui.notify(`Goal updated: ${objective}`, "info");
654
810
  }
655
- updateGoalUsage(activeGoal, ctx);
656
- cancelContinuationWork();
657
- clearBudgetWrapUp();
658
- blockStaleGoalToolCalls();
659
- abortCurrentTurn(ctx);
660
- activeGoal = transitionGoal(activeGoal, "paused");
661
- persistGoal(activeGoal);
662
- updateStatus(ctx, activeGoal);
663
- ctx.ui.notify(`Goal paused: ${activeGoal.text}`, "info");
664
- }
665
811
 
666
- async function resumeGoal(pi: ExtensionAPI, ctx: StatusContext) {
667
- if (!activeGoal) {
668
- ctx.ui.notify("No active goal.", "info");
669
- return;
812
+ function showGoal(ctx: StatusContext) {
813
+ if (!runtime.activeGoal) {
814
+ ctx.ui.notify("Usage: /goal <objective>\nNo goal is currently set.", "info");
815
+ ctx.ui.setStatus(STATUS_KEY, undefined);
816
+ return;
817
+ }
818
+ updateGoalUsage(runtime.activeGoal, ctx);
819
+ persistGoal(runtime.activeGoal);
820
+ updateStatus(ctx, runtime.activeGoal);
821
+ ctx.ui.notify(goalSummary(runtime.activeGoal), "info");
670
822
  }
671
- if (!isResumableGoalStatus(activeGoal.status)) {
823
+
824
+ function stopGoalAfterAgentEnd(
825
+ ctx: StatusContext,
826
+ goal: ActiveGoal,
827
+ assistant: AssistantMessageLike,
828
+ status: "paused" | "blocked" | "usage_limited",
829
+ ) {
830
+ cancelContinuationWork();
831
+ clearBudgetWrapUp();
832
+ blockStaleGoalToolCalls();
833
+ abortCurrentTurn(ctx);
834
+ runtime.activeGoal = transitionGoal(goal, status);
835
+ persistGoal(runtime.activeGoal);
836
+ updateStatus(ctx, runtime.activeGoal);
837
+
838
+ const details = assistant.errorMessage
839
+ ? ` (${truncateNotification(assistant.errorMessage)})`
840
+ : "";
841
+ if (status === "paused") {
842
+ ctx.ui.notify(
843
+ `Goal paused after interruption${details}. Run /goal resume to continue.`,
844
+ "warning",
845
+ );
846
+ return;
847
+ }
848
+ if (status === "usage_limited") {
849
+ ctx.ui.notify(
850
+ `Goal stopped after provider usage limit${details}. Run /goal resume when usage is available.`,
851
+ "warning",
852
+ );
853
+ return;
854
+ }
672
855
  ctx.ui.notify(
673
- `Goal is ${activeGoal.status}; only paused, blocked, usage-limited, or budget-limited goals can be resumed.`,
856
+ `Goal blocked after agent error${details}. Resolve the blocker or run /goal resume to retry.`,
674
857
  "warning",
675
858
  );
676
- return;
677
859
  }
678
- if (
679
- activeGoal.tokenBudget !== undefined &&
680
- activeGoal.tokensUsed >= activeGoal.tokenBudget
681
- ) {
682
- ctx.ui.notify(`Goal token budget is still reached: ${formatBudget(activeGoal)}`, "warning");
683
- return;
860
+
861
+ function requestContinuation(goal: ActiveGoal) {
862
+ if (hasContinuationWorkForGoal(goal.id)) return false;
863
+ const marker = continuationMarker(goal);
864
+ runtime.continuationIntent = {
865
+ goalId: goal.id,
866
+ iteration: goal.iteration,
867
+ marker,
868
+ prompt: buildContinuePrompt(goal, marker),
869
+ };
870
+ return true;
684
871
  }
685
- const stoppedGoal = activeGoal;
686
- const stoppedStatus = stoppedGoal.status;
687
- cancelContinuationWork();
688
- clearGoalRecovery();
689
- clearBudgetWrapUp();
690
- clearStaleGoalToolCallBlock();
691
- activeGoal = transitionGoal(nextGoalInstance(activeGoal), "active");
692
- persistGoal(activeGoal);
693
- updateStatus(ctx, activeGoal);
694
- if (activeGoal.status !== "active") {
695
- ctx.ui.notify(`Goal token budget is still reached: ${formatBudget(activeGoal)}`, "warning");
696
- return;
872
+
873
+ function dispatchContinuationIfSettled(ctx: StatusContext) {
874
+ const intent = runtime.continuationIntent;
875
+ if (!intent) return false;
876
+ if (
877
+ !runtime.activeGoal ||
878
+ runtime.activeGoal.id !== intent.goalId ||
879
+ runtime.activeGoal.status !== "active"
880
+ ) {
881
+ runtime.continuationIntent = undefined;
882
+ return false;
883
+ }
884
+ if (ctx.isIdle?.() !== true || hasPendingMessages(ctx)) return false;
885
+
886
+ runtime.continuationIntent = undefined;
887
+ runtime.continuationDelivery = intent;
888
+ try {
889
+ runtime.pi.sendUserMessage(intent.prompt);
890
+ return true;
891
+ } catch (error) {
892
+ if (runtime.continuationDelivery?.marker === intent.marker)
893
+ runtime.continuationDelivery = undefined;
894
+ if (runtime.activeGoal?.id === intent.goalId && runtime.activeGoal.status === "active") {
895
+ runtime.continuationIntent = intent;
896
+ }
897
+ ctx.ui.notify(`Goal prompt failed: ${formatError(error)}`, "error");
898
+ return false;
899
+ }
697
900
  }
698
- const resumedGoal = activeGoal;
699
- const sent = await sendResumePrompt(pi, ctx, resumedGoal, stoppedStatus);
700
- if (!sent) {
701
- if (activeGoal?.id === resumedGoal.id && activeGoal.status === "active") {
702
- activeGoal = stoppedGoal;
703
- persistGoal(activeGoal);
704
- updateStatus(ctx, activeGoal);
705
- if (blocksStaleGoalToolCalls(activeGoal.status)) blockStaleGoalToolCalls();
901
+
902
+ function hasContinuationWorkForGoal(goalId: string) {
903
+ return (
904
+ runtime.continuationIntent?.goalId === goalId ||
905
+ runtime.continuationDelivery?.goalId === goalId
906
+ );
907
+ }
908
+
909
+ function updateStatus(ctx: StatusContext, goal: ActiveGoal) {
910
+ clearCompletionStatusTimer();
911
+ ctx.ui.setStatus(STATUS_KEY, formatStatus(goal));
912
+ }
913
+
914
+ function blockStaleGoalToolCalls() {
915
+ runtime.staleGoalToolCallsBlocked = true;
916
+ }
917
+
918
+ function clearStaleGoalToolCallBlock() {
919
+ runtime.staleGoalToolCallsBlocked = false;
920
+ }
921
+
922
+ function clearGoalRecovery() {
923
+ runtime.goalRecovery = undefined;
924
+ }
925
+
926
+ function clearBudgetWrapUp() {
927
+ runtime.budgetWrapUp = undefined;
928
+ }
929
+
930
+ function keepBudgetWrapUpMessage(message: unknown) {
931
+ if (!message || typeof message !== "object") return true;
932
+ const candidate = message as {
933
+ role?: unknown;
934
+ customType?: unknown;
935
+ details?: { goalId?: unknown };
936
+ };
937
+ if (candidate.role !== "custom" || candidate.customType !== BUDGET_WRAP_UP_MESSAGE_TYPE) {
938
+ return true;
706
939
  }
707
- return;
940
+ return (
941
+ typeof candidate.details?.goalId === "string" &&
942
+ candidate.details.goalId === runtime.budgetWrapUp?.goalId &&
943
+ candidate.details.goalId === runtime.activeGoal?.id
944
+ );
708
945
  }
709
- ctx.ui.notify(
710
- `Goal resumed from ${stoppedStatusLabel(stoppedStatus)}: ${resumedGoal.text}`,
711
- "info",
712
- );
713
- }
714
946
 
715
- function clearGoal(ctx: StatusContext) {
716
- if (!activeGoal) {
717
- ctx.ui.notify("No active goal.", "info");
947
+ function queueBudgetWrapUp(ctx: StatusContext, goal: ActiveGoal) {
948
+ if (!runtime.budgetWrapUp || runtime.budgetWrapUp.goalId !== goal.id) {
949
+ runtime.budgetWrapUp = { goalId: goal.id, delivered: false };
950
+ }
951
+ if (runtime.budgetWrapUp.delivered) return true;
952
+ runtime.budgetWrapUp.delivered = true;
953
+ try {
954
+ runtime.pi.sendMessage(
955
+ {
956
+ customType: BUDGET_WRAP_UP_MESSAGE_TYPE,
957
+ content: BUDGET_WRAP_UP_PROMPT,
958
+ display: true,
959
+ details: { goalId: goal.id },
960
+ },
961
+ { deliverAs: "steer" },
962
+ );
963
+ return true;
964
+ } catch (error) {
965
+ runtime.budgetWrapUp.delivered = false;
966
+ ctx.ui.notify(`Goal budget wrap-up failed: ${formatError(error)}`, "error");
967
+ return false;
968
+ }
969
+ }
970
+
971
+ function limitActiveGoalForBudget(ctx: StatusContext, sendWrapUp: boolean) {
972
+ const goal = runtime.activeGoal;
973
+ if (
974
+ goal?.status !== "active" ||
975
+ goal.tokenBudget === undefined ||
976
+ goal.tokensUsed < goal.tokenBudget
977
+ ) {
978
+ return false;
979
+ }
980
+
718
981
  cancelContinuationWork();
719
- clearGoalRecovery();
982
+ clearGoalRecoveryForGoal(goal.id);
720
983
  clearBudgetWrapUp();
721
- clearStaleGoalToolCallBlock();
722
- clearPersistedGoal(ctx.cwd);
723
- ctx.ui.setStatus(STATUS_KEY, undefined);
724
- return;
984
+ runtime.activeGoal = transitionGoal(goal, "budget_limited");
985
+ persistGoal(runtime.activeGoal);
986
+ updateStatus(ctx, runtime.activeGoal);
987
+ ctx.ui.notify(`Goal token budget reached: ${formatBudget(runtime.activeGoal)}`, "warning");
988
+ if (sendWrapUp) queueBudgetWrapUp(ctx, runtime.activeGoal);
989
+ return true;
725
990
  }
726
991
 
727
- const stoppedGoal = activeGoal.text;
728
- clearActiveGoal(ctx);
729
- ctx.ui.notify(`Goal cleared: ${stoppedGoal}`, "warning");
730
- }
992
+ function clearGoalRecoveryForGoal(goalId: string) {
993
+ if (runtime.goalRecovery?.goalId === goalId) runtime.goalRecovery = undefined;
994
+ }
731
995
 
732
- async function editGoal(
733
- objective: string,
734
- tokenBudget: number | undefined,
735
- pi: ExtensionAPI,
736
- ctx: StatusContext,
737
- ) {
738
- const validationError = validateObjective(objective);
739
- if (validationError) {
740
- ctx.ui.notify(validationError, "warning");
741
- return;
996
+ function isPiOwnedCompactionRetry(event: unknown, goalId: string) {
997
+ const compaction = event as { reason?: unknown; willRetry?: unknown };
998
+ if (compaction.willRetry === true) return true;
999
+ return (
1000
+ runtime.goalRecovery?.goalId === goalId &&
1001
+ runtime.goalRecovery.kind === "compaction_retry" &&
1002
+ (compaction.reason === undefined || compaction.reason === "overflow")
1003
+ );
742
1004
  }
743
- if (!activeGoal) {
744
- ctx.ui.notify("No active goal. Use /goal <objective> to start one.", "warning");
745
- return;
1005
+
1006
+ function clearContinuationTracking() {
1007
+ runtime.continuationIntent = undefined;
1008
+ runtime.continuationDelivery = undefined;
1009
+ runtime.cancelledContinuationMarkers.clear();
746
1010
  }
747
1011
 
748
- updateGoalUsage(activeGoal, ctx);
749
- const previousGoal = { ...activeGoal };
750
- cancelContinuationWork();
751
- clearGoalRecovery();
752
- clearBudgetWrapUp();
753
- const previousStatus = activeGoal.status;
754
- activeGoal = transitionGoal(
755
- {
756
- ...nextGoalInstance(activeGoal),
757
- text: objective,
758
- tokenBudget: tokenBudget ?? activeGoal.tokenBudget,
759
- },
760
- editedGoalStatus(previousStatus),
761
- );
762
- persistGoal(activeGoal);
763
- updateStatus(ctx, activeGoal);
764
- if (activeGoal.status === "active") {
765
- clearStaleGoalToolCallBlock();
766
- const editedGoal = activeGoal;
767
- const sent = await sendObjectiveUpdatedPrompt(pi, ctx, editedGoal);
768
- if (!sent) {
769
- if (activeGoal?.id === editedGoal.id) {
770
- if (previousStatus === "active") {
771
- abortCurrentTurn(ctx);
772
- activeGoal = transitionGoal(previousGoal, "paused");
773
- blockStaleGoalToolCalls();
774
- } else {
775
- activeGoal = previousGoal;
776
- if (blocksStaleGoalToolCalls(activeGoal.status)) blockStaleGoalToolCalls();
777
- else clearStaleGoalToolCallBlock();
778
- }
779
- persistGoal(activeGoal);
780
- updateStatus(ctx, activeGoal);
781
- }
1012
+ function cancelContinuationWork() {
1013
+ if (runtime.continuationDelivery)
1014
+ rememberCancelledContinuationMarker(runtime.continuationDelivery.marker);
1015
+ runtime.continuationIntent = undefined;
1016
+ runtime.continuationDelivery = undefined;
1017
+ }
1018
+
1019
+ function rememberCancelledContinuationMarker(marker: string) {
1020
+ runtime.cancelledContinuationMarkers.add(marker);
1021
+ if (runtime.cancelledContinuationMarkers.size <= MAX_CANCELLED_CONTINUATION_PROMPTS) return;
1022
+ const oldest = runtime.cancelledContinuationMarkers.values().next().value;
1023
+ if (oldest) runtime.cancelledContinuationMarkers.delete(oldest);
1024
+ }
1025
+
1026
+ function consumeCancelledContinuationPrompt(prompt: string) {
1027
+ const marker = extractContinuationMarker(prompt);
1028
+ return marker ? runtime.cancelledContinuationMarkers.delete(marker) : false;
1029
+ }
1030
+
1031
+ function markContinuationStarted(prompt: string) {
1032
+ const marker = extractContinuationMarker(prompt);
1033
+ if (!marker) {
1034
+ // A user, retry, or another extension started newer work. Cancel both an
1035
+ // unsent intent and a delivery that may have lost the non-atomic idle race;
1036
+ // the newer work's agent_end will record a fresh intent.
1037
+ cancelContinuationWork();
782
1038
  return;
783
1039
  }
784
- } else if (blocksStaleGoalToolCalls(activeGoal.status)) {
785
- blockStaleGoalToolCalls();
786
- } else {
787
- clearStaleGoalToolCallBlock();
1040
+ if (runtime.continuationDelivery?.marker === marker) runtime.continuationDelivery = undefined;
1041
+ }
1042
+
1043
+ function persistGoal(goal: ActiveGoal) {
1044
+ runtime.pi.appendEntry<GoalStateEntryData>(GOAL_STATE_ENTRY_TYPE, { goal });
788
1045
  }
789
- ctx.ui.notify(`Goal updated: ${objective}`, "info");
790
- }
791
1046
 
792
- function showGoal(ctx: StatusContext) {
793
- if (!activeGoal) {
794
- ctx.ui.notify("Usage: /goal <objective>\nNo goal is currently set.", "info");
1047
+ function clearPersistedGoal(cwd: string) {
1048
+ runtime.pi.appendEntry<GoalStateEntryData>(GOAL_STATE_ENTRY_TYPE, { goal: null });
1049
+ clearLegacyPersistedGoal(cwd);
1050
+ }
1051
+
1052
+ function clearActiveGoal(ctx: StatusContext) {
1053
+ cancelContinuationWork();
1054
+ clearGoalRecovery();
1055
+ clearBudgetWrapUp();
1056
+ clearStaleGoalToolCallBlock();
1057
+ runtime.activeGoal = undefined;
1058
+ clearPersistedGoal(ctx.cwd);
795
1059
  ctx.ui.setStatus(STATUS_KEY, undefined);
796
- return;
797
1060
  }
798
- updateGoalUsage(activeGoal, ctx);
799
- persistGoal(activeGoal);
800
- updateStatus(ctx, activeGoal);
801
- ctx.ui.notify(goalSummary(activeGoal), "info");
1061
+
1062
+ function showCompletionStatus(ctx: StatusContext) {
1063
+ clearCompletionStatusTimer();
1064
+ ctx.ui.setStatus(STATUS_KEY, "complete");
1065
+ runtime.completionStatusTimer = setTimeout(() => {
1066
+ runtime.completionStatusTimer = undefined;
1067
+ try {
1068
+ ctx.ui.setStatus(STATUS_KEY, undefined);
1069
+ } catch {
1070
+ // The completion status is best-effort; the captured ctx may be stale after
1071
+ // session replacement or reload before this timer fires.
1072
+ }
1073
+ }, 8_000);
1074
+ }
1075
+
1076
+ function clearCompletionStatusTimer() {
1077
+ if (!runtime.completionStatusTimer) return;
1078
+ clearTimeout(runtime.completionStatusTimer);
1079
+ runtime.completionStatusTimer = undefined;
1080
+ }
802
1081
  }
803
1082
 
804
- function createGoal(text: string, tokenBudget: number | undefined, baselineTokens: number): ActiveGoal {
1083
+ function createGoal(
1084
+ text: string,
1085
+ tokenBudget: number | undefined,
1086
+ baselineTokens: number,
1087
+ ): ActiveGoal {
805
1088
  const now = Date.now();
806
1089
  return {
807
1090
  id: randomUUID(),
@@ -844,38 +1127,6 @@ function incrementGoal(goal: ActiveGoal): ActiveGoal {
844
1127
  return { ...goal, iteration: goal.iteration + 1, updatedAt: Date.now() };
845
1128
  }
846
1129
 
847
- function stopGoalAfterAgentEnd(
848
- ctx: StatusContext,
849
- goal: ActiveGoal,
850
- assistant: AssistantMessageLike,
851
- status: "paused" | "blocked" | "usage_limited",
852
- ) {
853
- cancelContinuationWork();
854
- clearBudgetWrapUp();
855
- blockStaleGoalToolCalls();
856
- abortCurrentTurn(ctx);
857
- activeGoal = transitionGoal(goal, status);
858
- persistGoal(activeGoal);
859
- updateStatus(ctx, activeGoal);
860
-
861
- const details = assistant.errorMessage ? ` (${truncateNotification(assistant.errorMessage)})` : "";
862
- if (status === "paused") {
863
- ctx.ui.notify(`Goal paused after interruption${details}. Run /goal resume to continue.`, "warning");
864
- return;
865
- }
866
- if (status === "usage_limited") {
867
- ctx.ui.notify(
868
- `Goal stopped after provider usage limit${details}. Run /goal resume when usage is available.`,
869
- "warning",
870
- );
871
- return;
872
- }
873
- ctx.ui.notify(
874
- `Goal blocked after agent error${details}. Resolve the blocker or run /goal resume to retry.`,
875
- "warning",
876
- );
877
- }
878
-
879
1130
  async function sendGoalPrompt(pi: ExtensionAPI, ctx: StatusContext, goal: ActiveGoal) {
880
1131
  return sendPrompt(pi, ctx, buildGoalPrompt(goal));
881
1132
  }
@@ -893,46 +1144,6 @@ async function sendResumePrompt(
893
1144
  return sendPrompt(pi, ctx, buildResumePrompt(goal, stoppedStatus));
894
1145
  }
895
1146
 
896
- function requestContinuation(goal: ActiveGoal) {
897
- if (hasContinuationWorkForGoal(goal.id)) return false;
898
- const marker = continuationMarker(goal);
899
- continuationIntent = {
900
- goalId: goal.id,
901
- iteration: goal.iteration,
902
- marker,
903
- prompt: buildContinuePrompt(goal, marker),
904
- };
905
- return true;
906
- }
907
-
908
- function dispatchContinuationIfSettled(pi: ExtensionAPI, ctx: StatusContext) {
909
- const intent = continuationIntent;
910
- if (!intent) return false;
911
- if (!activeGoal || activeGoal.id !== intent.goalId || activeGoal.status !== "active") {
912
- continuationIntent = undefined;
913
- return false;
914
- }
915
- if (ctx.isIdle?.() !== true || hasPendingMessages(ctx)) return false;
916
-
917
- continuationIntent = undefined;
918
- continuationDelivery = intent;
919
- try {
920
- pi.sendUserMessage(intent.prompt);
921
- return true;
922
- } catch (error) {
923
- if (continuationDelivery?.marker === intent.marker) continuationDelivery = undefined;
924
- if (activeGoal?.id === intent.goalId && activeGoal.status === "active") {
925
- continuationIntent = intent;
926
- }
927
- ctx.ui.notify(`Goal prompt failed: ${formatError(error)}`, "error");
928
- return false;
929
- }
930
- }
931
-
932
- function hasContinuationWorkForGoal(goalId: string) {
933
- return continuationIntent?.goalId === goalId || continuationDelivery?.goalId === goalId;
934
- }
935
-
936
1147
  async function sendPrompt(pi: ExtensionAPI, ctx: StatusContext, prompt: string) {
937
1148
  try {
938
1149
  const sent = ctx.isIdle?.()
@@ -946,11 +1157,6 @@ async function sendPrompt(pi: ExtensionAPI, ctx: StatusContext, prompt: string)
946
1157
  }
947
1158
  }
948
1159
 
949
- function updateStatus(ctx: StatusContext, goal: ActiveGoal) {
950
- clearCompletionStatusTimer();
951
- ctx.ui.setStatus(STATUS_KEY, formatStatus(goal));
952
- }
953
-
954
1160
  export function formatStatus(goal: ActiveGoal | undefined) {
955
1161
  if (!goal) return undefined;
956
1162
  if (goal.status === "complete") return "complete";
@@ -997,10 +1203,6 @@ function abortCurrentTurn(ctx: StatusContext) {
997
1203
  }
998
1204
  }
999
1205
 
1000
- function blockStaleGoalToolCalls() {
1001
- staleGoalToolCallsBlocked = true;
1002
- }
1003
-
1004
1206
  function blocksStaleGoalToolCalls(status: GoalStatus) {
1005
1207
  return status === "paused" || status === "blocked" || status === "usage_limited";
1006
1208
  }
@@ -1015,95 +1217,6 @@ function stoppedStatusLabel(status: GoalStatus) {
1015
1217
  return status;
1016
1218
  }
1017
1219
 
1018
- function clearStaleGoalToolCallBlock() {
1019
- staleGoalToolCallsBlocked = false;
1020
- }
1021
-
1022
- function clearGoalRecovery() {
1023
- goalRecovery = undefined;
1024
- }
1025
-
1026
- function clearBudgetWrapUp() {
1027
- budgetWrapUp = undefined;
1028
- }
1029
-
1030
- function keepBudgetWrapUpMessage(message: unknown) {
1031
- if (!message || typeof message !== "object") return true;
1032
- const candidate = message as {
1033
- role?: unknown;
1034
- customType?: unknown;
1035
- details?: { goalId?: unknown };
1036
- };
1037
- if (candidate.role !== "custom" || candidate.customType !== BUDGET_WRAP_UP_MESSAGE_TYPE) {
1038
- return true;
1039
- }
1040
- return (
1041
- typeof candidate.details?.goalId === "string" &&
1042
- candidate.details.goalId === budgetWrapUp?.goalId &&
1043
- candidate.details.goalId === activeGoal?.id
1044
- );
1045
- }
1046
-
1047
- function queueBudgetWrapUp(pi: ExtensionAPI, ctx: StatusContext, goal: ActiveGoal) {
1048
- if (!budgetWrapUp || budgetWrapUp.goalId !== goal.id) {
1049
- budgetWrapUp = { goalId: goal.id, delivered: false };
1050
- }
1051
- if (budgetWrapUp.delivered) return true;
1052
- budgetWrapUp.delivered = true;
1053
- try {
1054
- pi.sendMessage(
1055
- {
1056
- customType: BUDGET_WRAP_UP_MESSAGE_TYPE,
1057
- content: BUDGET_WRAP_UP_PROMPT,
1058
- display: true,
1059
- details: { goalId: goal.id },
1060
- },
1061
- { deliverAs: "steer" },
1062
- );
1063
- return true;
1064
- } catch (error) {
1065
- budgetWrapUp.delivered = false;
1066
- ctx.ui.notify(`Goal budget wrap-up failed: ${formatError(error)}`, "error");
1067
- return false;
1068
- }
1069
- }
1070
-
1071
- function limitActiveGoalForBudget(pi: ExtensionAPI, ctx: StatusContext, sendWrapUp: boolean) {
1072
- const goal = activeGoal;
1073
- if (
1074
- !goal ||
1075
- goal.status !== "active" ||
1076
- goal.tokenBudget === undefined ||
1077
- goal.tokensUsed < goal.tokenBudget
1078
- ) {
1079
- return false;
1080
- }
1081
-
1082
- cancelContinuationWork();
1083
- clearGoalRecoveryForGoal(goal.id);
1084
- clearBudgetWrapUp();
1085
- activeGoal = transitionGoal(goal, "budget_limited");
1086
- persistGoal(activeGoal);
1087
- updateStatus(ctx, activeGoal);
1088
- ctx.ui.notify(`Goal token budget reached: ${formatBudget(activeGoal)}`, "warning");
1089
- if (sendWrapUp) queueBudgetWrapUp(pi, ctx, activeGoal);
1090
- return true;
1091
- }
1092
-
1093
- function clearGoalRecoveryForGoal(goalId: string) {
1094
- if (goalRecovery?.goalId === goalId) goalRecovery = undefined;
1095
- }
1096
-
1097
- function isPiOwnedCompactionRetry(event: unknown, goalId: string) {
1098
- const compaction = event as { reason?: unknown; willRetry?: unknown };
1099
- if (compaction.willRetry === true) return true;
1100
- return (
1101
- goalRecovery?.goalId === goalId &&
1102
- goalRecovery.kind === "compaction_retry" &&
1103
- (compaction.reason === undefined || compaction.reason === "overflow")
1104
- );
1105
- }
1106
-
1107
1220
  export function isContradictoryCompletionSummary(summary: string) {
1108
1221
  return CONTRADICTORY_COMPLETION_PATTERNS.some((pattern) => pattern.test(summary));
1109
1222
  }
@@ -1173,50 +1286,10 @@ function zeroUsage(): Usage {
1173
1286
  };
1174
1287
  }
1175
1288
 
1176
- function clearContinuationTracking() {
1177
- continuationIntent = undefined;
1178
- continuationDelivery = undefined;
1179
- cancelledContinuationMarkers.clear();
1180
- }
1181
-
1182
- function cancelContinuationWork() {
1183
- if (continuationDelivery) rememberCancelledContinuationMarker(continuationDelivery.marker);
1184
- continuationIntent = undefined;
1185
- continuationDelivery = undefined;
1186
- }
1187
-
1188
- function rememberCancelledContinuationMarker(marker: string) {
1189
- cancelledContinuationMarkers.add(marker);
1190
- if (cancelledContinuationMarkers.size <= MAX_CANCELLED_CONTINUATION_PROMPTS) return;
1191
- const oldest = cancelledContinuationMarkers.values().next().value;
1192
- if (oldest) cancelledContinuationMarkers.delete(oldest);
1193
- }
1194
-
1195
- function consumeCancelledContinuationPrompt(prompt: string) {
1196
- const marker = extractContinuationMarker(prompt);
1197
- return marker ? cancelledContinuationMarkers.delete(marker) : false;
1198
- }
1199
-
1200
- function markContinuationStarted(prompt: string) {
1201
- const marker = extractContinuationMarker(prompt);
1202
- if (!marker) {
1203
- // A user, retry, or another extension started newer work. Cancel both an
1204
- // unsent intent and a delivery that may have lost the non-atomic idle race;
1205
- // the newer work's agent_end will record a fresh intent.
1206
- cancelContinuationWork();
1207
- return;
1208
- }
1209
- if (continuationDelivery?.marker === marker) continuationDelivery = undefined;
1210
- }
1211
-
1212
1289
  function continuationMarker(goal: ActiveGoal) {
1213
1290
  return `${goal.id}:${goal.iteration}:${randomUUID()}`;
1214
1291
  }
1215
1292
 
1216
- function continuationMarkerComment(marker: string) {
1217
- return `<!-- ${CONTINUATION_MARKER_PREFIX}${marker} -->`;
1218
- }
1219
-
1220
1293
  function escapeRegExpText(value: string) {
1221
1294
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1222
1295
  }
@@ -1240,7 +1313,8 @@ export function findFinalAssistantMessage(messages: unknown[]): AssistantMessage
1240
1313
  stopReason: isAgentStopReason(candidate.stopReason) ? candidate.stopReason : undefined,
1241
1314
  errorMessage: typeof candidate.errorMessage === "string" ? candidate.errorMessage : undefined,
1242
1315
  };
1243
- if (Array.isArray(candidate.content)) assistant.content = candidate.content as PiAssistantMessage["content"];
1316
+ if (Array.isArray(candidate.content))
1317
+ assistant.content = candidate.content as PiAssistantMessage["content"];
1244
1318
  if (typeof candidate.api === "string") assistant.api = candidate.api;
1245
1319
  if (typeof candidate.provider === "string") assistant.provider = candidate.provider;
1246
1320
  if (typeof candidate.model === "string") assistant.model = candidate.model;
@@ -1276,10 +1350,6 @@ function normalizeUsage(value: unknown): Usage | undefined {
1276
1350
  };
1277
1351
  }
1278
1352
 
1279
- function escapeXmlText(value: string) {
1280
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1281
- }
1282
-
1283
1353
  function formatError(error: unknown) {
1284
1354
  return truncateNotification(error instanceof Error ? error.message : String(error));
1285
1355
  }
@@ -1288,43 +1358,8 @@ function truncateNotification(value: string) {
1288
1358
  return value.length > 160 ? `${value.slice(0, 157)}...` : value;
1289
1359
  }
1290
1360
 
1291
- function persistGoal(goal: ActiveGoal) {
1292
- extensionApi?.appendEntry<GoalStateEntryData>(GOAL_STATE_ENTRY_TYPE, { goal });
1293
- }
1294
-
1295
- function clearPersistedGoal(cwd: string) {
1296
- extensionApi?.appendEntry<GoalStateEntryData>(GOAL_STATE_ENTRY_TYPE, { goal: null });
1297
- clearLegacyPersistedGoal(cwd);
1298
- }
1299
-
1300
- function clearActiveGoal(ctx: StatusContext) {
1301
- cancelContinuationWork();
1302
- clearGoalRecovery();
1303
- clearBudgetWrapUp();
1304
- clearStaleGoalToolCallBlock();
1305
- activeGoal = undefined;
1306
- clearPersistedGoal(ctx.cwd);
1307
- ctx.ui.setStatus(STATUS_KEY, undefined);
1308
- }
1309
-
1310
- function showCompletionStatus(ctx: StatusContext) {
1311
- clearCompletionStatusTimer();
1312
- ctx.ui.setStatus(STATUS_KEY, "complete");
1313
- completionStatusTimer = setTimeout(() => {
1314
- completionStatusTimer = undefined;
1315
- try {
1316
- ctx.ui.setStatus(STATUS_KEY, undefined);
1317
- } catch {
1318
- // The completion status is best-effort; the captured ctx may be stale after
1319
- // session replacement or reload before this timer fires.
1320
- }
1321
- }, 8_000);
1322
- }
1323
-
1324
- function clearCompletionStatusTimer() {
1325
- if (!completionStatusTimer) return;
1326
- clearTimeout(completionStatusTimer);
1327
- completionStatusTimer = undefined;
1361
+ export default function goal(pi: ExtensionAPI) {
1362
+ registerGoalRuntime(pi);
1328
1363
  }
1329
1364
 
1330
1365
  export {
@@ -1333,5 +1368,12 @@ export {
1333
1368
  formatDuration,
1334
1369
  formatTokenCount,
1335
1370
  } from "./accounting.js";
1336
- export { completeGoalArguments, parseCommand, parseTokenBudget, validateObjective } from "./command.js";
1371
+
1372
+ export {
1373
+ completeGoalArguments,
1374
+ parseCommand,
1375
+ parseTokenBudget,
1376
+ validateObjective,
1377
+ } from "./command.js";
1378
+
1337
1379
  export { buildGoalSystemPrompt } from "./prompts.js";