@narumitw/pi-goal 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/goal.ts CHANGED
@@ -1,44 +1,37 @@
1
- import { randomUUID } from "node:crypto";
2
- import {
3
- isContextOverflow,
4
- type AssistantMessage as PiAssistantMessage,
5
- type Usage,
6
- } from "@earendil-works/pi-ai";
7
1
  import { defineTool, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
8
2
  import { Type } from "typebox";
3
+ import { currentTokenTotal, updateGoalUsage } from "./accounting.js";
4
+ import { completeGoalArguments, parseCommand } from "./command.js";
5
+ import { GoalCommandController } from "./commands.js";
6
+ import { type ActiveGoal, loadGoalStateFromSession } from "./persistence.js";
7
+ import { buildGoalPrompt, buildGoalSystemPrompt } from "./prompts.js";
8
+ import { activateQueuedGoal } from "./queue.js";
9
9
  import {
10
- assistantUsageTokens,
11
- checkpointGoalActiveTime,
12
- currentTokenTotal,
13
- formatDuration,
14
- formatTokenCount,
15
- nonNegativeFiniteNumber,
16
- updateGoalUsage,
17
- } from "./accounting.js";
18
- import { completeGoalArguments, parseCommand, validateObjective } from "./command.js";
19
- import {
20
- type ActiveGoal,
21
- clearLegacyPersistedGoal,
22
- type GoalStateEntryData,
23
- loadGoalFromSession,
24
- } from "./persistence.js";
25
- import {
26
- buildContinuePrompt,
27
- buildGoalPrompt,
28
- buildGoalSystemPrompt,
29
- buildObjectiveUpdatedPrompt,
30
- buildResumePrompt,
31
- type GoalStatus,
32
- } from "./prompts.js";
33
-
34
- type AgentStopReason = "stop" | "length" | "toolUse" | "error" | "aborted";
35
-
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.
10
+ type AssistantMessageLike,
11
+ abortCurrentTurn,
12
+ blocksStaleGoalToolCalls,
13
+ findFinalAssistantMessage,
14
+ formatError,
15
+ formatStatus,
16
+ GOAL_BLOCKED_TOOL,
17
+ GOAL_COMPLETE_TOOL,
18
+ GoalRuntime,
19
+ goalIdRejectionReason,
20
+ incrementGoal,
21
+ isContradictoryCompletionSummary,
22
+ isGoalContextOverflow,
23
+ isRetryableGoalInterruption,
24
+ isUsageLimitedGoalInterruption,
25
+ STATUS_KEY,
26
+ type StatusContext,
27
+ transitionGoal,
28
+ truncateNotification,
29
+ } from "./runtime.js";
30
+ import { DEFAULT_GOAL_SETTINGS, readGoalSettings } from "./settings.js";
31
+
32
+ // goal.ts is the Pi-facing composition root: it keeps tool contracts and event
33
+ // ordering together. Per-session mechanisms live in runtime.ts, while user command
34
+ // transitions live in commands.ts. Each factory constructs isolated instances.
42
35
 
43
36
  interface GoalCompleteDetails {
44
37
  goal: string;
@@ -54,107 +47,61 @@ interface GoalBlockedDetails {
54
47
  repeated_turns: number;
55
48
  }
56
49
 
57
- interface ContinuationTicket {
58
- goalId: string;
59
- iteration: number;
60
- marker: string;
61
- prompt: string;
62
- }
63
-
64
- interface BudgetWrapUp {
65
- goalId: string;
66
- delivered: boolean;
67
- }
68
-
69
- type GoalRecoveryKind = "provider_retry" | "compaction_retry";
70
-
71
- interface GoalRecovery {
72
- goalId: string;
73
- kind: GoalRecoveryKind;
74
- }
75
-
76
- interface AssistantMessageLike {
77
- role: "assistant";
78
- stopReason?: AgentStopReason;
79
- errorMessage?: string;
80
- content?: PiAssistantMessage["content"];
81
- api?: PiAssistantMessage["api"];
82
- provider?: PiAssistantMessage["provider"];
83
- model?: string;
84
- usage?: Usage;
85
- timestamp?: number;
50
+ interface GoalOptions {
51
+ settingsPath?: string;
86
52
  }
87
53
 
88
- interface StatusContext {
89
- cwd: string;
90
- ui: {
91
- confirm: (title: string, message: string) => Promise<boolean>;
92
- notify: (message: string, level?: "info" | "warning" | "error") => void;
93
- setStatus: (key: string, value: string | undefined) => void;
94
- };
95
- isIdle?: () => boolean;
96
- hasPendingMessages?: () => boolean;
97
- abort?: () => void;
98
- sessionManager?: unknown;
99
- }
100
-
101
- const STATUS_KEY = "goal";
102
- const GOAL_STATE_ENTRY_TYPE = "goal-state";
54
+ const EXPERIMENTAL_GOALS_WARNING =
55
+ "Experimental ordered goals are enabled for pi-goal. Queue behavior and persisted state may change.";
103
56
  const MAX_BLOCKER_REASON_LENGTH = 1_000;
104
57
  const MAX_BLOCKER_EVIDENCE_LENGTH = 4_000;
105
- const MAX_CANCELLED_CONTINUATION_PROMPTS = 20;
106
- const CONTINUATION_MARKER_PREFIX = "pi-goal-continuation:";
107
- const BUDGET_WRAP_UP_MESSAGE_TYPE = "goal-budget-wrap-up";
108
- const BUDGET_WRAP_UP_PROMPT =
109
- "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.";
110
- const CONTRADICTORY_COMPLETION_PATTERNS = [
111
- /(?<!could\s)\bnot\s+(?:yet\s+)?(?:complete|completed|done|finished)\b/i,
112
- /\bstill\s+(?:incomplete|failing|failing\s+tests?|fails?)\b/i,
113
- /\btests?\s+(?:still\s+)?fail(?:ing)?\b/i,
114
- ] as const;
115
- const USAGE_LIMIT_GOAL_ERROR_PATTERNS = [
116
- /usage[_\s-]*(?:limit|cap)|chatgpt.{0,32}usage/i,
117
- /quota.{0,32}(?:reached|exceeded|exhausted|depleted)|(?:reached|exceeded|exhausted|depleted).{0,32}quota/i,
118
- /insufficient[_\s-]*(?:quota|credits?)|out of credits|out of budget|available balance|payment required/i,
119
- /(?:credit|balance).{0,32}(?:low|exhausted|depleted)|billing/i,
120
- ] as const;
121
- const NON_RETRYABLE_GOAL_ERROR_RE =
122
- /multi-auth rotation failed|credentials tried|unauthori[sz]ed|invalid api key/i;
123
- // Pi 0.79 does not export its assistant-error retry classifier. Keep this
124
- // compatibility mirror aligned with Pi's public retry utility in newer versions.
125
- const RETRYABLE_GOAL_ERROR_PATTERNS = [
126
- /overloaded|rate.?limit|too many requests|\b(?:429|500|502|503|504)\b|service.?unavailable|server.?error|internal.?error/i,
127
- /provider.?returned.?error|you can retry your request|try your request again|please retry your request/i,
128
- /network.?error|connection.?(?:error|refused|lost)|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up/i,
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,
130
- /context[_\s-]*length[_\s-]*exceeded|input exceeds the context window/i,
131
- ] as const;
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
58
 
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);
59
+ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
60
+ const runtime = new GoalRuntime(pi);
61
+ const commands = new GoalCommandController(runtime);
62
+
63
+ // Bind per-factory runtime operations once so event orchestration stays concise
64
+ // without reintroducing module-global mutable state.
65
+ const clearCompletionStatusTimer = runtime.clearCompletionStatusTimer.bind(runtime);
66
+ const clearContinuationTracking = runtime.clearContinuationTracking.bind(runtime);
67
+ const clearPendingGoalPrompts = runtime.clearPendingGoalPrompts.bind(runtime);
68
+ const clearGoalRecovery = runtime.clearGoalRecovery.bind(runtime);
69
+ const clearBudgetWrapUp = runtime.clearBudgetWrapUp.bind(runtime);
70
+ const clearStaleGoalToolCallBlock = runtime.clearStaleGoalToolCallBlock.bind(runtime);
71
+ const persistGoal = runtime.persistGoal.bind(runtime);
72
+ const updateStatus = runtime.updateStatus.bind(runtime);
73
+ const limitActiveGoalForBudget = runtime.limitActiveGoalForBudget.bind(runtime);
74
+ const hideGoalToolsIfLocked = runtime.hideGoalToolsIfLocked.bind(runtime);
75
+ const goalToolsAvailable = runtime.goalToolsAvailable.bind(runtime);
76
+ const pauseGoalForUnavailableTools = runtime.pauseGoalForUnavailableTools.bind(runtime);
77
+ const isPiOwnedCompactionRetry = runtime.isPiOwnedCompactionRetry.bind(runtime);
78
+ const requestContinuation = runtime.requestContinuation.bind(runtime);
79
+ const dispatchContinuationIfSettled = runtime.dispatchContinuationIfSettled.bind(runtime);
80
+ const keepBudgetWrapUpMessage = runtime.keepBudgetWrapUpMessage.bind(runtime);
81
+ const isGoalToolName = runtime.isGoalToolName.bind(runtime);
82
+ const queueBudgetWrapUp = runtime.queueBudgetWrapUp.bind(runtime);
83
+ const clearGoalRecoveryForGoal = runtime.clearGoalRecoveryForGoal.bind(runtime);
84
+ const blockStaleGoalToolCalls = runtime.blockStaleGoalToolCalls.bind(runtime);
85
+ const cancelContinuationWork = runtime.cancelContinuationWork.bind(runtime);
86
+ const consumeCancelledContinuationPrompt =
87
+ runtime.consumeCancelledContinuationPrompt.bind(runtime);
88
+ const consumePendingGoalPrompt = runtime.consumeOwnedGoalPrompt.bind(runtime);
89
+ const markContinuationStarted = runtime.markContinuationStarted.bind(runtime);
90
+ const hasContinuationWorkForGoal = runtime.hasContinuationWorkForGoal.bind(runtime);
91
+ const clearActiveGoal = runtime.clearActiveGoal.bind(runtime);
92
+ const showCompletionStatus = runtime.showCompletionStatus.bind(runtime);
93
+ const restoreGoalToolsHiddenByPolicy = runtime.restoreGoalToolsHiddenByPolicy.bind(runtime);
94
+ const sendOwnedGoalPrompt = (
95
+ _pi: ExtensionAPI,
96
+ ctx: StatusContext,
97
+ goalId: string,
98
+ prompt: string,
99
+ ) => runtime.sendOwnedGoalPrompt(ctx, goalId, prompt);
100
+ const dispatchPendingQueueActionIfSettled =
101
+ commands.dispatchPendingQueueActionIfSettled.bind(commands);
155
102
 
156
103
  const goalCompleteTool = defineTool({
157
- name: "goal_complete",
104
+ name: GOAL_COMPLETE_TOOL,
158
105
  label: "Goal Complete",
159
106
  description:
160
107
  "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.",
@@ -196,6 +143,19 @@ function registerGoalRuntime(pi: ExtensionAPI) {
196
143
  completedGoal.status === "budget_limited" &&
197
144
  runtime.budgetWrapUp?.goalId === completedGoal.id &&
198
145
  runtime.budgetWrapUp.delivered;
146
+ if (hasPendingSkipForGoal(completedGoal.id)) {
147
+ updateGoalUsage(completedGoal, ctx);
148
+ persistGoal(completedGoal);
149
+ updateStatus(ctx, completedGoal);
150
+ clearBudgetWrapUp();
151
+ const rejection = "Goal completion rejected: goal is queued to be skipped.";
152
+ ctx.ui.notify(rejection, "warning");
153
+ return {
154
+ content: [{ type: "text", text: rejection }],
155
+ details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
156
+ terminate: true,
157
+ };
158
+ }
199
159
  const staleGoalRejection = goalIdRejectionReason(completedGoal, requestedGoalId);
200
160
  if (staleGoalRejection) {
201
161
  const rejection = `Goal completion rejected: ${staleGoalRejection}.`;
@@ -250,6 +210,48 @@ function registerGoalRuntime(pi: ExtensionAPI) {
250
210
 
251
211
  runtime.activeGoal = transitionGoal(completedGoal, "complete");
252
212
  updateGoalUsage(runtime.activeGoal, ctx);
213
+ if (runtime.pendingQueueAction?.kind === "prioritize") {
214
+ persistGoal(runtime.activeGoal);
215
+ ctx.ui.setStatus(STATUS_KEY, "complete");
216
+ ctx.ui.notify(`Goal complete: ${goal}. Priority goal waits for Pi to settle.`, "info");
217
+ return {
218
+ content: [{ type: "text", text: `Goal complete: ${summary}` }],
219
+ details: {
220
+ goal,
221
+ goal_id: requestedGoalId,
222
+ summary,
223
+ } satisfies GoalCompleteDetails,
224
+ terminate: true,
225
+ };
226
+ }
227
+ if (runtime.queuedGoals.length > 0) {
228
+ runtime.pendingQueueAction = {
229
+ kind: "advance",
230
+ goalId: runtime.activeGoal.id,
231
+ reason: "complete",
232
+ completedText: goal,
233
+ };
234
+ persistGoal(runtime.activeGoal);
235
+ ctx.ui.setStatus(STATUS_KEY, "complete");
236
+ ctx.ui.notify(
237
+ `Goal complete: ${goal}. Next goal queued: ${runtime.queuedGoals[0]?.text}`,
238
+ "info",
239
+ );
240
+ return {
241
+ content: [
242
+ {
243
+ type: "text",
244
+ text: `Goal complete: ${summary}\nNext goal queued: ${runtime.queuedGoals[0]?.text}`,
245
+ },
246
+ ],
247
+ details: {
248
+ goal,
249
+ goal_id: requestedGoalId,
250
+ summary,
251
+ } satisfies GoalCompleteDetails,
252
+ terminate: true,
253
+ };
254
+ }
253
255
  persistGoal(runtime.activeGoal);
254
256
 
255
257
  ctx.ui.setStatus(STATUS_KEY, formatStatus(runtime.activeGoal));
@@ -266,7 +268,7 @@ function registerGoalRuntime(pi: ExtensionAPI) {
266
268
  });
267
269
 
268
270
  const goalBlockedTool = defineTool({
269
- name: "goal_blocked",
271
+ name: GOAL_BLOCKED_TOOL,
270
272
  label: "Goal Blocked",
271
273
  description:
272
274
  "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.",
@@ -305,7 +307,7 @@ function registerGoalRuntime(pi: ExtensionAPI) {
305
307
  const evidence = typeof params.evidence === "string" ? params.evidence.trim() : "";
306
308
  const repeatedTurns =
307
309
  typeof params.repeated_turns === "number" ? params.repeated_turns : Number.NaN;
308
- const reject = (rejectionReason: string) => {
310
+ const reject = (rejectionReason: string, terminate = false) => {
309
311
  const rejection = `goal_blocked rejected: ${rejectionReason}.`;
310
312
  ctx.ui.notify(rejection, "warning");
311
313
  return {
@@ -317,10 +319,18 @@ function registerGoalRuntime(pi: ExtensionAPI) {
317
319
  evidence: evidence.slice(0, MAX_BLOCKER_EVIDENCE_LENGTH),
318
320
  repeated_turns: Number.isFinite(repeatedTurns) ? repeatedTurns : 0,
319
321
  } satisfies GoalBlockedDetails,
322
+ ...(terminate ? { terminate: true as const } : {}),
320
323
  };
321
324
  };
322
325
 
323
326
  if (!blockedGoal) return reject("no active goal");
327
+ if (hasPendingSkipForGoal(blockedGoal.id)) {
328
+ updateGoalUsage(blockedGoal, ctx);
329
+ persistGoal(blockedGoal);
330
+ updateStatus(ctx, blockedGoal);
331
+ clearBudgetWrapUp();
332
+ return reject("goal is queued to be skipped", true);
333
+ }
324
334
  const staleGoalRejection = goalIdRejectionReason(blockedGoal, requestedGoalId);
325
335
  if (staleGoalRejection) return reject(staleGoalRejection);
326
336
  if (blockedGoal.status !== "active") {
@@ -359,71 +369,202 @@ function registerGoalRuntime(pi: ExtensionAPI) {
359
369
 
360
370
  pi.registerTool(goalCompleteTool);
361
371
  pi.registerTool(goalBlockedTool);
372
+ // Do not touch the active tool set during factory registration: ExtensionAPI
373
+ // actions are unbound until the session binds the runtime. session_start applies
374
+ // baseline visibility once actions work; later hooks only enforce goal safety.
362
375
 
363
376
  pi.registerCommand("goal", {
364
377
  description: "Run a goal to completion: /goal [--tokens 100k] <goal_to_complete>",
365
- getArgumentCompletions: completeGoalArguments,
378
+ getArgumentCompletions: (prefix) =>
379
+ completeGoalArguments(prefix, {
380
+ experimentalGoals: runtime.settings.experimental.goals,
381
+ }),
366
382
  handler: async (args, ctx) => {
367
- const result = parseCommand(args);
383
+ const result = parseCommand(args, {
384
+ experimentalGoals: runtime.settings.experimental.goals,
385
+ });
368
386
  if (typeof result === "string") {
369
387
  ctx.ui.notify(result, "warning");
370
388
  return;
371
389
  }
390
+ if (runtime.queueFrozen) {
391
+ if (result.kind === "show") commands.showGoal(ctx);
392
+ else if (result.kind === "clear") commands.clearGoal(ctx);
393
+ else commands.notifyFrozenQueue(ctx);
394
+ return;
395
+ }
396
+ if (runtime.pendingQueueAction && result.kind !== "show" && result.kind !== "clear") {
397
+ ctx.ui.notify(
398
+ "A queued goal change is waiting for Pi to settle. Retry after it finishes.",
399
+ "warning",
400
+ );
401
+ return;
402
+ }
372
403
 
373
404
  switch (result.kind) {
374
405
  case "show":
375
- showGoal(ctx);
406
+ commands.showGoal(ctx);
376
407
  return;
377
408
  case "pause":
378
- pauseGoal(ctx);
409
+ commands.pauseGoal(ctx);
379
410
  return;
380
411
  case "resume":
381
- await resumeGoal(runtime.pi, ctx);
412
+ await commands.resumeGoal(ctx);
382
413
  return;
383
414
  case "clear":
384
- clearGoal(ctx);
415
+ commands.clearGoal(ctx);
385
416
  return;
386
417
  case "edit":
387
- await editGoal(result.objective ?? "", result.tokenBudget, runtime.pi, ctx);
418
+ await commands.editGoal(result.objective ?? "", result.tokenBudget, ctx);
419
+ return;
420
+ case "add":
421
+ await commands.addGoal(result.objective ?? "", result.tokenBudget, ctx);
422
+ return;
423
+ case "prioritize":
424
+ await commands.prioritizeGoal(result.objective ?? "", result.tokenBudget, ctx);
425
+ return;
426
+ case "drop-last":
427
+ commands.dropLastGoal(ctx);
428
+ return;
429
+ case "skip":
430
+ await commands.skipGoal(ctx);
388
431
  return;
389
432
  case "start":
390
- await startGoal(result.objective ?? "", result.tokenBudget, runtime.pi, ctx);
433
+ await commands.startGoal(result.objective ?? "", result.tokenBudget, ctx);
391
434
  return;
392
435
  }
393
436
  },
394
437
  });
395
438
 
396
- pi.on("session_start", (_event, ctx) => {
439
+ pi.on("session_start", async (_event, ctx) => {
397
440
  clearCompletionStatusTimer();
398
441
  clearContinuationTracking();
442
+ clearPendingGoalPrompts();
443
+ runtime.agentRunGoalId = undefined;
399
444
  clearGoalRecovery();
400
445
  clearBudgetWrapUp();
401
446
  clearStaleGoalToolCallBlock();
402
- runtime.activeGoal = loadGoalFromSession(ctx);
447
+ runtime.queuedGoals = [];
448
+ runtime.pendingQueueAction = undefined;
449
+ runtime.queueFrozen = false;
450
+ const previousToolVisibility = runtime.settings.toolVisibility;
451
+ const settingsResult = readGoalSettings(options.settingsPath);
452
+ runtime.settings =
453
+ settingsResult.kind === "loaded" ? settingsResult.settings : DEFAULT_GOAL_SETTINGS;
454
+ if (settingsResult.kind === "invalid") {
455
+ ctx.ui.notify(
456
+ `pi-goal settings ignored: ${settingsResult.reason}. Using default settings.`,
457
+ "warning",
458
+ );
459
+ }
460
+ if (runtime.settings.experimental.goals) {
461
+ ctx.ui.notify(EXPERIMENTAL_GOALS_WARNING, "warning");
462
+ }
463
+ if (
464
+ runtime.settings.toolVisibility === "after-first-goal" &&
465
+ previousToolVisibility === "always"
466
+ ) {
467
+ runtime.goalToolsUnlocked = false;
468
+ }
469
+ if (runtime.settings.toolVisibility === "always") {
470
+ if (runtime.goalToolsHiddenByPolicy.size > 0) {
471
+ try {
472
+ restoreGoalToolsHiddenByPolicy();
473
+ } catch (error) {
474
+ ctx.ui.notify(
475
+ `Could not restore always-visible goal tools: ${formatError(error)}`,
476
+ "error",
477
+ );
478
+ }
479
+ }
480
+ runtime.goalToolsUnlocked = true;
481
+ }
482
+
483
+ const loaded = loadGoalStateFromSession(ctx);
484
+ runtime.activeGoal = loaded.goal;
485
+ runtime.queuedGoals = loaded.queue;
486
+ runtime.pendingQueueAction = loaded.pendingAction;
487
+ runtime.queueFrozen = loaded.hasExperimentalQueueState && !runtime.settings.experimental.goals;
488
+ if (runtime.queueFrozen) {
489
+ if (runtime.activeGoal) persistGoal(runtime.activeGoal);
490
+ ctx.ui.setStatus(STATUS_KEY, "queue off");
491
+ ctx.ui.notify(
492
+ "An experimental goal queue is frozen because experimental.goals is disabled. Re-enable it and run /reload to continue, or use /goal clear.",
493
+ "warning",
494
+ );
495
+ return;
496
+ }
497
+
498
+ let startRestoredQueuedGoal = false;
499
+ if (runtime.activeGoal?.status === "queued" && !runtime.pendingQueueAction) {
500
+ runtime.activeGoal = activateQueuedGoal(runtime.activeGoal, currentTokenTotal(ctx));
501
+ startRestoredQueuedGoal = true;
502
+ }
503
+ if (runtime.pendingQueueAction) await dispatchPendingQueueActionIfSettled(ctx);
403
504
  if (runtime.activeGoal) {
404
505
  if (runtime.activeGoal.status === "active") {
405
506
  updateGoalUsage(runtime.activeGoal, ctx);
406
507
  if (limitActiveGoalForBudget(ctx, false)) return;
407
508
  }
509
+ if (runtime.settings.toolVisibility === "after-first-goal") {
510
+ // Registered tools are already active on an unrestricted fresh runtime.
511
+ // If an earlier session_start handler removed them, that restrictive
512
+ // policy wins: mark lazy visibility unlocked without widening its set.
513
+ runtime.goalToolsUnlocked = true;
514
+ runtime.goalToolsHiddenByPolicy.clear();
515
+ }
516
+ if (runtime.activeGoal.status === "active" && !goalToolsAvailable()) {
517
+ pauseGoalForUnavailableTools(ctx, false);
518
+ return;
519
+ }
408
520
  persistGoal(runtime.activeGoal);
409
521
  updateStatus(ctx, runtime.activeGoal);
410
- } else ctx.ui.setStatus(STATUS_KEY, undefined);
522
+ if (startRestoredQueuedGoal) {
523
+ const restoredGoal = runtime.activeGoal;
524
+ const sent = await sendOwnedGoalPrompt(
525
+ runtime.pi,
526
+ ctx,
527
+ restoredGoal.id,
528
+ buildGoalPrompt(restoredGoal),
529
+ );
530
+ if (!sent && runtime.activeGoal?.id === restoredGoal.id) {
531
+ runtime.activeGoal = transitionGoal(restoredGoal, "paused");
532
+ blockStaleGoalToolCalls();
533
+ persistGoal(runtime.activeGoal);
534
+ updateStatus(ctx, runtime.activeGoal);
535
+ }
536
+ }
537
+ } else {
538
+ if (runtime.settings.toolVisibility === "after-first-goal" && !runtime.goalToolsUnlocked) {
539
+ hideGoalToolsIfLocked();
540
+ }
541
+ ctx.ui.setStatus(STATUS_KEY, undefined);
542
+ }
411
543
  });
412
544
 
413
545
  pi.on("session_shutdown", (_event, ctx) => {
414
546
  if (runtime.activeGoal) {
415
- updateGoalUsage(runtime.activeGoal, ctx, false);
547
+ if (!runtime.queueFrozen && runtime.activeGoal.status === "active") {
548
+ updateGoalUsage(runtime.activeGoal, ctx, false);
549
+ }
416
550
  persistGoal(runtime.activeGoal);
417
551
  }
418
552
  clearContinuationTracking();
553
+ clearPendingGoalPrompts();
554
+ runtime.agentRunGoalId = undefined;
419
555
  clearGoalRecovery();
420
556
  clearBudgetWrapUp();
421
557
  clearStaleGoalToolCallBlock();
558
+ runtime.activeGoal = undefined;
559
+ runtime.queuedGoals = [];
560
+ runtime.pendingQueueAction = undefined;
561
+ runtime.queueFrozen = false;
422
562
  ctx.ui.setStatus(STATUS_KEY, undefined);
423
563
  clearCompletionStatusTimer();
424
564
  });
425
565
 
426
566
  pi.on("session_before_compact", (event, ctx) => {
567
+ if (runtime.queueFrozen) return;
427
568
  if (runtime.activeGoal?.status === "budget_limited") {
428
569
  if ((event as { willRetry?: boolean }).willRetry === true) return { cancel: true as const };
429
570
  return;
@@ -433,20 +574,31 @@ function registerGoalRuntime(pi: ExtensionAPI) {
433
574
  cancelContinuationWork();
434
575
  persistGoal(runtime.activeGoal);
435
576
  updateStatus(ctx, runtime.activeGoal);
577
+ if (runtime.pendingQueueAction) return;
436
578
  if (limitActiveGoalForBudget(ctx, false)) return { cancel: true as const };
437
579
  });
438
580
 
439
- pi.on("session_compact", (event, ctx) => {
581
+ pi.on("session_compact", async (event, ctx) => {
582
+ if (runtime.queueFrozen) return;
440
583
  if (runtime.activeGoal?.status !== "active") {
441
584
  clearGoalRecovery();
585
+ if (runtime.pendingQueueAction) await dispatchPendingQueueActionIfSettled(ctx);
442
586
  return;
443
587
  }
444
588
 
445
- const restoredGoal = loadGoalFromSession(ctx);
446
- if (restoredGoal?.id === runtime.activeGoal.id) runtime.activeGoal = restoredGoal;
589
+ const restoredState = loadGoalStateFromSession(ctx);
590
+ if (restoredState.goal?.id === runtime.activeGoal.id) {
591
+ runtime.activeGoal = restoredState.goal;
592
+ runtime.queuedGoals = restoredState.queue;
593
+ runtime.pendingQueueAction = restoredState.pendingAction;
594
+ }
447
595
  updateGoalUsage(runtime.activeGoal, ctx);
448
596
  persistGoal(runtime.activeGoal);
449
597
  updateStatus(ctx, runtime.activeGoal);
598
+ if (runtime.pendingQueueAction) {
599
+ await dispatchPendingQueueActionIfSettled(ctx);
600
+ return;
601
+ }
450
602
  if (limitActiveGoalForBudget(ctx, false)) return;
451
603
 
452
604
  const wasPiRetry = isPiOwnedCompactionRetry(event, runtime.activeGoal.id);
@@ -460,6 +612,7 @@ function registerGoalRuntime(pi: ExtensionAPI) {
460
612
  });
461
613
 
462
614
  pi.on("input", (event) => {
615
+ if (runtime.queueFrozen) return;
463
616
  if (event.source === "extension") {
464
617
  if (consumeCancelledContinuationPrompt(event.text)) return { action: "handled" as const };
465
618
  return;
@@ -476,6 +629,14 @@ function registerGoalRuntime(pi: ExtensionAPI) {
476
629
  });
477
630
 
478
631
  pi.on("tool_call", (event, ctx) => {
632
+ if (runtime.queueFrozen) {
633
+ if (!isGoalToolName(event.toolName)) return;
634
+ return {
635
+ block: true,
636
+ reason:
637
+ "The experimental goal queue is frozen. Re-enable experimental.goals and run /reload, or use /goal clear.",
638
+ };
639
+ }
479
640
  if (
480
641
  runtime.activeGoal?.status === "budget_limited" &&
481
642
  runtime.budgetWrapUp?.goalId === runtime.activeGoal.id &&
@@ -501,6 +662,7 @@ function registerGoalRuntime(pi: ExtensionAPI) {
501
662
  });
502
663
 
503
664
  pi.on("tool_execution_end", (_event, ctx) => {
665
+ if (runtime.queueFrozen) return;
504
666
  if (
505
667
  runtime.activeGoal?.status === "budget_limited" &&
506
668
  runtime.budgetWrapUp?.goalId === runtime.activeGoal.id &&
@@ -516,12 +678,43 @@ function registerGoalRuntime(pi: ExtensionAPI) {
516
678
  updateGoalUsage(runtime.activeGoal, ctx);
517
679
  persistGoal(runtime.activeGoal);
518
680
  updateStatus(ctx, runtime.activeGoal);
519
- limitActiveGoalForBudget(ctx, true);
681
+ if (limitActiveGoalForBudget(ctx, true)) return;
682
+ if (!goalToolsAvailable()) pauseGoalForUnavailableTools(ctx);
520
683
  });
521
684
 
522
- pi.on("before_agent_start", (event) => {
523
- markContinuationStarted(event.prompt);
524
- if (runtime.activeGoal?.status !== "active") return;
685
+ pi.on("before_agent_start", (event, ctx) => {
686
+ if (runtime.queueFrozen) {
687
+ runtime.agentRunGoalId = undefined;
688
+ return;
689
+ }
690
+ const goalPromptGoalId = consumePendingGoalPrompt(event.prompt);
691
+ const continuationGoalId = goalPromptGoalId ? undefined : markContinuationStarted(event.prompt);
692
+ const ownedPromptGoalId = goalPromptGoalId ?? continuationGoalId;
693
+ if (
694
+ runtime.pendingQueueAction?.kind === "advance" &&
695
+ runtime.pendingQueueAction.goalId === runtime.activeGoal?.id
696
+ ) {
697
+ runtime.agentRunGoalId = ownedPromptGoalId ?? runtime.activeGoal.id;
698
+ if (ownedPromptGoalId) abortCurrentTurn(ctx);
699
+ return;
700
+ }
701
+ if (ownedPromptGoalId && ownedPromptGoalId !== runtime.activeGoal?.id) {
702
+ runtime.agentRunGoalId = ownedPromptGoalId;
703
+ if (runtime.activeGoal?.status === "active" && !goalToolsAvailable()) {
704
+ pauseGoalForUnavailableTools(ctx, false);
705
+ }
706
+ abortCurrentTurn(ctx);
707
+ return;
708
+ }
709
+ if (runtime.activeGoal?.status !== "active") {
710
+ runtime.agentRunGoalId = undefined;
711
+ return;
712
+ }
713
+ runtime.agentRunGoalId = runtime.activeGoal.id;
714
+ if (!goalToolsAvailable()) {
715
+ pauseGoalForUnavailableTools(ctx, ownedPromptGoalId !== undefined);
716
+ return;
717
+ }
525
718
 
526
719
  return {
527
720
  systemPrompt: `${event.systemPrompt}\n\n${buildGoalSystemPrompt(runtime.activeGoal)}`,
@@ -529,6 +722,10 @@ function registerGoalRuntime(pi: ExtensionAPI) {
529
722
  });
530
723
 
531
724
  pi.on("agent_end", (event, ctx) => {
725
+ if (runtime.queueFrozen) return;
726
+ const agentRunGoalId = runtime.agentRunGoalId;
727
+ runtime.agentRunGoalId = undefined;
728
+ if (agentRunGoalId && agentRunGoalId !== runtime.activeGoal?.id) return;
532
729
  if (!runtime.activeGoal) return;
533
730
  if (
534
731
  runtime.activeGoal.status === "budget_limited" &&
@@ -541,6 +738,15 @@ function registerGoalRuntime(pi: ExtensionAPI) {
541
738
  return;
542
739
  }
543
740
  if (runtime.activeGoal.status !== "active") return;
741
+ if (
742
+ runtime.pendingQueueAction?.kind === "advance" &&
743
+ runtime.pendingQueueAction.goalId === runtime.activeGoal.id
744
+ ) {
745
+ updateGoalUsage(runtime.activeGoal, ctx);
746
+ persistGoal(runtime.activeGoal);
747
+ updateStatus(ctx, runtime.activeGoal);
748
+ return;
749
+ }
544
750
 
545
751
  const goalId = runtime.activeGoal.id;
546
752
  const alreadyAwaitingContinuation = hasContinuationWorkForGoal(goalId);
@@ -558,6 +764,10 @@ function registerGoalRuntime(pi: ExtensionAPI) {
558
764
  if (finalAssistant?.stopReason === "error") {
559
765
  if (isRetryableGoalInterruption(finalAssistant)) {
560
766
  if (limitActiveGoalForBudget(ctx, false)) return;
767
+ if (!goalToolsAvailable()) {
768
+ pauseGoalForUnavailableTools(ctx);
769
+ return;
770
+ }
561
771
  runtime.goalRecovery = {
562
772
  goalId,
563
773
  kind: isGoalContextOverflow(finalAssistant) ? "compaction_retry" : "provider_retry",
@@ -580,245 +790,37 @@ function registerGoalRuntime(pi: ExtensionAPI) {
580
790
  clearGoalRecoveryForGoal(goalId);
581
791
 
582
792
  if (limitActiveGoalForBudget(ctx, false)) return;
793
+ if (!goalToolsAvailable()) {
794
+ pauseGoalForUnavailableTools(ctx);
795
+ return;
796
+ }
583
797
 
584
798
  persistGoal(runtime.activeGoal);
585
799
  updateStatus(ctx, runtime.activeGoal);
586
800
 
587
801
  const currentGoal = runtime.activeGoal;
588
802
  if (!currentGoal || currentGoal.id !== goalId || currentGoal.status !== "active") return;
803
+ if (runtime.pendingQueueAction?.kind === "prioritize") return;
589
804
  requestContinuation(currentGoal);
590
805
  });
591
806
 
592
807
  pi.on("agent_settled", (_event, ctx) => {
593
- dispatchContinuationIfSettled(ctx);
594
- });
595
-
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
- }
619
-
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",
653
- );
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
- );
666
- return;
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");
677
- }
678
-
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();
725
- }
726
- return;
727
- }
728
- ctx.ui.notify(
729
- `Goal resumed from ${stoppedStatusLabel(stoppedStatus)}: ${resumedGoal.text}`,
730
- "info",
731
- );
732
- }
733
-
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");
749
- }
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");
808
+ if (runtime.queueFrozen) return;
809
+ if (!runtime.pendingQueueAction) {
810
+ dispatchContinuationIfSettled(ctx);
764
811
  return;
765
812
  }
813
+ return dispatchPendingQueueActionIfSettled(ctx).then((dispatched) => {
814
+ if (!dispatched) dispatchContinuationIfSettled(ctx);
815
+ });
816
+ });
766
817
 
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),
818
+ function hasPendingSkipForGoal(goalId: string) {
819
+ return (
820
+ runtime.pendingQueueAction?.kind === "advance" &&
821
+ runtime.pendingQueueAction.reason === "skip" &&
822
+ runtime.pendingQueueAction.goalId === goalId
780
823
  );
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");
810
- }
811
-
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");
822
824
  }
823
825
 
824
826
  function stopGoalAfterAgentEnd(
@@ -857,509 +859,10 @@ function registerGoalRuntime(pi: ExtensionAPI) {
857
859
  "warning",
858
860
  );
859
861
  }
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;
871
- }
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
- }
900
- }
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;
939
- }
940
- return (
941
- typeof candidate.details?.goalId === "string" &&
942
- candidate.details.goalId === runtime.budgetWrapUp?.goalId &&
943
- candidate.details.goalId === runtime.activeGoal?.id
944
- );
945
- }
946
-
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
-
981
- cancelContinuationWork();
982
- clearGoalRecoveryForGoal(goal.id);
983
- clearBudgetWrapUp();
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;
990
- }
991
-
992
- function clearGoalRecoveryForGoal(goalId: string) {
993
- if (runtime.goalRecovery?.goalId === goalId) runtime.goalRecovery = undefined;
994
- }
995
-
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
- );
1004
- }
1005
-
1006
- function clearContinuationTracking() {
1007
- runtime.continuationIntent = undefined;
1008
- runtime.continuationDelivery = undefined;
1009
- runtime.cancelledContinuationMarkers.clear();
1010
- }
1011
-
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();
1038
- return;
1039
- }
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 });
1045
- }
1046
-
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);
1059
- ctx.ui.setStatus(STATUS_KEY, undefined);
1060
- }
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
- }
1081
- }
1082
-
1083
- function createGoal(
1084
- text: string,
1085
- tokenBudget: number | undefined,
1086
- baselineTokens: number,
1087
- ): ActiveGoal {
1088
- const now = Date.now();
1089
- return {
1090
- id: randomUUID(),
1091
- text,
1092
- status: "active",
1093
- startedAt: now,
1094
- updatedAt: now,
1095
- iteration: 0,
1096
- tokenBudget,
1097
- tokensUsed: 0,
1098
- timeUsedSeconds: 0,
1099
- baselineTokens,
1100
- activeStartedAt: now,
1101
- };
1102
- }
1103
-
1104
- function transitionGoal(goal: ActiveGoal, requestedStatus: GoalStatus): ActiveGoal {
1105
- const now = Date.now();
1106
- const status =
1107
- requestedStatus === "active" &&
1108
- goal.tokenBudget !== undefined &&
1109
- goal.tokensUsed >= goal.tokenBudget
1110
- ? "budget_limited"
1111
- : requestedStatus;
1112
- const next = { ...goal, status, updatedAt: now };
1113
- checkpointGoalActiveTime(next, now, status === "active");
1114
- return next;
1115
- }
1116
-
1117
- function nextGoalInstance(goal: ActiveGoal): ActiveGoal {
1118
- return { ...goal, id: randomUUID(), updatedAt: Date.now() };
1119
- }
1120
-
1121
- function editedGoalStatus(status: GoalStatus): GoalStatus {
1122
- if (status === "paused" || status === "blocked" || status === "usage_limited") return status;
1123
- return "active";
1124
- }
1125
-
1126
- function incrementGoal(goal: ActiveGoal): ActiveGoal {
1127
- return { ...goal, iteration: goal.iteration + 1, updatedAt: Date.now() };
1128
- }
1129
-
1130
- async function sendGoalPrompt(pi: ExtensionAPI, ctx: StatusContext, goal: ActiveGoal) {
1131
- return sendPrompt(pi, ctx, buildGoalPrompt(goal));
1132
- }
1133
-
1134
- async function sendObjectiveUpdatedPrompt(pi: ExtensionAPI, ctx: StatusContext, goal: ActiveGoal) {
1135
- return sendPrompt(pi, ctx, buildObjectiveUpdatedPrompt(goal));
1136
- }
1137
-
1138
- async function sendResumePrompt(
1139
- pi: ExtensionAPI,
1140
- ctx: StatusContext,
1141
- goal: ActiveGoal,
1142
- stoppedStatus: GoalStatus,
1143
- ) {
1144
- return sendPrompt(pi, ctx, buildResumePrompt(goal, stoppedStatus));
1145
- }
1146
-
1147
- async function sendPrompt(pi: ExtensionAPI, ctx: StatusContext, prompt: string) {
1148
- try {
1149
- const sent = ctx.isIdle?.()
1150
- ? (pi.sendUserMessage(prompt) as void | Promise<void>)
1151
- : (pi.sendUserMessage(prompt, { deliverAs: "followUp" }) as void | Promise<void>);
1152
- await sent;
1153
- return true;
1154
- } catch (error) {
1155
- ctx.ui.notify(`Goal prompt failed: ${formatError(error)}`, "error");
1156
- return false;
1157
- }
1158
- }
1159
-
1160
- export function formatStatus(goal: ActiveGoal | undefined) {
1161
- if (!goal) return undefined;
1162
- if (goal.status === "complete") return "complete";
1163
- if (goal.status === "paused") return "paused";
1164
- if (goal.status === "blocked") return "blocked";
1165
- if (goal.status === "usage_limited") return "usage";
1166
- if (goal.status === "budget_limited") return `budget ${formatBudget(goal)}`;
1167
- if (goal.tokenBudget !== undefined) return `active ${formatBudget(goal)}`;
1168
- return `active ${formatDuration(goal.timeUsedSeconds)}`;
1169
- }
1170
-
1171
- function formatBudget(goal: ActiveGoal) {
1172
- return `${formatTokenCount(goal.tokensUsed)}/${formatTokenCount(goal.tokenBudget ?? 0)}`;
1173
- }
1174
-
1175
- function goalSummary(goal: ActiveGoal) {
1176
- return [
1177
- `Goal: ${goal.text}`,
1178
- `Status: ${goal.status}`,
1179
- `Iteration: ${goal.iteration}`,
1180
- `Active elapsed: ${formatDuration(goal.timeUsedSeconds)}`,
1181
- `Tokens: ${goal.tokenBudget === undefined ? formatTokenCount(goal.tokensUsed) : formatBudget(goal)}`,
1182
- `Commands: ${goalCommandHint(goal.status)}`,
1183
- ].join("\n");
1184
- }
1185
-
1186
- function goalCommandHint(status: GoalStatus) {
1187
- if (status === "active") return "/goal edit <objective>, /goal pause, /goal clear";
1188
- if (isResumableGoalStatus(status)) {
1189
- return "/goal edit <objective>, /goal resume, /goal clear";
1190
- }
1191
- return "/goal edit <objective>, /goal clear";
1192
- }
1193
-
1194
- function hasPendingMessages(ctx: StatusContext) {
1195
- return ctx.hasPendingMessages?.() ?? false;
1196
- }
1197
-
1198
- function abortCurrentTurn(ctx: StatusContext) {
1199
- try {
1200
- ctx.abort?.();
1201
- } catch {
1202
- // Best effort: stale goal guards still prevent follow-on tool calls.
1203
- }
1204
- }
1205
-
1206
- function blocksStaleGoalToolCalls(status: GoalStatus) {
1207
- return status === "paused" || status === "blocked" || status === "usage_limited";
1208
- }
1209
-
1210
- function isResumableGoalStatus(status: GoalStatus) {
1211
- return blocksStaleGoalToolCalls(status) || status === "budget_limited";
1212
- }
1213
-
1214
- function stoppedStatusLabel(status: GoalStatus) {
1215
- if (status === "usage_limited") return "usage-limited";
1216
- if (status === "budget_limited") return "budget-limited";
1217
- return status;
1218
- }
1219
-
1220
- export function isContradictoryCompletionSummary(summary: string) {
1221
- return CONTRADICTORY_COMPLETION_PATTERNS.some((pattern) => pattern.test(summary));
1222
- }
1223
-
1224
- function goalIdRejectionReason(goal: ActiveGoal, requestedGoalId: string) {
1225
- if (!requestedGoalId) return "missing goal_id";
1226
- if (requestedGoalId !== goal.id) return "goal_id does not match the active goal";
1227
- return undefined;
1228
- }
1229
-
1230
- export function isUsageLimitedGoalInterruption(assistant: AssistantMessageLike) {
1231
- const errorMessage = assistant.errorMessage;
1232
- return (
1233
- assistant.stopReason === "error" &&
1234
- typeof errorMessage === "string" &&
1235
- USAGE_LIMIT_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(errorMessage))
1236
- );
1237
- }
1238
-
1239
- export function isRetryableGoalInterruption(assistant: AssistantMessageLike) {
1240
- if (assistant.stopReason !== "error") return false;
1241
- if (!assistant.errorMessage) return false;
1242
- if (
1243
- isUsageLimitedGoalInterruption(assistant) ||
1244
- NON_RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage)
1245
- ) {
1246
- return false;
1247
- }
1248
- return (
1249
- isGoalContextOverflow(assistant) ||
1250
- RETRYABLE_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(assistant.errorMessage ?? ""))
1251
- );
1252
- }
1253
-
1254
- function isGoalContextOverflow(assistant: AssistantMessageLike) {
1255
- return isContextOverflow(toPiAssistantMessage(assistant));
1256
862
  }
1257
863
 
1258
- function toPiAssistantMessage(assistant: AssistantMessageLike): PiAssistantMessage {
1259
- return {
1260
- role: "assistant",
1261
- content: assistant.content ?? [],
1262
- api: assistant.api ?? "openai-responses",
1263
- provider: assistant.provider ?? "unknown",
1264
- model: assistant.model ?? "unknown",
1265
- usage: assistant.usage ?? zeroUsage(),
1266
- stopReason: assistant.stopReason ?? "error",
1267
- errorMessage: assistant.errorMessage,
1268
- timestamp: assistant.timestamp ?? Date.now(),
1269
- };
1270
- }
1271
-
1272
- function zeroUsage(): Usage {
1273
- return {
1274
- input: 0,
1275
- output: 0,
1276
- cacheRead: 0,
1277
- cacheWrite: 0,
1278
- totalTokens: 0,
1279
- cost: {
1280
- input: 0,
1281
- output: 0,
1282
- cacheRead: 0,
1283
- cacheWrite: 0,
1284
- total: 0,
1285
- },
1286
- };
1287
- }
1288
-
1289
- function continuationMarker(goal: ActiveGoal) {
1290
- return `${goal.id}:${goal.iteration}:${randomUUID()}`;
1291
- }
1292
-
1293
- function escapeRegExpText(value: string) {
1294
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1295
- }
1296
-
1297
- const CONTINUATION_MARKER_PATTERN = new RegExp(
1298
- `<!--\\s*${escapeRegExpText(CONTINUATION_MARKER_PREFIX)}([^\\s>]+)\\s*-->`,
1299
- );
1300
-
1301
- function extractContinuationMarker(prompt: string) {
1302
- return CONTINUATION_MARKER_PATTERN.exec(prompt)?.[1];
1303
- }
1304
-
1305
- export function findFinalAssistantMessage(messages: unknown[]): AssistantMessageLike | undefined {
1306
- for (let i = messages.length - 1; i >= 0; i--) {
1307
- const message = messages[i];
1308
- if (!message || typeof message !== "object") continue;
1309
- const candidate = message as Record<string, unknown>;
1310
- if (candidate.role !== "assistant") continue;
1311
- const assistant: AssistantMessageLike = {
1312
- role: "assistant",
1313
- stopReason: isAgentStopReason(candidate.stopReason) ? candidate.stopReason : undefined,
1314
- errorMessage: typeof candidate.errorMessage === "string" ? candidate.errorMessage : undefined,
1315
- };
1316
- if (Array.isArray(candidate.content))
1317
- assistant.content = candidate.content as PiAssistantMessage["content"];
1318
- if (typeof candidate.api === "string") assistant.api = candidate.api;
1319
- if (typeof candidate.provider === "string") assistant.provider = candidate.provider;
1320
- if (typeof candidate.model === "string") assistant.model = candidate.model;
1321
- if (typeof candidate.timestamp === "number") assistant.timestamp = candidate.timestamp;
1322
- const usage = normalizeUsage(candidate.usage);
1323
- if (usage) assistant.usage = usage;
1324
- return assistant;
1325
- }
1326
- return undefined;
1327
- }
1328
-
1329
- function isAgentStopReason(value: unknown): value is AgentStopReason {
1330
- return ["stop", "length", "toolUse", "error", "aborted"].includes(String(value));
1331
- }
1332
-
1333
- function normalizeUsage(value: unknown): Usage | undefined {
1334
- if (!value || typeof value !== "object") return undefined;
1335
- const usage = value as Partial<Usage>;
1336
- if (typeof usage.input !== "number" || typeof usage.output !== "number") return undefined;
1337
- return {
1338
- input: nonNegativeFiniteNumber(usage.input),
1339
- output: nonNegativeFiniteNumber(usage.output),
1340
- cacheRead: nonNegativeFiniteNumber(usage.cacheRead),
1341
- cacheWrite: nonNegativeFiniteNumber(usage.cacheWrite),
1342
- totalTokens: assistantUsageTokens(usage),
1343
- cost: {
1344
- input: usage.cost?.input ?? 0,
1345
- output: usage.cost?.output ?? 0,
1346
- cacheRead: usage.cost?.cacheRead ?? 0,
1347
- cacheWrite: usage.cost?.cacheWrite ?? 0,
1348
- total: usage.cost?.total ?? 0,
1349
- },
1350
- };
1351
- }
1352
-
1353
- function formatError(error: unknown) {
1354
- return truncateNotification(error instanceof Error ? error.message : String(error));
1355
- }
1356
-
1357
- function truncateNotification(value: string) {
1358
- return value.length > 160 ? `${value.slice(0, 157)}...` : value;
1359
- }
1360
-
1361
- export default function goal(pi: ExtensionAPI) {
1362
- registerGoalRuntime(pi);
864
+ export default function goal(pi: ExtensionAPI, options: GoalOptions = {}) {
865
+ registerGoalRuntime(pi, options);
1363
866
  }
1364
867
 
1365
868
  export {
@@ -1377,3 +880,11 @@ export {
1377
880
  } from "./command.js";
1378
881
 
1379
882
  export { buildGoalSystemPrompt } from "./prompts.js";
883
+
884
+ export {
885
+ findFinalAssistantMessage,
886
+ formatStatus,
887
+ isContradictoryCompletionSummary,
888
+ isRetryableGoalInterruption,
889
+ isUsageLimitedGoalInterruption,
890
+ } from "./runtime.js";