@narumitw/pi-goal 0.54.3 → 0.54.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +117 -190
  2. package/dist/chunks/{chunk-QWIUWKRW.js → chunk-VJ5LR26S.js} +57 -77
  3. package/dist/chunks/chunk-VJ5LR26S.js.map +7 -0
  4. package/dist/chunks/{chunk-UQRRW4CY.js → chunk-WQIA35U2.js} +6 -5
  5. package/dist/chunks/chunk-WQIA35U2.js.map +7 -0
  6. package/dist/chunks/{menu-WEFDREGC.js → menu-JMGWQZIT.js} +7 -22
  7. package/dist/chunks/menu-JMGWQZIT.js.map +7 -0
  8. package/dist/chunks/{settings-ui-MVYTTBHW.js → settings-ui-JG3PFRB5.js} +6 -18
  9. package/dist/chunks/settings-ui-JG3PFRB5.js.map +7 -0
  10. package/dist/index.ts +111 -126
  11. package/dist/index.ts.map +2 -2
  12. package/docs/managing-goals.md +47 -0
  13. package/docs/settings.md +91 -0
  14. package/package.json +55 -58
  15. package/src/accounting.ts +62 -66
  16. package/src/command-registration.ts +104 -102
  17. package/src/command.ts +101 -112
  18. package/src/commands.ts +465 -501
  19. package/src/errors.ts +127 -122
  20. package/src/goal-contract.ts +64 -64
  21. package/src/goal.ts +25 -25
  22. package/src/lifecycle.ts +615 -628
  23. package/src/markers.ts +6 -6
  24. package/src/menu.ts +565 -591
  25. package/src/persistence.ts +177 -192
  26. package/src/prompts.ts +53 -67
  27. package/src/run-protocol.ts +299 -325
  28. package/src/runtime.ts +1422 -1495
  29. package/src/safety.ts +51 -51
  30. package/src/settings-ui.ts +366 -393
  31. package/src/settings.ts +134 -147
  32. package/src/tool-policy.ts +6 -6
  33. package/src/tools.ts +371 -347
  34. package/src/wait.ts +47 -51
  35. package/src/workflow-mutex.ts +68 -68
  36. package/dist/chunks/chunk-QWIUWKRW.js.map +0 -7
  37. package/dist/chunks/chunk-UQRRW4CY.js.map +0 -7
  38. package/dist/chunks/menu-WEFDREGC.js.map +0 -7
  39. package/dist/chunks/settings-ui-MVYTTBHW.js.map +0 -7
package/src/runtime.ts CHANGED
@@ -1,62 +1,49 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
+ import { checkpointGoalActiveTime, formatDuration, formatTokenCount, updateGoalUsage } from "./accounting.js";
4
+ import { formatError, isStaleContextError, notifyTerminal, safeGoalMenuText, truncateNotification } from "./errors.js";
3
5
  import {
4
- checkpointGoalActiveTime,
5
- formatDuration,
6
- formatTokenCount,
7
- updateGoalUsage,
8
- } from "./accounting.js";
9
- import { formatError, notifyTerminal, safeGoalMenuText, truncateNotification } from "./errors.js";
10
- import {
11
- createGoalContextContract,
12
- createInactiveGoalContextContract,
13
- hasGoalContextContract,
14
- hasGoalContextContractHistory,
15
- hasInactiveGoalContextContract,
6
+ createGoalContextContract,
7
+ createInactiveGoalContextContract,
8
+ hasGoalContextContract,
9
+ hasGoalContextContractHistory,
10
+ hasInactiveGoalContextContract,
16
11
  } from "./goal-contract.js";
12
+ import { appendGoalPromptMarker, extractContinuationMarker, extractGoalPromptMarker } from "./markers.js";
17
13
  import {
18
- appendGoalPromptMarker,
19
- extractContinuationMarker,
20
- extractGoalPromptMarker,
21
- } from "./markers.js";
22
- import {
23
- type ActiveGoal,
24
- clearLegacyPersistedGoal,
25
- type LegacyQueueState,
26
- type SafetyPauseCause,
27
- serializeGoalState,
14
+ type ActiveGoal,
15
+ clearLegacyPersistedGoal,
16
+ type LegacyQueueState,
17
+ type SafetyPauseCause,
18
+ serializeGoalState,
28
19
  } from "./persistence.js";
29
20
  import { buildContinuePrompt, type GoalStatus } from "./prompts.js";
30
21
  import { nextToolFreeRepeatState, resetGoalSafetyEpoch } from "./safety.js";
31
22
 
32
23
  export { queueGoalSafetyReset, resetGoalSafetyEpoch } from "./safety.js";
33
24
 
34
- import {
35
- DEFAULT_GOAL_SETTINGS,
36
- type GoalSettings,
37
- type GoalSettingsLoadIssue,
38
- } from "./settings.js";
25
+ import { DEFAULT_GOAL_SETTINGS, type GoalSettings, type GoalSettingsLoadIssue } from "./settings.js";
39
26
  import { assertGoalToolsAvailable, goalToolsAvailable } from "./tool-policy.js";
40
27
  import { type GoalWait, GoalWaitTimer } from "./wait.js";
41
28
  import { WorkflowMutex, type WorkflowMutexOwner } from "./workflow-mutex.js";
42
29
 
43
30
  export {
44
- GOAL_BLOCKED_TOOL,
45
- GOAL_COMPLETE_TOOL,
46
- GOAL_TOOL_NAMES,
47
- GOAL_WAIT_TOOL,
31
+ GOAL_BLOCKED_TOOL,
32
+ GOAL_COMPLETE_TOOL,
33
+ GOAL_TOOL_NAMES,
34
+ GOAL_WAIT_TOOL,
48
35
  } from "./tool-policy.js";
49
36
 
50
37
  export interface ContinuationTicket {
51
- goalId: string;
52
- iteration: number;
53
- marker: string;
54
- prompt: string;
38
+ goalId: string;
39
+ iteration: number;
40
+ marker: string;
41
+ prompt: string;
55
42
  }
56
43
 
57
44
  export interface BudgetWrapUp {
58
- goalId: string;
59
- delivered: boolean;
45
+ goalId: string;
46
+ delivered: boolean;
60
47
  }
61
48
 
62
49
  export type GoalRecoveryKind = "provider_retry" | "compaction_retry";
@@ -64,63 +51,63 @@ export type GoalRecoveryKind = "provider_retry" | "compaction_retry";
64
51
  export type GoalRunOrigin = "manual" | "automatic";
65
52
 
66
53
  export interface GoalRecovery {
67
- goalId: string;
68
- kind: GoalRecoveryKind;
69
- automaticOwner: boolean;
70
- errorMessage?: string;
54
+ goalId: string;
55
+ kind: GoalRecoveryKind;
56
+ automaticOwner: boolean;
57
+ errorMessage?: string;
71
58
  }
72
59
 
73
60
  export interface CompletedGoalRun {
74
- goalId?: string | null;
75
- origin?: GoalRunOrigin;
76
- toolAttempted: boolean;
61
+ goalId?: string | null;
62
+ origin?: GoalRunOrigin;
63
+ toolAttempted: boolean;
77
64
  }
78
65
 
79
66
  type StoppedGoalStatus = "paused" | "blocked" | "usage_limited" | "budget_limited";
80
67
 
81
68
  export type GoalStopRequest =
82
- | { kind: "explicit_pause"; expectedGoalId: string }
83
- | { kind: "budget_limit"; expectedGoalId: string; reason: string }
84
- | {
85
- kind: "safety_pause";
86
- expectedGoalId: string;
87
- cause: SafetyPauseCause;
88
- abortTurn: boolean;
89
- reason: string;
90
- }
91
- | { kind: "retry_exhausted"; expectedGoalId: string; reason: string }
92
- | {
93
- kind: "tools_unavailable";
94
- expectedGoalId: string;
95
- abortTurn: boolean;
96
- recordUsage: boolean;
97
- }
98
- | { kind: "blocker_report"; expectedGoalId: string; reason: string }
99
- | {
100
- kind: "agent_interruption";
101
- expectedGoalId: string;
102
- status: "paused" | "blocked" | "usage_limited";
103
- reason: string;
104
- }
105
- | {
106
- kind: "activation_rollback";
107
- expectedGoalId: string;
108
- restoreGoal: ActiveGoal;
109
- abortTurn: boolean;
110
- };
69
+ | { kind: "explicit_pause"; expectedGoalId: string }
70
+ | { kind: "budget_limit"; expectedGoalId: string; reason: string }
71
+ | {
72
+ kind: "safety_pause";
73
+ expectedGoalId: string;
74
+ cause: SafetyPauseCause;
75
+ abortTurn: boolean;
76
+ reason: string;
77
+ }
78
+ | { kind: "retry_exhausted"; expectedGoalId: string; reason: string }
79
+ | {
80
+ kind: "tools_unavailable";
81
+ expectedGoalId: string;
82
+ abortTurn: boolean;
83
+ recordUsage: boolean;
84
+ }
85
+ | { kind: "blocker_report"; expectedGoalId: string; reason: string }
86
+ | {
87
+ kind: "agent_interruption";
88
+ expectedGoalId: string;
89
+ status: "paused" | "blocked" | "usage_limited";
90
+ reason: string;
91
+ }
92
+ | {
93
+ kind: "activation_rollback";
94
+ expectedGoalId: string;
95
+ restoreGoal: ActiveGoal;
96
+ abortTurn: boolean;
97
+ };
111
98
 
112
99
  export interface StatusContext {
113
- cwd: string;
114
- mode?: "tui" | "rpc" | "json" | "print";
115
- ui: {
116
- confirm: (title: string, message: string) => Promise<boolean>;
117
- notify: (message: string, level?: "info" | "warning" | "error") => void;
118
- setStatus: (key: string, value: string | undefined) => void;
119
- };
120
- isIdle?: () => boolean;
121
- hasPendingMessages?: () => boolean;
122
- abort?: () => void;
123
- sessionManager?: unknown;
100
+ cwd: string;
101
+ mode?: "tui" | "rpc" | "json" | "print";
102
+ ui: {
103
+ confirm: (title: string, message: string) => Promise<boolean>;
104
+ notify: (message: string, level?: "info" | "warning" | "error") => void;
105
+ setStatus: (key: string, value: string | undefined) => void;
106
+ };
107
+ isIdle?: () => boolean;
108
+ hasPendingMessages?: () => boolean;
109
+ abort?: () => void;
110
+ sessionManager?: unknown;
124
111
  }
125
112
 
126
113
  export const STATUS_KEY = "goal";
@@ -131,62 +118,62 @@ export const MAX_GOAL_ID_LENGTH = 128;
131
118
  export type GoalStateSnapshotStatus = GoalStatus | "cleared";
132
119
 
133
120
  export interface GoalStateSnapshot {
134
- goalId: string;
135
- status: GoalStateSnapshotStatus;
136
- summary?: string;
137
- reason?: string;
121
+ goalId: string;
122
+ status: GoalStateSnapshotStatus;
123
+ summary?: string;
124
+ reason?: string;
138
125
  }
139
126
 
140
127
  /** Terminal statuses for Goal persistence and managed-run lifecycle publication. */
141
128
  export function isTerminalGoalStatus(status: GoalStateSnapshotStatus): boolean {
142
- return status !== "active" && status !== "queued";
129
+ return status !== "active";
143
130
  }
144
131
 
145
132
  function buildGoalStateSnapshot(
146
- goal: ActiveGoal,
147
- summary: string | undefined,
148
- reason: string | undefined,
133
+ goal: ActiveGoal,
134
+ summary: string | undefined,
135
+ reason: string | undefined,
149
136
  ): GoalStateSnapshot {
150
- const snapshot: GoalStateSnapshot = { goalId: goal.id, status: goal.status };
151
- if (goal.status === "complete" && summary) snapshot.summary = summary;
152
- else if (goal.status !== "complete" && isTerminalGoalStatus(goal.status) && reason) {
153
- snapshot.reason = reason;
154
- }
155
- return snapshot;
137
+ const snapshot: GoalStateSnapshot = { goalId: goal.id, status: goal.status };
138
+ if (goal.status === "complete" && summary) snapshot.summary = summary;
139
+ else if (goal.status !== "complete" && isTerminalGoalStatus(goal.status) && reason) {
140
+ snapshot.reason = reason;
141
+ }
142
+ return snapshot;
156
143
  }
157
144
 
158
145
  interface GoalTerminalDetails {
159
- goalId: string;
160
- summary?: string;
161
- reason?: string;
146
+ goalId: string;
147
+ summary?: string;
148
+ reason?: string;
162
149
  }
163
150
 
164
151
  export interface GoalSettingsRuntimeSnapshot {
165
- settings: GoalSettings;
166
- activeGoal?: ActiveGoal;
167
- legacyQueueState?: LegacyQueueState;
168
- legacyExperimentalGoalsSetting: boolean;
169
- continuationIntent?: ContinuationTicket;
170
- continuationDelivery?: ContinuationTicket;
171
- goalRecovery?: GoalRecovery;
172
- budgetWrapUp?: BudgetWrapUp;
173
- guardAbortGoalId?: string;
174
- staleGoalToolCallsBlocked: boolean;
175
- cancelledContinuationMarkers: Array<[string, string]>;
176
- terminalDetails?: GoalTerminalDetails;
152
+ settings: GoalSettings;
153
+ activeGoal?: ActiveGoal;
154
+ legacyQueueState?: LegacyQueueState;
155
+ legacyExperimentalGoalsSetting: boolean;
156
+ continuationIntent?: ContinuationTicket;
157
+ continuationDelivery?: ContinuationTicket;
158
+ goalRecovery?: GoalRecovery;
159
+ budgetWrapUp?: BudgetWrapUp;
160
+ guardAbortGoalId?: string;
161
+ staleGoalToolCallsBlocked: boolean;
162
+ cancelledContinuationMarkers: [string, string][];
163
+ terminalDetails?: GoalTerminalDetails;
177
164
  }
178
165
 
179
166
  interface PendingGoalPrompt {
180
- goalId: string;
181
- resetSafetyEpoch: boolean;
182
- fingerprint: string;
183
- prompt: string;
167
+ goalId: string;
168
+ resetSafetyEpoch: boolean;
169
+ fingerprint: string;
170
+ prompt: string;
184
171
  }
185
172
 
186
173
  interface PendingNonGoalInput {
187
- behavior: "steer" | "followUp";
188
- fingerprint: string;
189
- resetSafetyEpoch: boolean;
174
+ behavior: "steer" | "followUp";
175
+ fingerprint: string;
176
+ resetSafetyEpoch: boolean;
190
177
  }
191
178
 
192
179
  const MAX_CANCELLED_CONTINUATION_PROMPTS = 20;
@@ -194,1453 +181,1393 @@ const MAX_PENDING_GOAL_PROMPTS = 20;
194
181
  const MAX_PENDING_NON_GOAL_INPUTS = 20;
195
182
  const BUDGET_WRAP_UP_MESSAGE_TYPE = "goal-budget-wrap-up";
196
183
  const BUDGET_WRAP_UP_PROMPT =
197
- "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.";
184
+ "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.";
198
185
  const CONTRADICTORY_COMPLETION_PATTERNS = [
199
- /(?<!could\s)\bnot\s+(?:yet\s+)?(?:complete|completed|done|finished)\b/i,
200
- /\bstill\s+(?:incomplete|failing|failing\s+tests?|fails?)\b/i,
201
- /\btests?\s+(?:still\s+)?fail(?:ing)?\b/i,
186
+ /(?<!could\s)\bnot\s+(?:yet\s+)?(?:complete|completed|done|finished)\b/i,
187
+ /\bstill\s+(?:incomplete|failing|failing\s+tests?|fails?)\b/i,
188
+ /\btests?\s+(?:still\s+)?fail(?:ing)?\b/i,
202
189
  ] as const;
203
190
  // One instance belongs to one extension factory. It owns all mutable session state
204
191
  // and the cross-cutting invariants used by command and lifecycle orchestration.
205
192
  // Keep this state machine cohesive despite its size: prompt ownership, continuation,
206
- // budget, safety, external-wait, and queue transitions share ordering-sensitive invariants.
193
+ // budget, safety, and external-wait transitions share ordering-sensitive invariants.
207
194
  // Tool availability and generic wait-timer mechanics are delegated to focused collaborators.
208
- // Cohesion justification: Goal transitions, continuation and wait ownership, queue state, and
209
- // budget/retry recovery share one generation-guarded runtime; separating them further would
195
+ // Cohesion justification: Goal transitions, continuation and wait ownership, and budget/retry
196
+ // recovery share one generation-guarded runtime; separating them further would
210
197
  // duplicate stale-turn, timer, and persistence invariants across modules.
211
198
  export class GoalRuntime {
212
- settings: GoalSettings = DEFAULT_GOAL_SETTINGS;
213
- settingsLoadIssue?: GoalSettingsLoadIssue;
214
- activeGoal?: ActiveGoal;
215
- /** Terminal details captured for the matching persisted-state snapshot. */
216
- private terminalDetails?: GoalTerminalDetails;
217
- private goalStateSink?: (snapshot: GoalStateSnapshot) => void;
218
- legacyQueueState?: LegacyQueueState;
219
- legacyExperimentalGoalsSetting = false;
220
- completionStatusTimer?: NodeJS.Timeout;
221
- private continuationDispatchTimer?: NodeJS.Timeout;
222
- private readonly goalWaitTimer = new GoalWaitTimer();
223
- private goalWaitDeadlineRetry?: {
224
- goalId: string;
225
- resumeAt: number;
226
- retryAt?: number;
227
- exhausted: boolean;
228
- };
229
- continuationIntent?: ContinuationTicket;
230
- continuationDelivery?: ContinuationTicket;
231
- goalRecovery?: GoalRecovery;
232
- budgetWrapUp?: BudgetWrapUp;
233
- /** `null` marks a run that must not be charged to the active goal. */
234
- agentRunGoalId?: string | null;
235
- agentRunOrigin?: GoalRunOrigin;
236
- agentRunToolAttempted = false;
237
- guardAbortGoalId?: string;
238
- staleGoalToolCallsBlocked = false;
239
- private readonly workflowMutex: WorkflowMutex;
240
- private workflowOwner?: WorkflowMutexOwner;
241
- private workflowSession?: object;
242
- pendingGoalPromptMarkers = new Map<string, PendingGoalPrompt>();
243
- claimedGoalPromptMarkers = new Map<string, string>();
244
- cancelledGoalPromptMarkers = new Map<string, string>();
245
- cancelledContinuationMarkers = new Map<string, string>();
246
- claimedContinuationMarkers = new Map<string, string>();
247
- pendingNonGoalInputs: PendingNonGoalInput[] = [];
248
- menuGeneration = 0;
249
- menuController = new AbortController();
250
-
251
- readonly pi: ExtensionAPI;
252
-
253
- constructor(pi: ExtensionAPI) {
254
- this.pi = pi;
255
- this.workflowMutex = new WorkflowMutex(pi);
256
- }
257
-
258
- goalToolsAvailable() {
259
- return goalToolsAvailable(this.pi);
260
- }
261
-
262
- assertGoalToolsAvailable() {
263
- assertGoalToolsAvailable(this.pi);
264
- }
265
-
266
- bindWorkflowSession(session: object) {
267
- this.workflowSession = session;
268
- this.workflowOwner = undefined;
269
- this.workflowMutex.bindSession(session);
270
- }
271
-
272
- unbindWorkflowSession(session: object) {
273
- if (this.workflowSession !== session) return;
274
- this.workflowMutex.unbindSession(session);
275
- this.workflowOwner = undefined;
276
- this.workflowSession = undefined;
277
- }
278
-
279
- acquireWorkflow(session?: unknown) {
280
- if (session && typeof session === "object" && this.workflowSession !== session) {
281
- this.bindWorkflowSession(session);
282
- }
283
- if (this.workflowMutex.isOwner(this.workflowOwner)) return true;
284
- const owner = this.workflowMutex.acquire();
285
- if (!owner) return false;
286
- this.workflowOwner = owner;
287
- return true;
288
- }
289
-
290
- ownsWorkflow(goal: ActiveGoal | undefined = this.activeGoal) {
291
- return goal?.status === "active" && this.workflowMutex.isOwner(this.workflowOwner);
292
- }
293
-
294
- releaseWorkflow() {
295
- const owner = this.workflowOwner;
296
- this.workflowMutex.release(owner);
297
- if (!this.workflowMutex.isOwner(owner)) this.workflowOwner = undefined;
298
- }
299
-
300
- hasLegacyQueueInterface() {
301
- return this.legacyExperimentalGoalsSetting || this.legacyQueueState !== undefined;
302
- }
303
-
304
- setGoalStateSink(sink: ((snapshot: GoalStateSnapshot) => void) | undefined) {
305
- this.goalStateSink = sink;
306
- }
307
-
308
- private publishGoalState(snapshot: GoalStateSnapshot) {
309
- try {
310
- this.goalStateSink?.(snapshot);
311
- } catch {
312
- // Protocol publication must not interrupt canonical Goal persistence.
313
- }
314
- }
315
-
316
- replaceMenuSession() {
317
- this.menuGeneration += 1;
318
- this.menuController.abort(new DOMException("Goal session replaced", "AbortError"));
319
- this.menuController = new AbortController();
320
- }
321
-
322
- closeMenuSession() {
323
- this.menuGeneration += 1;
324
- this.menuController.abort(new DOMException("Goal session shut down", "AbortError"));
325
- }
326
-
327
- canRecordGoalUsage(goalId?: string) {
328
- return (
329
- this.agentRunGoalId !== null &&
330
- (goalId === undefined || this.agentRunGoalId === undefined || this.agentRunGoalId === goalId)
331
- );
332
- }
333
-
334
- hasActiveBudgetWrapUp() {
335
- return (
336
- this.activeGoal?.status === "budget_limited" &&
337
- this.budgetWrapUp?.goalId === this.activeGoal.id &&
338
- this.budgetWrapUp.delivered
339
- );
340
- }
341
-
342
- hasActiveGoalRecovery() {
343
- return Boolean(this.activeGoal && this.goalRecovery?.goalId === this.activeGoal.id);
344
- }
345
-
346
- beginAgentRun(goalId: string | null | undefined, origin: GoalRunOrigin | undefined) {
347
- this.agentRunGoalId = goalId;
348
- this.agentRunOrigin = origin;
349
- this.agentRunToolAttempted = false;
350
- }
351
-
352
- beginRecoveryRunIfNeeded() {
353
- if (this.agentRunGoalId !== undefined || !this.activeGoal) return;
354
- const recovery = this.goalRecovery;
355
- if (!recovery || recovery.goalId !== this.activeGoal.id) return;
356
- this.beginAgentRun(recovery.goalId, recovery.automaticOwner ? "automatic" : "manual");
357
- }
358
-
359
- markAgentToolAttempted() {
360
- if (this.agentRunGoalId !== undefined) this.agentRunToolAttempted = true;
361
- }
362
-
363
- finishAgentRun(): CompletedGoalRun {
364
- const run = {
365
- goalId: this.agentRunGoalId,
366
- origin: this.agentRunOrigin,
367
- toolAttempted: this.agentRunToolAttempted,
368
- };
369
- this.clearAgentRun();
370
- return run;
371
- }
372
-
373
- clearAgentRun() {
374
- this.agentRunGoalId = undefined;
375
- this.agentRunOrigin = undefined;
376
- this.agentRunToolAttempted = false;
377
- }
378
-
379
- reclassifyAgentRunAsManual() {
380
- if (this.agentRunGoalId !== undefined) this.agentRunOrigin = "manual";
381
- }
382
-
383
- isAutomaticRunForGoal(goalId: string) {
384
- return this.agentRunGoalId === goalId && this.agentRunOrigin === "automatic";
385
- }
386
-
387
- recordGoalUsage(
388
- goal: ActiveGoal,
389
- ctx: StatusContext,
390
- checkpointActiveTime = goal.status === "active" && !goal.waiting,
391
- ) {
392
- if (!this.canRecordGoalUsage(goal.id)) return false;
393
- updateGoalUsage(goal, ctx, checkpointActiveTime);
394
- return true;
395
- }
396
-
397
- requestContinuation(goal: ActiveGoal) {
398
- if (!this.ownsWorkflow(goal)) return false;
399
- if (goal.waiting || this.hasContinuationWorkForGoal(goal.id)) return false;
400
- const marker = continuationMarker(goal);
401
- this.continuationIntent = {
402
- goalId: goal.id,
403
- iteration: goal.iteration,
404
- marker,
405
- prompt: buildContinuePrompt(goal, marker),
406
- };
407
- return true;
408
- }
409
-
410
- dispatchContinuationIfSettled(ctx: StatusContext) {
411
- const intent = this.continuationIntent;
412
- if (!this.ownsWorkflow()) {
413
- this.cancelContinuationWork();
414
- return false;
415
- }
416
- if (!intent) return false;
417
- if (this.activeGoal?.status === "active" && !this.goalToolsAvailable()) {
418
- this.pauseGoalForUnavailableTools(ctx);
419
- return false;
420
- }
421
- if (
422
- !this.activeGoal ||
423
- this.activeGoal.id !== intent.goalId ||
424
- this.activeGoal.status !== "active" ||
425
- this.activeGoal.waiting
426
- ) {
427
- this.continuationIntent = undefined;
428
- return false;
429
- }
430
- if (this.enforceAutomaticTurnLimit(ctx, false) || this.enforceNoProgressLimit(ctx)) {
431
- return false;
432
- }
433
- if (ctx.isIdle?.() !== true || hasPendingMessages(ctx)) return false;
434
-
435
- this.clearContinuationDispatchTimer();
436
- this.continuationIntent = undefined;
437
- this.continuationDelivery = intent;
438
- try {
439
- this.pi.sendUserMessage(intent.prompt, { deliverAs: "followUp" });
440
- return true;
441
- } catch (error) {
442
- if (this.continuationDelivery?.marker === intent.marker) {
443
- this.continuationDelivery = undefined;
444
- }
445
- if (this.activeGoal?.id === intent.goalId && this.activeGoal.status === "active") {
446
- this.continuationIntent = intent;
447
- }
448
- notifyTerminal(ctx.ui, `Goal prompt failed: ${formatError(error)}`, "error");
449
- return false;
450
- }
451
- }
452
-
453
- hasContinuationWorkForGoal(goalId: string) {
454
- return (
455
- this.continuationIntent?.goalId === goalId || this.continuationDelivery?.goalId === goalId
456
- );
457
- }
458
-
459
- enterGoalWait(ctx: StatusContext, goalId: string, waiting: GoalWait) {
460
- const goal = this.activeGoal;
461
- if (!goal || goal.id !== goalId || !this.ownsWorkflow(goal)) return undefined;
462
- this.recordGoalUsage(goal, ctx, false);
463
- this.cancelContinuationWork();
464
- this.clearGoalRecoveryForGoal(goal.id);
465
- this.clearGoalWaitTimer();
466
- this.activeGoal = {
467
- ...goal,
468
- waiting,
469
- activeStartedAt: undefined,
470
- updatedAt: Date.now(),
471
- };
472
- this.persistGoal(this.activeGoal);
473
- this.updateStatus(ctx, this.activeGoal);
474
- this.restoreGoalWaitTimer(ctx);
475
- return this.activeGoal;
476
- }
477
-
478
- clearGoalWait(ctx: StatusContext, goalId: string) {
479
- const goal = this.activeGoal;
480
- if (!goal || goal.id !== goalId || !this.ownsWorkflow(goal) || !goal.waiting) return false;
481
- this.clearGoalWaitTimer();
482
- const { waiting: _waiting, ...nextGoal } = goal;
483
- const now = Date.now();
484
- checkpointGoalActiveTime(nextGoal, now, true);
485
- nextGoal.updatedAt = now;
486
- this.activeGoal = nextGoal;
487
- this.persistGoal(this.activeGoal);
488
- this.updateStatus(ctx, this.activeGoal);
489
- return true;
490
- }
491
-
492
- restoreGoalWaitTimer(ctx: StatusContext) {
493
- this.clearGoalWaitTimer();
494
- const goal = this.activeGoal;
495
- if (!this.ownsWorkflow(goal)) return false;
496
- const resumeAt = goal?.status === "active" ? goal.waiting?.resumeAt : undefined;
497
- if (!goal || resumeAt === undefined) return false;
498
- this.scheduleGoalWaitTimer(ctx, goal.id, resumeAt);
499
- return true;
500
- }
501
-
502
- dispatchDueGoalWait(ctx: StatusContext) {
503
- const goal = this.activeGoal;
504
- if (!this.ownsWorkflow(goal)) return false;
505
- const waiting = goal?.status === "active" ? goal.waiting : undefined;
506
- const resumeAt = waiting?.resumeAt;
507
- if (!goal || !waiting || resumeAt === undefined) return false;
508
- const retry = this.goalWaitDeadlineRetry;
509
- const matchingRetry =
510
- retry?.goalId === goal.id && retry.resumeAt === resumeAt ? retry : undefined;
511
- if (matchingRetry?.exhausted) return false;
512
- const wakeAt = matchingRetry?.retryAt ?? resumeAt;
513
- if (Date.now() < wakeAt) return false;
514
- const retryAttempt = matchingRetry?.retryAt !== undefined;
515
- if (ctx.isIdle?.() !== true || hasPendingMessages(ctx)) return false;
516
- if (retryAttempt) this.goalWaitDeadlineRetry = undefined;
517
- if (!this.clearGoalWait(ctx, goal.id)) return false;
518
- const resumedGoal = this.activeGoal;
519
- if (!resumedGoal || resumedGoal.id !== goal.id || resumedGoal.status !== "active") return false;
520
- this.requestContinuation(resumedGoal);
521
- const dispatched = this.dispatchContinuationIfSettled(ctx);
522
- if (dispatched) return true;
523
- if (
524
- this.activeGoal?.id === goal.id &&
525
- this.activeGoal.status === "active" &&
526
- this.continuationIntent?.goalId === goal.id
527
- ) {
528
- this.restoreGoalWaitAfterDeadlineFailure(ctx, goal.id, waiting, !retryAttempt);
529
- }
530
- return false;
531
- }
532
-
533
- clearGoalWaitTimer() {
534
- this.goalWaitTimer.clear();
535
- this.goalWaitDeadlineRetry = undefined;
536
- }
537
-
538
- private scheduleGoalWaitTimer(ctx: StatusContext, goalId: string, wakeAt: number) {
539
- const generation = this.menuGeneration;
540
- this.goalWaitTimer.schedule(wakeAt, () => {
541
- if (
542
- generation !== this.menuGeneration ||
543
- this.activeGoal?.id !== goalId ||
544
- !this.ownsWorkflow(this.activeGoal)
545
- ) {
546
- return;
547
- }
548
- try {
549
- this.dispatchDueGoalWait(ctx);
550
- } catch (error) {
551
- notifyTerminal(ctx.ui, `Goal wait deadline failed: ${formatError(error)}`, "error");
552
- }
553
- });
554
- }
555
-
556
- private restoreGoalWaitAfterDeadlineFailure(
557
- ctx: StatusContext,
558
- goalId: string,
559
- waiting: GoalWait,
560
- allowRetry: boolean,
561
- ) {
562
- const goal = this.activeGoal;
563
- if (!goal || goal.id !== goalId || goal.status !== "active" || waiting.resumeAt === undefined) {
564
- return;
565
- }
566
- this.cancelContinuationWork();
567
- this.recordGoalUsage(goal, ctx, false);
568
- this.goalWaitTimer.clear();
569
- this.activeGoal = {
570
- ...goal,
571
- waiting,
572
- activeStartedAt: undefined,
573
- updatedAt: Date.now(),
574
- };
575
- const retryAt = allowRetry ? Date.now() + 1_000 : undefined;
576
- this.goalWaitDeadlineRetry = {
577
- goalId,
578
- resumeAt: waiting.resumeAt,
579
- retryAt,
580
- exhausted: !allowRetry,
581
- };
582
- this.persistGoal(this.activeGoal);
583
- this.updateStatus(ctx, this.activeGoal);
584
- if (retryAt !== undefined) this.scheduleGoalWaitTimer(ctx, goalId, retryAt);
585
- }
586
-
587
- updateStatus(ctx: StatusContext, goal: ActiveGoal) {
588
- this.clearCompletionStatusTimer();
589
- ctx.ui.setStatus(
590
- STATUS_KEY,
591
- formatStatus(goal, this.settings.continuationLimits.automaticTurns),
592
- );
593
- }
594
-
595
- stopActiveGoal(ctx: StatusContext, request: GoalStopRequest) {
596
- const currentGoal = this.activeGoal;
597
- if (!currentGoal || currentGoal.id !== request.expectedGoalId) return undefined;
598
-
599
- this.clearGoalWaitTimer();
600
- let goal = currentGoal;
601
- let status: StoppedGoalStatus;
602
- let terminalReason: string | undefined;
603
- switch (request.kind) {
604
- case "explicit_pause":
605
- this.recordGoalUsage(goal, ctx);
606
- this.cancelContinuationWork();
607
- this.clearGoalRecoveryForGoal(goal.id);
608
- this.clearBudgetWrapUp();
609
- this.blockStaleGoalToolCalls();
610
- abortCurrentTurn(ctx);
611
- status = "paused";
612
- break;
613
- case "budget_limit":
614
- this.cancelContinuationWork();
615
- this.clearGoalRecoveryForGoal(goal.id);
616
- this.clearBudgetWrapUp();
617
- this.blockStaleGoalToolCalls();
618
- abortCurrentTurn(ctx);
619
- status = "budget_limited";
620
- terminalReason = request.reason;
621
- break;
622
- case "safety_pause":
623
- this.cancelContinuationWork();
624
- this.clearGoalRecoveryForGoal(goal.id);
625
- this.clearBudgetWrapUp();
626
- this.blockStaleGoalToolCalls();
627
- if (request.abortTurn) {
628
- this.guardAbortGoalId = goal.id;
629
- abortCurrentTurn(ctx);
630
- }
631
- goal = { ...goal, safetyPauseCause: request.cause };
632
- status = "paused";
633
- terminalReason = request.reason;
634
- break;
635
- case "retry_exhausted":
636
- this.clearGoalRecoveryForGoal(goal.id);
637
- this.cancelContinuationWork();
638
- this.clearBudgetWrapUp();
639
- this.blockStaleGoalToolCalls();
640
- status = "blocked";
641
- terminalReason = request.reason;
642
- break;
643
- case "tools_unavailable":
644
- if (request.recordUsage) this.recordGoalUsage(goal, ctx);
645
- this.cancelContinuationWork();
646
- this.clearGoalRecoveryForGoal(goal.id);
647
- this.clearBudgetWrapUp();
648
- if (request.abortTurn) {
649
- this.blockStaleGoalToolCalls();
650
- abortCurrentTurn(ctx);
651
- } else {
652
- this.clearStaleGoalToolCallBlock();
653
- }
654
- status = "paused";
655
- break;
656
- case "blocker_report":
657
- this.recordGoalUsage(goal, ctx);
658
- this.cancelContinuationWork();
659
- this.clearBudgetWrapUp();
660
- this.clearGoalRecoveryForGoal(goal.id);
661
- this.blockStaleGoalToolCalls();
662
- status = "blocked";
663
- terminalReason = request.reason;
664
- break;
665
- case "agent_interruption":
666
- this.cancelContinuationWork();
667
- this.clearBudgetWrapUp();
668
- this.blockStaleGoalToolCalls();
669
- abortCurrentTurn(ctx);
670
- status = request.status;
671
- terminalReason = request.reason;
672
- break;
673
- case "activation_rollback":
674
- goal = request.restoreGoal;
675
- if (request.abortTurn) abortCurrentTurn(ctx);
676
- this.blockStaleGoalToolCalls();
677
- status = "paused";
678
- break;
679
- }
680
-
681
- this.activeGoal = transitionGoal(goal, status);
682
- if (terminalReason !== undefined) this.setTerminalReason(this.activeGoal.id, terminalReason);
683
- const stoppedGoal = this.activeGoal;
684
- this.persistGoal(stoppedGoal);
685
- if (request.kind !== "blocker_report") this.ensureInactiveGoalContextContract(ctx);
686
- if (this.activeGoal?.id === stoppedGoal.id && this.activeGoal.status === stoppedGoal.status) {
687
- this.updateStatus(ctx, stoppedGoal);
688
- this.releaseWorkflow();
689
- }
690
- return stoppedGoal;
691
- }
692
-
693
- blockStaleGoalToolCalls() {
694
- this.staleGoalToolCallsBlocked = true;
695
- }
696
-
697
- clearStaleGoalToolCallBlock() {
698
- this.staleGoalToolCallsBlocked = false;
699
- }
700
-
701
- clearGoalRecovery() {
702
- this.goalRecovery = undefined;
703
- }
704
-
705
- clearBudgetWrapUp() {
706
- this.budgetWrapUp = undefined;
707
- }
708
-
709
- setCompletionSummary(goalId: string, summary: string) {
710
- this.terminalDetails = { goalId, summary };
711
- }
712
-
713
- setTerminalReason(goalId: string, reason: string) {
714
- this.terminalDetails = { goalId, reason };
715
- }
716
-
717
- clearTerminalDetails() {
718
- this.terminalDetails = undefined;
719
- }
720
-
721
- isActiveBudgetWrapUpMessage(message: unknown) {
722
- if (!message || typeof message !== "object") return false;
723
- const candidate = message as {
724
- role?: unknown;
725
- customType?: unknown;
726
- details?: { goalId?: unknown };
727
- };
728
- return (
729
- candidate.role === "custom" &&
730
- candidate.customType === BUDGET_WRAP_UP_MESSAGE_TYPE &&
731
- typeof candidate.details?.goalId === "string" &&
732
- candidate.details.goalId === this.budgetWrapUp?.goalId &&
733
- candidate.details.goalId === this.activeGoal?.id
734
- );
735
- }
736
-
737
- keepBudgetWrapUpMessage(message: unknown) {
738
- if (!message || typeof message !== "object") return true;
739
- const candidate = message as { role?: unknown; customType?: unknown };
740
- if (candidate.role !== "custom" || candidate.customType !== BUDGET_WRAP_UP_MESSAGE_TYPE) {
741
- return true;
742
- }
743
- return this.isActiveBudgetWrapUpMessage(message);
744
- }
745
-
746
- queueBudgetWrapUp(ctx: StatusContext, goal: ActiveGoal) {
747
- if (!this.ownsWorkflow(goal)) return false;
748
- if (!this.budgetWrapUp || this.budgetWrapUp.goalId !== goal.id) {
749
- this.budgetWrapUp = { goalId: goal.id, delivered: false };
750
- }
751
- if (this.budgetWrapUp.delivered) return true;
752
- this.budgetWrapUp.delivered = true;
753
- try {
754
- this.pi.sendMessage(
755
- {
756
- customType: BUDGET_WRAP_UP_MESSAGE_TYPE,
757
- content: BUDGET_WRAP_UP_PROMPT,
758
- display: true,
759
- details: { goalId: goal.id },
760
- },
761
- { deliverAs: "steer" },
762
- );
763
- return true;
764
- } catch (error) {
765
- this.budgetWrapUp.delivered = false;
766
- notifyTerminal(ctx.ui, `Goal budget wrap-up failed: ${formatError(error)}`, "error");
767
- return false;
768
- }
769
- }
770
-
771
- limitActiveGoalForBudget(ctx: StatusContext, sendWrapUp: boolean) {
772
- const goal = this.activeGoal;
773
- if (
774
- goal?.status !== "active" ||
775
- goal.tokenBudget === undefined ||
776
- goal.tokensUsed < goal.tokenBudget
777
- ) {
778
- return false;
779
- }
780
-
781
- const stoppedGoal = this.stopActiveGoal(ctx, {
782
- kind: "budget_limit",
783
- expectedGoalId: goal.id,
784
- reason: `token budget reached (${formatBudget(goal)})`,
785
- });
786
- if (!stoppedGoal) return false;
787
- notifyTerminal(ctx.ui, `Goal token budget reached: ${formatBudget(stoppedGoal)}`, "warning");
788
- if (sendWrapUp) this.queueBudgetWrapUp(ctx, stoppedGoal);
789
- return true;
790
- }
791
-
792
- recordAutomaticTurn(ctx: StatusContext, message: unknown) {
793
- const goal = this.activeGoal;
794
- if (goal?.status !== "active" || !this.isAutomaticRunForGoal(goal.id)) return false;
795
- const candidate = message as { role?: unknown; stopReason?: unknown } | undefined;
796
- if (candidate?.role === "assistant" && candidate.stopReason === "aborted") return false;
797
- goal.automaticModelTurns = Math.min(Number.MAX_SAFE_INTEGER, goal.automaticModelTurns + 1);
798
- this.recordGoalUsage(goal, ctx);
799
- this.persistGoal(goal);
800
- this.updateStatus(ctx, goal);
801
- // Terminal errors need agent_end classification before a safety pause can
802
- // choose between usage_limited, blocked, or retryable cleanup.
803
- if (candidate?.role === "assistant" && candidate.stopReason === "error") return false;
804
- return this.enforceAutomaticTurnLimit(ctx, true);
805
- }
806
-
807
- recordAutomaticRunProgress(
808
- ctx: StatusContext,
809
- goalId: string,
810
- messages: readonly unknown[],
811
- toolAttempted: boolean,
812
- ) {
813
- const goal = this.activeGoal;
814
- if (goal?.id !== goalId || goal.status !== "active") return false;
815
- const next = nextToolFreeRepeatState(goal, messages, toolAttempted);
816
- goal.toolFreeRepeatCount = next.toolFreeRepeatCount;
817
- goal.lastToolFreeOutputFingerprint = next.lastToolFreeOutputFingerprint;
818
- this.persistGoal(goal);
819
- this.updateStatus(ctx, goal);
820
- const limit = this.settings.continuationLimits.noProgressTurns;
821
- if (limit === null || goal.toolFreeRepeatCount < limit) return false;
822
- return this.pauseGoalForSafety(ctx, "no_progress", false);
823
- }
824
-
825
- enforceAutomaticTurnLimit(ctx: StatusContext, abortTurn: boolean) {
826
- const goal = this.activeGoal;
827
- const limit = this.settings.continuationLimits.automaticTurns;
828
- if (goal?.status !== "active" || limit === null || goal.automaticModelTurns < limit) {
829
- return false;
830
- }
831
- return this.pauseGoalForSafety(ctx, "continuation_limit", abortTurn);
832
- }
833
-
834
- enforceNoProgressLimit(ctx: StatusContext, abortTurn = false) {
835
- const goal = this.activeGoal;
836
- const limit = this.settings.continuationLimits.noProgressTurns;
837
- if (goal?.status !== "active" || limit === null || goal.toolFreeRepeatCount < limit) {
838
- return false;
839
- }
840
- return this.pauseGoalForSafety(ctx, "no_progress", abortTurn);
841
- }
842
-
843
- pauseGoalForSafety(ctx: StatusContext, cause: SafetyPauseCause, abortTurn: boolean) {
844
- const goal = this.activeGoal;
845
- if (goal?.status !== "active") return false;
846
- const automaticLimit = this.settings.continuationLimits.automaticTurns;
847
- const count =
848
- cause === "continuation_limit"
849
- ? `${goal.automaticModelTurns} of ${automaticLimit ?? "Unlimited"} automatic model responses`
850
- : `no progress across ${goal.toolFreeRepeatCount} automatic runs`;
851
- const stoppedGoal = this.stopActiveGoal(ctx, {
852
- kind: "safety_pause",
853
- expectedGoalId: goal.id,
854
- cause,
855
- abortTurn,
856
- reason: `${cause} (${count}; ${formatTokenCount(goal.tokensUsed)} tokens)`,
857
- });
858
- if (!stoppedGoal) return false;
859
- notifyTerminal(
860
- ctx.ui,
861
- cause === "continuation_limit"
862
- ? `Automatic-work limit reached: ${stoppedGoal.automaticModelTurns} of ${automaticLimit} responses. Goal progress is saved with ${formatTokenCount(stoppedGoal.tokensUsed)} cumulative tokens. Open /goal to review and continue.`
863
- : `Goal paused: ${count}; ${formatTokenCount(stoppedGoal.tokensUsed)} cumulative tokens. Open /goal to review and continue.`,
864
- "warning",
865
- );
866
- return true;
867
- }
868
-
869
- resetActiveSafetyEpoch(ctx: StatusContext) {
870
- const goal = this.activeGoal;
871
- if (goal?.status !== "active") return false;
872
- this.activeGoal = resetGoalSafetyEpoch(goal);
873
- this.reclassifyAgentRunAsManual();
874
- this.persistGoal(this.activeGoal);
875
- this.updateStatus(ctx, this.activeGoal);
876
- return true;
877
- }
878
-
879
- finalizeSettledRecovery(ctx: StatusContext) {
880
- const recovery = this.goalRecovery;
881
- if (!recovery) return false;
882
- this.goalRecovery = undefined;
883
- const goal = this.activeGoal;
884
- if (goal?.id !== recovery.goalId || goal.status !== "active" || !this.ownsWorkflow(goal)) {
885
- return false;
886
- }
887
- const details = recovery.errorMessage ? `: ${truncateNotification(recovery.errorMessage)}` : "";
888
- if (recovery.kind === "provider_retry") {
889
- const waitingGoal = this.enterGoalWait(ctx, goal.id, {
890
- reason: `Provider retries exhausted${details}`,
891
- });
892
- if (!waitingGoal) return false;
893
- notifyTerminal(
894
- ctx.ui,
895
- `Goal waiting after provider retries were exhausted${details}. Send a follow-up or run /goal resume to retry.`,
896
- "warning",
897
- );
898
- return true;
899
- }
900
- const stoppedGoal = this.stopActiveGoal(ctx, {
901
- kind: "retry_exhausted",
902
- expectedGoalId: goal.id,
903
- reason: `agent error after retries${details}`,
904
- });
905
- if (!stoppedGoal) return false;
906
- notifyTerminal(
907
- ctx.ui,
908
- `Goal blocked after agent error retries were exhausted${details}. Resolve the blocker or run /goal resume to retry.`,
909
- "warning",
910
- );
911
- return true;
912
- }
913
-
914
- clearSettledSafetyTracking() {
915
- this.guardAbortGoalId = undefined;
916
- this.pendingNonGoalInputs = [];
917
- this.claimedGoalPromptMarkers.clear();
918
- this.claimedContinuationMarkers.clear();
919
- this.clearAgentRun();
920
- }
921
-
922
- clearGoalRecoveryForGoal(goalId: string) {
923
- if (this.goalRecovery?.goalId === goalId) this.goalRecovery = undefined;
924
- }
925
-
926
- isPiOwnedCompactionRetry(event: unknown, goalId: string) {
927
- const compaction = event as { reason?: unknown; willRetry?: unknown };
928
- if (compaction.willRetry === true) return true;
929
- return (
930
- this.goalRecovery?.goalId === goalId &&
931
- this.goalRecovery.kind === "compaction_retry" &&
932
- (compaction.reason === undefined || compaction.reason === "overflow")
933
- );
934
- }
935
-
936
- clearContinuationTracking() {
937
- this.clearContinuationDispatchTimer();
938
- this.continuationIntent = undefined;
939
- this.continuationDelivery = undefined;
940
- this.cancelledContinuationMarkers.clear();
941
- this.claimedContinuationMarkers.clear();
942
- }
943
-
944
- clearPendingGoalPrompts() {
945
- this.pendingGoalPromptMarkers.clear();
946
- this.claimedGoalPromptMarkers.clear();
947
- this.cancelledGoalPromptMarkers.clear();
948
- this.pendingNonGoalInputs = [];
949
- }
950
-
951
- ensureGoalContextContract(ctx: StatusContext, goal: ActiveGoal) {
952
- const contract = this.goalContextContractForPrompt(ctx, goal);
953
- if (contract) this.pi.sendMessage(contract, { triggerTurn: false });
954
- }
955
-
956
- ensureInactiveGoalContextContract(ctx: StatusContext) {
957
- const contract = this.goalContextContractForPrompt(ctx);
958
- if (contract) this.pi.sendMessage(contract, { triggerTurn: false });
959
- }
960
-
961
- goalContextContractForPrompt(ctx: StatusContext, goal?: ActiveGoal) {
962
- const { contextEntries, historyEntries } = goalContractEntries(ctx);
963
- if (goal) {
964
- return hasGoalContextContract(contextEntries, goal)
965
- ? undefined
966
- : createGoalContextContract(goal);
967
- }
968
- const hasHistory =
969
- hasGoalContextContractHistory(contextEntries) ||
970
- hasGoalContextContractHistory(historyEntries);
971
- if (!hasHistory || hasInactiveGoalContextContract(contextEntries)) return undefined;
972
- return createInactiveGoalContextContract();
973
- }
974
-
975
- hasGoalContextContractHistory(ctx: StatusContext) {
976
- const { contextEntries, historyEntries } = goalContractEntries(ctx);
977
- return (
978
- hasGoalContextContractHistory(contextEntries) || hasGoalContextContractHistory(historyEntries)
979
- );
980
- }
981
-
982
- async sendOwnedGoalPrompt(
983
- ctx: StatusContext,
984
- goalId: string,
985
- prompt: string,
986
- resetSafetyEpoch = true,
987
- isCurrent?: () => boolean,
988
- ) {
989
- if (this.activeGoal?.id !== goalId || !this.ownsWorkflow(this.activeGoal)) return false;
990
- const pending = this.rememberPendingGoalPrompt(goalId, prompt, resetSafetyEpoch);
991
- const sent = await sendPrompt(this.pi, ctx, pending.prompt, isCurrent);
992
- if (
993
- !sent ||
994
- (isCurrent && !isCurrent()) ||
995
- this.activeGoal?.id !== goalId ||
996
- !this.ownsWorkflow(this.activeGoal)
997
- ) {
998
- this.pendingGoalPromptMarkers.delete(pending.marker);
999
- return false;
1000
- }
1001
- return true;
1002
- }
1003
-
1004
- cancelContinuationWork() {
1005
- this.clearContinuationDispatchTimer();
1006
- if (this.continuationDelivery) {
1007
- this.rememberCancelledContinuationMarker(this.continuationDelivery);
1008
- }
1009
- this.continuationIntent = undefined;
1010
- this.continuationDelivery = undefined;
1011
- }
1012
-
1013
- scheduleContinuationDispatch(ctx: StatusContext, goalId: string) {
1014
- this.clearContinuationDispatchTimer();
1015
- const generation = this.menuGeneration;
1016
- this.continuationDispatchTimer = setTimeout(() => {
1017
- this.continuationDispatchTimer = undefined;
1018
- if (
1019
- generation !== this.menuGeneration ||
1020
- this.activeGoal?.id !== goalId ||
1021
- !this.ownsWorkflow(this.activeGoal)
1022
- ) {
1023
- return;
1024
- }
1025
- this.dispatchContinuationIfSettled(ctx);
1026
- }, 0);
1027
- }
1028
-
1029
- private clearContinuationDispatchTimer() {
1030
- if (!this.continuationDispatchTimer) return;
1031
- clearTimeout(this.continuationDispatchTimer);
1032
- this.continuationDispatchTimer = undefined;
1033
- }
1034
-
1035
- consumeCancelledGoalPrompt(prompt: string) {
1036
- const marker = extractGoalPromptMarker(prompt);
1037
- if (!marker) return false;
1038
- const cancelledPrompt = this.cancelledGoalPromptMarkers.get(marker);
1039
- if (!cancelledPrompt || !preservesOwnedPromptAtTerminalBoundary(prompt, cancelledPrompt)) {
1040
- return false;
1041
- }
1042
- this.cancelledGoalPromptMarkers.delete(marker);
1043
- return true;
1044
- }
1045
-
1046
- consumeCancelledContinuationPrompt(prompt: string) {
1047
- const marker = extractContinuationMarker(prompt);
1048
- if (!marker) return false;
1049
- const cancelledPrompt = this.cancelledContinuationMarkers.get(marker);
1050
- if (!cancelledPrompt || !preservesOwnedPromptAtTerminalBoundary(prompt, cancelledPrompt)) {
1051
- return false;
1052
- }
1053
- this.cancelledContinuationMarkers.delete(marker);
1054
- return true;
1055
- }
1056
-
1057
- acceptOwnedInputBoundary(prompt: string) {
1058
- const fingerprint = inputFingerprint(prompt);
1059
- const goalMarker = extractGoalPromptMarker(prompt);
1060
- if (goalMarker) {
1061
- const pending = this.pendingGoalPromptMarkers.get(goalMarker);
1062
- if (pending && preservesOwnedPromptAtTerminalBoundary(prompt, pending.prompt)) return true;
1063
- if (this.claimedGoalPromptMarkers.get(goalMarker) === fingerprint) return true;
1064
- }
1065
- const continuationMarker = extractContinuationMarker(prompt);
1066
- if (!continuationMarker) return false;
1067
- if (
1068
- this.continuationDelivery?.marker === continuationMarker &&
1069
- preservesOwnedPromptAtTerminalBoundary(prompt, this.continuationDelivery.prompt)
1070
- ) {
1071
- return true;
1072
- }
1073
- return this.claimedContinuationMarkers.get(continuationMarker) === fingerprint;
1074
- }
1075
-
1076
- supersedeOwnedInputCollision(prompt: string) {
1077
- const fingerprint = inputFingerprint(prompt);
1078
- const goalMarker = extractGoalPromptMarker(prompt);
1079
- if (goalMarker) {
1080
- const pending = this.pendingGoalPromptMarkers.get(goalMarker);
1081
- if (pending && pending.fingerprint !== fingerprint) {
1082
- this.pendingGoalPromptMarkers.delete(goalMarker);
1083
- this.rememberCancelledGoalPromptMarker(goalMarker, pending.prompt);
1084
- }
1085
- this.claimedGoalPromptMarkers.delete(goalMarker);
1086
- }
1087
- const continuationMarker = extractContinuationMarker(prompt);
1088
- if (!continuationMarker) return;
1089
- if (
1090
- (this.continuationDelivery?.marker === continuationMarker &&
1091
- !preservesOwnedPromptAtTerminalBoundary(prompt, this.continuationDelivery.prompt)) ||
1092
- this.continuationIntent?.marker === continuationMarker
1093
- ) {
1094
- this.cancelContinuationWork();
1095
- }
1096
- this.claimedContinuationMarkers.delete(continuationMarker);
1097
- }
1098
-
1099
- hasOwnedPromptBoundary(prompt: string) {
1100
- const fingerprint = inputFingerprint(prompt);
1101
- const goalMarker = extractGoalPromptMarker(prompt);
1102
- if (goalMarker) {
1103
- const pending = this.pendingGoalPromptMarkers.get(goalMarker);
1104
- if (
1105
- (pending && preservesOwnedPromptAtTerminalBoundary(prompt, pending.prompt)) ||
1106
- this.claimedGoalPromptMarkers.get(goalMarker) === fingerprint
1107
- ) {
1108
- return true;
1109
- }
1110
- }
1111
- const continuationMarker = extractContinuationMarker(prompt);
1112
- if (!continuationMarker) return false;
1113
- return (
1114
- (this.continuationDelivery?.marker === continuationMarker &&
1115
- preservesOwnedPromptAtTerminalBoundary(prompt, this.continuationDelivery.prompt)) ||
1116
- this.claimedContinuationMarkers.get(continuationMarker) === fingerprint
1117
- );
1118
- }
1119
-
1120
- consumeStaleOwnedGoalPrompt(prompt: string) {
1121
- const marker = extractGoalPromptMarker(prompt);
1122
- if (!marker) return false;
1123
- const pending = this.pendingGoalPromptMarkers.get(marker);
1124
- if (!pending || !preservesOwnedPromptAtTerminalBoundary(prompt, pending.prompt)) return false;
1125
- if (this.activeGoal?.id === pending.goalId && this.activeGoal.status === "active") {
1126
- return false;
1127
- }
1128
- this.pendingGoalPromptMarkers.delete(marker);
1129
- return true;
1130
- }
1131
-
1132
- noteQueuedNonGoalInput(prompt: string, behavior: "steer" | "followUp", resetSafetyEpoch = false) {
1133
- this.pendingNonGoalInputs.push({
1134
- behavior,
1135
- fingerprint: inputFingerprint(prompt),
1136
- resetSafetyEpoch,
1137
- });
1138
- if (this.pendingNonGoalInputs.length > MAX_PENDING_NON_GOAL_INPUTS) {
1139
- this.pendingNonGoalInputs.shift();
1140
- }
1141
- }
1142
-
1143
- consumeQueuedNonGoalInput(prompt: string, allowDeliveryFallback = true) {
1144
- if (typeof prompt !== "string") return undefined;
1145
- const fingerprint = inputFingerprint(prompt);
1146
- // Pi delivers steers before follow-ups. Prefer a matching steer even when an
1147
- // identical follow-up was queued first so it cannot steal follow-up ownership.
1148
- const steerIndex = this.pendingNonGoalInputs.findIndex(
1149
- (pending) => pending.behavior === "steer" && pending.fingerprint === fingerprint,
1150
- );
1151
- const exactIndex =
1152
- steerIndex >= 0
1153
- ? steerIndex
1154
- : this.pendingNonGoalInputs.findIndex(
1155
- (pending) => pending.behavior === "followUp" && pending.fingerprint === fingerprint,
1156
- );
1157
- if (exactIndex >= 0) return this.pendingNonGoalInputs.splice(exactIndex, 1)[0];
1158
- if (!allowDeliveryFallback) return undefined;
1159
-
1160
- // Skills, templates, and later input handlers can transform the raw text after
1161
- // pi-goal records it. Fall back to Pi's delivery priority as a bounded marker:
1162
- // steers drain before follow-ups, and settlement clears stale entries.
1163
- const fallbackSteerIndex = this.pendingNonGoalInputs.findIndex(
1164
- (pending) => pending.behavior === "steer",
1165
- );
1166
- const fallbackIndex =
1167
- fallbackSteerIndex >= 0
1168
- ? fallbackSteerIndex
1169
- : this.pendingNonGoalInputs.findIndex((pending) => pending.behavior === "followUp");
1170
- if (fallbackIndex < 0) return undefined;
1171
- return this.pendingNonGoalInputs.splice(fallbackIndex, 1)[0];
1172
- }
1173
-
1174
- consumeQueuedNonGoalFollowUpForAgentStart() {
1175
- // A pending steer owns the next intra-run boundary. Do not let a later
1176
- // follow-up suppress cleanup until all earlier-priority steers have started.
1177
- if (this.pendingNonGoalInputs.some((pending) => pending.behavior === "steer")) return false;
1178
- const index = this.pendingNonGoalInputs.findIndex((pending) => pending.behavior === "followUp");
1179
- if (index < 0) return false;
1180
- this.pendingNonGoalInputs.splice(index, 1);
1181
- return true;
1182
- }
1183
-
1184
- markContinuationStarted(prompt: string) {
1185
- const marker = extractContinuationMarker(prompt);
1186
- if (!marker) {
1187
- // A user, retry, or another extension started newer work. Cancel both an
1188
- // unsent intent and a delivery that may have lost the non-atomic idle race;
1189
- // the newer work's agent_end will record a fresh intent.
1190
- this.cancelContinuationWork();
1191
- return undefined;
1192
- }
1193
- const fingerprint = inputFingerprint(prompt);
1194
- if (this.continuationDelivery?.marker === marker) {
1195
- const delivery = this.continuationDelivery;
1196
- if (preservesOwnedPromptAtTerminalBoundary(prompt, delivery.prompt)) {
1197
- this.continuationDelivery = undefined;
1198
- this.rememberClaimedContinuationMarker(marker, prompt);
1199
- return marker.split(":", 1)[0];
1200
- }
1201
- }
1202
- const cancelledPrompt = this.cancelledContinuationMarkers.get(marker);
1203
- if (
1204
- this.claimedContinuationMarkers.get(marker) === fingerprint ||
1205
- (cancelledPrompt && preservesOwnedPromptAtTerminalBoundary(prompt, cancelledPrompt))
1206
- ) {
1207
- return marker.split(":", 1)[0];
1208
- }
1209
- this.cancelContinuationWork();
1210
- return undefined;
1211
- }
1212
-
1213
- persistGoal(goal: ActiveGoal) {
1214
- if (!isTerminalGoalStatus(goal.status) || this.terminalDetails?.goalId !== goal.id) {
1215
- this.clearTerminalDetails();
1216
- }
1217
- this.pi.appendEntry(GOAL_STATE_ENTRY_TYPE, serializeGoalState(goal));
1218
- this.publishGoalState(
1219
- buildGoalStateSnapshot(goal, this.terminalDetails?.summary, this.terminalDetails?.reason),
1220
- );
1221
- }
1222
-
1223
- clearPersistedGoal(cwd: string, clearedGoal?: ActiveGoal, reason = "goal cleared") {
1224
- this.pi.appendEntry(GOAL_STATE_ENTRY_TYPE, serializeGoalState(undefined));
1225
- if (clearedGoal) {
1226
- this.publishGoalState({
1227
- goalId: clearedGoal.id,
1228
- status: "cleared",
1229
- reason,
1230
- });
1231
- }
1232
- this.clearTerminalDetails();
1233
- clearLegacyPersistedGoal(cwd);
1234
- }
1235
-
1236
- clearActiveGoal(ctx: StatusContext, reason = "goal cleared", releaseWorkflow = true) {
1237
- this.clearActiveGoalState(ctx, reason, releaseWorkflow);
1238
- this.ensureInactiveGoalContextContract(ctx);
1239
- }
1240
-
1241
- clearCompletedGoal(ctx: StatusContext) {
1242
- this.clearActiveGoalState(ctx, "goal cleared", true);
1243
- }
1244
-
1245
- private clearActiveGoalState(ctx: StatusContext, reason: string, releaseWorkflow: boolean) {
1246
- const clearedGoal = this.activeGoal;
1247
- this.clearGoalWaitTimer();
1248
- this.cancelContinuationWork();
1249
- this.clearGoalRecovery();
1250
- this.clearBudgetWrapUp();
1251
- this.clearStaleGoalToolCallBlock();
1252
- this.activeGoal = undefined;
1253
- this.legacyQueueState = undefined;
1254
- this.clearPersistedGoal(ctx.cwd, clearedGoal, reason);
1255
- ctx.ui.setStatus(STATUS_KEY, undefined);
1256
- if (releaseWorkflow) this.releaseWorkflow();
1257
- }
1258
-
1259
- snapshotSettingsApplicationState(): GoalSettingsRuntimeSnapshot {
1260
- return {
1261
- settings: structuredClone(this.settings),
1262
- activeGoal: this.activeGoal ? structuredClone(this.activeGoal) : undefined,
1263
- legacyQueueState: this.legacyQueueState ? structuredClone(this.legacyQueueState) : undefined,
1264
- legacyExperimentalGoalsSetting: this.legacyExperimentalGoalsSetting,
1265
- continuationIntent: this.continuationIntent
1266
- ? structuredClone(this.continuationIntent)
1267
- : undefined,
1268
- continuationDelivery: this.continuationDelivery
1269
- ? structuredClone(this.continuationDelivery)
1270
- : undefined,
1271
- goalRecovery: this.goalRecovery ? structuredClone(this.goalRecovery) : undefined,
1272
- budgetWrapUp: this.budgetWrapUp ? structuredClone(this.budgetWrapUp) : undefined,
1273
- guardAbortGoalId: this.guardAbortGoalId,
1274
- staleGoalToolCallsBlocked: this.staleGoalToolCallsBlocked,
1275
- cancelledContinuationMarkers: [...this.cancelledContinuationMarkers],
1276
- terminalDetails: this.terminalDetails ? structuredClone(this.terminalDetails) : undefined,
1277
- };
1278
- }
1279
-
1280
- restoreSettingsApplicationState(snapshot: GoalSettingsRuntimeSnapshot) {
1281
- if (snapshot.activeGoal?.status === "active" && !this.acquireWorkflow()) {
1282
- throw new Error("another workflow became active before Goal settings could roll back");
1283
- }
1284
- this.settings = structuredClone(snapshot.settings);
1285
- this.activeGoal = snapshot.activeGoal ? structuredClone(snapshot.activeGoal) : undefined;
1286
- this.legacyQueueState = snapshot.legacyQueueState
1287
- ? structuredClone(snapshot.legacyQueueState)
1288
- : undefined;
1289
- this.legacyExperimentalGoalsSetting = snapshot.legacyExperimentalGoalsSetting;
1290
- this.continuationIntent = snapshot.continuationIntent
1291
- ? structuredClone(snapshot.continuationIntent)
1292
- : undefined;
1293
- this.continuationDelivery = snapshot.continuationDelivery
1294
- ? structuredClone(snapshot.continuationDelivery)
1295
- : undefined;
1296
- this.goalRecovery = snapshot.goalRecovery ? structuredClone(snapshot.goalRecovery) : undefined;
1297
- this.budgetWrapUp = snapshot.budgetWrapUp ? structuredClone(snapshot.budgetWrapUp) : undefined;
1298
- this.guardAbortGoalId = snapshot.guardAbortGoalId;
1299
- this.staleGoalToolCallsBlocked = snapshot.staleGoalToolCallsBlocked;
1300
- this.cancelledContinuationMarkers = new Map(snapshot.cancelledContinuationMarkers);
1301
- this.terminalDetails = snapshot.terminalDetails
1302
- ? structuredClone(snapshot.terminalDetails)
1303
- : undefined;
1304
- }
1305
-
1306
- pauseGoalForUnavailableTools(ctx: StatusContext, abortTurn = true, recordUsage = true) {
1307
- const goal = this.activeGoal;
1308
- if (goal?.status !== "active") return false;
1309
- const stoppedGoal = this.stopActiveGoal(ctx, {
1310
- kind: "tools_unavailable",
1311
- expectedGoalId: goal.id,
1312
- abortTurn,
1313
- recordUsage,
1314
- });
1315
- if (!stoppedGoal) return false;
1316
- notifyTerminal(
1317
- ctx.ui,
1318
- "Goal tools are unavailable, so the active goal was paused. Restore the tools and run /goal resume.",
1319
- "warning",
1320
- );
1321
- return true;
1322
- }
1323
-
1324
- showCompletionStatus(ctx: StatusContext) {
1325
- this.clearCompletionStatusTimer();
1326
- ctx.ui.setStatus(STATUS_KEY, "complete");
1327
- this.completionStatusTimer = setTimeout(() => {
1328
- this.completionStatusTimer = undefined;
1329
- try {
1330
- ctx.ui.setStatus(STATUS_KEY, undefined);
1331
- } catch {
1332
- // The completion status is best-effort; the captured ctx may be stale after
1333
- // session replacement or reload before this timer fires.
1334
- }
1335
- }, 8_000);
1336
- }
1337
-
1338
- clearCompletionStatusTimer() {
1339
- if (!this.completionStatusTimer) return;
1340
- clearTimeout(this.completionStatusTimer);
1341
- this.completionStatusTimer = undefined;
1342
- }
1343
-
1344
- private rememberPendingGoalPrompt(goalId: string, prompt: string, resetSafetyEpoch: boolean) {
1345
- const marker = randomUUID();
1346
- const ownedPrompt = appendGoalPromptMarker(prompt, marker);
1347
- this.pendingGoalPromptMarkers.set(marker, {
1348
- goalId,
1349
- resetSafetyEpoch,
1350
- fingerprint: inputFingerprint(ownedPrompt),
1351
- prompt: ownedPrompt,
1352
- });
1353
- if (this.pendingGoalPromptMarkers.size > MAX_PENDING_GOAL_PROMPTS) {
1354
- const oldest = this.pendingGoalPromptMarkers.keys().next().value;
1355
- if (oldest) this.pendingGoalPromptMarkers.delete(oldest);
1356
- }
1357
- return { marker, prompt: ownedPrompt };
1358
- }
1359
-
1360
- private consumePendingGoalPrompt(prompt: string) {
1361
- const marker = extractGoalPromptMarker(prompt);
1362
- if (!marker) return undefined;
1363
- const pending = this.pendingGoalPromptMarkers.get(marker);
1364
- if (!pending || !preservesOwnedPromptAtTerminalBoundary(prompt, pending.prompt)) {
1365
- return undefined;
1366
- }
1367
- this.pendingGoalPromptMarkers.delete(marker);
1368
- this.rememberClaimedGoalPromptMarker(marker, inputFingerprint(prompt));
1369
- return pending;
1370
- }
1371
-
1372
- private rememberCancelledGoalPromptMarker(marker: string, prompt: string) {
1373
- this.cancelledGoalPromptMarkers.set(marker, prompt);
1374
- if (this.cancelledGoalPromptMarkers.size <= MAX_PENDING_GOAL_PROMPTS) return;
1375
- const oldest = this.cancelledGoalPromptMarkers.keys().next().value;
1376
- if (oldest) this.cancelledGoalPromptMarkers.delete(oldest);
1377
- }
1378
-
1379
- private rememberClaimedGoalPromptMarker(marker: string, fingerprint: string) {
1380
- this.claimedGoalPromptMarkers.set(marker, fingerprint);
1381
- if (this.claimedGoalPromptMarkers.size <= MAX_PENDING_GOAL_PROMPTS) return;
1382
- const oldest = this.claimedGoalPromptMarkers.keys().next().value;
1383
- if (oldest) this.claimedGoalPromptMarkers.delete(oldest);
1384
- }
1385
-
1386
- private rememberClaimedContinuationMarker(marker: string, prompt: string) {
1387
- this.claimedContinuationMarkers.set(marker, inputFingerprint(prompt));
1388
- if (this.claimedContinuationMarkers.size <= MAX_CANCELLED_CONTINUATION_PROMPTS) return;
1389
- const oldest = this.claimedContinuationMarkers.keys().next().value;
1390
- if (oldest) this.claimedContinuationMarkers.delete(oldest);
1391
- }
1392
-
1393
- consumeOwnedGoalPrompt(prompt: string) {
1394
- return this.consumePendingGoalPrompt(prompt);
1395
- }
1396
-
1397
- private rememberCancelledContinuationMarker(ticket: ContinuationTicket) {
1398
- this.cancelledContinuationMarkers.set(ticket.marker, ticket.prompt);
1399
- if (this.cancelledContinuationMarkers.size <= MAX_CANCELLED_CONTINUATION_PROMPTS) return;
1400
- const oldest = this.cancelledContinuationMarkers.keys().next().value;
1401
- if (oldest) this.cancelledContinuationMarkers.delete(oldest);
1402
- }
199
+ settings: GoalSettings = DEFAULT_GOAL_SETTINGS;
200
+ settingsLoadIssue?: GoalSettingsLoadIssue;
201
+ activeGoal?: ActiveGoal;
202
+ /** Terminal details captured for the matching persisted-state snapshot. */
203
+ private terminalDetails?: GoalTerminalDetails;
204
+ private goalStateSink?: (snapshot: GoalStateSnapshot) => void;
205
+ legacyQueueState?: LegacyQueueState;
206
+ legacyExperimentalGoalsSetting = false;
207
+ completionStatusTimer?: NodeJS.Timeout;
208
+ private continuationDispatchTimer?: NodeJS.Timeout;
209
+ private readonly goalWaitTimer = new GoalWaitTimer();
210
+ private goalWaitDeadlineRetry?: {
211
+ goalId: string;
212
+ resumeAt: number;
213
+ retryAt?: number;
214
+ exhausted: boolean;
215
+ };
216
+ continuationIntent?: ContinuationTicket;
217
+ continuationDelivery?: ContinuationTicket;
218
+ goalRecovery?: GoalRecovery;
219
+ budgetWrapUp?: BudgetWrapUp;
220
+ /** `null` marks a run that must not be charged to the active goal. */
221
+ agentRunGoalId?: string | null;
222
+ agentRunOrigin?: GoalRunOrigin;
223
+ agentRunToolAttempted = false;
224
+ guardAbortGoalId?: string;
225
+ staleGoalToolCallsBlocked = false;
226
+ private readonly workflowMutex: WorkflowMutex;
227
+ private workflowOwner?: WorkflowMutexOwner;
228
+ private workflowSession?: object;
229
+ pendingGoalPromptMarkers = new Map<string, PendingGoalPrompt>();
230
+ claimedGoalPromptMarkers = new Map<string, string>();
231
+ cancelledGoalPromptMarkers = new Map<string, string>();
232
+ cancelledContinuationMarkers = new Map<string, string>();
233
+ claimedContinuationMarkers = new Map<string, string>();
234
+ pendingNonGoalInputs: PendingNonGoalInput[] = [];
235
+ menuGeneration = 0;
236
+ menuController = new AbortController();
237
+
238
+ readonly pi: ExtensionAPI;
239
+
240
+ constructor(pi: ExtensionAPI) {
241
+ this.pi = pi;
242
+ this.workflowMutex = new WorkflowMutex(pi);
243
+ }
244
+
245
+ goalToolsAvailable() {
246
+ return goalToolsAvailable(this.pi);
247
+ }
248
+
249
+ assertGoalToolsAvailable() {
250
+ assertGoalToolsAvailable(this.pi);
251
+ }
252
+
253
+ bindWorkflowSession(session: object) {
254
+ this.workflowSession = session;
255
+ this.workflowOwner = undefined;
256
+ this.workflowMutex.bindSession(session);
257
+ }
258
+
259
+ unbindWorkflowSession(session: object) {
260
+ if (this.workflowSession !== session) return;
261
+ this.workflowMutex.unbindSession(session);
262
+ this.workflowOwner = undefined;
263
+ this.workflowSession = undefined;
264
+ }
265
+
266
+ acquireWorkflow(session?: unknown) {
267
+ if (session && typeof session === "object" && this.workflowSession !== session) {
268
+ this.bindWorkflowSession(session);
269
+ }
270
+ if (this.workflowMutex.isOwner(this.workflowOwner)) return true;
271
+ const owner = this.workflowMutex.acquire();
272
+ if (!owner) return false;
273
+ this.workflowOwner = owner;
274
+ return true;
275
+ }
276
+
277
+ ownsWorkflow(goal: ActiveGoal | undefined = this.activeGoal) {
278
+ return goal?.status === "active" && this.workflowMutex.isOwner(this.workflowOwner);
279
+ }
280
+
281
+ releaseWorkflow() {
282
+ const owner = this.workflowOwner;
283
+ this.workflowMutex.release(owner);
284
+ if (!this.workflowMutex.isOwner(owner)) this.workflowOwner = undefined;
285
+ }
286
+
287
+ hasLegacyQueueInterface() {
288
+ return this.legacyExperimentalGoalsSetting || this.legacyQueueState !== undefined;
289
+ }
290
+
291
+ setGoalStateSink(sink: ((snapshot: GoalStateSnapshot) => void) | undefined) {
292
+ this.goalStateSink = sink;
293
+ }
294
+
295
+ private publishGoalState(snapshot: GoalStateSnapshot) {
296
+ try {
297
+ this.goalStateSink?.(snapshot);
298
+ } catch {
299
+ // Protocol publication must not interrupt canonical Goal persistence.
300
+ }
301
+ }
302
+
303
+ replaceMenuSession() {
304
+ this.menuGeneration += 1;
305
+ this.menuController.abort(new DOMException("Goal session replaced", "AbortError"));
306
+ this.menuController = new AbortController();
307
+ }
308
+
309
+ closeMenuSession() {
310
+ this.menuGeneration += 1;
311
+ this.menuController.abort(new DOMException("Goal session shut down", "AbortError"));
312
+ }
313
+
314
+ canRecordGoalUsage(goalId?: string) {
315
+ return (
316
+ this.agentRunGoalId !== null &&
317
+ (goalId === undefined || this.agentRunGoalId === undefined || this.agentRunGoalId === goalId)
318
+ );
319
+ }
320
+
321
+ hasActiveBudgetWrapUp() {
322
+ return (
323
+ this.activeGoal?.status === "budget_limited" &&
324
+ this.budgetWrapUp?.goalId === this.activeGoal.id &&
325
+ this.budgetWrapUp.delivered
326
+ );
327
+ }
328
+
329
+ hasActiveGoalRecovery() {
330
+ return Boolean(this.activeGoal && this.goalRecovery?.goalId === this.activeGoal.id);
331
+ }
332
+
333
+ beginAgentRun(goalId: string | null | undefined, origin: GoalRunOrigin | undefined) {
334
+ this.agentRunGoalId = goalId;
335
+ this.agentRunOrigin = origin;
336
+ this.agentRunToolAttempted = false;
337
+ }
338
+
339
+ beginRecoveryRunIfNeeded() {
340
+ if (this.agentRunGoalId !== undefined || !this.activeGoal) return;
341
+ const recovery = this.goalRecovery;
342
+ if (!recovery || recovery.goalId !== this.activeGoal.id) return;
343
+ this.beginAgentRun(recovery.goalId, recovery.automaticOwner ? "automatic" : "manual");
344
+ }
345
+
346
+ markAgentToolAttempted() {
347
+ if (this.agentRunGoalId !== undefined) this.agentRunToolAttempted = true;
348
+ }
349
+
350
+ finishAgentRun(): CompletedGoalRun {
351
+ const run = {
352
+ goalId: this.agentRunGoalId,
353
+ origin: this.agentRunOrigin,
354
+ toolAttempted: this.agentRunToolAttempted,
355
+ };
356
+ this.clearAgentRun();
357
+ return run;
358
+ }
359
+
360
+ clearAgentRun() {
361
+ this.agentRunGoalId = undefined;
362
+ this.agentRunOrigin = undefined;
363
+ this.agentRunToolAttempted = false;
364
+ }
365
+
366
+ reclassifyAgentRunAsManual() {
367
+ if (this.agentRunGoalId !== undefined) this.agentRunOrigin = "manual";
368
+ }
369
+
370
+ isAutomaticRunForGoal(goalId: string) {
371
+ return this.agentRunGoalId === goalId && this.agentRunOrigin === "automatic";
372
+ }
373
+
374
+ recordGoalUsage(
375
+ goal: ActiveGoal,
376
+ ctx: StatusContext,
377
+ checkpointActiveTime = goal.status === "active" && !goal.waiting,
378
+ ) {
379
+ if (!this.canRecordGoalUsage(goal.id)) return false;
380
+ updateGoalUsage(goal, ctx, checkpointActiveTime);
381
+ return true;
382
+ }
383
+
384
+ requestContinuation(goal: ActiveGoal) {
385
+ if (!this.ownsWorkflow(goal)) return false;
386
+ if (goal.waiting || this.hasContinuationWorkForGoal(goal.id)) return false;
387
+ const marker = continuationMarker(goal);
388
+ this.continuationIntent = {
389
+ goalId: goal.id,
390
+ iteration: goal.iteration,
391
+ marker,
392
+ prompt: buildContinuePrompt(goal, marker),
393
+ };
394
+ return true;
395
+ }
396
+
397
+ dispatchContinuationIfSettled(ctx: StatusContext) {
398
+ const intent = this.continuationIntent;
399
+ if (!this.ownsWorkflow()) {
400
+ this.cancelContinuationWork();
401
+ return false;
402
+ }
403
+ if (!intent) return false;
404
+ if (this.activeGoal?.status === "active" && !this.goalToolsAvailable()) {
405
+ this.pauseGoalForUnavailableTools(ctx);
406
+ return false;
407
+ }
408
+ if (
409
+ !this.activeGoal ||
410
+ this.activeGoal.id !== intent.goalId ||
411
+ this.activeGoal.status !== "active" ||
412
+ this.activeGoal.waiting
413
+ ) {
414
+ this.continuationIntent = undefined;
415
+ return false;
416
+ }
417
+ if (this.enforceAutomaticTurnLimit(ctx, false) || this.enforceNoProgressLimit(ctx)) {
418
+ return false;
419
+ }
420
+ if (ctx.isIdle?.() !== true || hasPendingMessages(ctx)) return false;
421
+
422
+ this.clearContinuationDispatchTimer();
423
+ this.continuationIntent = undefined;
424
+ this.continuationDelivery = intent;
425
+ try {
426
+ this.pi.sendUserMessage(intent.prompt, { deliverAs: "followUp" });
427
+ return true;
428
+ } catch (error) {
429
+ if (this.continuationDelivery?.marker === intent.marker) {
430
+ this.continuationDelivery = undefined;
431
+ }
432
+ if (this.activeGoal?.id === intent.goalId && this.activeGoal.status === "active") {
433
+ this.continuationIntent = intent;
434
+ }
435
+ notifyWhenSessionAlive(ctx, `Goal prompt failed: ${formatError(error)}`, "error");
436
+ return false;
437
+ }
438
+ }
439
+
440
+ hasContinuationWorkForGoal(goalId: string) {
441
+ return this.continuationIntent?.goalId === goalId || this.continuationDelivery?.goalId === goalId;
442
+ }
443
+
444
+ enterGoalWait(ctx: StatusContext, goalId: string, waiting: GoalWait) {
445
+ const goal = this.activeGoal;
446
+ if (!goal || goal.id !== goalId || !this.ownsWorkflow(goal)) return undefined;
447
+ this.recordGoalUsage(goal, ctx, false);
448
+ this.cancelContinuationWork();
449
+ this.clearGoalRecoveryForGoal(goal.id);
450
+ this.clearGoalWaitTimer();
451
+ this.activeGoal = {
452
+ ...goal,
453
+ waiting,
454
+ activeStartedAt: undefined,
455
+ updatedAt: Date.now(),
456
+ };
457
+ this.persistGoal(this.activeGoal);
458
+ this.updateStatus(ctx, this.activeGoal);
459
+ this.restoreGoalWaitTimer(ctx);
460
+ return this.activeGoal;
461
+ }
462
+
463
+ clearGoalWait(ctx: StatusContext, goalId: string) {
464
+ const goal = this.activeGoal;
465
+ if (!goal || goal.id !== goalId || !this.ownsWorkflow(goal) || !goal.waiting) return false;
466
+ this.clearGoalWaitTimer();
467
+ const { waiting: _waiting, ...nextGoal } = goal;
468
+ const now = Date.now();
469
+ checkpointGoalActiveTime(nextGoal, now, true);
470
+ nextGoal.updatedAt = now;
471
+ this.activeGoal = nextGoal;
472
+ this.persistGoal(this.activeGoal);
473
+ this.updateStatus(ctx, this.activeGoal);
474
+ return true;
475
+ }
476
+
477
+ restoreGoalWaitTimer(ctx: StatusContext) {
478
+ this.clearGoalWaitTimer();
479
+ const goal = this.activeGoal;
480
+ if (!this.ownsWorkflow(goal)) return false;
481
+ const resumeAt = goal?.status === "active" ? goal.waiting?.resumeAt : undefined;
482
+ if (!goal || resumeAt === undefined) return false;
483
+ this.scheduleGoalWaitTimer(ctx, goal.id, resumeAt);
484
+ return true;
485
+ }
486
+
487
+ dispatchDueGoalWait(ctx: StatusContext) {
488
+ const goal = this.activeGoal;
489
+ if (!this.ownsWorkflow(goal)) return false;
490
+ const waiting = goal?.status === "active" ? goal.waiting : undefined;
491
+ const resumeAt = waiting?.resumeAt;
492
+ if (!goal || !waiting || resumeAt === undefined) return false;
493
+ const retry = this.goalWaitDeadlineRetry;
494
+ const matchingRetry = retry?.goalId === goal.id && retry.resumeAt === resumeAt ? retry : undefined;
495
+ if (matchingRetry?.exhausted) return false;
496
+ const wakeAt = matchingRetry?.retryAt ?? resumeAt;
497
+ if (Date.now() < wakeAt) return false;
498
+ const retryAttempt = matchingRetry?.retryAt !== undefined;
499
+ if (ctx.isIdle?.() !== true || hasPendingMessages(ctx)) return false;
500
+ if (retryAttempt) this.goalWaitDeadlineRetry = undefined;
501
+ if (!this.clearGoalWait(ctx, goal.id)) return false;
502
+ const resumedGoal = this.activeGoal;
503
+ if (!resumedGoal || resumedGoal.id !== goal.id || resumedGoal.status !== "active") return false;
504
+ this.requestContinuation(resumedGoal);
505
+ const dispatched = this.dispatchContinuationIfSettled(ctx);
506
+ if (dispatched) return true;
507
+ if (
508
+ this.activeGoal?.id === goal.id &&
509
+ this.activeGoal.status === "active" &&
510
+ this.continuationIntent?.goalId === goal.id
511
+ ) {
512
+ this.restoreGoalWaitAfterDeadlineFailure(ctx, goal.id, waiting, !retryAttempt);
513
+ }
514
+ return false;
515
+ }
516
+
517
+ clearGoalWaitTimer() {
518
+ this.goalWaitTimer.clear();
519
+ this.goalWaitDeadlineRetry = undefined;
520
+ }
521
+
522
+ private scheduleGoalWaitTimer(ctx: StatusContext, goalId: string, wakeAt: number) {
523
+ const generation = this.menuGeneration;
524
+ this.goalWaitTimer.schedule(wakeAt, () => {
525
+ if (generation !== this.menuGeneration || this.activeGoal?.id !== goalId || !this.ownsWorkflow(this.activeGoal)) {
526
+ return;
527
+ }
528
+ try {
529
+ this.dispatchDueGoalWait(ctx);
530
+ } catch (error) {
531
+ notifyWhenSessionAlive(ctx, `Goal wait deadline failed: ${formatError(error)}`, "error");
532
+ }
533
+ });
534
+ }
535
+
536
+ private restoreGoalWaitAfterDeadlineFailure(
537
+ ctx: StatusContext,
538
+ goalId: string,
539
+ waiting: GoalWait,
540
+ allowRetry: boolean,
541
+ ) {
542
+ const goal = this.activeGoal;
543
+ if (!goal || goal.id !== goalId || goal.status !== "active" || waiting.resumeAt === undefined) {
544
+ return;
545
+ }
546
+ this.cancelContinuationWork();
547
+ this.recordGoalUsage(goal, ctx, false);
548
+ this.goalWaitTimer.clear();
549
+ this.activeGoal = {
550
+ ...goal,
551
+ waiting,
552
+ activeStartedAt: undefined,
553
+ updatedAt: Date.now(),
554
+ };
555
+ const retryAt = allowRetry ? Date.now() + 1_000 : undefined;
556
+ this.goalWaitDeadlineRetry = {
557
+ goalId,
558
+ resumeAt: waiting.resumeAt,
559
+ retryAt,
560
+ exhausted: !allowRetry,
561
+ };
562
+ this.persistGoal(this.activeGoal);
563
+ this.updateStatus(ctx, this.activeGoal);
564
+ if (retryAt !== undefined) this.scheduleGoalWaitTimer(ctx, goalId, retryAt);
565
+ }
566
+
567
+ updateStatus(ctx: StatusContext, goal: ActiveGoal) {
568
+ this.clearCompletionStatusTimer();
569
+ ctx.ui.setStatus(STATUS_KEY, formatStatus(goal, this.settings.continuationLimits.automaticTurns));
570
+ }
571
+
572
+ stopActiveGoal(ctx: StatusContext, request: GoalStopRequest) {
573
+ const currentGoal = this.activeGoal;
574
+ if (!currentGoal || currentGoal.id !== request.expectedGoalId) return undefined;
575
+
576
+ this.clearGoalWaitTimer();
577
+ let goal = currentGoal;
578
+ let status: StoppedGoalStatus;
579
+ let terminalReason: string | undefined;
580
+ switch (request.kind) {
581
+ case "explicit_pause":
582
+ this.recordGoalUsage(goal, ctx);
583
+ this.cancelContinuationWork();
584
+ this.clearGoalRecoveryForGoal(goal.id);
585
+ this.clearBudgetWrapUp();
586
+ this.blockStaleGoalToolCalls();
587
+ abortCurrentTurn(ctx);
588
+ status = "paused";
589
+ break;
590
+ case "budget_limit":
591
+ this.cancelContinuationWork();
592
+ this.clearGoalRecoveryForGoal(goal.id);
593
+ this.clearBudgetWrapUp();
594
+ this.blockStaleGoalToolCalls();
595
+ abortCurrentTurn(ctx);
596
+ status = "budget_limited";
597
+ terminalReason = request.reason;
598
+ break;
599
+ case "safety_pause":
600
+ this.cancelContinuationWork();
601
+ this.clearGoalRecoveryForGoal(goal.id);
602
+ this.clearBudgetWrapUp();
603
+ this.blockStaleGoalToolCalls();
604
+ if (request.abortTurn) {
605
+ this.guardAbortGoalId = goal.id;
606
+ abortCurrentTurn(ctx);
607
+ }
608
+ goal = { ...goal, safetyPauseCause: request.cause };
609
+ status = "paused";
610
+ terminalReason = request.reason;
611
+ break;
612
+ case "retry_exhausted":
613
+ this.clearGoalRecoveryForGoal(goal.id);
614
+ this.cancelContinuationWork();
615
+ this.clearBudgetWrapUp();
616
+ this.blockStaleGoalToolCalls();
617
+ status = "blocked";
618
+ terminalReason = request.reason;
619
+ break;
620
+ case "tools_unavailable":
621
+ if (request.recordUsage) this.recordGoalUsage(goal, ctx);
622
+ this.cancelContinuationWork();
623
+ this.clearGoalRecoveryForGoal(goal.id);
624
+ this.clearBudgetWrapUp();
625
+ if (request.abortTurn) {
626
+ this.blockStaleGoalToolCalls();
627
+ abortCurrentTurn(ctx);
628
+ } else {
629
+ this.clearStaleGoalToolCallBlock();
630
+ }
631
+ status = "paused";
632
+ break;
633
+ case "blocker_report":
634
+ this.recordGoalUsage(goal, ctx);
635
+ this.cancelContinuationWork();
636
+ this.clearBudgetWrapUp();
637
+ this.clearGoalRecoveryForGoal(goal.id);
638
+ this.blockStaleGoalToolCalls();
639
+ status = "blocked";
640
+ terminalReason = request.reason;
641
+ break;
642
+ case "agent_interruption":
643
+ this.cancelContinuationWork();
644
+ this.clearBudgetWrapUp();
645
+ this.blockStaleGoalToolCalls();
646
+ abortCurrentTurn(ctx);
647
+ status = request.status;
648
+ terminalReason = request.reason;
649
+ break;
650
+ case "activation_rollback":
651
+ goal = request.restoreGoal;
652
+ if (request.abortTurn) abortCurrentTurn(ctx);
653
+ this.blockStaleGoalToolCalls();
654
+ status = "paused";
655
+ break;
656
+ }
657
+
658
+ this.activeGoal = transitionGoal(goal, status);
659
+ if (terminalReason !== undefined) this.setTerminalReason(this.activeGoal.id, terminalReason);
660
+ const stoppedGoal = this.activeGoal;
661
+ this.persistGoal(stoppedGoal);
662
+ if (request.kind !== "blocker_report") this.ensureInactiveGoalContextContract(ctx);
663
+ if (this.activeGoal?.id === stoppedGoal.id && this.activeGoal.status === stoppedGoal.status) {
664
+ this.updateStatus(ctx, stoppedGoal);
665
+ this.releaseWorkflow();
666
+ }
667
+ return stoppedGoal;
668
+ }
669
+
670
+ blockStaleGoalToolCalls() {
671
+ this.staleGoalToolCallsBlocked = true;
672
+ }
673
+
674
+ clearStaleGoalToolCallBlock() {
675
+ this.staleGoalToolCallsBlocked = false;
676
+ }
677
+
678
+ clearGoalRecovery() {
679
+ this.goalRecovery = undefined;
680
+ }
681
+
682
+ clearBudgetWrapUp() {
683
+ this.budgetWrapUp = undefined;
684
+ }
685
+
686
+ setCompletionSummary(goalId: string, summary: string) {
687
+ this.terminalDetails = { goalId, summary };
688
+ }
689
+
690
+ setTerminalReason(goalId: string, reason: string) {
691
+ this.terminalDetails = { goalId, reason };
692
+ }
693
+
694
+ clearTerminalDetails() {
695
+ this.terminalDetails = undefined;
696
+ }
697
+
698
+ isActiveBudgetWrapUpMessage(message: unknown) {
699
+ if (!message || typeof message !== "object") return false;
700
+ const candidate = message as {
701
+ role?: unknown;
702
+ customType?: unknown;
703
+ details?: { goalId?: unknown };
704
+ };
705
+ return (
706
+ candidate.role === "custom" &&
707
+ candidate.customType === BUDGET_WRAP_UP_MESSAGE_TYPE &&
708
+ typeof candidate.details?.goalId === "string" &&
709
+ candidate.details.goalId === this.budgetWrapUp?.goalId &&
710
+ candidate.details.goalId === this.activeGoal?.id
711
+ );
712
+ }
713
+
714
+ keepBudgetWrapUpMessage(message: unknown) {
715
+ if (!message || typeof message !== "object") return true;
716
+ const candidate = message as { role?: unknown; customType?: unknown };
717
+ if (candidate.role !== "custom" || candidate.customType !== BUDGET_WRAP_UP_MESSAGE_TYPE) {
718
+ return true;
719
+ }
720
+ return this.isActiveBudgetWrapUpMessage(message);
721
+ }
722
+
723
+ queueBudgetWrapUp(ctx: StatusContext, goal: ActiveGoal) {
724
+ if (!this.ownsWorkflow(goal)) return false;
725
+ if (!this.budgetWrapUp || this.budgetWrapUp.goalId !== goal.id) {
726
+ this.budgetWrapUp = { goalId: goal.id, delivered: false };
727
+ }
728
+ if (this.budgetWrapUp.delivered) return true;
729
+ this.budgetWrapUp.delivered = true;
730
+ try {
731
+ this.pi.sendMessage(
732
+ {
733
+ customType: BUDGET_WRAP_UP_MESSAGE_TYPE,
734
+ content: BUDGET_WRAP_UP_PROMPT,
735
+ display: true,
736
+ details: { goalId: goal.id },
737
+ },
738
+ { deliverAs: "steer" },
739
+ );
740
+ return true;
741
+ } catch (error) {
742
+ this.budgetWrapUp.delivered = false;
743
+ notifyWhenSessionAlive(ctx, `Goal budget wrap-up failed: ${formatError(error)}`, "error");
744
+ return false;
745
+ }
746
+ }
747
+
748
+ limitActiveGoalForBudget(ctx: StatusContext, sendWrapUp: boolean) {
749
+ const goal = this.activeGoal;
750
+ if (goal?.status !== "active" || goal.tokenBudget === undefined || goal.tokensUsed < goal.tokenBudget) {
751
+ return false;
752
+ }
753
+
754
+ const stoppedGoal = this.stopActiveGoal(ctx, {
755
+ kind: "budget_limit",
756
+ expectedGoalId: goal.id,
757
+ reason: `token budget reached (${formatBudget(goal)})`,
758
+ });
759
+ if (!stoppedGoal) return false;
760
+ notifyTerminal(ctx.ui, `Goal token budget reached: ${formatBudget(stoppedGoal)}`, "warning");
761
+ if (sendWrapUp) this.queueBudgetWrapUp(ctx, stoppedGoal);
762
+ return true;
763
+ }
764
+
765
+ recordAutomaticTurn(ctx: StatusContext, message: unknown) {
766
+ const goal = this.activeGoal;
767
+ if (goal?.status !== "active" || !this.isAutomaticRunForGoal(goal.id)) return false;
768
+ const candidate = message as { role?: unknown; stopReason?: unknown } | undefined;
769
+ if (candidate?.role === "assistant" && candidate.stopReason === "aborted") return false;
770
+ goal.automaticModelTurns = Math.min(Number.MAX_SAFE_INTEGER, goal.automaticModelTurns + 1);
771
+ this.recordGoalUsage(goal, ctx);
772
+ this.persistGoal(goal);
773
+ this.updateStatus(ctx, goal);
774
+ // Terminal errors need agent_end classification before a safety pause can
775
+ // choose between usage_limited, blocked, or retryable cleanup.
776
+ if (candidate?.role === "assistant" && candidate.stopReason === "error") return false;
777
+ return this.enforceAutomaticTurnLimit(ctx, true);
778
+ }
779
+
780
+ recordAutomaticRunProgress(ctx: StatusContext, goalId: string, messages: readonly unknown[], toolAttempted: boolean) {
781
+ const goal = this.activeGoal;
782
+ if (goal?.id !== goalId || goal.status !== "active") return false;
783
+ const next = nextToolFreeRepeatState(goal, messages, toolAttempted);
784
+ goal.toolFreeRepeatCount = next.toolFreeRepeatCount;
785
+ goal.lastToolFreeOutputFingerprint = next.lastToolFreeOutputFingerprint;
786
+ this.persistGoal(goal);
787
+ this.updateStatus(ctx, goal);
788
+ const limit = this.settings.continuationLimits.noProgressTurns;
789
+ if (limit === null || goal.toolFreeRepeatCount < limit) return false;
790
+ return this.pauseGoalForSafety(ctx, "no_progress", false);
791
+ }
792
+
793
+ enforceAutomaticTurnLimit(ctx: StatusContext, abortTurn: boolean) {
794
+ const goal = this.activeGoal;
795
+ const limit = this.settings.continuationLimits.automaticTurns;
796
+ if (goal?.status !== "active" || limit === null || goal.automaticModelTurns < limit) {
797
+ return false;
798
+ }
799
+ return this.pauseGoalForSafety(ctx, "continuation_limit", abortTurn);
800
+ }
801
+
802
+ enforceNoProgressLimit(ctx: StatusContext, abortTurn = false) {
803
+ const goal = this.activeGoal;
804
+ const limit = this.settings.continuationLimits.noProgressTurns;
805
+ if (goal?.status !== "active" || limit === null || goal.toolFreeRepeatCount < limit) {
806
+ return false;
807
+ }
808
+ return this.pauseGoalForSafety(ctx, "no_progress", abortTurn);
809
+ }
810
+
811
+ pauseGoalForSafety(ctx: StatusContext, cause: SafetyPauseCause, abortTurn: boolean) {
812
+ const goal = this.activeGoal;
813
+ if (goal?.status !== "active") return false;
814
+ const automaticLimit = this.settings.continuationLimits.automaticTurns;
815
+ const count =
816
+ cause === "continuation_limit"
817
+ ? `${goal.automaticModelTurns} of ${automaticLimit ?? "Unlimited"} automatic model responses`
818
+ : `no progress across ${goal.toolFreeRepeatCount} automatic runs`;
819
+ const stoppedGoal = this.stopActiveGoal(ctx, {
820
+ kind: "safety_pause",
821
+ expectedGoalId: goal.id,
822
+ cause,
823
+ abortTurn,
824
+ reason: `${cause} (${count}; ${formatTokenCount(goal.tokensUsed)} tokens)`,
825
+ });
826
+ if (!stoppedGoal) return false;
827
+ notifyTerminal(
828
+ ctx.ui,
829
+ cause === "continuation_limit"
830
+ ? `Automatic-work limit reached: ${stoppedGoal.automaticModelTurns} of ${automaticLimit} responses. Goal progress is saved with ${formatTokenCount(stoppedGoal.tokensUsed)} cumulative tokens. Open /goal to review and continue.`
831
+ : `Goal paused: ${count}; ${formatTokenCount(stoppedGoal.tokensUsed)} cumulative tokens. Open /goal to review and continue.`,
832
+ "warning",
833
+ );
834
+ return true;
835
+ }
836
+
837
+ resetActiveSafetyEpoch(ctx: StatusContext) {
838
+ const goal = this.activeGoal;
839
+ if (goal?.status !== "active") return false;
840
+ this.activeGoal = resetGoalSafetyEpoch(goal);
841
+ this.reclassifyAgentRunAsManual();
842
+ this.persistGoal(this.activeGoal);
843
+ this.updateStatus(ctx, this.activeGoal);
844
+ return true;
845
+ }
846
+
847
+ finalizeSettledRecovery(ctx: StatusContext) {
848
+ const recovery = this.goalRecovery;
849
+ if (!recovery) return false;
850
+ this.goalRecovery = undefined;
851
+ const goal = this.activeGoal;
852
+ if (goal?.id !== recovery.goalId || goal.status !== "active" || !this.ownsWorkflow(goal)) {
853
+ return false;
854
+ }
855
+ const details = recovery.errorMessage ? `: ${truncateNotification(recovery.errorMessage)}` : "";
856
+ if (recovery.kind === "provider_retry") {
857
+ const waitingGoal = this.enterGoalWait(ctx, goal.id, {
858
+ reason: `Provider retries exhausted${details}`,
859
+ });
860
+ if (!waitingGoal) return false;
861
+ notifyTerminal(
862
+ ctx.ui,
863
+ `Goal waiting after provider retries were exhausted${details}. Send a follow-up or run /goal resume to retry.`,
864
+ "warning",
865
+ );
866
+ return true;
867
+ }
868
+ const stoppedGoal = this.stopActiveGoal(ctx, {
869
+ kind: "retry_exhausted",
870
+ expectedGoalId: goal.id,
871
+ reason: `agent error after retries${details}`,
872
+ });
873
+ if (!stoppedGoal) return false;
874
+ notifyTerminal(
875
+ ctx.ui,
876
+ `Goal blocked after agent error retries were exhausted${details}. Resolve the blocker or run /goal resume to retry.`,
877
+ "warning",
878
+ );
879
+ return true;
880
+ }
881
+
882
+ clearSettledSafetyTracking() {
883
+ this.guardAbortGoalId = undefined;
884
+ this.pendingNonGoalInputs = [];
885
+ this.claimedGoalPromptMarkers.clear();
886
+ this.claimedContinuationMarkers.clear();
887
+ this.clearAgentRun();
888
+ }
889
+
890
+ clearGoalRecoveryForGoal(goalId: string) {
891
+ if (this.goalRecovery?.goalId === goalId) this.goalRecovery = undefined;
892
+ }
893
+
894
+ isPiOwnedCompactionRetry(event: unknown, goalId: string) {
895
+ const compaction = event as { reason?: unknown; willRetry?: unknown };
896
+ if (compaction.willRetry === true) return true;
897
+ return (
898
+ this.goalRecovery?.goalId === goalId &&
899
+ this.goalRecovery.kind === "compaction_retry" &&
900
+ (compaction.reason === undefined || compaction.reason === "overflow")
901
+ );
902
+ }
903
+
904
+ clearContinuationTracking() {
905
+ this.clearContinuationDispatchTimer();
906
+ this.continuationIntent = undefined;
907
+ this.continuationDelivery = undefined;
908
+ this.cancelledContinuationMarkers.clear();
909
+ this.claimedContinuationMarkers.clear();
910
+ }
911
+
912
+ clearPendingGoalPrompts() {
913
+ this.pendingGoalPromptMarkers.clear();
914
+ this.claimedGoalPromptMarkers.clear();
915
+ this.cancelledGoalPromptMarkers.clear();
916
+ this.pendingNonGoalInputs = [];
917
+ }
918
+
919
+ ensureGoalContextContract(ctx: StatusContext, goal: ActiveGoal) {
920
+ const contract = this.goalContextContractForPrompt(ctx, goal);
921
+ if (contract) this.pi.sendMessage(contract, { triggerTurn: false });
922
+ }
923
+
924
+ ensureInactiveGoalContextContract(ctx: StatusContext) {
925
+ const contract = this.goalContextContractForPrompt(ctx);
926
+ if (contract) this.pi.sendMessage(contract, { triggerTurn: false });
927
+ }
928
+
929
+ goalContextContractForPrompt(ctx: StatusContext, goal?: ActiveGoal) {
930
+ const { contextEntries, historyEntries } = goalContractEntries(ctx);
931
+ if (goal) {
932
+ return hasGoalContextContract(contextEntries, goal) ? undefined : createGoalContextContract(goal);
933
+ }
934
+ const hasHistory = hasGoalContextContractHistory(contextEntries) || hasGoalContextContractHistory(historyEntries);
935
+ if (!hasHistory || hasInactiveGoalContextContract(contextEntries)) return undefined;
936
+ return createInactiveGoalContextContract();
937
+ }
938
+
939
+ hasGoalContextContractHistory(ctx: StatusContext) {
940
+ const { contextEntries, historyEntries } = goalContractEntries(ctx);
941
+ return hasGoalContextContractHistory(contextEntries) || hasGoalContextContractHistory(historyEntries);
942
+ }
943
+
944
+ async sendOwnedGoalPrompt(
945
+ ctx: StatusContext,
946
+ goalId: string,
947
+ prompt: string,
948
+ resetSafetyEpoch = true,
949
+ isCurrent?: () => boolean,
950
+ ) {
951
+ if (this.activeGoal?.id !== goalId || !this.ownsWorkflow(this.activeGoal)) return false;
952
+ const pending = this.rememberPendingGoalPrompt(goalId, prompt, resetSafetyEpoch);
953
+ const sent = await sendPrompt(this.pi, ctx, pending.prompt, isCurrent);
954
+ if (!sent || (isCurrent && !isCurrent()) || this.activeGoal?.id !== goalId || !this.ownsWorkflow(this.activeGoal)) {
955
+ this.pendingGoalPromptMarkers.delete(pending.marker);
956
+ return false;
957
+ }
958
+ return true;
959
+ }
960
+
961
+ cancelContinuationWork() {
962
+ this.clearContinuationDispatchTimer();
963
+ if (this.continuationDelivery) {
964
+ this.rememberCancelledContinuationMarker(this.continuationDelivery);
965
+ }
966
+ this.continuationIntent = undefined;
967
+ this.continuationDelivery = undefined;
968
+ }
969
+
970
+ scheduleContinuationDispatch(ctx: StatusContext, goalId: string) {
971
+ this.clearContinuationDispatchTimer();
972
+ const generation = this.menuGeneration;
973
+ this.continuationDispatchTimer = setTimeout(() => {
974
+ this.continuationDispatchTimer = undefined;
975
+ if (generation !== this.menuGeneration || this.activeGoal?.id !== goalId || !this.ownsWorkflow(this.activeGoal)) {
976
+ return;
977
+ }
978
+ this.dispatchContinuationIfSettled(ctx);
979
+ }, 0);
980
+ }
981
+
982
+ private clearContinuationDispatchTimer() {
983
+ if (!this.continuationDispatchTimer) return;
984
+ clearTimeout(this.continuationDispatchTimer);
985
+ this.continuationDispatchTimer = undefined;
986
+ }
987
+
988
+ consumeCancelledGoalPrompt(prompt: string) {
989
+ const marker = extractGoalPromptMarker(prompt);
990
+ if (!marker) return false;
991
+ const cancelledPrompt = this.cancelledGoalPromptMarkers.get(marker);
992
+ if (!cancelledPrompt || !preservesOwnedPromptAtTerminalBoundary(prompt, cancelledPrompt)) {
993
+ return false;
994
+ }
995
+ this.cancelledGoalPromptMarkers.delete(marker);
996
+ return true;
997
+ }
998
+
999
+ consumeCancelledContinuationPrompt(prompt: string) {
1000
+ const marker = extractContinuationMarker(prompt);
1001
+ if (!marker) return false;
1002
+ const cancelledPrompt = this.cancelledContinuationMarkers.get(marker);
1003
+ if (!cancelledPrompt || !preservesOwnedPromptAtTerminalBoundary(prompt, cancelledPrompt)) {
1004
+ return false;
1005
+ }
1006
+ this.cancelledContinuationMarkers.delete(marker);
1007
+ return true;
1008
+ }
1009
+
1010
+ acceptOwnedInputBoundary(prompt: string) {
1011
+ const fingerprint = inputFingerprint(prompt);
1012
+ const goalMarker = extractGoalPromptMarker(prompt);
1013
+ if (goalMarker) {
1014
+ const pending = this.pendingGoalPromptMarkers.get(goalMarker);
1015
+ if (pending && preservesOwnedPromptAtTerminalBoundary(prompt, pending.prompt)) return true;
1016
+ if (this.claimedGoalPromptMarkers.get(goalMarker) === fingerprint) return true;
1017
+ }
1018
+ const continuationMarker = extractContinuationMarker(prompt);
1019
+ if (!continuationMarker) return false;
1020
+ if (
1021
+ this.continuationDelivery?.marker === continuationMarker &&
1022
+ preservesOwnedPromptAtTerminalBoundary(prompt, this.continuationDelivery.prompt)
1023
+ ) {
1024
+ return true;
1025
+ }
1026
+ return this.claimedContinuationMarkers.get(continuationMarker) === fingerprint;
1027
+ }
1028
+
1029
+ supersedeOwnedInputCollision(prompt: string) {
1030
+ const fingerprint = inputFingerprint(prompt);
1031
+ const goalMarker = extractGoalPromptMarker(prompt);
1032
+ if (goalMarker) {
1033
+ const pending = this.pendingGoalPromptMarkers.get(goalMarker);
1034
+ if (pending && pending.fingerprint !== fingerprint) {
1035
+ this.pendingGoalPromptMarkers.delete(goalMarker);
1036
+ this.rememberCancelledGoalPromptMarker(goalMarker, pending.prompt);
1037
+ }
1038
+ this.claimedGoalPromptMarkers.delete(goalMarker);
1039
+ }
1040
+ const continuationMarker = extractContinuationMarker(prompt);
1041
+ if (!continuationMarker) return;
1042
+ if (
1043
+ (this.continuationDelivery?.marker === continuationMarker &&
1044
+ !preservesOwnedPromptAtTerminalBoundary(prompt, this.continuationDelivery.prompt)) ||
1045
+ this.continuationIntent?.marker === continuationMarker
1046
+ ) {
1047
+ this.cancelContinuationWork();
1048
+ }
1049
+ this.claimedContinuationMarkers.delete(continuationMarker);
1050
+ }
1051
+
1052
+ hasOwnedPromptBoundary(prompt: string) {
1053
+ const fingerprint = inputFingerprint(prompt);
1054
+ const goalMarker = extractGoalPromptMarker(prompt);
1055
+ if (goalMarker) {
1056
+ const pending = this.pendingGoalPromptMarkers.get(goalMarker);
1057
+ if (
1058
+ (pending && preservesOwnedPromptAtTerminalBoundary(prompt, pending.prompt)) ||
1059
+ this.claimedGoalPromptMarkers.get(goalMarker) === fingerprint
1060
+ ) {
1061
+ return true;
1062
+ }
1063
+ }
1064
+ const continuationMarker = extractContinuationMarker(prompt);
1065
+ if (!continuationMarker) return false;
1066
+ return (
1067
+ (this.continuationDelivery?.marker === continuationMarker &&
1068
+ preservesOwnedPromptAtTerminalBoundary(prompt, this.continuationDelivery.prompt)) ||
1069
+ this.claimedContinuationMarkers.get(continuationMarker) === fingerprint
1070
+ );
1071
+ }
1072
+
1073
+ consumeStaleOwnedGoalPrompt(prompt: string) {
1074
+ const marker = extractGoalPromptMarker(prompt);
1075
+ if (!marker) return false;
1076
+ const pending = this.pendingGoalPromptMarkers.get(marker);
1077
+ if (!pending || !preservesOwnedPromptAtTerminalBoundary(prompt, pending.prompt)) return false;
1078
+ if (this.activeGoal?.id === pending.goalId && this.activeGoal.status === "active") {
1079
+ return false;
1080
+ }
1081
+ this.pendingGoalPromptMarkers.delete(marker);
1082
+ return true;
1083
+ }
1084
+
1085
+ noteQueuedNonGoalInput(prompt: string, behavior: "steer" | "followUp", resetSafetyEpoch = false) {
1086
+ this.pendingNonGoalInputs.push({
1087
+ behavior,
1088
+ fingerprint: inputFingerprint(prompt),
1089
+ resetSafetyEpoch,
1090
+ });
1091
+ if (this.pendingNonGoalInputs.length > MAX_PENDING_NON_GOAL_INPUTS) {
1092
+ this.pendingNonGoalInputs.shift();
1093
+ }
1094
+ }
1095
+
1096
+ consumeQueuedNonGoalInput(prompt: string, allowDeliveryFallback = true) {
1097
+ if (typeof prompt !== "string") return undefined;
1098
+ const fingerprint = inputFingerprint(prompt);
1099
+ // Pi delivers steers before follow-ups. Prefer a matching steer even when an
1100
+ // identical follow-up was queued first so it cannot steal follow-up ownership.
1101
+ const steerIndex = this.pendingNonGoalInputs.findIndex(
1102
+ (pending) => pending.behavior === "steer" && pending.fingerprint === fingerprint,
1103
+ );
1104
+ const exactIndex =
1105
+ steerIndex >= 0
1106
+ ? steerIndex
1107
+ : this.pendingNonGoalInputs.findIndex(
1108
+ (pending) => pending.behavior === "followUp" && pending.fingerprint === fingerprint,
1109
+ );
1110
+ if (exactIndex >= 0) return this.pendingNonGoalInputs.splice(exactIndex, 1)[0];
1111
+ if (!allowDeliveryFallback) return undefined;
1112
+
1113
+ // Skills, templates, and later input handlers can transform the raw text after
1114
+ // pi-goal records it. Fall back to Pi's delivery priority as a bounded marker:
1115
+ // steers drain before follow-ups, and settlement clears stale entries.
1116
+ const fallbackSteerIndex = this.pendingNonGoalInputs.findIndex((pending) => pending.behavior === "steer");
1117
+ const fallbackIndex =
1118
+ fallbackSteerIndex >= 0
1119
+ ? fallbackSteerIndex
1120
+ : this.pendingNonGoalInputs.findIndex((pending) => pending.behavior === "followUp");
1121
+ if (fallbackIndex < 0) return undefined;
1122
+ return this.pendingNonGoalInputs.splice(fallbackIndex, 1)[0];
1123
+ }
1124
+
1125
+ consumeQueuedNonGoalFollowUpForAgentStart() {
1126
+ // A pending steer owns the next intra-run boundary. Do not let a later
1127
+ // follow-up suppress cleanup until all earlier-priority steers have started.
1128
+ if (this.pendingNonGoalInputs.some((pending) => pending.behavior === "steer")) return false;
1129
+ const index = this.pendingNonGoalInputs.findIndex((pending) => pending.behavior === "followUp");
1130
+ if (index < 0) return false;
1131
+ this.pendingNonGoalInputs.splice(index, 1);
1132
+ return true;
1133
+ }
1134
+
1135
+ markContinuationStarted(prompt: string) {
1136
+ const marker = extractContinuationMarker(prompt);
1137
+ if (!marker) {
1138
+ // A user, retry, or another extension started newer work. Cancel both an
1139
+ // unsent intent and a delivery that may have lost the non-atomic idle race;
1140
+ // the newer work's agent_end will record a fresh intent.
1141
+ this.cancelContinuationWork();
1142
+ return undefined;
1143
+ }
1144
+ const fingerprint = inputFingerprint(prompt);
1145
+ if (this.continuationDelivery?.marker === marker) {
1146
+ const delivery = this.continuationDelivery;
1147
+ if (preservesOwnedPromptAtTerminalBoundary(prompt, delivery.prompt)) {
1148
+ this.continuationDelivery = undefined;
1149
+ this.rememberClaimedContinuationMarker(marker, prompt);
1150
+ return marker.split(":", 1)[0];
1151
+ }
1152
+ }
1153
+ const cancelledPrompt = this.cancelledContinuationMarkers.get(marker);
1154
+ if (
1155
+ this.claimedContinuationMarkers.get(marker) === fingerprint ||
1156
+ (cancelledPrompt && preservesOwnedPromptAtTerminalBoundary(prompt, cancelledPrompt))
1157
+ ) {
1158
+ return marker.split(":", 1)[0];
1159
+ }
1160
+ this.cancelContinuationWork();
1161
+ return undefined;
1162
+ }
1163
+
1164
+ persistGoal(goal: ActiveGoal) {
1165
+ if (!isTerminalGoalStatus(goal.status) || this.terminalDetails?.goalId !== goal.id) {
1166
+ this.clearTerminalDetails();
1167
+ }
1168
+ this.pi.appendEntry(GOAL_STATE_ENTRY_TYPE, serializeGoalState(goal));
1169
+ this.publishGoalState(buildGoalStateSnapshot(goal, this.terminalDetails?.summary, this.terminalDetails?.reason));
1170
+ }
1171
+
1172
+ clearPersistedGoal(cwd: string, clearedGoal?: ActiveGoal, reason = "goal cleared") {
1173
+ this.pi.appendEntry(GOAL_STATE_ENTRY_TYPE, serializeGoalState(undefined));
1174
+ if (clearedGoal) {
1175
+ this.publishGoalState({
1176
+ goalId: clearedGoal.id,
1177
+ status: "cleared",
1178
+ reason,
1179
+ });
1180
+ }
1181
+ this.clearTerminalDetails();
1182
+ clearLegacyPersistedGoal(cwd);
1183
+ }
1184
+
1185
+ clearActiveGoal(ctx: StatusContext, reason = "goal cleared", releaseWorkflow = true) {
1186
+ this.clearActiveGoalState(ctx, reason, releaseWorkflow);
1187
+ this.ensureInactiveGoalContextContract(ctx);
1188
+ }
1189
+
1190
+ clearCompletedGoal(ctx: StatusContext) {
1191
+ this.clearActiveGoalState(ctx, "goal cleared", true);
1192
+ }
1193
+
1194
+ private clearActiveGoalState(ctx: StatusContext, reason: string, releaseWorkflow: boolean) {
1195
+ const clearedGoal = this.activeGoal;
1196
+ this.clearGoalWaitTimer();
1197
+ this.cancelContinuationWork();
1198
+ this.clearGoalRecovery();
1199
+ this.clearBudgetWrapUp();
1200
+ this.clearStaleGoalToolCallBlock();
1201
+ this.activeGoal = undefined;
1202
+ this.legacyQueueState = undefined;
1203
+ this.clearPersistedGoal(ctx.cwd, clearedGoal, reason);
1204
+ ctx.ui.setStatus(STATUS_KEY, undefined);
1205
+ if (releaseWorkflow) this.releaseWorkflow();
1206
+ }
1207
+
1208
+ snapshotSettingsApplicationState(): GoalSettingsRuntimeSnapshot {
1209
+ return {
1210
+ settings: structuredClone(this.settings),
1211
+ activeGoal: this.activeGoal ? structuredClone(this.activeGoal) : undefined,
1212
+ legacyQueueState: this.legacyQueueState ? structuredClone(this.legacyQueueState) : undefined,
1213
+ legacyExperimentalGoalsSetting: this.legacyExperimentalGoalsSetting,
1214
+ continuationIntent: this.continuationIntent ? structuredClone(this.continuationIntent) : undefined,
1215
+ continuationDelivery: this.continuationDelivery ? structuredClone(this.continuationDelivery) : undefined,
1216
+ goalRecovery: this.goalRecovery ? structuredClone(this.goalRecovery) : undefined,
1217
+ budgetWrapUp: this.budgetWrapUp ? structuredClone(this.budgetWrapUp) : undefined,
1218
+ guardAbortGoalId: this.guardAbortGoalId,
1219
+ staleGoalToolCallsBlocked: this.staleGoalToolCallsBlocked,
1220
+ cancelledContinuationMarkers: [...this.cancelledContinuationMarkers],
1221
+ terminalDetails: this.terminalDetails ? structuredClone(this.terminalDetails) : undefined,
1222
+ };
1223
+ }
1224
+
1225
+ restoreSettingsApplicationState(snapshot: GoalSettingsRuntimeSnapshot) {
1226
+ if (snapshot.activeGoal?.status === "active" && !this.acquireWorkflow()) {
1227
+ throw new Error("another workflow became active before Goal settings could roll back");
1228
+ }
1229
+ this.settings = structuredClone(snapshot.settings);
1230
+ this.activeGoal = snapshot.activeGoal ? structuredClone(snapshot.activeGoal) : undefined;
1231
+ this.legacyQueueState = snapshot.legacyQueueState ? structuredClone(snapshot.legacyQueueState) : undefined;
1232
+ this.legacyExperimentalGoalsSetting = snapshot.legacyExperimentalGoalsSetting;
1233
+ this.continuationIntent = snapshot.continuationIntent ? structuredClone(snapshot.continuationIntent) : undefined;
1234
+ this.continuationDelivery = snapshot.continuationDelivery
1235
+ ? structuredClone(snapshot.continuationDelivery)
1236
+ : undefined;
1237
+ this.goalRecovery = snapshot.goalRecovery ? structuredClone(snapshot.goalRecovery) : undefined;
1238
+ this.budgetWrapUp = snapshot.budgetWrapUp ? structuredClone(snapshot.budgetWrapUp) : undefined;
1239
+ this.guardAbortGoalId = snapshot.guardAbortGoalId;
1240
+ this.staleGoalToolCallsBlocked = snapshot.staleGoalToolCallsBlocked;
1241
+ this.cancelledContinuationMarkers = new Map(snapshot.cancelledContinuationMarkers);
1242
+ this.terminalDetails = snapshot.terminalDetails ? structuredClone(snapshot.terminalDetails) : undefined;
1243
+ }
1244
+
1245
+ pauseGoalForUnavailableTools(ctx: StatusContext, abortTurn = true, recordUsage = true) {
1246
+ const goal = this.activeGoal;
1247
+ if (goal?.status !== "active") return false;
1248
+ const stoppedGoal = this.stopActiveGoal(ctx, {
1249
+ kind: "tools_unavailable",
1250
+ expectedGoalId: goal.id,
1251
+ abortTurn,
1252
+ recordUsage,
1253
+ });
1254
+ if (!stoppedGoal) return false;
1255
+ notifyTerminal(
1256
+ ctx.ui,
1257
+ "Goal tools are unavailable, so the active goal was paused. Restore the tools and run /goal resume.",
1258
+ "warning",
1259
+ );
1260
+ return true;
1261
+ }
1262
+
1263
+ showCompletionStatus(ctx: StatusContext) {
1264
+ this.clearCompletionStatusTimer();
1265
+ ctx.ui.setStatus(STATUS_KEY, "complete");
1266
+ this.completionStatusTimer = setTimeout(() => {
1267
+ this.completionStatusTimer = undefined;
1268
+ try {
1269
+ ctx.ui.setStatus(STATUS_KEY, undefined);
1270
+ } catch {
1271
+ // The completion status is best-effort; the captured ctx may be stale after
1272
+ // session replacement or reload before this timer fires.
1273
+ }
1274
+ }, 8_000);
1275
+ }
1276
+
1277
+ clearCompletionStatusTimer() {
1278
+ if (!this.completionStatusTimer) return;
1279
+ clearTimeout(this.completionStatusTimer);
1280
+ this.completionStatusTimer = undefined;
1281
+ }
1282
+
1283
+ private rememberPendingGoalPrompt(goalId: string, prompt: string, resetSafetyEpoch: boolean) {
1284
+ const marker = randomUUID();
1285
+ const ownedPrompt = appendGoalPromptMarker(prompt, marker);
1286
+ this.pendingGoalPromptMarkers.set(marker, {
1287
+ goalId,
1288
+ resetSafetyEpoch,
1289
+ fingerprint: inputFingerprint(ownedPrompt),
1290
+ prompt: ownedPrompt,
1291
+ });
1292
+ if (this.pendingGoalPromptMarkers.size > MAX_PENDING_GOAL_PROMPTS) {
1293
+ const oldest = this.pendingGoalPromptMarkers.keys().next().value;
1294
+ if (oldest) this.pendingGoalPromptMarkers.delete(oldest);
1295
+ }
1296
+ return { marker, prompt: ownedPrompt };
1297
+ }
1298
+
1299
+ private consumePendingGoalPrompt(prompt: string) {
1300
+ const marker = extractGoalPromptMarker(prompt);
1301
+ if (!marker) return undefined;
1302
+ const pending = this.pendingGoalPromptMarkers.get(marker);
1303
+ if (!pending || !preservesOwnedPromptAtTerminalBoundary(prompt, pending.prompt)) {
1304
+ return undefined;
1305
+ }
1306
+ this.pendingGoalPromptMarkers.delete(marker);
1307
+ this.rememberClaimedGoalPromptMarker(marker, inputFingerprint(prompt));
1308
+ return pending;
1309
+ }
1310
+
1311
+ private rememberCancelledGoalPromptMarker(marker: string, prompt: string) {
1312
+ this.cancelledGoalPromptMarkers.set(marker, prompt);
1313
+ if (this.cancelledGoalPromptMarkers.size <= MAX_PENDING_GOAL_PROMPTS) return;
1314
+ const oldest = this.cancelledGoalPromptMarkers.keys().next().value;
1315
+ if (oldest) this.cancelledGoalPromptMarkers.delete(oldest);
1316
+ }
1317
+
1318
+ private rememberClaimedGoalPromptMarker(marker: string, fingerprint: string) {
1319
+ this.claimedGoalPromptMarkers.set(marker, fingerprint);
1320
+ if (this.claimedGoalPromptMarkers.size <= MAX_PENDING_GOAL_PROMPTS) return;
1321
+ const oldest = this.claimedGoalPromptMarkers.keys().next().value;
1322
+ if (oldest) this.claimedGoalPromptMarkers.delete(oldest);
1323
+ }
1324
+
1325
+ private rememberClaimedContinuationMarker(marker: string, prompt: string) {
1326
+ this.claimedContinuationMarkers.set(marker, inputFingerprint(prompt));
1327
+ if (this.claimedContinuationMarkers.size <= MAX_CANCELLED_CONTINUATION_PROMPTS) return;
1328
+ const oldest = this.claimedContinuationMarkers.keys().next().value;
1329
+ if (oldest) this.claimedContinuationMarkers.delete(oldest);
1330
+ }
1331
+
1332
+ consumeOwnedGoalPrompt(prompt: string) {
1333
+ return this.consumePendingGoalPrompt(prompt);
1334
+ }
1335
+
1336
+ private rememberCancelledContinuationMarker(ticket: ContinuationTicket) {
1337
+ this.cancelledContinuationMarkers.set(ticket.marker, ticket.prompt);
1338
+ if (this.cancelledContinuationMarkers.size <= MAX_CANCELLED_CONTINUATION_PROMPTS) return;
1339
+ const oldest = this.cancelledContinuationMarkers.keys().next().value;
1340
+ if (oldest) this.cancelledContinuationMarkers.delete(oldest);
1341
+ }
1403
1342
  }
1404
1343
 
1405
- export function createGoal(
1406
- text: string,
1407
- tokenBudget: number | undefined,
1408
- baselineTokens: number,
1409
- ): ActiveGoal {
1410
- const now = Date.now();
1411
- return {
1412
- id: randomUUID(),
1413
- text,
1414
- status: "active",
1415
- startedAt: now,
1416
- updatedAt: now,
1417
- iteration: 0,
1418
- tokenBudget,
1419
- tokensUsed: 0,
1420
- timeUsedSeconds: 0,
1421
- baselineTokens,
1422
- activeStartedAt: now,
1423
- automaticModelTurns: 0,
1424
- toolFreeRepeatCount: 0,
1425
- };
1344
+ export function createGoal(text: string, tokenBudget: number | undefined, baselineTokens: number): ActiveGoal {
1345
+ const now = Date.now();
1346
+ return {
1347
+ id: randomUUID(),
1348
+ text,
1349
+ status: "active",
1350
+ startedAt: now,
1351
+ updatedAt: now,
1352
+ iteration: 0,
1353
+ tokenBudget,
1354
+ tokensUsed: 0,
1355
+ timeUsedSeconds: 0,
1356
+ baselineTokens,
1357
+ activeStartedAt: now,
1358
+ automaticModelTurns: 0,
1359
+ toolFreeRepeatCount: 0,
1360
+ };
1426
1361
  }
1427
1362
 
1428
1363
  export function transitionGoal(goal: ActiveGoal, requestedStatus: GoalStatus): ActiveGoal {
1429
- const now = Date.now();
1430
- const status =
1431
- requestedStatus === "active" &&
1432
- goal.tokenBudget !== undefined &&
1433
- goal.tokensUsed >= goal.tokenBudget
1434
- ? "budget_limited"
1435
- : requestedStatus;
1436
- const next = {
1437
- ...goal,
1438
- status,
1439
- updatedAt: now,
1440
- ...(status === "active" ? {} : { waiting: undefined }),
1441
- };
1442
- checkpointGoalActiveTime(next, now, status === "active" && !next.waiting);
1443
- return next;
1364
+ const now = Date.now();
1365
+ const status =
1366
+ requestedStatus === "active" && goal.tokenBudget !== undefined && goal.tokensUsed >= goal.tokenBudget
1367
+ ? "budget_limited"
1368
+ : requestedStatus;
1369
+ const next = {
1370
+ ...goal,
1371
+ status,
1372
+ updatedAt: now,
1373
+ ...(status === "active" ? {} : { waiting: undefined }),
1374
+ };
1375
+ checkpointGoalActiveTime(next, now, status === "active" && !next.waiting);
1376
+ return next;
1444
1377
  }
1445
1378
 
1446
1379
  export function nextGoalInstance(goal: ActiveGoal): ActiveGoal {
1447
- return { ...goal, id: randomUUID(), updatedAt: Date.now() };
1380
+ return { ...goal, id: randomUUID(), updatedAt: Date.now() };
1448
1381
  }
1449
1382
 
1450
1383
  export function editedGoalStatus(status: GoalStatus): GoalStatus {
1451
- if (status === "paused" || status === "blocked" || status === "usage_limited") return status;
1452
- return "active";
1384
+ if (status === "paused" || status === "blocked" || status === "usage_limited") return status;
1385
+ return "active";
1453
1386
  }
1454
1387
 
1455
1388
  export function incrementGoal(goal: ActiveGoal): ActiveGoal {
1456
- return { ...goal, iteration: goal.iteration + 1, updatedAt: Date.now() };
1389
+ return { ...goal, iteration: goal.iteration + 1, updatedAt: Date.now() };
1457
1390
  }
1458
1391
 
1459
1392
  export function formatStatus(
1460
- goal: ActiveGoal | undefined,
1461
- automaticTurnLimit: number | null = DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns,
1393
+ goal: ActiveGoal | undefined,
1394
+ automaticTurnLimit: number | null = DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns,
1462
1395
  ) {
1463
- if (!goal) return undefined;
1464
- if (goal.status === "complete") return "complete";
1465
- const automatic =
1466
- automaticTurnLimit === null
1467
- ? "automatic Unlimited"
1468
- : `automatic ${goal.automaticModelTurns}/${automaticTurnLimit}`;
1469
- if (goal.status === "queued") return `queued · ${automatic}`;
1470
- if (goal.waiting) {
1471
- return `waiting ${safeGoalMenuText(goal.waiting.reason)} · ${automatic}`;
1472
- }
1473
- if (goal.status === "paused" && goal.safetyPauseCause === "continuation_limit") {
1474
- if (automaticTurnLimit === null) {
1475
- return `paused · previous automatic limit at ${goal.automaticModelTurns}`;
1476
- }
1477
- if (goal.automaticModelTurns < automaticTurnLimit) {
1478
- return `paused · automatic ${goal.automaticModelTurns}/${automaticTurnLimit}`;
1479
- }
1480
- return `paused · automatic limit ${goal.automaticModelTurns}/${automaticTurnLimit}`;
1481
- }
1482
- if (goal.status === "paused") return `paused · ${automatic}`;
1483
- if (goal.status === "blocked") return `blocked · ${automatic}`;
1484
- if (goal.status === "usage_limited") return `usage · ${automatic}`;
1485
- if (goal.status === "budget_limited") return `budget ${formatBudget(goal)} · ${automatic}`;
1486
- if (goal.tokenBudget !== undefined) return `active ${formatBudget(goal)} · ${automatic}`;
1487
- return `active ${formatDuration(goal.timeUsedSeconds)} · ${automatic}`;
1396
+ if (!goal) return undefined;
1397
+ if (goal.status === "complete") return "complete";
1398
+ const automatic =
1399
+ automaticTurnLimit === null ? "automatic Unlimited" : `automatic ${goal.automaticModelTurns}/${automaticTurnLimit}`;
1400
+ if (goal.waiting) {
1401
+ return `waiting ${safeGoalMenuText(goal.waiting.reason)} · ${automatic}`;
1402
+ }
1403
+ if (goal.status === "paused" && goal.safetyPauseCause === "continuation_limit") {
1404
+ if (automaticTurnLimit === null) {
1405
+ return `paused · previous automatic limit at ${goal.automaticModelTurns}`;
1406
+ }
1407
+ if (goal.automaticModelTurns < automaticTurnLimit) {
1408
+ return `paused · automatic ${goal.automaticModelTurns}/${automaticTurnLimit}`;
1409
+ }
1410
+ return `paused · automatic limit ${goal.automaticModelTurns}/${automaticTurnLimit}`;
1411
+ }
1412
+ if (goal.status === "paused") return `paused · ${automatic}`;
1413
+ if (goal.status === "blocked") return `blocked · ${automatic}`;
1414
+ if (goal.status === "usage_limited") return `usage · ${automatic}`;
1415
+ if (goal.status === "budget_limited") return `budget ${formatBudget(goal)} · ${automatic}`;
1416
+ if (goal.tokenBudget !== undefined) return `active ${formatBudget(goal)} · ${automatic}`;
1417
+ return `active ${formatDuration(goal.timeUsedSeconds)} · ${automatic}`;
1488
1418
  }
1489
1419
 
1490
1420
  export function formatBudget(goal: ActiveGoal) {
1491
- return `${formatTokenCount(goal.tokensUsed)}/${formatTokenCount(goal.tokenBudget ?? 0)}`;
1421
+ return `${formatTokenCount(goal.tokensUsed)}/${formatTokenCount(goal.tokenBudget ?? 0)}`;
1492
1422
  }
1493
1423
 
1494
1424
  export function goalSummary(
1495
- goal: ActiveGoal,
1496
- automaticTurnLimit: number | null = DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns,
1425
+ goal: ActiveGoal,
1426
+ automaticTurnLimit: number | null = DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns,
1497
1427
  ) {
1498
- const summary = [
1499
- `Goal: ${goal.text}`,
1500
- `Status: ${goal.waiting ? "waiting" : goal.status}`,
1501
- ...(goal.waiting
1502
- ? [
1503
- `Waiting: ${safeGoalMenuText(goal.waiting.reason, 1_000)}`,
1504
- ...(goal.waiting.resumeAt === undefined
1505
- ? []
1506
- : [`Resume deadline: ${new Date(goal.waiting.resumeAt).toISOString()}`]),
1507
- ]
1508
- : []),
1509
- `Iteration: ${goal.iteration}`,
1510
- automaticTurnLimit === null
1511
- ? `Automatic work: ${goal.automaticModelTurns} responses · Unlimited`
1512
- : `Automatic work: ${goal.automaticModelTurns} of ${automaticTurnLimit} responses`,
1513
- `Active elapsed: ${formatDuration(goal.timeUsedSeconds)}`,
1514
- `Tokens: ${goal.tokenBudget === undefined ? formatTokenCount(goal.tokensUsed) : formatBudget(goal)}`,
1515
- ];
1516
- if (goal.safetyPauseCause) {
1517
- summary.push(
1518
- goal.safetyPauseCause === "continuation_limit"
1519
- ? `Safety pause: automatic-work limit reached (${goal.automaticModelTurns} of ${automaticTurnLimit ?? "Unlimited"} responses). Progress is saved; open /goal to review and continue.`
1520
- : "Safety pause: no progress. Progress is saved; open /goal to review and continue.",
1521
- );
1522
- }
1523
- summary.push(`Commands: ${goalCommandHint(goal)}`);
1524
- return summary.join("\n");
1428
+ const summary = [
1429
+ `Goal: ${goal.text}`,
1430
+ `Status: ${goal.waiting ? "waiting" : goal.status}`,
1431
+ ...(goal.waiting
1432
+ ? [
1433
+ `Waiting: ${safeGoalMenuText(goal.waiting.reason, 1_000)}`,
1434
+ ...(goal.waiting.resumeAt === undefined
1435
+ ? []
1436
+ : [`Resume deadline: ${new Date(goal.waiting.resumeAt).toISOString()}`]),
1437
+ ]
1438
+ : []),
1439
+ `Iteration: ${goal.iteration}`,
1440
+ automaticTurnLimit === null
1441
+ ? `Automatic work: ${goal.automaticModelTurns} responses · Unlimited`
1442
+ : `Automatic work: ${goal.automaticModelTurns} of ${automaticTurnLimit} responses`,
1443
+ `Active elapsed: ${formatDuration(goal.timeUsedSeconds)}`,
1444
+ `Tokens: ${goal.tokenBudget === undefined ? formatTokenCount(goal.tokensUsed) : formatBudget(goal)}`,
1445
+ ];
1446
+ if (goal.safetyPauseCause) {
1447
+ summary.push(
1448
+ goal.safetyPauseCause === "continuation_limit"
1449
+ ? `Safety pause: automatic-work limit reached (${goal.automaticModelTurns} of ${automaticTurnLimit ?? "Unlimited"} responses). Progress is saved; open /goal to review and continue.`
1450
+ : "Safety pause: no progress. Progress is saved; open /goal to review and continue.",
1451
+ );
1452
+ }
1453
+ summary.push(`Commands: ${goalCommandHint(goal)}`);
1454
+ return summary.join("\n");
1525
1455
  }
1526
1456
 
1527
1457
  export function hasPendingMessages(ctx: StatusContext) {
1528
- return ctx.hasPendingMessages?.() ?? false;
1458
+ return ctx.hasPendingMessages?.() ?? false;
1529
1459
  }
1530
1460
 
1531
1461
  export function abortCurrentTurn(ctx: StatusContext) {
1532
- try {
1533
- ctx.abort?.();
1534
- } catch {
1535
- // Best effort: stale goal guards still prevent follow-on tool calls.
1536
- }
1462
+ try {
1463
+ ctx.abort?.();
1464
+ } catch {
1465
+ // Best effort: stale goal guards still prevent follow-on tool calls.
1466
+ }
1537
1467
  }
1538
1468
 
1539
1469
  export function blocksStaleGoalToolCalls(status: GoalStatus) {
1540
- return (
1541
- status === "paused" ||
1542
- status === "blocked" ||
1543
- status === "usage_limited" ||
1544
- status === "budget_limited"
1545
- );
1470
+ return status === "paused" || status === "blocked" || status === "usage_limited" || status === "budget_limited";
1546
1471
  }
1547
1472
 
1548
1473
  export function isResumableGoalStatus(status: GoalStatus) {
1549
- return blocksStaleGoalToolCalls(status);
1474
+ return blocksStaleGoalToolCalls(status);
1550
1475
  }
1551
1476
 
1552
1477
  export function stoppedStatusLabel(status: GoalStatus) {
1553
- if (status === "usage_limited") return "usage-limited";
1554
- if (status === "budget_limited") return "budget-limited";
1555
- return status;
1478
+ if (status === "usage_limited") return "usage-limited";
1479
+ if (status === "budget_limited") return "budget-limited";
1480
+ return status;
1556
1481
  }
1557
1482
 
1558
1483
  export function isContradictoryCompletionSummary(summary: string) {
1559
- return CONTRADICTORY_COMPLETION_PATTERNS.some((pattern) => pattern.test(summary));
1484
+ return CONTRADICTORY_COMPLETION_PATTERNS.some((pattern) => pattern.test(summary));
1560
1485
  }
1561
1486
 
1562
1487
  export function goalIdRejectionReason(goal: ActiveGoal, requestedGoalId: string) {
1563
- if (!requestedGoalId) return "missing goal_id";
1564
- if (requestedGoalId.length > MAX_GOAL_ID_LENGTH) return "goal_id is too long";
1565
- if (requestedGoalId !== goal.id) return "goal_id does not match the active goal";
1566
- return undefined;
1488
+ if (!requestedGoalId) return "missing goal_id";
1489
+ if (requestedGoalId.length > MAX_GOAL_ID_LENGTH) return "goal_id is too long";
1490
+ if (requestedGoalId !== goal.id) return "goal_id does not match the active goal";
1491
+ return undefined;
1567
1492
  }
1568
1493
 
1569
1494
  function preservesOwnedPromptAtTerminalBoundary(prompt: string, ownedPrompt: string) {
1570
- // Earlier input handlers may prefix a live pi-goal message before this runtime
1571
- // can fingerprint it. Require the complete generated prompt as the terminal
1572
- // boundary so a quoted marker or text appended by an external sender is not owned.
1573
- return prompt === ownedPrompt || prompt.endsWith(ownedPrompt);
1495
+ // Earlier input handlers may prefix a live pi-goal message before this runtime
1496
+ // can fingerprint it. Require the complete generated prompt as the terminal
1497
+ // boundary so a quoted marker or text appended by an external sender is not owned.
1498
+ return prompt === ownedPrompt || prompt.endsWith(ownedPrompt);
1574
1499
  }
1575
1500
 
1576
1501
  function inputFingerprint(prompt: unknown) {
1577
- return createHash("sha256")
1578
- .update(typeof prompt === "string" ? prompt : "", "utf8")
1579
- .digest("hex");
1502
+ return createHash("sha256")
1503
+ .update(typeof prompt === "string" ? prompt : "", "utf8")
1504
+ .digest("hex");
1580
1505
  }
1581
1506
 
1582
1507
  function goalContractEntries(ctx: StatusContext) {
1583
- const sessionManager = ctx.sessionManager as
1584
- | {
1585
- buildContextEntries?: () => unknown[];
1586
- buildSessionContext?: () => { messages?: unknown[] };
1587
- getBranch?: () => unknown[];
1588
- getEntries?: () => unknown[];
1589
- }
1590
- | undefined;
1591
- const historyEntries = sessionManager?.getBranch?.() ?? sessionManager?.getEntries?.() ?? [];
1592
- return {
1593
- contextEntries:
1594
- sessionManager?.buildSessionContext?.().messages ??
1595
- sessionManager?.buildContextEntries?.() ??
1596
- historyEntries,
1597
- historyEntries,
1598
- };
1508
+ const sessionManager = ctx.sessionManager as
1509
+ | {
1510
+ buildContextEntries?: () => unknown[];
1511
+ buildSessionContext?: () => { messages?: unknown[] };
1512
+ getBranch?: () => unknown[];
1513
+ getEntries?: () => unknown[];
1514
+ }
1515
+ | undefined;
1516
+ const historyEntries = sessionManager?.getBranch?.() ?? sessionManager?.getEntries?.() ?? [];
1517
+ return {
1518
+ contextEntries:
1519
+ sessionManager?.buildSessionContext?.().messages ?? sessionManager?.buildContextEntries?.() ?? historyEntries,
1520
+ historyEntries,
1521
+ };
1599
1522
  }
1600
1523
 
1601
- async function sendPrompt(
1602
- pi: ExtensionAPI,
1603
- ctx: StatusContext,
1604
- prompt: string,
1605
- isCurrent?: () => boolean,
1606
- ) {
1607
- try {
1608
- await pi.sendUserMessage(prompt, { deliverAs: "followUp" });
1609
- return true;
1610
- } catch (error) {
1611
- if (!isCurrent || isCurrent()) {
1612
- notifyTerminal(ctx.ui, `Goal prompt failed: ${formatError(error)}`, "error");
1613
- }
1614
- return false;
1615
- }
1524
+ async function sendPrompt(pi: ExtensionAPI, ctx: StatusContext, prompt: string, isCurrent?: () => boolean) {
1525
+ try {
1526
+ await pi.sendUserMessage(prompt, { deliverAs: "followUp" });
1527
+ return true;
1528
+ } catch (error) {
1529
+ if (!isCurrent || isCurrent()) {
1530
+ notifyWhenSessionAlive(ctx, `Goal prompt failed: ${formatError(error)}`, "error");
1531
+ }
1532
+ return false;
1533
+ }
1534
+ }
1535
+
1536
+ // A delayed callback can outlive its session: after replacement or reload Pi
1537
+ // throws a stale-context error from every ctx getter, so reporting through the
1538
+ // dead session's UI must not turn into another throw inside a timer or a catch
1539
+ // block.
1540
+ function notifyWhenSessionAlive(ctx: StatusContext, message: string, level?: "info" | "warning" | "error") {
1541
+ try {
1542
+ notifyTerminal(ctx.ui, message, level);
1543
+ } catch (error) {
1544
+ if (!isStaleContextError(error)) throw error;
1545
+ }
1616
1546
  }
1617
1547
 
1618
- function goalCommandHint(goal: ActiveGoal, experimentalGoals = false) {
1619
- const queueCommands = experimentalGoals
1620
- ? ", /goal add <objective>, /goal prioritize <objective>, /goal drop-last, /goal skip"
1621
- : "";
1622
- if (goal.waiting) {
1623
- return `/goal resume, /goal edit <objective>, /goal pause, /goal clear${queueCommands}`;
1624
- }
1625
- if (goal.status === "active") {
1626
- return `/goal edit <objective>, /goal pause, /goal clear${queueCommands}`;
1627
- }
1628
- if (isResumableGoalStatus(goal.status)) {
1629
- return `/goal edit <objective>, /goal resume, /goal clear${queueCommands}`;
1630
- }
1631
- return `/goal edit <objective>, /goal clear${queueCommands}`;
1548
+ function goalCommandHint(goal: ActiveGoal) {
1549
+ if (goal.waiting) {
1550
+ return "/goal resume, /goal edit <objective>, /goal pause, /goal clear";
1551
+ }
1552
+ if (goal.status === "active") {
1553
+ return "/goal edit <objective>, /goal pause, /goal clear";
1554
+ }
1555
+ if (isResumableGoalStatus(goal.status)) {
1556
+ return "/goal edit <objective>, /goal resume, /goal clear";
1557
+ }
1558
+ return "/goal edit <objective>, /goal clear";
1632
1559
  }
1633
1560
 
1634
1561
  function continuationMarker(goal: ActiveGoal) {
1635
- return `${goal.id}:${goal.iteration}:${randomUUID()}`;
1562
+ return `${goal.id}:${goal.iteration}:${randomUUID()}`;
1636
1563
  }
1637
1564
 
1638
1565
  export type { AssistantMessageLike } from "./errors.js";
1639
1566
  export {
1640
- findFinalAssistantMessage,
1641
- formatError,
1642
- isGoalContextOverflow,
1643
- isRetryableGoalInterruption,
1644
- isUsageLimitedGoalInterruption,
1645
- truncateNotification,
1567
+ findFinalAssistantMessage,
1568
+ formatError,
1569
+ isGoalContextOverflow,
1570
+ isRetryableGoalInterruption,
1571
+ isUsageLimitedGoalInterruption,
1572
+ truncateNotification,
1646
1573
  } from "./errors.js";