@narumitw/pi-goal 0.54.4 → 0.54.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +41 -166
  2. package/dist/chunks/{chunk-UQRRW4CY.js → chunk-6T3MHA45.js} +7 -6
  3. package/dist/chunks/chunk-6T3MHA45.js.map +7 -0
  4. package/dist/chunks/{chunk-QWIUWKRW.js → chunk-WLIH47XO.js} +57 -77
  5. package/dist/chunks/chunk-WLIH47XO.js.map +7 -0
  6. package/dist/chunks/{menu-WEFDREGC.js → menu-RGCRCQJK.js} +7 -22
  7. package/dist/chunks/menu-RGCRCQJK.js.map +7 -0
  8. package/dist/chunks/{settings-ui-MVYTTBHW.js → settings-ui-BAWNTINU.js} +6 -18
  9. package/dist/chunks/settings-ui-BAWNTINU.js.map +7 -0
  10. package/dist/index.ts +92 -126
  11. package/dist/index.ts.map +2 -2
  12. package/docs/managing-goals.md +47 -0
  13. package/docs/settings.md +91 -0
  14. package/package.json +55 -55
  15. package/src/accounting.ts +62 -66
  16. package/src/command-registration.ts +104 -102
  17. package/src/command.ts +101 -112
  18. package/src/commands.ts +465 -501
  19. package/src/errors.ts +127 -122
  20. package/src/goal-contract.ts +64 -64
  21. package/src/goal.ts +25 -25
  22. package/src/lifecycle.ts +615 -628
  23. package/src/markers.ts +6 -6
  24. package/src/menu.ts +565 -591
  25. package/src/persistence.ts +177 -192
  26. package/src/prompts.ts +53 -67
  27. package/src/run-protocol.ts +299 -325
  28. package/src/runtime.ts +1422 -1495
  29. package/src/safety.ts +51 -51
  30. package/src/settings-ui.ts +366 -393
  31. package/src/settings.ts +134 -147
  32. package/src/tool-policy.ts +6 -6
  33. package/src/tools.ts +360 -371
  34. package/src/wait.ts +47 -51
  35. package/src/workflow-mutex.ts +68 -68
  36. package/dist/chunks/chunk-QWIUWKRW.js.map +0 -7
  37. package/dist/chunks/chunk-UQRRW4CY.js.map +0 -7
  38. package/dist/chunks/menu-WEFDREGC.js.map +0 -7
  39. package/dist/chunks/settings-ui-MVYTTBHW.js.map +0 -7
package/README.md CHANGED
@@ -4,7 +4,6 @@
4
4
 
5
5
  Give Pi one session-scoped objective and let it continue after Pi becomes fully idle.
6
6
  Goal mode stops when work completes, pauses, waits for an external event, or reaches a safety limit.
7
-
8
7
  Explicit completion, blocker, and wait tools give each managed run a clear stopping reason.
9
8
 
10
9
  ## ✨ Features
@@ -54,88 +53,29 @@ Use the manager to review, pause, resume, edit, or clear the current goal.
54
53
 
55
54
  ## ⚙️ Settings
56
55
 
57
- Settings are optional.
58
- When `~/.pi/agent/pi-goal.json` is absent, pi-goal uses these built-in defaults without creating the file:
56
+ Use `/goal` → **Settings…** in TUI mode, or edit `<getAgentDir()>/pi-goal.json` (normally `~/.pi/agent/pi-goal.json`).
57
+ A missing file uses the defaults without creating it:
59
58
 
60
59
  ```json
61
60
  {
62
- "rpc": {
63
- "enabled": false
64
- },
65
61
  "continuationLimits": {
66
62
  "automaticTurns": 25,
67
63
  "noProgressTurns": 3
68
- }
64
+ },
65
+ "rpc": { "enabled": false }
69
66
  }
70
67
  ```
71
68
 
72
- Use `/goal` → **Settings…** in the TUI to create or update the file, or edit it directly.
73
- The Settings screen shows all three controls on one level.
74
- The two safety limits open separate choice screens:
75
-
76
- - **Automatic-work limit** shows the exact response limit or **Unlimited**.
77
- Choose **Set response limit…** to edit the current finite value (or the built-in default of 25 when switching from Unlimited), or choose **Unlimited…**.
78
- Unlimited requires confirmation that tool loops may continue consuming tokens and provider cost without a response-count cap.
79
- - **No-progress guard** shows **_N_ runs** or **Off**.
80
- Choose the default threshold, **Off**, or **Set threshold…** and enter a safe whole number greater than zero.
81
- - **Managed run RPC** controls whether trusted installed extensions may start and cancel managed Goal runs.
82
- It defaults to **Off** and controls cooperation, not extension permissions.
83
-
84
- Custom number inputs accept only positive safe integers.
85
- Choose **Unlimited** or **Off** explicitly instead of entering zero, a negative number, a decimal, or text.
86
- Interactive changes run in order, publish atomically, preserve unknown fields, and apply to the current runtime.
87
- A successful save updates the visible state immediately.
88
- A failed save restores the prior value and reports the settings path so it can be retried.
89
- Escape returns to the previous screen without reverting changes that were already saved.
90
-
91
- Pi-goal registers `goal_complete`, `goal_blocked`, and `goal_wait` once and keeps their schemas stable from startup.
92
- Visible Goal tools do not mean Goal mode is active, and only the latest effective active Goal contract authorizes their use.
93
- 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.
94
- The retired `toolVisibility` key is ignored and preserved as unknown data when another setting is saved.
95
-
96
- `experimental.goals` is a removed legacy setting.
97
- If it remains `true`, pi-goal accepts the settings file and ignores the old queue feature.
98
- Affected users see a warning that recommends `/goal edit` for an active objective or `/goal <objectives>` when no goal is active.
99
- Later settings saves preserve unknown legacy fields instead of deleting them.
100
-
101
- `rpc.enabled` accepts a boolean and defaults to `false`.
102
- When disabled, a valid managed-run start receives `RPC_DISABLED`; manual and restored Goals remain unchanged.
103
- A Settings-menu change applies immediately after its atomic save.
104
- Disabling rejects new starts but lets an already accepted run continue publishing its exact state and accept its exact cancellation until terminal, avoiding stranded work.
105
- Reload, replacement, and shutdown clear that in-memory ownership.
106
-
107
- `continuationLimits` controls the automatic-work safety guards:
108
-
109
- - `automaticTurns` accepts a positive safe integer or `null` and defaults to `25`.
110
- It counts every completed normal `turn_end` owned by automatically started Goal work, including model responses inside tool loops and matching Pi-owned retries.
111
- The user-triggered kickoff, resume, edit, and ordinary user runs are not charged.
112
- At the limit, the goal becomes `paused` with cause `continuation_limit` and pending continuation or recovery is cancelled.
113
- The current operation is aborted before a 26th normal response starts.
114
- Pi may invoke a provider adapter once more with an already-aborted signal to produce its synthetic terminal event; that event is not counted and cannot resume Goal work.
115
- Set this field explicitly to `null` to opt into Unlimited mode; existing explicit `null` values remain compatible.
116
- - `noProgressTurns` is a positive safe integer and defaults to `3`.
117
- At the end of an automatic run, pi-goal compares visible assistant text after Unicode normalization, lowercase conversion, control-character removal, and whitespace collapse.
118
- Thinking and tool blocks are excluded; empty and punctuation-only output are equivalent.
119
- Consecutive empty or identical tool-free outputs increment the repeat count.
120
- Different non-empty output starts a new run at one, and any attempted tool call resets it.
121
- Set this field to `null` to disable only this heuristic.
122
-
123
- Settings are reread at Pi startup, session replacement, and `/reload`.
124
- Direct file edits are not watched, while Goal-menu changes apply immediately.
125
- A missing file remains absent and uses the built-in defaults.
126
- The first successful settings change creates the file atomically; later saves preserve unknown fields.
127
-
128
- Omitted fields use the defaults above.
129
- Invalid or malformed existing settings are never overwritten; they produce a warning and fall back to all defaults.
130
- In the TUI, Goal Settings becomes a read-only summary that identifies the invalid file and tells you to fix it and run `/reload`.
131
-
132
- Plan mode or another restrictive policy may hide Goal tools.
133
- Pi-goal does not override that policy during restore or later turns.
134
- Activation fails when required terminal tools are unavailable, and an active goal pauses without automatic continuation if they disappear.
135
- A restrictive allowlist created before `goal_wait` existed can still run ordinary Goals with `goal_complete` and `goal_blocked`.
136
- The model cannot enter external waiting until that allowlist also includes `goal_wait`.
137
- The pause aborts a Goal-owned kickoff, resume, active edit, or automatic-continuation prompt.
138
- It does not cancel or stale-block unrelated user or extension turns, including startup follow-ups after a restrictive restore.
69
+ The automatic-work limit counts model responses in Goal-owned automatic work, including tool loops.
70
+ The no-progress guard pauses repeated tool-free output.
71
+ Choose **Unlimited** or **Off** explicitly to disable the corresponding guard; Unlimited requires confirmation and can continue consuming tokens and provider cost.
72
+ Neither these guards nor an optional token budget is a dollar-cost cap.
73
+
74
+ Menu saves apply immediately, run in order, preserve unknown fields, and publish atomically.
75
+ Manual edits apply at session start or `/reload`.
76
+ Invalid settings remain untouched, use defaults, and make the TUI Settings screen read-only until repaired and reloaded.
77
+
78
+ Read the [settings reference](./docs/settings.md) for exact counting rules, accepted values, managed-run RPC behavior, tool-policy restrictions, and legacy-setting recovery.
139
79
 
140
80
  ## 🔒 Security and privacy
141
81
 
@@ -178,61 +118,24 @@ Guaranteed coexistence with Plan mode requires `@narumitw/pi-plan-mode` `0.52.0`
178
118
 
179
119
  ## 💬 Commands
180
120
 
181
- ```text
182
- /goal
183
- /goal status
184
- /goal implement snake game
185
- /goal --tokens 100k fix the failing test and verify it
186
- /goal edit ship the smaller fix first
187
- /goal pause
188
- /goal resume
189
- /goal clear
190
- ```
191
-
192
- - In the TUI, `/goal` opens a standard state-aware manager.
193
- Its first action follows the current state: start when empty, pause when active, review a reached automatic-work limit, resume for other stopped states, or increase an exhausted token budget.
194
- Active and paused views show **Automatic work: _used_ of _limit_ responses** with the remaining count, or explicitly show **Unlimited**.
195
- A hard-cap pause opens **Review and continue…** and confirms that the objective, cumulative usage, and active time are preserved.
196
- Continuing resets the counter to zero and allows one more configured epoch.
197
- **Change automatic-work limit…** opens that setting while leaving the goal paused; Back and Escape make no change.
198
- **Start with token budget…** first offers `25k`, a suggested `100k`, `300k`, and **Set a custom budget…**, then collects the objective with the selected budget still visible.
199
- Custom input accepts examples such as `300000`, `300k`, `2.5k`, and `1.5m`; invalid input retains its draft for correction.
200
- Status, Settings, Help, invalid-settings guidance, Clear, and Close remain shallow, labeled routes.
201
- Arrow keys navigate, Enter selects or submits, Escape goes Back, and Ctrl+C closes the full flow.
202
- - In RPC mode, bare `/goal` and `/goal status` report the current summary through an observable notification without opening terminal UI.
203
- Pi exposes no extension-command output channel in print or JSON mode.
204
- Those routes return an explicit unsupported-mode error instead of treating stderr as status output.
205
- - Menu-driven Replace and Clear actions preview the exact affected goal and require confirmation.
206
- Existing direct routes remain immediate for compatibility and automation.
207
- - `/goal <goal_to_complete>` starts goal mode.
208
- If another unfinished goal exists, Pi asks for confirmation before replacing it with a new active goal and resetting its usage counters.
209
- Failed kickoff delivery clears a new goal or restores the exact prior Goal and tool-policy snapshot; a previously active or waiting Goal keeps its existing workflow ownership.
210
- - `/goal --tokens 100k <goal_to_complete>` starts or replaces goal mode with a token budget.
211
- `k` and `m` suffixes are accepted, for example `100k` or `1.5m`.
212
- - `/goal edit <goal_to_complete>` updates the existing goal objective without resetting usage counters.
213
- A successful active edit rotates the stale-turn guard and starts a fresh safety epoch.
214
- Paused, blocked, and usage-limited goals stay stopped and retain their safety state until resume.
215
- A budget-limited goal reactivates only when `edit --tokens` raises its budget above current usage.
216
- Failed prompt delivery restores the exact previous Goal, guard id, safety counters, cause, tool-policy snapshot, and active ownership when applicable.
217
- - `/goal pause` stops prompt injection and auto-continuation, aborts the current turn, and keeps the goal for later resume.
218
- Only active goals can be paused.
219
- - `/goal resume` resumes a paused, blocked, usage-limited, or budget-limited goal when its token budget allows it.
220
- When the queued resume prompt starts, pi-goal rotates the stale-turn guard id, resets the automatic-response and repeat safety epoch, and clears a safety-pause cause.
221
- The command reports the new finite epoch or explicit Unlimited state.
222
- Objective, cumulative usage, and elapsed time are preserved.
223
- If prompt delivery fails, the original stopped state, guard id, counters, fingerprint, and cause are restored.
224
- - `/goal clear` clears the current goal, status, pending continuation, inert legacy queue state, and legacy persisted state for the current working directory.
225
- It does not abort unrelated in-flight work.
226
-
227
- The experimental ordered-goal queue has been removed.
228
- Use `/goal edit <objective>` to reprioritize the active objective instead.
229
- For example, if `task b` is complete and `task c` is in progress, edit the objective to say: `task b is complete; do task a next; after task a, continue task c, then task d; do not redo task b unless verification shows it is incomplete.`
230
-
231
- Former queue command words such as `add`, `prioritize`, `drop-last`, `skip`, `push`, `unshift`, `pop`, and `shift` are ordinary objective text for unaffected users.
232
- If a session still has legacy queue settings or persisted queue state, those words show a migration warning instead of replacing the active Goal.
233
-
234
- Goal objectives are limited to 4,000 characters.
235
- Put longer instructions in a file and reference the file path from `/goal`.
121
+ | Command | Purpose |
122
+ | --- | --- |
123
+ | `/goal` | Manage the current goal in TUI; report its summary in RPC. |
124
+ | `/goal status` | Report the current goal and progress. |
125
+ | `/goal [--tokens <budget>] <objective>` | Start automatic work, confirming replacement of an unfinished goal. |
126
+ | `/goal edit [--tokens <budget>] <objective>` | Update the objective or budget without resetting cumulative usage. |
127
+ | `/goal pause` | Pause an active goal and abort its current turn, preserving progress. |
128
+ | `/goal resume` | Resume an eligible stopped goal or wake an active waiting goal. |
129
+ | `/goal clear` (alias: `stop`) | Immediately clear the goal and pending continuation, not unrelated in-flight work. |
130
+
131
+ All routes support TUI and RPC; bare `/goal` and `status` reject print and JSON modes, while direct mutation routes remain available.
132
+ Objectives are limited to 4,000 characters; reference a file for longer instructions.
133
+ `--tokens` must precede the objective and accepts positive amounts such as `100k` or `1.5m`.
134
+ `status`, `pause`, `resume`, and `clear`/`stop` reject trailing arguments; other text starts an objective.
135
+
136
+ Starting, editing an active goal, or resuming can trigger paid model work; [token budgets](#-token-budgets-and-elapsed-time) are not dollar-cost caps.
137
+ Direct Clear is immediate, while menu Clear requires confirmation.
138
+ See [Managing goals](./docs/managing-goals.md) for safety-epoch resets, failed-delivery recovery, budget-limited edits, and migration from removed queue commands.
236
139
 
237
140
  ## 🛠️ Tools
238
141
 
@@ -528,46 +431,18 @@ No compatibility aliases are registered.
528
431
 
529
432
  ## 🗂️ Package layout
530
433
 
531
- ```txt
434
+ ```text
532
435
  packages/pi-goal/
533
- ├── dist/ # Generated TypeScript runtime loaded by Jiti
534
- ├── scripts/
535
- │ └── build-runtime.mjs # Deterministic runtime builder and boundary validator
536
- ├── src/
537
- │ ├── index.ts # Pi package entrypoint
538
- │ ├── goal.ts # Order-explicit extension composition root
539
- │ ├── command-registration.ts # Lightweight slash-command adapter with lazy manager/settings UI
540
- │ ├── commands.ts # Per-factory user-command controller
541
- │ ├── tools.ts # Goal completion and blocker tool adapters
542
- │ ├── lifecycle.ts # Pi session, agent, tool, and compaction event adapter
543
- │ ├── goal-contract.ts # Deterministic post-compaction model contract
544
- │ ├── runtime.ts # Per-factory Goal state, transitions, prompts, and budgets
545
- │ ├── tool-policy.ts # Goal tool names and read-only availability checks
546
- │ ├── safety.ts # Output normalization and no-progress fingerprint state
547
- │ ├── wait.ts # External-wait validation and session timer ownership
548
- │ ├── errors.ts # Pi-aligned provider error and retry classification
549
- │ ├── markers.ts # Bounded Goal prompt marker parsing and formatting
550
- │ ├── run-protocol.ts # Default-off managed-run protocol and session ownership
551
- │ └── *.ts # Package-local parsing, settings, prompts, accounting, and persistence
552
- ├── test/
553
- ├── README.md
554
- ├── LICENSE
555
- ├── tsconfig.json
556
- └── package.json
557
- ```
558
-
559
- `index.ts` is the Pi entrypoint and forwards to `goal.ts`; the other source modules are internal.
560
- The package exposes its Pi extension through `package.json`:
561
-
562
- ```json
563
- {
564
- "pi": {
565
- "extensions": ["./dist/index.ts"]
566
- }
567
- }
436
+ ├── src/ # State, safety, waiting, settings, and protocol modules
437
+ │ ├── index.ts # Thin Pi entrypoint
438
+ │ └── goal.ts # Goal lifecycle, commands, and tools
439
+ ├── dist/ # Generated Jiti runtime
440
+ ├── scripts/build-runtime.mjs # Runtime builder
441
+ ├── docs/ # Published reference documentation
442
+ └── test/ # Behavior and lifecycle coverage
568
443
  ```
569
444
 
570
- The generated runtime is built from the authoritative `src/index.ts` graph and does not import back into `src`.
445
+ The generated runtime is built from `src/index.ts` and does not import back into `src`.
571
446
 
572
447
  ## 🔎 Keywords
573
448
 
@@ -86,7 +86,7 @@ var RETRYABLE_GOAL_ERROR_PATTERNS = [
86
86
  /overloaded|rate.?limit|too many requests|\b(?:429|500|502|503|504)\b|service.?unavailable|server.?error|internal.?error/i,
87
87
  /provider.?returned.?error|you can retry your request|try your request again|please retry your request/i,
88
88
  /network.?error|connection.?(?:error|refused|lost)|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up/i,
89
- /timed? out|timeout|terminated|websocket.?(?:closed|error)|ended without|stream ended before message_stop|http2 request did not get a response|retry delay/i,
89
+ /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,
90
90
  /context[_\s-]*length[_\s-]*exceeded|input exceeds the context window/i
91
91
  ];
92
92
  function safeTerminalText(value) {
@@ -104,6 +104,9 @@ function safeGoalMenuText(value, maxCharacters = 120) {
104
104
  function notifyTerminal(ui, message, level) {
105
105
  ui.notify(safeTerminalText(message), level);
106
106
  }
107
+ function isStaleContextError(error) {
108
+ return error instanceof Error && error.message.includes("This extension ctx is stale after session replacement or reload");
109
+ }
107
110
  function formatError(error) {
108
111
  return truncateNotification(error instanceof Error ? error.message : String(error));
109
112
  }
@@ -269,10 +272,7 @@ function saveGoalSettings(settings, settingsPath = join(getAgentDir(), GOAL_SETT
269
272
  )}
270
273
  `;
271
274
  const fs = { mkdirSync, writeFileSync, renameSync, rmSync, ...overrides };
272
- const temporaryPath = join(
273
- dirname(settingsPath),
274
- `.${basename(settingsPath)}.${randomUUID()}.tmp`
275
- );
275
+ const temporaryPath = join(dirname(settingsPath), `.${basename(settingsPath)}.${randomUUID()}.tmp`);
276
276
  try {
277
277
  fs.mkdirSync(dirname(settingsPath), { recursive: true });
278
278
  fs.writeFileSync(temporaryPath, document, { encoding: "utf8", flag: "wx" });
@@ -328,6 +328,7 @@ export {
328
328
  safeTerminalText,
329
329
  safeGoalMenuText,
330
330
  notifyTerminal,
331
+ isStaleContextError,
331
332
  formatError,
332
333
  truncateNotification,
333
334
  isUsageLimitedGoalInterruption,
@@ -339,4 +340,4 @@ export {
339
340
  saveGoalSettings,
340
341
  readGoalSettings
341
342
  };
342
- //# sourceMappingURL=chunk-UQRRW4CY.js.map
343
+ //# sourceMappingURL=chunk-6T3MHA45.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 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 status: string;\n baselineTokens: number;\n tokensUsed: number;\n timeUsedSeconds: number;\n activeStartedAt?: number;\n updatedAt: number;\n}\n\ninterface AssistantUsageEntryLike {\n type?: unknown;\n message?: unknown;\n}\n\ninterface UsageContext {\n sessionManager?: unknown;\n}\n\nexport function checkpointGoalActiveTime(goal: GoalAccountingState, now: number, continueClock: boolean) {\n const accumulated = nonNegativeFiniteNumber(goal.timeUsedSeconds);\n const startedAt = goal.activeStartedAt;\n if (typeof startedAt === \"number\" && Number.isFinite(startedAt)) {\n goal.timeUsedSeconds = accumulated + Math.max(0, now - startedAt) / 1000;\n } else {\n goal.timeUsedSeconds = accumulated;\n }\n goal.activeStartedAt = continueClock ? now : undefined;\n}\n\nexport function updateGoalUsage(\n goal: GoalAccountingState,\n ctx: UsageContext,\n continueClock = goal.status === \"active\",\n) {\n const now = Date.now();\n const baselineTokens = nonNegativeFiniteNumber(goal.baselineTokens);\n goal.baselineTokens = baselineTokens;\n goal.tokensUsed = Math.max(0, currentTokenTotal(ctx) - baselineTokens);\n checkpointGoalActiveTime(goal, now, continueClock);\n goal.updatedAt = now;\n}\n\nexport function formatDuration(seconds: number) {\n const wholeSeconds = Math.max(0, Math.floor(nonNegativeFiniteNumber(seconds)));\n if (wholeSeconds < 60) return `${wholeSeconds}s`;\n const minutes = Math.floor(wholeSeconds / 60);\n if (minutes < 60) return `${minutes}m`;\n const hours = Math.floor(minutes / 60);\n return `${hours}h${minutes % 60}m`;\n}\n\nexport function formatTokenCount(value: number) {\n if (value < 1_000) return `${value}`;\n if (value < 1_000_000) {\n return `${Number.isInteger(value / 1_000) ? value / 1_000 : (value / 1_000).toFixed(1)}k`;\n }\n return `${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 return typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n}\n\nexport function nonNegativeFiniteNumber(value: unknown) {\n return isNonNegativeFiniteNumber(value) ? value : 0;\n}\n\nexport function normalizeTokenBudget(value: unknown) {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 ? value : undefined;\n}\n\nexport function assistantUsageTokens(value: unknown) {\n if (!value || typeof value !== \"object\") return 0;\n const usage = value as Partial<Usage>;\n if (isNonNegativeFiniteNumber(usage.totalTokens)) return usage.totalTokens;\n return Math.min(\n Number.MAX_SAFE_INTEGER,\n nonNegativeFiniteNumber(usage.input) +\n nonNegativeFiniteNumber(usage.output) +\n nonNegativeFiniteNumber(usage.cacheRead) +\n nonNegativeFiniteNumber(usage.cacheWrite),\n );\n}\n\nexport function cumulativeAssistantTokens(entries: unknown[]) {\n let total = 0;\n for (const entry of entries) {\n const candidate = entry as AssistantUsageEntryLike;\n if (candidate?.type !== \"message\") continue;\n const message = candidate.message as { role?: unknown; usage?: unknown } | undefined;\n if (message?.role !== \"assistant\") continue;\n total = Math.min(Number.MAX_SAFE_INTEGER, total + assistantUsageTokens(message.usage));\n }\n return total;\n}\n\nexport function currentTokenTotal(ctx: UsageContext): number {\n const sessionManager = ctx.sessionManager as { getBranch?: () => unknown[] } | undefined;\n return cumulativeAssistantTokens(sessionManager?.getBranch?.() ?? []);\n}\n", "import {\n isContextOverflow,\n isRetryableAssistantError,\n type AssistantMessage as PiAssistantMessage,\n type 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 role: \"assistant\";\n stopReason?: AgentStopReason;\n errorMessage?: string;\n content?: PiAssistantMessage[\"content\"];\n api?: PiAssistantMessage[\"api\"];\n provider?: PiAssistantMessage[\"provider\"];\n model?: string;\n usage?: Usage;\n timestamp?: number;\n}\n\nconst USAGE_LIMIT_GOAL_ERROR_PATTERNS = [\n /usage[_\\s-]*(?:limit|cap)|chatgpt.{0,32}usage/i,\n /quota.{0,32}(?:reached|exceeded|exhausted|depleted)|(?:reached|exceeded|exhausted|depleted).{0,32}quota/i,\n /insufficient[_\\s-]*(?:quota|credits?)|out of credits|out of budget|available balance|payment required/i,\n /(?:credit|balance).{0,32}(?:low|exhausted|depleted)|billing/i,\n] as const;\nconst NON_RETRYABLE_GOAL_ERROR_RE = /multi-auth rotation failed|credentials tried|unauthori[sz]ed|invalid api key/i;\nconst RETRYABLE_GOAL_ERROR_PATTERNS = [\n /overloaded|rate.?limit|too many requests|\\b(?:429|500|502|503|504)\\b|service.?unavailable|server.?error|internal.?error/i,\n /provider.?returned.?error|you can retry your request|try your request again|please retry your request/i,\n /network.?error|connection.?(?:error|refused|lost)|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up/i,\n /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,\n /context[_\\s-]*length[_\\s-]*exceeded|input exceeds the context window/i,\n] as const;\n\nexport function safeTerminalText(value: string) {\n return [...stripTerminalSequences(value)]\n .map((character) => {\n const codePoint = character.codePointAt(0) ?? 0;\n if (character === \"\\n\") return character;\n return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? \" \" : character;\n })\n .join(\"\")\n .trim();\n}\n\nexport function safeGoalMenuText(value: string, maxCharacters = 120) {\n const sanitized = safeTerminalText(value).replace(/\\s+/gu, \" \").trim();\n const characters = [...sanitized];\n return characters.length <= maxCharacters ? sanitized : `${characters.slice(0, maxCharacters).join(\"\")}\u2026`;\n}\n\nexport function notifyTerminal(\n ui: { notify: (message: string, level?: \"info\" | \"warning\" | \"error\") => void },\n message: string,\n level?: \"info\" | \"warning\" | \"error\",\n) {\n ui.notify(safeTerminalText(message), level);\n}\n\n/**\n * True when an error came from an ExtensionContext invalidated by session\n * replacement or reload. Pi throws this from every ctx getter and pi method on\n * the stale runner, so deferred callbacks must treat it as cancellation.\n */\nexport function isStaleContextError(error: unknown): boolean {\n return (\n error instanceof Error && error.message.includes(\"This extension ctx is stale after session replacement or reload\")\n );\n}\n\nexport function formatError(error: unknown) {\n return truncateNotification(error instanceof Error ? error.message : String(error));\n}\n\nexport function truncateNotification(value: string) {\n const safe = [...safeTerminalText(value)];\n return safe.length > 160 ? `${safe.slice(0, 157).join(\"\")}...` : safe.join(\"\");\n}\n\nexport function isUsageLimitedGoalInterruption(assistant: AssistantMessageLike) {\n const errorMessage = assistant.errorMessage;\n return (\n assistant.stopReason === \"error\" &&\n typeof errorMessage === \"string\" &&\n USAGE_LIMIT_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(errorMessage))\n );\n}\n\nexport function isRetryableGoalInterruption(assistant: AssistantMessageLike) {\n if (assistant.stopReason !== \"error\" || !assistant.errorMessage) return false;\n if (isUsageLimitedGoalInterruption(assistant) || NON_RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage)) {\n return false;\n }\n return (\n isGoalContextOverflow(assistant) ||\n isRetryableAssistantError(toPiAssistantMessage(assistant)) ||\n RETRYABLE_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(assistant.errorMessage ?? \"\"))\n );\n}\n\nexport function isGoalContextOverflow(assistant: AssistantMessageLike) {\n return isContextOverflow(toPiAssistantMessage(assistant));\n}\n\nexport function findFinalAssistantMessage(messages: unknown[]): AssistantMessageLike | undefined {\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index];\n if (!message || typeof message !== \"object\") continue;\n const candidate = message as Record<string, unknown>;\n if (candidate.role !== \"assistant\") continue;\n const assistant: AssistantMessageLike = {\n role: \"assistant\",\n stopReason: isAgentStopReason(candidate.stopReason) ? candidate.stopReason : undefined,\n errorMessage: typeof candidate.errorMessage === \"string\" ? candidate.errorMessage : undefined,\n };\n if (Array.isArray(candidate.content)) {\n assistant.content = candidate.content as PiAssistantMessage[\"content\"];\n }\n if (typeof candidate.api === \"string\") assistant.api = candidate.api;\n if (typeof candidate.provider === \"string\") assistant.provider = candidate.provider;\n if (typeof candidate.model === \"string\") assistant.model = candidate.model;\n if (typeof candidate.timestamp === \"number\") assistant.timestamp = candidate.timestamp;\n const usage = normalizeUsage(candidate.usage);\n if (usage) assistant.usage = usage;\n return assistant;\n }\n return undefined;\n}\n\nfunction toPiAssistantMessage(assistant: AssistantMessageLike): PiAssistantMessage {\n return {\n role: \"assistant\",\n content: assistant.content ?? [],\n api: assistant.api ?? \"openai-responses\",\n provider: assistant.provider ?? \"unknown\",\n model: assistant.model ?? \"unknown\",\n usage: assistant.usage ?? zeroUsage(),\n stopReason: assistant.stopReason ?? \"error\",\n errorMessage: assistant.errorMessage,\n timestamp: assistant.timestamp ?? Date.now(),\n };\n}\n\nfunction zeroUsage(): Usage {\n return {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n totalTokens: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n };\n}\n\nfunction isAgentStopReason(value: unknown): value is AgentStopReason {\n return [\"stop\", \"length\", \"toolUse\", \"error\", \"aborted\"].includes(String(value));\n}\n\nfunction normalizeUsage(value: unknown): Usage | undefined {\n if (!value || typeof value !== \"object\") return undefined;\n const usage = value as Partial<Usage>;\n if (typeof usage.input !== \"number\" || typeof usage.output !== \"number\") return undefined;\n return {\n input: nonNegativeFiniteNumber(usage.input),\n output: nonNegativeFiniteNumber(usage.output),\n cacheRead: nonNegativeFiniteNumber(usage.cacheRead),\n cacheWrite: nonNegativeFiniteNumber(usage.cacheWrite),\n totalTokens: assistantUsageTokens(usage),\n cost: {\n input: usage.cost?.input ?? 0,\n output: usage.cost?.output ?? 0,\n cacheRead: usage.cost?.cacheRead ?? 0,\n cacheWrite: usage.cost?.cacheWrite ?? 0,\n total: usage.cost?.total ?? 0,\n },\n };\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 rpc: {\n enabled: boolean;\n };\n continuationLimits: {\n automaticTurns: ContinuationLimit;\n noProgressTurns: ContinuationLimit;\n };\n}\n\nexport const DEFAULT_GOAL_SETTINGS: GoalSettings = {\n rpc: { enabled: false },\n continuationLimits: { automaticTurns: 25, noProgressTurns: 3 },\n};\n\nexport type GoalSettingsLoadResult =\n | { kind: \"missing\"; legacyExperimentalGoals: false }\n | { kind: \"invalid\"; reason: string }\n | { kind: \"loaded\"; settings: GoalSettings; legacyExperimentalGoals: boolean };\n\nexport type GoalSettingsLoadIssue = Extract<GoalSettingsLoadResult, { kind: \"invalid\" }>;\n\ninterface GoalSettingsSaveFileSystem {\n mkdirSync: typeof mkdirSync;\n writeFileSync: typeof writeFileSync;\n renameSync: typeof renameSync;\n rmSync: typeof rmSync;\n}\n\nexport function normalizeGoalSettings(value: unknown): GoalSettings | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return undefined;\n\n const rpcValue = Object.hasOwn(value, \"rpc\") ? Reflect.get(value, \"rpc\") : undefined;\n if (rpcValue !== undefined && (typeof rpcValue !== \"object\" || rpcValue === null || Array.isArray(rpcValue))) {\n return undefined;\n }\n const rpcEnabled =\n rpcValue && Object.hasOwn(rpcValue, \"enabled\")\n ? Reflect.get(rpcValue, \"enabled\")\n : DEFAULT_GOAL_SETTINGS.rpc.enabled;\n if (typeof rpcEnabled !== \"boolean\") return undefined;\n\n const continuationLimitsValue = Object.hasOwn(value, \"continuationLimits\")\n ? Reflect.get(value, \"continuationLimits\")\n : undefined;\n if (\n continuationLimitsValue !== undefined &&\n (typeof continuationLimitsValue !== \"object\" ||\n continuationLimitsValue === null ||\n Array.isArray(continuationLimitsValue))\n ) {\n return undefined;\n }\n const automaticTurns = continuationLimitsValue\n ? normalizeContinuationLimit(\n Reflect.get(continuationLimitsValue, \"automaticTurns\"),\n DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns,\n )\n : DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns;\n const noProgressTurns = continuationLimitsValue\n ? normalizeContinuationLimit(\n Reflect.get(continuationLimitsValue, \"noProgressTurns\"),\n DEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns,\n )\n : DEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns;\n if (automaticTurns === undefined || noProgressTurns === undefined) return undefined;\n\n return {\n rpc: { enabled: rpcEnabled },\n continuationLimits: { automaticTurns, noProgressTurns },\n };\n}\n\nfunction normalizeContinuationLimit(value: unknown, fallback: ContinuationLimit): ContinuationLimit | undefined {\n if (value === undefined) return fallback;\n if (value === null) return null;\n return typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 ? value : undefined;\n}\n\nexport function saveGoalSettings(\n settings: GoalSettings,\n settingsPath = join(getAgentDir(), GOAL_SETTINGS_FILE),\n overrides: Partial<GoalSettingsSaveFileSystem> = {},\n) {\n const normalized = normalizeGoalSettings(settings);\n if (!normalized) throw new Error(\"Refusing to save invalid pi-goal settings.\");\n\n let raw: Record<string, unknown> = {};\n try {\n const contents = readFileSync(settingsPath, \"utf8\");\n const parsed = JSON.parse(contents) as unknown;\n if (!normalizeGoalSettings(parsed)) {\n throw new Error(`${settingsPath}: invalid settings shape`);\n }\n raw = ownRecord(parsed) ?? {};\n } catch (error) {\n if (!isNodeError(error) || error.code !== \"ENOENT\") {\n throw new Error(`Cannot save invalid settings file: ${formatError(error)}`);\n }\n }\n\n const rpc = ownRecord(raw.rpc) ?? {};\n const continuationLimits = ownRecord(raw.continuationLimits) ?? {};\n const document = `${JSON.stringify(\n {\n ...raw,\n rpc: { ...rpc, enabled: normalized.rpc.enabled },\n continuationLimits: {\n ...continuationLimits,\n automaticTurns: normalized.continuationLimits.automaticTurns,\n noProgressTurns: normalized.continuationLimits.noProgressTurns,\n },\n },\n null,\n 2,\n )}\\n`;\n const fs = { mkdirSync, writeFileSync, renameSync, rmSync, ...overrides };\n const temporaryPath = join(dirname(settingsPath), `.${basename(settingsPath)}.${randomUUID()}.tmp`);\n try {\n fs.mkdirSync(dirname(settingsPath), { recursive: true });\n fs.writeFileSync(temporaryPath, document, { encoding: \"utf8\", flag: \"wx\" });\n fs.renameSync(temporaryPath, settingsPath);\n } finally {\n try {\n fs.rmSync(temporaryPath, { force: true });\n } catch {\n // Best-effort cleanup must not replace the save result.\n }\n }\n}\n\nexport function readGoalSettings(settingsPath = join(getAgentDir(), GOAL_SETTINGS_FILE)): GoalSettingsLoadResult {\n let contents: string;\n try {\n contents = readFileSync(settingsPath, \"utf8\");\n } catch (error: unknown) {\n if (isNodeError(error) && error.code === \"ENOENT\") {\n return { kind: \"missing\", legacyExperimentalGoals: false };\n }\n return { kind: \"invalid\", reason: `${settingsPath}: ${formatError(error)}` };\n }\n\n try {\n const parsed = JSON.parse(contents) as unknown;\n const settings = normalizeGoalSettings(parsed);\n return settings\n ? { kind: \"loaded\", settings, legacyExperimentalGoals: hasLegacyExperimentalGoals(parsed) }\n : { kind: \"invalid\", reason: `${settingsPath}: invalid settings shape` };\n } catch (error: unknown) {\n return { kind: \"invalid\", reason: `${settingsPath}: ${formatError(error)}` };\n }\n}\n\nfunction hasLegacyExperimentalGoals(value: unknown) {\n const experimental = ownRecord(ownRecord(value)?.experimental);\n return experimental?.goals === true;\n}\n\nfunction ownRecord(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === \"object\" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"code\" in error;\n}\n\nfunction formatError(error: unknown) {\n return error instanceof Error ? error.message : String(error);\n}\n"],
5
+ "mappings": ";;;;AAoBO,SAAS,yBAAyB,MAA2B,KAAa,eAAwB;AACvG,QAAM,cAAc,wBAAwB,KAAK,eAAe;AAChE,QAAM,YAAY,KAAK;AACvB,MAAI,OAAO,cAAc,YAAY,OAAO,SAAS,SAAS,GAAG;AAC/D,SAAK,kBAAkB,cAAc,KAAK,IAAI,GAAG,MAAM,SAAS,IAAI;AAAA,EACtE,OAAO;AACL,SAAK,kBAAkB;AAAA,EACzB;AACA,OAA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