@narumitw/pi-goal 0.46.0 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,662 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { currentTokenTotal } from "./accounting.js";
3
+ import type { GoalCommandController } from "./commands.js";
4
+ import { type ActiveGoal, loadGoalStateFromSession } from "./persistence.js";
5
+ import { buildGoalPrompt, buildGoalSystemPrompt } from "./prompts.js";
6
+ import { activateQueuedGoal } from "./queue.js";
7
+ import type { GoalRunController } from "./run-protocol.js";
8
+ import {
9
+ type AssistantMessageLike,
10
+ abortCurrentTurn,
11
+ blocksStaleGoalToolCalls,
12
+ findFinalAssistantMessage,
13
+ formatError,
14
+ type GoalRuntime,
15
+ incrementGoal,
16
+ isGoalContextOverflow,
17
+ isRetryableGoalInterruption,
18
+ isUsageLimitedGoalInterruption,
19
+ resetGoalSafetyEpoch,
20
+ STATUS_KEY,
21
+ type StatusContext,
22
+ truncateNotification,
23
+ } from "./runtime.js";
24
+ import { hasAssistantToolCall } from "./safety.js";
25
+ import { DEFAULT_GOAL_SETTINGS, readGoalSettings } from "./settings.js";
26
+
27
+ const EXPERIMENTAL_GOALS_WARNING =
28
+ "Experimental ordered goals are enabled for pi-goal. Queue behavior and persisted state may change.";
29
+
30
+ interface GoalLifecycleOptions {
31
+ settingsPath?: string;
32
+ }
33
+
34
+ export function registerGoalLifecycle(
35
+ pi: ExtensionAPI,
36
+ runtime: GoalRuntime,
37
+ commands: GoalCommandController,
38
+ runController: GoalRunController,
39
+ options: GoalLifecycleOptions = {},
40
+ ) {
41
+ pi.on("session_start", async (_event, ctx) => {
42
+ runtime.replaceMenuSession();
43
+ runtime.clearCompletionStatusTimer();
44
+ runtime.clearContinuationTracking();
45
+ runtime.clearPendingGoalPrompts();
46
+ runtime.clearAgentRun();
47
+ runtime.guardAbortGoalId = undefined;
48
+ runtime.clearGoalRecovery();
49
+ runtime.clearBudgetWrapUp();
50
+ runtime.clearStaleGoalToolCallBlock();
51
+ runtime.queuedGoals = [];
52
+ runtime.pendingQueueAction = undefined;
53
+ runtime.queueFrozen = false;
54
+ runtime.queueFreezeAwaitingSettle = false;
55
+ runtime.clearTerminalDetails();
56
+ const previousToolVisibility = runtime.settings.toolVisibility;
57
+ const settingsResult = readGoalSettings(options.settingsPath);
58
+ runtime.settings =
59
+ settingsResult.kind === "loaded" ? settingsResult.settings : DEFAULT_GOAL_SETTINGS;
60
+ runtime.settingsLoadIssue = settingsResult.kind === "invalid" ? settingsResult : undefined;
61
+ if (settingsResult.kind === "invalid") {
62
+ ctx.ui.notify(
63
+ `pi-goal settings ignored: ${settingsResult.reason}. Using default settings.`,
64
+ "warning",
65
+ );
66
+ }
67
+ if (runtime.settings.experimental.goals) {
68
+ ctx.ui.notify(EXPERIMENTAL_GOALS_WARNING, "warning");
69
+ }
70
+ try {
71
+ runtime.toolPolicy.prepareSessionStart(
72
+ runtime.settings.toolVisibility,
73
+ previousToolVisibility,
74
+ );
75
+ } catch (error) {
76
+ ctx.ui.notify(`Could not restore always-visible goal tools: ${formatError(error)}`, "error");
77
+ }
78
+
79
+ const loaded = loadGoalStateFromSession(ctx);
80
+ runtime.activeGoal = loaded.goal;
81
+ runtime.queuedGoals = loaded.queue;
82
+ runtime.pendingQueueAction = loaded.pendingAction;
83
+ runtime.queueFrozen = loaded.hasExperimentalQueueState && !runtime.settings.experimental.goals;
84
+ runController.bindSession(ctx);
85
+ if (runtime.queueFrozen) {
86
+ if (runtime.activeGoal) runtime.persistGoal(runtime.activeGoal);
87
+ ctx.ui.setStatus(STATUS_KEY, "queue off");
88
+ ctx.ui.notify(
89
+ "An experimental goal queue is frozen because experimental.goals is disabled. Re-enable it and run /reload to continue, or use /goal clear.",
90
+ "warning",
91
+ );
92
+ return;
93
+ }
94
+
95
+ let startRestoredQueuedGoal = false;
96
+ if (runtime.activeGoal?.status === "queued" && !runtime.pendingQueueAction) {
97
+ runtime.activeGoal = activateQueuedGoal(runtime.activeGoal, currentTokenTotal(ctx));
98
+ startRestoredQueuedGoal = runtime.activeGoal.status === "active";
99
+ }
100
+ if (runtime.pendingQueueAction) await commands.dispatchPendingQueueActionIfSettled(ctx);
101
+ if (runtime.activeGoal) {
102
+ if (runtime.activeGoal.status === "active" && runtime.activeGoal.safetyResetPending) {
103
+ // Resume/edit activation is persisted before its queued prompt starts. A
104
+ // reload must commit that promised reset before enforcing the old limits.
105
+ runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
106
+ }
107
+ if (runtime.activeGoal.status === "active") {
108
+ runtime.recordGoalUsage(runtime.activeGoal, ctx);
109
+ if (runtime.limitActiveGoalForBudget(ctx, false)) return;
110
+ if (runtime.enforceAutomaticTurnLimit(ctx, false) || runtime.enforceNoProgressLimit(ctx))
111
+ return;
112
+ }
113
+ // On lazy restore, an earlier restrictive session-start policy still wins:
114
+ // reconciliation unlocks ownership without widening the active tool set.
115
+ runtime.toolPolicy.reconcileRestoredState(runtime.settings.toolVisibility, true);
116
+ if (runtime.activeGoal.status === "active" && !runtime.toolPolicy.toolsAvailable()) {
117
+ runtime.pauseGoalForUnavailableTools(ctx, false);
118
+ return;
119
+ }
120
+ runtime.persistGoal(runtime.activeGoal);
121
+ runtime.updateStatus(ctx, runtime.activeGoal);
122
+ if (startRestoredQueuedGoal) {
123
+ const restoredGoal = runtime.activeGoal;
124
+ const sent = await runtime.sendOwnedGoalPrompt(
125
+ ctx,
126
+ restoredGoal.id,
127
+ buildGoalPrompt(restoredGoal),
128
+ false, // Reloaded queue activation preserves its persisted safety epoch.
129
+ );
130
+ if (!sent && runtime.activeGoal?.id === restoredGoal.id) {
131
+ runtime.stopActiveGoal(ctx, {
132
+ kind: "activation_rollback",
133
+ expectedGoalId: restoredGoal.id,
134
+ restoreGoal: restoredGoal,
135
+ abortTurn: false,
136
+ });
137
+ }
138
+ }
139
+ } else {
140
+ runtime.toolPolicy.reconcileRestoredState(runtime.settings.toolVisibility, false);
141
+ ctx.ui.setStatus(STATUS_KEY, undefined);
142
+ }
143
+ });
144
+
145
+ pi.on("session_shutdown", (_event, ctx) => {
146
+ runController.unbindSession();
147
+ runtime.closeMenuSession();
148
+ if (runtime.activeGoal) {
149
+ if (!runtime.queueFrozen && runtime.activeGoal.status === "active") {
150
+ runtime.recordGoalUsage(runtime.activeGoal, ctx, false);
151
+ }
152
+ runtime.persistGoal(runtime.activeGoal);
153
+ }
154
+ runtime.clearContinuationTracking();
155
+ runtime.clearPendingGoalPrompts();
156
+ runtime.clearAgentRun();
157
+ runtime.guardAbortGoalId = undefined;
158
+ runtime.clearGoalRecovery();
159
+ runtime.clearBudgetWrapUp();
160
+ runtime.clearStaleGoalToolCallBlock();
161
+ runtime.activeGoal = undefined;
162
+ runtime.queuedGoals = [];
163
+ runtime.pendingQueueAction = undefined;
164
+ runtime.queueFrozen = false;
165
+ runtime.queueFreezeAwaitingSettle = false;
166
+ ctx.ui.setStatus(STATUS_KEY, undefined);
167
+ runtime.clearCompletionStatusTimer();
168
+ runtime.clearTerminalDetails();
169
+ });
170
+
171
+ pi.on("session_before_compact", (event, ctx) => {
172
+ if (runtime.queueFrozen) return;
173
+ if (runtime.activeGoal?.status === "budget_limited") {
174
+ if ((event as { willRetry?: boolean }).willRetry === true) return { cancel: true as const };
175
+ return;
176
+ }
177
+ if (runtime.activeGoal?.status !== "active") return;
178
+ if (!runtime.recordGoalUsage(runtime.activeGoal, ctx)) return;
179
+ runtime.cancelContinuationWork();
180
+ runtime.persistGoal(runtime.activeGoal);
181
+ runtime.updateStatus(ctx, runtime.activeGoal);
182
+ if (runtime.pendingQueueAction) return;
183
+ if (runtime.limitActiveGoalForBudget(ctx, false)) return { cancel: true as const };
184
+ });
185
+
186
+ pi.on("session_compact", async (event, ctx) => {
187
+ if (runtime.queueFrozen) return;
188
+ if (runtime.activeGoal?.status !== "active") {
189
+ runtime.clearGoalRecovery();
190
+ if (runtime.pendingQueueAction) await commands.dispatchPendingQueueActionIfSettled(ctx);
191
+ return;
192
+ }
193
+
194
+ const restoredState = loadGoalStateFromSession(ctx);
195
+ if (restoredState.goal?.id === runtime.activeGoal.id) {
196
+ runtime.activeGoal = restoredState.goal;
197
+ runtime.queuedGoals = restoredState.queue;
198
+ runtime.pendingQueueAction = restoredState.pendingAction;
199
+ }
200
+ const usageRecorded = runtime.recordGoalUsage(runtime.activeGoal, ctx);
201
+ if (usageRecorded) {
202
+ runtime.persistGoal(runtime.activeGoal);
203
+ runtime.updateStatus(ctx, runtime.activeGoal);
204
+ }
205
+ if (runtime.pendingQueueAction) {
206
+ await commands.dispatchPendingQueueActionIfSettled(ctx);
207
+ return;
208
+ }
209
+ if (!usageRecorded) return;
210
+ if (runtime.limitActiveGoalForBudget(ctx, false)) return;
211
+
212
+ const wasPiRetry = runtime.isPiOwnedCompactionRetry(event, runtime.activeGoal.id);
213
+ if (wasPiRetry) return;
214
+ runtime.clearGoalRecoveryForGoal(runtime.activeGoal.id);
215
+ runtime.requestContinuation(runtime.activeGoal);
216
+ // Manual compaction does not emit agent_settled. This common dispatcher is
217
+ // therefore the narrow fallback; threshold compaction leaves the intent for
218
+ // agent_settled when Pi is still busy.
219
+ runtime.dispatchContinuationIfSettled(ctx);
220
+ });
221
+
222
+ pi.on("input", (event, ctx) => {
223
+ if (event.source === "extension") {
224
+ if (
225
+ runtime.consumeCancelledContinuationPrompt(event.text) ||
226
+ runtime.consumeStaleOwnedGoalPrompt(event.text)
227
+ ) {
228
+ return { action: "handled" as const };
229
+ }
230
+ if (runtime.queueFrozen) return;
231
+ // Streaming input is queued before its model work starts. Keep owned
232
+ // markers pending for message_start, and track non-goal delivery mode so a
233
+ // steer cannot consume a later follow-up's cleanup protection.
234
+ if (runtime.hasPendingOwnedGoalPrompt(event.text)) return;
235
+ if (event.streamingBehavior === "steer" || event.streamingBehavior === "followUp") {
236
+ runtime.noteQueuedNonGoalInput(event.text, event.streamingBehavior);
237
+ }
238
+ runtime.clearGoalRecovery();
239
+ return;
240
+ }
241
+ if (runtime.queueFrozen) return;
242
+ if (/^\/goal(?:\s|$)/u.test(event.text.trimStart())) return;
243
+ if (event.streamingBehavior === "followUp") {
244
+ runtime.noteQueuedNonGoalInput(event.text, "followUp", true);
245
+ return;
246
+ }
247
+ if (event.streamingBehavior === "steer") {
248
+ runtime.noteQueuedNonGoalInput(event.text, "steer");
249
+ }
250
+ runtime.clearGoalRecovery();
251
+ runtime.clearBudgetWrapUp();
252
+ runtime.clearStaleGoalToolCallBlock();
253
+ runtime.resetActiveSafetyEpoch(ctx);
254
+ });
255
+
256
+ pi.on("message_start", (event, ctx) => {
257
+ const message = event.message as { role?: unknown; content?: unknown };
258
+ if (
259
+ message.role === "assistant" &&
260
+ runtime.activeGoal?.status === "paused" &&
261
+ runtime.guardAbortGoalId === runtime.activeGoal.id
262
+ ) {
263
+ abortCurrentTurn(ctx);
264
+ return;
265
+ }
266
+ if (message.role === "custom") {
267
+ if (runtime.isActiveBudgetWrapUpMessage(message)) return;
268
+ if (runtime.guardAbortGoalId === runtime.activeGoal?.id) {
269
+ runtime.guardAbortGoalId = undefined;
270
+ }
271
+ beginNonGoalFollowUp(ctx, false);
272
+ return;
273
+ }
274
+ if (message.role !== "user") return;
275
+ const prompt = Array.isArray(message.content)
276
+ ? message.content
277
+ .filter(
278
+ (part) => part && typeof part === "object" && Reflect.get(part, "type") === "text",
279
+ )
280
+ .map((part) => Reflect.get(part as object, "text"))
281
+ .filter((text): text is string => typeof text === "string")
282
+ .join("\n")
283
+ : typeof message.content === "string"
284
+ ? message.content
285
+ : "";
286
+ const ownedPrompt = runtime.consumeOwnedGoalPrompt(prompt);
287
+ const ownedPromptBoundary = runtime.hasOwnedPromptBoundary(prompt);
288
+ const queuedNonGoalInput = runtime.consumeQueuedNonGoalInput(prompt, !ownedPromptBoundary);
289
+ if (!ownedPrompt) {
290
+ if (queuedNonGoalInput?.behavior === "followUp") {
291
+ beginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);
292
+ }
293
+ return;
294
+ }
295
+ if (runtime.activeGoal?.id !== ownedPrompt.goalId || runtime.activeGoal.status !== "active") {
296
+ return;
297
+ }
298
+ if (runtime.agentRunGoalId !== undefined && runtime.agentRunGoalId !== ownedPrompt.goalId) {
299
+ runtime.activeGoal.baselineTokens = Math.max(
300
+ 0,
301
+ currentTokenTotal(ctx) - runtime.activeGoal.tokensUsed,
302
+ );
303
+ }
304
+ runtime.beginAgentRun(ownedPrompt.goalId, "manual");
305
+ if (ownedPrompt.resetSafetyEpoch) {
306
+ runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
307
+ }
308
+ runtime.persistGoal(runtime.activeGoal);
309
+ runtime.updateStatus(ctx, runtime.activeGoal);
310
+ });
311
+
312
+ pi.on("context", (event, ctx) => {
313
+ const messages = event.messages.filter((message) => runtime.keepBudgetWrapUpMessage(message));
314
+ if (
315
+ runtime.activeGoal?.status === "paused" &&
316
+ runtime.guardAbortGoalId === runtime.activeGoal.id
317
+ ) {
318
+ // A current custom follow-up clears the guard at message_start. Otherwise,
319
+ // context transformation aborts before the provider adapter receives the signal.
320
+ abortCurrentTurn(ctx);
321
+ }
322
+ if (messages.length !== event.messages.length) return { messages };
323
+ });
324
+
325
+ pi.on("tool_call", (event, ctx) => {
326
+ runtime.markAgentToolAttempted();
327
+ if (runtime.queueFrozen) {
328
+ if (!runtime.toolPolicy.isGoalToolName(event.toolName)) return;
329
+ // Blocking alone feeds an error tool result back to the model. Abort too so
330
+ // stale Goal calls cannot loop while the experimental queue remains frozen.
331
+ abortCurrentTurn(ctx);
332
+ return {
333
+ block: true,
334
+ reason:
335
+ "The experimental goal queue is frozen. Re-enable experimental.goals and run /reload, or use /goal clear.",
336
+ };
337
+ }
338
+ if (
339
+ runtime.activeGoal?.status === "budget_limited" &&
340
+ runtime.budgetWrapUp?.goalId === runtime.activeGoal.id &&
341
+ event.toolName !== "goal_complete"
342
+ ) {
343
+ // A blocked tool result would normally trigger another model call. Abort the
344
+ // wrap-up instead so a tool-seeking model cannot create an unbounded loop.
345
+ abortCurrentTurn(ctx);
346
+ return {
347
+ block: true,
348
+ reason: "Goal token budget is exhausted; only goal_complete is allowed during wrap-up.",
349
+ };
350
+ }
351
+ if (!runtime.staleGoalToolCallsBlocked) return;
352
+ if (!runtime.activeGoal || !blocksStaleGoalToolCalls(runtime.activeGoal.status)) {
353
+ runtime.clearStaleGoalToolCallBlock();
354
+ return;
355
+ }
356
+ // A blocked tool result would normally trigger another model call. Abort the
357
+ // current turn so a tool-seeking model cannot create an unbounded loop that
358
+ // burns provider quota while the goal is stopped.
359
+ abortCurrentTurn(ctx);
360
+ return {
361
+ block: true,
362
+ reason: "Blocked stale /goal tool call after the goal stopped or was interrupted.",
363
+ };
364
+ });
365
+
366
+ pi.on("tool_execution_end", (_event, ctx) => {
367
+ if (runtime.queueFrozen) return;
368
+ if (
369
+ runtime.activeGoal?.status === "budget_limited" &&
370
+ runtime.budgetWrapUp?.goalId === runtime.activeGoal.id &&
371
+ !runtime.budgetWrapUp.delivered
372
+ ) {
373
+ runtime.queueBudgetWrapUp(ctx, runtime.activeGoal);
374
+ return;
375
+ }
376
+ if (runtime.activeGoal?.status !== "active") return;
377
+
378
+ // AgentSession persists assistant message_end before tool execution events,
379
+ // so the completed assistant call's usage is authoritative at this boundary.
380
+ if (!runtime.recordGoalUsage(runtime.activeGoal, ctx)) return;
381
+ runtime.persistGoal(runtime.activeGoal);
382
+ runtime.updateStatus(ctx, runtime.activeGoal);
383
+ if (runtime.limitActiveGoalForBudget(ctx, true)) return;
384
+ if (!runtime.toolPolicy.toolsAvailable()) runtime.pauseGoalForUnavailableTools(ctx);
385
+ });
386
+
387
+ pi.on("before_agent_start", (event, ctx) => {
388
+ runtime.clearAgentRun();
389
+ if (runtime.queueFrozen) return;
390
+ // Pi-owned retries emit agent_start directly. Reaching a normal prompt
391
+ // boundary means cleanup no longer owns the next run, so the hard-cap guard
392
+ // must not abort it.
393
+ if (runtime.guardAbortGoalId) runtime.guardAbortGoalId = undefined;
394
+ const goalPrompt = runtime.consumeOwnedGoalPrompt(event.prompt);
395
+ const goalPromptGoalId = goalPrompt?.goalId;
396
+ const continuationGoalId = goalPromptGoalId
397
+ ? undefined
398
+ : runtime.markContinuationStarted(event.prompt);
399
+ const ownedPromptGoalId = goalPromptGoalId ?? continuationGoalId;
400
+ const ownedPromptBoundary = runtime.hasOwnedPromptBoundary(event.prompt);
401
+ const activeBudgetWrapUp = runtime.hasActiveBudgetWrapUp();
402
+ const activeGoalRecovery = runtime.hasActiveGoalRecovery();
403
+ const queuedNonGoalInput = activeBudgetWrapUp
404
+ ? undefined
405
+ : runtime.consumeQueuedNonGoalInput(
406
+ event.prompt,
407
+ !activeGoalRecovery && ownedPromptGoalId === undefined && !ownedPromptBoundary,
408
+ );
409
+ if (queuedNonGoalInput?.behavior === "followUp") {
410
+ beginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);
411
+ }
412
+ const runOrigin = continuationGoalId
413
+ ? "automatic"
414
+ : activeGoalRecovery && runtime.goalRecovery?.automaticOwner
415
+ ? "automatic"
416
+ : "manual";
417
+ if (
418
+ runtime.pendingQueueAction?.kind === "prioritize" &&
419
+ !activeBudgetWrapUp &&
420
+ !activeGoalRecovery
421
+ ) {
422
+ // A turn that starts after priority intent is committed belongs to neither
423
+ // the displaced goal nor the not-yet-activated urgent goal. Persist the
424
+ // displaced goal's final accounting boundary so reload cannot absorb this run.
425
+ if (!runtime.pendingQueueAction.displacedUsageFinalized) {
426
+ if (runtime.activeGoal?.status === "active") {
427
+ runtime.recordGoalUsage(runtime.activeGoal, ctx, false);
428
+ }
429
+ runtime.pendingQueueAction.displacedUsageFinalized = true;
430
+ if (runtime.activeGoal) {
431
+ runtime.persistGoal(runtime.activeGoal);
432
+ runtime.updateStatus(ctx, runtime.activeGoal);
433
+ }
434
+ }
435
+ runtime.beginAgentRun(null, undefined);
436
+ if (ownedPromptGoalId) abortCurrentTurn(ctx);
437
+ return;
438
+ }
439
+ if (activeBudgetWrapUp && runtime.activeGoal) {
440
+ runtime.beginAgentRun(runtime.activeGoal.id, "manual");
441
+ return;
442
+ }
443
+ if (
444
+ runtime.pendingQueueAction?.kind === "advance" &&
445
+ runtime.pendingQueueAction.goalId === runtime.activeGoal?.id
446
+ ) {
447
+ runtime.beginAgentRun(ownedPromptGoalId ?? runtime.activeGoal.id, runOrigin);
448
+ if (ownedPromptGoalId) abortCurrentTurn(ctx);
449
+ return;
450
+ }
451
+ if (ownedPromptGoalId && ownedPromptGoalId !== runtime.activeGoal?.id) {
452
+ runtime.beginAgentRun(ownedPromptGoalId, runOrigin);
453
+ if (runtime.activeGoal?.status === "active" && !runtime.toolPolicy.toolsAvailable()) {
454
+ runtime.pauseGoalForUnavailableTools(ctx, false);
455
+ }
456
+ abortCurrentTurn(ctx);
457
+ return;
458
+ }
459
+ if (runtime.activeGoal?.status !== "active") return;
460
+ runtime.beginAgentRun(runtime.activeGoal.id, runOrigin);
461
+ if (!runtime.toolPolicy.toolsAvailable()) {
462
+ runtime.pauseGoalForUnavailableTools(ctx, ownedPromptGoalId !== undefined);
463
+ return;
464
+ }
465
+ if (goalPrompt?.resetSafetyEpoch && goalPromptGoalId === runtime.activeGoal.id) {
466
+ runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
467
+ runtime.persistGoal(runtime.activeGoal);
468
+ runtime.updateStatus(ctx, runtime.activeGoal);
469
+ }
470
+
471
+ return {
472
+ systemPrompt: `${event.systemPrompt}\n\n${buildGoalSystemPrompt(runtime.activeGoal)}`,
473
+ };
474
+ });
475
+
476
+ pi.on("agent_start", (_event, _ctx) => {
477
+ if (runtime.queueFrozen) return;
478
+ const activeGoal = runtime.activeGoal;
479
+ if (
480
+ activeGoal &&
481
+ runtime.guardAbortGoalId === activeGoal.id &&
482
+ activeGoal.status === "paused"
483
+ ) {
484
+ if (runtime.consumeQueuedNonGoalFollowUpForAgentStart()) {
485
+ runtime.guardAbortGoalId = undefined;
486
+ runtime.clearStaleGoalToolCallBlock();
487
+ runtime.beginAgentRun(null, undefined);
488
+ }
489
+ // Unknown runs defer cleanup until their message/context boundary: custom
490
+ // follow-ups have no input event, while bare recovery is aborted pre-provider.
491
+ return;
492
+ }
493
+ runtime.beginRecoveryRunIfNeeded();
494
+ });
495
+
496
+ pi.on("turn_end", (event, ctx) => {
497
+ if (runtime.queueFrozen) return;
498
+ runtime.recordAutomaticTurn(ctx, event.message);
499
+ });
500
+
501
+ pi.on("agent_end", (event, ctx) => {
502
+ const run = runtime.finishAgentRun();
503
+ if (runtime.queueFrozen || run.goalId === null) return;
504
+ if (!runtime.canRecordGoalUsage() && !runtime.hasActiveBudgetWrapUp()) return;
505
+ if (run.goalId && run.goalId !== runtime.activeGoal?.id) return;
506
+ if (!runtime.activeGoal) return;
507
+ if (
508
+ runtime.activeGoal.status === "budget_limited" &&
509
+ runtime.budgetWrapUp?.goalId === runtime.activeGoal.id
510
+ ) {
511
+ runtime.recordGoalUsage(runtime.activeGoal, ctx);
512
+ runtime.persistGoal(runtime.activeGoal);
513
+ runtime.updateStatus(ctx, runtime.activeGoal);
514
+ runtime.clearBudgetWrapUp();
515
+ return;
516
+ }
517
+ if (runtime.activeGoal.status !== "active") return;
518
+ if (
519
+ runtime.pendingQueueAction?.kind === "advance" &&
520
+ runtime.pendingQueueAction.goalId === runtime.activeGoal.id
521
+ ) {
522
+ runtime.recordGoalUsage(runtime.activeGoal, ctx);
523
+ runtime.persistGoal(runtime.activeGoal);
524
+ runtime.updateStatus(ctx, runtime.activeGoal);
525
+ return;
526
+ }
527
+
528
+ const goalId = runtime.activeGoal.id;
529
+ const alreadyAwaitingContinuation = runtime.hasContinuationWorkForGoal(goalId);
530
+ const finalAssistant = findFinalAssistantMessage(event.messages);
531
+
532
+ if (!alreadyAwaitingContinuation) runtime.activeGoal = incrementGoal(runtime.activeGoal);
533
+ runtime.recordGoalUsage(runtime.activeGoal, ctx);
534
+
535
+ if (finalAssistant?.stopReason === "aborted") {
536
+ runtime.clearGoalRecoveryForGoal(goalId);
537
+ stopGoalAfterAgentEnd(ctx, runtime.activeGoal, finalAssistant, "paused");
538
+ return;
539
+ }
540
+
541
+ if (finalAssistant?.stopReason === "error") {
542
+ if (isRetryableGoalInterruption(finalAssistant)) {
543
+ if (run.origin === "automatic" && runtime.enforceAutomaticTurnLimit(ctx, true)) return;
544
+ if (runtime.limitActiveGoalForBudget(ctx, false)) return;
545
+ if (!runtime.toolPolicy.toolsAvailable()) {
546
+ runtime.pauseGoalForUnavailableTools(ctx);
547
+ return;
548
+ }
549
+ runtime.goalRecovery = {
550
+ goalId,
551
+ kind: isGoalContextOverflow(finalAssistant) ? "compaction_retry" : "provider_retry",
552
+ automaticOwner: run.origin === "automatic",
553
+ errorMessage: finalAssistant.errorMessage,
554
+ };
555
+ runtime.cancelContinuationWork();
556
+ runtime.persistGoal(runtime.activeGoal);
557
+ runtime.updateStatus(ctx, runtime.activeGoal);
558
+ return;
559
+ }
560
+ runtime.clearGoalRecoveryForGoal(goalId);
561
+ stopGoalAfterAgentEnd(
562
+ ctx,
563
+ runtime.activeGoal,
564
+ finalAssistant,
565
+ isUsageLimitedGoalInterruption(finalAssistant) ? "usage_limited" : "blocked",
566
+ );
567
+ return;
568
+ }
569
+
570
+ runtime.clearGoalRecoveryForGoal(goalId);
571
+
572
+ if (runtime.limitActiveGoalForBudget(ctx, false)) return;
573
+ if (!runtime.toolPolicy.toolsAvailable()) {
574
+ runtime.pauseGoalForUnavailableTools(ctx);
575
+ return;
576
+ }
577
+ if (
578
+ run.origin === "automatic" &&
579
+ runtime.recordAutomaticRunProgress(
580
+ ctx,
581
+ goalId,
582
+ event.messages,
583
+ run.toolAttempted || hasAssistantToolCall(event.messages),
584
+ )
585
+ ) {
586
+ return;
587
+ }
588
+
589
+ runtime.persistGoal(runtime.activeGoal);
590
+ runtime.updateStatus(ctx, runtime.activeGoal);
591
+
592
+ const currentGoal = runtime.activeGoal;
593
+ if (!currentGoal || currentGoal.id !== goalId || currentGoal.status !== "active") return;
594
+ if (runtime.pendingQueueAction?.kind === "prioritize") return;
595
+ runtime.requestContinuation(currentGoal);
596
+ });
597
+
598
+ pi.on("agent_settled", async (_event, ctx) => {
599
+ if (runtime.queueFrozen) {
600
+ runtime.clearSettledSafetyTracking();
601
+ runtime.queueFreezeAwaitingSettle = false;
602
+ if (runtime.settings.experimental.goals) {
603
+ await commands.resumeQueueAfterUnfreeze(ctx);
604
+ }
605
+ return;
606
+ }
607
+ runtime.finalizeSettledRecovery(ctx);
608
+ let dispatchedQueueAction = false;
609
+ if (runtime.pendingQueueAction) {
610
+ dispatchedQueueAction = await commands.dispatchPendingQueueActionIfSettled(ctx);
611
+ }
612
+ if (!dispatchedQueueAction) runtime.dispatchContinuationIfSettled(ctx);
613
+ runtime.clearSettledSafetyTracking();
614
+ });
615
+
616
+ function beginNonGoalFollowUp(ctx: StatusContext, resetSafetyEpoch: boolean) {
617
+ runtime.clearGoalRecovery();
618
+ runtime.clearStaleGoalToolCallBlock();
619
+ if (resetSafetyEpoch) runtime.clearBudgetWrapUp();
620
+ const activeGoalId =
621
+ runtime.activeGoal?.status === "active" ? runtime.activeGoal.id : undefined;
622
+ runtime.beginAgentRun(activeGoalId ?? null, activeGoalId ? "manual" : undefined);
623
+ if (resetSafetyEpoch && activeGoalId) runtime.resetActiveSafetyEpoch(ctx);
624
+ }
625
+
626
+ function stopGoalAfterAgentEnd(
627
+ ctx: StatusContext,
628
+ goal: ActiveGoal,
629
+ assistant: AssistantMessageLike,
630
+ status: "paused" | "blocked" | "usage_limited",
631
+ ) {
632
+ const stoppedGoal = runtime.stopActiveGoal(ctx, {
633
+ kind: "agent_interruption",
634
+ expectedGoalId: goal.id,
635
+ status,
636
+ reason: assistant.errorMessage ?? `goal ${status} after agent interruption`,
637
+ });
638
+ if (!stoppedGoal) return;
639
+
640
+ const details = assistant.errorMessage
641
+ ? ` (${truncateNotification(assistant.errorMessage)})`
642
+ : "";
643
+ if (status === "paused") {
644
+ ctx.ui.notify(
645
+ `Goal paused after interruption${details}. Run /goal resume to continue.`,
646
+ "warning",
647
+ );
648
+ return;
649
+ }
650
+ if (status === "usage_limited") {
651
+ ctx.ui.notify(
652
+ `Goal stopped after provider usage limit${details}. Run /goal resume when usage is available.`,
653
+ "warning",
654
+ );
655
+ return;
656
+ }
657
+ ctx.ui.notify(
658
+ `Goal blocked after agent error${details}. Resolve the blocker or run /goal resume to retry.`,
659
+ "warning",
660
+ );
661
+ }
662
+ }