@narumitw/pi-goal 0.20.0 → 0.27.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 +62 -11
- package/package.json +3 -3
- package/src/commands.ts +13 -4
- package/src/errors.ts +147 -0
- package/src/goal.ts +193 -43
- package/src/markers.ts +25 -0
- package/src/persistence.ts +22 -0
- package/src/queue.ts +2 -0
- package/src/rpc.ts +188 -0
- package/src/runtime.ts +379 -188
- package/src/safety.ts +62 -0
- package/src/settings.ts +41 -0
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
`@narumitw/pi-goal` is a native [Pi coding agent](https://pi.dev) extension that adds session-scoped `/goal` commands, a `goal_complete({ goal_id, summary })` completion tool, and a strict `goal_blocked({ goal_id, reason, evidence, repeated_turns })` impasse tool for autonomous, verifiable task completion. An opt-in experimental mode adds an ordered queue without introducing a second command or tool namespace.
|
|
6
6
|
|
|
7
|
-
Goal mode uses Codex-like persistence instructions and sends guarded continuation messages from Pi's fully settled idle boundary until the agent completes the goal, the user pauses or clears it, a true blocker or provider usage limit stops it, or an optional token budget is reached. With ordered goals enabled, the same lifecycle advances through queued objectives one at a time.
|
|
7
|
+
Goal mode uses Codex-like persistence instructions and sends guarded continuation messages from Pi's fully settled idle boundary until the agent completes the goal, the user pauses or clears it, a safety circuit breaker trips, a true blocker or provider usage limit stops it, or an optional token budget is reached. With ordered goals enabled, the same lifecycle advances through queued objectives one at a time.
|
|
8
8
|
|
|
9
9
|
## ✨ Features
|
|
10
10
|
|
|
@@ -13,6 +13,8 @@ Goal mode uses Codex-like persistence instructions and sends guarded continuatio
|
|
|
13
13
|
- Keeps advanced goal management inside `/goal` subcommands: `pause`, `resume`, `clear`, and `edit`.
|
|
14
14
|
- Exposes only one top-level command: `/goal`, including when ordered goals are enabled.
|
|
15
15
|
- Optionally adds ordered-goal operations through `/goal add`, `prioritize`, `drop-last`, and `skip`, while accepting `push`, `unshift`, `pop`, and `shift` as hidden compatibility aliases.
|
|
16
|
+
- Bounds automatic work by default to 25 normal model responses, including responses inside automatic tool loops and Pi-owned retry/compaction recovery; set `continuationLimits.automaticTurns` explicitly to `null` only when unbounded automatic work is intended.
|
|
17
|
+
- Pauses after three consecutive empty or normalized-identical tool-free automatic runs, while distinct short output and tool activity reset the repeat detector.
|
|
16
18
|
- Supports optional token budgets such as `/goal --tokens 100k <goal>`, using provider-reported total-token accounting with a cache-inclusive compatibility fallback.
|
|
17
19
|
- Tracks distinct `active`, `paused`, `blocked`, `usage_limited`, `budget_limited`, and `complete` states.
|
|
18
20
|
- Stores goal state in the current Pi session, following Codex's thread-owned goal model instead of using a global per-directory goal. Experimental queues keep independent budget, usage, elapsed-time, iteration, status, and stale-id accounting for every item.
|
|
@@ -23,7 +25,7 @@ Goal mode uses Codex-like persistence instructions and sends guarded continuatio
|
|
|
23
25
|
- Lets retry, compaction, steering, follow-up, and other queued work settle before automatic goal continuation.
|
|
24
26
|
- Separates user interruption (`paused`), true impasse or terminal non-usage error (`blocked`), provider/account quota exhaustion (`usage_limited`), and user token budget exhaustion (`budget_limited`).
|
|
25
27
|
- Detects budget exhaustion after completed tool activity when assistant usage is persisted, then injects at most one non-user-authored wrap-up instruction and blocks further substantive tools.
|
|
26
|
-
- Keeps retryable provider interruptions and Pi compaction retries active without enqueueing duplicate goal continuations while Pi retries.
|
|
28
|
+
- Keeps retryable provider interruptions and Pi compaction retries active without enqueueing duplicate goal continuations while Pi retries, then marks a matching unresolved error `blocked` only when `agent_settled` proves no retry, compaction, or follow-up remains.
|
|
27
29
|
- Preserves active goals across manual, threshold, and overflow compaction.
|
|
28
30
|
- Guards auto-follow-ups and Goal-owned kickoff deliveries so duplicate, replaced, stopped, cleared, completed, budget-limited, or stale queued prompts cannot continue or overwrite a newer goal.
|
|
29
31
|
- Rotates the completion guard id when a goal is resumed or edited so delayed old turns cannot complete the newer goal instance.
|
|
@@ -59,6 +61,10 @@ Configuration is optional. Create `~/.pi/agent/pi-goal.json` only when overridin
|
|
|
59
61
|
"toolVisibility": "always",
|
|
60
62
|
"experimental": {
|
|
61
63
|
"goals": false
|
|
64
|
+
},
|
|
65
|
+
"continuationLimits": {
|
|
66
|
+
"automaticTurns": 25,
|
|
67
|
+
"noProgressTurns": 3
|
|
62
68
|
}
|
|
63
69
|
}
|
|
64
70
|
```
|
|
@@ -68,7 +74,14 @@ Configuration is optional. Create `~/.pi/agent/pi-goal.json` only when overridin
|
|
|
68
74
|
- `"always"` (default) — pi-goal does not proactively hide `goal_complete` or `goal_blocked`, keeping the tool schema stable from session startup.
|
|
69
75
|
- `"after-first-goal"` — hides both 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. 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. Failed kickoff, replacement, resume, or reactivating-edit delivery restores the exact pre-activation tool set, including terminal tools exposed by another extension. If revealing the tools would widen an already-running turn, wait for Pi to become idle and retry `/goal`.
|
|
70
76
|
|
|
71
|
-
`experimental.goals` accepts a boolean and defaults to `false`. Set it to `true` to enable the ordered-goal subcommands and automatic queue advancement described below. Enabled sessions show one warning because command behavior and persisted queue state remain experimental.
|
|
77
|
+
`experimental.goals` accepts a boolean and defaults to `false`. Set it to `true` to enable the ordered-goal subcommands and automatic queue advancement described below. Enabled sessions show one warning because command behavior and persisted queue state remain experimental.
|
|
78
|
+
|
|
79
|
+
`continuationLimits` controls the default-on runaway guards:
|
|
80
|
+
|
|
81
|
+
- `automaticTurns` is a positive safe integer and defaults to `25`. It counts every completed normal `turn_end` owned by automatically started Goal work, including model responses inside tool loops and matching Pi-owned retries. The user-triggered kickoff, resume, edit, and ordinary user runs are not charged. At the limit, the goal becomes `paused` with cause `continuation_limit`, pending continuation/recovery is cancelled, and the current operation is aborted. 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. Set this field to `null` to remove the authoritative hard bound.
|
|
82
|
+
- `noProgressTurns` is a positive safe integer and defaults to `3`. At the end of an automatic run, pi-goal compares visible assistant text after Unicode normalization, lowercasing, control-character removal, and whitespace collapse. Thinking and tool blocks are excluded; empty and punctuation-only output are equivalent. Consecutive empty or identical tool-free outputs increment the repeat count. Different non-empty output starts a new run at one, and any attempted tool call resets it. Set this field to `null` to disable only this heuristic.
|
|
83
|
+
|
|
84
|
+
Settings are reread at Pi startup, session replacement, and `/reload`; the file is not watched live.
|
|
72
85
|
|
|
73
86
|
Missing settings and omitted fields use the defaults above. Invalid settings produce a warning and fall back to all defaults; pi-goal never creates the file automatically. Reload Pi after changing the file. 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.
|
|
74
87
|
|
|
@@ -92,12 +105,12 @@ Tool visibility is a baseline, not ownership of Pi's global active-tool list. Pl
|
|
|
92
105
|
/goal skip
|
|
93
106
|
```
|
|
94
107
|
|
|
95
|
-
- `/goal` shows the current goal, status, iteration count, active elapsed time, token usage, and available `/goal` subcommands.
|
|
108
|
+
- `/goal` shows the current goal, status, lifetime iteration count, automatic model-response count, active elapsed time, token usage, any safety-pause reason, and available `/goal` subcommands.
|
|
96
109
|
- `/goal <goal_to_complete>` starts goal mode. If another unfinished goal exists, Pi asks for confirmation before replacing it with a new active goal and resetting its usage counters. Failed kickoff delivery clears a new goal or restores the prior goal; a previously active goal is restored as paused.
|
|
97
110
|
- `/goal --tokens 100k <goal_to_complete>` starts or replaces goal mode with a token budget. `k` and `m` suffixes are accepted, for example `100k` or `1.5m`.
|
|
98
|
-
- `/goal edit <goal_to_complete>` updates the existing goal objective without resetting usage counters.
|
|
111
|
+
- `/goal edit <goal_to_complete>` updates the existing goal objective without resetting usage counters. A successful active edit rotates the stale-turn guard and starts a fresh safety epoch. Paused, blocked, and usage-limited goals stay stopped and retain their safety state until resume. A budget-limited goal reactivates only when `edit --tokens` raises its budget above current usage. Failed prompt delivery restores the exact previous safety counters/cause; it restores a budget-limited goal or restores and pauses a previously active goal.
|
|
99
112
|
- `/goal pause` stops prompt injection and auto-continuation, aborts the current turn, and keeps the goal for later resume. Only active goals can be paused.
|
|
100
|
-
- `/goal resume` resumes a paused, blocked, usage-limited, or budget-limited goal when its token budget allows it, rotates the stale-turn guard id, and queues a resume prompt so work continues. If prompt delivery fails, the original stopped state
|
|
113
|
+
- `/goal resume` resumes a paused, blocked, usage-limited, or budget-limited goal when its token budget allows it, rotates the stale-turn guard id, resets the automatic-response/repeat safety epoch, clears a safety-pause cause, and queues a resume prompt so work continues. If prompt delivery fails, the original stopped state, guard id, counters, fingerprint, and cause are restored.
|
|
101
114
|
- `/goal clear` clears the current goal or the entire ordered queue, status, pending continuation/transition, and legacy persisted state for the current working directory without aborting unrelated in-flight work.
|
|
102
115
|
|
|
103
116
|
With `experimental.goals: true`:
|
|
@@ -115,9 +128,9 @@ Goal objectives are limited to 4,000 characters. Put longer instructions in a fi
|
|
|
115
128
|
|
|
116
129
|
## 🔁 Session and reload behavior
|
|
117
130
|
|
|
118
|
-
Goal state is stored as Pi session state, similar to Codex's thread-owned goals. `/reload` and reopening the same Pi session can restore that session's unfinished goal. With `"after-first-goal"`, that 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 either terminal tool is missing. If no unfinished goal remains, a fresh runtime starts locked again. Active elapsed time is checkpointed before shutdown and restarted after reload, so offline and stopped wall-clock time is excluded. Starting a new Pi session in the same working directory does not inherit the old goal.
|
|
131
|
+
Goal state is stored as Pi session state, similar to Codex's thread-owned goals. `/reload` and reopening the same Pi session can restore that session's unfinished goal. With `"after-first-goal"`, that 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 either terminal tool is missing. If no unfinished goal remains, a fresh runtime starts locked again. Active elapsed time is checkpointed before shutdown and restarted after reload, so offline and stopped wall-clock time is excluded. Automatic-response counts, repeat fingerprints, and safety-pause causes persist across reload and compaction. 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. Starting a new Pi session in the same working directory does not inherit the old goal.
|
|
119
132
|
|
|
120
|
-
Ordered queues use the same canonical `goal-state` session entry as single goals. The legacy `{ goal }` shape remains valid, and
|
|
133
|
+
Ordered queues use the same canonical `goal-state` session entry as single goals. Every item owns independent usage and safety state. Shelving, priority displacement, automatic advancement, and later reactivation preserve that item's epoch rather than granting more automatic work. The legacy `{ goal }` shape remains valid, and missing safety fields normalize to zero/defaults. Queue fields are written only when needed. Sessions created by the former standalone `pi-goals` experiment can migrate their last `goals-state` array and pending `unshift` intent when the branch has never written a canonical `goal-state`; any canonical entry, including an explicit clear, takes precedence so old plural state cannot be resurrected.
|
|
121
134
|
|
|
122
135
|
If a session still contains multiple goals or a pending queue transition when `experimental.goals` is disabled, pi-goal freezes that queue. It does not inject Goal prompts or continue work, reports `queue off`, preserves every item, and accepts only `/goal` for inspection or `/goal clear` for removal. Re-enable the setting and run `/reload` to resume. A migrated legacy array containing only one goal becomes an ordinary single goal without requiring the experiment.
|
|
123
136
|
|
|
@@ -129,7 +142,7 @@ Older versions wrote unfinished goals to `~/.pi/agent/pi-goal-state.json` keyed
|
|
|
129
142
|
|
|
130
143
|
- `active 3m` — an active goal without a token budget; elapsed time counts only periods when its status is active.
|
|
131
144
|
- `active 18k/100k` — an active goal with token usage and budget.
|
|
132
|
-
- `paused` — the user paused or
|
|
145
|
+
- `paused` — the user paused/interrupted the goal, terminal tools disappeared, or a `continuation_limit`/`no_progress` safety breaker stopped automatic work. Bare `/goal` shows the fixed safety reason and counters.
|
|
133
146
|
- `blocked` — progress requires user or external action, or a terminal non-usage error stopped work.
|
|
134
147
|
- `usage` — the provider or account usage limit stopped work.
|
|
135
148
|
- `budget 100k/100k` — the user-configured token budget was reached; auto-continuation stops.
|
|
@@ -142,6 +155,8 @@ For each persisted assistant message, `pi-goal` uses finite, non-negative `usage
|
|
|
142
155
|
|
|
143
156
|
Provider usage becomes authoritative only when an assistant message finishes, so a budget can overshoot by one model call. When completed tool activity first exposes exhaustion, the goal transitions once to `budget_limited`, cancels continuation, and queues one bounded custom wrap-up instruction before the next model call. The instruction permits only a concise progress/results/blockers summary; a substantive tool attempt is blocked and aborts the remaining wrap-up. A rejected `goal_complete` also terminates the wrap-up, while accepted completion still requires existing evidence that proves every requirement—budget exhaustion itself never means completion. If exhaustion is first visible at `agent_end` and no turn remains, the extension stops without creating another model turn.
|
|
144
157
|
|
|
158
|
+
The automatic-response cap is a call-count boundary, not a fixed cost ceiling: context size, cache pricing, output length, and provider rates vary, and the 25th response is still retained. No default token budget is imposed. For stricter spend control, combine the default circuit breakers with `/goal --tokens`.
|
|
159
|
+
|
|
145
160
|
Elapsed time is accumulated only while status is `active`. Pause, blocked, usage-limited, budget-limited, shutdown, and offline periods do not increase it. Legacy session entries are migrated by preserving their accumulated seconds and starting a fresh active clock when loaded.
|
|
146
161
|
|
|
147
162
|
## ✅ How completion works
|
|
@@ -152,7 +167,7 @@ Before completion, the shared audit tells the agent to treat completion as unpro
|
|
|
152
167
|
|
|
153
168
|
To finish, the agent must call `goal_complete` with the exact current `goal_id` and a `summary` of completion evidence. Missing or stale `goal_id` values are rejected before summary validation. Paused, blocked, and usage-limited goals cannot be completed until resumed; a budget-limited goal permits completion only during its bounded in-flight wrap-up. The summary is completion evidence, not the stale-turn safety token.
|
|
154
169
|
|
|
155
|
-
If a turn ends before completion, `pi-goal` records usage and creates one continuation intent. It dispatches that continuation only from Pi's `agent_settled` lifecycle after retries, automatic compaction, steering, and follow-up work have drained, `ctx.isIdle()` is true, and no messages are pending. Repeated settled events cannot dispatch the same intent twice. Goal-owned kickoff, resume, active-edit, and automatic-continuation deliveries are bound to the goal instance that created them; a delayed prompt from a replaced goal is aborted without rolling back, injecting, or stopping the newer goal.
|
|
170
|
+
If a turn ends before completion, `pi-goal` records usage and creates one continuation intent unless a circuit breaker pauses it first. It dispatches that continuation only from Pi's `agent_settled` lifecycle after retries, automatic compaction, steering, and follow-up work have drained, `ctx.isIdle()` is true, and no messages are pending. Repeated settled events cannot dispatch the same intent twice. Goal-owned kickoff, resume, active-edit, and automatic-continuation deliveries are bound to the goal instance that created them; a delayed prompt from a replaced goal is aborted without rolling back, injecting, or stopping the newer goal. Plain assistant text never marks a goal complete—even an exact-reply objective pauses safely when the model repeatedly omits `goal_complete`.
|
|
156
171
|
|
|
157
172
|
Manual compaction does not emit `agent_settled`, so its completion hook uses the same single-flight dispatcher as a narrow idle-only fallback. Pi extensions cannot reserve an idle turn atomically like Codex core; another extension can still win the race after the idle check, and its newer turn supersedes the old continuation intent.
|
|
158
173
|
|
|
@@ -164,7 +179,39 @@ Do not use `goal_blocked` merely because work is difficult, incomplete, uncertai
|
|
|
164
179
|
|
|
165
180
|
## 🛑 Interruption and queued-input behavior
|
|
166
181
|
|
|
167
|
-
A user pause or aborted turn produces `paused`; a terminal provider/account quota error produces `usage_limited`; another non-retryable agent error produces `blocked`. 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`. On `/goal clear`, the extension clears goal state, continuation markers, and any stale tool-call block without aborting an unrelated in-flight turn. Retryable provider interruptions and overflow compaction retries stay `active` while Pi retries; no extra continuation is queued. User and extension work that starts before settlement supersedes the older continuation intent, and pending messages always take priority.
|
|
182
|
+
A user pause or aborted turn produces `paused`; a terminal provider/account quota error produces `usage_limited`; another non-retryable agent error produces `blocked`. 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`. On `/goal clear`, the extension clears goal state, continuation markers, and any stale tool-call block without aborting an unrelated in-flight turn. 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. If matching recovery still exists at `agent_settled`, retries are exhausted and the goal becomes `blocked` before any pending queue transition dispatches. Stale recovery cannot block a replacement goal. User and extension work that starts before settlement supersedes the older continuation intent, and pending messages always take priority.
|
|
183
|
+
|
|
184
|
+
## 🤝 Cross-extension RPC and events
|
|
185
|
+
|
|
186
|
+
pi-goal exposes a session-local, dependency-free integration contract over Pi's shared `pi.events` bus so sibling extensions (such as `@tintinweb/pi-subagents`) can start, pause, and observe goals programmatically without driving the `/goal` slash command. The contract is bound only while a Pi session is active: it is established on `session_start` and the captured session context is unbound on `session_shutdown`. All channels are plain JSON-shaped payloads; this extension never adds a runtime dependency for them.
|
|
187
|
+
|
|
188
|
+
### Starting a goal: `pi-goal:rpc:start`
|
|
189
|
+
|
|
190
|
+
Emit `pi-goal:rpc:start` with `{ requestId: string, objective: string, tokenBudget?: number }`. `tokenBudget` is an absolute positive integer token count (for example `100000`), not a `k`/`m` string. The request reuses the same `startGoal()` transition as the slash command, so it never implements goal transitions twice.
|
|
191
|
+
|
|
192
|
+
pi-goal replies on `pi-goal:rpc:start:reply:${requestId}` with one of:
|
|
193
|
+
|
|
194
|
+
```jsonc
|
|
195
|
+
// success
|
|
196
|
+
{ "success": true, "data": { "goalId": "<uuid>", "status": "active" } }
|
|
197
|
+
// failure (validation, no session, pre-existing goal, or failed activation)
|
|
198
|
+
{ "success": false, "error": "<human-readable reason>" }
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
Behavior notes:
|
|
202
|
+
|
|
203
|
+
- Malformed payloads (missing/empty/non-string `objective`, or a non-positive-integer `tokenBudget`) fail fast with a descriptive `error`.
|
|
204
|
+
- If no session context is bound (before `session_start` or after `session_shutdown`), the reply is a failure rather than starting a goal.
|
|
205
|
+
- RPC starts run in a fresh child context, so a **pre-existing goal fails** instead of prompting, replacing, or reusing stale state. Clear the existing goal first.
|
|
206
|
+
- The reply `status` is read from the authoritative goal state, so an immediate terminal outcome during start is represented rather than assumed to be `active`.
|
|
207
|
+
|
|
208
|
+
### Pausing a goal: `pi-goal:rpc:pause`
|
|
209
|
+
|
|
210
|
+
Emit `pi-goal:rpc:pause` with `{ goalId?: string, requestId?: string, reason?: string }` to stop an active RPC-owned goal safely. After a successful start reply, pass its `goalId`. To cancel while the start reply is still pending, omit `goalId` and pass the originating start `requestId`. Uncorrelated requests, stale request IDs, mismatched goal IDs, and goals not created through RPC are ignored. A successful pause uses the normal Goal pause transition and emits the authoritative `pi-goal:state` event described below.
|
|
211
|
+
|
|
212
|
+
### Observing goal state: `pi-goal:state`
|
|
213
|
+
|
|
214
|
+
Whenever pi-goal persists canonical goal state, it emits `pi-goal:state` with `{ goalId, status, summary?, reason? }`. `goalId` and `status` are always authoritative. Terminal statuses are `complete`, `blocked`, `paused`, `usage_limited`, `budget_limited`, and `cleared`. Explicit clears and failed activation rollbacks emit `cleared` for the removed goal so observers cannot retain stale active state. `summary` is populated from the matching `goal_complete` summary when available, and `reason` is populated from the same goal instance's blocked/usage/budget/clear state where available; an `active` or `queued` event carries only `goalId` and `status`. Listeners must treat any non-terminal status as in-progress and should key follow-up behavior on `goalId` plus a terminal `status`.
|
|
168
215
|
|
|
169
216
|
## 🧠 Use cases
|
|
170
217
|
|
|
@@ -182,6 +229,10 @@ extensions/pi-goal/
|
|
|
182
229
|
│ ├── goal.ts # Pi entrypoint, tool contracts, and lifecycle orchestration
|
|
183
230
|
│ ├── commands.ts # Per-factory user-command and queue mutation controller
|
|
184
231
|
│ ├── runtime.ts # Per-factory state, prompt ownership, budgets, and tool policy
|
|
232
|
+
│ ├── safety.ts # Output normalization and no-progress fingerprint state
|
|
233
|
+
│ ├── errors.ts # Pi-aligned provider error and retry classification
|
|
234
|
+
│ ├── markers.ts # Bounded Goal prompt marker parsing and formatting
|
|
235
|
+
│ ├── rpc.ts # Session-local cross-extension request ownership and replies
|
|
185
236
|
│ ├── queue.ts # Pure ordered-goal transitions
|
|
186
237
|
│ └── *.ts # Package-local parsing, settings, prompts, accounting, and persistence
|
|
187
238
|
├── README.md
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@narumitw/pi-goal",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.27.0",
|
|
4
4
|
"description": "Pi extension for autonomous /goal completion with opt-in experimental ordered queues.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -34,8 +34,8 @@
|
|
|
34
34
|
},
|
|
35
35
|
"devDependencies": {
|
|
36
36
|
"@biomejs/biome": "2.5.3",
|
|
37
|
-
"@earendil-works/pi-ai": "0.
|
|
38
|
-
"@earendil-works/pi-coding-agent": "0.
|
|
37
|
+
"@earendil-works/pi-ai": "0.81.1",
|
|
38
|
+
"@earendil-works/pi-coding-agent": "0.81.1",
|
|
39
39
|
"typescript": "7.0.2"
|
|
40
40
|
},
|
|
41
41
|
"repository": {
|
package/src/commands.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { currentTokenTotal } from "./accounting.js";
|
|
2
2
|
import { validateObjective } from "./command.js";
|
|
3
|
+
import type { ActiveGoal } from "./persistence.js";
|
|
3
4
|
import { buildGoalPrompt, buildObjectiveUpdatedPrompt, buildResumePrompt } from "./prompts.js";
|
|
4
5
|
import {
|
|
5
6
|
activateQueuedGoal,
|
|
@@ -36,7 +37,12 @@ export class GoalCommandController {
|
|
|
36
37
|
this.runtime = runtime;
|
|
37
38
|
}
|
|
38
39
|
|
|
39
|
-
async startGoal(
|
|
40
|
+
async startGoal(
|
|
41
|
+
objective: string,
|
|
42
|
+
tokenBudget: number | undefined,
|
|
43
|
+
ctx: StatusContext,
|
|
44
|
+
onActivated?: (goal: ActiveGoal) => void,
|
|
45
|
+
) {
|
|
40
46
|
const validationError = validateObjective(objective);
|
|
41
47
|
if (validationError) {
|
|
42
48
|
ctx.ui.notify(validationError, "warning");
|
|
@@ -75,9 +81,10 @@ export class GoalCommandController {
|
|
|
75
81
|
this.runtime.queuedGoals = [];
|
|
76
82
|
this.runtime.pendingQueueAction = undefined;
|
|
77
83
|
this.runtime.activeGoal = createGoal(objective, tokenBudget, currentTokenTotal(ctx));
|
|
78
|
-
this.runtime.persistGoal(this.runtime.activeGoal);
|
|
79
|
-
this.runtime.updateStatus(ctx, this.runtime.activeGoal);
|
|
80
84
|
const startedGoal = this.runtime.activeGoal;
|
|
85
|
+
onActivated?.(startedGoal);
|
|
86
|
+
this.runtime.persistGoal(startedGoal);
|
|
87
|
+
this.runtime.updateStatus(ctx, startedGoal);
|
|
81
88
|
const sent = await this.runtime.sendOwnedGoalPrompt(
|
|
82
89
|
ctx,
|
|
83
90
|
startedGoal.id,
|
|
@@ -280,6 +287,7 @@ export class GoalCommandController {
|
|
|
280
287
|
ctx,
|
|
281
288
|
activatedGoal.id,
|
|
282
289
|
buildGoalPrompt(activatedGoal),
|
|
290
|
+
false, // Queue reactivation preserves its persisted safety epoch.
|
|
283
291
|
);
|
|
284
292
|
if (!sent && this.runtime.activeGoal?.id === activatedGoal.id) {
|
|
285
293
|
this.runtime.activeGoal = transitionGoal(activatedGoal, "paused");
|
|
@@ -435,9 +443,10 @@ export class GoalCommandController {
|
|
|
435
443
|
this.runtime.clearGoalRecovery();
|
|
436
444
|
this.runtime.clearBudgetWrapUp();
|
|
437
445
|
const previousStatus = this.runtime.activeGoal.status;
|
|
446
|
+
const rotatedGoal = nextGoalInstance(this.runtime.activeGoal);
|
|
438
447
|
const nextGoal = transitionGoal(
|
|
439
448
|
{
|
|
440
|
-
...
|
|
449
|
+
...rotatedGoal,
|
|
441
450
|
text: objective,
|
|
442
451
|
tokenBudget: tokenBudget ?? this.runtime.activeGoal.tokenBudget,
|
|
443
452
|
},
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isContextOverflow,
|
|
3
|
+
isRetryableAssistantError,
|
|
4
|
+
type AssistantMessage as PiAssistantMessage,
|
|
5
|
+
type Usage,
|
|
6
|
+
} from "@earendil-works/pi-ai";
|
|
7
|
+
import { assistantUsageTokens, nonNegativeFiniteNumber } from "./accounting.js";
|
|
8
|
+
|
|
9
|
+
export type AgentStopReason = "stop" | "length" | "toolUse" | "error" | "aborted";
|
|
10
|
+
|
|
11
|
+
export interface AssistantMessageLike {
|
|
12
|
+
role: "assistant";
|
|
13
|
+
stopReason?: AgentStopReason;
|
|
14
|
+
errorMessage?: string;
|
|
15
|
+
content?: PiAssistantMessage["content"];
|
|
16
|
+
api?: PiAssistantMessage["api"];
|
|
17
|
+
provider?: PiAssistantMessage["provider"];
|
|
18
|
+
model?: string;
|
|
19
|
+
usage?: Usage;
|
|
20
|
+
timestamp?: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const USAGE_LIMIT_GOAL_ERROR_PATTERNS = [
|
|
24
|
+
/usage[_\s-]*(?:limit|cap)|chatgpt.{0,32}usage/i,
|
|
25
|
+
/quota.{0,32}(?:reached|exceeded|exhausted|depleted)|(?:reached|exceeded|exhausted|depleted).{0,32}quota/i,
|
|
26
|
+
/insufficient[_\s-]*(?:quota|credits?)|out of credits|out of budget|available balance|payment required/i,
|
|
27
|
+
/(?:credit|balance).{0,32}(?:low|exhausted|depleted)|billing/i,
|
|
28
|
+
] as const;
|
|
29
|
+
const NON_RETRYABLE_GOAL_ERROR_RE =
|
|
30
|
+
/multi-auth rotation failed|credentials tried|unauthori[sz]ed|invalid api key/i;
|
|
31
|
+
const RETRYABLE_GOAL_ERROR_PATTERNS = [
|
|
32
|
+
/overloaded|rate.?limit|too many requests|\b(?:429|500|502|503|504)\b|service.?unavailable|server.?error|internal.?error/i,
|
|
33
|
+
/provider.?returned.?error|you can retry your request|try your request again|please retry your request/i,
|
|
34
|
+
/network.?error|connection.?(?:error|refused|lost)|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up/i,
|
|
35
|
+
/timed? out|timeout|terminated|websocket.?(?:closed|error)|ended without|stream ended before message_stop|http2 request did not get a response|retry delay/i,
|
|
36
|
+
/context[_\s-]*length[_\s-]*exceeded|input exceeds the context window/i,
|
|
37
|
+
] as const;
|
|
38
|
+
|
|
39
|
+
export function formatError(error: unknown) {
|
|
40
|
+
return truncateNotification(error instanceof Error ? error.message : String(error));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function truncateNotification(value: string) {
|
|
44
|
+
return value.length > 160 ? `${value.slice(0, 157)}...` : value;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function isUsageLimitedGoalInterruption(assistant: AssistantMessageLike) {
|
|
48
|
+
const errorMessage = assistant.errorMessage;
|
|
49
|
+
return (
|
|
50
|
+
assistant.stopReason === "error" &&
|
|
51
|
+
typeof errorMessage === "string" &&
|
|
52
|
+
USAGE_LIMIT_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(errorMessage))
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function isRetryableGoalInterruption(assistant: AssistantMessageLike) {
|
|
57
|
+
if (assistant.stopReason !== "error" || !assistant.errorMessage) return false;
|
|
58
|
+
if (
|
|
59
|
+
isUsageLimitedGoalInterruption(assistant) ||
|
|
60
|
+
NON_RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage)
|
|
61
|
+
) {
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
return (
|
|
65
|
+
isGoalContextOverflow(assistant) ||
|
|
66
|
+
isRetryableAssistantError(toPiAssistantMessage(assistant)) ||
|
|
67
|
+
RETRYABLE_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(assistant.errorMessage ?? ""))
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function isGoalContextOverflow(assistant: AssistantMessageLike) {
|
|
72
|
+
return isContextOverflow(toPiAssistantMessage(assistant));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function findFinalAssistantMessage(messages: unknown[]): AssistantMessageLike | undefined {
|
|
76
|
+
for (let index = messages.length - 1; index >= 0; index--) {
|
|
77
|
+
const message = messages[index];
|
|
78
|
+
if (!message || typeof message !== "object") continue;
|
|
79
|
+
const candidate = message as Record<string, unknown>;
|
|
80
|
+
if (candidate.role !== "assistant") continue;
|
|
81
|
+
const assistant: AssistantMessageLike = {
|
|
82
|
+
role: "assistant",
|
|
83
|
+
stopReason: isAgentStopReason(candidate.stopReason) ? candidate.stopReason : undefined,
|
|
84
|
+
errorMessage: typeof candidate.errorMessage === "string" ? candidate.errorMessage : undefined,
|
|
85
|
+
};
|
|
86
|
+
if (Array.isArray(candidate.content)) {
|
|
87
|
+
assistant.content = candidate.content as PiAssistantMessage["content"];
|
|
88
|
+
}
|
|
89
|
+
if (typeof candidate.api === "string") assistant.api = candidate.api;
|
|
90
|
+
if (typeof candidate.provider === "string") assistant.provider = candidate.provider;
|
|
91
|
+
if (typeof candidate.model === "string") assistant.model = candidate.model;
|
|
92
|
+
if (typeof candidate.timestamp === "number") assistant.timestamp = candidate.timestamp;
|
|
93
|
+
const usage = normalizeUsage(candidate.usage);
|
|
94
|
+
if (usage) assistant.usage = usage;
|
|
95
|
+
return assistant;
|
|
96
|
+
}
|
|
97
|
+
return undefined;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function toPiAssistantMessage(assistant: AssistantMessageLike): PiAssistantMessage {
|
|
101
|
+
return {
|
|
102
|
+
role: "assistant",
|
|
103
|
+
content: assistant.content ?? [],
|
|
104
|
+
api: assistant.api ?? "openai-responses",
|
|
105
|
+
provider: assistant.provider ?? "unknown",
|
|
106
|
+
model: assistant.model ?? "unknown",
|
|
107
|
+
usage: assistant.usage ?? zeroUsage(),
|
|
108
|
+
stopReason: assistant.stopReason ?? "error",
|
|
109
|
+
errorMessage: assistant.errorMessage,
|
|
110
|
+
timestamp: assistant.timestamp ?? Date.now(),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function zeroUsage(): Usage {
|
|
115
|
+
return {
|
|
116
|
+
input: 0,
|
|
117
|
+
output: 0,
|
|
118
|
+
cacheRead: 0,
|
|
119
|
+
cacheWrite: 0,
|
|
120
|
+
totalTokens: 0,
|
|
121
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function isAgentStopReason(value: unknown): value is AgentStopReason {
|
|
126
|
+
return ["stop", "length", "toolUse", "error", "aborted"].includes(String(value));
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function normalizeUsage(value: unknown): Usage | undefined {
|
|
130
|
+
if (!value || typeof value !== "object") return undefined;
|
|
131
|
+
const usage = value as Partial<Usage>;
|
|
132
|
+
if (typeof usage.input !== "number" || typeof usage.output !== "number") return undefined;
|
|
133
|
+
return {
|
|
134
|
+
input: nonNegativeFiniteNumber(usage.input),
|
|
135
|
+
output: nonNegativeFiniteNumber(usage.output),
|
|
136
|
+
cacheRead: nonNegativeFiniteNumber(usage.cacheRead),
|
|
137
|
+
cacheWrite: nonNegativeFiniteNumber(usage.cacheWrite),
|
|
138
|
+
totalTokens: assistantUsageTokens(usage),
|
|
139
|
+
cost: {
|
|
140
|
+
input: usage.cost?.input ?? 0,
|
|
141
|
+
output: usage.cost?.output ?? 0,
|
|
142
|
+
cacheRead: usage.cost?.cacheRead ?? 0,
|
|
143
|
+
cacheWrite: usage.cost?.cacheWrite ?? 0,
|
|
144
|
+
total: usage.cost?.total ?? 0,
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
}
|