@narumitw/pi-goal 0.54.17 → 0.55.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -23,6 +23,9 @@ The maintained implementation and tests are authoritative:
23
23
  - `packages/pi-goal/src/prompts.ts`
24
24
  - `packages/pi-goal/src/goal-contract.ts`
25
25
  - `packages/pi-goal/src/workflow-mutex.ts`
26
+ - `packages/pi-goal/src/wait.ts`
27
+ - `packages/pi-goal/src/usage-limit-recovery.ts`
28
+ - `packages/pi-goal/src/usage-reset.ts`
26
29
  - `packages/pi-goal/test/goal-continuation.test.ts`
27
30
  - `packages/pi-goal/test/goal-error-lifecycle.test.ts`
28
31
  - `packages/pi-goal/test/errors.test.ts`
@@ -42,8 +45,8 @@ keeps only the internal lifecycle rationale and public-API boundaries.
42
45
 
43
46
  `pi-goal` separates outcome classification from continuation dispatch:
44
47
 
45
- 1. `turn_end` accounts every completed model response owned by automatic Goal work and enforces an
46
- optional configured response cap.
48
+ 1. `turn_end` accounts completed model responses owned by automatic Goal work and enforces an
49
+ optional configured response cap, except for the narrowly owned quota rejection described below.
47
50
  2. `agent_end` records final usage, classifies the run outcome, applies the no-progress guard, and
48
51
  creates an in-memory continuation intent for an eligible active goal. It does not send the normal
49
52
  continuation.
@@ -96,12 +99,13 @@ A restrictive external allowlist can still hide Goal tools; Goal start and resto
96
99
 
97
100
  Pi owns recovery classification and execution. Goal delegates provider eligibility to the public `isRetryableAssistantError()` helper and overflow eligibility to `isContextOverflow()`.
98
101
  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.
102
+ Goal has no positive or negative native retry patterns and does not implement Pi's provider retry loop.
103
+ Its unchanged subscription, quota, credit, and billing classifier selects stopped `usage_limited` by default, or scheduled active waiting when `retryUsageLimits` is enabled; it cannot veto recovery accepted by the native helpers.
101
104
  SDK `auto_retry_start` and `auto_retry_end` notifications are not extension events, so Goal uses public agent and compaction events instead.
102
105
 
103
106
  - `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.
107
+ With quota recovery disabled, a native-ineligible recognized usage limit still selects `usage_limited` immediately.
108
+ With recovery enabled, it retains recovery ownership until settlement before entering a scheduled wait.
105
109
  Unknown errors pass the same automatic-response, existing no-progress, token-budget, and helper-availability guards before recovery is recorded.
106
110
  - Native retries emit `agent_start` without `before_agent_start`; recovery carries the original manual or automatic ownership into that run.
107
111
  - 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.
@@ -113,25 +117,27 @@ SDK `auto_retry_start` and `auto_retry_end` notifications are not extension even
113
117
  This is separate from failed overflow or length compact-and-retry recovery, which requires a stopped state.
114
118
  - 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
119
  - `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.
120
+ - Otherwise, final recognized usage exhaustion selects stopped `usage_limited` by default, or scheduled active waiting with quota recovery enabled. Remaining provider retry or unclassified-error recovery enters deadline-free waiting while remaining canonically active.
117
121
  Pending native-ineligible errors use a distinct `provider_error` kind, so their status does not claim unattempted retries were exhausted.
118
122
  Blank or absent error text still waits; any displayed detail is bounded and sanitized.
119
123
  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.
124
+ An explicit wait already accepted before a later non-usage assistant error retains its reason and deadline, unless cancellation or failed compaction recovery requires stopping.
125
+ Recognized usage errors instead follow the configured quota policy.
126
+ - Disabled retries or a zero retry budget can still end in quiet waiting without another native retry; only opt-in quota recovery can schedule a later request for a recognized usage limit.
122
127
  - 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.
123
128
  - 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
129
 
125
130
  Native retry-only cancellation preserves existing active waiting behavior for transient non-usage failures.
126
131
  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.
132
+ Final usage-limit policy still applies: default-off recovery stops as `usage_limited`, while enabled recovery can schedule a later request.
133
+ For non-usage errors, Goal uses the same deadline-free wait as provider retry exhaustion, retains Goal identity and managed-run ownership, and sends no extra request.
128
134
  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.
129
135
 
130
136
  Native classification replaces Goal's former retry text fallbacks, not its ability to wait.
131
137
  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
138
  Mixed quota or authentication wording cannot prevent a native-classified retry; successful native recovery keeps the same Goal active.
133
139
 
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.
140
+ The ordinary provider-error 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
141
  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
142
  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
143
  External messages can wake a permanently failing request and incur another provider charge; waiting itself creates no deadline, poller, continuation, or provider request.
@@ -142,6 +148,69 @@ Stopped transitions cancel current continuation ownership and block stale Goal-o
142
148
  Successful stopped-state resume rotates the goal id and starts a fresh blocker and safety audit.
143
149
  Waiting resume preserves the goal id, while clear removes Goal state and stale guards without aborting unrelated work.
144
150
 
151
+ ## Optional usage-limit recovery
152
+
153
+ `retryUsageLimits` is a boolean that defaults to `false`; the [settings reference](./settings.md#usage-limit-recovery) owns enablement and operational warnings.
154
+ This policy does not change error classification, native retry eligibility, backoff, cancellation, ordinary external waiting, or external-input wake rules.
155
+ A final recognized usage error enters tagged active waiting only when enabled and after the native recovery boundary settles; cancellation takes precedence.
156
+ It retains the Goal ID, cumulative usage, safety counters, and cooperative workflow ownership.
157
+ A managed run stays nonterminal `active`: no terminal `usage_limited` event is emitted and later reopened.
158
+ Quiet waiting is excluded from active elapsed time.
159
+
160
+ ### State and dispatch
161
+
162
+ The existing wait record carries optional `usageLimit` metadata `{ provider, model, api }` and an absolute `resumeAt` deadline.
163
+ Old wait records without that metadata remain ordinary waits.
164
+ The fallback deadline is 15 minutes after rejection; another direct quota rejection of the scheduled request arranges a new wait.
165
+ Successful work returns to normal Goal processing, and other errors retain their existing policies.
166
+ Recovery does not call stopped-state `/goal resume`, rotate the Goal ID, or reset the safety epoch.
167
+
168
+ The existing wait timer requests continuation intent; neither timers nor usage-query callbacks send model prompts directly.
169
+ The common settled-idle dispatcher requires the exact session, Goal, generation, workflow ownership, available helpers, remaining budget, applicable safety limits, idle state, and no pending messages.
170
+ One due deadline can dispatch at most one recovery request despite repeated settled events or competing callbacks.
171
+ Start-boundary ownership checks still protect the non-atomic idle-send race described above.
172
+
173
+ Pause, clear, edit, replacement, completion, terminal limits, helper loss, session replacement, shutdown, and observed model changes cancel owned timers, pending usage queries, and delivery intent.
174
+ A model-scope mismatch stops quota recovery as `usage_limited`; Pi cannot immediately expose every credential change.
175
+ Disabling recovery stops pending quota recovery only after the settings change commits; failed saves preserve the previous effective policy.
176
+ Enabling it does not restart an old stopped Goal.
177
+ Reload restores the persisted absolute deadline without restarting or re-clamping it; overdue deadlines still require the settled-idle gates.
178
+ Only Goal-owned state and the chosen deadline persist, not raw usage reports, credentials, or account fingerprints.
179
+
180
+ ### Optional public reset hints
181
+
182
+ Goal is independently installable and uses only the extension-neutral public [`usage:query:v1` event-bus protocol](https://github.com/narumiruna/pi-extensions/blob/main/packages/pi-usage/docs/api/usage-v1.md).
183
+ It does not import, require, identify, or inspect another extension.
184
+ A missing service leaves the fixed 15-minute fallback in place.
185
+ The query uses `refresh: true`, the synchronous response-offer transport, a cancellation signal, and a deadline of at most 15 seconds; it does not create a usage poller or refresh-notification loop.
186
+ The request is bound to the session-manager object, session ID, selected model and provider, Goal, and generation.
187
+ Callbacks revalidate ownership after asynchronous work and synchronous event publication before changing the deadline.
188
+
189
+ Only a fresh, valid refresh report for the selected provider can supply a hint.
190
+ Public `modelKeys` must match the current model's exact `id` or `name`; Goal does not interpret private bucket IDs or display labels as model scope or window relationships.
191
+ Unscoped buckets, including omitted or empty `modelKeys`, leave applicability ambiguous and require fallback.
192
+ Among confirmed applicable exhausted buckets, Goal chooses the latest future reset so all confirmed constraints can reset.
193
+ Missing or contradictory measurements, ambiguous window relationships, duplicate constraint identities, or missing usable future resets also require fallback.
194
+ Absent, unavailable, malformed, stale, rejected, cancelled, or timed-out responses cannot supply a hint.
195
+
196
+ Protocol `resetsAt` timestamps are Unix epoch milliseconds; `expiresAt` is report cache expiry, not quota reset.
197
+ A selected deadline is only a scheduling hint, not proof that allowance has returned or a request-specific `retryAt` guarantee.
198
+ Goal does not retain expired reports as authoritative availability evidence.
199
+ The current public API cannot always express safe applicability, including for Codex, so neither an installed usage service nor a displayed reset guarantees an actionable hint.
200
+
201
+ ### Recovery accounting
202
+
203
+ Request ownership, not error text alone, selects the exception.
204
+ Only a directly quota-rejected, work-free **scheduled recovery request** is exempt from automatic-work and no-progress increments.
205
+ Waiting and read-only usage queries create no model responses.
206
+ The first or original rejection, manual requests, successful work, partial work, other errors, and existing native retry work keep their existing accounting.
207
+ The exemption does not reset counters, subtract an unrelated earlier response, or bypass already exhausted safety or token limits.
208
+ All provider-reported token usage remains counted, including failed-request usage.
209
+
210
+ Because the unchanged classifier includes billing and credit exhaustion, enabled recovery can wait indefinitely and retain workflow ownership until account-owner action or cancellation.
211
+ Recovery requests can incur charges; there is no automatic credit redemption, authentication change, or provider-settings mutation.
212
+ Live quota reset, accounting delay, entitlement behavior, and provider-console agreement remain unverified; no live provider traffic was authorized for this change.
213
+
145
214
  ## Compaction persistence
146
215
 
147
216
  Canonical Goal state is stored in `goal-state` session entries. Before compaction, the runtime
@@ -177,7 +246,8 @@ Active elapsed time is accumulated only while status is `active` and not waiting
177
246
 
178
247
  Automatic-work safety is separate from the token budget:
179
248
 
180
- - `continuationLimits.automaticTurns` defaults to `25`; explicit `null` selects Unlimited, and `turn_end` counts normal responses from automatic continuations, including tool loops and matching recovery work.
249
+ - `continuationLimits.automaticTurns` defaults to `25`; explicit `null` selects Unlimited, and `turn_end` counts normal responses from automatic continuations, including tool loops and matching native recovery work.
250
+ Only the work-free scheduled quota-rejection exception above is excluded.
181
251
  - `continuationLimits.noProgressTurns` defaults to `3`. Repeated empty or normalized-identical
182
252
  tool-free automatic runs pause the goal; attempted tool calls reset that heuristic.
183
253
  - The no-progress fingerprint is fixed-size and stores no raw assistant text.
@@ -30,6 +30,24 @@ In the TUI, an automatic-work-limit pause offers **Review and continue…**, whi
30
30
  Changing the automatic-work limit alone leaves the goal paused; Back or Escape makes no change.
31
31
  An exhausted token budget must be raised above current usage before work can resume.
32
32
 
33
+ ## Recover from a provider usage limit
34
+
35
+ By default, recognized quota errors stop the Goal as `usage_limited` with no scheduled recovery.
36
+ Resolve the account condition and use `/goal resume`, or opt in to **Retry usage limits** in `/goal` → **Settings…** for future failures.
37
+ Enabling the setting does not wake an already stopped Goal; resume it explicitly.
38
+
39
+ Enabled recovery keeps the same Goal ID and safety epoch in active waiting, with its managed run and cooperative workflow ownership retained.
40
+ It uses an applicable reset hint or a 15-minute fallback and may wait indefinitely for billing, credit, or entitlement action.
41
+ Requests can incur provider charges; recovery does not redeem credits or change authentication or provider settings.
42
+ An exhausted safety or token limit still prevents further automatic work.
43
+
44
+ Use `/goal pause` or clear to stop recovery.
45
+ Turning **Retry usage limits** Off after a successful save cancels active quota recovery and restores stopped `usage_limited` behavior.
46
+ Editing or replacing the Goal cancels its previous recovery work; observed model changes also stop quota recovery.
47
+ Reload preserves the absolute deadline, not a new interval.
48
+ Manual `/goal resume` on an active waiting Goal wakes it without resetting its safety epoch, unlike resuming a stopped Goal.
49
+ See the [settings reference](./settings.md#usage-limit-recovery) for counting, cancellation, and service limitations.
50
+
33
51
  ## Clear and migrate legacy queues
34
52
 
35
53
  Menu-driven Clear previews the affected goal and requires confirmation.
package/docs/settings.md CHANGED
@@ -15,6 +15,7 @@ When `~/.pi/agent/pi-goal.json` is absent, pi-goal uses these built-in defaults
15
15
  "rpc": {
16
16
  "enabled": false
17
17
  },
18
+ "retryUsageLimits": false,
18
19
  "continuationLimits": {
19
20
  "automaticTurns": 25,
20
21
  "noProgressTurns": 3
@@ -23,7 +24,7 @@ When `~/.pi/agent/pi-goal.json` is absent, pi-goal uses these built-in defaults
23
24
  ```
24
25
 
25
26
  Use `/goal` → **Settings…** in the TUI to create or update the file, or edit it directly.
26
- The Settings screen shows all three controls on one level.
27
+ The Settings screen shows all four controls on one level.
27
28
  The two safety limits open separate choice screens:
28
29
 
29
30
  - **Automatic-work limit** shows the exact response limit or **Unlimited**.
@@ -31,6 +32,8 @@ The two safety limits open separate choice screens:
31
32
  Unlimited requires confirmation that tool loops may continue consuming tokens and provider cost without a response-count cap.
32
33
  - **No-progress guard** shows **_N_ runs** or **Off**.
33
34
  Choose the default threshold, **Off**, or **Set threshold…** and enter a safe whole number greater than zero.
35
+ - **Retry usage limits** is an **On**/**Off** row, defaulting to **Off**.
36
+ It enables scheduled recovery after recognized provider quota errors; read the [recovery policy](#usage-limit-recovery) before enabling it.
34
37
  - **Managed run RPC** controls whether trusted installed extensions may start and cancel managed Goal runs.
35
38
  It defaults to **Off** and controls cooperation, not extension permissions.
36
39
 
@@ -60,7 +63,8 @@ Reload, replacement, and shutdown clear that in-memory ownership.
60
63
  `continuationLimits` controls the automatic-work safety guards:
61
64
 
62
65
  - `automaticTurns` accepts a positive safe integer or `null` and defaults to `25`.
63
- It counts every completed normal `turn_end` owned by automatically started Goal work, including model responses inside tool loops and matching Pi-owned retries.
66
+ It counts completed normal `turn_end` responses owned by automatically started Goal work, including model responses inside tool loops and matching Pi-owned retries.
67
+ The only quota-recovery exception is a work-free, directly quota-rejected scheduled request, as described below.
64
68
  The user-triggered kickoff, resume, edit, and ordinary user runs are not charged.
65
69
  At the limit, the goal becomes `paused` with cause `continuation_limit` and pending continuation or recovery is cancelled.
66
70
  The current operation is aborted before a 26th normal response starts.
@@ -73,6 +77,48 @@ Reload, replacement, and shutdown clear that in-memory ownership.
73
77
  Different non-empty output starts a new run at one, and any attempted tool call resets it.
74
78
  Set this field to `null` to disable only this heuristic.
75
79
 
80
+ ## Usage-limit recovery
81
+
82
+ `retryUsageLimits` accepts only a boolean and defaults to `false`.
83
+ With recovery disabled, a final recognized quota error stops the Goal as `usage_limited`; resolve the account condition and run `/goal resume` manually.
84
+ To opt in, use **Retry usage limits** in Settings or set `"retryUsageLimits": true` in the user settings file and reload.
85
+ There are no interval, retry-count, or provider-specific settings.
86
+
87
+ When enabled, recovery keeps the same Goal ID, cumulative usage, safety counters, managed run, and cooperative workflow ownership in active waiting.
88
+ Quiet waiting does not count toward active elapsed time.
89
+ A usable public reset hint determines the next recovery deadline; otherwise the fallback is 15 minutes.
90
+ Another extension or usage service is not required.
91
+ The public usage API cannot always establish which limits apply, including for Codex; a displayed reset time does not guarantee an actionable hint or available quota.
92
+ See the [lifecycle reference](./continuation-lifecycle.md#optional-usage-limit-recovery) for hint validation and dispatch rules.
93
+
94
+ Waiting and read-only usage queries do not count as model responses.
95
+ Only a scheduled recovery request that is directly rejected by a recognized usage limit without actual work is exempt from automatic-work and no-progress counters.
96
+ Successful responses, partial work, the original rejected request, manual requests, and existing native retry work retain their existing accounting.
97
+ All provider-reported token usage is retained, including failed-request usage.
98
+ Recovery does not reset counters or bypass an exhausted work, no-progress, or token limit.
99
+
100
+ The classifier is unchanged and includes subscription, billing, and credit exhaustion, not just temporary quotas.
101
+ Recovery can wait indefinitely for account-owner action and can make paid requests when a deadline or external input wakes the Goal.
102
+ It does not redeem credits, change authentication, or modify provider settings.
103
+ Pi's native retry policy, ordinary `goal_wait`, and external-input wake behavior are unchanged.
104
+
105
+ Turning recovery **Off** after a committed settings save cancels pending quota recovery and stops that Goal as `usage_limited` for manual recovery.
106
+ A failed save does not commit that stop.
107
+ Turning it **On** does not restart an already stopped Goal; resume it explicitly.
108
+ Pause, clear, edit, replacement, completion, terminal limits, session replacement, shutdown, and observed model changes cancel pending recovery work.
109
+ Reload restores the absolute deadline instead of restarting the interval.
110
+ Pi does not report every credential change immediately, so immediate account-switch detection is not guaranteed.
111
+
112
+ Live quota reset, provider accounting delay, entitlement behavior, and agreement with a provider console remain unverified.
113
+ No live provider traffic was authorized for this change; deterministic verification does not establish those external behaviors.
114
+
115
+ ## Loading and compatibility
116
+
117
+ The settings file is user-scoped at `<getAgentDir()>/pi-goal.json`, normally `~/.pi/agent/pi-goal.json`; Goal has no project settings override.
118
+ Omitted fields use built-in defaults, and explicit valid user values override them.
119
+ Settings reads do not create files or directories.
120
+ Saves are ordered within one Pi process; they do not coordinate separate Pi processes.
121
+
76
122
  Settings are reread at Pi startup, session replacement, and `/reload`.
77
123
  Direct file edits are not watched, while Goal-menu changes apply immediately.
78
124
  A missing file remains absent and uses the built-in defaults.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-goal",
3
- "version": "0.54.17",
3
+ "version": "0.55.1",
4
4
  "description": "Pi extension for autonomous single-objective /goal completion.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -44,11 +44,11 @@
44
44
  "@earendil-works/pi-coding-agent": "1.5.0",
45
45
  "@earendil-works/pi-tui": "1.5.0",
46
46
  "esbuild": "0.28.2",
47
- "typebox": "1.4.3",
47
+ "typebox": "1.4.4",
48
48
  "typescript": "7.0.2"
49
49
  },
50
50
  "dependencies": {
51
- "@narumitw/pi-tui-kit": "^0.69.1"
51
+ "@narumitw/pi-tui-kit": "^0.70.0"
52
52
  },
53
53
  "repository": {
54
54
  "type": "git",
package/src/lifecycle.ts CHANGED
@@ -27,6 +27,7 @@ import {
27
27
  } from "./runtime.js";
28
28
  import { hasAssistantToolCall } from "./safety.js";
29
29
  import { DEFAULT_GOAL_SETTINGS, readGoalSettings } from "./settings.js";
30
+ import { usageLimitScope } from "./usage-limit-recovery.js";
30
31
 
31
32
  const REMOVED_QUEUE_SETTING_WARNING =
32
33
  "Ordered goal queue has been removed. Use /goal edit to reprioritize an active objective, or start /goal <objectives> if no active goal exists.";
@@ -177,6 +178,10 @@ export function registerGoalLifecycle(
177
178
  runtime.unbindWorkflowSession(shutdownSession);
178
179
  });
179
180
 
181
+ pi.on("model_select", (_event, ctx) => {
182
+ if (sessionActive) runtime.usageLimitRecovery.modelChanged(ctx);
183
+ });
184
+
180
185
  pi.on("session_before_compact", (event, ctx) => {
181
186
  if (!sessionActive) return;
182
187
  if (runtime.activeGoal?.status === "budget_limited") {
@@ -425,7 +430,8 @@ export function registerGoalLifecycle(
425
430
  if (runtime.guardAbortGoalId) runtime.guardAbortGoalId = undefined;
426
431
  const goalPrompt = runtime.consumeOwnedGoalPrompt(event.prompt);
427
432
  const goalPromptGoalId = goalPrompt?.goalId;
428
- const continuationGoalId = goalPromptGoalId ? undefined : runtime.markContinuationStarted(event.prompt);
433
+ const continuation = goalPromptGoalId ? undefined : runtime.markContinuationStarted(event.prompt);
434
+ const continuationGoalId = continuation?.goalId;
429
435
  const ownedPromptGoalId = goalPromptGoalId ?? continuationGoalId;
430
436
  const ownedPromptBoundary = runtime.hasOwnedPromptBoundary(event.prompt);
431
437
  const activeBudgetWrapUp = runtime.hasActiveBudgetWrapUp();
@@ -469,7 +475,7 @@ export function registerGoalLifecycle(
469
475
  if (runtime.activeGoal?.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
470
476
  return goalContractBoundaryResult(ctx);
471
477
  }
472
- runtime.beginAgentRun(runtime.activeGoal.id, runOrigin);
478
+ runtime.beginAgentRun(runtime.activeGoal.id, runOrigin, continuation?.usageLimitRetry);
473
479
  if (!runtime.goalToolsAvailable()) {
474
480
  runtime.pauseGoalForUnavailableTools(ctx, ownedPromptGoalId !== undefined);
475
481
  return goalContractBoundaryResult(ctx);
@@ -546,7 +552,7 @@ export function registerGoalLifecycle(
546
552
 
547
553
  if (finalAssistant?.stopReason === "error") {
548
554
  const nativeRecovery = isRetryableGoalInterruption(finalAssistant);
549
- if (!nativeRecovery && isUsageLimitedGoalInterruption(finalAssistant)) {
555
+ if (!nativeRecovery && isUsageLimitedGoalInterruption(finalAssistant) && !runtime.settings.retryUsageLimits) {
550
556
  runtime.clearGoalRecoveryForGoal(goalId);
551
557
  stopGoalAfterAgentEnd(ctx, runtime.activeGoal, finalAssistant, "usage_limited");
552
558
  return;
@@ -572,6 +578,9 @@ export function registerGoalLifecycle(
572
578
  : "provider_error",
573
579
  automaticOwner: run.origin === "automatic",
574
580
  errorMessage: finalAssistant.errorMessage,
581
+ ...(runtime.settings.retryUsageLimits && isUsageLimitedGoalInterruption(finalAssistant)
582
+ ? { usageLimitScope: run.usageLimitRetry ?? usageLimitScope(ctx) }
583
+ : {}),
575
584
  };
576
585
  runtime.cancelContinuationWork();
577
586
  runtime.persistGoal(runtime.activeGoal);