@narumitw/pi-goal 0.53.1 → 0.54.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,6 +10,7 @@ Goal mode adds explicit completion, blocker, and external-wait tools so managed
10
10
 
11
11
  - Starts or manages a session goal through one `/goal` command and direct status, pause, resume, edit, or clear routes.
12
12
  - Continues exactly once from Pi's settled idle boundary after queued work, retries, and compaction have finished.
13
+ - Waits quietly for a follow-up when transient provider retries are exhausted instead of terminally blocking the Goal.
13
14
  - Uses explicit `goal_complete`, `goal_blocked`, and `goal_wait` tools with stale-goal guards and evidence requirements.
14
15
  - Tracks active, paused, blocked, usage-limited, budget-limited, waiting, and complete outcomes separately.
15
16
  - Pauses after a configurable response limit or repeated no-progress runs and offers a guided review before continuing.
@@ -54,7 +55,6 @@ When `~/.pi/agent/pi-goal.json` is absent, pi-goal uses these built-in defaults
54
55
 
55
56
  ```json
56
57
  {
57
- "toolVisibility": "after-first-goal",
58
58
  "rpc": {
59
59
  "enabled": false
60
60
  },
@@ -66,14 +66,13 @@ When `~/.pi/agent/pi-goal.json` is absent, pi-goal uses these built-in defaults
66
66
  ```
67
67
 
68
68
  Use `/goal` → **Settings…** in the TUI to create or update the file interactively, or create and edit it directly.
69
- The standard Settings screen keeps all four controls on one level in task order; the two safety limits open standard choice screens:
69
+ The standard Settings screen keeps all three controls on one level in task order; the two safety limits open standard choice screens:
70
70
 
71
71
  - **Automatic-work limit** shows the exact response limit or **Unlimited**.
72
72
  Choose **Set response limit…** to edit the current finite value (or the built-in default of 25 when switching from Unlimited), or choose **Unlimited…**.
73
73
  Unlimited requires confirmation that tool loops may continue consuming tokens and provider cost without a response-count cap.
74
74
  - **No-progress guard** shows **_N_ runs** or **Off**.
75
75
  Choose the default threshold, **Off**, or **Set threshold…** and enter a safe whole number greater than zero.
76
- - **Goal tools** controls whether all Goal tools are always visible or appear after the first goal.
77
76
  - **Managed run RPC** controls whether trusted installed extensions may start and cancel managed Goal runs.
78
77
  It defaults to **Off** and is a cooperation setting, not an extension security sandbox.
79
78
 
@@ -81,16 +80,12 @@ Custom number inputs reject zero, negative numbers, decimals, text, and unsafe i
81
80
  Interactive changes are serialized, written atomically, preserve unknown fields, and apply to the current runtime.
82
81
  A successful change updates the visible state immediately.
83
82
  A failed save restores the prior value and reports the settings path so it can be retried.
84
- Tool-visibility changes that would alter the active tool schema are rejected while Pi is busy or another cooperative workflow owns the session; retry after both conditions clear.
85
83
  Escape returns to the previous screen without reverting changes that were already saved.
86
84
 
87
- `toolVisibility` accepts:
88
-
89
- - `"always"` — pi-goal does not proactively hide `goal_complete`, `goal_blocked`, or `goal_wait`, keeping the Goal tool schema stable from session startup.
90
- - `"after-first-goal"` (default) — hides all three Goal tools at fresh runtime startup, reveals them for the first accepted Goal activation, and treats an unfinished-goal restore as unlocked for the remainder of that extension runtime.
91
- On restore, pi-goal uses the active tools already established by earlier lifecycle handlers; it does not re-add missing terminal tools over a restrictive policy.
92
- Failed kickoff, replacement, resume, or reactivating-edit delivery restores the exact pre-activation tool set, including Goal tools exposed by another extension.
93
- If revealing the tools would widen an already-running turn, wait for Pi to become idle and retry `/goal`.
85
+ Pi-goal registers `goal_complete`, `goal_blocked`, and `goal_wait` once and keeps their schemas stable from startup.
86
+ Visible Goal tools do not mean Goal mode is active, and only the latest effective active Goal contract authorizes their use.
87
+ Pi-goal never widens a restrictive active-tool policy; activation rejects when required terminal tools are missing, and an active Goal pauses if they later disappear.
88
+ The retired `toolVisibility` key is ignored and preserved as unknown data when another setting is saved.
94
89
 
95
90
  `experimental.goals` is a removed legacy setting.
96
91
  If it remains `true`, pi-goal accepts the settings file, ignores the old queue feature, and shows an affected-user warning that recommends `/goal edit` when an active objective exists or `/goal <objectives>` when no active goal exists.
@@ -125,11 +120,9 @@ Omitted fields use the defaults above.
125
120
  Invalid or malformed existing settings are never overwritten; they produce a warning and fall back to all defaults.
126
121
  In the TUI, Goal Settings becomes a read-only summary that identifies the invalid file and directs the user to fix it and run `/reload`.
127
122
  Reload Pi after changing the file.
128
- If a live runtime reloads settings, switching `toolVisibility` to `"always"` restores only the exact tools that pi-goal previously hid, while switching to `"after-first-goal"` locks a runtime that has no unfinished goal.
129
123
 
130
- Inactive tool widening first takes temporary Workflow Mutex ownership and leaves settings, hidden-tool ownership, and active tools unchanged when another workflow is active.
131
- Tool visibility is a baseline, not ownership of Pi's global active-tool list.
132
- Plan mode or another restrictive policy may temporarily hide the tools. pi-goal does not fight that policy on restore or on every turn: activation is rejected if the required terminal tools cannot be made available, and an already-active goal is paused without automatic continuation if they disappear.
124
+ Plan mode or another restrictive policy may hide Goal tools.
125
+ Pi-goal does not fight that policy on restore or on later turns: activation rejects when required terminal tools are unavailable, and an already-active goal pauses without automatic continuation if they disappear.
133
126
  A restrictive allowlist created before `goal_wait` existed can still run ordinary Goals with `goal_complete` and `goal_blocked`, but the model cannot enter external waiting until that allowlist also includes `goal_wait`.
134
127
  The pause aborts a Goal-owned kickoff, resume, active-edit, or automatic-continuation prompt, but it does not cancel or stale-block an unrelated user or extension turn, including startup follow-ups after a restrictive restore.
135
128
 
@@ -148,8 +141,6 @@ Restored active Goal state acquires before tool restoration, persistence publica
148
141
  If restoration is busy, the Goal moves only to its existing paused safe state, does not change active tools or schedule work, and can be resumed explicitly after the other workflow ends.
149
142
  Restored stopped Goals and inert legacy queues do not acquire or schedule automatic work.
150
143
 
151
- Inactive session-start restoration and live settings changes that could alter Goal tool visibility use temporary synchronous ownership.
152
- A busy result preserves the settings file, in-memory settings, active tools, and hidden-tool retry ownership.
153
144
  An active Goal still pauses if a non-participating restrictive policy later removes its required terminal tools.
154
145
 
155
146
  The coexistence guarantee is cooperative and applies only when every contender implements v1 on the characterized Pi runtime and shares its event bus and session-manager identity.
@@ -228,8 +219,7 @@ Goal state is stored as Pi session state, similar to Codex's thread-owned goals.
228
219
  `/reload` and reopening the same Pi session can restore that session's unfinished goal.
229
220
  An active restored goal already at or above its finite automatic-work limit pauses before another provider request and reports that progress is saved; use `/goal` to review and continue.
230
221
  A restored waiting Goal remains quiet, excludes offline and waiting wall time from active elapsed time, and restores only its absolute optional deadline timer.
231
- With `"after-first-goal"`, an admitted unfinished restore marks the tools unlocked in the new extension runtime, but it does not widen an active-tool set already restricted by an earlier lifecycle handler; an active goal instead restores as paused when admission is busy or either terminal tool is missing.
232
- If no unfinished goal remains, a fresh runtime starts locked again.
222
+ An active restored goal pauses when workflow admission is busy or either required terminal tool is missing, without changing the active tool set.
233
223
  Active elapsed time is checkpointed before shutdown and restarted after reload only when the Goal is not waiting, so offline and stopped wall-clock time is excluded.
234
224
  Automatic-response counts, repeat fingerprints, and safety-pause causes persist across reload and compaction.
235
225
  A direct non-`/goal` user/RPC input resets the safety epoch only while the goal is active and reclassifies the in-flight run as manual; extension input and messages sent while stopped do not reset it.
@@ -284,8 +274,8 @@ The default 25-response automatic-work limit is a response-count boundary, not a
284
274
  Pi derives displayed cost estimates from provider-reported token usage and local model pricing; pi-goal does not query a billing balance or enforce a dollar cap.
285
275
  For tighter token control, choose a smaller `automaticTurns` value and/or use `/goal --tokens`; choosing Unlimited removes only the response-count boundary.
286
276
 
287
- Elapsed time is accumulated only while status is `active`.
288
- Pause, blocked, usage-limited, budget-limited, shutdown, and offline periods do not increase it.
277
+ Elapsed time is accumulated only while status is `active` and the Goal is not waiting.
278
+ Waiting, paused, blocked, usage-limited, budget-limited, shutdown, and offline periods do not increase it.
289
279
  Legacy session entries are migrated by preserving their accumulated seconds and starting a fresh active clock when loaded.
290
280
 
291
281
  ## ✅ How completion works
@@ -294,11 +284,13 @@ While a goal is active, Goal-owned messages carry persistence rules and a `<goal
294
284
  Kickoff, resume, edited-objective, wait-resume, and automatic-continuation prompts all place a trust boundary before the escaped objective, identifying it as user-provided task data; they preserve its full scope across turns and require the agent to derive concrete requirements from the objective and referenced artifacts.
295
285
  They treat the current worktree, command output, tests, runtime behavior, PR state, rendered artifacts, and external state as authoritative; previous conversation and plans are context rather than proof.
296
286
 
297
- With the default `toolVisibility: "after-first-goal"`, the first accepted Goal activation intentionally reveals the three Goal tools and changes the tool-definition prefix once.
298
- After that activation boundary, pi-goal does not change the base system instructions or ordered active tools merely for continuation, token accounting, or wait resume.
287
+ Goal helper names, definitions, and active prompt metadata remain stable across Goal activation, continuation, token accounting, wait resume, completion, and clearing.
288
+ Mode-only positive instructions live in the append-only active Goal contract instead of globally active tool prompt metadata.
299
289
  Current token-budget usage is carried by the newly appended Goal prompt instead of rewriting leading system instructions.
300
- For every active Goal, one deterministic hidden Goal contract occupies a fixed leading boundary and excludes mutable token, iteration, and elapsed-time counters.
301
- This contract follows leading summaries after compaction and also restores Goal instructions when persisted active state has no retained handoff.
290
+ The first accepted handoff for each Goal identity persists one deterministic hidden Goal contract at the same agent-start boundary, after previously retained conversation history.
291
+ The contract explicitly supersedes earlier Goal contracts, excludes mutable token, iteration, and elapsed-time counters, and stays at its appended history position.
292
+ Editing, replacing, and stopped-state resume append a new superseding active contract without deleting earlier provider input; failed handoff delivery appends no contract.
293
+ Completion, clearing, and stopped transitions append one inactive superseding contract, while compaction and session restore append a missing current-state contract without waking a waiting Goal.
302
294
  These structural guarantees make provider prefix reuse possible, but the provider still decides cache eligibility, cache hits, pricing, and billing.
303
295
 
304
296
  Before completion, the shared audit tells the agent to treat completion as unproven, inspect requirement-by-requirement evidence for every named artifact, command, test, gate, invariant, and deliverable, and match each check's scope to the requirement it supports.
@@ -340,7 +332,12 @@ Omitting `resume_after_ms` intentionally permits an indefinite quiet wait.
340
332
  An accepted call keeps the canonical Goal status active, checkpoints active elapsed time, cancels pending continuation work, persists the reason and absolute optional deadline, and terminates the normal single-tool run.
341
333
  Call `goal_wait` alone because Pi only guarantees early termination when every finalized result in a parallel tool batch terminates.
342
334
 
343
- Interactive input, RPC input, another extension's `sendUserMessage()` input, and supported non-Goal custom follow-ups clear the wait before their turn runs. pi-goal-owned kickoff, resume, edit, continuation, stale, or cancelled prompts do not count as external wake-ups.
335
+ When Pi exhausts retries for a transient provider error such as HTTP 429, pi-goal enters the same active waiting state without a deadline instead of marking the Goal blocked.
336
+ The warning reports bounded provider status and explains that a follow-up or `/goal resume` retries the Goal.
337
+ Context-overflow compaction exhaustion remains blocked because another model turn can repeat the same oversized request without corrective compaction.
338
+
339
+ Interactive input, RPC input, another extension's `sendUserMessage()` input, and supported non-Goal custom follow-ups clear the wait before their turn runs.
340
+ pi-goal-owned kickoff, resume, edit, continuation, stale, or cancelled prompts do not count as external wake-ups.
344
341
  Pi does not expose the sending extension's identity, so any non-Goal extension message is treated as a wake signal.
345
342
 
346
343
  After a waking turn ends, ordinary continuation rules apply again.
@@ -354,8 +351,8 @@ An already-due deadline waits for Pi's settled, idle, no-pending-message boundar
354
351
  If that delivery throws, pi-goal restores the wait, retries once after one second, and leaves the Goal visibly waiting after a second failure instead of retry-looping.
355
352
  A deadline never sends a prompt directly from a stale timer.
356
353
 
357
- Waiting time is excluded from **Active elapsed**, while tokens, iteration, automatic-response count, no-progress state, managed-run ownership remain preserved.
358
- The managed-run protocol continues reporting `active` because waiting is non-terminal.
354
+ Waiting time is excluded from **Active elapsed**, while tokens, iteration, automatic-response count, no-progress state, and managed-run ownership remain preserved.
355
+ The managed-run protocol continues reporting `active` without a duplicate state event because waiting is non-terminal, including after transient provider retry exhaustion.
359
356
  Editing or replacing a waiting Goal clears the previous wait so the updated objective performs a fresh external-state check.
360
357
 
361
358
  ## 🚧 Blocked goals
@@ -375,8 +372,10 @@ A user pause or aborted turn produces `paused`; a terminal provider/account quot
375
372
  Each stopped transition cancels pending continuation intent or delivery, aborts stale work when applicable, and blocks stale tool calls until the next non-goal user prompt, successful reactivation/replacement, or `/goal clear`.
376
373
  On `/goal clear`, the extension clears goal state, continuation markers, and any stale tool-call block without aborting an unrelated in-flight turn.
377
374
  Retryable provider interruptions and overflow compaction retries stay `active` while Pi retries; no extra continuation is queued, and automatic ownership remains charged through retry `agent_start` events.
378
- If matching recovery still exists at `agent_settled`, retries are exhausted and the goal becomes `blocked` before any continuation dispatches.
379
- Stale recovery cannot block a replacement goal.
375
+ If matching provider recovery still exists at `agent_settled`, retries are exhausted and the Goal enters a deadline-free active wait before any continuation dispatches.
376
+ A later non-Goal input wakes the same Goal without rotating its stale-turn guard, so the model can continue, complete, or enter another wait with the current `goal_id`.
377
+ If matching compaction recovery still exists at `agent_settled`, the Goal becomes `blocked` because recovery did not produce usable context.
378
+ Stale recovery cannot wait or block a replacement goal.
380
379
  User and extension work that starts before settlement supersedes the older continuation intent, and pending messages always take priority.
381
380
 
382
381
  ## 🤝 Managed run RPC
@@ -492,7 +491,7 @@ packages/pi-goal/
492
491
  │ ├── lifecycle.ts # Pi session, agent, tool, and compaction event adapter
493
492
  │ ├── goal-contract.ts # Deterministic post-compaction model contract
494
493
  │ ├── runtime.ts # Per-factory Goal state, transitions, prompts, and budgets
495
- │ ├── tool-policy.ts # Goal tool visibility ownership and rollback
494
+ │ ├── tool-policy.ts # Goal tool names and read-only availability checks
496
495
  │ ├── safety.ts # Output normalization and no-progress fingerprint state
497
496
  │ ├── wait.ts # External-wait validation and session timer ownership
498
497
  │ ├── errors.ts # Pi-aligned provider error and retry classification
@@ -1,5 +1,5 @@
1
1
  // @generated by scripts/build-runtime.mjs; do not edit.
2
- // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
2
+ // @ts-nocheck -- the generated entry uses a .ts extension for Pi's Jiti loader.
3
3
 
4
4
  // src/accounting.ts
5
5
  function checkpointGoalActiveTime(goal, now, continueClock) {
@@ -201,16 +201,12 @@ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node
201
201
  import { basename, dirname, join } from "node:path";
202
202
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
203
203
  var GOAL_SETTINGS_FILE = "pi-goal.json";
204
- var GOAL_TOOL_VISIBILITIES = ["always", "after-first-goal"];
205
204
  var DEFAULT_GOAL_SETTINGS = {
206
- toolVisibility: "after-first-goal",
207
205
  rpc: { enabled: false },
208
206
  continuationLimits: { automaticTurns: 25, noProgressTurns: 3 }
209
207
  };
210
208
  function normalizeGoalSettings(value) {
211
209
  if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
212
- const toolVisibility = Object.hasOwn(value, "toolVisibility") ? Reflect.get(value, "toolVisibility") : DEFAULT_GOAL_SETTINGS.toolVisibility;
213
- if (!GOAL_TOOL_VISIBILITIES.includes(toolVisibility)) return void 0;
214
210
  const rpcValue = Object.hasOwn(value, "rpc") ? Reflect.get(value, "rpc") : void 0;
215
211
  if (rpcValue !== void 0 && (typeof rpcValue !== "object" || rpcValue === null || Array.isArray(rpcValue))) {
216
212
  return void 0;
@@ -231,7 +227,6 @@ function normalizeGoalSettings(value) {
231
227
  ) : DEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns;
232
228
  if (automaticTurns === void 0 || noProgressTurns === void 0) return void 0;
233
229
  return {
234
- toolVisibility,
235
230
  rpc: { enabled: rpcEnabled },
236
231
  continuationLimits: { automaticTurns, noProgressTurns }
237
232
  };
@@ -262,7 +257,6 @@ function saveGoalSettings(settings, settingsPath = join(getAgentDir(), GOAL_SETT
262
257
  const document = `${JSON.stringify(
263
258
  {
264
259
  ...raw,
265
- toolVisibility: normalized.toolVisibility,
266
260
  rpc: { ...rpc, enabled: normalized.rpc.enabled },
267
261
  continuationLimits: {
268
262
  ...continuationLimits,
@@ -345,4 +339,4 @@ export {
345
339
  saveGoalSettings,
346
340
  readGoalSettings
347
341
  };
348
- //# sourceMappingURL=chunk-UA7LMS63.ts.map
342
+ //# sourceMappingURL=chunk-UQRRW4CY.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/accounting.ts", "../../src/errors.ts", "../../src/settings.ts"],
4
- "sourcesContent": ["import type { Usage } from \"@earendil-works/pi-ai\";\n\nexport interface GoalAccountingState {\n\tstatus: string;\n\tbaselineTokens: number;\n\ttokensUsed: number;\n\ttimeUsedSeconds: number;\n\tactiveStartedAt?: number;\n\tupdatedAt: number;\n}\n\ninterface AssistantUsageEntryLike {\n\ttype?: unknown;\n\tmessage?: unknown;\n}\n\ninterface UsageContext {\n\tsessionManager?: unknown;\n}\n\nexport function checkpointGoalActiveTime(\n\tgoal: GoalAccountingState,\n\tnow: number,\n\tcontinueClock: boolean,\n) {\n\tconst accumulated = nonNegativeFiniteNumber(goal.timeUsedSeconds);\n\tconst startedAt = goal.activeStartedAt;\n\tif (typeof startedAt === \"number\" && Number.isFinite(startedAt)) {\n\t\tgoal.timeUsedSeconds = accumulated + Math.max(0, now - startedAt) / 1000;\n\t} else {\n\t\tgoal.timeUsedSeconds = accumulated;\n\t}\n\tgoal.activeStartedAt = continueClock ? now : undefined;\n}\n\nexport function updateGoalUsage(\n\tgoal: GoalAccountingState,\n\tctx: UsageContext,\n\tcontinueClock = goal.status === \"active\",\n) {\n\tconst now = Date.now();\n\tconst baselineTokens = nonNegativeFiniteNumber(goal.baselineTokens);\n\tgoal.baselineTokens = baselineTokens;\n\tgoal.tokensUsed = Math.max(0, currentTokenTotal(ctx) - baselineTokens);\n\tcheckpointGoalActiveTime(goal, now, continueClock);\n\tgoal.updatedAt = now;\n}\n\nexport function formatDuration(seconds: number) {\n\tconst wholeSeconds = Math.max(0, Math.floor(nonNegativeFiniteNumber(seconds)));\n\tif (wholeSeconds < 60) return `${wholeSeconds}s`;\n\tconst minutes = Math.floor(wholeSeconds / 60);\n\tif (minutes < 60) return `${minutes}m`;\n\tconst hours = Math.floor(minutes / 60);\n\treturn `${hours}h${minutes % 60}m`;\n}\n\nexport function formatTokenCount(value: number) {\n\tif (value < 1_000) return `${value}`;\n\tif (value < 1_000_000) {\n\t\treturn `${Number.isInteger(value / 1_000) ? value / 1_000 : (value / 1_000).toFixed(1)}k`;\n\t}\n\treturn `${Number.isInteger(value / 1_000_000) ? value / 1_000_000 : (value / 1_000_000).toFixed(1)}m`;\n}\n\nexport function isNonNegativeFiniteNumber(value: unknown): value is number {\n\treturn typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n}\n\nexport function nonNegativeFiniteNumber(value: unknown) {\n\treturn isNonNegativeFiniteNumber(value) ? value : 0;\n}\n\nexport function normalizeTokenBudget(value: unknown) {\n\treturn typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 ? value : undefined;\n}\n\nexport function assistantUsageTokens(value: unknown) {\n\tif (!value || typeof value !== \"object\") return 0;\n\tconst usage = value as Partial<Usage>;\n\tif (isNonNegativeFiniteNumber(usage.totalTokens)) return usage.totalTokens;\n\treturn Math.min(\n\t\tNumber.MAX_SAFE_INTEGER,\n\t\tnonNegativeFiniteNumber(usage.input) +\n\t\t\tnonNegativeFiniteNumber(usage.output) +\n\t\t\tnonNegativeFiniteNumber(usage.cacheRead) +\n\t\t\tnonNegativeFiniteNumber(usage.cacheWrite),\n\t);\n}\n\nexport function cumulativeAssistantTokens(entries: unknown[]) {\n\tlet total = 0;\n\tfor (const entry of entries) {\n\t\tconst candidate = entry as AssistantUsageEntryLike;\n\t\tif (candidate?.type !== \"message\") continue;\n\t\tconst message = candidate.message as { role?: unknown; usage?: unknown } | undefined;\n\t\tif (message?.role !== \"assistant\") continue;\n\t\ttotal = Math.min(Number.MAX_SAFE_INTEGER, total + assistantUsageTokens(message.usage));\n\t}\n\treturn total;\n}\n\nexport function currentTokenTotal(ctx: UsageContext): number {\n\tconst sessionManager = ctx.sessionManager as { getBranch?: () => unknown[] } | undefined;\n\treturn cumulativeAssistantTokens(sessionManager?.getBranch?.() ?? []);\n}\n", "import {\n\tisContextOverflow,\n\tisRetryableAssistantError,\n\ttype AssistantMessage as PiAssistantMessage,\n\ttype Usage,\n} from \"@earendil-works/pi-ai\";\nimport { stripTerminalSequences } from \"@earendil-works/pi-tui\";\nimport { assistantUsageTokens, nonNegativeFiniteNumber } from \"./accounting.js\";\n\nexport type AgentStopReason = \"stop\" | \"length\" | \"toolUse\" | \"error\" | \"aborted\";\n\nexport interface AssistantMessageLike {\n\trole: \"assistant\";\n\tstopReason?: AgentStopReason;\n\terrorMessage?: string;\n\tcontent?: PiAssistantMessage[\"content\"];\n\tapi?: PiAssistantMessage[\"api\"];\n\tprovider?: PiAssistantMessage[\"provider\"];\n\tmodel?: string;\n\tusage?: Usage;\n\ttimestamp?: number;\n}\n\nconst USAGE_LIMIT_GOAL_ERROR_PATTERNS = [\n\t/usage[_\\s-]*(?:limit|cap)|chatgpt.{0,32}usage/i,\n\t/quota.{0,32}(?:reached|exceeded|exhausted|depleted)|(?:reached|exceeded|exhausted|depleted).{0,32}quota/i,\n\t/insufficient[_\\s-]*(?:quota|credits?)|out of credits|out of budget|available balance|payment required/i,\n\t/(?:credit|balance).{0,32}(?:low|exhausted|depleted)|billing/i,\n] as const;\nconst NON_RETRYABLE_GOAL_ERROR_RE =\n\t/multi-auth rotation failed|credentials tried|unauthori[sz]ed|invalid api key/i;\nconst RETRYABLE_GOAL_ERROR_PATTERNS = [\n\t/overloaded|rate.?limit|too many requests|\\b(?:429|500|502|503|504)\\b|service.?unavailable|server.?error|internal.?error/i,\n\t/provider.?returned.?error|you can retry your request|try your request again|please retry your request/i,\n\t/network.?error|connection.?(?:error|refused|lost)|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up/i,\n\t/timed? out|timeout|terminated|websocket.?(?:closed|error)|ended without|stream ended before message_stop|http2 request did not get a response|retry delay/i,\n\t/context[_\\s-]*length[_\\s-]*exceeded|input exceeds the context window/i,\n] as const;\n\nexport function safeTerminalText(value: string) {\n\treturn [...stripTerminalSequences(value)]\n\t\t.map((character) => {\n\t\t\tconst codePoint = character.codePointAt(0) ?? 0;\n\t\t\tif (character === \"\\n\") return character;\n\t\t\treturn codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? \" \" : character;\n\t\t})\n\t\t.join(\"\")\n\t\t.trim();\n}\n\nexport function safeGoalMenuText(value: string, maxCharacters = 120) {\n\tconst sanitized = safeTerminalText(value).replace(/\\s+/gu, \" \").trim();\n\tconst characters = [...sanitized];\n\treturn characters.length <= maxCharacters\n\t\t? sanitized\n\t\t: `${characters.slice(0, maxCharacters).join(\"\")}\u2026`;\n}\n\nexport function notifyTerminal(\n\tui: { notify: (message: string, level?: \"info\" | \"warning\" | \"error\") => void },\n\tmessage: string,\n\tlevel?: \"info\" | \"warning\" | \"error\",\n) {\n\tui.notify(safeTerminalText(message), level);\n}\n\nexport function formatError(error: unknown) {\n\treturn truncateNotification(error instanceof Error ? error.message : String(error));\n}\n\nexport function truncateNotification(value: string) {\n\tconst safe = [...safeTerminalText(value)];\n\treturn safe.length > 160 ? `${safe.slice(0, 157).join(\"\")}...` : safe.join(\"\");\n}\n\nexport function isUsageLimitedGoalInterruption(assistant: AssistantMessageLike) {\n\tconst errorMessage = assistant.errorMessage;\n\treturn (\n\t\tassistant.stopReason === \"error\" &&\n\t\ttypeof errorMessage === \"string\" &&\n\t\tUSAGE_LIMIT_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(errorMessage))\n\t);\n}\n\nexport function isRetryableGoalInterruption(assistant: AssistantMessageLike) {\n\tif (assistant.stopReason !== \"error\" || !assistant.errorMessage) return false;\n\tif (\n\t\tisUsageLimitedGoalInterruption(assistant) ||\n\t\tNON_RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage)\n\t) {\n\t\treturn false;\n\t}\n\treturn (\n\t\tisGoalContextOverflow(assistant) ||\n\t\tisRetryableAssistantError(toPiAssistantMessage(assistant)) ||\n\t\tRETRYABLE_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(assistant.errorMessage ?? \"\"))\n\t);\n}\n\nexport function isGoalContextOverflow(assistant: AssistantMessageLike) {\n\treturn isContextOverflow(toPiAssistantMessage(assistant));\n}\n\nexport function findFinalAssistantMessage(messages: unknown[]): AssistantMessageLike | undefined {\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index];\n\t\tif (!message || typeof message !== \"object\") continue;\n\t\tconst candidate = message as Record<string, unknown>;\n\t\tif (candidate.role !== \"assistant\") continue;\n\t\tconst assistant: AssistantMessageLike = {\n\t\t\trole: \"assistant\",\n\t\t\tstopReason: isAgentStopReason(candidate.stopReason) ? candidate.stopReason : undefined,\n\t\t\terrorMessage: typeof candidate.errorMessage === \"string\" ? candidate.errorMessage : undefined,\n\t\t};\n\t\tif (Array.isArray(candidate.content)) {\n\t\t\tassistant.content = candidate.content as PiAssistantMessage[\"content\"];\n\t\t}\n\t\tif (typeof candidate.api === \"string\") assistant.api = candidate.api;\n\t\tif (typeof candidate.provider === \"string\") assistant.provider = candidate.provider;\n\t\tif (typeof candidate.model === \"string\") assistant.model = candidate.model;\n\t\tif (typeof candidate.timestamp === \"number\") assistant.timestamp = candidate.timestamp;\n\t\tconst usage = normalizeUsage(candidate.usage);\n\t\tif (usage) assistant.usage = usage;\n\t\treturn assistant;\n\t}\n\treturn undefined;\n}\n\nfunction toPiAssistantMessage(assistant: AssistantMessageLike): PiAssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: assistant.content ?? [],\n\t\tapi: assistant.api ?? \"openai-responses\",\n\t\tprovider: assistant.provider ?? \"unknown\",\n\t\tmodel: assistant.model ?? \"unknown\",\n\t\tusage: assistant.usage ?? zeroUsage(),\n\t\tstopReason: assistant.stopReason ?? \"error\",\n\t\terrorMessage: assistant.errorMessage,\n\t\ttimestamp: assistant.timestamp ?? Date.now(),\n\t};\n}\n\nfunction zeroUsage(): Usage {\n\treturn {\n\t\tinput: 0,\n\t\toutput: 0,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\ttotalTokens: 0,\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t};\n}\n\nfunction isAgentStopReason(value: unknown): value is AgentStopReason {\n\treturn [\"stop\", \"length\", \"toolUse\", \"error\", \"aborted\"].includes(String(value));\n}\n\nfunction normalizeUsage(value: unknown): Usage | undefined {\n\tif (!value || typeof value !== \"object\") return undefined;\n\tconst usage = value as Partial<Usage>;\n\tif (typeof usage.input !== \"number\" || typeof usage.output !== \"number\") return undefined;\n\treturn {\n\t\tinput: nonNegativeFiniteNumber(usage.input),\n\t\toutput: nonNegativeFiniteNumber(usage.output),\n\t\tcacheRead: nonNegativeFiniteNumber(usage.cacheRead),\n\t\tcacheWrite: nonNegativeFiniteNumber(usage.cacheWrite),\n\t\ttotalTokens: assistantUsageTokens(usage),\n\t\tcost: {\n\t\t\tinput: usage.cost?.input ?? 0,\n\t\t\toutput: usage.cost?.output ?? 0,\n\t\t\tcacheRead: usage.cost?.cacheRead ?? 0,\n\t\t\tcacheWrite: usage.cost?.cacheWrite ?? 0,\n\t\t\ttotal: usage.cost?.total ?? 0,\n\t\t},\n\t};\n}\n", "import { randomUUID } from \"node:crypto\";\nimport { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\nimport { getAgentDir } from \"@earendil-works/pi-coding-agent\";\n\nexport const GOAL_SETTINGS_FILE = \"pi-goal.json\";\nexport const GOAL_TOOL_VISIBILITIES = [\"always\", \"after-first-goal\"] as const;\n\nexport type GoalToolVisibility = (typeof GOAL_TOOL_VISIBILITIES)[number];\nexport type ContinuationLimit = number | null;\n\nexport interface GoalSettings {\n\ttoolVisibility: GoalToolVisibility;\n\trpc: {\n\t\tenabled: boolean;\n\t};\n\tcontinuationLimits: {\n\t\tautomaticTurns: ContinuationLimit;\n\t\tnoProgressTurns: ContinuationLimit;\n\t};\n}\n\nexport const DEFAULT_GOAL_SETTINGS: GoalSettings = {\n\ttoolVisibility: \"after-first-goal\",\n\trpc: { enabled: false },\n\tcontinuationLimits: { automaticTurns: 25, noProgressTurns: 3 },\n};\n\nexport type GoalSettingsLoadResult =\n\t| { kind: \"missing\"; legacyExperimentalGoals: false }\n\t| { kind: \"invalid\"; reason: string }\n\t| { kind: \"loaded\"; settings: GoalSettings; legacyExperimentalGoals: boolean };\n\nexport type GoalSettingsLoadIssue = Extract<GoalSettingsLoadResult, { kind: \"invalid\" }>;\n\ninterface GoalSettingsSaveFileSystem {\n\tmkdirSync: typeof mkdirSync;\n\twriteFileSync: typeof writeFileSync;\n\trenameSync: typeof renameSync;\n\trmSync: typeof rmSync;\n}\n\nexport function normalizeGoalSettings(value: unknown): GoalSettings | undefined {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return undefined;\n\tconst toolVisibility = Object.hasOwn(value, \"toolVisibility\")\n\t\t? Reflect.get(value, \"toolVisibility\")\n\t\t: DEFAULT_GOAL_SETTINGS.toolVisibility;\n\tif (!GOAL_TOOL_VISIBILITIES.includes(toolVisibility as GoalToolVisibility)) return undefined;\n\n\tconst rpcValue = Object.hasOwn(value, \"rpc\") ? Reflect.get(value, \"rpc\") : undefined;\n\tif (\n\t\trpcValue !== undefined &&\n\t\t(typeof rpcValue !== \"object\" || rpcValue === null || Array.isArray(rpcValue))\n\t) {\n\t\treturn undefined;\n\t}\n\tconst rpcEnabled =\n\t\trpcValue && Object.hasOwn(rpcValue, \"enabled\")\n\t\t\t? Reflect.get(rpcValue, \"enabled\")\n\t\t\t: DEFAULT_GOAL_SETTINGS.rpc.enabled;\n\tif (typeof rpcEnabled !== \"boolean\") return undefined;\n\n\tconst continuationLimitsValue = Object.hasOwn(value, \"continuationLimits\")\n\t\t? Reflect.get(value, \"continuationLimits\")\n\t\t: undefined;\n\tif (\n\t\tcontinuationLimitsValue !== undefined &&\n\t\t(typeof continuationLimitsValue !== \"object\" ||\n\t\t\tcontinuationLimitsValue === null ||\n\t\t\tArray.isArray(continuationLimitsValue))\n\t) {\n\t\treturn undefined;\n\t}\n\tconst automaticTurns = continuationLimitsValue\n\t\t? normalizeContinuationLimit(\n\t\t\t\tReflect.get(continuationLimitsValue, \"automaticTurns\"),\n\t\t\t\tDEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns,\n\t\t\t)\n\t\t: DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns;\n\tconst noProgressTurns = continuationLimitsValue\n\t\t? normalizeContinuationLimit(\n\t\t\t\tReflect.get(continuationLimitsValue, \"noProgressTurns\"),\n\t\t\t\tDEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns,\n\t\t\t)\n\t\t: DEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns;\n\tif (automaticTurns === undefined || noProgressTurns === undefined) return undefined;\n\n\treturn {\n\t\ttoolVisibility: toolVisibility as GoalToolVisibility,\n\t\trpc: { enabled: rpcEnabled },\n\t\tcontinuationLimits: { automaticTurns, noProgressTurns },\n\t};\n}\n\nfunction normalizeContinuationLimit(\n\tvalue: unknown,\n\tfallback: ContinuationLimit,\n): ContinuationLimit | undefined {\n\tif (value === undefined) return fallback;\n\tif (value === null) return null;\n\treturn typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 ? value : undefined;\n}\n\nexport function saveGoalSettings(\n\tsettings: GoalSettings,\n\tsettingsPath = join(getAgentDir(), GOAL_SETTINGS_FILE),\n\toverrides: Partial<GoalSettingsSaveFileSystem> = {},\n) {\n\tconst normalized = normalizeGoalSettings(settings);\n\tif (!normalized) throw new Error(\"Refusing to save invalid pi-goal settings.\");\n\n\tlet raw: Record<string, unknown> = {};\n\ttry {\n\t\tconst contents = readFileSync(settingsPath, \"utf8\");\n\t\tconst parsed = JSON.parse(contents) as unknown;\n\t\tif (!normalizeGoalSettings(parsed)) {\n\t\t\tthrow new Error(`${settingsPath}: invalid settings shape`);\n\t\t}\n\t\traw = ownRecord(parsed) ?? {};\n\t} catch (error) {\n\t\tif (!isNodeError(error) || error.code !== \"ENOENT\") {\n\t\t\tthrow new Error(`Cannot save invalid settings file: ${formatError(error)}`);\n\t\t}\n\t}\n\n\tconst rpc = ownRecord(raw.rpc) ?? {};\n\tconst continuationLimits = ownRecord(raw.continuationLimits) ?? {};\n\tconst document = `${JSON.stringify(\n\t\t{\n\t\t\t...raw,\n\t\t\ttoolVisibility: normalized.toolVisibility,\n\t\t\trpc: { ...rpc, enabled: normalized.rpc.enabled },\n\t\t\tcontinuationLimits: {\n\t\t\t\t...continuationLimits,\n\t\t\t\tautomaticTurns: normalized.continuationLimits.automaticTurns,\n\t\t\t\tnoProgressTurns: normalized.continuationLimits.noProgressTurns,\n\t\t\t},\n\t\t},\n\t\tnull,\n\t\t2,\n\t)}\\n`;\n\tconst fs = { mkdirSync, writeFileSync, renameSync, rmSync, ...overrides };\n\tconst temporaryPath = join(\n\t\tdirname(settingsPath),\n\t\t`.${basename(settingsPath)}.${randomUUID()}.tmp`,\n\t);\n\ttry {\n\t\tfs.mkdirSync(dirname(settingsPath), { recursive: true });\n\t\tfs.writeFileSync(temporaryPath, document, { encoding: \"utf8\", flag: \"wx\" });\n\t\tfs.renameSync(temporaryPath, settingsPath);\n\t} finally {\n\t\ttry {\n\t\t\tfs.rmSync(temporaryPath, { force: true });\n\t\t} catch {\n\t\t\t// Best-effort cleanup must not replace the save result.\n\t\t}\n\t}\n}\n\nexport function readGoalSettings(\n\tsettingsPath = join(getAgentDir(), GOAL_SETTINGS_FILE),\n): GoalSettingsLoadResult {\n\tlet contents: string;\n\ttry {\n\t\tcontents = readFileSync(settingsPath, \"utf8\");\n\t} catch (error: unknown) {\n\t\tif (isNodeError(error) && error.code === \"ENOENT\") {\n\t\t\treturn { kind: \"missing\", legacyExperimentalGoals: false };\n\t\t}\n\t\treturn { kind: \"invalid\", reason: `${settingsPath}: ${formatError(error)}` };\n\t}\n\n\ttry {\n\t\tconst parsed = JSON.parse(contents) as unknown;\n\t\tconst settings = normalizeGoalSettings(parsed);\n\t\treturn settings\n\t\t\t? { kind: \"loaded\", settings, legacyExperimentalGoals: hasLegacyExperimentalGoals(parsed) }\n\t\t\t: { kind: \"invalid\", reason: `${settingsPath}: invalid settings shape` };\n\t} catch (error: unknown) {\n\t\treturn { kind: \"invalid\", reason: `${settingsPath}: ${formatError(error)}` };\n\t}\n}\n\nfunction hasLegacyExperimentalGoals(value: unknown) {\n\tconst experimental = ownRecord(ownRecord(value)?.experimental);\n\treturn experimental?.goals === true;\n}\n\nfunction ownRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn value && typeof value === \"object\" && !Array.isArray(value)\n\t\t? (value as Record<string, unknown>)\n\t\t: undefined;\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n\treturn error instanceof Error && \"code\" in error;\n}\n\nfunction formatError(error: unknown) {\n\treturn error instanceof Error ? error.message : String(error);\n}\n"],
5
- "mappings": ";;;;AAoBO,SAAS,yBACf,MACA,KACA,eACC;AACD,QAAM,cAAc,wBAAwB,KAAK,eAAe;AAChE,QAAM,YAAY,KAAK;AACvB,MAAI,OAAO,cAAc,YAAY,OAAO,SAAS,SAAS,GAAG;AAChE,SAAK,kBAAkB,cAAc,KAAK,IAAI,GAAG,MAAM,SAAS,IAAI;AAAA,EACrE,OAAO;AACN,SAAK,kBAAkB;AAAA,EACxB;AACA,OAAK,kBAAkB,gBAAgB,MAAM;AAC9C;AAEO,SAAS,gBACf,MACA,KACA,gBAAgB,KAAK,WAAW,UAC/B;AACD,QAAM,MAAM,KAAK,IAAI;AACrB,QAAM,iBAAiB,wBAAwB,KAAK,cAAc;AAClE,OAAK,iBAAiB;AACtB,OAAK,aAAa,KAAK,IAAI,GAAG,kBAAkB,GAAG,IAAI,cAAc;AACrE,2BAAyB,MAAM,KAAK,aAAa;AACjD,OAAK,YAAY;AAClB;AAEO,SAAS,eAAe,SAAiB;AAC/C,QAAM,eAAe,KAAK,IAAI,GAAG,KAAK,MAAM,wBAAwB,OAAO,CAAC,CAAC;AAC7E,MAAI,eAAe,GAAI,QAAO,GAAG,YAAY;AAC7C,QAAM,UAAU,KAAK,MAAM,eAAe,EAAE;AAC5C,MAAI,UAAU,GAAI,QAAO,GAAG,OAAO;AACnC,QAAM,QAAQ,KAAK,MAAM,UAAU,EAAE;AACrC,SAAO,GAAG,KAAK,IAAI,UAAU,EAAE;AAChC;AAEO,SAAS,iBAAiB,OAAe;AAC/C,MAAI,QAAQ,IAAO,QAAO,GAAG,KAAK;AAClC,MAAI,QAAQ,KAAW;AACtB,WAAO,GAAG,OA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,WAAW,QAAQ,GAAG,YAAY,KAAKA,aAAY,KAAK,CAAC,GAAG;AAAA,EAC5E;AACD;AAEA,SAAS,2BAA2B,OAAgB;AACnD,QAAM,eAAe,UAAU,UAAU,KAAK,GAAG,YAAY;AAC7D,SAAO,cAAc,UAAU;AAChC;AAEA,SAAS,UAAU,OAAqD;AACvE,SAAO,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IAC7D,QACD;AACJ;AAEA,SAAS,YAAY,OAAgD;AACpE,SAAO,iBAAiB,SAAS,UAAU;AAC5C;AAEA,SAASA,aAAY,OAAgB;AACpC,SAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC7D;",
4
+ "sourcesContent": ["import type { Usage } from \"@earendil-works/pi-ai\";\n\nexport interface GoalAccountingState {\n\tstatus: string;\n\tbaselineTokens: number;\n\ttokensUsed: number;\n\ttimeUsedSeconds: number;\n\tactiveStartedAt?: number;\n\tupdatedAt: number;\n}\n\ninterface AssistantUsageEntryLike {\n\ttype?: unknown;\n\tmessage?: unknown;\n}\n\ninterface UsageContext {\n\tsessionManager?: unknown;\n}\n\nexport function checkpointGoalActiveTime(\n\tgoal: GoalAccountingState,\n\tnow: number,\n\tcontinueClock: boolean,\n) {\n\tconst accumulated = nonNegativeFiniteNumber(goal.timeUsedSeconds);\n\tconst startedAt = goal.activeStartedAt;\n\tif (typeof startedAt === \"number\" && Number.isFinite(startedAt)) {\n\t\tgoal.timeUsedSeconds = accumulated + Math.max(0, now - startedAt) / 1000;\n\t} else {\n\t\tgoal.timeUsedSeconds = accumulated;\n\t}\n\tgoal.activeStartedAt = continueClock ? now : undefined;\n}\n\nexport function updateGoalUsage(\n\tgoal: GoalAccountingState,\n\tctx: UsageContext,\n\tcontinueClock = goal.status === \"active\",\n) {\n\tconst now = Date.now();\n\tconst baselineTokens = nonNegativeFiniteNumber(goal.baselineTokens);\n\tgoal.baselineTokens = baselineTokens;\n\tgoal.tokensUsed = Math.max(0, currentTokenTotal(ctx) - baselineTokens);\n\tcheckpointGoalActiveTime(goal, now, continueClock);\n\tgoal.updatedAt = now;\n}\n\nexport function formatDuration(seconds: number) {\n\tconst wholeSeconds = Math.max(0, Math.floor(nonNegativeFiniteNumber(seconds)));\n\tif (wholeSeconds < 60) return `${wholeSeconds}s`;\n\tconst minutes = Math.floor(wholeSeconds / 60);\n\tif (minutes < 60) return `${minutes}m`;\n\tconst hours = Math.floor(minutes / 60);\n\treturn `${hours}h${minutes % 60}m`;\n}\n\nexport function formatTokenCount(value: number) {\n\tif (value < 1_000) return `${value}`;\n\tif (value < 1_000_000) {\n\t\treturn `${Number.isInteger(value / 1_000) ? value / 1_000 : (value / 1_000).toFixed(1)}k`;\n\t}\n\treturn `${Number.isInteger(value / 1_000_000) ? value / 1_000_000 : (value / 1_000_000).toFixed(1)}m`;\n}\n\nexport function isNonNegativeFiniteNumber(value: unknown): value is number {\n\treturn typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n}\n\nexport function nonNegativeFiniteNumber(value: unknown) {\n\treturn isNonNegativeFiniteNumber(value) ? value : 0;\n}\n\nexport function normalizeTokenBudget(value: unknown) {\n\treturn typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 ? value : undefined;\n}\n\nexport function assistantUsageTokens(value: unknown) {\n\tif (!value || typeof value !== \"object\") return 0;\n\tconst usage = value as Partial<Usage>;\n\tif (isNonNegativeFiniteNumber(usage.totalTokens)) return usage.totalTokens;\n\treturn Math.min(\n\t\tNumber.MAX_SAFE_INTEGER,\n\t\tnonNegativeFiniteNumber(usage.input) +\n\t\t\tnonNegativeFiniteNumber(usage.output) +\n\t\t\tnonNegativeFiniteNumber(usage.cacheRead) +\n\t\t\tnonNegativeFiniteNumber(usage.cacheWrite),\n\t);\n}\n\nexport function cumulativeAssistantTokens(entries: unknown[]) {\n\tlet total = 0;\n\tfor (const entry of entries) {\n\t\tconst candidate = entry as AssistantUsageEntryLike;\n\t\tif (candidate?.type !== \"message\") continue;\n\t\tconst message = candidate.message as { role?: unknown; usage?: unknown } | undefined;\n\t\tif (message?.role !== \"assistant\") continue;\n\t\ttotal = Math.min(Number.MAX_SAFE_INTEGER, total + assistantUsageTokens(message.usage));\n\t}\n\treturn total;\n}\n\nexport function currentTokenTotal(ctx: UsageContext): number {\n\tconst sessionManager = ctx.sessionManager as { getBranch?: () => unknown[] } | undefined;\n\treturn cumulativeAssistantTokens(sessionManager?.getBranch?.() ?? []);\n}\n", "import {\n\tisContextOverflow,\n\tisRetryableAssistantError,\n\ttype AssistantMessage as PiAssistantMessage,\n\ttype Usage,\n} from \"@earendil-works/pi-ai\";\nimport { stripTerminalSequences } from \"@earendil-works/pi-tui\";\nimport { assistantUsageTokens, nonNegativeFiniteNumber } from \"./accounting.js\";\n\nexport type AgentStopReason = \"stop\" | \"length\" | \"toolUse\" | \"error\" | \"aborted\";\n\nexport interface AssistantMessageLike {\n\trole: \"assistant\";\n\tstopReason?: AgentStopReason;\n\terrorMessage?: string;\n\tcontent?: PiAssistantMessage[\"content\"];\n\tapi?: PiAssistantMessage[\"api\"];\n\tprovider?: PiAssistantMessage[\"provider\"];\n\tmodel?: string;\n\tusage?: Usage;\n\ttimestamp?: number;\n}\n\nconst USAGE_LIMIT_GOAL_ERROR_PATTERNS = [\n\t/usage[_\\s-]*(?:limit|cap)|chatgpt.{0,32}usage/i,\n\t/quota.{0,32}(?:reached|exceeded|exhausted|depleted)|(?:reached|exceeded|exhausted|depleted).{0,32}quota/i,\n\t/insufficient[_\\s-]*(?:quota|credits?)|out of credits|out of budget|available balance|payment required/i,\n\t/(?:credit|balance).{0,32}(?:low|exhausted|depleted)|billing/i,\n] as const;\nconst NON_RETRYABLE_GOAL_ERROR_RE =\n\t/multi-auth rotation failed|credentials tried|unauthori[sz]ed|invalid api key/i;\nconst RETRYABLE_GOAL_ERROR_PATTERNS = [\n\t/overloaded|rate.?limit|too many requests|\\b(?:429|500|502|503|504)\\b|service.?unavailable|server.?error|internal.?error/i,\n\t/provider.?returned.?error|you can retry your request|try your request again|please retry your request/i,\n\t/network.?error|connection.?(?:error|refused|lost)|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up/i,\n\t/timed? out|timeout|terminated|websocket.?(?:closed|error)|ended without|stream ended before message_stop|http2 request did not get a response|retry delay/i,\n\t/context[_\\s-]*length[_\\s-]*exceeded|input exceeds the context window/i,\n] as const;\n\nexport function safeTerminalText(value: string) {\n\treturn [...stripTerminalSequences(value)]\n\t\t.map((character) => {\n\t\t\tconst codePoint = character.codePointAt(0) ?? 0;\n\t\t\tif (character === \"\\n\") return character;\n\t\t\treturn codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? \" \" : character;\n\t\t})\n\t\t.join(\"\")\n\t\t.trim();\n}\n\nexport function safeGoalMenuText(value: string, maxCharacters = 120) {\n\tconst sanitized = safeTerminalText(value).replace(/\\s+/gu, \" \").trim();\n\tconst characters = [...sanitized];\n\treturn characters.length <= maxCharacters\n\t\t? sanitized\n\t\t: `${characters.slice(0, maxCharacters).join(\"\")}\u2026`;\n}\n\nexport function notifyTerminal(\n\tui: { notify: (message: string, level?: \"info\" | \"warning\" | \"error\") => void },\n\tmessage: string,\n\tlevel?: \"info\" | \"warning\" | \"error\",\n) {\n\tui.notify(safeTerminalText(message), level);\n}\n\nexport function formatError(error: unknown) {\n\treturn truncateNotification(error instanceof Error ? error.message : String(error));\n}\n\nexport function truncateNotification(value: string) {\n\tconst safe = [...safeTerminalText(value)];\n\treturn safe.length > 160 ? `${safe.slice(0, 157).join(\"\")}...` : safe.join(\"\");\n}\n\nexport function isUsageLimitedGoalInterruption(assistant: AssistantMessageLike) {\n\tconst errorMessage = assistant.errorMessage;\n\treturn (\n\t\tassistant.stopReason === \"error\" &&\n\t\ttypeof errorMessage === \"string\" &&\n\t\tUSAGE_LIMIT_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(errorMessage))\n\t);\n}\n\nexport function isRetryableGoalInterruption(assistant: AssistantMessageLike) {\n\tif (assistant.stopReason !== \"error\" || !assistant.errorMessage) return false;\n\tif (\n\t\tisUsageLimitedGoalInterruption(assistant) ||\n\t\tNON_RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage)\n\t) {\n\t\treturn false;\n\t}\n\treturn (\n\t\tisGoalContextOverflow(assistant) ||\n\t\tisRetryableAssistantError(toPiAssistantMessage(assistant)) ||\n\t\tRETRYABLE_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(assistant.errorMessage ?? \"\"))\n\t);\n}\n\nexport function isGoalContextOverflow(assistant: AssistantMessageLike) {\n\treturn isContextOverflow(toPiAssistantMessage(assistant));\n}\n\nexport function findFinalAssistantMessage(messages: unknown[]): AssistantMessageLike | undefined {\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index];\n\t\tif (!message || typeof message !== \"object\") continue;\n\t\tconst candidate = message as Record<string, unknown>;\n\t\tif (candidate.role !== \"assistant\") continue;\n\t\tconst assistant: AssistantMessageLike = {\n\t\t\trole: \"assistant\",\n\t\t\tstopReason: isAgentStopReason(candidate.stopReason) ? candidate.stopReason : undefined,\n\t\t\terrorMessage: typeof candidate.errorMessage === \"string\" ? candidate.errorMessage : undefined,\n\t\t};\n\t\tif (Array.isArray(candidate.content)) {\n\t\t\tassistant.content = candidate.content as PiAssistantMessage[\"content\"];\n\t\t}\n\t\tif (typeof candidate.api === \"string\") assistant.api = candidate.api;\n\t\tif (typeof candidate.provider === \"string\") assistant.provider = candidate.provider;\n\t\tif (typeof candidate.model === \"string\") assistant.model = candidate.model;\n\t\tif (typeof candidate.timestamp === \"number\") assistant.timestamp = candidate.timestamp;\n\t\tconst usage = normalizeUsage(candidate.usage);\n\t\tif (usage) assistant.usage = usage;\n\t\treturn assistant;\n\t}\n\treturn undefined;\n}\n\nfunction toPiAssistantMessage(assistant: AssistantMessageLike): PiAssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: assistant.content ?? [],\n\t\tapi: assistant.api ?? \"openai-responses\",\n\t\tprovider: assistant.provider ?? \"unknown\",\n\t\tmodel: assistant.model ?? \"unknown\",\n\t\tusage: assistant.usage ?? zeroUsage(),\n\t\tstopReason: assistant.stopReason ?? \"error\",\n\t\terrorMessage: assistant.errorMessage,\n\t\ttimestamp: assistant.timestamp ?? Date.now(),\n\t};\n}\n\nfunction zeroUsage(): Usage {\n\treturn {\n\t\tinput: 0,\n\t\toutput: 0,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\ttotalTokens: 0,\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t};\n}\n\nfunction isAgentStopReason(value: unknown): value is AgentStopReason {\n\treturn [\"stop\", \"length\", \"toolUse\", \"error\", \"aborted\"].includes(String(value));\n}\n\nfunction normalizeUsage(value: unknown): Usage | undefined {\n\tif (!value || typeof value !== \"object\") return undefined;\n\tconst usage = value as Partial<Usage>;\n\tif (typeof usage.input !== \"number\" || typeof usage.output !== \"number\") return undefined;\n\treturn {\n\t\tinput: nonNegativeFiniteNumber(usage.input),\n\t\toutput: nonNegativeFiniteNumber(usage.output),\n\t\tcacheRead: nonNegativeFiniteNumber(usage.cacheRead),\n\t\tcacheWrite: nonNegativeFiniteNumber(usage.cacheWrite),\n\t\ttotalTokens: assistantUsageTokens(usage),\n\t\tcost: {\n\t\t\tinput: usage.cost?.input ?? 0,\n\t\t\toutput: usage.cost?.output ?? 0,\n\t\t\tcacheRead: usage.cost?.cacheRead ?? 0,\n\t\t\tcacheWrite: usage.cost?.cacheWrite ?? 0,\n\t\t\ttotal: usage.cost?.total ?? 0,\n\t\t},\n\t};\n}\n", "import { randomUUID } from \"node:crypto\";\nimport { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\nimport { getAgentDir } from \"@earendil-works/pi-coding-agent\";\n\nexport const GOAL_SETTINGS_FILE = \"pi-goal.json\";\n\nexport type ContinuationLimit = number | null;\n\nexport interface GoalSettings {\n\trpc: {\n\t\tenabled: boolean;\n\t};\n\tcontinuationLimits: {\n\t\tautomaticTurns: ContinuationLimit;\n\t\tnoProgressTurns: ContinuationLimit;\n\t};\n}\n\nexport const DEFAULT_GOAL_SETTINGS: GoalSettings = {\n\trpc: { enabled: false },\n\tcontinuationLimits: { automaticTurns: 25, noProgressTurns: 3 },\n};\n\nexport type GoalSettingsLoadResult =\n\t| { kind: \"missing\"; legacyExperimentalGoals: false }\n\t| { kind: \"invalid\"; reason: string }\n\t| { kind: \"loaded\"; settings: GoalSettings; legacyExperimentalGoals: boolean };\n\nexport type GoalSettingsLoadIssue = Extract<GoalSettingsLoadResult, { kind: \"invalid\" }>;\n\ninterface GoalSettingsSaveFileSystem {\n\tmkdirSync: typeof mkdirSync;\n\twriteFileSync: typeof writeFileSync;\n\trenameSync: typeof renameSync;\n\trmSync: typeof rmSync;\n}\n\nexport function normalizeGoalSettings(value: unknown): GoalSettings | undefined {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return undefined;\n\n\tconst rpcValue = Object.hasOwn(value, \"rpc\") ? Reflect.get(value, \"rpc\") : undefined;\n\tif (\n\t\trpcValue !== undefined &&\n\t\t(typeof rpcValue !== \"object\" || rpcValue === null || Array.isArray(rpcValue))\n\t) {\n\t\treturn undefined;\n\t}\n\tconst rpcEnabled =\n\t\trpcValue && Object.hasOwn(rpcValue, \"enabled\")\n\t\t\t? Reflect.get(rpcValue, \"enabled\")\n\t\t\t: DEFAULT_GOAL_SETTINGS.rpc.enabled;\n\tif (typeof rpcEnabled !== \"boolean\") return undefined;\n\n\tconst continuationLimitsValue = Object.hasOwn(value, \"continuationLimits\")\n\t\t? Reflect.get(value, \"continuationLimits\")\n\t\t: undefined;\n\tif (\n\t\tcontinuationLimitsValue !== undefined &&\n\t\t(typeof continuationLimitsValue !== \"object\" ||\n\t\t\tcontinuationLimitsValue === null ||\n\t\t\tArray.isArray(continuationLimitsValue))\n\t) {\n\t\treturn undefined;\n\t}\n\tconst automaticTurns = continuationLimitsValue\n\t\t? normalizeContinuationLimit(\n\t\t\t\tReflect.get(continuationLimitsValue, \"automaticTurns\"),\n\t\t\t\tDEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns,\n\t\t\t)\n\t\t: DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns;\n\tconst noProgressTurns = continuationLimitsValue\n\t\t? normalizeContinuationLimit(\n\t\t\t\tReflect.get(continuationLimitsValue, \"noProgressTurns\"),\n\t\t\t\tDEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns,\n\t\t\t)\n\t\t: DEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns;\n\tif (automaticTurns === undefined || noProgressTurns === undefined) return undefined;\n\n\treturn {\n\t\trpc: { enabled: rpcEnabled },\n\t\tcontinuationLimits: { automaticTurns, noProgressTurns },\n\t};\n}\n\nfunction normalizeContinuationLimit(\n\tvalue: unknown,\n\tfallback: ContinuationLimit,\n): ContinuationLimit | undefined {\n\tif (value === undefined) return fallback;\n\tif (value === null) return null;\n\treturn typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 ? value : undefined;\n}\n\nexport function saveGoalSettings(\n\tsettings: GoalSettings,\n\tsettingsPath = join(getAgentDir(), GOAL_SETTINGS_FILE),\n\toverrides: Partial<GoalSettingsSaveFileSystem> = {},\n) {\n\tconst normalized = normalizeGoalSettings(settings);\n\tif (!normalized) throw new Error(\"Refusing to save invalid pi-goal settings.\");\n\n\tlet raw: Record<string, unknown> = {};\n\ttry {\n\t\tconst contents = readFileSync(settingsPath, \"utf8\");\n\t\tconst parsed = JSON.parse(contents) as unknown;\n\t\tif (!normalizeGoalSettings(parsed)) {\n\t\t\tthrow new Error(`${settingsPath}: invalid settings shape`);\n\t\t}\n\t\traw = ownRecord(parsed) ?? {};\n\t} catch (error) {\n\t\tif (!isNodeError(error) || error.code !== \"ENOENT\") {\n\t\t\tthrow new Error(`Cannot save invalid settings file: ${formatError(error)}`);\n\t\t}\n\t}\n\n\tconst rpc = ownRecord(raw.rpc) ?? {};\n\tconst continuationLimits = ownRecord(raw.continuationLimits) ?? {};\n\tconst document = `${JSON.stringify(\n\t\t{\n\t\t\t...raw,\n\t\t\trpc: { ...rpc, enabled: normalized.rpc.enabled },\n\t\t\tcontinuationLimits: {\n\t\t\t\t...continuationLimits,\n\t\t\t\tautomaticTurns: normalized.continuationLimits.automaticTurns,\n\t\t\t\tnoProgressTurns: normalized.continuationLimits.noProgressTurns,\n\t\t\t},\n\t\t},\n\t\tnull,\n\t\t2,\n\t)}\\n`;\n\tconst fs = { mkdirSync, writeFileSync, renameSync, rmSync, ...overrides };\n\tconst temporaryPath = join(\n\t\tdirname(settingsPath),\n\t\t`.${basename(settingsPath)}.${randomUUID()}.tmp`,\n\t);\n\ttry {\n\t\tfs.mkdirSync(dirname(settingsPath), { recursive: true });\n\t\tfs.writeFileSync(temporaryPath, document, { encoding: \"utf8\", flag: \"wx\" });\n\t\tfs.renameSync(temporaryPath, settingsPath);\n\t} finally {\n\t\ttry {\n\t\t\tfs.rmSync(temporaryPath, { force: true });\n\t\t} catch {\n\t\t\t// Best-effort cleanup must not replace the save result.\n\t\t}\n\t}\n}\n\nexport function readGoalSettings(\n\tsettingsPath = join(getAgentDir(), GOAL_SETTINGS_FILE),\n): GoalSettingsLoadResult {\n\tlet contents: string;\n\ttry {\n\t\tcontents = readFileSync(settingsPath, \"utf8\");\n\t} catch (error: unknown) {\n\t\tif (isNodeError(error) && error.code === \"ENOENT\") {\n\t\t\treturn { kind: \"missing\", legacyExperimentalGoals: false };\n\t\t}\n\t\treturn { kind: \"invalid\", reason: `${settingsPath}: ${formatError(error)}` };\n\t}\n\n\ttry {\n\t\tconst parsed = JSON.parse(contents) as unknown;\n\t\tconst settings = normalizeGoalSettings(parsed);\n\t\treturn settings\n\t\t\t? { kind: \"loaded\", settings, legacyExperimentalGoals: hasLegacyExperimentalGoals(parsed) }\n\t\t\t: { kind: \"invalid\", reason: `${settingsPath}: invalid settings shape` };\n\t} catch (error: unknown) {\n\t\treturn { kind: \"invalid\", reason: `${settingsPath}: ${formatError(error)}` };\n\t}\n}\n\nfunction hasLegacyExperimentalGoals(value: unknown) {\n\tconst experimental = ownRecord(ownRecord(value)?.experimental);\n\treturn experimental?.goals === true;\n}\n\nfunction ownRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn value && typeof value === \"object\" && !Array.isArray(value)\n\t\t? (value as Record<string, unknown>)\n\t\t: undefined;\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n\treturn error instanceof Error && \"code\" in error;\n}\n\nfunction formatError(error: unknown) {\n\treturn error instanceof Error ? error.message : String(error);\n}\n"],
5
+ "mappings": ";;;;AAoBO,SAAS,yBACf,MACA,KACA,eACC;AACD,QAAM,cAAc,wBAAwB,KAAK,eAAe;AAChE,QAAM,YAAY,KAAK;AACvB,MAAI,OAAO,cAAc,YAAY,OAAO,SAAS,SAAS,GAAG;AAChE,SAAK,kBAAkB,cAAc,KAAK,IAAI,GAAG,MAAM,SAAS,IAAI;AAAA,EACrE,OAAO;AACN,SAAK,kBAAkB;AAAA,EACxB;AACA,OAAK,kBAAkB,gBAAgB,MAAM;AAC9C;AAEO,SAAS,gBACf,MACA,KACA,gBAAgB,KAAK,WAAW,UAC/B;AACD,QAAM,MAAM,KAAK,IAAI;AACrB,QAAM,iBAAiB,wBAAwB,KAAK,cAAc;AAClE,OAAK,iBAAiB;AACtB,OAAK,aAAa,KAAK,IAAI,GAAG,kBAAkB,GAAG,IAAI,cAAc;AACrE,2BAAyB,MAAM,KAAK,aAAa;AACjD,OAAK,YAAY;AAClB;AAEO,SAAS,eAAe,SAAiB;AAC/C,QAAM,eAAe,KAAK,IAAI,GAAG,KAAK,MAAM,wBAAwB,OAAO,CAAC,CAAC;AAC7E,MAAI,eAAe,GAAI,QAAO,GAAG,YAAY;AAC7C,QAAM,UAAU,KAAK,MAAM,eAAe,EAAE;AAC5C,MAAI,UAAU,GAAI,QAAO,GAAG,OAAO;AACnC,Q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