@narumitw/pi-goal 0.54.15 → 0.54.17

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.
@@ -14,6 +14,7 @@ The maintained implementation and tests are authoritative:
14
14
 
15
15
  - `packages/pi-goal/src/goal.ts`
16
16
  - `packages/pi-goal/src/lifecycle.ts`
17
+ - `packages/pi-goal/src/errors.ts`
17
18
  - `packages/pi-goal/src/runtime.ts`
18
19
  - `packages/pi-goal/src/tools.ts`
19
20
  - `packages/pi-goal/src/tool-policy.ts`
@@ -24,6 +25,9 @@ The maintained implementation and tests are authoritative:
24
25
  - `packages/pi-goal/src/workflow-mutex.ts`
25
26
  - `packages/pi-goal/test/goal-continuation.test.ts`
26
27
  - `packages/pi-goal/test/goal-error-lifecycle.test.ts`
28
+ - `packages/pi-goal/test/errors.test.ts`
29
+ - `packages/pi-goal/test/goal-native-recovery.test.ts`
30
+ - `packages/pi-goal/test/goal-unknown-error-waiting.test.ts`
27
31
  - `packages/pi-goal/test/goal-wait.test.ts`
28
32
  - `packages/pi-goal/test/goal-run-protocol.test.ts`
29
33
  - `packages/pi-goal/test/goal-cache-contract.test.ts`
@@ -44,7 +48,7 @@ keeps only the internal lifecycle rationale and public-API boundaries.
44
48
  creates an in-memory continuation intent for an eligible active goal. It does not send the normal
45
49
  continuation.
46
50
  3. `agent_settled` runs after retry, automatic compaction, steering, and follow-up work drains.
47
- It moves exhausted provider recovery into deadline-free waiting, blocks exhausted compaction recovery, and then may dispatch an ordinary continuation.
51
+ It first honors recovery cancellation, then selects final usage-limit, provider-waiting, or compaction-blocked state before an ordinary continuation can dispatch.
48
52
  4. Continuation dispatch re-reads the active goal, requires matching ownership, `ctx.isIdle()`, and
49
53
  no pending messages. Repeated settled events cannot consume one intent twice.
50
54
 
@@ -65,6 +69,12 @@ separately clears pending prompt, continuation, recovery, and run ownership. A n
65
69
  turn can supersede old continuation intent. A delayed prompt from a replaced, stopped, cleared, or
66
70
  completed goal cannot reactivate work or overwrite a newer goal.
67
71
 
72
+ The last eligible ended Goal identity remains available until settlement so cancellation before a native recovery event cannot dispatch a continuation.
73
+ New runs and session teardown invalidate that identity; cancellation cannot pause a replacement Goal.
74
+ New manual input also clears unclaimed length-recovery ownership at the same boundaries as provider recovery, while a queued interactive follow-up preserves ownership until that follow-up starts.
75
+ The runtime owns unconfirmed length candidates so an accepted `goal_wait` can invalidate older candidates.
76
+ A length response after that wait can reserve a fresh candidate before either progress or final-state publication, allowing synchronous listeners to supersede it safely.
77
+
68
78
  Goal's idle dispatcher does not atomically reserve a turn. Another extension can still win after
69
79
  `ctx.isIdle()` and pending-message checks. Goal markers, start-boundary revalidation, and later fresh
70
80
  intent recovery bound this race. This is a limit of the current dispatcher, not proof that Pi has no
@@ -84,19 +94,50 @@ A restrictive external allowlist can still hide Goal tools; Goal start and resto
84
94
 
85
95
  ## Retry, compaction, and stopped states
86
96
 
87
- Retryable provider failures and context-overflow compaction remain Pi-owned recovery:
88
-
89
- - `agent_end` keeps the matching goal active, cancels ordinary continuation pressure, and records
90
- recovery ownership instead of blocking retry tools.
91
- - A retry or compaction start consumes or carries that ownership into the replacement run so
92
- automatic accounting cannot be bypassed.
93
- - If matching provider recovery remains when `agent_settled` proves no retry or follow-up is pending, the Goal enters deadline-free waiting while remaining canonically active.
97
+ Pi owns recovery classification and execution. Goal delegates provider eligibility to the public `isRetryableAssistantError()` helper and overflow eligibility to `isContextOverflow()`.
98
+ Native retry eligibility is separate from Goal's waiting policy: an unclassified assistant error can wait without becoming eligible for a Pi retry.
99
+ Goal has no positive or negative retry patterns and no provider retry loop.
100
+ Its existing subscription, quota, credit, and billing classifier remains final-status policy; it cannot veto recovery accepted by the native helpers.
101
+ SDK `auto_retry_start` and `auto_retry_end` notifications are not extension events, so Goal uses public agent and compaction events instead.
102
+
103
+ - `agent_end` keeps a matching Goal active for native recovery or an unclassified assistant error, cancels ordinary continuation pressure, and records recovery ownership instead of stopping the Goal.
104
+ A native-ineligible recognized usage limit still selects `usage_limited` immediately.
105
+ Unknown errors pass the same automatic-response, existing no-progress, token-budget, and helper-availability guards before recovery is recorded.
106
+ - Native retries emit `agent_start` without `before_agent_start`; recovery carries the original manual or automatic ownership into that run.
107
+ - A final `length` response retains its run origin until Pi confirms compaction recovery through `session_before_compact.willRetry` or an overflow `session_compact_failed` event.
108
+ The same public events are authoritative if they confirm compaction recovery for a matching pending provider error; Goal does not infer that recovery from unknown wording.
109
+ In the currently tested Pi runtime, usage-based silent overflow applies to successful or length-stopped responses, not assistant errors.
110
+ Without native recovery, ordinary length-response continuation remains unchanged.
111
+ A repeated native length failure can emit only `session_compact_failed`, so that event also cancels the pending ordinary continuation.
112
+ - Non-retrying threshold compaction preserves a pending provider error until settlement, whether its summary succeeds or fails without cancellation; it cannot turn the error into an ordinary Goal continuation.
113
+ This is separate from failed overflow or length compact-and-retry recovery, which requires a stopped state.
114
+ - At settlement, `agent_settled.aborted` takes precedence over the retained failed assistant message and selects `paused`, even when a full session abort during backoff produced no new assistant response.
115
+ - `session_compact_failed.aborted` also marks its matching ended run as cancelled, including threshold and overflow compaction. Independent manual compaction has no ended run to pause.
116
+ - Otherwise, final recognized usage exhaustion selects `usage_limited`. Remaining provider retry or unclassified-error recovery enters deadline-free waiting while remaining canonically active.
117
+ Pending native-ineligible errors use a distinct `provider_error` kind, so their status does not claim unattempted retries were exhausted.
118
+ Blank or absent error text still waits; any displayed detail is bounded and sanitized.
119
+ Before publication, settlement rechecks current safety limits, budget, and helper availability because native post-run work can change them.
120
+ An explicit wait already accepted before a later assistant error retains its reason and deadline, unless cancellation, a recognized usage limit, or failed compaction recovery requires stopping.
121
+ - Disabled retries or a zero retry budget can still end in quiet waiting, but never cause Goal to make an extra retry.
94
122
  - A non-Goal follow-up wakes the same Goal and preserves its stale-turn guard so the next model run can continue, complete, or wait again.
95
- - If matching compaction recovery remains at settlement, the Goal becomes `blocked` because another model turn can repeat the same context-overflow failure without corrective compaction.
96
- - Explicit subscription, quota, credit, or billing exhaustion becomes `usage_limited`; transient rate limits and server failures remain retryable.
97
- - User interruption becomes `paused`. Other terminal non-usage failures become `blocked`.
123
+ - Remaining compaction recovery becomes `blocked` because no usable recovery response followed. Explicit `goal_blocked` and other stopped-state transitions remain independent of unknown-error waiting.
124
+
125
+ Native retry-only cancellation preserves existing active waiting behavior for transient non-usage failures.
126
+ The native TUI Escape handler during backoff and RPC `abort_retry` call `abortRetry()`, which emits an SDK retry-end notification but leaves `agent_settled.aborted` false.
127
+ Final usage-limit policy still applies; otherwise Goal uses the same deadline-free wait as provider retry exhaustion, retains Goal identity and managed-run ownership, and sends no extra request.
128
+ This is distinct from a full session abort or `/goal pause`, which selects `paused`; no Pi public-API change or private retry event is required.
98
129
 
99
- Provider-exhaustion waiting cancels continuation pressure but retains Goal identity and Workflow Mutex ownership.
130
+ Native classification replaces Goal's former retry text fallbacks, not its ability to wait.
131
+ The published `Connection prematurely closed BEFORE response` fixture and other truncated-stream variants remain native-ineligible, but now preserve the original active waiting and same-ID follow-up behavior.
132
+ Mixed quota or authentication wording cannot prevent a native-classified retry; successful native recovery keeps the same Goal active.
133
+
134
+ This policy intentionally also waits for invalid-request, authentication, permission, empty-message, and unrecognized account-limit errors that the existing usage policy does not identify.
135
+ It cannot infer a structured error cause from arbitrary provider wording. Pi's native classifiers and Goal's usage-limit policy still use regex; Goal adds no new retry text heuristic.
136
+ Waiting can last indefinitely, does not repair the failing request, and retains managed-run and cooperative Workflow Mutex ownership until wake, completion, or explicit cancellation.
137
+ External messages can wake a permanently failing request and incur another provider charge; waiting itself creates no deadline, poller, continuation, or provider request.
138
+ Ordinary tool-result errors do not independently enter this assistant-error policy.
139
+
140
+ Provider-error waiting cancels continuation pressure but retains Goal identity and Workflow Mutex ownership.
100
141
  Stopped transitions cancel current continuation ownership and block stale Goal-owned tool calls.
101
142
  Successful stopped-state resume rotates the goal id and starts a fresh blocker and safety audit.
102
143
  Waiting resume preserves the goal id, while clear removes Goal state and stale guards without aborting unrelated work.
@@ -159,6 +200,10 @@ Moving to `agent_before_settle` would be a separate runtime change that must ver
159
200
  recovery, waiting, accounting, cancellation, and exactly-once behavior; this note does not claim that
160
201
  migration is implemented or verified.
161
202
 
203
+ Non-retrying compaction after a successful `stop` response is unchanged by this error-wait policy.
204
+ For example, Pi can detect silent overflow from successful-response usage and compact without retrying; a failed summary can leave the Goal active without a new continuation.
205
+ This work does not claim that non-error continuation path is repaired.
206
+
162
207
  The existing dispatcher does not reserve an idle turn, add a Goal-aware abort event or queue
163
208
  priority, or globally schedule every extension. The cooperative Workflow Mutex cannot control
164
209
  non-participating extensions, and later boundary handlers can override a continuation proposal.
@@ -169,10 +214,12 @@ non-participating extensions, and later boundary handlers can override a continu
169
214
  - Workflow Mutex acquisition, rejection before mutation, restore fallbacks, release, and reacquisition: `packages/pi-goal/test/workflow-mutex.test.ts` and the Goal package lifecycle tests.
170
215
  - Stable helper-tool schemas and restrictive allowlist behavior: `packages/pi-goal/test/goal-tool-policy.test.ts` and `packages/pi-goal/test/tool-policy.test.ts`.
171
216
  - Stable leading prompt prefix, immediate and deferred handoff publication, canonical context reinjection, compaction-sensitive Goal contracts, and terminal tool-result ordering: `packages/pi-goal/test/goal-cache-contract.test.ts`.
172
- - Retry, overflow, compaction, provider-exhaustion waiting, wake-up, restored waiting, and stopped-state classification: `packages/pi-goal/test/goal-error-lifecycle.test.ts`.
217
+ - Native-helper parity, unsupported premature-close wording, and mixed quota/authentication errors: `packages/pi-goal/test/errors.test.ts`.
218
+ - Retry, overflow, compaction, provider-error waiting, wake-up, restored waiting, and stopped-state classification: `packages/pi-goal/test/goal-error-lifecycle.test.ts`.
219
+ - Unknown-error equivalence classes, settled-only waiting, unchanged native eligibility, contract preservation, cancellation, safety, supersession, compaction promotion, and reload: `packages/pi-goal/test/goal-unknown-error-waiting.test.ts`.
220
+ - Backoff cancellation, final usage policy, length-recovery ownership, replacement/shutdown, and recovery safety limits: `packages/pi-goal/test/goal-native-recovery.test.ts`.
173
221
  - External-wait deadlines, cleanup, quiet elapsed time, and wake boundaries: `packages/pi-goal/test/goal-wait.test.ts`.
174
222
  - Managed-run active waiting and later terminal completion: `packages/pi-goal/test/goal-run-protocol.test.ts`.
175
223
  - Budget exhaustion without a wrap-up or extra model request: `packages/pi-goal/test/goal-budget-lifecycle.test.ts`.
176
224
  - Usage totals, active time, tool-boundary budgets, and safety epochs: the accounting, budget, safety, persistence, and settings tests under `packages/pi-goal/test/`.
177
- - Real Pi event ordering, retries, manual compaction, no-progress stopping, automatic tool loops, and
178
- bounded pre-aborted cleanup: `packages/pi-goal/test/goal-runtime-smoke.mjs`.
225
+ - Real Pi event ordering, native retry attempt counts, disabled/zero retry budgets, backoff cancellation, managed waiting, length and manual compaction, no-progress stopping, automatic tool loops, and bounded pre-aborted cleanup: `packages/pi-goal/test/goal-runtime-smoke.mjs`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-goal",
3
- "version": "0.54.15",
3
+ "version": "0.54.17",
4
4
  "description": "Pi extension for autonomous single-objective /goal completion.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -48,7 +48,7 @@
48
48
  "typescript": "7.0.2"
49
49
  },
50
50
  "dependencies": {
51
- "@narumitw/pi-tui-kit": "^0.69.0"
51
+ "@narumitw/pi-tui-kit": "^0.69.1"
52
52
  },
53
53
  "repository": {
54
54
  "type": "git",
package/src/errors.ts CHANGED
@@ -27,14 +27,6 @@ const USAGE_LIMIT_GOAL_ERROR_PATTERNS = [
27
27
  /insufficient[_\s-]*(?:quota|credits?)|out of credits|out of budget|available balance|payment required/i,
28
28
  /(?:credit|balance).{0,32}(?:low|exhausted|depleted)|billing/i,
29
29
  ] as const;
30
- const NON_RETRYABLE_GOAL_ERROR_RE = /multi-auth rotation failed|credentials tried|unauthori[sz]ed|invalid api key/i;
31
- const RETRYABLE_GOAL_ERROR_PATTERNS = [
32
- /overloaded|rate.?limit|too many requests|\b(?:429|500|502|503|504)\b|service.?unavailable|server.?error|internal.?error/i,
33
- /provider.?returned.?error|you can retry your request|try your request again|please retry your request/i,
34
- /network.?error|connection.?(?:error|refused|lost)|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up/i,
35
- /timed? out|timeout|terminated|websocket.?(?:closed|error)|ended without|stream (?:ended|closed|terminated) before|premature (?:close|end)|incomplete (?:stream|response)|unexpected end of (?:stream|response)|http2 request did not get a response|retry delay/i,
36
- /context[_\s-]*length[_\s-]*exceeded|input exceeds the context window/i,
37
- ] as const;
38
30
 
39
31
  export function safeTerminalText(value: string) {
40
32
  return [...stripTerminalSequences(value)]
@@ -92,14 +84,8 @@ export function isUsageLimitedGoalInterruption(assistant: AssistantMessageLike)
92
84
 
93
85
  export function isRetryableGoalInterruption(assistant: AssistantMessageLike) {
94
86
  if (assistant.stopReason !== "error" || !assistant.errorMessage) return false;
95
- if (isUsageLimitedGoalInterruption(assistant) || NON_RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage)) {
96
- return false;
97
- }
98
- return (
99
- isGoalContextOverflow(assistant) ||
100
- isRetryableAssistantError(toPiAssistantMessage(assistant)) ||
101
- RETRYABLE_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(assistant.errorMessage ?? ""))
102
- );
87
+ // Pi owns eligibility and execution; Goal only tracks the recovery boundary.
88
+ return isGoalContextOverflow(assistant) || isRetryableAssistantError(toPiAssistantMessage(assistant));
103
89
  }
104
90
 
105
91
  export function isGoalContextOverflow(assistant: AssistantMessageLike) {
package/src/lifecycle.ts CHANGED
@@ -50,8 +50,11 @@ export function registerGoalLifecycle(
50
50
  // starts true so handlers keep working on runners where session_start was
51
51
  // never emitted (for example late extension loading).
52
52
  let sessionActive = true;
53
+ let endedGoalRun: { goalId: string; aborted: boolean } | undefined;
53
54
  pi.on("session_start", async (_event, ctx) => {
54
55
  sessionActive = true;
56
+ runtime.pendingLengthRecovery = undefined;
57
+ endedGoalRun = undefined;
55
58
  runtime.bindWorkflowSession(ctx.sessionManager);
56
59
  runtime.replaceMenuSession();
57
60
  runtime.clearCompletionStatusTimer();
@@ -145,6 +148,8 @@ export function registerGoalLifecycle(
145
148
 
146
149
  pi.on("session_shutdown", (_event, ctx) => {
147
150
  sessionActive = false;
151
+ runtime.pendingLengthRecovery = undefined;
152
+ endedGoalRun = undefined;
148
153
  const shutdownSession = ctx.sessionManager;
149
154
  runController.unbindSession();
150
155
  runtime.closeMenuSession();
@@ -182,12 +187,22 @@ export function registerGoalLifecycle(
182
187
  return;
183
188
  }
184
189
  if (!runtime.recordGoalUsage(runtime.activeGoal, ctx)) return;
190
+ if (event.willRetry === true) claimCompactionRecovery(runtime.activeGoal.id);
185
191
  runtime.cancelContinuationWork();
186
192
  runtime.persistGoal(runtime.activeGoal);
187
193
  runtime.updateStatus(ctx, runtime.activeGoal);
188
194
  if (runtime.limitActiveGoalForBudget(ctx, false)) return { cancel: true as const };
189
195
  });
190
196
 
197
+ pi.on("session_compact_failed", (event) => {
198
+ if (!sessionActive || !runtime.ownsWorkflow() || !runtime.activeGoal) return;
199
+ // A repeated length failure ends recovery without another before_compact.
200
+ if (event.reason === "overflow") claimCompactionRecovery(runtime.activeGoal.id);
201
+ // Native compaction-only cancellation does not set agent_settled.aborted.
202
+ // An independent manual compaction has no ended run and cannot pause a Goal.
203
+ if (event.aborted && endedGoalRun?.goalId === runtime.activeGoal.id) endedGoalRun.aborted = true;
204
+ });
205
+
191
206
  pi.on("session_compact", async (event, ctx) => {
192
207
  if (!sessionActive) return;
193
208
  if (runtime.activeGoal?.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
@@ -218,7 +233,9 @@ export function registerGoalLifecycle(
218
233
  if (!usageRecorded) return;
219
234
 
220
235
  const wasPiRetry = runtime.isPiOwnedCompactionRetry(event, runtime.activeGoal.id);
221
- if (wasPiRetry) return;
236
+ // Threshold compaction can follow a provider error without retrying it.
237
+ // Keep that error pending so settlement waits instead of sending a new turn.
238
+ if (wasPiRetry || runtime.hasActiveGoalRecovery()) return;
222
239
  runtime.clearGoalRecoveryForGoal(runtime.activeGoal.id);
223
240
  runtime.requestContinuation(runtime.activeGoal);
224
241
  // Pi emits session_compact before it clears its manual-compaction controller,
@@ -247,6 +264,7 @@ export function registerGoalLifecycle(
247
264
  if (event.streamingBehavior === "steer" || event.streamingBehavior === "followUp") {
248
265
  runtime.noteQueuedNonGoalInput(event.text, event.streamingBehavior);
249
266
  }
267
+ runtime.pendingLengthRecovery = undefined;
250
268
  runtime.clearGoalRecovery();
251
269
  return;
252
270
  }
@@ -259,6 +277,7 @@ export function registerGoalLifecycle(
259
277
  if (event.streamingBehavior === "steer") {
260
278
  runtime.noteQueuedNonGoalInput(event.text, "steer");
261
279
  }
280
+ runtime.pendingLengthRecovery = undefined;
262
281
  runtime.clearGoalRecovery();
263
282
  runtime.clearBudgetWrapUp();
264
283
  runtime.clearStaleGoalToolCallBlock();
@@ -397,6 +416,8 @@ export function registerGoalLifecycle(
397
416
  pi.on("before_agent_start", (event, ctx) => {
398
417
  // Custom runs use message_start to establish non-goal ownership.
399
418
  if (!sessionActive || event.messageType === "custom") return;
419
+ runtime.pendingLengthRecovery = undefined;
420
+ endedGoalRun = undefined;
400
421
  runtime.clearAgentRun();
401
422
  // Pi-owned retries emit agent_start directly. Reaching a normal prompt
402
423
  // boundary means cleanup no longer owns the next run, so the hard-cap guard
@@ -463,6 +484,8 @@ export function registerGoalLifecycle(
463
484
 
464
485
  pi.on("agent_start", (_event, _ctx) => {
465
486
  if (!sessionActive) return;
487
+ runtime.pendingLengthRecovery = undefined;
488
+ endedGoalRun = undefined;
466
489
  const activeGoal = runtime.activeGoal;
467
490
  if (activeGoal && runtime.guardAbortGoalId === activeGoal.id && activeGoal.status === "paused") {
468
491
  if (runtime.consumeQueuedNonGoalFollowUpForAgentStart()) {
@@ -489,6 +512,8 @@ export function registerGoalLifecycle(
489
512
 
490
513
  pi.on("agent_end", (event, ctx) => {
491
514
  if (!sessionActive) return;
515
+ runtime.pendingLengthRecovery = undefined;
516
+ endedGoalRun = undefined;
492
517
  const run = runtime.finishAgentRun();
493
518
  if (run.goalId === null) return;
494
519
  if (!runtime.canRecordGoalUsage() && !runtime.hasActiveBudgetWrapUp()) return;
@@ -506,6 +531,7 @@ export function registerGoalLifecycle(
506
531
  }
507
532
 
508
533
  const goalId = runtime.activeGoal.id;
534
+ endedGoalRun = { goalId, aborted: false };
509
535
  const alreadyAwaitingContinuation = runtime.hasContinuationWorkForGoal(goalId);
510
536
  const finalAssistant = findFinalAssistantMessage(event.messages);
511
537
 
@@ -519,31 +545,39 @@ export function registerGoalLifecycle(
519
545
  }
520
546
 
521
547
  if (finalAssistant?.stopReason === "error") {
522
- if (isRetryableGoalInterruption(finalAssistant)) {
523
- if (run.origin === "automatic" && runtime.enforceAutomaticTurnLimit(ctx, true)) return;
524
- if (runtime.limitActiveGoalForBudget(ctx, false)) return;
525
- if (!runtime.goalToolsAvailable()) {
526
- runtime.pauseGoalForUnavailableTools(ctx);
527
- return;
528
- }
529
- runtime.goalRecovery = {
530
- goalId,
531
- kind: isGoalContextOverflow(finalAssistant) ? "compaction_retry" : "provider_retry",
532
- automaticOwner: run.origin === "automatic",
533
- errorMessage: finalAssistant.errorMessage,
534
- };
535
- runtime.cancelContinuationWork();
536
- runtime.persistGoal(runtime.activeGoal);
537
- runtime.updateStatus(ctx, runtime.activeGoal);
548
+ const nativeRecovery = isRetryableGoalInterruption(finalAssistant);
549
+ if (!nativeRecovery && isUsageLimitedGoalInterruption(finalAssistant)) {
550
+ runtime.clearGoalRecoveryForGoal(goalId);
551
+ stopGoalAfterAgentEnd(ctx, runtime.activeGoal, finalAssistant, "usage_limited");
538
552
  return;
539
553
  }
540
- runtime.clearGoalRecoveryForGoal(goalId);
541
- stopGoalAfterAgentEnd(
542
- ctx,
543
- runtime.activeGoal,
544
- finalAssistant,
545
- isUsageLimitedGoalInterruption(finalAssistant) ? "usage_limited" : "blocked",
546
- );
554
+ if (
555
+ run.origin === "automatic" &&
556
+ (runtime.enforceAutomaticTurnLimit(ctx, true) || runtime.enforceNoProgressLimit(ctx, true))
557
+ ) {
558
+ return;
559
+ }
560
+ if (runtime.limitActiveGoalForBudget(ctx, false)) return;
561
+ if (!runtime.goalToolsAvailable()) {
562
+ runtime.pauseGoalForUnavailableTools(ctx);
563
+ return;
564
+ }
565
+ // Waiting does not grant retry eligibility. Pi still owns every attempt.
566
+ runtime.goalRecovery = {
567
+ goalId,
568
+ kind: isGoalContextOverflow(finalAssistant)
569
+ ? "compaction_retry"
570
+ : nativeRecovery
571
+ ? "provider_retry"
572
+ : "provider_error",
573
+ automaticOwner: run.origin === "automatic",
574
+ errorMessage: finalAssistant.errorMessage,
575
+ };
576
+ runtime.cancelContinuationWork();
577
+ runtime.persistGoal(runtime.activeGoal);
578
+ if (runtime.activeGoal?.id === goalId && runtime.ownsWorkflow(runtime.activeGoal)) {
579
+ runtime.updateStatus(ctx, runtime.activeGoal);
580
+ }
547
581
  return;
548
582
  }
549
583
 
@@ -554,6 +588,15 @@ export function registerGoalLifecycle(
554
588
  runtime.pauseGoalForUnavailableTools(ctx);
555
589
  return;
556
590
  }
591
+ if (finalAssistant?.stopReason === "length") {
592
+ // Reserve before either progress or final-state publication: a reentrant
593
+ // goal_wait invalidates old work, while a later length response is fresh.
594
+ runtime.pendingLengthRecovery = {
595
+ goalId,
596
+ kind: "compaction_retry",
597
+ automaticOwner: run.origin === "automatic",
598
+ };
599
+ }
557
600
  if (
558
601
  run.origin === "automatic" &&
559
602
  runtime.recordAutomaticRunProgress(
@@ -566,34 +609,49 @@ export function registerGoalLifecycle(
566
609
  return;
567
610
  }
568
611
 
569
- runtime.persistGoal(runtime.activeGoal);
570
- runtime.updateStatus(ctx, runtime.activeGoal);
571
-
572
612
  const currentGoal = runtime.activeGoal;
573
- if (!currentGoal || currentGoal.id !== goalId || currentGoal.status !== "active") return;
574
- runtime.requestContinuation(currentGoal);
613
+ if (!currentGoal || currentGoal.id !== goalId || !runtime.ownsWorkflow(currentGoal)) return;
614
+ runtime.persistGoal(currentGoal);
615
+ const persistedGoal = runtime.activeGoal;
616
+ if (!persistedGoal || persistedGoal.id !== goalId || !runtime.ownsWorkflow(persistedGoal)) return;
617
+ runtime.updateStatus(ctx, persistedGoal);
618
+ runtime.requestContinuation(persistedGoal);
575
619
  });
576
620
 
577
- pi.on("agent_settled", (_event, ctx) => {
621
+ pi.on("agent_settled", (event, ctx) => {
578
622
  if (!sessionActive) return;
623
+ runtime.pendingLengthRecovery = undefined;
624
+ const settledRun = endedGoalRun;
625
+ endedGoalRun = undefined;
579
626
  if (runtime.activeGoal?.status === "active" && !runtime.ownsWorkflow(runtime.activeGoal)) {
580
627
  runtime.cancelContinuationWork();
581
628
  runtime.clearGoalRecovery();
582
629
  runtime.clearSettledSafetyTracking();
583
630
  return;
584
631
  }
585
- runtime.finalizeSettledRecovery(ctx);
632
+ runtime.finalizeSettledRecovery(ctx, event.aborted === true || settledRun?.aborted === true, settledRun?.goalId);
586
633
  const resumedWait = runtime.dispatchDueGoalWait(ctx);
587
634
  if (!resumedWait) runtime.dispatchContinuationIfSettled(ctx);
588
635
  runtime.clearSettledSafetyTracking();
589
636
  });
590
637
 
638
+ function claimCompactionRecovery(goalId: string) {
639
+ const lengthRecovery = runtime.pendingLengthRecovery?.goalId === goalId ? runtime.pendingLengthRecovery : undefined;
640
+ if (lengthRecovery) runtime.pendingLengthRecovery = undefined;
641
+ const recovery = lengthRecovery ?? (runtime.goalRecovery?.goalId === goalId ? runtime.goalRecovery : undefined);
642
+ if (!recovery) return;
643
+ // Pi's public compaction events confirm recovery for this matching run.
644
+ runtime.goalRecovery = { ...recovery, kind: "compaction_retry" };
645
+ runtime.cancelContinuationWork();
646
+ }
647
+
591
648
  function goalContractBoundaryResult(ctx: StatusContext, goal?: ActiveGoal) {
592
649
  const message = runtime.goalContextContractForPrompt(ctx, goal);
593
650
  return message ? { message } : undefined;
594
651
  }
595
652
 
596
653
  function beginNonGoalFollowUp(ctx: StatusContext, resetSafetyEpoch: boolean) {
654
+ runtime.pendingLengthRecovery = undefined;
597
655
  runtime.clearGoalRecovery();
598
656
  runtime.clearStaleGoalToolCallBlock();
599
657
  if (resetSafetyEpoch) runtime.clearBudgetWrapUp();
@@ -606,7 +664,7 @@ export function registerGoalLifecycle(
606
664
  ctx: StatusContext,
607
665
  goal: ActiveGoal,
608
666
  assistant: AssistantMessageLike,
609
- status: "paused" | "blocked" | "usage_limited",
667
+ status: "paused" | "usage_limited",
610
668
  ) {
611
669
  const stoppedGoal = runtime.stopActiveGoal(ctx, {
612
670
  kind: "agent_interruption",
@@ -621,17 +679,9 @@ export function registerGoalLifecycle(
621
679
  notifyTerminal(ctx.ui, `Goal paused after interruption${details}. Run /goal resume to continue.`, "warning");
622
680
  return;
623
681
  }
624
- if (status === "usage_limited") {
625
- notifyTerminal(
626
- ctx.ui,
627
- `Goal stopped after provider usage limit${details}. Run /goal resume when usage is available.`,
628
- "warning",
629
- );
630
- return;
631
- }
632
682
  notifyTerminal(
633
683
  ctx.ui,
634
- `Goal blocked after agent error${details}. Resolve the blocker or run /goal resume to retry.`,
684
+ `Goal stopped after provider usage limit${details}. Run /goal resume when usage is available.`,
635
685
  "warning",
636
686
  );
637
687
  }
@@ -62,7 +62,8 @@ interface SessionContext {
62
62
  }
63
63
 
64
64
  export function serializeGoalState(goal: ActiveGoal | undefined): GoalStateEntryData {
65
- return { goal: goal ?? null };
65
+ // Pi retains custom-entry data by reference, so detach the full append-time snapshot.
66
+ return { goal: goal ? structuredClone(goal) : null };
66
67
  }
67
68
 
68
69
  export function loadGoalStateFromSession(ctx: SessionContext): LoadedGoalState {