@narumitw/pi-goal 0.12.0 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/goal.ts CHANGED
@@ -1,6 +1,3 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
- import { dirname, join } from "node:path";
3
- import process from "node:process";
4
1
  import { randomUUID } from "node:crypto";
5
2
  import { defineTool, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
3
  import {
@@ -9,22 +6,46 @@ import {
9
6
  type Usage,
10
7
  } from "@earendil-works/pi-ai";
11
8
  import { Type } from "typebox";
9
+ import {
10
+ assistantUsageTokens,
11
+ checkpointGoalActiveTime,
12
+ cumulativeAssistantTokens,
13
+ currentTokenTotal,
14
+ formatDuration,
15
+ formatTokenCount,
16
+ isNonNegativeFiniteNumber,
17
+ nonNegativeFiniteNumber,
18
+ normalizeTokenBudget,
19
+ updateGoalUsage,
20
+ } from "./accounting.js";
21
+ import {
22
+ completeGoalArguments,
23
+ parseCommand,
24
+ parseTokenBudget,
25
+ validateObjective,
26
+ } from "./command.js";
27
+ import {
28
+ type ActiveGoal,
29
+ clearLegacyPersistedGoal,
30
+ type GoalStateEntryData,
31
+ loadGoalFromSession,
32
+ } from "./persistence.js";
33
+ import {
34
+ buildContinuePrompt,
35
+ buildGoalPrompt,
36
+ buildGoalSystemPrompt,
37
+ buildObjectiveUpdatedPrompt,
38
+ buildResumePrompt,
39
+ type GoalStatus,
40
+ } from "./prompts.js";
12
41
 
13
- type GoalStatus = "active" | "paused" | "budget_limited" | "complete";
14
42
  type AgentStopReason = "stop" | "length" | "toolUse" | "error" | "aborted";
15
43
 
16
- interface ActiveGoal {
17
- id: string;
18
- text: string;
19
- status: GoalStatus;
20
- startedAt: number;
21
- updatedAt: number;
22
- iteration: number;
23
- tokenBudget?: number;
24
- tokensUsed: number;
25
- timeUsedSeconds: number;
26
- baselineTokens: number;
27
- }
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.
28
49
 
29
50
  interface GoalCompleteDetails {
30
51
  goal: string;
@@ -32,13 +53,26 @@ interface GoalCompleteDetails {
32
53
  summary: string;
33
54
  }
34
55
 
35
- interface ContinuationPending {
56
+ interface GoalBlockedDetails {
57
+ goal: string;
58
+ goal_id: string;
59
+ reason: string;
60
+ evidence: string;
61
+ repeated_turns: number;
62
+ }
63
+
64
+ interface ContinuationTicket {
36
65
  goalId: string;
37
66
  iteration: number;
38
67
  marker: string;
39
68
  prompt: string;
40
69
  }
41
70
 
71
+ interface BudgetWrapUp {
72
+ goalId: string;
73
+ delivered: boolean;
74
+ }
75
+
42
76
  type GoalRecoveryKind = "provider_retry" | "compaction_retry";
43
77
 
44
78
  interface GoalRecovery {
@@ -58,22 +92,6 @@ interface AssistantMessageLike {
58
92
  timestamp?: number;
59
93
  }
60
94
 
61
- interface GoalStateEntryData {
62
- goal?: ActiveGoal | null;
63
- }
64
-
65
- interface CommandResult {
66
- kind: "show" | "start" | "pause" | "resume" | "clear" | "edit";
67
- objective?: string;
68
- tokenBudget?: number;
69
- }
70
-
71
- interface GoalArgumentCompletion {
72
- value: string;
73
- label: string;
74
- description?: string;
75
- }
76
-
77
95
  interface StatusContext {
78
96
  cwd: string;
79
97
  ui: {
@@ -89,41 +107,42 @@ interface StatusContext {
89
107
 
90
108
  const STATUS_KEY = "goal";
91
109
  const GOAL_STATE_ENTRY_TYPE = "goal-state";
92
- const MAX_OBJECTIVE_LENGTH = 4_000;
110
+ const MAX_BLOCKER_REASON_LENGTH = 1_000;
111
+ const MAX_BLOCKER_EVIDENCE_LENGTH = 4_000;
93
112
  const MAX_CANCELLED_CONTINUATION_PROMPTS = 20;
94
113
  const CONTINUATION_MARKER_PREFIX = "pi-goal-continuation:";
114
+ const BUDGET_WRAP_UP_MESSAGE_TYPE = "goal-budget-wrap-up";
115
+ const BUDGET_WRAP_UP_PROMPT =
116
+ "The active /goal token budget is exhausted. Stop substantive work and do not call substantive tools. Summarize progress, verified results, remaining work, and blockers concisely. Treat completion as unproven. Do not call goal_complete unless authoritative, requirement-by-requirement evidence already proves every requirement is complete. Weak, indirect, or missing evidence is not enough. Budget exhaustion is not completion.";
95
117
  const CONTRADICTORY_COMPLETION_PATTERNS = [
96
118
  /(?<!could\s)\bnot\s+(?:yet\s+)?(?:complete|completed|done|finished)\b/i,
97
119
  /\bstill\s+(?:incomplete|failing|failing\s+tests?|fails?)\b/i,
98
120
  /\btests?\s+(?:still\s+)?fail(?:ing)?\b/i,
99
121
  ] as const;
122
+ const USAGE_LIMIT_GOAL_ERROR_PATTERNS = [
123
+ /usage[_\s-]*(?:limit|cap)|chatgpt.{0,32}usage/i,
124
+ /quota.{0,32}(?:reached|exceeded|exhausted|depleted)|(?:reached|exceeded|exhausted|depleted).{0,32}quota/i,
125
+ /insufficient[_\s-]*(?:quota|credits?)|out of credits|out of budget|available balance|payment required/i,
126
+ /(?:credit|balance).{0,32}(?:low|exhausted|depleted)|billing/i,
127
+ ] as const;
100
128
  const NON_RETRYABLE_GOAL_ERROR_RE =
101
- /usage[_\s-]*limit|chatgpt usage limit|multi-auth rotation failed|credentials tried|unauthori[sz]ed|invalid api key/i;
102
- const RETRYABLE_GOAL_ERROR_RE =
103
- /websocket closed|sse response headers timed out|headers timed out|context[_\s-]*length[_\s-]*exceeded|input exceeds the context window|provider returned error/i;
104
- const GOAL_ARGUMENT_COMPLETIONS: readonly GoalArgumentCompletion[] = [
105
- { value: "pause", label: "pause", description: "Pause the active goal" },
106
- { value: "resume", label: "resume", description: "Resume a paused or budget-limited goal" },
107
- { value: "clear", label: "clear", description: "Clear the current goal" },
108
- { value: "edit", label: "edit", description: "Edit the current goal objective" },
109
- { value: "status", label: "status", description: "Show the current goal" },
110
- { value: "--tokens ", label: "--tokens", description: "Set a token budget before the goal" },
111
- ];
112
- const EDIT_TOKEN_COMPLETION: GoalArgumentCompletion = {
113
- value: "edit --tokens ",
114
- label: "--tokens",
115
- description: "Set a token budget before the updated goal",
116
- };
117
- const STATE_FILE = join(
118
- process.env.PI_CODING_AGENT_DIR ?? join(process.env.HOME ?? ".", ".pi", "agent"),
119
- "pi-goal-state.json",
120
- );
121
-
129
+ /multi-auth rotation failed|credentials tried|unauthori[sz]ed|invalid api key/i;
130
+ // Pi 0.79 does not export its assistant-error retry classifier. Keep this
131
+ // compatibility mirror aligned with Pi's public retry utility in newer versions.
132
+ const RETRYABLE_GOAL_ERROR_PATTERNS = [
133
+ /overloaded|rate.?limit|too many requests|\b(?:429|500|502|503|504)\b|service.?unavailable|server.?error|internal.?error/i,
134
+ /provider.?returned.?error|you can retry your request|try your request again|please retry your request/i,
135
+ /network.?error|connection.?(?:error|refused|lost)|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up/i,
136
+ /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
+ /context[_\s-]*length[_\s-]*exceeded|input exceeds the context window/i,
138
+ ] as const;
122
139
  let activeGoal: ActiveGoal | undefined;
123
140
  let completionStatusTimer: NodeJS.Timeout | undefined;
124
141
  let extensionApi: ExtensionAPI | undefined;
125
- let continuationPending: ContinuationPending | undefined;
142
+ let continuationIntent: ContinuationTicket | undefined;
143
+ let continuationDelivery: ContinuationTicket | undefined;
126
144
  let goalRecovery: GoalRecovery | undefined;
145
+ let budgetWrapUp: BudgetWrapUp | undefined;
127
146
  let staleGoalToolCallsBlocked = false;
128
147
  const cancelledContinuationMarkers = new Set<string>();
129
148
 
@@ -137,7 +156,7 @@ const goalCompleteTool = defineTool({
137
156
  promptGuidelines: [
138
157
  "When a /goal is active, keep working until the goal is complete; do not stop with only a plan or partial progress.",
139
158
  "Before calling goal_complete, audit the active goal requirement by requirement against the current files, command output, tests, or external state.",
140
- "Pass the exact goal_id shown in the current /goal prompt; never reuse a goal_id from an older, paused, replaced, or cleared turn.",
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.",
141
160
  "Call goal_complete only after the requested goal is fully implemented, verified, and no known required work remains; otherwise keep working.",
142
161
  ],
143
162
  parameters: Type.Object({
@@ -166,18 +185,28 @@ const goalCompleteTool = defineTool({
166
185
  };
167
186
  }
168
187
 
188
+ const completingDuringBudgetWrapUp =
189
+ completedGoal.status === "budget_limited" &&
190
+ budgetWrapUp?.goalId === completedGoal.id &&
191
+ budgetWrapUp.delivered;
169
192
  const staleGoalRejection = goalIdRejectionReason(completedGoal, requestedGoalId);
170
193
  if (staleGoalRejection) {
171
194
  const rejection = `Goal completion rejected: ${staleGoalRejection}.`;
172
195
  ctx.ui.notify(rejection, "warning");
196
+ if (completingDuringBudgetWrapUp) {
197
+ updateGoalUsage(completedGoal, ctx);
198
+ persistGoal(completedGoal);
199
+ updateStatus(ctx, completedGoal);
200
+ clearBudgetWrapUp();
201
+ }
173
202
 
174
203
  return {
175
204
  content: [{ type: "text", text: rejection }],
176
205
  details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
206
+ terminate: completingDuringBudgetWrapUp || undefined,
177
207
  };
178
208
  }
179
-
180
- if (completedGoal.status !== "active") {
209
+ if (completedGoal.status !== "active" && !completingDuringBudgetWrapUp) {
181
210
  const rejection = `Goal completion rejected: goal is ${completedGoal.status}, not active.`;
182
211
  ctx.ui.notify(rejection, "warning");
183
212
 
@@ -198,6 +227,7 @@ const goalCompleteTool = defineTool({
198
227
  updateStatus(ctx, completedGoal);
199
228
  const rejection = `Goal completion rejected: ${rejectionReason}.`;
200
229
  ctx.ui.notify(rejection, "warning");
230
+ if (completingDuringBudgetWrapUp) clearBudgetWrapUp();
201
231
 
202
232
  return {
203
233
  content: [
@@ -207,6 +237,7 @@ const goalCompleteTool = defineTool({
207
237
  },
208
238
  ],
209
239
  details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
240
+ terminate: completingDuringBudgetWrapUp || undefined,
210
241
  };
211
242
  }
212
243
 
@@ -227,9 +258,102 @@ const goalCompleteTool = defineTool({
227
258
  },
228
259
  });
229
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
+ return {
305
+ content: [{ type: "text" as const, text: rejection }],
306
+ details: {
307
+ goal,
308
+ 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,
312
+ } satisfies GoalBlockedDetails,
313
+ };
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
+ });
352
+
230
353
  export default function goal(pi: ExtensionAPI) {
231
354
  extensionApi = pi;
232
355
  pi.registerTool(goalCompleteTool);
356
+ pi.registerTool(goalBlockedTool);
233
357
 
234
358
  pi.registerCommand("goal", {
235
359
  description: "Run a goal to completion: /goal [--tokens 100k] <goal_to_complete>",
@@ -268,30 +392,46 @@ export default function goal(pi: ExtensionAPI) {
268
392
  clearCompletionStatusTimer();
269
393
  clearContinuationTracking();
270
394
  clearGoalRecovery();
395
+ clearBudgetWrapUp();
271
396
  clearStaleGoalToolCallBlock();
272
397
  activeGoal = loadGoalFromSession(ctx);
273
- if (activeGoal) updateStatus(ctx, activeGoal);
274
- else ctx.ui.setStatus(STATUS_KEY, undefined);
398
+ if (activeGoal) {
399
+ if (activeGoal.status === "active") {
400
+ updateGoalUsage(activeGoal, ctx);
401
+ if (limitActiveGoalForBudget(pi, ctx, false)) return;
402
+ }
403
+ persistGoal(activeGoal);
404
+ updateStatus(ctx, activeGoal);
405
+ } else ctx.ui.setStatus(STATUS_KEY, undefined);
275
406
  });
276
407
 
277
408
  pi.on("session_shutdown", (_event, ctx) => {
278
- if (activeGoal) persistGoal(activeGoal);
409
+ if (activeGoal) {
410
+ updateGoalUsage(activeGoal, ctx, false);
411
+ persistGoal(activeGoal);
412
+ }
279
413
  clearContinuationTracking();
280
414
  clearGoalRecovery();
415
+ clearBudgetWrapUp();
281
416
  clearStaleGoalToolCallBlock();
282
417
  ctx.ui.setStatus(STATUS_KEY, undefined);
283
418
  clearCompletionStatusTimer();
284
419
  });
285
420
 
286
- pi.on("session_before_compact", (_event, ctx) => {
421
+ pi.on("session_before_compact", (event, ctx) => {
422
+ if (activeGoal?.status === "budget_limited") {
423
+ if ((event as { willRetry?: boolean }).willRetry === true) return { cancel: true as const };
424
+ return;
425
+ }
287
426
  if (!activeGoal || activeGoal.status !== "active") return;
288
427
  updateGoalUsage(activeGoal, ctx);
289
- cancelContinuationPending();
428
+ cancelContinuationWork();
290
429
  persistGoal(activeGoal);
291
430
  updateStatus(ctx, activeGoal);
431
+ if (limitActiveGoalForBudget(pi, ctx, false)) return { cancel: true as const };
292
432
  });
293
433
 
294
- pi.on("session_compact", async (event, ctx) => {
434
+ pi.on("session_compact", (event, ctx) => {
295
435
  if (!activeGoal || activeGoal.status !== "active") {
296
436
  clearGoalRecovery();
297
437
  return;
@@ -302,11 +442,16 @@ export default function goal(pi: ExtensionAPI) {
302
442
  updateGoalUsage(activeGoal, ctx);
303
443
  persistGoal(activeGoal);
304
444
  updateStatus(ctx, activeGoal);
445
+ if (limitActiveGoalForBudget(pi, ctx, false)) return;
305
446
 
306
447
  const wasPiRetry = isPiOwnedCompactionRetry(event, activeGoal.id);
307
448
  clearGoalRecoveryForGoal(activeGoal.id);
308
- if (wasPiRetry || hasPendingMessages(ctx)) return;
309
- await sendContinuationPrompt(pi, ctx, activeGoal);
449
+ if (wasPiRetry) return;
450
+ requestContinuation(activeGoal);
451
+ // Manual compaction does not emit agent_settled. This common dispatcher is
452
+ // therefore the narrow fallback; threshold compaction leaves the intent for
453
+ // agent_settled when Pi is still busy.
454
+ dispatchContinuationIfSettled(pi, ctx);
310
455
  });
311
456
 
312
457
  pi.on("input", (event) => {
@@ -314,24 +459,63 @@ export default function goal(pi: ExtensionAPI) {
314
459
  if (consumeCancelledContinuationPrompt(event.text)) return { action: "handled" as const };
315
460
  return;
316
461
  }
462
+ if (/^\/goal(?:\s|$)/u.test(event.text.trimStart())) return;
317
463
  clearGoalRecovery();
464
+ clearBudgetWrapUp();
318
465
  clearStaleGoalToolCallBlock();
319
466
  });
320
467
 
321
- pi.on("tool_call", () => {
468
+ pi.on("context", (event) => {
469
+ const messages = event.messages.filter((message) => keepBudgetWrapUpMessage(message));
470
+ if (messages.length !== event.messages.length) return { messages };
471
+ });
472
+
473
+ pi.on("tool_call", (event, ctx) => {
474
+ if (
475
+ activeGoal?.status === "budget_limited" &&
476
+ budgetWrapUp?.goalId === activeGoal.id &&
477
+ event.toolName !== "goal_complete"
478
+ ) {
479
+ // A blocked tool result would normally trigger another model call. Abort the
480
+ // wrap-up instead so a tool-seeking model cannot create an unbounded loop.
481
+ abortCurrentTurn(ctx);
482
+ return {
483
+ block: true,
484
+ reason: "Goal token budget is exhausted; only goal_complete is allowed during wrap-up.",
485
+ };
486
+ }
322
487
  if (!staleGoalToolCallsBlocked) return;
323
- if (!activeGoal || activeGoal.status !== "paused") {
488
+ if (!activeGoal || !blocksStaleGoalToolCalls(activeGoal.status)) {
324
489
  clearStaleGoalToolCallBlock();
325
490
  return;
326
491
  }
327
492
  return {
328
493
  block: true,
329
- reason: "Blocked stale /goal tool call after the goal was paused or interrupted.",
494
+ reason: "Blocked stale /goal tool call after the goal stopped or was interrupted.",
330
495
  };
331
496
  });
332
497
 
498
+ pi.on("tool_execution_end", (_event, ctx) => {
499
+ if (
500
+ activeGoal?.status === "budget_limited" &&
501
+ budgetWrapUp?.goalId === activeGoal.id &&
502
+ !budgetWrapUp.delivered
503
+ ) {
504
+ queueBudgetWrapUp(pi, ctx, activeGoal);
505
+ return;
506
+ }
507
+ if (!activeGoal || activeGoal.status !== "active") return;
508
+
509
+ // AgentSession persists assistant message_end before tool execution events,
510
+ // 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);
515
+ });
516
+
333
517
  pi.on("before_agent_start", (event) => {
334
- markContinuationDelivered(event.prompt);
518
+ markContinuationStarted(event.prompt);
335
519
  if (!activeGoal || activeGoal.status !== "active") return;
336
520
 
337
521
  return {
@@ -339,55 +523,66 @@ export default function goal(pi: ExtensionAPI) {
339
523
  };
340
524
  });
341
525
 
342
- pi.on("agent_end", async (event, ctx) => {
343
- if (!activeGoal || activeGoal.status !== "active") return;
526
+ 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
+ clearBudgetWrapUp();
533
+ return;
534
+ }
535
+ if (activeGoal.status !== "active") return;
344
536
 
345
537
  const goalId = activeGoal.id;
346
- const hadPendingContinuation = continuationPending?.goalId === goalId;
538
+ const alreadyAwaitingContinuation = hasContinuationWorkForGoal(goalId);
347
539
  const finalAssistant = findFinalAssistantMessage(event.messages);
348
540
 
349
- if (!hadPendingContinuation) activeGoal = incrementGoal(activeGoal);
541
+ if (!alreadyAwaitingContinuation) activeGoal = incrementGoal(activeGoal);
350
542
  updateGoalUsage(activeGoal, ctx);
351
543
 
352
- if (finalAssistant?.stopReason === "aborted" || finalAssistant?.stopReason === "error") {
544
+ if (finalAssistant?.stopReason === "aborted") {
545
+ clearGoalRecoveryForGoal(goalId);
546
+ stopGoalAfterAgentEnd(ctx, activeGoal, finalAssistant, "paused");
547
+ return;
548
+ }
549
+
550
+ if (finalAssistant?.stopReason === "error") {
353
551
  if (isRetryableGoalInterruption(finalAssistant)) {
552
+ if (limitActiveGoalForBudget(pi, ctx, false)) return;
354
553
  goalRecovery = {
355
554
  goalId,
356
555
  kind: isGoalContextOverflow(finalAssistant) ? "compaction_retry" : "provider_retry",
357
556
  };
358
- cancelContinuationPending();
557
+ cancelContinuationWork();
359
558
  persistGoal(activeGoal);
360
559
  updateStatus(ctx, activeGoal);
361
560
  return;
362
561
  }
363
562
  clearGoalRecoveryForGoal(goalId);
364
- pauseGoalAfterAgentEnd(ctx, activeGoal, finalAssistant);
563
+ stopGoalAfterAgentEnd(
564
+ ctx,
565
+ activeGoal,
566
+ finalAssistant,
567
+ isUsageLimitedGoalInterruption(finalAssistant) ? "usage_limited" : "blocked",
568
+ );
365
569
  return;
366
570
  }
367
571
 
368
572
  clearGoalRecoveryForGoal(goalId);
369
573
 
370
- if (activeGoal.tokenBudget !== undefined && activeGoal.tokensUsed >= activeGoal.tokenBudget) {
371
- cancelContinuationPending();
372
- activeGoal = transitionGoal(activeGoal, "budget_limited");
373
- persistGoal(activeGoal);
374
- updateStatus(ctx, activeGoal);
375
- ctx.ui.notify(`Goal token budget reached: ${formatBudget(activeGoal)}`, "warning");
376
- return;
377
- }
574
+ if (limitActiveGoalForBudget(pi, ctx, false)) return;
378
575
 
379
576
  persistGoal(activeGoal);
380
577
  updateStatus(ctx, activeGoal);
381
578
 
382
- if (hadPendingContinuation) {
383
- if (hasPendingMessages(ctx)) return;
384
- if (continuationPending?.goalId === goalId) continuationPending = undefined;
385
- }
386
-
387
579
  const currentGoal = activeGoal;
388
580
  if (!currentGoal || currentGoal.id !== goalId || currentGoal.status !== "active") return;
389
- if (hasPendingMessages(ctx)) return;
390
- await sendContinuationPrompt(pi, ctx, currentGoal);
581
+ requestContinuation(currentGoal);
582
+ });
583
+
584
+ pi.on("agent_settled", (_event, ctx) => {
585
+ dispatchContinuationIfSettled(pi, ctx);
391
586
  });
392
587
  }
393
588
 
@@ -415,14 +610,37 @@ async function startGoal(
415
610
  }
416
611
  }
417
612
 
418
- cancelContinuationPending();
613
+ cancelContinuationWork();
419
614
  clearGoalRecovery();
615
+ clearBudgetWrapUp();
420
616
  clearStaleGoalToolCallBlock();
421
617
  activeGoal = createGoal(objective, tokenBudget, currentTokenTotal(ctx));
422
618
  persistGoal(activeGoal);
423
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);
639
+ }
640
+ }
641
+ return;
642
+ }
424
643
  ctx.ui.notify(existingGoal ? `Goal replaced: ${objective}` : `Goal started: ${objective}`, "info");
425
- await sendGoalPrompt(pi, ctx, activeGoal);
426
644
  }
427
645
 
428
646
  function pauseGoal(ctx: StatusContext) {
@@ -434,7 +652,9 @@ function pauseGoal(ctx: StatusContext) {
434
652
  ctx.ui.notify(`Goal is ${activeGoal.status}; only active goals can be paused.`, "warning");
435
653
  return;
436
654
  }
437
- cancelContinuationPending();
655
+ updateGoalUsage(activeGoal, ctx);
656
+ cancelContinuationWork();
657
+ clearBudgetWrapUp();
438
658
  blockStaleGoalToolCalls();
439
659
  abortCurrentTurn(ctx);
440
660
  activeGoal = transitionGoal(activeGoal, "paused");
@@ -448,11 +668,25 @@ async function resumeGoal(pi: ExtensionAPI, ctx: StatusContext) {
448
668
  ctx.ui.notify("No active goal.", "info");
449
669
  return;
450
670
  }
451
- if (activeGoal.status !== "paused" && activeGoal.status !== "budget_limited") {
452
- ctx.ui.notify(`Goal is ${activeGoal.status}; only paused or budget-limited goals can be resumed.`, "warning");
671
+ if (!isResumableGoalStatus(activeGoal.status)) {
672
+ ctx.ui.notify(
673
+ `Goal is ${activeGoal.status}; only paused, blocked, usage-limited, or budget-limited goals can be resumed.`,
674
+ "warning",
675
+ );
453
676
  return;
454
677
  }
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;
684
+ }
685
+ const stoppedGoal = activeGoal;
686
+ const stoppedStatus = stoppedGoal.status;
687
+ cancelContinuationWork();
455
688
  clearGoalRecovery();
689
+ clearBudgetWrapUp();
456
690
  clearStaleGoalToolCallBlock();
457
691
  activeGoal = transitionGoal(nextGoalInstance(activeGoal), "active");
458
692
  persistGoal(activeGoal);
@@ -461,15 +695,29 @@ async function resumeGoal(pi: ExtensionAPI, ctx: StatusContext) {
461
695
  ctx.ui.notify(`Goal token budget is still reached: ${formatBudget(activeGoal)}`, "warning");
462
696
  return;
463
697
  }
464
- ctx.ui.notify(`Goal resumed: ${activeGoal.text}`, "info");
465
- await sendResumePrompt(pi, ctx, activeGoal);
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();
706
+ }
707
+ return;
708
+ }
709
+ ctx.ui.notify(
710
+ `Goal resumed from ${stoppedStatusLabel(stoppedStatus)}: ${resumedGoal.text}`,
711
+ "info",
712
+ );
466
713
  }
467
714
 
468
715
  function clearGoal(ctx: StatusContext) {
469
716
  if (!activeGoal) {
470
717
  ctx.ui.notify("No active goal.", "info");
471
- cancelContinuationPending();
718
+ cancelContinuationWork();
472
719
  clearGoalRecovery();
720
+ clearBudgetWrapUp();
473
721
  clearStaleGoalToolCallBlock();
474
722
  clearPersistedGoal(ctx.cwd);
475
723
  ctx.ui.setStatus(STATUS_KEY, undefined);
@@ -498,22 +746,47 @@ async function editGoal(
498
746
  }
499
747
 
500
748
  updateGoalUsage(activeGoal, ctx);
501
- cancelContinuationPending();
749
+ const previousGoal = { ...activeGoal };
750
+ cancelContinuationWork();
502
751
  clearGoalRecovery();
503
- activeGoal = normalizeGoalForBudget({
504
- ...nextGoalInstance(activeGoal),
505
- text: objective,
506
- status: editedGoalStatus(activeGoal.status),
507
- tokenBudget: tokenBudget ?? activeGoal.tokenBudget,
508
- updatedAt: Date.now(),
509
- });
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
+ );
510
762
  persistGoal(activeGoal);
511
763
  updateStatus(ctx, activeGoal);
512
- ctx.ui.notify(`Goal updated: ${objective}`, "info");
513
764
  if (activeGoal.status === "active") {
514
765
  clearStaleGoalToolCallBlock();
515
- await sendObjectiveUpdatedPrompt(pi, ctx, activeGoal);
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
+ }
782
+ return;
783
+ }
784
+ } else if (blocksStaleGoalToolCalls(activeGoal.status)) {
785
+ blockStaleGoalToolCalls();
786
+ } else {
787
+ clearStaleGoalToolCallBlock();
516
788
  }
789
+ ctx.ui.notify(`Goal updated: ${objective}`, "info");
517
790
  }
518
791
 
519
792
  function showGoal(ctx: StatusContext) {
@@ -541,11 +814,21 @@ function createGoal(text: string, tokenBudget: number | undefined, baselineToken
541
814
  tokensUsed: 0,
542
815
  timeUsedSeconds: 0,
543
816
  baselineTokens,
817
+ activeStartedAt: now,
544
818
  };
545
819
  }
546
820
 
547
- function transitionGoal(goal: ActiveGoal, status: GoalStatus): ActiveGoal {
548
- return normalizeGoalForBudget({ ...goal, status, updatedAt: Date.now() });
821
+ function transitionGoal(goal: ActiveGoal, requestedStatus: GoalStatus): ActiveGoal {
822
+ const now = Date.now();
823
+ const status =
824
+ requestedStatus === "active" &&
825
+ goal.tokenBudget !== undefined &&
826
+ goal.tokensUsed >= goal.tokenBudget
827
+ ? "budget_limited"
828
+ : requestedStatus;
829
+ const next = { ...goal, status, updatedAt: now };
830
+ checkpointGoalActiveTime(next, now, status === "active");
831
+ return next;
549
832
  }
550
833
 
551
834
  function nextGoalInstance(goal: ActiveGoal): ActiveGoal {
@@ -553,165 +836,101 @@ function nextGoalInstance(goal: ActiveGoal): ActiveGoal {
553
836
  }
554
837
 
555
838
  function editedGoalStatus(status: GoalStatus): GoalStatus {
556
- return status === "paused" ? "paused" : "active";
557
- }
558
-
559
- function normalizeGoalForBudget(goal: ActiveGoal): ActiveGoal {
560
- if (
561
- goal.status === "active" &&
562
- goal.tokenBudget !== undefined &&
563
- goal.tokensUsed >= goal.tokenBudget
564
- ) {
565
- return { ...goal, status: "budget_limited" };
566
- }
567
- return goal;
839
+ if (status === "paused" || status === "blocked" || status === "usage_limited") return status;
840
+ return "active";
568
841
  }
569
842
 
570
843
  function incrementGoal(goal: ActiveGoal): ActiveGoal {
571
844
  return { ...goal, iteration: goal.iteration + 1, updatedAt: Date.now() };
572
845
  }
573
846
 
574
- function pauseGoalAfterAgentEnd(
847
+ function stopGoalAfterAgentEnd(
575
848
  ctx: StatusContext,
576
849
  goal: ActiveGoal,
577
850
  assistant: AssistantMessageLike,
851
+ status: "paused" | "blocked" | "usage_limited",
578
852
  ) {
579
- cancelContinuationPending();
853
+ cancelContinuationWork();
854
+ clearBudgetWrapUp();
580
855
  blockStaleGoalToolCalls();
581
856
  abortCurrentTurn(ctx);
582
- activeGoal = transitionGoal(goal, "paused");
857
+ activeGoal = transitionGoal(goal, status);
583
858
  persistGoal(activeGoal);
584
859
  updateStatus(ctx, activeGoal);
585
860
 
586
- const reason = assistant.stopReason === "aborted" ? "interruption" : "agent error";
587
861
  const details = assistant.errorMessage ? ` (${truncateNotification(assistant.errorMessage)})` : "";
588
- ctx.ui.notify(`Goal paused after ${reason}${details}. Run /goal resume to continue.`, "warning");
589
- }
590
-
591
- function updateGoalUsage(goal: ActiveGoal, ctx: StatusContext) {
592
- goal.tokensUsed = Math.max(0, currentTokenTotal(ctx) - goal.baselineTokens);
593
- goal.timeUsedSeconds = Math.max(0, Math.floor((Date.now() - goal.startedAt) / 1000));
594
- goal.updatedAt = Date.now();
595
- }
596
-
597
- export function completeGoalArguments(argumentPrefix: string): GoalArgumentCompletion[] | null {
598
- const prefix = argumentPrefix.trimStart();
599
- if (prefix === "") return [...GOAL_ARGUMENT_COMPLETIONS];
600
-
601
- const editOptionPrefix = /^edit\s+(\S*)$/.exec(prefix)?.[1];
602
- if (editOptionPrefix !== undefined) {
603
- return editOptionPrefix === "" || "--tokens".startsWith(editOptionPrefix)
604
- ? [EDIT_TOKEN_COMPLETION]
605
- : null;
862
+ if (status === "paused") {
863
+ ctx.ui.notify(`Goal paused after interruption${details}. Run /goal resume to continue.`, "warning");
864
+ return;
606
865
  }
607
-
608
- if (/\s/.test(prefix)) return null;
609
-
610
- const matches = GOAL_ARGUMENT_COMPLETIONS.filter(
611
- (item) => item.value.startsWith(prefix) || item.label.startsWith(prefix),
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",
612
876
  );
613
- return matches.length > 0 ? [...matches] : null;
614
877
  }
615
878
 
616
- export function parseCommand(args: string): CommandResult | string {
617
- const tokens = tokenize(args.trim());
618
- if (tokens.length === 0) return { kind: "show" };
619
-
620
- const [first, ...rest] = tokens;
621
- if (first === "pause") return rest.length === 0 ? { kind: "pause" } : "Usage: /goal pause";
622
- if (first === "resume") return rest.length === 0 ? { kind: "resume" } : "Usage: /goal resume";
623
- if (first === "clear" || first === "stop") return rest.length === 0 ? { kind: "clear" } : "Usage: /goal clear";
624
- if (first === "status") return rest.length === 0 ? { kind: "show" } : "Usage: /goal status";
625
- if (first === "edit") return parseObjective("edit", rest);
626
- return parseObjective("start", tokens);
879
+ async function sendGoalPrompt(pi: ExtensionAPI, ctx: StatusContext, goal: ActiveGoal) {
880
+ return sendPrompt(pi, ctx, buildGoalPrompt(goal));
627
881
  }
628
882
 
629
- function parseObjective(kind: "start" | "edit", tokens: string[]): CommandResult | string {
630
- let tokenBudget: number | undefined;
631
- const objectiveTokens = [...tokens];
632
-
633
- if (objectiveTokens[0] === "--tokens") {
634
- const rawBudget = objectiveTokens[1];
635
- if (!rawBudget) return "Usage: /goal --tokens 100k <goal_to_complete>";
636
- const parsedBudget = parseTokenBudget(rawBudget);
637
- if (parsedBudget === undefined) return `Invalid token budget: ${rawBudget}`;
638
- tokenBudget = parsedBudget;
639
- objectiveTokens.splice(0, 2);
640
- }
641
-
642
- if (objectiveTokens.length === 0) {
643
- return kind === "edit" ? "Usage: /goal edit <goal_to_complete>" : "Usage: /goal <goal_to_complete>";
644
- }
645
-
646
- return { kind, objective: objectiveTokens.join(" "), tokenBudget };
883
+ async function sendObjectiveUpdatedPrompt(pi: ExtensionAPI, ctx: StatusContext, goal: ActiveGoal) {
884
+ return sendPrompt(pi, ctx, buildObjectiveUpdatedPrompt(goal));
647
885
  }
648
886
 
649
- function tokenize(input: string): string[] {
650
- const tokens: string[] = [];
651
- let current = "";
652
- let quote: '"' | "'" | undefined;
653
-
654
- for (const char of input) {
655
- if (quote) {
656
- if (char === quote) quote = undefined;
657
- else current += char;
658
- continue;
659
- }
660
- if (char === '"' || char === "'") {
661
- quote = char;
662
- continue;
663
- }
664
- if (/\s/.test(char)) {
665
- if (current) tokens.push(current);
666
- current = "";
667
- continue;
668
- }
669
- current += char;
670
- }
671
- if (current) tokens.push(current);
672
- return tokens;
887
+ async function sendResumePrompt(
888
+ pi: ExtensionAPI,
889
+ ctx: StatusContext,
890
+ goal: ActiveGoal,
891
+ stoppedStatus: GoalStatus,
892
+ ) {
893
+ return sendPrompt(pi, ctx, buildResumePrompt(goal, stoppedStatus));
673
894
  }
674
895
 
675
- export function parseTokenBudget(value: string): number | undefined {
676
- const match = /^(\d+(?:\.\d+)?)([km])?$/iu.exec(value.trim());
677
- if (!match) return undefined;
678
- const amount = Number(match[1]);
679
- if (!Number.isFinite(amount) || amount <= 0) return undefined;
680
- const multiplier = match[2]?.toLowerCase() === "m" ? 1_000_000 : match[2]?.toLowerCase() === "k" ? 1_000 : 1;
681
- return Math.floor(amount * multiplier);
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;
682
906
  }
683
907
 
684
- export function validateObjective(objective: string): string | undefined {
685
- const trimmed = objective.trim();
686
- if (!trimmed) return "Usage: /goal <goal_to_complete>";
687
- if (trimmed.length > MAX_OBJECTIVE_LENGTH) {
688
- return `Goal objective is too long (${trimmed.length}/${MAX_OBJECTIVE_LENGTH} characters). Put long instructions in a file and reference it from /goal instead.`;
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;
689
914
  }
690
- return undefined;
691
- }
915
+ if (ctx.isIdle?.() !== true || hasPendingMessages(ctx)) return false;
692
916
 
693
- async function sendGoalPrompt(pi: ExtensionAPI, ctx: StatusContext, goal: ActiveGoal) {
694
- return sendPrompt(pi, ctx, buildGoalPrompt(goal));
695
- }
696
-
697
- async function sendObjectiveUpdatedPrompt(pi: ExtensionAPI, ctx: StatusContext, goal: ActiveGoal) {
698
- return sendPrompt(pi, ctx, buildObjectiveUpdatedPrompt(goal));
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
+ }
699
930
  }
700
931
 
701
- async function sendResumePrompt(pi: ExtensionAPI, ctx: StatusContext, goal: ActiveGoal) {
702
- return sendPrompt(pi, ctx, buildResumePrompt(goal));
703
- }
704
-
705
- async function sendContinuationPrompt(pi: ExtensionAPI, ctx: StatusContext, goal: ActiveGoal) {
706
- if (continuationPending?.goalId === goal.id) return false;
707
- if (hasPendingMessages(ctx)) return false;
708
-
709
- const marker = continuationMarker(goal);
710
- const prompt = buildContinuePrompt(goal, marker);
711
- continuationPending = { goalId: goal.id, iteration: goal.iteration, marker, prompt };
712
- const sent = await sendPrompt(pi, ctx, prompt);
713
- if (!sent && continuationPending?.marker === marker) continuationPending = undefined;
714
- return sent;
932
+ function hasContinuationWorkForGoal(goalId: string) {
933
+ return continuationIntent?.goalId === goalId || continuationDelivery?.goalId === goalId;
715
934
  }
716
935
 
717
936
  async function sendPrompt(pi: ExtensionAPI, ctx: StatusContext, prompt: string) {
@@ -736,6 +955,8 @@ export function formatStatus(goal: ActiveGoal | undefined) {
736
955
  if (!goal) return undefined;
737
956
  if (goal.status === "complete") return "complete";
738
957
  if (goal.status === "paused") return "paused";
958
+ if (goal.status === "blocked") return "blocked";
959
+ if (goal.status === "usage_limited") return "usage";
739
960
  if (goal.status === "budget_limited") return `budget ${formatBudget(goal)}`;
740
961
  if (goal.tokenBudget !== undefined) return `active ${formatBudget(goal)}`;
741
962
  return `active ${formatDuration(goal.timeUsedSeconds)}`;
@@ -750,7 +971,7 @@ function goalSummary(goal: ActiveGoal) {
750
971
  `Goal: ${goal.text}`,
751
972
  `Status: ${goal.status}`,
752
973
  `Iteration: ${goal.iteration}`,
753
- `Elapsed: ${formatDuration(goal.timeUsedSeconds)}`,
974
+ `Active elapsed: ${formatDuration(goal.timeUsedSeconds)}`,
754
975
  `Tokens: ${goal.tokenBudget === undefined ? formatTokenCount(goal.tokensUsed) : formatBudget(goal)}`,
755
976
  `Commands: ${goalCommandHint(goal.status)}`,
756
977
  ].join("\n");
@@ -758,86 +979,115 @@ function goalSummary(goal: ActiveGoal) {
758
979
 
759
980
  function goalCommandHint(status: GoalStatus) {
760
981
  if (status === "active") return "/goal edit <objective>, /goal pause, /goal clear";
761
- if (status === "paused") return "/goal edit <objective>, /goal resume, /goal clear";
982
+ if (isResumableGoalStatus(status)) {
983
+ return "/goal edit <objective>, /goal resume, /goal clear";
984
+ }
762
985
  return "/goal edit <objective>, /goal clear";
763
986
  }
764
987
 
765
- export function formatDuration(seconds: number) {
766
- if (seconds < 60) return `${seconds}s`;
767
- const minutes = Math.floor(seconds / 60);
768
- if (minutes < 60) return `${minutes}m`;
769
- const hours = Math.floor(minutes / 60);
770
- return `${hours}h${minutes % 60}m`;
771
- }
772
-
773
- export function formatTokenCount(value: number) {
774
- if (value < 1_000) return `${value}`;
775
- if (value < 1_000_000) return `${Number.isInteger(value / 1_000) ? value / 1_000 : (value / 1_000).toFixed(1)}k`;
776
- return `${Number.isInteger(value / 1_000_000) ? value / 1_000_000 : (value / 1_000_000).toFixed(1)}m`;
777
- }
778
-
779
- function buildGoalPrompt(goal: ActiveGoal) {
780
- const budgetLine = goal.tokenBudget === undefined ? "" : `\nToken budget: ${formatTokenCount(goal.tokenBudget)}.`;
781
- return `Goal mode is active. Complete this goal fully:\n\n${goalContextBlock(goal)}${budgetLine}\n\n${goalPersistenceRules("this goal")}`;
988
+ function hasPendingMessages(ctx: StatusContext) {
989
+ return ctx.hasPendingMessages?.() ?? false;
782
990
  }
783
991
 
784
- function buildObjectiveUpdatedPrompt(goal: ActiveGoal) {
785
- const budgetLine = goal.tokenBudget === undefined ? "" : `\nToken budget: ${formatBudget(goal)} used.`;
786
- return `The active /goal objective was updated. Continue working toward this goal:\n\n${goalContextBlock(goal)}${budgetLine}\n\n${goalPersistenceRules("the updated goal")}`;
992
+ function abortCurrentTurn(ctx: StatusContext) {
993
+ try {
994
+ ctx.abort?.();
995
+ } catch {
996
+ // Best effort: stale goal guards still prevent follow-on tool calls.
997
+ }
787
998
  }
788
999
 
789
- function buildResumePrompt(goal: ActiveGoal) {
790
- const budgetLine = goal.tokenBudget === undefined ? "" : `\nToken budget: ${formatBudget(goal)} used.`;
791
- return `The user explicitly resumed the paused /goal. Continue working toward this goal:\n\n${goalContextBlock(goal)}${budgetLine}\n\n${goalPersistenceRules("this goal")}`;
1000
+ function blockStaleGoalToolCalls() {
1001
+ staleGoalToolCallsBlocked = true;
792
1002
  }
793
1003
 
794
- export function buildGoalSystemPrompt(goal: ActiveGoal) {
795
- const budgetLine = goal.tokenBudget === undefined ? "" : `\n- Respect the goal token budget (${formatBudget(goal)} used).`;
796
- return `Active /goal:\n${goalContextBlock(goal)}\n\nGoal-mode rules:\n- Keep going until the active goal is completely resolved end-to-end.\n- Treat the current worktree, command output, tests, and external state as authoritative.\n- Do not redefine the goal into a smaller task; audit every requirement before completion.\n- Do not stop at analysis, a plan, TODO list, partial fixes, or suggested next steps.\n- Autonomously perform implementation and verification with the available tools when they are needed to complete the goal.\n- Persevere through recoverable tool failures by trying reasonable alternatives instead of yielding early.\n- If the goal is not complete at the end of a turn, expect an automatic continuation and keep working from where you left off.\n- Only call the goal_complete tool after the goal is fully complete and verified, and pass this exact goal_id.${budgetLine}`;
1004
+ function blocksStaleGoalToolCalls(status: GoalStatus) {
1005
+ return status === "paused" || status === "blocked" || status === "usage_limited";
797
1006
  }
798
1007
 
799
- function buildContinuePrompt(goal: ActiveGoal, marker: string) {
800
- return `Continue the active /goal until it is complete:\n\n${goalContextBlock(goal)}\n\nThis is automatic continuation #${goal.iteration}. Current files, command output, tests, and external state are authoritative; re-check them as needed. ${goalPersistenceRules("this goal")}\n\n${continuationMarkerComment(marker)}`;
1008
+ function isResumableGoalStatus(status: GoalStatus) {
1009
+ return blocksStaleGoalToolCalls(status) || status === "budget_limited";
801
1010
  }
802
1011
 
803
- function goalContextBlock(goal: ActiveGoal) {
804
- return `${goalObjectiveBlock(goal)}\n\n${goalCompletionGuardBlock(goal)}`;
1012
+ function stoppedStatusLabel(status: GoalStatus) {
1013
+ if (status === "usage_limited") return "usage-limited";
1014
+ if (status === "budget_limited") return "budget-limited";
1015
+ return status;
805
1016
  }
806
1017
 
807
- function goalObjectiveBlock(goal: ActiveGoal) {
808
- return `<goal_objective>\n${escapeXmlText(goal.text)}\n</goal_objective>`;
1018
+ function clearStaleGoalToolCallBlock() {
1019
+ staleGoalToolCallsBlocked = false;
809
1020
  }
810
1021
 
811
- function goalCompletionGuardBlock(goal: ActiveGoal) {
812
- return `<goal_id>\n${escapeXmlText(goal.id)}\n</goal_id>\nThis goal_id is only the goal_complete tool stale-turn guard, not part of the objective. If and only if the goal is fully complete, pass this exact goal_id to goal_complete with the completion summary.`;
1022
+ function clearGoalRecovery() {
1023
+ goalRecovery = undefined;
813
1024
  }
814
1025
 
815
- function goalPersistenceRules(goalLabel: string) {
816
- return `Keep going until ${goalLabel} is completely resolved end-to-end. Do not redefine ${goalLabel} into a smaller task. Do not stop at analysis, a plan, TODO list, partial fixes, or suggested next steps. Autonomously perform implementation and verification with the available tools when they are needed. Treat the current worktree, command output, tests, and external state as authoritative. If a tool call fails, try reasonable alternatives instead of yielding early. Before calling goal_complete, audit ${goalLabel} requirement by requirement against the verified current state. Only call the goal_complete tool after ${goalLabel} is fully complete and verified, and pass this exact goal_id. Never reuse a goal_id from an older, paused, replaced, or cleared turn.`;
1026
+ function clearBudgetWrapUp() {
1027
+ budgetWrapUp = undefined;
817
1028
  }
818
1029
 
819
- function hasPendingMessages(ctx: StatusContext) {
820
- return ctx.hasPendingMessages?.() ?? false;
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
+ );
821
1045
  }
822
1046
 
823
- function abortCurrentTurn(ctx: StatusContext) {
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;
824
1053
  try {
825
- ctx.abort?.();
826
- } catch {
827
- // Best effort: stale goal guards still prevent follow-on tool calls.
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;
828
1068
  }
829
1069
  }
830
1070
 
831
- function blockStaleGoalToolCalls() {
832
- staleGoalToolCallsBlocked = true;
833
- }
834
-
835
- function clearStaleGoalToolCallBlock() {
836
- staleGoalToolCallsBlocked = false;
837
- }
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
+ }
838
1081
 
839
- function clearGoalRecovery() {
840
- goalRecovery = undefined;
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;
841
1091
  }
842
1092
 
843
1093
  function clearGoalRecoveryForGoal(goalId: string) {
@@ -864,11 +1114,28 @@ function goalIdRejectionReason(goal: ActiveGoal, requestedGoalId: string) {
864
1114
  return undefined;
865
1115
  }
866
1116
 
1117
+ export function isUsageLimitedGoalInterruption(assistant: AssistantMessageLike) {
1118
+ const errorMessage = assistant.errorMessage;
1119
+ return (
1120
+ assistant.stopReason === "error" &&
1121
+ typeof errorMessage === "string" &&
1122
+ USAGE_LIMIT_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(errorMessage))
1123
+ );
1124
+ }
1125
+
867
1126
  export function isRetryableGoalInterruption(assistant: AssistantMessageLike) {
868
1127
  if (assistant.stopReason !== "error") return false;
869
1128
  if (!assistant.errorMessage) return false;
870
- if (NON_RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage)) return false;
871
- return isGoalContextOverflow(assistant) || RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage);
1129
+ if (
1130
+ isUsageLimitedGoalInterruption(assistant) ||
1131
+ NON_RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage)
1132
+ ) {
1133
+ return false;
1134
+ }
1135
+ return (
1136
+ isGoalContextOverflow(assistant) ||
1137
+ RETRYABLE_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(assistant.errorMessage ?? ""))
1138
+ );
872
1139
  }
873
1140
 
874
1141
  function isGoalContextOverflow(assistant: AssistantMessageLike) {
@@ -907,13 +1174,15 @@ function zeroUsage(): Usage {
907
1174
  }
908
1175
 
909
1176
  function clearContinuationTracking() {
910
- continuationPending = undefined;
1177
+ continuationIntent = undefined;
1178
+ continuationDelivery = undefined;
911
1179
  cancelledContinuationMarkers.clear();
912
1180
  }
913
1181
 
914
- function cancelContinuationPending() {
915
- if (continuationPending) rememberCancelledContinuationMarker(continuationPending.marker);
916
- continuationPending = undefined;
1182
+ function cancelContinuationWork() {
1183
+ if (continuationDelivery) rememberCancelledContinuationMarker(continuationDelivery.marker);
1184
+ continuationIntent = undefined;
1185
+ continuationDelivery = undefined;
917
1186
  }
918
1187
 
919
1188
  function rememberCancelledContinuationMarker(marker: string) {
@@ -928,9 +1197,16 @@ function consumeCancelledContinuationPrompt(prompt: string) {
928
1197
  return marker ? cancelledContinuationMarkers.delete(marker) : false;
929
1198
  }
930
1199
 
931
- function markContinuationDelivered(prompt: string) {
1200
+ function markContinuationStarted(prompt: string) {
932
1201
  const marker = extractContinuationMarker(prompt);
933
- if (marker && continuationPending?.marker === marker) continuationPending = undefined;
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;
934
1210
  }
935
1211
 
936
1212
  function continuationMarker(goal: ActiveGoal) {
@@ -985,11 +1261,11 @@ function normalizeUsage(value: unknown): Usage | undefined {
985
1261
  const usage = value as Partial<Usage>;
986
1262
  if (typeof usage.input !== "number" || typeof usage.output !== "number") return undefined;
987
1263
  return {
988
- input: usage.input,
989
- output: usage.output,
990
- cacheRead: usage.cacheRead ?? 0,
991
- cacheWrite: usage.cacheWrite ?? 0,
992
- totalTokens: usage.totalTokens ?? usage.input + usage.output + (usage.cacheRead ?? 0),
1264
+ input: nonNegativeFiniteNumber(usage.input),
1265
+ output: nonNegativeFiniteNumber(usage.output),
1266
+ cacheRead: nonNegativeFiniteNumber(usage.cacheRead),
1267
+ cacheWrite: nonNegativeFiniteNumber(usage.cacheWrite),
1268
+ totalTokens: assistantUsageTokens(usage),
993
1269
  cost: {
994
1270
  input: usage.cost?.input ?? 0,
995
1271
  output: usage.cost?.output ?? 0,
@@ -1012,21 +1288,6 @@ function truncateNotification(value: string) {
1012
1288
  return value.length > 160 ? `${value.slice(0, 157)}...` : value;
1013
1289
  }
1014
1290
 
1015
- function currentTokenTotal(ctx: StatusContext): number {
1016
- const sessionManager = ctx.sessionManager as
1017
- | { getBranch?: () => Array<{ type?: string; message?: { role?: string; usage?: unknown } }> }
1018
- | undefined;
1019
- const branch = sessionManager?.getBranch?.() ?? [];
1020
- let total = 0;
1021
- for (const entry of branch) {
1022
- if (entry.type !== "message" || entry.message?.role !== "assistant") continue;
1023
- const usage = entry.message.usage as { input?: number; output?: number } | undefined;
1024
- total += usage?.input ?? 0;
1025
- total += usage?.output ?? 0;
1026
- }
1027
- return total;
1028
- }
1029
-
1030
1291
  function persistGoal(goal: ActiveGoal) {
1031
1292
  extensionApi?.appendEntry<GoalStateEntryData>(GOAL_STATE_ENTRY_TYPE, { goal });
1032
1293
  }
@@ -1036,24 +1297,10 @@ function clearPersistedGoal(cwd: string) {
1036
1297
  clearLegacyPersistedGoal(cwd);
1037
1298
  }
1038
1299
 
1039
- function loadGoalFromSession(ctx: StatusContext): ActiveGoal | undefined {
1040
- const sessionManager = ctx.sessionManager as
1041
- | {
1042
- getBranch?: () => Array<{ type?: string; customType?: string; data?: unknown }>;
1043
- getEntries?: () => Array<{ type?: string; customType?: string; data?: unknown }>;
1044
- }
1045
- | undefined;
1046
- const entries = sessionManager?.getBranch?.() ?? sessionManager?.getEntries?.() ?? [];
1047
- const entry = entries
1048
- .filter((entry) => entry.type === "custom" && entry.customType === GOAL_STATE_ENTRY_TYPE)
1049
- .pop();
1050
- const data = entry?.data as GoalStateEntryData | undefined;
1051
- return isGoal(data?.goal) && data.goal.status !== "complete" ? data.goal : undefined;
1052
- }
1053
-
1054
1300
  function clearActiveGoal(ctx: StatusContext) {
1055
- cancelContinuationPending();
1301
+ cancelContinuationWork();
1056
1302
  clearGoalRecovery();
1303
+ clearBudgetWrapUp();
1057
1304
  clearStaleGoalToolCallBlock();
1058
1305
  activeGoal = undefined;
1059
1306
  clearPersistedGoal(ctx.cwd);
@@ -1080,39 +1327,11 @@ function clearCompletionStatusTimer() {
1080
1327
  completionStatusTimer = undefined;
1081
1328
  }
1082
1329
 
1083
- function readState(): Record<string, unknown> {
1084
- if (!existsSync(STATE_FILE)) return {};
1085
- try {
1086
- const parsed = JSON.parse(readFileSync(STATE_FILE, "utf8")) as unknown;
1087
- return parsed && typeof parsed === "object" && !Array.isArray(parsed)
1088
- ? (parsed as Record<string, unknown>)
1089
- : {};
1090
- } catch {
1091
- return {};
1092
- }
1093
- }
1094
-
1095
- function clearLegacyPersistedGoal(cwd: string) {
1096
- if (!existsSync(STATE_FILE)) return;
1097
- const goals = readState();
1098
- delete goals[cwd];
1099
- mkdirSync(dirname(STATE_FILE), { recursive: true });
1100
- writeFileSync(STATE_FILE, `${JSON.stringify(goals, null, 2)}\n`);
1101
- }
1102
-
1103
-
1104
- function isGoal(value: unknown): value is ActiveGoal {
1105
- if (!value || typeof value !== "object") return false;
1106
- const goal = value as Partial<ActiveGoal>;
1107
- return (
1108
- typeof goal.id === "string" &&
1109
- typeof goal.text === "string" &&
1110
- ["active", "paused", "budget_limited", "complete"].includes(String(goal.status)) &&
1111
- typeof goal.startedAt === "number" &&
1112
- typeof goal.updatedAt === "number" &&
1113
- typeof goal.iteration === "number" &&
1114
- typeof goal.tokensUsed === "number" &&
1115
- typeof goal.timeUsedSeconds === "number" &&
1116
- typeof goal.baselineTokens === "number"
1117
- );
1118
- }
1330
+ export {
1331
+ assistantUsageTokens,
1332
+ cumulativeAssistantTokens,
1333
+ formatDuration,
1334
+ formatTokenCount,
1335
+ } from "./accounting.js";
1336
+ export { completeGoalArguments, parseCommand, parseTokenBudget, validateObjective } from "./command.js";
1337
+ export { buildGoalSystemPrompt } from "./prompts.js";