@narumitw/pi-goal 0.54.3 → 0.54.4
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 +114 -62
- package/dist/index.ts +19 -0
- package/dist/index.ts.map +2 -2
- package/package.json +6 -9
- package/src/tools.ts +35 -0
package/README.md
CHANGED
|
@@ -2,23 +2,25 @@
|
|
|
2
2
|
|
|
3
3
|
[](https://www.npmjs.com/package/@narumitw/pi-goal) [](https://pi.dev) [](./LICENSE)
|
|
4
4
|
|
|
5
|
-
Give Pi
|
|
5
|
+
Give Pi one session-scoped objective and let it continue after Pi becomes fully idle.
|
|
6
|
+
Goal mode stops when work completes, pauses, waits for an external event, or reaches a safety limit.
|
|
6
7
|
|
|
7
|
-
|
|
8
|
+
Explicit completion, blocker, and wait tools give each managed run a clear stopping reason.
|
|
8
9
|
|
|
9
10
|
## ✨ Features
|
|
10
11
|
|
|
11
|
-
- Starts
|
|
12
|
+
- Starts and manages one session goal through `/goal` and its status, pause, resume, edit, and clear routes.
|
|
12
13
|
- Continues exactly once from Pi's settled idle boundary after queued work, retries, and compaction have finished.
|
|
13
14
|
- Waits quietly for a follow-up when transient provider retries are exhausted instead of terminally blocking the Goal.
|
|
14
15
|
- Uses explicit `goal_complete`, `goal_blocked`, and `goal_wait` tools with stale-goal guards and evidence requirements.
|
|
16
|
+
- Renders an accepted `goal_complete` summary as Markdown in the TUI.
|
|
15
17
|
- Tracks active, paused, blocked, usage-limited, budget-limited, waiting, and complete outcomes separately.
|
|
16
18
|
- Pauses after a configurable response limit or repeated no-progress runs and offers a guided review before continuing.
|
|
17
19
|
- Supports optional token budgets that stop Goal-owned work immediately when exhausted.
|
|
18
20
|
- Keeps Goal continuation accounting out of the leading system instructions so post-activation provider request prefixes remain stable.
|
|
19
21
|
- Persists the goal in the current session across reload, resume, compatible forks, and compaction.
|
|
20
22
|
- Rejects stale continuations and tool calls after replacement, pause, completion, limits, or other terminal state changes.
|
|
21
|
-
- Optionally exposes a default-off
|
|
23
|
+
- Optionally exposes a default-off protocol for trusted extensions to start, observe, and cancel one Goal lifecycle.
|
|
22
24
|
|
|
23
25
|
## 📦 Install
|
|
24
26
|
|
|
@@ -41,12 +43,14 @@ npm --workspace @narumitw/pi-goal run build
|
|
|
41
43
|
pi -e ./packages/pi-goal
|
|
42
44
|
```
|
|
43
45
|
|
|
44
|
-
The package declares `dist/index.ts`, so an unbuilt local checkout
|
|
46
|
+
The package declares `dist/index.ts`, so Pi cannot load an unbuilt local checkout.
|
|
47
|
+
Pi extensions run with your user permissions.
|
|
48
|
+
Goal mode can start repeated paid model turns and edit the current workspace, so review its limits and source before installing it.
|
|
45
49
|
|
|
46
50
|
## 🚀 Quick start
|
|
47
51
|
|
|
48
|
-
Run `/goal <objective>` to start
|
|
49
|
-
Use the manager to review
|
|
52
|
+
Run `/goal <objective>` to start Goal mode, or run `/goal` to open the state-aware manager.
|
|
53
|
+
Use the manager to review, pause, resume, edit, or clear the current goal.
|
|
50
54
|
|
|
51
55
|
## ⚙️ Settings
|
|
52
56
|
|
|
@@ -65,8 +69,9 @@ When `~/.pi/agent/pi-goal.json` is absent, pi-goal uses these built-in defaults
|
|
|
65
69
|
}
|
|
66
70
|
```
|
|
67
71
|
|
|
68
|
-
Use `/goal` → **Settings…** in the TUI to create or update the file
|
|
69
|
-
The
|
|
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:
|
|
70
75
|
|
|
71
76
|
- **Automatic-work limit** shows the exact response limit or **Unlimited**.
|
|
72
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…**.
|
|
@@ -74,11 +79,12 @@ The standard Settings screen keeps all three controls on one level in task order
|
|
|
74
79
|
- **No-progress guard** shows **_N_ runs** or **Off**.
|
|
75
80
|
Choose the default threshold, **Off**, or **Set threshold…** and enter a safe whole number greater than zero.
|
|
76
81
|
- **Managed run RPC** controls whether trusted installed extensions may start and cancel managed Goal runs.
|
|
77
|
-
It defaults to **Off** and
|
|
82
|
+
It defaults to **Off** and controls cooperation, not extension permissions.
|
|
78
83
|
|
|
79
|
-
Custom number inputs
|
|
80
|
-
|
|
81
|
-
|
|
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.
|
|
82
88
|
A failed save restores the prior value and reports the settings path so it can be retried.
|
|
83
89
|
Escape returns to the previous screen without reverting changes that were already saved.
|
|
84
90
|
|
|
@@ -88,7 +94,8 @@ Pi-goal never widens a restrictive active-tool policy; activation rejects when r
|
|
|
88
94
|
The retired `toolVisibility` key is ignored and preserved as unknown data when another setting is saved.
|
|
89
95
|
|
|
90
96
|
`experimental.goals` is a removed legacy setting.
|
|
91
|
-
If it remains `true`, pi-goal accepts the settings file
|
|
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.
|
|
92
99
|
Later settings saves preserve unknown legacy fields instead of deleting them.
|
|
93
100
|
|
|
94
101
|
`rpc.enabled` accepts a boolean and defaults to `false`.
|
|
@@ -97,34 +104,46 @@ A Settings-menu change applies immediately after its atomic save.
|
|
|
97
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.
|
|
98
105
|
Reload, replacement, and shutdown clear that in-memory ownership.
|
|
99
106
|
|
|
100
|
-
`continuationLimits` controls the
|
|
107
|
+
`continuationLimits` controls the automatic-work safety guards:
|
|
101
108
|
|
|
102
109
|
- `automaticTurns` accepts a positive safe integer or `null` and defaults to `25`.
|
|
103
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.
|
|
104
111
|
The user-triggered kickoff, resume, edit, and ordinary user runs are not charged.
|
|
105
|
-
At the limit, the goal becomes `paused` with cause `continuation_limit
|
|
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.
|
|
106
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.
|
|
107
115
|
Set this field explicitly to `null` to opt into Unlimited mode; existing explicit `null` values remain compatible.
|
|
108
116
|
- `noProgressTurns` is a positive safe integer and defaults to `3`.
|
|
109
|
-
At the end of an automatic run, pi-goal compares visible assistant text after Unicode normalization,
|
|
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.
|
|
110
118
|
Thinking and tool blocks are excluded; empty and punctuation-only output are equivalent.
|
|
111
119
|
Consecutive empty or identical tool-free outputs increment the repeat count.
|
|
112
120
|
Different non-empty output starts a new run at one, and any attempted tool call resets it.
|
|
113
121
|
Set this field to `null` to disable only this heuristic.
|
|
114
122
|
|
|
115
|
-
Settings are reread at Pi startup, session replacement, and `/reload
|
|
123
|
+
Settings are reread at Pi startup, session replacement, and `/reload`.
|
|
124
|
+
Direct file edits are not watched, while Goal-menu changes apply immediately.
|
|
116
125
|
A missing file remains absent and uses the built-in defaults.
|
|
117
126
|
The first successful settings change creates the file atomically; later saves preserve unknown fields.
|
|
118
127
|
|
|
119
128
|
Omitted fields use the defaults above.
|
|
120
129
|
Invalid or malformed existing settings are never overwritten; they produce a warning and fall back to all defaults.
|
|
121
|
-
In the TUI, Goal Settings becomes a read-only summary that identifies the invalid file and
|
|
122
|
-
Reload Pi after changing the file.
|
|
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`.
|
|
123
131
|
|
|
124
132
|
Plan mode or another restrictive policy may hide Goal tools.
|
|
125
|
-
Pi-goal does not
|
|
126
|
-
|
|
127
|
-
|
|
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.
|
|
139
|
+
|
|
140
|
+
## 🔒 Security and privacy
|
|
141
|
+
|
|
142
|
+
Goal mode can start repeated paid model turns and use active Pi tools, including tools that modify the workspace.
|
|
143
|
+
The default automatic-work limit and optional token budget reduce runaway work but are not dollar-cost caps.
|
|
144
|
+
Setting `rpc.enabled` to `true` lets trusted installed extensions request and cancel managed runs through Pi's shared event bus.
|
|
145
|
+
The protocol does not authenticate or sandbox installed extensions.
|
|
146
|
+
Workflow mutual exclusion is cooperative and does not prevent unrelated processes or extensions from editing the same workspace.
|
|
128
147
|
|
|
129
148
|
## 🤝 Workflow coexistence
|
|
130
149
|
|
|
@@ -133,12 +152,15 @@ On the characterized Pi `0.84.2` runtime, it participates in the anonymous `work
|
|
|
133
152
|
An active Goal holds the group through ordinary work, external waiting, continuation delivery, compaction recovery, and provider retry.
|
|
134
153
|
Paused, blocked, usage-limited, budget-limited, complete, cleared, and legacy-queue-only states do not hold it.
|
|
135
154
|
|
|
136
|
-
Direct starts, menu starts, managed-run starts, stopped resumes, and stopped-goal edits use one final synchronous admission
|
|
155
|
+
Direct starts, menu starts, managed-run starts, stopped resumes, and stopped-goal edits use one final synchronous admission.
|
|
156
|
+
Admission occurs after validation and confirmation but before any tool, Goal-state, persistence, prompt, queue, or status mutation.
|
|
137
157
|
Replacing or editing an already active or waiting Goal retains its current owner.
|
|
138
|
-
If admission is busy, TUI and RPC show an anonymous warning, print and JSON direct routes throw before mutation
|
|
158
|
+
If admission is busy, TUI and RPC show an anonymous warning, while print and JSON direct routes throw before mutation.
|
|
159
|
+
Managed-run RPC emits one terminal `ACTIVATION_FAILED` event without creating a Goal.
|
|
139
160
|
|
|
140
161
|
Restored active Goal state acquires before tool restoration, persistence publication, status, wait timers, retry state, or continuation work.
|
|
141
|
-
If restoration is busy, the Goal moves only to its existing paused safe state
|
|
162
|
+
If restoration is busy, the Goal moves only to its existing paused safe state.
|
|
163
|
+
It does not change active tools or schedule work, and you can resume it after the other workflow ends.
|
|
142
164
|
Restored stopped Goals and inert legacy queues do not acquire or schedule automatic work.
|
|
143
165
|
|
|
144
166
|
An active Goal still pauses if a non-participating restrictive policy later removes its required terminal tools.
|
|
@@ -170,14 +192,16 @@ Guaranteed coexistence with Plan mode requires `@narumitw/pi-plan-mode` `0.52.0`
|
|
|
170
192
|
- In the TUI, `/goal` opens a standard state-aware manager.
|
|
171
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.
|
|
172
194
|
Active and paused views show **Automatic work: _used_ of _limit_ responses** with the remaining count, or explicitly show **Unlimited**.
|
|
173
|
-
A hard-cap pause opens **Review and continue
|
|
174
|
-
|
|
175
|
-
**
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
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.
|
|
179
202
|
- In RPC mode, bare `/goal` and `/goal status` report the current summary through an observable notification without opening terminal UI.
|
|
180
|
-
Pi exposes no extension-command output channel in print or JSON mode
|
|
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.
|
|
181
205
|
- Menu-driven Replace and Clear actions preview the exact affected goal and require confirmation.
|
|
182
206
|
Existing direct routes remain immediate for compatibility and automation.
|
|
183
207
|
- `/goal <goal_to_complete>` starts goal mode.
|
|
@@ -192,10 +216,13 @@ Arrow keys navigate, Enter selects or submits, Escape goes Back, and Ctrl+C clos
|
|
|
192
216
|
Failed prompt delivery restores the exact previous Goal, guard id, safety counters, cause, tool-policy snapshot, and active ownership when applicable.
|
|
193
217
|
- `/goal pause` stops prompt injection and auto-continuation, aborts the current turn, and keeps the goal for later resume.
|
|
194
218
|
Only active goals can be paused.
|
|
195
|
-
- `/goal resume` resumes a paused, blocked, usage-limited, or budget-limited goal when its token budget allows it
|
|
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.
|
|
196
222
|
Objective, cumulative usage, and elapsed time are preserved.
|
|
197
223
|
If prompt delivery fails, the original stopped state, guard id, counters, fingerprint, and cause are restored.
|
|
198
|
-
- `/goal clear` clears the current goal, status, pending continuation, inert legacy queue state, and legacy persisted state for the current working directory
|
|
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.
|
|
199
226
|
|
|
200
227
|
The experimental ordered-goal queue has been removed.
|
|
201
228
|
Use `/goal edit <objective>` to reprioritize the active objective instead.
|
|
@@ -209,20 +236,22 @@ Put longer instructions in a file and reference the file path from `/goal`.
|
|
|
209
236
|
|
|
210
237
|
## 🛠️ Tools
|
|
211
238
|
|
|
212
|
-
- `goal_complete` records completion only for the exact active goal id
|
|
239
|
+
- `goal_complete` records completion only for the exact active goal id, requires an evidence-based summary, and renders an accepted summary as Markdown in the TUI.
|
|
213
240
|
- `goal_blocked` records a true repeated impasse with the exact goal id, reason, evidence, and repeated-turn count.
|
|
214
241
|
- `goal_wait` pauses automatic continuation after the agent arranges an external wake source, with an optional bounded resume deadline.
|
|
215
242
|
|
|
216
243
|
## 🔁 Session and reload behavior
|
|
217
244
|
|
|
218
|
-
Goal state is stored
|
|
245
|
+
Goal state is stored in the current Pi session.
|
|
219
246
|
`/reload` and reopening the same Pi session can restore that session's unfinished goal.
|
|
220
|
-
An active restored goal
|
|
247
|
+
An active restored goal at or above its finite automatic-work limit pauses before another provider request and reports that progress is saved.
|
|
248
|
+
Use `/goal` to review and continue.
|
|
221
249
|
A restored waiting Goal remains quiet, excludes offline and waiting wall time from active elapsed time, and restores only its absolute optional deadline timer.
|
|
222
250
|
An active restored goal pauses when workflow admission is busy or either required terminal tool is missing, without changing the active tool set.
|
|
223
251
|
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.
|
|
224
252
|
Automatic-response counts, repeat fingerprints, and safety-pause causes persist across reload and compaction.
|
|
225
|
-
A direct non-`/goal` user
|
|
253
|
+
A direct non-`/goal` user or RPC input resets the safety epoch only while the goal is active and reclassifies the in-flight run as manual.
|
|
254
|
+
Extension input and messages sent while stopped do not reset it.
|
|
226
255
|
Starting a new Pi session in the same working directory does not inherit the old goal.
|
|
227
256
|
|
|
228
257
|
The legacy `{ goal }` shape remains valid, and missing safety fields normalize to zero/defaults.
|
|
@@ -253,10 +282,11 @@ This version no longer reads that global file, and `/goal clear` removes any leg
|
|
|
253
282
|
|
|
254
283
|
## 💰 Token budgets and elapsed time
|
|
255
284
|
|
|
256
|
-
The TUI budget chooser
|
|
257
|
-
|
|
285
|
+
The TUI budget chooser treats a token budget as cumulative Goal usage and keeps the independent automatic-work response limit visible.
|
|
286
|
+
The final model call may exceed the selected token budget, so it is not a dollar-cost cap.
|
|
258
287
|
Choosing a preset or entering a custom value remains provisional until the objective is submitted; cancelling the chooser, custom input, or objective editor creates no Goal.
|
|
259
|
-
**Increase budget and resume…** shows the
|
|
288
|
+
**Increase budget and resume…** shows the current budget and usage and requires a new total above current usage.
|
|
289
|
+
It previews the new total and automatic-work epoch, then resumes only after confirmation.
|
|
260
290
|
If the goal or its usage changes while that dialog is open, no change is applied.
|
|
261
291
|
|
|
262
292
|
For each persisted assistant message, `pi-goal` uses finite, non-negative `usage.totalTokens` when available.
|
|
@@ -265,12 +295,14 @@ It does not add `reasoning` because reasoning is already part of output, or `cac
|
|
|
265
295
|
Goal usage is the current branch's cumulative assistant total minus the baseline captured when the goal started, clamped at zero after branch rewinds.
|
|
266
296
|
|
|
267
297
|
Provider usage becomes authoritative only when an assistant message finishes, so a budget can overshoot by one model call.
|
|
268
|
-
When completed tool activity first exposes exhaustion, the goal transitions once to `budget_limited
|
|
298
|
+
When completed tool activity first exposes exhaustion, the goal transitions once to `budget_limited`.
|
|
299
|
+
It cancels continuation, recovery, waits, and stale Goal-owned work, aborts the current turn, and releases workflow ownership.
|
|
269
300
|
It does not queue a summary or another model turn after budget exhaustion.
|
|
270
301
|
Stale Goal tool calls remain blocked until an unrelated user or extension turn begins or the Goal is explicitly reactivated.
|
|
271
302
|
A budget-limited Goal cannot call `goal_complete`; raise its budget above current usage and resume or edit it first.
|
|
272
303
|
|
|
273
|
-
The default 25-response automatic-work limit is a response-count boundary, not a fixed cost ceiling
|
|
304
|
+
The default 25-response automatic-work limit is a response-count boundary, not a fixed cost ceiling.
|
|
305
|
+
Context size, cache pricing, output length, and provider rates vary, and the final capped response is still retained.
|
|
274
306
|
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.
|
|
275
307
|
For tighter token control, choose a smaller `automaticTurns` value and/or use `/goal --tokens`; choosing Unlimited removes only the response-count boundary.
|
|
276
308
|
|
|
@@ -281,8 +313,10 @@ Legacy session entries are migrated by preserving their accumulated seconds and
|
|
|
281
313
|
## ✅ How completion works
|
|
282
314
|
|
|
283
315
|
While a goal is active, Goal-owned messages carry persistence rules and a `<goal_id>` stale-turn guard, and pi-goal exposes `goal_complete`.
|
|
284
|
-
Kickoff, resume, edited-objective, wait-resume, and automatic-continuation prompts
|
|
285
|
-
They
|
|
316
|
+
Kickoff, resume, edited-objective, wait-resume, and automatic-continuation prompts place a trust boundary before the escaped objective and identify it as user-provided task data.
|
|
317
|
+
They preserve its full scope across turns and require the agent to derive concrete requirements from the objective and referenced artifacts.
|
|
318
|
+
The prompts treat the current worktree, command output, tests, runtime behavior, pull request state, rendered artifacts, and external state as authoritative.
|
|
319
|
+
Previous conversation and plans are context, not proof.
|
|
286
320
|
|
|
287
321
|
Goal helper names, definitions, and active prompt metadata remain stable across Goal activation, continuation, token accounting, wait resume, completion, and clearing.
|
|
288
322
|
Mode-only positive instructions live in the append-only active Goal contract instead of globally active tool prompt metadata.
|
|
@@ -290,12 +324,15 @@ Current token-budget usage is carried by the newly appended Goal prompt instead
|
|
|
290
324
|
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
325
|
The contract explicitly supersedes earlier Goal contracts, excludes mutable token, iteration, and elapsed-time counters, and stays at its appended history position.
|
|
292
326
|
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
|
|
327
|
+
Completion, clearing, and stopped transitions append one inactive superseding contract.
|
|
328
|
+
Compaction and session restore append a missing current-state contract without waking a waiting Goal.
|
|
294
329
|
These structural guarantees make provider prefix reuse possible, but the provider still decides cache eligibility, cache hits, pricing, and billing.
|
|
295
330
|
|
|
296
|
-
Before completion, the shared audit tells the agent to treat completion as unproven
|
|
331
|
+
Before completion, the shared audit tells the agent to treat completion as unproven.
|
|
332
|
+
The agent must inspect evidence for every named artifact, command, test, gate, invariant, and deliverable and match each check to the requirement it supports.
|
|
297
333
|
Weak, indirect, missing, or merely consistent evidence means work must continue.
|
|
298
|
-
This prompt wording is a behavioral guardrail, not proof
|
|
334
|
+
This prompt wording is a behavioral guardrail, not proof.
|
|
335
|
+
Pi-goal can enforce the current goal id and reject empty or plainly contradictory summaries, but it cannot prove that external work is complete.
|
|
299
336
|
|
|
300
337
|
To finish, the agent must call `goal_complete` with the exact current `goal_id` and a `summary` of completion evidence.
|
|
301
338
|
Missing or stale `goal_id` values are rejected before summary validation.
|
|
@@ -303,13 +340,16 @@ Paused, blocked, usage-limited, and budget-limited goals cannot be completed unt
|
|
|
303
340
|
The summary is completion evidence, not the stale-turn safety token.
|
|
304
341
|
|
|
305
342
|
If a turn ends before completion, `pi-goal` records usage and creates one continuation intent unless a circuit breaker pauses it first.
|
|
306
|
-
It dispatches that continuation only from Pi's `agent_settled` lifecycle
|
|
343
|
+
It dispatches that continuation only from Pi's `agent_settled` lifecycle.
|
|
344
|
+
Retries, automatic compaction, steering, and follow-up work must be drained, `ctx.isIdle()` must be true, and no messages may be pending.
|
|
307
345
|
Repeated settled events cannot dispatch the same intent twice.
|
|
308
|
-
Goal-owned kickoff, resume, active-edit, and automatic-continuation deliveries are bound to the goal instance that created them
|
|
346
|
+
Goal-owned kickoff, resume, active-edit, and automatic-continuation deliveries are bound to the goal instance that created them.
|
|
347
|
+
A delayed prompt from a replaced goal is aborted without rolling back, injecting, or stopping the newer goal.
|
|
309
348
|
Plain assistant text never marks a goal complete—even an exact-reply objective pauses safely when the model repeatedly omits `goal_complete`.
|
|
310
349
|
|
|
311
|
-
Manual compaction does not emit `agent_settled`, so its completion hook uses the same single-flight dispatcher
|
|
312
|
-
Pi extensions cannot reserve an idle turn atomically like Codex core
|
|
350
|
+
Manual compaction does not emit `agent_settled`, so its completion hook uses the same single-flight dispatcher only when Pi is idle.
|
|
351
|
+
Pi extensions cannot reserve an idle turn atomically like Codex core.
|
|
352
|
+
Another extension can win the race after the idle check, and its newer turn supersedes the old continuation intent.
|
|
313
353
|
|
|
314
354
|
## ⏳ External waiting
|
|
315
355
|
|
|
@@ -325,11 +365,13 @@ goal_wait({
|
|
|
325
365
|
|
|
326
366
|
`goal_id` must match the current active Goal, `reason` must contain 1–1,000 characters, and the optional `resume_after_ms` must be a whole number from 1 through 2,147,483,647.
|
|
327
367
|
The deadline is a safety wake-up rather than a polling interval.
|
|
328
|
-
Requests below 10,000 milliseconds are accepted for compatibility but clamped to an effective 10,000-millisecond deadline
|
|
368
|
+
Requests below 10,000 milliseconds are accepted for compatibility but clamped to an effective 10,000-millisecond deadline.
|
|
369
|
+
The tool result reports both the requested and effective values.
|
|
329
370
|
Prefer deadlines measured in minutes instead of repeated short wakes.
|
|
330
371
|
Omitting `resume_after_ms` intentionally permits an indefinite quiet wait.
|
|
331
372
|
|
|
332
|
-
An accepted call keeps the canonical Goal status active, checkpoints active elapsed time, cancels pending continuation work
|
|
373
|
+
An accepted call keeps the canonical Goal status active, checkpoints active elapsed time, and cancels pending continuation work.
|
|
374
|
+
It persists the reason and optional absolute deadline and terminates the normal single-tool run.
|
|
333
375
|
Call `goal_wait` alone because Pi only guarantees early termination when every finalized result in a parallel tool batch terminates.
|
|
334
376
|
|
|
335
377
|
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.
|
|
@@ -358,7 +400,12 @@ Editing or replacing a waiting Goal clears the previous wait so the updated obje
|
|
|
358
400
|
## 🚧 Blocked goals
|
|
359
401
|
|
|
360
402
|
`goal_blocked` is intentionally narrower than completion or ordinary clarification.
|
|
361
|
-
Every goal-mode prompt
|
|
403
|
+
Every goal-mode prompt requires these fields for the blocked audit:
|
|
404
|
+
|
|
405
|
+
- the exact current `goal_id`;
|
|
406
|
+
- a specific reason, up to 1,000 characters, describing the required user or external action;
|
|
407
|
+
- concrete evidence from failed resolution attempts, up to 4,000 characters;
|
|
408
|
+
- `repeated_turns` showing that the same blocker recurred for at least three consecutive goal turns.
|
|
362
409
|
A resumed goal starts a fresh blocker audit.
|
|
363
410
|
Empty or oversized reasons/evidence, stale ids, non-whole turn counts, stopped goals, and fewer than three turns are rejected.
|
|
364
411
|
Accepted blocker reports set `blocked`, stop automatic continuation, and terminate the tool batch when Pi can do so safely.
|
|
@@ -369,9 +416,11 @@ The user can resolve the external condition and run `/goal resume` to rotate the
|
|
|
369
416
|
## 🛑 Interruption and queued-input behavior
|
|
370
417
|
|
|
371
418
|
A user pause or aborted turn produces `paused`; a terminal provider/account quota error produces `usage_limited`; another non-retryable agent error produces `blocked`.
|
|
372
|
-
Each stopped transition cancels pending continuation intent or delivery
|
|
419
|
+
Each stopped transition cancels pending continuation intent or delivery and aborts stale work when applicable.
|
|
420
|
+
Stale tool calls remain blocked until the next non-goal user prompt, successful reactivation or replacement, or `/goal clear`.
|
|
373
421
|
On `/goal clear`, the extension clears goal state, continuation markers, and any stale tool-call block without aborting an unrelated in-flight turn.
|
|
374
|
-
Retryable provider interruptions and overflow compaction retries stay `active` while Pi retries
|
|
422
|
+
Retryable provider interruptions and overflow compaction retries stay `active` while Pi retries.
|
|
423
|
+
No extra continuation is queued, and automatic ownership remains charged through retry `agent_start` events.
|
|
375
424
|
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
425
|
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
426
|
If matching compaction recovery still exists at `agent_settled`, the Goal becomes `blocked` because recovery did not produce usable context.
|
|
@@ -382,7 +431,8 @@ User and extension work that starts before settlement supersedes the older conti
|
|
|
382
431
|
|
|
383
432
|
With `rpc.enabled: true`, pi-goal exposes a session-local, dependency-free protocol over Pi's shared `pi.events` bus.
|
|
384
433
|
It is intended for trusted sibling extensions that need to start, observe, and cancel one Goal lifecycle without driving the `/goal` command.
|
|
385
|
-
Installed Pi extensions remain fully privileged
|
|
434
|
+
Installed Pi extensions remain fully privileged.
|
|
435
|
+
This setting controls only whether pi-goal cooperates with these channels; it does not provide authentication or sandboxing.
|
|
386
436
|
|
|
387
437
|
The public channels are:
|
|
388
438
|
|
|
@@ -418,13 +468,14 @@ A successful start produces canonical state on `pi-goal:event:${runId}`:
|
|
|
418
468
|
}
|
|
419
469
|
```
|
|
420
470
|
|
|
421
|
-
|
|
422
|
-
`complete` is
|
|
471
|
+
Later state events use `active`, `complete`, `blocked`, `paused`, `usage_limited`, `budget_limited`, or `cleared`.
|
|
472
|
+
Only `complete` is a successful terminal outcome.
|
|
423
473
|
A matching completion may include `summary`; other terminal outcomes may include `reason`.
|
|
424
474
|
Events come only from canonical Goal persistence and only for the matching managed run.
|
|
425
475
|
Manual and restored Goals are not adopted or broadcast, unchanged persistence does not duplicate a status, and each run emits at most one terminal event.
|
|
426
476
|
|
|
427
|
-
Terminal events are dispatched after the underlying Goal transition settles
|
|
477
|
+
Terminal events are dispatched after the underlying Goal transition settles.
|
|
478
|
+
A listener can start the next managed run directly after `complete` without re-entering completion cleanup.
|
|
428
479
|
Other terminal statuses leave a stopped Goal that must be resolved or cleared first.
|
|
429
480
|
If a manual edit, replacement, or edit transition rotates the Goal id, the prior managed run ends as `cleared` with a superseded reason; the replacement remains outside that run.
|
|
430
481
|
|
|
@@ -498,6 +549,7 @@ packages/pi-goal/
|
|
|
498
549
|
│ ├── markers.ts # Bounded Goal prompt marker parsing and formatting
|
|
499
550
|
│ ├── run-protocol.ts # Default-off managed-run protocol and session ownership
|
|
500
551
|
│ └── *.ts # Package-local parsing, settings, prompts, accounting, and persistence
|
|
552
|
+
├── test/
|
|
501
553
|
├── README.md
|
|
502
554
|
├── LICENSE
|
|
503
555
|
├── tsconfig.json
|
package/dist/index.ts
CHANGED
|
@@ -1363,8 +1363,10 @@ import {
|
|
|
1363
1363
|
DEFAULT_MAX_BYTES,
|
|
1364
1364
|
DEFAULT_MAX_LINES,
|
|
1365
1365
|
defineTool,
|
|
1366
|
+
getMarkdownTheme,
|
|
1366
1367
|
truncateHead
|
|
1367
1368
|
} from "@earendil-works/pi-coding-agent";
|
|
1369
|
+
import { Markdown } from "@earendil-works/pi-tui";
|
|
1368
1370
|
import { Type } from "typebox";
|
|
1369
1371
|
var MAX_GOAL_TEXT_LENGTH = 4e3;
|
|
1370
1372
|
var MAX_COMPLETION_SUMMARY_LENGTH = 4e3;
|
|
@@ -1387,6 +1389,9 @@ function registerGoalTools(pi, runtime) {
|
|
|
1387
1389
|
description: "State what was completed and what evidence verified it. Do not use this tool to report partial progress, blockers, failures, or remaining work."
|
|
1388
1390
|
})
|
|
1389
1391
|
}),
|
|
1392
|
+
renderResult(result) {
|
|
1393
|
+
return renderGoalCompletion(result);
|
|
1394
|
+
},
|
|
1390
1395
|
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1391
1396
|
const completedGoal = runtime.activeGoal;
|
|
1392
1397
|
const goal2 = completedGoal?.text ?? "unknown goal";
|
|
@@ -1624,6 +1629,20 @@ Requested resume_after_ms ${requestedMs} was clamped to ${effectiveMs}.` : `Goal
|
|
|
1624
1629
|
pi.registerTool(goalBlockedTool);
|
|
1625
1630
|
pi.registerTool(goalWaitTool);
|
|
1626
1631
|
}
|
|
1632
|
+
function goalCompletionMarkdown(result) {
|
|
1633
|
+
const content = result.content.filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n").trim();
|
|
1634
|
+
const completionPrefix = "Goal complete:";
|
|
1635
|
+
if (!content.startsWith(completionPrefix)) return content;
|
|
1636
|
+
const details = result.details;
|
|
1637
|
+
const summary = details && typeof details === "object" && "summary" in details && typeof details.summary === "string" ? details.summary : content.slice(completionPrefix.length);
|
|
1638
|
+
const safeSummary = safeTerminalText(summary);
|
|
1639
|
+
return safeSummary ? `**Goal complete**
|
|
1640
|
+
|
|
1641
|
+
${safeSummary}` : "**Goal complete**";
|
|
1642
|
+
}
|
|
1643
|
+
function renderGoalCompletion(result) {
|
|
1644
|
+
return new Markdown(goalCompletionMarkdown(result), 0, 0, getMarkdownTheme());
|
|
1645
|
+
}
|
|
1627
1646
|
function toolContent(text) {
|
|
1628
1647
|
return [
|
|
1629
1648
|
{
|
package/dist/index.ts.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/command-registration.ts", "../src/commands.ts", "../src/lifecycle.ts", "../src/run-protocol.ts", "../src/tools.ts", "../src/goal.ts"],
|
|
4
|
-
"sourcesContent": ["import type { ExtensionAPI, ExtensionCommandContext } from \"@earendil-works/pi-coding-agent\";\nimport { completeGoalArguments, isRemovedQueueCommand, parseCommand } from \"./command.js\";\nimport type { GoalCommandController } from \"./commands.js\";\nimport { notifyTerminal, safeTerminalText } from \"./errors.js\";\nimport type { GoalRuntime } from \"./runtime.js\";\n\ntype GoalManagerModule = Pick<typeof import(\"./menu.js\"), \"showGoalManager\">;\ntype GoalSettingsModule = Pick<typeof import(\"./settings-ui.js\"), \"showGoalSettings\">;\n\nexport interface GoalCommandRegistrationOptions {\n\tsettingsPath?: string;\n\tloadGoalManager?: () => Promise<GoalManagerModule>;\n\tloadGoalSettings?: () => Promise<GoalSettingsModule>;\n}\n\nexport function registerGoalCommand(\n\tpi: ExtensionAPI,\n\truntime: GoalRuntime,\n\tcommands: GoalCommandController,\n\toptions: GoalCommandRegistrationOptions = {},\n) {\n\tconst loadGoalManager = cachedModuleLoader(\n\t\toptions.loadGoalManager ?? (() => import(\"./menu.js\")),\n\t);\n\tconst loadGoalSettings = cachedModuleLoader(\n\t\toptions.loadGoalSettings ?? (() => import(\"./settings-ui.js\")),\n\t);\n\n\tpi.registerCommand(\"goal\", {\n\t\tdescription: \"Run a goal to completion: /goal [--tokens 100k] <goal_to_complete>\",\n\t\tgetArgumentCompletions: (prefix) => completeGoalArguments(prefix),\n\t\thandler: async (args, ctx) => {\n\t\t\tif (runtime.hasLegacyQueueInterface() && isRemovedQueueCommand(args)) {\n\t\t\t\treportRemovedQueueCommand(ctx, runtime);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst result = parseCommand(args);\n\t\t\tif (typeof result === \"string\") {\n\t\t\t\treportCommandError(result, ctx);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (result.kind === \"show\" && args.trim() === \"\") {\n\t\t\t\tconst menuIsCurrent = captureMenuOwnership(runtime);\n\t\t\t\tlet managerModule: GoalManagerModule;\n\t\t\t\ttry {\n\t\t\t\t\tmanagerModule = await loadGoalManager();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!menuIsCurrent()) return;\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tif (!menuIsCurrent()) return;\n\t\t\t\tconst { showGoalManager } = managerModule;\n\t\t\t\tawait showGoalManager(runtime, commands, ctx, async (menuCtx, target) => {\n\t\t\t\t\tconst settingsAreCurrent = captureMenuOwnership(runtime);\n\t\t\t\t\tlet settingsModule: GoalSettingsModule;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsettingsModule = await loadGoalSettings();\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!settingsAreCurrent()) return;\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t\tif (!settingsAreCurrent()) return;\n\t\t\t\t\tconst { showGoalSettings } = settingsModule;\n\t\t\t\t\tawait showGoalSettings(runtime, menuCtx, {\n\t\t\t\t\t\tsettingsPath: options.settingsPath,\n\t\t\t\t\t\tinitialScreen: target,\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tswitch (result.kind) {\n\t\t\t\tcase \"show\":\n\t\t\t\t\tcommands.showGoal(ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"pause\":\n\t\t\t\t\tcommands.pauseGoal(ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"resume\":\n\t\t\t\t\tawait commands.resumeGoal(ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"clear\":\n\t\t\t\t\tcommands.clearGoal(ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"edit\":\n\t\t\t\t\tawait commands.editGoal(result.objective ?? \"\", result.tokenBudget, ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"start\":\n\t\t\t\t\tawait commands.startGoal(result.objective ?? \"\", result.tokenBudget, ctx);\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t},\n\t});\n}\n\nfunction reportCommandError(message: string, ctx: ExtensionCommandContext) {\n\tconst safeMessage = safeTerminalText(message);\n\tif (ctx.mode === \"print\" || ctx.mode === \"json\") throw new Error(safeMessage);\n\tnotifyTerminal(ctx.ui, safeMessage, \"warning\");\n}\n\nfunction reportRemovedQueueCommand(ctx: ExtensionCommandContext, runtime: GoalRuntime) {\n\tconst message = runtime.activeGoal\n\t\t? \"Ordered goal queue has been removed. Use /goal edit to reprioritize the active objective instead.\"\n\t\t: \"Ordered goal queue has been removed. Start /goal <objectives> to continue with one merged objective, or use /goal clear to discard the old queue state.\";\n\tif (ctx.mode === \"print\" || ctx.mode === \"json\") throw new Error(message);\n\tnotifyTerminal(ctx.ui, message, \"warning\");\n}\n\nfunction captureMenuOwnership(runtime: GoalRuntime): () => boolean {\n\tconst generation = runtime.menuGeneration;\n\tconst controller = runtime.menuController;\n\treturn () =>\n\t\truntime.menuGeneration === generation &&\n\t\truntime.menuController === controller &&\n\t\t!controller.signal.aborted;\n}\n\nfunction cachedModuleLoader<Module>(load: () => Promise<Module>): () => Promise<Module> {\n\tlet pending: Promise<Module> | undefined;\n\treturn () => {\n\t\tif (!pending) {\n\t\t\tpending = load().catch((error) => {\n\t\t\t\tpending = undefined;\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t}\n\t\treturn pending;\n\t};\n}\n", "import { currentTokenTotal, formatTokenCount } from \"./accounting.js\";\nimport { validateObjective } from \"./command.js\";\nimport { notifyTerminal, safeGoalMenuText } from \"./errors.js\";\nimport type { ActiveGoal } from \"./persistence.js\";\nimport {\n\tbuildGoalPrompt,\n\tbuildObjectiveUpdatedPrompt,\n\tbuildResumePrompt,\n\tbuildWaitingResumePrompt,\n} from \"./prompts.js\";\nimport {\n\tblocksStaleGoalToolCalls,\n\tcreateGoal,\n\teditedGoalStatus,\n\tformatBudget,\n\tformatError,\n\ttype GoalRuntime,\n\tgoalSummary,\n\tisResumableGoalStatus,\n\tnextGoalInstance,\n\tqueueGoalSafetyReset,\n\tSTATUS_KEY,\n\ttype StatusContext,\n\tstoppedStatusLabel,\n\ttransitionGoal,\n} from \"./runtime.js\";\n\n// User-command mutations are kept separate from Pi event wiring. Every controller\n// receives exactly one per-factory GoalRuntime, preserving session isolation.\nexport class GoalCommandController {\n\tprivate readonly runtime: GoalRuntime;\n\n\tconstructor(runtime: GoalRuntime) {\n\t\tthis.runtime = runtime;\n\t}\n\n\tasync startGoal(\n\t\tobjective: string,\n\t\ttokenBudget: number | undefined,\n\t\tctx: StatusContext,\n\t\tonActivated?: (goal: ActiveGoal) => void,\n\t\tisActivationCurrent?: (goal: ActiveGoal) => boolean,\n\t\tisRequestCurrent?: () => boolean,\n\t) {\n\t\tif (isRequestCurrent && !isRequestCurrent()) return;\n\t\tconst validationError = validateObjective(objective);\n\t\tif (validationError) {\n\t\t\tnotifyTerminal(ctx.ui, validationError, \"warning\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst existingGoal =\n\t\t\tthis.runtime.activeGoal?.status !== \"complete\" ? this.runtime.activeGoal : undefined;\n\t\tconst legacyQueueBeforeActivation = existingGoal\n\t\t\t? undefined\n\t\t\t: this.runtime.legacyQueueState\n\t\t\t\t? structuredClone(this.runtime.legacyQueueState)\n\t\t\t\t: undefined;\n\t\tif (existingGoal) {\n\t\t\tconst shouldReplace = await ctx.ui.confirm(\n\t\t\t\t\"Replace goal?\",\n\t\t\t\t`Current goal: ${safeGoalMenuText(existingGoal.text, 4_000)}\\n\\nNew goal: ${safeGoalMenuText(objective, 4_000)}`,\n\t\t\t);\n\t\t\tif (!shouldReplace) {\n\t\t\t\tnotifyTerminal(ctx.ui, `Goal kept: ${existingGoal.text}`, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (isRequestCurrent && !isRequestCurrent()) return;\n\t\t\tif (this.runtime.activeGoal?.id !== existingGoal.id) {\n\t\t\t\tnotifyTerminal(\n\t\t\t\t\tctx.ui,\n\t\t\t\t\t\"The active goal changed while confirmation was open. Try again.\",\n\t\t\t\t\t\"warning\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t// Tool registration keeps the Goal schema stable. A missing tool means another\n\t\t// policy or allowlist intentionally removed it, so activation must not widen it.\n\t\tif (isRequestCurrent && !isRequestCurrent()) return;\n\t\tconst retainedOwner = this.runtime.ownsWorkflow(existingGoal);\n\t\tif (!this.runtime.acquireWorkflow(ctx.sessionManager)) return this.reportWorkflowBusy(ctx);\n\t\tconst acquiredForRequest = !retainedOwner;\n\t\ttry {\n\t\t\tthis.runtime.assertGoalToolsAvailable();\n\t\t} catch (error) {\n\t\t\tnotifyTerminal(ctx.ui, `Cannot start /goal: ${formatError(error)}`, \"error\");\n\t\t\tif (existingGoal?.status === \"active\") this.runtime.pauseGoalForUnavailableTools(ctx);\n\t\t\telse if (acquiredForRequest) this.runtime.releaseWorkflow();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.runtime.clearGoalWaitTimer();\n\t\tthis.runtime.cancelContinuationWork();\n\t\tthis.runtime.clearGoalRecovery();\n\t\tthis.runtime.clearBudgetWrapUp();\n\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\tif (!legacyQueueBeforeActivation) this.runtime.legacyQueueState = undefined;\n\t\tthis.runtime.activeGoal = createGoal(objective, tokenBudget, currentTokenTotal(ctx));\n\t\tconst startedGoal = this.runtime.activeGoal;\n\t\tonActivated?.(startedGoal);\n\t\tif (!legacyQueueBeforeActivation) this.runtime.persistGoal(startedGoal);\n\t\tif (\n\t\t\tthis.runtime.activeGoal?.id !== startedGoal.id ||\n\t\t\t!this.runtime.ownsWorkflow(this.runtime.activeGoal)\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tthis.runtime.updateStatus(ctx, startedGoal);\n\t\tconst sent = await this.runtime.sendOwnedGoalPrompt(\n\t\t\tctx,\n\t\t\tstartedGoal.id,\n\t\t\tbuildGoalPrompt(startedGoal),\n\t\t\ttrue,\n\t\t\t() => (isRequestCurrent?.() ?? true) && (isActivationCurrent?.(startedGoal) ?? true),\n\t\t);\n\t\tif (\n\t\t\tsent &&\n\t\t\tlegacyQueueBeforeActivation &&\n\t\t\tthis.runtime.activeGoal?.id === startedGoal.id &&\n\t\t\tthis.runtime.activeGoal.status === \"active\"\n\t\t) {\n\t\t\tthis.runtime.legacyQueueState = undefined;\n\t\t\tthis.runtime.persistGoal(startedGoal);\n\t\t}\n\t\tif (isActivationCurrent && !isActivationCurrent(startedGoal)) return;\n\t\tif (!sent) {\n\t\t\tlet rolledBackStartedGoal = false;\n\t\t\tif (this.runtime.activeGoal?.id === startedGoal.id) {\n\t\t\t\trolledBackStartedGoal = true;\n\t\t\t\tif (existingGoal) {\n\t\t\t\t\tthis.runtime.recordGoalUsage(existingGoal, ctx);\n\t\t\t\t\tif (existingGoal.status === \"active\" && existingGoal.waiting) {\n\t\t\t\t\t\tthis.runtime.activeGoal = existingGoal;\n\t\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\t\tthis.runtime.persistGoal(existingGoal);\n\t\t\t\t\t\tthis.runtime.updateStatus(ctx, existingGoal);\n\t\t\t\t\t\tthis.runtime.restoreGoalWaitTimer(ctx);\n\t\t\t\t\t} else if (existingGoal.status === \"active\") {\n\t\t\t\t\t\tthis.runtime.activeGoal = existingGoal;\n\t\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\t\tthis.runtime.persistGoal(existingGoal);\n\t\t\t\t\t\tif (this.runtime.activeGoal?.id === existingGoal.id) {\n\t\t\t\t\t\t\tthis.runtime.updateStatus(ctx, existingGoal);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.runtime.activeGoal = existingGoal;\n\t\t\t\t\t\tif (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {\n\t\t\t\t\t\t\tthis.runtime.blockStaleGoalToolCalls();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.runtime.persistGoal(this.runtime.activeGoal);\n\t\t\t\t\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\t\t\t\t}\n\t\t\t\t} else if (legacyQueueBeforeActivation) {\n\t\t\t\t\tthis.runtime.activeGoal = undefined;\n\t\t\t\t\tthis.runtime.legacyQueueState = legacyQueueBeforeActivation;\n\t\t\t\t\tthis.runtime.cancelContinuationWork();\n\t\t\t\t\tthis.runtime.clearGoalRecovery();\n\t\t\t\t\tthis.runtime.clearBudgetWrapUp();\n\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t\t\t} else {\n\t\t\t\t\tthis.runtime.clearActiveGoal(ctx, \"goal activation rolled back\", false);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (rolledBackStartedGoal) {\n\t\t\t\tif (acquiredForRequest && !this.runtime.ownsWorkflow(existingGoal)) {\n\t\t\t\t\tthis.runtime.releaseWorkflow();\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (\n\t\t\tthis.runtime.activeGoal?.id !== startedGoal.id ||\n\t\t\t!this.runtime.ownsWorkflow(this.runtime.activeGoal)\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tconst automaticLimit = this.runtime.settings.continuationLimits.automaticTurns;\n\t\tnotifyTerminal(\n\t\t\tctx.ui,\n\t\t\t`${existingGoal ? \"Goal replaced\" : \"Goal started\"}: ${objective}. ${\n\t\t\t\tstartedGoal.tokenBudget === undefined\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: `Token budget: ${formatTokenCount(startedGoal.tokenBudget)} cumulative; the final model call may exceed it. `\n\t\t\t}${\n\t\t\t\tautomaticLimit === null\n\t\t\t\t\t? \"Automatic work is Unlimited; tool loops may consume substantial tokens and provider cost. Open /goal to monitor.\"\n\t\t\t\t\t: `Automatic work pauses after ${automaticLimit} responses; open /goal to monitor progress.`\n\t\t\t}`,\n\t\t\tautomaticLimit === null ? \"warning\" : \"info\",\n\t\t);\n\t}\n\n\tpauseGoal(ctx: StatusContext) {\n\t\tif (!this.runtime.activeGoal) {\n\t\t\tnotifyTerminal(ctx.ui, \"No active goal.\", \"info\");\n\t\t\treturn;\n\t\t}\n\t\tif (this.runtime.activeGoal.status !== \"active\") {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal is ${this.runtime.activeGoal.status}; only active goals can be paused.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst stoppedGoal = this.runtime.stopActiveGoal(ctx, {\n\t\t\tkind: \"explicit_pause\",\n\t\t\texpectedGoalId: this.runtime.activeGoal.id,\n\t\t});\n\t\tif (stoppedGoal) notifyTerminal(ctx.ui, `Goal paused: ${stoppedGoal.text}`, \"info\");\n\t}\n\n\tasync resumeGoal(ctx: StatusContext) {\n\t\tif (!this.runtime.activeGoal) {\n\t\t\tnotifyTerminal(ctx.ui, \"No active goal.\", \"info\");\n\t\t\treturn;\n\t\t}\n\t\tif (this.runtime.activeGoal.status === \"active\" && this.runtime.activeGoal.waiting) {\n\t\t\tawait this.resumeWaitingGoal(ctx);\n\t\t\treturn;\n\t\t}\n\t\tif (!isResumableGoalStatus(this.runtime.activeGoal.status)) {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal is ${this.runtime.activeGoal.status}; only paused, blocked, usage-limited, or budget-limited goals can be resumed.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (\n\t\t\tthis.runtime.activeGoal.tokenBudget !== undefined &&\n\t\t\tthis.runtime.activeGoal.tokensUsed >= this.runtime.activeGoal.tokenBudget\n\t\t) {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal token budget is still reached: ${formatBudget(this.runtime.activeGoal)}`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.acquireWorkflow(ctx.sessionManager)) {\n\t\t\tthis.reportWorkflowBusy(ctx);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tthis.runtime.assertGoalToolsAvailable();\n\t\t} catch (error) {\n\t\t\tnotifyTerminal(ctx.ui, `Cannot resume /goal: ${formatError(error)}`, \"error\");\n\t\t\tthis.runtime.releaseWorkflow();\n\t\t\treturn;\n\t\t}\n\t\tconst stoppedGoal = this.runtime.activeGoal;\n\t\tconst stoppedStatus = stoppedGoal.status;\n\t\tthis.runtime.cancelContinuationWork();\n\t\tthis.runtime.clearGoalRecovery();\n\t\tthis.runtime.clearBudgetWrapUp();\n\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\tthis.runtime.activeGoal = queueGoalSafetyReset(\n\t\t\ttransitionGoal(nextGoalInstance(this.runtime.activeGoal), \"active\"),\n\t\t);\n\t\tthis.runtime.persistGoal(this.runtime.activeGoal);\n\t\tif (this.runtime.activeGoal.status !== \"active\") {\n\t\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\t\tthis.runtime.releaseWorkflow();\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal token budget is still reached: ${formatBudget(this.runtime.activeGoal)}`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.ownsWorkflow(this.runtime.activeGoal)) return;\n\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\tconst resumedGoal = this.runtime.activeGoal;\n\t\tconst sent = await this.runtime.sendOwnedGoalPrompt(\n\t\t\tctx,\n\t\t\tresumedGoal.id,\n\t\t\tbuildResumePrompt(resumedGoal, stoppedStatus),\n\t\t);\n\t\tif (!sent) {\n\t\t\tif (\n\t\t\t\tthis.runtime.activeGoal?.id === resumedGoal.id &&\n\t\t\t\tthis.runtime.activeGoal.status === \"active\"\n\t\t\t) {\n\t\t\t\tthis.runtime.activeGoal = stoppedGoal;\n\t\t\t\tthis.runtime.persistGoal(this.runtime.activeGoal);\n\t\t\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\t\t\tif (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {\n\t\t\t\t\tthis.runtime.blockStaleGoalToolCalls();\n\t\t\t\t}\n\t\t\t\tthis.runtime.releaseWorkflow();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.ownsWorkflow(resumedGoal)) return;\n\t\tconst automaticLimit = this.runtime.settings.continuationLimits.automaticTurns;\n\t\tnotifyTerminal(\n\t\t\tctx.ui,\n\t\t\t`Goal resumed from ${stoppedStatusLabel(stoppedStatus)}: ${resumedGoal.text}. ${\n\t\t\t\tautomaticLimit === null\n\t\t\t\t\t? \"Automatic work remains Unlimited; goal progress and cumulative usage are preserved.\"\n\t\t\t\t\t: `The automatic-work counter will reset to 0 of ${automaticLimit} when the resumed prompt starts; goal progress and cumulative usage are preserved.`\n\t\t\t}`,\n\t\t\tautomaticLimit === null ? \"warning\" : \"info\",\n\t\t);\n\t}\n\n\tprivate async resumeWaitingGoal(ctx: StatusContext) {\n\t\tconst waitingGoal = this.runtime.activeGoal;\n\t\tconst waiting = waitingGoal?.waiting;\n\t\tif (waitingGoal?.status !== \"active\" || !waiting) return;\n\t\tif (!this.runtime.acquireWorkflow(ctx.sessionManager)) {\n\t\t\tthis.reportWorkflowBusy(ctx);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tthis.runtime.assertGoalToolsAvailable();\n\t\t} catch (error) {\n\t\t\tnotifyTerminal(ctx.ui, `Cannot resume /goal: ${formatError(error)}`, \"error\");\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.clearGoalWait(ctx, waitingGoal.id)) return;\n\t\tconst resumedGoal = this.runtime.activeGoal;\n\t\tif (!resumedGoal || resumedGoal.id !== waitingGoal.id || resumedGoal.status !== \"active\")\n\t\t\treturn;\n\t\tconst sent = await this.runtime.sendOwnedGoalPrompt(\n\t\t\tctx,\n\t\t\tresumedGoal.id,\n\t\t\tbuildWaitingResumePrompt(resumedGoal, waiting.reason),\n\t\t\tfalse,\n\t\t);\n\t\tif (!sent) {\n\t\t\tif (this.runtime.activeGoal?.id === waitingGoal.id) {\n\t\t\t\tthis.runtime.enterGoalWait(ctx, waitingGoal.id, waiting);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.ownsWorkflow(resumedGoal)) return;\n\t\tnotifyTerminal(ctx.ui, `Goal resumed from waiting: ${waitingGoal.text}`, \"info\");\n\t}\n\n\tclearGoal(ctx: StatusContext) {\n\t\tif (!this.runtime.activeGoal) {\n\t\t\tconst hadLegacyQueue = this.runtime.legacyQueueState !== undefined;\n\t\t\tthis.runtime.legacyQueueState = undefined;\n\t\t\tthis.runtime.cancelContinuationWork();\n\t\t\tthis.runtime.clearGoalRecovery();\n\t\t\tthis.runtime.clearBudgetWrapUp();\n\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\tthis.runtime.clearPersistedGoal(ctx.cwd);\n\t\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\thadLegacyQueue ? \"Removed legacy ordered goal queue state.\" : \"No active goal.\",\n\t\t\t\thadLegacyQueue ? \"warning\" : \"info\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tconst stoppedGoal = this.runtime.activeGoal.text;\n\t\tthis.runtime.clearActiveGoal(ctx);\n\t\tnotifyTerminal(ctx.ui, `Goal cleared: ${stoppedGoal}`, \"warning\");\n\t}\n\n\tasync editGoal(objective: string, tokenBudget: number | undefined, ctx: StatusContext) {\n\t\tconst validationError = validateObjective(objective);\n\t\tif (validationError) {\n\t\t\tnotifyTerminal(ctx.ui, validationError, \"warning\");\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.activeGoal) {\n\t\t\tnotifyTerminal(ctx.ui, \"No active goal. Use /goal <objective> to start one.\", \"warning\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst currentGoal = this.runtime.activeGoal;\n\t\tconst effectiveTokenBudget = tokenBudget ?? currentGoal.tokenBudget;\n\t\tif (\n\t\t\tcurrentGoal.status === \"budget_limited\" &&\n\t\t\teffectiveTokenBudget !== undefined &&\n\t\t\teffectiveTokenBudget <= currentGoal.tokensUsed\n\t\t) {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal token budget is still reached: ${formatBudget(currentGoal)}. Raise the budget above current usage before editing.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst previousStatus = currentGoal.status;\n\t\tconst intendsActive = editedGoalStatus(previousStatus) === \"active\";\n\t\tconst retainedOwner = this.runtime.ownsWorkflow(currentGoal);\n\t\tif (intendsActive && !this.runtime.acquireWorkflow(ctx.sessionManager)) {\n\t\t\tthis.reportWorkflowBusy(ctx);\n\t\t\treturn;\n\t\t}\n\t\tconst acquiredForEdit = intendsActive && !retainedOwner;\n\t\tif (intendsActive) {\n\t\t\ttry {\n\t\t\t\tthis.runtime.assertGoalToolsAvailable();\n\t\t\t} catch (error) {\n\t\t\t\tnotifyTerminal(ctx.ui, `Cannot reactivate /goal: ${formatError(error)}`, \"error\");\n\t\t\t\tif (currentGoal.status === \"active\") this.runtime.pauseGoalForUnavailableTools(ctx);\n\t\t\t\telse if (acquiredForEdit) this.runtime.releaseWorkflow();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tthis.runtime.recordGoalUsage(currentGoal, ctx);\n\t\tconst previousGoal = { ...currentGoal };\n\t\tthis.runtime.clearGoalWaitTimer();\n\t\tthis.runtime.cancelContinuationWork();\n\t\tthis.runtime.clearGoalRecovery();\n\t\tthis.runtime.clearBudgetWrapUp();\n\t\tconst rotatedGoal = nextGoalInstance(currentGoal);\n\t\tconst transitionedGoal = transitionGoal(\n\t\t\t{\n\t\t\t\t...rotatedGoal,\n\t\t\t\ttext: objective,\n\t\t\t\ttokenBudget: effectiveTokenBudget,\n\t\t\t\twaiting: undefined,\n\t\t\t},\n\t\t\teditedGoalStatus(previousStatus),\n\t\t);\n\t\tconst nextGoal =\n\t\t\ttransitionedGoal.status === \"active\"\n\t\t\t\t? queueGoalSafetyReset(transitionedGoal)\n\t\t\t\t: transitionedGoal;\n\t\tthis.runtime.activeGoal = nextGoal;\n\t\tthis.runtime.persistGoal(this.runtime.activeGoal);\n\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\tconst editedGoal = this.runtime.activeGoal;\n\t\tif (!editedGoal) return;\n\t\tif (editedGoal.status === \"active\") {\n\t\t\tif (!this.runtime.ownsWorkflow(editedGoal)) return;\n\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\tconst sent = await this.runtime.sendOwnedGoalPrompt(\n\t\t\t\tctx,\n\t\t\t\teditedGoal.id,\n\t\t\t\tbuildObjectiveUpdatedPrompt(editedGoal),\n\t\t\t);\n\t\t\tif (!sent) {\n\t\t\t\tif (this.runtime.activeGoal?.id === editedGoal.id) {\n\t\t\t\t\tif (previousStatus === \"active\" && previousGoal.waiting) {\n\t\t\t\t\t\tthis.runtime.activeGoal = previousGoal;\n\t\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\t\tthis.runtime.persistGoal(previousGoal);\n\t\t\t\t\t\tthis.runtime.updateStatus(ctx, previousGoal);\n\t\t\t\t\t\tthis.runtime.restoreGoalWaitTimer(ctx);\n\t\t\t\t\t} else if (previousStatus === \"active\") {\n\t\t\t\t\t\tthis.runtime.activeGoal = previousGoal;\n\t\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\t\tthis.runtime.persistGoal(previousGoal);\n\t\t\t\t\t\tif (this.runtime.activeGoal?.id === previousGoal.id) {\n\t\t\t\t\t\t\tthis.runtime.updateStatus(ctx, previousGoal);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.runtime.activeGoal = previousGoal;\n\t\t\t\t\t\tif (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {\n\t\t\t\t\t\t\tthis.runtime.blockStaleGoalToolCalls();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.runtime.persistGoal(this.runtime.activeGoal);\n\t\t\t\t\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\t\t\t\t}\n\t\t\t\t\tif (acquiredForEdit && previousStatus !== \"active\") {\n\t\t\t\t\t\tthis.runtime.releaseWorkflow();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!this.runtime.ownsWorkflow(editedGoal)) return;\n\t\t} else if (blocksStaleGoalToolCalls(editedGoal.status)) {\n\t\t\tthis.runtime.blockStaleGoalToolCalls();\n\t\t} else {\n\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t}\n\t\tif (editedGoal.status !== \"active\" && (retainedOwner || acquiredForEdit)) {\n\t\t\tthis.runtime.releaseWorkflow();\n\t\t}\n\t\tnotifyTerminal(ctx.ui, `Goal updated: ${objective}`, \"info\");\n\t}\n\n\tprivate reportWorkflowBusy(ctx: StatusContext) {\n\t\tconst message = \"Another workflow is active in this session. End it before starting Goal.\";\n\t\tif (ctx.mode === \"print\" || ctx.mode === \"json\") throw new Error(message);\n\t\tnotifyTerminal(ctx.ui, message, \"warning\");\n\t\treturn { kind: \"busy\" as const };\n\t}\n\n\tshowGoal(ctx: StatusContext) {\n\t\tif (!this.runtime.activeGoal) {\n\t\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t\tthis.reportGoalStatus(ctx, this.emptyGoalMessage());\n\t\t\treturn;\n\t\t}\n\t\tthis.runtime.recordGoalUsage(this.runtime.activeGoal, ctx);\n\t\tthis.runtime.persistGoal(this.runtime.activeGoal);\n\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\tthis.reportGoalStatus(\n\t\t\tctx,\n\t\t\tgoalSummary(this.runtime.activeGoal, this.runtime.settings.continuationLimits.automaticTurns),\n\t\t);\n\t}\n\n\tprivate emptyGoalMessage() {\n\t\tconst legacy = this.runtime.legacyQueueState;\n\t\tif (!legacy) return \"Usage: /goal <objective>\\nNo goal is currently set.\";\n\t\treturn [\n\t\t\t\"Ordered goal queue has been removed.\",\n\t\t\t`Legacy queue state with ${legacy.retainedGoals} retained ${legacy.retainedGoals === 1 ? \"goal\" : \"goals\"} will not run automatically.`,\n\t\t\t\"Use /goal edit to reprioritize an active objective, start /goal <objectives>, or use /goal clear to discard the old queue state.\",\n\t\t\t'Example objective: \"task b is complete; do task a next, then task c and task d.\"',\n\t\t].join(\"\\n\");\n\t}\n\n\tprivate reportGoalStatus(ctx: StatusContext, message: string) {\n\t\tif (ctx.mode === \"print\" || ctx.mode === \"json\") {\n\t\t\tthrow new Error(\n\t\t\t\t`/goal status is unavailable in ${ctx.mode} mode because Pi does not expose an extension-command output channel. Use TUI or RPC mode.`,\n\t\t\t);\n\t\t}\n\t\tnotifyTerminal(ctx.ui, message, \"info\");\n\t}\n}\n", "import type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport { currentTokenTotal } from \"./accounting.js\";\nimport { notifyTerminal } from \"./errors.js\";\nimport {\n\tGOAL_CONTRACT_MESSAGE_TYPE,\n\tisGoalContextContract,\n\treconcileGoalContextContract,\n\treconcileInactiveGoalContextContract,\n} from \"./goal-contract.js\";\nimport { type ActiveGoal, loadGoalStateFromSession } from \"./persistence.js\";\nimport type { GoalRunController } from \"./run-protocol.js\";\nimport {\n\ttype AssistantMessageLike,\n\tabortCurrentTurn,\n\tblocksStaleGoalToolCalls,\n\tfindFinalAssistantMessage,\n\ttype GoalRuntime,\n\tincrementGoal,\n\tisGoalContextOverflow,\n\tisRetryableGoalInterruption,\n\tisUsageLimitedGoalInterruption,\n\tresetGoalSafetyEpoch,\n\tSTATUS_KEY,\n\ttype StatusContext,\n\ttransitionGoal,\n\ttruncateNotification,\n} from \"./runtime.js\";\nimport { hasAssistantToolCall } from \"./safety.js\";\nimport { DEFAULT_GOAL_SETTINGS, readGoalSettings } from \"./settings.js\";\n\nconst REMOVED_QUEUE_SETTING_WARNING =\n\t\"Ordered goal queue has been removed. Use /goal edit to reprioritize an active objective, or start /goal <objectives> if no active goal exists.\";\nconst REMOVED_PERSISTED_QUEUE_WARNING =\n\t\"Ordered goal queue has been removed. Start /goal <objectives> to continue with one merged objective, or use /goal clear to discard the old queue state.\";\n\ninterface GoalLifecycleOptions {\n\tsettingsPath?: string;\n}\n\nexport function registerGoalLifecycle(\n\tpi: ExtensionAPI,\n\truntime: GoalRuntime,\n\trunController: GoalRunController,\n\toptions: GoalLifecycleOptions = {},\n) {\n\tpi.on(\"session_start\", async (_event, ctx) => {\n\t\truntime.bindWorkflowSession(ctx.sessionManager);\n\t\truntime.replaceMenuSession();\n\t\truntime.clearCompletionStatusTimer();\n\t\truntime.clearContinuationTracking();\n\t\truntime.clearGoalWaitTimer();\n\t\truntime.clearPendingGoalPrompts();\n\t\truntime.clearAgentRun();\n\t\truntime.guardAbortGoalId = undefined;\n\t\truntime.clearGoalRecovery();\n\t\truntime.clearBudgetWrapUp();\n\t\truntime.clearStaleGoalToolCallBlock();\n\t\truntime.legacyQueueState = undefined;\n\t\truntime.legacyExperimentalGoalsSetting = false;\n\t\truntime.clearTerminalDetails();\n\t\tconst settingsResult = readGoalSettings(options.settingsPath);\n\t\tconst loaded = loadGoalStateFromSession(ctx);\n\t\truntime.settings =\n\t\t\tsettingsResult.kind === \"loaded\" ? settingsResult.settings : DEFAULT_GOAL_SETTINGS;\n\t\truntime.settingsLoadIssue = settingsResult.kind === \"invalid\" ? settingsResult : undefined;\n\t\truntime.activeGoal = undefined;\n\t\truntime.legacyQueueState = loaded.legacyQueueState;\n\t\truntime.legacyExperimentalGoalsSetting =\n\t\t\tsettingsResult.kind !== \"invalid\" && settingsResult.legacyExperimentalGoals;\n\t\trunController.bindSession(ctx);\n\n\t\tif (settingsResult.kind === \"invalid\") {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`pi-goal settings ignored: ${settingsResult.reason}. Using default settings.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t}\n\t\tif (runtime.legacyExperimentalGoalsSetting && !runtime.legacyQueueState) {\n\t\t\tnotifyTerminal(ctx.ui, REMOVED_QUEUE_SETTING_WARNING, \"warning\");\n\t\t}\n\n\t\tif (loaded.goal?.status === \"active\") {\n\t\t\tif (!runtime.acquireWorkflow()) {\n\t\t\t\truntime.activeGoal = transitionGoal(loaded.goal, \"paused\");\n\t\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\t\truntime.ensureInactiveGoalContextContract(ctx);\n\t\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t\t\tnotifyTerminal(\n\t\t\t\t\tctx.ui,\n\t\t\t\t\t\"Goal was paused during restore because another workflow is active in this session. Resume it after the other workflow ends.\",\n\t\t\t\t\t\"warning\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\truntime.activeGoal = loaded.goal;\n\t\t\tif (runtime.activeGoal.safetyResetPending) {\n\t\t\t\t// Resume/edit activation is persisted before its owned prompt starts. A\n\t\t\t\t// reload must commit that promised reset before enforcing the old limits.\n\t\t\t\truntime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);\n\t\t\t}\n\t\t\truntime.recordGoalUsage(runtime.activeGoal, ctx);\n\t\t\tif (runtime.limitActiveGoalForBudget(ctx, false)) return;\n\t\t\tif (runtime.enforceAutomaticTurnLimit(ctx, false) || runtime.enforceNoProgressLimit(ctx)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!runtime.goalToolsAvailable()) {\n\t\t\t\truntime.pauseGoalForUnavailableTools(ctx, false);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\tif (!runtime.ownsWorkflow(runtime.activeGoal)) return;\n\t\t\tconst restoredGoalId = runtime.activeGoal.id;\n\t\t\truntime.ensureGoalContextContract(ctx, runtime.activeGoal);\n\t\t\tif (\n\t\t\t\truntime.activeGoal?.id !== restoredGoalId ||\n\t\t\t\truntime.activeGoal.status !== \"active\" ||\n\t\t\t\t!runtime.ownsWorkflow(runtime.activeGoal)\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t\truntime.restoreGoalWaitTimer(ctx);\n\t\t\treturn;\n\t\t}\n\n\t\truntime.activeGoal = loaded.goal;\n\t\tif (runtime.legacyQueueState) {\n\t\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t\tnotifyTerminal(ctx.ui, REMOVED_PERSISTED_QUEUE_WARNING, \"warning\");\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.activeGoal) {\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\truntime.ensureInactiveGoalContextContract(ctx);\n\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t} else {\n\t\t\truntime.ensureInactiveGoalContextContract(ctx);\n\t\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t}\n\t});\n\n\tpi.on(\"session_shutdown\", (_event, ctx) => {\n\t\tconst shutdownSession = ctx.sessionManager;\n\t\trunController.unbindSession();\n\t\truntime.closeMenuSession();\n\t\truntime.clearGoalWaitTimer();\n\t\tif (runtime.activeGoal) {\n\t\t\tif (runtime.activeGoal.status === \"active\") {\n\t\t\t\truntime.recordGoalUsage(runtime.activeGoal, ctx, false);\n\t\t\t}\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t}\n\t\truntime.clearContinuationTracking();\n\t\truntime.clearPendingGoalPrompts();\n\t\truntime.clearAgentRun();\n\t\truntime.guardAbortGoalId = undefined;\n\t\truntime.clearGoalRecovery();\n\t\truntime.clearBudgetWrapUp();\n\t\truntime.clearStaleGoalToolCallBlock();\n\t\truntime.activeGoal = undefined;\n\t\truntime.legacyQueueState = undefined;\n\t\truntime.legacyExperimentalGoalsSetting = false;\n\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\truntime.clearCompletionStatusTimer();\n\t\truntime.clearTerminalDetails();\n\t\truntime.releaseWorkflow();\n\t\truntime.unbindWorkflowSession(shutdownSession);\n\t});\n\n\tpi.on(\"session_before_compact\", (event, ctx) => {\n\t\tif (runtime.activeGoal?.status === \"budget_limited\") {\n\t\t\tif ((event as { willRetry?: boolean }).willRetry === true) return { cancel: true as const };\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.activeGoal?.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\treturn;\n\t\t}\n\t\tif (!runtime.recordGoalUsage(runtime.activeGoal, ctx)) return;\n\t\truntime.cancelContinuationWork();\n\t\truntime.persistGoal(runtime.activeGoal);\n\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\tif (runtime.limitActiveGoalForBudget(ctx, false)) return { cancel: true as const };\n\t});\n\n\tpi.on(\"session_compact\", async (event, ctx) => {\n\t\tif (runtime.activeGoal?.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\truntime.clearGoalRecovery();\n\t\t\treturn;\n\t\t}\n\n\t\tconst restoredState = loadGoalStateFromSession(ctx);\n\t\tif (restoredState.goal?.id === runtime.activeGoal.id) {\n\t\t\truntime.activeGoal = restoredState.goal;\n\t\t}\n\t\tconst usageRecorded = runtime.recordGoalUsage(runtime.activeGoal, ctx);\n\t\tif (usageRecorded) {\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t}\n\t\tif (runtime.limitActiveGoalForBudget(ctx, false)) return;\n\t\tconst compactedGoalId = runtime.activeGoal.id;\n\t\truntime.ensureGoalContextContract(ctx, runtime.activeGoal);\n\t\tif (\n\t\t\truntime.activeGoal?.id !== compactedGoalId ||\n\t\t\truntime.activeGoal.status !== \"active\" ||\n\t\t\t!runtime.ownsWorkflow(runtime.activeGoal)\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tif (!usageRecorded) return;\n\n\t\tconst wasPiRetry = runtime.isPiOwnedCompactionRetry(event, runtime.activeGoal.id);\n\t\tif (wasPiRetry) return;\n\t\truntime.clearGoalRecoveryForGoal(runtime.activeGoal.id);\n\t\truntime.requestContinuation(runtime.activeGoal);\n\t\t// Pi emits session_compact before it clears its manual-compaction controller,\n\t\t// so sendUserMessage still rejects inside this hook even when ctx reports idle.\n\t\t// Defer one task; threshold compaction retains the intent for agent_settled\n\t\t// when Pi is still busy.\n\t\truntime.scheduleContinuationDispatch(ctx, runtime.activeGoal.id);\n\t});\n\n\tpi.on(\"input\", (event, ctx) => {\n\t\tif (event.source === \"extension\") {\n\t\t\tif (\n\t\t\t\truntime.consumeCancelledGoalPrompt(event.text) ||\n\t\t\t\truntime.consumeCancelledContinuationPrompt(event.text) ||\n\t\t\t\truntime.consumeStaleOwnedGoalPrompt(event.text)\n\t\t\t) {\n\t\t\t\treturn { action: \"handled\" as const };\n\t\t\t}\n\t\t\t// Streaming input is queued before its model work starts. Keep owned\n\t\t\t// markers pending for message_start, and track non-goal delivery mode so a\n\t\t\t// steer cannot consume a later follow-up's cleanup protection.\n\t\t\tif (runtime.acceptOwnedInputBoundary(event.text)) return;\n\t\t\truntime.supersedeOwnedInputCollision(event.text);\n\t\t\tif (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);\n\t\t\tif (event.streamingBehavior === \"steer\" || event.streamingBehavior === \"followUp\") {\n\t\t\t\truntime.noteQueuedNonGoalInput(event.text, event.streamingBehavior);\n\t\t\t}\n\t\t\truntime.clearGoalRecovery();\n\t\t\treturn;\n\t\t}\n\t\tif (/^\\/goal(?:\\s|$)/u.test(event.text.trimStart())) return;\n\t\tif (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);\n\t\tif (event.streamingBehavior === \"followUp\") {\n\t\t\truntime.noteQueuedNonGoalInput(event.text, \"followUp\", true);\n\t\t\treturn;\n\t\t}\n\t\tif (event.streamingBehavior === \"steer\") {\n\t\t\truntime.noteQueuedNonGoalInput(event.text, \"steer\");\n\t\t}\n\t\truntime.clearGoalRecovery();\n\t\truntime.clearBudgetWrapUp();\n\t\truntime.clearStaleGoalToolCallBlock();\n\t\truntime.resetActiveSafetyEpoch(ctx);\n\t});\n\n\tpi.on(\"message_start\", (event, ctx) => {\n\t\tconst message = event.message as { role?: unknown; content?: unknown };\n\t\tif (\n\t\t\tmessage.role === \"assistant\" &&\n\t\t\truntime.activeGoal?.status === \"paused\" &&\n\t\t\truntime.guardAbortGoalId === runtime.activeGoal.id\n\t\t) {\n\t\t\tabortCurrentTurn(ctx);\n\t\t\treturn;\n\t\t}\n\t\tif (message.role === \"custom\") {\n\t\t\tif (Reflect.get(message, \"customType\") === GOAL_CONTRACT_MESSAGE_TYPE) return;\n\t\t\tif (runtime.isActiveBudgetWrapUpMessage(message)) return;\n\t\t\tif (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);\n\t\t\tif (runtime.guardAbortGoalId === runtime.activeGoal?.id) {\n\t\t\t\truntime.guardAbortGoalId = undefined;\n\t\t\t}\n\t\t\tbeginNonGoalFollowUp(ctx, false);\n\t\t\treturn;\n\t\t}\n\t\tif (message.role !== \"user\") return;\n\t\tconst prompt = Array.isArray(message.content)\n\t\t\t? message.content\n\t\t\t\t\t.filter(\n\t\t\t\t\t\t(part) => part && typeof part === \"object\" && Reflect.get(part, \"type\") === \"text\",\n\t\t\t\t\t)\n\t\t\t\t\t.map((part) => Reflect.get(part as object, \"text\"))\n\t\t\t\t\t.filter((text): text is string => typeof text === \"string\")\n\t\t\t\t\t.join(\"\\n\")\n\t\t\t: typeof message.content === \"string\"\n\t\t\t\t? message.content\n\t\t\t\t: \"\";\n\t\tconst ownedPrompt = runtime.consumeOwnedGoalPrompt(prompt);\n\t\tconst ownedPromptBoundary = runtime.hasOwnedPromptBoundary(prompt);\n\t\tconst queuedNonGoalInput = runtime.consumeQueuedNonGoalInput(prompt, !ownedPromptBoundary);\n\t\tif (!ownedPrompt) {\n\t\t\tif (queuedNonGoalInput?.behavior === \"followUp\") {\n\t\t\t\tbeginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (\n\t\t\truntime.activeGoal?.id !== ownedPrompt.goalId ||\n\t\t\t!runtime.ownsWorkflow(runtime.activeGoal)\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.agentRunGoalId !== undefined && runtime.agentRunGoalId !== ownedPrompt.goalId) {\n\t\t\truntime.activeGoal.baselineTokens = Math.max(\n\t\t\t\t0,\n\t\t\t\tcurrentTokenTotal(ctx) - runtime.activeGoal.tokensUsed,\n\t\t\t);\n\t\t}\n\t\truntime.beginAgentRun(ownedPrompt.goalId, \"manual\");\n\t\tif (ownedPrompt.resetSafetyEpoch) {\n\t\t\truntime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);\n\t\t}\n\t\truntime.persistGoal(runtime.activeGoal);\n\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t});\n\n\tpi.on(\"context\", (event, ctx) => {\n\t\tconst keptMessages = event.messages.filter((message) =>\n\t\t\truntime.keepBudgetWrapUpMessage(message),\n\t\t);\n\t\tconst hasGoalContractHistory =\n\t\t\tkeptMessages.some(isGoalContextContract) || runtime.hasGoalContextContractHistory(ctx);\n\t\tconst messages =\n\t\t\truntime.activeGoal?.status === \"active\" && runtime.ownsWorkflow(runtime.activeGoal)\n\t\t\t\t? reconcileGoalContextContract(keptMessages, runtime.activeGoal)\n\t\t\t\t: hasGoalContractHistory\n\t\t\t\t\t? reconcileInactiveGoalContextContract(keptMessages)\n\t\t\t\t\t: keptMessages;\n\t\tif (\n\t\t\truntime.activeGoal?.status === \"paused\" &&\n\t\t\truntime.guardAbortGoalId === runtime.activeGoal.id\n\t\t) {\n\t\t\t// A current custom follow-up clears the guard at message_start. Otherwise,\n\t\t\t// context transformation aborts before the provider adapter receives the signal.\n\t\t\tabortCurrentTurn(ctx);\n\t\t}\n\t\tif (messages !== keptMessages || keptMessages.length !== event.messages.length) {\n\t\t\treturn { messages: messages as typeof event.messages };\n\t\t}\n\t});\n\n\tpi.on(\"tool_call\", (event, ctx) => {\n\t\truntime.markAgentToolAttempted();\n\t\tif (\n\t\t\truntime.activeGoal?.status === \"budget_limited\" &&\n\t\t\truntime.budgetWrapUp?.goalId === runtime.activeGoal.id &&\n\t\t\tevent.toolName !== \"goal_complete\"\n\t\t) {\n\t\t\t// A blocked tool result would normally trigger another model call. Abort the\n\t\t\t// wrap-up instead so a tool-seeking model cannot create an unbounded loop.\n\t\t\tabortCurrentTurn(ctx);\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason: \"Goal token budget is exhausted; only goal_complete is allowed during wrap-up.\",\n\t\t\t};\n\t\t}\n\t\tif (!runtime.staleGoalToolCallsBlocked) return;\n\t\tif (!runtime.activeGoal || !blocksStaleGoalToolCalls(runtime.activeGoal.status)) {\n\t\t\truntime.clearStaleGoalToolCallBlock();\n\t\t\treturn;\n\t\t}\n\t\t// A blocked tool result would normally trigger another model call. Abort the\n\t\t// current turn so a tool-seeking model cannot create an unbounded loop that\n\t\t// burns provider quota while the goal is stopped.\n\t\tabortCurrentTurn(ctx);\n\t\treturn {\n\t\t\tblock: true,\n\t\t\treason: \"Blocked stale /goal tool call after the goal stopped or was interrupted.\",\n\t\t};\n\t});\n\n\tpi.on(\"tool_execution_end\", (_event, ctx) => {\n\t\tif (\n\t\t\truntime.activeGoal?.status === \"budget_limited\" &&\n\t\t\truntime.budgetWrapUp?.goalId === runtime.activeGoal.id &&\n\t\t\t!runtime.budgetWrapUp.delivered\n\t\t) {\n\t\t\truntime.queueBudgetWrapUp(ctx, runtime.activeGoal);\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.activeGoal?.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\treturn;\n\t\t}\n\n\t\t// AgentSession persists assistant message_end before tool execution events,\n\t\t// so the completed assistant call's usage is authoritative at this boundary.\n\t\tif (!runtime.recordGoalUsage(runtime.activeGoal, ctx)) return;\n\t\truntime.persistGoal(runtime.activeGoal);\n\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\tif (runtime.limitActiveGoalForBudget(ctx, true)) return;\n\t\tif (!runtime.goalToolsAvailable()) runtime.pauseGoalForUnavailableTools(ctx);\n\t});\n\n\tpi.on(\"before_agent_start\", (event, ctx) => {\n\t\truntime.clearAgentRun();\n\t\t// Pi-owned retries emit agent_start directly. Reaching a normal prompt\n\t\t// boundary means cleanup no longer owns the next run, so the hard-cap guard\n\t\t// must not abort it.\n\t\tif (runtime.guardAbortGoalId) runtime.guardAbortGoalId = undefined;\n\t\tconst goalPrompt = runtime.consumeOwnedGoalPrompt(event.prompt);\n\t\tconst goalPromptGoalId = goalPrompt?.goalId;\n\t\tconst continuationGoalId = goalPromptGoalId\n\t\t\t? undefined\n\t\t\t: runtime.markContinuationStarted(event.prompt);\n\t\tconst ownedPromptGoalId = goalPromptGoalId ?? continuationGoalId;\n\t\tconst ownedPromptBoundary = runtime.hasOwnedPromptBoundary(event.prompt);\n\t\tconst activeBudgetWrapUp = runtime.hasActiveBudgetWrapUp();\n\t\tconst activeGoalRecovery = runtime.hasActiveGoalRecovery();\n\t\tconst queuedNonGoalInput = activeBudgetWrapUp\n\t\t\t? undefined\n\t\t\t: runtime.consumeQueuedNonGoalInput(\n\t\t\t\t\tevent.prompt,\n\t\t\t\t\t!activeGoalRecovery && ownedPromptGoalId === undefined && !ownedPromptBoundary,\n\t\t\t\t);\n\t\tif (queuedNonGoalInput?.behavior === \"followUp\") {\n\t\t\tbeginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);\n\t\t}\n\t\tif (!ownedPromptGoalId && !ownedPromptBoundary) {\n\t\t\truntime.supersedeOwnedInputCollision(event.prompt);\n\t\t\tif (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);\n\t\t}\n\t\tif (runtime.activeGoal?.status === \"active\" && !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\truntime.cancelContinuationWork();\n\t\t\truntime.clearGoalRecovery();\n\t\t\tabortCurrentTurn(ctx);\n\t\t\treturn;\n\t\t}\n\t\tconst runOrigin = continuationGoalId\n\t\t\t? \"automatic\"\n\t\t\t: activeGoalRecovery && runtime.goalRecovery?.automaticOwner\n\t\t\t\t? \"automatic\"\n\t\t\t\t: \"manual\";\n\t\tif (activeBudgetWrapUp && runtime.activeGoal) {\n\t\t\truntime.beginAgentRun(runtime.activeGoal.id, \"manual\");\n\t\t\treturn goalContractBoundaryResult(ctx);\n\t\t}\n\t\tif (ownedPromptGoalId && ownedPromptGoalId !== runtime.activeGoal?.id) {\n\t\t\truntime.beginAgentRun(ownedPromptGoalId, runOrigin);\n\t\t\tif (runtime.activeGoal?.status === \"active\" && !runtime.goalToolsAvailable()) {\n\t\t\t\truntime.pauseGoalForUnavailableTools(ctx, false);\n\t\t\t}\n\t\t\tabortCurrentTurn(ctx);\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.activeGoal?.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\treturn goalContractBoundaryResult(ctx);\n\t\t}\n\t\truntime.beginAgentRun(runtime.activeGoal.id, runOrigin);\n\t\tif (!runtime.goalToolsAvailable()) {\n\t\t\truntime.pauseGoalForUnavailableTools(ctx, ownedPromptGoalId !== undefined);\n\t\t\treturn goalContractBoundaryResult(ctx);\n\t\t}\n\t\tif (goalPrompt?.resetSafetyEpoch && goalPromptGoalId === runtime.activeGoal.id) {\n\t\t\truntime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t}\n\t\treturn goalContractBoundaryResult(ctx, runtime.activeGoal);\n\t});\n\n\tpi.on(\"agent_start\", (_event, _ctx) => {\n\t\tconst activeGoal = runtime.activeGoal;\n\t\tif (\n\t\t\tactiveGoal &&\n\t\t\truntime.guardAbortGoalId === activeGoal.id &&\n\t\t\tactiveGoal.status === \"paused\"\n\t\t) {\n\t\t\tif (runtime.consumeQueuedNonGoalFollowUpForAgentStart()) {\n\t\t\t\truntime.guardAbortGoalId = undefined;\n\t\t\t\truntime.clearStaleGoalToolCallBlock();\n\t\t\t\truntime.beginAgentRun(null, undefined);\n\t\t\t}\n\t\t\t// Unknown runs defer cleanup until their message/context boundary: custom\n\t\t\t// follow-ups have no input event, while bare recovery is aborted pre-provider.\n\t\t\treturn;\n\t\t}\n\t\truntime.beginRecoveryRunIfNeeded();\n\t});\n\n\tpi.on(\"turn_end\", (event, ctx) => {\n\t\truntime.recordAutomaticTurn(ctx, event.message);\n\t\t// Terminal Goal tools transition state synchronously, but their inactive contract\n\t\t// must wait until Pi has persisted the real tool result at this turn boundary.\n\t\tif (runtime.activeGoal?.status !== \"active\") {\n\t\t\truntime.ensureInactiveGoalContextContract(ctx);\n\t\t}\n\t});\n\n\tpi.on(\"agent_end\", (event, ctx) => {\n\t\tconst run = runtime.finishAgentRun();\n\t\tif (run.goalId === null) return;\n\t\tif (!runtime.canRecordGoalUsage() && !runtime.hasActiveBudgetWrapUp()) return;\n\t\tif (run.goalId && run.goalId !== runtime.activeGoal?.id) return;\n\t\tif (!runtime.activeGoal) return;\n\t\tif (\n\t\t\truntime.activeGoal.status === \"budget_limited\" &&\n\t\t\truntime.budgetWrapUp?.goalId === runtime.activeGoal.id\n\t\t) {\n\t\t\truntime.recordGoalUsage(runtime.activeGoal, ctx);\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t\truntime.clearBudgetWrapUp();\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.activeGoal.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst goalId = runtime.activeGoal.id;\n\t\tconst alreadyAwaitingContinuation = runtime.hasContinuationWorkForGoal(goalId);\n\t\tconst finalAssistant = findFinalAssistantMessage(event.messages);\n\n\t\tif (!alreadyAwaitingContinuation) runtime.activeGoal = incrementGoal(runtime.activeGoal);\n\t\truntime.recordGoalUsage(runtime.activeGoal, ctx);\n\n\t\tif (finalAssistant?.stopReason === \"aborted\") {\n\t\t\truntime.clearGoalRecoveryForGoal(goalId);\n\t\t\tstopGoalAfterAgentEnd(ctx, runtime.activeGoal, finalAssistant, \"paused\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (finalAssistant?.stopReason === \"error\") {\n\t\t\tif (isRetryableGoalInterruption(finalAssistant)) {\n\t\t\t\tif (run.origin === \"automatic\" && runtime.enforceAutomaticTurnLimit(ctx, true)) return;\n\t\t\t\tif (runtime.limitActiveGoalForBudget(ctx, false)) return;\n\t\t\t\tif (!runtime.goalToolsAvailable()) {\n\t\t\t\t\truntime.pauseGoalForUnavailableTools(ctx);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\truntime.goalRecovery = {\n\t\t\t\t\tgoalId,\n\t\t\t\t\tkind: isGoalContextOverflow(finalAssistant) ? \"compaction_retry\" : \"provider_retry\",\n\t\t\t\t\tautomaticOwner: run.origin === \"automatic\",\n\t\t\t\t\terrorMessage: finalAssistant.errorMessage,\n\t\t\t\t};\n\t\t\t\truntime.cancelContinuationWork();\n\t\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\truntime.clearGoalRecoveryForGoal(goalId);\n\t\t\tstopGoalAfterAgentEnd(\n\t\t\t\tctx,\n\t\t\t\truntime.activeGoal,\n\t\t\t\tfinalAssistant,\n\t\t\t\tisUsageLimitedGoalInterruption(finalAssistant) ? \"usage_limited\" : \"blocked\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\truntime.clearGoalRecoveryForGoal(goalId);\n\n\t\tif (runtime.limitActiveGoalForBudget(ctx, false)) return;\n\t\tif (!runtime.goalToolsAvailable()) {\n\t\t\truntime.pauseGoalForUnavailableTools(ctx);\n\t\t\treturn;\n\t\t}\n\t\tif (\n\t\t\trun.origin === \"automatic\" &&\n\t\t\truntime.recordAutomaticRunProgress(\n\t\t\t\tctx,\n\t\t\t\tgoalId,\n\t\t\t\tevent.messages,\n\t\t\t\trun.toolAttempted || hasAssistantToolCall(event.messages),\n\t\t\t)\n\t\t) {\n\t\t\treturn;\n\t\t}\n\n\t\truntime.persistGoal(runtime.activeGoal);\n\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\n\t\tconst currentGoal = runtime.activeGoal;\n\t\tif (!currentGoal || currentGoal.id !== goalId || currentGoal.status !== \"active\") return;\n\t\truntime.requestContinuation(currentGoal);\n\t});\n\n\tpi.on(\"agent_settled\", (_event, ctx) => {\n\t\tif (runtime.activeGoal?.status === \"active\" && !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\truntime.cancelContinuationWork();\n\t\t\truntime.clearGoalRecovery();\n\t\t\truntime.clearSettledSafetyTracking();\n\t\t\treturn;\n\t\t}\n\t\truntime.finalizeSettledRecovery(ctx);\n\t\tconst resumedWait = runtime.dispatchDueGoalWait(ctx);\n\t\tif (!resumedWait) runtime.dispatchContinuationIfSettled(ctx);\n\t\truntime.clearSettledSafetyTracking();\n\t});\n\n\tfunction goalContractBoundaryResult(ctx: StatusContext, goal?: ActiveGoal) {\n\t\tconst message = runtime.goalContextContractForPrompt(ctx, goal);\n\t\treturn message ? { message } : undefined;\n\t}\n\n\tfunction beginNonGoalFollowUp(ctx: StatusContext, resetSafetyEpoch: boolean) {\n\t\truntime.clearGoalRecovery();\n\t\truntime.clearStaleGoalToolCallBlock();\n\t\tif (resetSafetyEpoch) runtime.clearBudgetWrapUp();\n\t\tconst activeGoalId =\n\t\t\truntime.activeGoal?.status === \"active\" ? runtime.activeGoal.id : undefined;\n\t\truntime.beginAgentRun(activeGoalId ?? null, activeGoalId ? \"manual\" : undefined);\n\t\tif (resetSafetyEpoch && activeGoalId) runtime.resetActiveSafetyEpoch(ctx);\n\t}\n\n\tfunction stopGoalAfterAgentEnd(\n\t\tctx: StatusContext,\n\t\tgoal: ActiveGoal,\n\t\tassistant: AssistantMessageLike,\n\t\tstatus: \"paused\" | \"blocked\" | \"usage_limited\",\n\t) {\n\t\tconst stoppedGoal = runtime.stopActiveGoal(ctx, {\n\t\t\tkind: \"agent_interruption\",\n\t\t\texpectedGoalId: goal.id,\n\t\t\tstatus,\n\t\t\treason: assistant.errorMessage ?? `goal ${status} after agent interruption`,\n\t\t});\n\t\tif (!stoppedGoal) return;\n\n\t\tconst details = assistant.errorMessage\n\t\t\t? ` (${truncateNotification(assistant.errorMessage)})`\n\t\t\t: \"\";\n\t\tif (status === \"paused\") {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal paused after interruption${details}. Run /goal resume to continue.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (status === \"usage_limited\") {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal stopped after provider usage limit${details}. Run /goal resume when usage is available.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tnotifyTerminal(\n\t\t\tctx.ui,\n\t\t\t`Goal blocked after agent error${details}. Resolve the blocker or run /goal resume to retry.`,\n\t\t\t\"warning\",\n\t\t);\n\t}\n}\n", "import type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport { validateObjective } from \"./command.js\";\nimport type { GoalCommandController } from \"./commands.js\";\nimport {\n\tformatError,\n\ttype GoalRuntime,\n\ttype GoalStateSnapshot,\n\tisTerminalGoalStatus,\n\ttype StatusContext,\n} from \"./runtime.js\";\n\nexport const GOAL_RUN_START_CHANNEL = \"pi-goal:start\";\nexport const GOAL_RUN_CANCEL_CHANNEL = \"pi-goal:cancel\";\n\nconst RUN_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;\nconst MAX_CANCEL_REASON_LENGTH = 1_000;\n\nexport type GoalRunStatus = Exclude<GoalStateSnapshot[\"status\"], \"queued\">;\nexport type GoalRunErrorCode =\n\t| \"RPC_DISABLED\"\n\t| \"INVALID_REQUEST\"\n\t| \"NO_ACTIVE_SESSION\"\n\t| \"RUN_ID_IN_USE\"\n\t| \"RUN_NOT_FOUND\"\n\t| \"GOAL_ALREADY_EXISTS\"\n\t| \"ACTIVATION_FAILED\"\n\t| \"SUPERSEDED\";\n\nexport type GoalRunEvent =\n\t| {\n\t\t\ttype: \"state\";\n\t\t\trunId: string;\n\t\t\tgoalId: string;\n\t\t\tstatus: GoalRunStatus;\n\t\t\tsummary?: string;\n\t\t\treason?: string;\n\t }\n\t| {\n\t\t\ttype: \"error\";\n\t\t\trunId: string;\n\t\t\toperation: \"start\" | \"cancel\";\n\t\t\terror: { code: GoalRunErrorCode; message: string };\n\t };\n\ninterface GoalRunStartPayload {\n\trunId: string;\n\tobjective: string;\n\ttokenBudget?: number;\n}\n\ninterface BoundSession {\n\tgeneration: number;\n\tctx: StatusContext;\n}\n\ninterface ManagedRun {\n\trunId: string;\n\tgeneration: number;\n\tgoalId?: string;\n\tlastStatus?: GoalRunStatus;\n\tclosed: boolean;\n\tcancelRequested: boolean;\n\tcancelReason?: string;\n}\n\nexport function goalRunEventChannel(runId: string) {\n\treturn `pi-goal:event:${runId}`;\n}\n\nfunction isPayloadRecord(data: unknown): data is object {\n\tif (!data || typeof data !== \"object\") return false;\n\ttry {\n\t\treturn !Array.isArray(data);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction readPayloadProperty(\n\tdata: object,\n\tkey: \"runId\" | \"objective\" | \"tokenBudget\" | \"reason\",\n): { ok: true; value: unknown } | { ok: false } {\n\ttry {\n\t\treturn { ok: true, value: Reflect.get(data, key) };\n\t} catch {\n\t\treturn { ok: false };\n\t}\n}\n\nfunction parseRunId(data: unknown): string | undefined {\n\tif (!isPayloadRecord(data)) return undefined;\n\tconst runId = readPayloadProperty(data, \"runId\");\n\treturn runId.ok && typeof runId.value === \"string\" && RUN_ID_PATTERN.test(runId.value)\n\t\t? runId.value\n\t\t: undefined;\n}\n\nfunction currentActiveGoal(runtime: GoalRuntime) {\n\treturn runtime.activeGoal;\n}\n\nfunction parseStartPayload(data: unknown): string | Omit<GoalRunStartPayload, \"runId\"> {\n\tif (!isPayloadRecord(data)) return \"start payload must be an object\";\n\tconst objectiveValue = readPayloadProperty(data, \"objective\");\n\tif (!objectiveValue.ok || typeof objectiveValue.value !== \"string\") {\n\t\treturn \"objective must be a string\";\n\t}\n\tconst objective = objectiveValue.value.trim();\n\tconst objectiveError = validateObjective(objective);\n\tif (objectiveError) return objectiveError;\n\tconst tokenBudgetValue = readPayloadProperty(data, \"tokenBudget\");\n\tif (\n\t\t!tokenBudgetValue.ok ||\n\t\t(tokenBudgetValue.value !== undefined &&\n\t\t\t(typeof tokenBudgetValue.value !== \"number\" ||\n\t\t\t\t!Number.isFinite(tokenBudgetValue.value) ||\n\t\t\t\t!Number.isSafeInteger(tokenBudgetValue.value) ||\n\t\t\t\ttokenBudgetValue.value <= 0))\n\t) {\n\t\treturn \"tokenBudget must be a positive integer\";\n\t}\n\treturn { objective, tokenBudget: tokenBudgetValue.value as number | undefined };\n}\n\nfunction parseCancelReason(data: unknown): string | undefined | { error: string } {\n\tif (!isPayloadRecord(data)) return { error: \"cancel payload must be an object\" };\n\tconst reasonValue = readPayloadProperty(data, \"reason\");\n\tif (\n\t\t!reasonValue.ok ||\n\t\t(reasonValue.value !== undefined && typeof reasonValue.value !== \"string\")\n\t) {\n\t\treturn { error: \"reason must be a string\" };\n\t}\n\tif (reasonValue.value === undefined) return undefined;\n\tconst reason = reasonValue.value.trim();\n\tif (reason.length > MAX_CANCEL_REASON_LENGTH) {\n\t\treturn { error: `reason must be at most ${MAX_CANCEL_REASON_LENGTH} characters` };\n\t}\n\treturn reason || undefined;\n}\n\nexport class GoalRunController {\n\tprivate readonly runtime: GoalRuntime;\n\tprivate readonly commands: GoalCommandController;\n\tprivate generation = 0;\n\tprivate session?: BoundSession;\n\tprivate run?: ManagedRun;\n\tprivate readonly usedRunIds = new Set<string>();\n\n\tconstructor(runtime: GoalRuntime, commands: GoalCommandController) {\n\t\tthis.runtime = runtime;\n\t\tthis.commands = commands;\n\t\tthis.runtime.setGoalStateSink((snapshot) => this.handleGoalState(snapshot));\n\t}\n\n\tregister(pi: ExtensionAPI) {\n\t\tpi.events.on(GOAL_RUN_START_CHANNEL, (data) => this.handleStart(data));\n\t\tpi.events.on(GOAL_RUN_CANCEL_CHANNEL, (data) => {\n\t\t\tthis.handleCancel(data);\n\t\t});\n\t}\n\n\tbindSession(ctx: StatusContext) {\n\t\tthis.generation += 1;\n\t\tthis.session = { generation: this.generation, ctx };\n\t\tthis.closeCurrentRun();\n\t\tthis.usedRunIds.clear();\n\t}\n\n\tunbindSession() {\n\t\tthis.generation += 1;\n\t\tthis.session = undefined;\n\t\tthis.closeCurrentRun();\n\t\tthis.usedRunIds.clear();\n\t}\n\n\tprivate async handleStart(data: unknown) {\n\t\tconst runId = parseRunId(data);\n\t\tif (!runId) return;\n\t\tconst session = this.session;\n\t\tif (!session) {\n\t\t\tthis.emitError(runId, \"start\", \"NO_ACTIVE_SESSION\", \"No active pi-goal session.\");\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.settings.rpc.enabled) {\n\t\t\tthis.emitError(runId, \"start\", \"RPC_DISABLED\", \"Managed run RPC is disabled.\");\n\t\t\treturn;\n\t\t}\n\t\tif (this.usedRunIds.has(runId)) {\n\t\t\tthis.emitError(runId, \"start\", \"RUN_ID_IN_USE\", \"runId was already used in this session.\");\n\t\t\treturn;\n\t\t}\n\t\tconst parsed = parseStartPayload(data);\n\t\tif (typeof parsed === \"string\") {\n\t\t\tthis.emitError(runId, \"start\", \"INVALID_REQUEST\", parsed);\n\t\t\treturn;\n\t\t}\n\t\tif (this.session !== session || this.generation !== session.generation) {\n\t\t\tthis.emitError(\n\t\t\t\trunId,\n\t\t\t\t\"start\",\n\t\t\t\t\"SUPERSEDED\",\n\t\t\t\t\"The pi-goal session changed while validating the request.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (this.usedRunIds.has(runId)) {\n\t\t\tthis.emitError(runId, \"start\", \"RUN_ID_IN_USE\", \"runId was already used in this session.\");\n\t\t\treturn;\n\t\t}\n\t\tif (this.runtime.activeGoal || (this.run && !this.run.closed)) {\n\t\t\tthis.emitError(runId, \"start\", \"GOAL_ALREADY_EXISTS\", \"A Goal already exists.\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst run: ManagedRun = {\n\t\t\trunId,\n\t\t\tgeneration: session.generation,\n\t\t\tclosed: false,\n\t\t\tcancelRequested: false,\n\t\t};\n\t\tthis.run = run;\n\t\tthis.usedRunIds.add(runId);\n\n\t\ttry {\n\t\t\tconst activation = await this.commands.startGoal(\n\t\t\t\tparsed.objective,\n\t\t\t\tparsed.tokenBudget,\n\t\t\t\tsession.ctx,\n\t\t\t\t(goal) => {\n\t\t\t\t\tif (this.ownsRun(run, session.generation)) run.goalId = goal.id;\n\t\t\t\t},\n\t\t\t\t() => this.ownsRun(run, session.generation),\n\t\t\t);\n\t\t\tif (activation?.kind === \"busy\" && this.ownsRun(run, session.generation)) {\n\t\t\t\tthis.closeCurrentRun();\n\t\t\t\tthis.emitError(\n\t\t\t\t\trunId,\n\t\t\t\t\t\"start\",\n\t\t\t\t\t\"ACTIVATION_FAILED\",\n\t\t\t\t\t\"Another workflow is active in this session. End it before starting Goal.\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (this.ownsRun(run, session.generation)) {\n\t\t\t\tthis.closeCurrentRun();\n\t\t\t\tthis.emitError(\n\t\t\t\t\trunId,\n\t\t\t\t\t\"start\",\n\t\t\t\t\t\"ACTIVATION_FAILED\",\n\t\t\t\t\t`Goal activation failed: ${formatError(error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.ownsRun(run, session.generation)) return;\n\t\tif (!run.goalId) {\n\t\t\tthis.closeCurrentRun();\n\t\t\tthis.emitError(runId, \"start\", \"ACTIVATION_FAILED\", \"Goal activation did not create a Goal.\");\n\t\t\treturn;\n\t\t}\n\t\tif (currentActiveGoal(this.runtime)?.id !== run.goalId) {\n\t\t\tthis.closeCurrentRun();\n\t\t\tthis.emitError(runId, \"start\", \"SUPERSEDED\", \"The managed Goal was superseded.\");\n\t\t\treturn;\n\t\t}\n\t\tif (run.cancelRequested) this.cancelActiveRun(run, session, run.cancelReason);\n\t}\n\n\tprivate handleCancel(data: unknown) {\n\t\tconst runId = parseRunId(data);\n\t\tif (!runId) return;\n\t\tconst session = this.session;\n\t\tif (!session) {\n\t\t\tthis.emitError(runId, \"cancel\", \"NO_ACTIVE_SESSION\", \"No active pi-goal session.\");\n\t\t\treturn;\n\t\t}\n\t\tconst reason = parseCancelReason(data);\n\t\tif (reason && typeof reason === \"object\") {\n\t\t\tthis.emitError(runId, \"cancel\", \"INVALID_REQUEST\", reason.error);\n\t\t\treturn;\n\t\t}\n\t\tconst run = this.run;\n\t\tif (!run || run.closed || run.runId !== runId || run.generation !== session.generation) {\n\t\t\tthis.emitError(runId, \"cancel\", \"RUN_NOT_FOUND\", \"No active managed run matches runId.\");\n\t\t\treturn;\n\t\t}\n\t\tif (!run.goalId) {\n\t\t\trun.cancelRequested = true;\n\t\t\trun.cancelReason = reason;\n\t\t\treturn;\n\t\t}\n\t\tthis.cancelActiveRun(run, session, reason);\n\t}\n\n\tprivate cancelActiveRun(run: ManagedRun, session: BoundSession, reason: string | undefined) {\n\t\tif (!this.ownsRun(run, session.generation)) return;\n\t\tconst goal = this.runtime.activeGoal;\n\t\tif (!goal || goal.id !== run.goalId) {\n\t\t\tthis.closeCurrentRun();\n\t\t\tthis.emitError(run.runId, \"cancel\", \"SUPERSEDED\", \"The managed Goal was superseded.\");\n\t\t\treturn;\n\t\t}\n\t\tif (goal.status !== \"active\") {\n\t\t\tthis.closeCurrentRun();\n\t\t\tthis.emitError(run.runId, \"cancel\", \"RUN_NOT_FOUND\", \"The managed run is no longer active.\");\n\t\t\treturn;\n\t\t}\n\t\tthis.runtime.setTerminalReason(goal.id, reason ?? \"goal cancelled by managed run\");\n\t\tthis.commands.pauseGoal(session.ctx);\n\t}\n\n\tprivate handleGoalState(snapshot: GoalStateSnapshot) {\n\t\tconst run = this.run;\n\t\tif (!run || run.closed || !run.goalId) return;\n\t\tif (run.goalId !== snapshot.goalId) {\n\t\t\tif (currentActiveGoal(this.runtime)?.id !== snapshot.goalId) return;\n\t\t\tthis.publishStateEvent(run, {\n\t\t\t\tgoalId: run.goalId,\n\t\t\t\tstatus: \"cleared\",\n\t\t\t\treason: \"managed Goal superseded by another Goal\",\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (snapshot.status === \"queued\" || run.lastStatus === snapshot.status) return;\n\t\tthis.publishStateEvent(run, snapshot);\n\t}\n\n\tprivate publishStateEvent(\n\t\trun: ManagedRun,\n\t\tsnapshot: Pick<GoalStateSnapshot, \"goalId\" | \"status\" | \"summary\" | \"reason\">,\n\t) {\n\t\tconst status = snapshot.status;\n\t\tif (status === \"queued\") return;\n\t\trun.lastStatus = status;\n\t\tconst event: GoalRunEvent = {\n\t\t\ttype: \"state\",\n\t\t\trunId: run.runId,\n\t\t\tgoalId: snapshot.goalId,\n\t\t\tstatus,\n\t\t\t...(snapshot.summary ? { summary: snapshot.summary } : {}),\n\t\t\t...(snapshot.reason ? { reason: snapshot.reason } : {}),\n\t\t};\n\t\tif (!isTerminalGoalStatus(status)) {\n\t\t\tthis.runtime.pi.events.emit(goalRunEventChannel(run.runId), event);\n\t\t\treturn;\n\t\t}\n\n\t\trun.closed = true;\n\t\tthis.run = undefined;\n\t\tconst generation = run.generation;\n\t\t// Active stays synchronous so a listener can cancel before kickoff. Terminal\n\t\t// publication waits until the transition finishes, preventing listener work\n\t\t// from being overwritten by the old transition's remaining UI or cleanup.\n\t\tqueueMicrotask(() => {\n\t\t\tif (this.generation !== generation) return;\n\t\t\tthis.runtime.pi.events.emit(goalRunEventChannel(run.runId), event);\n\t\t});\n\t}\n\n\tprivate emitError(\n\t\trunId: string,\n\t\toperation: \"start\" | \"cancel\",\n\t\tcode: GoalRunErrorCode,\n\t\tmessage: string,\n\t) {\n\t\tthis.runtime.pi.events.emit(goalRunEventChannel(runId), {\n\t\t\ttype: \"error\",\n\t\t\trunId,\n\t\t\toperation,\n\t\t\terror: { code, message },\n\t\t} satisfies GoalRunEvent);\n\t}\n\n\tprivate ownsRun(run: ManagedRun, generation: number) {\n\t\treturn (\n\t\t\tthis.session?.generation === generation &&\n\t\t\tthis.generation === generation &&\n\t\t\tthis.run === run &&\n\t\t\t!run.closed\n\t\t);\n\t}\n\n\tprivate closeCurrentRun() {\n\t\tif (this.run) this.run.closed = true;\n\t\tthis.run = undefined;\n\t}\n}\n", "import {\n\tDEFAULT_MAX_BYTES,\n\tDEFAULT_MAX_LINES,\n\tdefineTool,\n\ttype ExtensionAPI,\n\ttruncateHead,\n} from \"@earendil-works/pi-coding-agent\";\nimport { Type } from \"typebox\";\nimport { notifyTerminal, safeTerminalText } from \"./errors.js\";\nimport {\n\tformatStatus,\n\tGOAL_BLOCKED_TOOL,\n\tGOAL_COMPLETE_TOOL,\n\tGOAL_WAIT_TOOL,\n\ttype GoalRuntime,\n\tgoalIdRejectionReason,\n\tisContradictoryCompletionSummary,\n\tMAX_GOAL_ID_LENGTH,\n\tSTATUS_KEY,\n\ttransitionGoal,\n\ttruncateNotification,\n} from \"./runtime.js\";\nimport {\n\tcreateGoalWait,\n\tMAX_GOAL_WAIT_DELAY_MS,\n\tMAX_GOAL_WAIT_REASON_LENGTH,\n\tMIN_GOAL_WAIT_DELAY_MS,\n\tresolveGoalWaitDelay,\n} from \"./wait.js\";\n\ninterface GoalCompleteDetails {\n\tgoal: string;\n\tgoal_id: string;\n\tsummary: string;\n}\n\ninterface GoalBlockedDetails {\n\tgoal: string;\n\tgoal_id: string;\n\treason: string;\n\tevidence: string;\n\trepeated_turns: number;\n}\n\ninterface GoalWaitDetails {\n\tgoal: string;\n\tgoal_id: string;\n\treason: string;\n\trequested_resume_after_ms?: number;\n\tresume_after_ms?: number;\n\tresume_at?: number;\n}\n\nconst MAX_GOAL_TEXT_LENGTH = 4_000;\nconst MAX_COMPLETION_SUMMARY_LENGTH = 4_000;\nconst MAX_BLOCKER_REASON_LENGTH = 1_000;\nconst MAX_BLOCKER_EVIDENCE_LENGTH = 4_000;\n\nexport function registerGoalTools(pi: ExtensionAPI, runtime: GoalRuntime) {\n\tconst goalCompleteTool = defineTool({\n\t\tname: GOAL_COMPLETE_TOOL,\n\t\tlabel: \"Goal Complete\",\n\t\tdescription:\n\t\t\t\"Mark an active /goal complete only when the latest effective Goal contract explicitly says Goal mode is active, supplies the matching current goal_id, and every requirement is verified. Tool visibility alone does not activate Goal mode. Never call for ordinary work, partial progress, blockers, failures, or unverified work.\",\n\t\tparameters: Type.Object({\n\t\t\tgoal_id: Type.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tmaxLength: MAX_GOAL_ID_LENGTH,\n\t\t\t\tdescription:\n\t\t\t\t\t\"The exact goal_id shown in the current active /goal prompt. Used only to reject stale completion calls from older turns.\",\n\t\t\t}),\n\t\t\tsummary: Type.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tmaxLength: MAX_COMPLETION_SUMMARY_LENGTH,\n\t\t\t\tdescription:\n\t\t\t\t\t\"State what was completed and what evidence verified it. Do not use this tool to report partial progress, blockers, failures, or remaining work.\",\n\t\t\t}),\n\t\t}),\n\t\tasync execute(_toolCallId, params, _signal, _onUpdate, ctx) {\n\t\t\tconst completedGoal = runtime.activeGoal;\n\t\t\tconst goal = completedGoal?.text ?? \"unknown goal\";\n\t\t\tconst requestedGoalId = typeof params.goal_id === \"string\" ? params.goal_id.trim() : \"\";\n\t\t\tconst summary = typeof params.summary === \"string\" ? params.summary.trim() : \"\";\n\n\t\t\tif (!completedGoal) {\n\t\t\t\tconst rejection = \"Goal completion rejected: no active goal.\";\n\t\t\t\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst completingDuringBudgetWrapUp = runtime.hasActiveBudgetWrapUp();\n\t\t\tif (completedGoal.status === \"active\" && !runtime.ownsWorkflow(completedGoal)) {\n\t\t\t\tconst rejection = \"Goal completion rejected: active Goal no longer owns its workflow.\";\n\t\t\t\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (!runtime.canRecordGoalUsage() && !completingDuringBudgetWrapUp) {\n\t\t\t\tconst rejection = \"Goal completion rejected: current run does not own the active goal.\";\n\t\t\t\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst staleGoalRejection = goalIdRejectionReason(completedGoal, requestedGoalId);\n\t\t\tif (staleGoalRejection) {\n\t\t\t\tconst rejection = `Goal completion rejected: ${staleGoalRejection}.`;\n\t\t\t\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\t\t\t\tif (completingDuringBudgetWrapUp) {\n\t\t\t\t\truntime.recordGoalUsage(completedGoal, ctx);\n\t\t\t\t\truntime.persistGoal(completedGoal);\n\t\t\t\t\truntime.updateStatus(ctx, completedGoal);\n\t\t\t\t\truntime.clearBudgetWrapUp();\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\n\t\t\t\t\tterminate: completingDuringBudgetWrapUp || undefined,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (completedGoal.status !== \"active\" && !completingDuringBudgetWrapUp) {\n\t\t\t\tconst rejection = `Goal completion rejected: goal is ${completedGoal.status}, not active.`;\n\t\t\t\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst rejectionReason = !summary\n\t\t\t\t? \"summary is empty\"\n\t\t\t\t: summary.length > MAX_COMPLETION_SUMMARY_LENGTH\n\t\t\t\t\t? \"summary is too long\"\n\t\t\t\t\t: isContradictoryCompletionSummary(summary)\n\t\t\t\t\t\t? \"summary says the goal is not complete\"\n\t\t\t\t\t\t: undefined;\n\t\t\tif (rejectionReason) {\n\t\t\t\truntime.recordGoalUsage(completedGoal, ctx);\n\t\t\t\truntime.persistGoal(completedGoal);\n\t\t\t\truntime.updateStatus(ctx, completedGoal);\n\t\t\t\tconst rejection = `Goal completion rejected: ${rejectionReason}.`;\n\t\t\t\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\t\t\t\tif (completingDuringBudgetWrapUp) runtime.clearBudgetWrapUp();\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\n\t\t\t\t\tterminate: completingDuringBudgetWrapUp || undefined,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\truntime.clearGoalWaitTimer();\n\t\t\truntime.activeGoal = transitionGoal(completedGoal, \"complete\");\n\t\t\truntime.setCompletionSummary(runtime.activeGoal.id, summary);\n\t\t\truntime.recordGoalUsage(runtime.activeGoal, ctx);\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\n\t\t\tctx.ui.setStatus(STATUS_KEY, formatStatus(runtime.activeGoal));\n\t\t\truntime.clearCompletedGoal(ctx);\n\t\t\truntime.showCompletionStatus(ctx);\n\t\t\tnotifyTerminal(ctx.ui, `Goal complete: ${goal}`, \"info\");\n\n\t\t\treturn {\n\t\t\t\tcontent: toolContent(`Goal complete: ${summary}`),\n\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\n\t\t\t\tterminate: true,\n\t\t\t};\n\t\t},\n\t});\n\n\tconst goalBlockedTool = defineTool({\n\t\tname: GOAL_BLOCKED_TOOL,\n\t\tlabel: \"Goal Blocked\",\n\t\tdescription:\n\t\t\t\"Stop an active /goal only when the latest effective Goal contract explicitly says Goal mode is active, supplies the matching current goal_id, and the same evidenced external blocker recurred for at least three consecutive Goal turns. Tool visibility alone does not activate Goal mode. Never call for ordinary clarification, uncertainty, incomplete work, or recoverable failures.\",\n\t\tparameters: Type.Object({\n\t\t\tgoal_id: Type.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tmaxLength: MAX_GOAL_ID_LENGTH,\n\t\t\t\tdescription: \"The exact goal_id shown in the current active /goal prompt.\",\n\t\t\t}),\n\t\t\treason: Type.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tmaxLength: MAX_BLOCKER_REASON_LENGTH,\n\t\t\t\tdescription: \"The specific user or external action required to unblock the goal.\",\n\t\t\t}),\n\t\t\tevidence: Type.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tmaxLength: MAX_BLOCKER_EVIDENCE_LENGTH,\n\t\t\t\tdescription: \"Concrete evidence from the repeated attempts that proves the impasse.\",\n\t\t\t}),\n\t\t\trepeated_turns: Type.Integer({\n\t\t\t\tminimum: 3,\n\t\t\t\tdescription: \"Number of separate turns spent trying to resolve this same blocker.\",\n\t\t\t}),\n\t\t}),\n\t\tasync execute(_toolCallId, params, _signal, _onUpdate, ctx) {\n\t\t\tconst blockedGoal = runtime.activeGoal;\n\t\t\tconst goal = blockedGoal?.text ?? \"unknown goal\";\n\t\t\tconst requestedGoalId = typeof params.goal_id === \"string\" ? params.goal_id.trim() : \"\";\n\t\t\tconst reason = typeof params.reason === \"string\" ? params.reason.trim() : \"\";\n\t\t\tconst evidence = typeof params.evidence === \"string\" ? params.evidence.trim() : \"\";\n\t\t\tconst repeatedTurns =\n\t\t\t\ttypeof params.repeated_turns === \"number\" ? params.repeated_turns : Number.NaN;\n\t\t\tconst reject = (rejectionReason: string, terminate = false) => {\n\t\t\t\tconst rejection = `goal_blocked rejected: ${rejectionReason}.`;\n\t\t\t\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: blockerDetails(goal, requestedGoalId, reason, evidence, repeatedTurns),\n\t\t\t\t\t...(terminate ? { terminate: true as const } : {}),\n\t\t\t\t};\n\t\t\t};\n\n\t\t\tif (!blockedGoal) return reject(\"no active goal\");\n\t\t\tif (!runtime.canRecordGoalUsage()) {\n\t\t\t\treturn reject(\"current run does not own the active goal\");\n\t\t\t}\n\t\t\tconst staleGoalRejection = goalIdRejectionReason(blockedGoal, requestedGoalId);\n\t\t\tif (staleGoalRejection) return reject(staleGoalRejection);\n\t\t\tif (blockedGoal.status !== \"active\") {\n\t\t\t\treturn reject(`goal is ${blockedGoal.status}, not active`);\n\t\t\t}\n\t\t\tif (!runtime.ownsWorkflow(blockedGoal))\n\t\t\t\treturn reject(\"active Goal no longer owns its workflow\");\n\t\t\tif (!reason) return reject(\"reason is empty\");\n\t\t\tif (reason.length > MAX_BLOCKER_REASON_LENGTH) return reject(\"reason is too long\");\n\t\t\tif (!evidence) return reject(\"evidence is empty\");\n\t\t\tif (evidence.length > MAX_BLOCKER_EVIDENCE_LENGTH) return reject(\"evidence is too long\");\n\t\t\tif (!Number.isInteger(repeatedTurns)) return reject(\"repeated_turns must be a whole number\");\n\t\t\tif (repeatedTurns < 3) return reject(\"repeated_turns must be at least 3\");\n\n\t\t\tconst stoppedGoal = runtime.stopActiveGoal(ctx, {\n\t\t\t\tkind: \"blocker_report\",\n\t\t\t\texpectedGoalId: blockedGoal.id,\n\t\t\t\treason,\n\t\t\t});\n\t\t\tif (!stoppedGoal) return reject(\"active goal changed before blocker transition\");\n\t\t\tnotifyTerminal(ctx.ui, `Goal blocked: ${truncateNotification(reason)}`, \"warning\");\n\n\t\t\treturn {\n\t\t\t\tcontent: toolContent(`Goal blocked: ${reason}`),\n\t\t\t\tdetails: blockerDetails(goal, requestedGoalId, reason, evidence, repeatedTurns),\n\t\t\t\tterminate: true,\n\t\t\t};\n\t\t},\n\t});\n\n\tconst goalWaitTool = defineTool({\n\t\tname: GOAL_WAIT_TOOL,\n\t\tlabel: \"Goal Wait\",\n\t\tdescription: `Keep an active /goal quiet only when the latest effective Goal contract explicitly says Goal mode is active, supplies the matching current goal_id, and progress depends on an arranged external wake event or one safety deadline. Tool visibility alone does not activate Goal mode. Call goal_wait alone. Requests below ${MIN_GOAL_WAIT_DELAY_MS}ms are clamped to ${MIN_GOAL_WAIT_DELAY_MS}ms. Never call for ordinary unfinished work.`,\n\t\tparameters: Type.Object({\n\t\t\tgoal_id: Type.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tmaxLength: MAX_GOAL_ID_LENGTH,\n\t\t\t\tdescription: \"The exact goal_id shown in the current active /goal prompt.\",\n\t\t\t}),\n\t\t\treason: Type.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tmaxLength: MAX_GOAL_WAIT_REASON_LENGTH,\n\t\t\t\tdescription: \"Why the goal is waiting and which external event should wake it.\",\n\t\t\t}),\n\t\t\tresume_after_ms: Type.Optional(\n\t\t\t\tType.Integer({\n\t\t\t\t\tminimum: 1,\n\t\t\t\t\tmaximum: MAX_GOAL_WAIT_DELAY_MS,\n\t\t\t\t\tdescription: `Optional safety deadline in milliseconds that requests one continuation if no wake message arrives. Values below ${MIN_GOAL_WAIT_DELAY_MS} are accepted but clamped to ${MIN_GOAL_WAIT_DELAY_MS}.`,\n\t\t\t\t}),\n\t\t\t),\n\t\t}),\n\t\tasync execute(_toolCallId, params, _signal, _onUpdate, ctx) {\n\t\t\tconst activeGoal = runtime.activeGoal;\n\t\t\tconst goal = activeGoal?.text ?? \"unknown goal\";\n\t\t\tconst requestedGoalId = typeof params.goal_id === \"string\" ? params.goal_id.trim() : \"\";\n\t\t\tconst reason = typeof params.reason === \"string\" ? params.reason.trim() : \"\";\n\t\t\tconst resumeAfterMs =\n\t\t\t\ttypeof params.resume_after_ms === \"number\" ? params.resume_after_ms : undefined;\n\t\t\tconst reject = (rejectionReason: string) => {\n\t\t\t\tconst rejection = `goal_wait rejected: ${rejectionReason}.`;\n\t\t\t\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: waitDetails(goal, requestedGoalId, reason, resumeAfterMs),\n\t\t\t\t};\n\t\t\t};\n\n\t\t\tif (!activeGoal) return reject(\"no active goal\");\n\t\t\tif (!runtime.canRecordGoalUsage()) {\n\t\t\t\treturn reject(\"current run does not own the active goal\");\n\t\t\t}\n\t\t\tconst staleGoalRejection = goalIdRejectionReason(activeGoal, requestedGoalId);\n\t\t\tif (staleGoalRejection) return reject(staleGoalRejection);\n\t\t\tif (activeGoal.status !== \"active\") {\n\t\t\t\treturn reject(`goal is ${activeGoal.status}, not active`);\n\t\t\t}\n\t\t\tif (!runtime.ownsWorkflow(activeGoal))\n\t\t\t\treturn reject(\"active Goal no longer owns its workflow\");\n\t\t\tif (activeGoal.waiting) return reject(\"goal is already waiting\");\n\t\t\tif (!reason) return reject(\"reason is empty\");\n\t\t\tif (reason.length > MAX_GOAL_WAIT_REASON_LENGTH) return reject(\"reason is too long\");\n\t\t\tif (\n\t\t\t\tresumeAfterMs !== undefined &&\n\t\t\t\t(!Number.isInteger(resumeAfterMs) ||\n\t\t\t\t\tresumeAfterMs < 1 ||\n\t\t\t\t\tresumeAfterMs > MAX_GOAL_WAIT_DELAY_MS)\n\t\t\t) {\n\t\t\t\treturn reject(`resume_after_ms must be a whole number from 1 to ${MAX_GOAL_WAIT_DELAY_MS}`);\n\t\t\t}\n\n\t\t\tconst { requestedMs, effectiveMs } = resolveGoalWaitDelay(resumeAfterMs);\n\t\t\tconst waiting = createGoalWait(reason, resumeAfterMs);\n\t\t\tconst waitingGoal = runtime.enterGoalWait(ctx, activeGoal.id, waiting);\n\t\t\tif (!waitingGoal) return reject(\"active goal changed before waiting transition\");\n\t\t\tconst clamped = requestedMs !== undefined && effectiveMs !== requestedMs;\n\t\t\tnotifyTerminal(ctx.ui, `Goal waiting: ${truncateNotification(reason)}`, \"info\");\n\t\t\treturn {\n\t\t\t\tcontent: toolContent(\n\t\t\t\t\tclamped\n\t\t\t\t\t\t? `Goal waiting: ${reason}\\nRequested resume_after_ms ${requestedMs} was clamped to ${effectiveMs}.`\n\t\t\t\t\t\t: `Goal waiting: ${reason}`,\n\t\t\t\t),\n\t\t\t\tdetails: waitDetails(\n\t\t\t\t\tgoal,\n\t\t\t\t\trequestedGoalId,\n\t\t\t\t\treason,\n\t\t\t\t\teffectiveMs,\n\t\t\t\t\twaiting.resumeAt,\n\t\t\t\t\tclamped ? requestedMs : undefined,\n\t\t\t\t),\n\t\t\t\tterminate: true,\n\t\t\t};\n\t\t},\n\t});\n\n\tpi.registerTool(goalCompleteTool);\n\tpi.registerTool(goalBlockedTool);\n\tpi.registerTool(goalWaitTool);\n}\n\nfunction toolContent(text: string) {\n\treturn [\n\t\t{\n\t\t\ttype: \"text\" as const,\n\t\t\ttext: truncateHead(safeTerminalText(text), {\n\t\t\t\tmaxBytes: DEFAULT_MAX_BYTES,\n\t\t\t\tmaxLines: DEFAULT_MAX_LINES,\n\t\t\t}).content,\n\t\t},\n\t];\n}\n\nfunction completionDetails(goal: string, goalId: string, summary: string): GoalCompleteDetails {\n\treturn {\n\t\tgoal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),\n\t\tgoal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),\n\t\tsummary: summary.slice(0, MAX_COMPLETION_SUMMARY_LENGTH),\n\t};\n}\n\nfunction blockerDetails(\n\tgoal: string,\n\tgoalId: string,\n\treason: string,\n\tevidence: string,\n\trepeatedTurns: number,\n): GoalBlockedDetails {\n\treturn {\n\t\tgoal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),\n\t\tgoal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),\n\t\treason: reason.slice(0, MAX_BLOCKER_REASON_LENGTH),\n\t\tevidence: evidence.slice(0, MAX_BLOCKER_EVIDENCE_LENGTH),\n\t\trepeated_turns: Number.isFinite(repeatedTurns) ? repeatedTurns : 0,\n\t};\n}\n\nfunction waitDetails(\n\tgoal: string,\n\tgoalId: string,\n\treason: string,\n\tresumeAfterMs: number | undefined,\n\tresumeAt?: number,\n\trequestedResumeAfterMs?: number,\n): GoalWaitDetails {\n\treturn {\n\t\tgoal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),\n\t\tgoal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),\n\t\treason: reason.slice(0, MAX_GOAL_WAIT_REASON_LENGTH),\n\t\t...(requestedResumeAfterMs === undefined\n\t\t\t? {}\n\t\t\t: { requested_resume_after_ms: requestedResumeAfterMs }),\n\t\t...(resumeAfterMs === undefined ? {} : { resume_after_ms: resumeAfterMs }),\n\t\t...(resumeAt === undefined ? {} : { resume_at: resumeAt }),\n\t};\n}\n", "import type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport { registerGoalCommand } from \"./command-registration.js\";\nimport { GoalCommandController } from \"./commands.js\";\nimport { registerGoalLifecycle } from \"./lifecycle.js\";\nimport { GoalRunController } from \"./run-protocol.js\";\nimport { GoalRuntime } from \"./runtime.js\";\nimport { registerGoalTools } from \"./tools.js\";\n\ninterface GoalOptions {\n\tsettingsPath?: string;\n}\n\nfunction registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {\n\tconst runtime = new GoalRuntime(pi);\n\tconst commands = new GoalCommandController(runtime);\n\tconst runController = new GoalRunController(runtime, commands);\n\n\t// Keep registration order explicit: managed-run bus listeners exist before tools,\n\t// command routing, and session lifecycle bind the per-factory runtime.\n\trunController.register(pi);\n\tregisterGoalTools(pi, runtime);\n\tregisterGoalCommand(pi, runtime, commands, options);\n\tregisterGoalLifecycle(pi, runtime, runController, options);\n}\n\nexport default function goal(pi: ExtensionAPI, options: GoalOptions = {}) {\n\tregisterGoalRuntime(pi, options);\n}\n\nexport {\n\tassistantUsageTokens,\n\tcumulativeAssistantTokens,\n\tformatDuration,\n\tformatTokenCount,\n} from \"./accounting.js\";\n\nexport {\n\tcompleteGoalArguments,\n\tparseCommand,\n\tparseTokenBudget,\n\tvalidateObjective,\n} from \"./command.js\";\n\nexport { buildGoalSystemPrompt } from \"./prompts.js\";\n\nexport {\n\tfindFinalAssistantMessage,\n\tformatStatus,\n\tisContradictoryCompletionSummary,\n\tisRetryableGoalInterruption,\n\tisUsageLimitedGoalInterruption,\n} from \"./runtime.js\";\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;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AAsB,OAAO;AAClD,QAAM,gBAAgB,IAAI,kBAAkB,SAAS,QAAQ;AAI7D,gBAAc,SAAS,EAAE;AACzB,oBAAkB,IAAI,OAAO;AAC7B,sBAAoB,IAAI,SAAS,UAAU,OAAO;AAClD,wBAAsB,IAAI,SAAS,eAAe,OAAO;AAC1D;AAEe,SAAR,KAAsB,IAAkB,UAAuB,CAAC,GAAG;AACzE,sBAAoB,IAAI,OAAO;AAChC;",
|
|
4
|
+
"sourcesContent": ["import type { ExtensionAPI, ExtensionCommandContext } from \"@earendil-works/pi-coding-agent\";\nimport { completeGoalArguments, isRemovedQueueCommand, parseCommand } from \"./command.js\";\nimport type { GoalCommandController } from \"./commands.js\";\nimport { notifyTerminal, safeTerminalText } from \"./errors.js\";\nimport type { GoalRuntime } from \"./runtime.js\";\n\ntype GoalManagerModule = Pick<typeof import(\"./menu.js\"), \"showGoalManager\">;\ntype GoalSettingsModule = Pick<typeof import(\"./settings-ui.js\"), \"showGoalSettings\">;\n\nexport interface GoalCommandRegistrationOptions {\n\tsettingsPath?: string;\n\tloadGoalManager?: () => Promise<GoalManagerModule>;\n\tloadGoalSettings?: () => Promise<GoalSettingsModule>;\n}\n\nexport function registerGoalCommand(\n\tpi: ExtensionAPI,\n\truntime: GoalRuntime,\n\tcommands: GoalCommandController,\n\toptions: GoalCommandRegistrationOptions = {},\n) {\n\tconst loadGoalManager = cachedModuleLoader(\n\t\toptions.loadGoalManager ?? (() => import(\"./menu.js\")),\n\t);\n\tconst loadGoalSettings = cachedModuleLoader(\n\t\toptions.loadGoalSettings ?? (() => import(\"./settings-ui.js\")),\n\t);\n\n\tpi.registerCommand(\"goal\", {\n\t\tdescription: \"Run a goal to completion: /goal [--tokens 100k] <goal_to_complete>\",\n\t\tgetArgumentCompletions: (prefix) => completeGoalArguments(prefix),\n\t\thandler: async (args, ctx) => {\n\t\t\tif (runtime.hasLegacyQueueInterface() && isRemovedQueueCommand(args)) {\n\t\t\t\treportRemovedQueueCommand(ctx, runtime);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst result = parseCommand(args);\n\t\t\tif (typeof result === \"string\") {\n\t\t\t\treportCommandError(result, ctx);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (result.kind === \"show\" && args.trim() === \"\") {\n\t\t\t\tconst menuIsCurrent = captureMenuOwnership(runtime);\n\t\t\t\tlet managerModule: GoalManagerModule;\n\t\t\t\ttry {\n\t\t\t\t\tmanagerModule = await loadGoalManager();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!menuIsCurrent()) return;\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tif (!menuIsCurrent()) return;\n\t\t\t\tconst { showGoalManager } = managerModule;\n\t\t\t\tawait showGoalManager(runtime, commands, ctx, async (menuCtx, target) => {\n\t\t\t\t\tconst settingsAreCurrent = captureMenuOwnership(runtime);\n\t\t\t\t\tlet settingsModule: GoalSettingsModule;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsettingsModule = await loadGoalSettings();\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!settingsAreCurrent()) return;\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t\tif (!settingsAreCurrent()) return;\n\t\t\t\t\tconst { showGoalSettings } = settingsModule;\n\t\t\t\t\tawait showGoalSettings(runtime, menuCtx, {\n\t\t\t\t\t\tsettingsPath: options.settingsPath,\n\t\t\t\t\t\tinitialScreen: target,\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tswitch (result.kind) {\n\t\t\t\tcase \"show\":\n\t\t\t\t\tcommands.showGoal(ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"pause\":\n\t\t\t\t\tcommands.pauseGoal(ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"resume\":\n\t\t\t\t\tawait commands.resumeGoal(ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"clear\":\n\t\t\t\t\tcommands.clearGoal(ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"edit\":\n\t\t\t\t\tawait commands.editGoal(result.objective ?? \"\", result.tokenBudget, ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"start\":\n\t\t\t\t\tawait commands.startGoal(result.objective ?? \"\", result.tokenBudget, ctx);\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t},\n\t});\n}\n\nfunction reportCommandError(message: string, ctx: ExtensionCommandContext) {\n\tconst safeMessage = safeTerminalText(message);\n\tif (ctx.mode === \"print\" || ctx.mode === \"json\") throw new Error(safeMessage);\n\tnotifyTerminal(ctx.ui, safeMessage, \"warning\");\n}\n\nfunction reportRemovedQueueCommand(ctx: ExtensionCommandContext, runtime: GoalRuntime) {\n\tconst message = runtime.activeGoal\n\t\t? \"Ordered goal queue has been removed. Use /goal edit to reprioritize the active objective instead.\"\n\t\t: \"Ordered goal queue has been removed. Start /goal <objectives> to continue with one merged objective, or use /goal clear to discard the old queue state.\";\n\tif (ctx.mode === \"print\" || ctx.mode === \"json\") throw new Error(message);\n\tnotifyTerminal(ctx.ui, message, \"warning\");\n}\n\nfunction captureMenuOwnership(runtime: GoalRuntime): () => boolean {\n\tconst generation = runtime.menuGeneration;\n\tconst controller = runtime.menuController;\n\treturn () =>\n\t\truntime.menuGeneration === generation &&\n\t\truntime.menuController === controller &&\n\t\t!controller.signal.aborted;\n}\n\nfunction cachedModuleLoader<Module>(load: () => Promise<Module>): () => Promise<Module> {\n\tlet pending: Promise<Module> | undefined;\n\treturn () => {\n\t\tif (!pending) {\n\t\t\tpending = load().catch((error) => {\n\t\t\t\tpending = undefined;\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t}\n\t\treturn pending;\n\t};\n}\n", "import { currentTokenTotal, formatTokenCount } from \"./accounting.js\";\nimport { validateObjective } from \"./command.js\";\nimport { notifyTerminal, safeGoalMenuText } from \"./errors.js\";\nimport type { ActiveGoal } from \"./persistence.js\";\nimport {\n\tbuildGoalPrompt,\n\tbuildObjectiveUpdatedPrompt,\n\tbuildResumePrompt,\n\tbuildWaitingResumePrompt,\n} from \"./prompts.js\";\nimport {\n\tblocksStaleGoalToolCalls,\n\tcreateGoal,\n\teditedGoalStatus,\n\tformatBudget,\n\tformatError,\n\ttype GoalRuntime,\n\tgoalSummary,\n\tisResumableGoalStatus,\n\tnextGoalInstance,\n\tqueueGoalSafetyReset,\n\tSTATUS_KEY,\n\ttype StatusContext,\n\tstoppedStatusLabel,\n\ttransitionGoal,\n} from \"./runtime.js\";\n\n// User-command mutations are kept separate from Pi event wiring. Every controller\n// receives exactly one per-factory GoalRuntime, preserving session isolation.\nexport class GoalCommandController {\n\tprivate readonly runtime: GoalRuntime;\n\n\tconstructor(runtime: GoalRuntime) {\n\t\tthis.runtime = runtime;\n\t}\n\n\tasync startGoal(\n\t\tobjective: string,\n\t\ttokenBudget: number | undefined,\n\t\tctx: StatusContext,\n\t\tonActivated?: (goal: ActiveGoal) => void,\n\t\tisActivationCurrent?: (goal: ActiveGoal) => boolean,\n\t\tisRequestCurrent?: () => boolean,\n\t) {\n\t\tif (isRequestCurrent && !isRequestCurrent()) return;\n\t\tconst validationError = validateObjective(objective);\n\t\tif (validationError) {\n\t\t\tnotifyTerminal(ctx.ui, validationError, \"warning\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst existingGoal =\n\t\t\tthis.runtime.activeGoal?.status !== \"complete\" ? this.runtime.activeGoal : undefined;\n\t\tconst legacyQueueBeforeActivation = existingGoal\n\t\t\t? undefined\n\t\t\t: this.runtime.legacyQueueState\n\t\t\t\t? structuredClone(this.runtime.legacyQueueState)\n\t\t\t\t: undefined;\n\t\tif (existingGoal) {\n\t\t\tconst shouldReplace = await ctx.ui.confirm(\n\t\t\t\t\"Replace goal?\",\n\t\t\t\t`Current goal: ${safeGoalMenuText(existingGoal.text, 4_000)}\\n\\nNew goal: ${safeGoalMenuText(objective, 4_000)}`,\n\t\t\t);\n\t\t\tif (!shouldReplace) {\n\t\t\t\tnotifyTerminal(ctx.ui, `Goal kept: ${existingGoal.text}`, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (isRequestCurrent && !isRequestCurrent()) return;\n\t\t\tif (this.runtime.activeGoal?.id !== existingGoal.id) {\n\t\t\t\tnotifyTerminal(\n\t\t\t\t\tctx.ui,\n\t\t\t\t\t\"The active goal changed while confirmation was open. Try again.\",\n\t\t\t\t\t\"warning\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t// Tool registration keeps the Goal schema stable. A missing tool means another\n\t\t// policy or allowlist intentionally removed it, so activation must not widen it.\n\t\tif (isRequestCurrent && !isRequestCurrent()) return;\n\t\tconst retainedOwner = this.runtime.ownsWorkflow(existingGoal);\n\t\tif (!this.runtime.acquireWorkflow(ctx.sessionManager)) return this.reportWorkflowBusy(ctx);\n\t\tconst acquiredForRequest = !retainedOwner;\n\t\ttry {\n\t\t\tthis.runtime.assertGoalToolsAvailable();\n\t\t} catch (error) {\n\t\t\tnotifyTerminal(ctx.ui, `Cannot start /goal: ${formatError(error)}`, \"error\");\n\t\t\tif (existingGoal?.status === \"active\") this.runtime.pauseGoalForUnavailableTools(ctx);\n\t\t\telse if (acquiredForRequest) this.runtime.releaseWorkflow();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.runtime.clearGoalWaitTimer();\n\t\tthis.runtime.cancelContinuationWork();\n\t\tthis.runtime.clearGoalRecovery();\n\t\tthis.runtime.clearBudgetWrapUp();\n\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\tif (!legacyQueueBeforeActivation) this.runtime.legacyQueueState = undefined;\n\t\tthis.runtime.activeGoal = createGoal(objective, tokenBudget, currentTokenTotal(ctx));\n\t\tconst startedGoal = this.runtime.activeGoal;\n\t\tonActivated?.(startedGoal);\n\t\tif (!legacyQueueBeforeActivation) this.runtime.persistGoal(startedGoal);\n\t\tif (\n\t\t\tthis.runtime.activeGoal?.id !== startedGoal.id ||\n\t\t\t!this.runtime.ownsWorkflow(this.runtime.activeGoal)\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tthis.runtime.updateStatus(ctx, startedGoal);\n\t\tconst sent = await this.runtime.sendOwnedGoalPrompt(\n\t\t\tctx,\n\t\t\tstartedGoal.id,\n\t\t\tbuildGoalPrompt(startedGoal),\n\t\t\ttrue,\n\t\t\t() => (isRequestCurrent?.() ?? true) && (isActivationCurrent?.(startedGoal) ?? true),\n\t\t);\n\t\tif (\n\t\t\tsent &&\n\t\t\tlegacyQueueBeforeActivation &&\n\t\t\tthis.runtime.activeGoal?.id === startedGoal.id &&\n\t\t\tthis.runtime.activeGoal.status === \"active\"\n\t\t) {\n\t\t\tthis.runtime.legacyQueueState = undefined;\n\t\t\tthis.runtime.persistGoal(startedGoal);\n\t\t}\n\t\tif (isActivationCurrent && !isActivationCurrent(startedGoal)) return;\n\t\tif (!sent) {\n\t\t\tlet rolledBackStartedGoal = false;\n\t\t\tif (this.runtime.activeGoal?.id === startedGoal.id) {\n\t\t\t\trolledBackStartedGoal = true;\n\t\t\t\tif (existingGoal) {\n\t\t\t\t\tthis.runtime.recordGoalUsage(existingGoal, ctx);\n\t\t\t\t\tif (existingGoal.status === \"active\" && existingGoal.waiting) {\n\t\t\t\t\t\tthis.runtime.activeGoal = existingGoal;\n\t\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\t\tthis.runtime.persistGoal(existingGoal);\n\t\t\t\t\t\tthis.runtime.updateStatus(ctx, existingGoal);\n\t\t\t\t\t\tthis.runtime.restoreGoalWaitTimer(ctx);\n\t\t\t\t\t} else if (existingGoal.status === \"active\") {\n\t\t\t\t\t\tthis.runtime.activeGoal = existingGoal;\n\t\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\t\tthis.runtime.persistGoal(existingGoal);\n\t\t\t\t\t\tif (this.runtime.activeGoal?.id === existingGoal.id) {\n\t\t\t\t\t\t\tthis.runtime.updateStatus(ctx, existingGoal);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.runtime.activeGoal = existingGoal;\n\t\t\t\t\t\tif (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {\n\t\t\t\t\t\t\tthis.runtime.blockStaleGoalToolCalls();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.runtime.persistGoal(this.runtime.activeGoal);\n\t\t\t\t\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\t\t\t\t}\n\t\t\t\t} else if (legacyQueueBeforeActivation) {\n\t\t\t\t\tthis.runtime.activeGoal = undefined;\n\t\t\t\t\tthis.runtime.legacyQueueState = legacyQueueBeforeActivation;\n\t\t\t\t\tthis.runtime.cancelContinuationWork();\n\t\t\t\t\tthis.runtime.clearGoalRecovery();\n\t\t\t\t\tthis.runtime.clearBudgetWrapUp();\n\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t\t\t} else {\n\t\t\t\t\tthis.runtime.clearActiveGoal(ctx, \"goal activation rolled back\", false);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (rolledBackStartedGoal) {\n\t\t\t\tif (acquiredForRequest && !this.runtime.ownsWorkflow(existingGoal)) {\n\t\t\t\t\tthis.runtime.releaseWorkflow();\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (\n\t\t\tthis.runtime.activeGoal?.id !== startedGoal.id ||\n\t\t\t!this.runtime.ownsWorkflow(this.runtime.activeGoal)\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tconst automaticLimit = this.runtime.settings.continuationLimits.automaticTurns;\n\t\tnotifyTerminal(\n\t\t\tctx.ui,\n\t\t\t`${existingGoal ? \"Goal replaced\" : \"Goal started\"}: ${objective}. ${\n\t\t\t\tstartedGoal.tokenBudget === undefined\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: `Token budget: ${formatTokenCount(startedGoal.tokenBudget)} cumulative; the final model call may exceed it. `\n\t\t\t}${\n\t\t\t\tautomaticLimit === null\n\t\t\t\t\t? \"Automatic work is Unlimited; tool loops may consume substantial tokens and provider cost. Open /goal to monitor.\"\n\t\t\t\t\t: `Automatic work pauses after ${automaticLimit} responses; open /goal to monitor progress.`\n\t\t\t}`,\n\t\t\tautomaticLimit === null ? \"warning\" : \"info\",\n\t\t);\n\t}\n\n\tpauseGoal(ctx: StatusContext) {\n\t\tif (!this.runtime.activeGoal) {\n\t\t\tnotifyTerminal(ctx.ui, \"No active goal.\", \"info\");\n\t\t\treturn;\n\t\t}\n\t\tif (this.runtime.activeGoal.status !== \"active\") {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal is ${this.runtime.activeGoal.status}; only active goals can be paused.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst stoppedGoal = this.runtime.stopActiveGoal(ctx, {\n\t\t\tkind: \"explicit_pause\",\n\t\t\texpectedGoalId: this.runtime.activeGoal.id,\n\t\t});\n\t\tif (stoppedGoal) notifyTerminal(ctx.ui, `Goal paused: ${stoppedGoal.text}`, \"info\");\n\t}\n\n\tasync resumeGoal(ctx: StatusContext) {\n\t\tif (!this.runtime.activeGoal) {\n\t\t\tnotifyTerminal(ctx.ui, \"No active goal.\", \"info\");\n\t\t\treturn;\n\t\t}\n\t\tif (this.runtime.activeGoal.status === \"active\" && this.runtime.activeGoal.waiting) {\n\t\t\tawait this.resumeWaitingGoal(ctx);\n\t\t\treturn;\n\t\t}\n\t\tif (!isResumableGoalStatus(this.runtime.activeGoal.status)) {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal is ${this.runtime.activeGoal.status}; only paused, blocked, usage-limited, or budget-limited goals can be resumed.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (\n\t\t\tthis.runtime.activeGoal.tokenBudget !== undefined &&\n\t\t\tthis.runtime.activeGoal.tokensUsed >= this.runtime.activeGoal.tokenBudget\n\t\t) {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal token budget is still reached: ${formatBudget(this.runtime.activeGoal)}`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.acquireWorkflow(ctx.sessionManager)) {\n\t\t\tthis.reportWorkflowBusy(ctx);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tthis.runtime.assertGoalToolsAvailable();\n\t\t} catch (error) {\n\t\t\tnotifyTerminal(ctx.ui, `Cannot resume /goal: ${formatError(error)}`, \"error\");\n\t\t\tthis.runtime.releaseWorkflow();\n\t\t\treturn;\n\t\t}\n\t\tconst stoppedGoal = this.runtime.activeGoal;\n\t\tconst stoppedStatus = stoppedGoal.status;\n\t\tthis.runtime.cancelContinuationWork();\n\t\tthis.runtime.clearGoalRecovery();\n\t\tthis.runtime.clearBudgetWrapUp();\n\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\tthis.runtime.activeGoal = queueGoalSafetyReset(\n\t\t\ttransitionGoal(nextGoalInstance(this.runtime.activeGoal), \"active\"),\n\t\t);\n\t\tthis.runtime.persistGoal(this.runtime.activeGoal);\n\t\tif (this.runtime.activeGoal.status !== \"active\") {\n\t\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\t\tthis.runtime.releaseWorkflow();\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal token budget is still reached: ${formatBudget(this.runtime.activeGoal)}`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.ownsWorkflow(this.runtime.activeGoal)) return;\n\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\tconst resumedGoal = this.runtime.activeGoal;\n\t\tconst sent = await this.runtime.sendOwnedGoalPrompt(\n\t\t\tctx,\n\t\t\tresumedGoal.id,\n\t\t\tbuildResumePrompt(resumedGoal, stoppedStatus),\n\t\t);\n\t\tif (!sent) {\n\t\t\tif (\n\t\t\t\tthis.runtime.activeGoal?.id === resumedGoal.id &&\n\t\t\t\tthis.runtime.activeGoal.status === \"active\"\n\t\t\t) {\n\t\t\t\tthis.runtime.activeGoal = stoppedGoal;\n\t\t\t\tthis.runtime.persistGoal(this.runtime.activeGoal);\n\t\t\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\t\t\tif (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {\n\t\t\t\t\tthis.runtime.blockStaleGoalToolCalls();\n\t\t\t\t}\n\t\t\t\tthis.runtime.releaseWorkflow();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.ownsWorkflow(resumedGoal)) return;\n\t\tconst automaticLimit = this.runtime.settings.continuationLimits.automaticTurns;\n\t\tnotifyTerminal(\n\t\t\tctx.ui,\n\t\t\t`Goal resumed from ${stoppedStatusLabel(stoppedStatus)}: ${resumedGoal.text}. ${\n\t\t\t\tautomaticLimit === null\n\t\t\t\t\t? \"Automatic work remains Unlimited; goal progress and cumulative usage are preserved.\"\n\t\t\t\t\t: `The automatic-work counter will reset to 0 of ${automaticLimit} when the resumed prompt starts; goal progress and cumulative usage are preserved.`\n\t\t\t}`,\n\t\t\tautomaticLimit === null ? \"warning\" : \"info\",\n\t\t);\n\t}\n\n\tprivate async resumeWaitingGoal(ctx: StatusContext) {\n\t\tconst waitingGoal = this.runtime.activeGoal;\n\t\tconst waiting = waitingGoal?.waiting;\n\t\tif (waitingGoal?.status !== \"active\" || !waiting) return;\n\t\tif (!this.runtime.acquireWorkflow(ctx.sessionManager)) {\n\t\t\tthis.reportWorkflowBusy(ctx);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tthis.runtime.assertGoalToolsAvailable();\n\t\t} catch (error) {\n\t\t\tnotifyTerminal(ctx.ui, `Cannot resume /goal: ${formatError(error)}`, \"error\");\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.clearGoalWait(ctx, waitingGoal.id)) return;\n\t\tconst resumedGoal = this.runtime.activeGoal;\n\t\tif (!resumedGoal || resumedGoal.id !== waitingGoal.id || resumedGoal.status !== \"active\")\n\t\t\treturn;\n\t\tconst sent = await this.runtime.sendOwnedGoalPrompt(\n\t\t\tctx,\n\t\t\tresumedGoal.id,\n\t\t\tbuildWaitingResumePrompt(resumedGoal, waiting.reason),\n\t\t\tfalse,\n\t\t);\n\t\tif (!sent) {\n\t\t\tif (this.runtime.activeGoal?.id === waitingGoal.id) {\n\t\t\t\tthis.runtime.enterGoalWait(ctx, waitingGoal.id, waiting);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.ownsWorkflow(resumedGoal)) return;\n\t\tnotifyTerminal(ctx.ui, `Goal resumed from waiting: ${waitingGoal.text}`, \"info\");\n\t}\n\n\tclearGoal(ctx: StatusContext) {\n\t\tif (!this.runtime.activeGoal) {\n\t\t\tconst hadLegacyQueue = this.runtime.legacyQueueState !== undefined;\n\t\t\tthis.runtime.legacyQueueState = undefined;\n\t\t\tthis.runtime.cancelContinuationWork();\n\t\t\tthis.runtime.clearGoalRecovery();\n\t\t\tthis.runtime.clearBudgetWrapUp();\n\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\tthis.runtime.clearPersistedGoal(ctx.cwd);\n\t\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\thadLegacyQueue ? \"Removed legacy ordered goal queue state.\" : \"No active goal.\",\n\t\t\t\thadLegacyQueue ? \"warning\" : \"info\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tconst stoppedGoal = this.runtime.activeGoal.text;\n\t\tthis.runtime.clearActiveGoal(ctx);\n\t\tnotifyTerminal(ctx.ui, `Goal cleared: ${stoppedGoal}`, \"warning\");\n\t}\n\n\tasync editGoal(objective: string, tokenBudget: number | undefined, ctx: StatusContext) {\n\t\tconst validationError = validateObjective(objective);\n\t\tif (validationError) {\n\t\t\tnotifyTerminal(ctx.ui, validationError, \"warning\");\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.activeGoal) {\n\t\t\tnotifyTerminal(ctx.ui, \"No active goal. Use /goal <objective> to start one.\", \"warning\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst currentGoal = this.runtime.activeGoal;\n\t\tconst effectiveTokenBudget = tokenBudget ?? currentGoal.tokenBudget;\n\t\tif (\n\t\t\tcurrentGoal.status === \"budget_limited\" &&\n\t\t\teffectiveTokenBudget !== undefined &&\n\t\t\teffectiveTokenBudget <= currentGoal.tokensUsed\n\t\t) {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal token budget is still reached: ${formatBudget(currentGoal)}. Raise the budget above current usage before editing.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst previousStatus = currentGoal.status;\n\t\tconst intendsActive = editedGoalStatus(previousStatus) === \"active\";\n\t\tconst retainedOwner = this.runtime.ownsWorkflow(currentGoal);\n\t\tif (intendsActive && !this.runtime.acquireWorkflow(ctx.sessionManager)) {\n\t\t\tthis.reportWorkflowBusy(ctx);\n\t\t\treturn;\n\t\t}\n\t\tconst acquiredForEdit = intendsActive && !retainedOwner;\n\t\tif (intendsActive) {\n\t\t\ttry {\n\t\t\t\tthis.runtime.assertGoalToolsAvailable();\n\t\t\t} catch (error) {\n\t\t\t\tnotifyTerminal(ctx.ui, `Cannot reactivate /goal: ${formatError(error)}`, \"error\");\n\t\t\t\tif (currentGoal.status === \"active\") this.runtime.pauseGoalForUnavailableTools(ctx);\n\t\t\t\telse if (acquiredForEdit) this.runtime.releaseWorkflow();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tthis.runtime.recordGoalUsage(currentGoal, ctx);\n\t\tconst previousGoal = { ...currentGoal };\n\t\tthis.runtime.clearGoalWaitTimer();\n\t\tthis.runtime.cancelContinuationWork();\n\t\tthis.runtime.clearGoalRecovery();\n\t\tthis.runtime.clearBudgetWrapUp();\n\t\tconst rotatedGoal = nextGoalInstance(currentGoal);\n\t\tconst transitionedGoal = transitionGoal(\n\t\t\t{\n\t\t\t\t...rotatedGoal,\n\t\t\t\ttext: objective,\n\t\t\t\ttokenBudget: effectiveTokenBudget,\n\t\t\t\twaiting: undefined,\n\t\t\t},\n\t\t\teditedGoalStatus(previousStatus),\n\t\t);\n\t\tconst nextGoal =\n\t\t\ttransitionedGoal.status === \"active\"\n\t\t\t\t? queueGoalSafetyReset(transitionedGoal)\n\t\t\t\t: transitionedGoal;\n\t\tthis.runtime.activeGoal = nextGoal;\n\t\tthis.runtime.persistGoal(this.runtime.activeGoal);\n\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\tconst editedGoal = this.runtime.activeGoal;\n\t\tif (!editedGoal) return;\n\t\tif (editedGoal.status === \"active\") {\n\t\t\tif (!this.runtime.ownsWorkflow(editedGoal)) return;\n\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\tconst sent = await this.runtime.sendOwnedGoalPrompt(\n\t\t\t\tctx,\n\t\t\t\teditedGoal.id,\n\t\t\t\tbuildObjectiveUpdatedPrompt(editedGoal),\n\t\t\t);\n\t\t\tif (!sent) {\n\t\t\t\tif (this.runtime.activeGoal?.id === editedGoal.id) {\n\t\t\t\t\tif (previousStatus === \"active\" && previousGoal.waiting) {\n\t\t\t\t\t\tthis.runtime.activeGoal = previousGoal;\n\t\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\t\tthis.runtime.persistGoal(previousGoal);\n\t\t\t\t\t\tthis.runtime.updateStatus(ctx, previousGoal);\n\t\t\t\t\t\tthis.runtime.restoreGoalWaitTimer(ctx);\n\t\t\t\t\t} else if (previousStatus === \"active\") {\n\t\t\t\t\t\tthis.runtime.activeGoal = previousGoal;\n\t\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\t\tthis.runtime.persistGoal(previousGoal);\n\t\t\t\t\t\tif (this.runtime.activeGoal?.id === previousGoal.id) {\n\t\t\t\t\t\t\tthis.runtime.updateStatus(ctx, previousGoal);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.runtime.activeGoal = previousGoal;\n\t\t\t\t\t\tif (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {\n\t\t\t\t\t\t\tthis.runtime.blockStaleGoalToolCalls();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.runtime.persistGoal(this.runtime.activeGoal);\n\t\t\t\t\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\t\t\t\t}\n\t\t\t\t\tif (acquiredForEdit && previousStatus !== \"active\") {\n\t\t\t\t\t\tthis.runtime.releaseWorkflow();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!this.runtime.ownsWorkflow(editedGoal)) return;\n\t\t} else if (blocksStaleGoalToolCalls(editedGoal.status)) {\n\t\t\tthis.runtime.blockStaleGoalToolCalls();\n\t\t} else {\n\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t}\n\t\tif (editedGoal.status !== \"active\" && (retainedOwner || acquiredForEdit)) {\n\t\t\tthis.runtime.releaseWorkflow();\n\t\t}\n\t\tnotifyTerminal(ctx.ui, `Goal updated: ${objective}`, \"info\");\n\t}\n\n\tprivate reportWorkflowBusy(ctx: StatusContext) {\n\t\tconst message = \"Another workflow is active in this session. End it before starting Goal.\";\n\t\tif (ctx.mode === \"print\" || ctx.mode === \"json\") throw new Error(message);\n\t\tnotifyTerminal(ctx.ui, message, \"warning\");\n\t\treturn { kind: \"busy\" as const };\n\t}\n\n\tshowGoal(ctx: StatusContext) {\n\t\tif (!this.runtime.activeGoal) {\n\t\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t\tthis.reportGoalStatus(ctx, this.emptyGoalMessage());\n\t\t\treturn;\n\t\t}\n\t\tthis.runtime.recordGoalUsage(this.runtime.activeGoal, ctx);\n\t\tthis.runtime.persistGoal(this.runtime.activeGoal);\n\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\tthis.reportGoalStatus(\n\t\t\tctx,\n\t\t\tgoalSummary(this.runtime.activeGoal, this.runtime.settings.continuationLimits.automaticTurns),\n\t\t);\n\t}\n\n\tprivate emptyGoalMessage() {\n\t\tconst legacy = this.runtime.legacyQueueState;\n\t\tif (!legacy) return \"Usage: /goal <objective>\\nNo goal is currently set.\";\n\t\treturn [\n\t\t\t\"Ordered goal queue has been removed.\",\n\t\t\t`Legacy queue state with ${legacy.retainedGoals} retained ${legacy.retainedGoals === 1 ? \"goal\" : \"goals\"} will not run automatically.`,\n\t\t\t\"Use /goal edit to reprioritize an active objective, start /goal <objectives>, or use /goal clear to discard the old queue state.\",\n\t\t\t'Example objective: \"task b is complete; do task a next, then task c and task d.\"',\n\t\t].join(\"\\n\");\n\t}\n\n\tprivate reportGoalStatus(ctx: StatusContext, message: string) {\n\t\tif (ctx.mode === \"print\" || ctx.mode === \"json\") {\n\t\t\tthrow new Error(\n\t\t\t\t`/goal status is unavailable in ${ctx.mode} mode because Pi does not expose an extension-command output channel. Use TUI or RPC mode.`,\n\t\t\t);\n\t\t}\n\t\tnotifyTerminal(ctx.ui, message, \"info\");\n\t}\n}\n", "import type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport { currentTokenTotal } from \"./accounting.js\";\nimport { notifyTerminal } from \"./errors.js\";\nimport {\n\tGOAL_CONTRACT_MESSAGE_TYPE,\n\tisGoalContextContract,\n\treconcileGoalContextContract,\n\treconcileInactiveGoalContextContract,\n} from \"./goal-contract.js\";\nimport { type ActiveGoal, loadGoalStateFromSession } from \"./persistence.js\";\nimport type { GoalRunController } from \"./run-protocol.js\";\nimport {\n\ttype AssistantMessageLike,\n\tabortCurrentTurn,\n\tblocksStaleGoalToolCalls,\n\tfindFinalAssistantMessage,\n\ttype GoalRuntime,\n\tincrementGoal,\n\tisGoalContextOverflow,\n\tisRetryableGoalInterruption,\n\tisUsageLimitedGoalInterruption,\n\tresetGoalSafetyEpoch,\n\tSTATUS_KEY,\n\ttype StatusContext,\n\ttransitionGoal,\n\ttruncateNotification,\n} from \"./runtime.js\";\nimport { hasAssistantToolCall } from \"./safety.js\";\nimport { DEFAULT_GOAL_SETTINGS, readGoalSettings } from \"./settings.js\";\n\nconst REMOVED_QUEUE_SETTING_WARNING =\n\t\"Ordered goal queue has been removed. Use /goal edit to reprioritize an active objective, or start /goal <objectives> if no active goal exists.\";\nconst REMOVED_PERSISTED_QUEUE_WARNING =\n\t\"Ordered goal queue has been removed. Start /goal <objectives> to continue with one merged objective, or use /goal clear to discard the old queue state.\";\n\ninterface GoalLifecycleOptions {\n\tsettingsPath?: string;\n}\n\nexport function registerGoalLifecycle(\n\tpi: ExtensionAPI,\n\truntime: GoalRuntime,\n\trunController: GoalRunController,\n\toptions: GoalLifecycleOptions = {},\n) {\n\tpi.on(\"session_start\", async (_event, ctx) => {\n\t\truntime.bindWorkflowSession(ctx.sessionManager);\n\t\truntime.replaceMenuSession();\n\t\truntime.clearCompletionStatusTimer();\n\t\truntime.clearContinuationTracking();\n\t\truntime.clearGoalWaitTimer();\n\t\truntime.clearPendingGoalPrompts();\n\t\truntime.clearAgentRun();\n\t\truntime.guardAbortGoalId = undefined;\n\t\truntime.clearGoalRecovery();\n\t\truntime.clearBudgetWrapUp();\n\t\truntime.clearStaleGoalToolCallBlock();\n\t\truntime.legacyQueueState = undefined;\n\t\truntime.legacyExperimentalGoalsSetting = false;\n\t\truntime.clearTerminalDetails();\n\t\tconst settingsResult = readGoalSettings(options.settingsPath);\n\t\tconst loaded = loadGoalStateFromSession(ctx);\n\t\truntime.settings =\n\t\t\tsettingsResult.kind === \"loaded\" ? settingsResult.settings : DEFAULT_GOAL_SETTINGS;\n\t\truntime.settingsLoadIssue = settingsResult.kind === \"invalid\" ? settingsResult : undefined;\n\t\truntime.activeGoal = undefined;\n\t\truntime.legacyQueueState = loaded.legacyQueueState;\n\t\truntime.legacyExperimentalGoalsSetting =\n\t\t\tsettingsResult.kind !== \"invalid\" && settingsResult.legacyExperimentalGoals;\n\t\trunController.bindSession(ctx);\n\n\t\tif (settingsResult.kind === \"invalid\") {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`pi-goal settings ignored: ${settingsResult.reason}. Using default settings.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t}\n\t\tif (runtime.legacyExperimentalGoalsSetting && !runtime.legacyQueueState) {\n\t\t\tnotifyTerminal(ctx.ui, REMOVED_QUEUE_SETTING_WARNING, \"warning\");\n\t\t}\n\n\t\tif (loaded.goal?.status === \"active\") {\n\t\t\tif (!runtime.acquireWorkflow()) {\n\t\t\t\truntime.activeGoal = transitionGoal(loaded.goal, \"paused\");\n\t\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\t\truntime.ensureInactiveGoalContextContract(ctx);\n\t\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t\t\tnotifyTerminal(\n\t\t\t\t\tctx.ui,\n\t\t\t\t\t\"Goal was paused during restore because another workflow is active in this session. Resume it after the other workflow ends.\",\n\t\t\t\t\t\"warning\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\truntime.activeGoal = loaded.goal;\n\t\t\tif (runtime.activeGoal.safetyResetPending) {\n\t\t\t\t// Resume/edit activation is persisted before its owned prompt starts. A\n\t\t\t\t// reload must commit that promised reset before enforcing the old limits.\n\t\t\t\truntime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);\n\t\t\t}\n\t\t\truntime.recordGoalUsage(runtime.activeGoal, ctx);\n\t\t\tif (runtime.limitActiveGoalForBudget(ctx, false)) return;\n\t\t\tif (runtime.enforceAutomaticTurnLimit(ctx, false) || runtime.enforceNoProgressLimit(ctx)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!runtime.goalToolsAvailable()) {\n\t\t\t\truntime.pauseGoalForUnavailableTools(ctx, false);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\tif (!runtime.ownsWorkflow(runtime.activeGoal)) return;\n\t\t\tconst restoredGoalId = runtime.activeGoal.id;\n\t\t\truntime.ensureGoalContextContract(ctx, runtime.activeGoal);\n\t\t\tif (\n\t\t\t\truntime.activeGoal?.id !== restoredGoalId ||\n\t\t\t\truntime.activeGoal.status !== \"active\" ||\n\t\t\t\t!runtime.ownsWorkflow(runtime.activeGoal)\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t\truntime.restoreGoalWaitTimer(ctx);\n\t\t\treturn;\n\t\t}\n\n\t\truntime.activeGoal = loaded.goal;\n\t\tif (runtime.legacyQueueState) {\n\t\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t\tnotifyTerminal(ctx.ui, REMOVED_PERSISTED_QUEUE_WARNING, \"warning\");\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.activeGoal) {\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\truntime.ensureInactiveGoalContextContract(ctx);\n\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t} else {\n\t\t\truntime.ensureInactiveGoalContextContract(ctx);\n\t\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t}\n\t});\n\n\tpi.on(\"session_shutdown\", (_event, ctx) => {\n\t\tconst shutdownSession = ctx.sessionManager;\n\t\trunController.unbindSession();\n\t\truntime.closeMenuSession();\n\t\truntime.clearGoalWaitTimer();\n\t\tif (runtime.activeGoal) {\n\t\t\tif (runtime.activeGoal.status === \"active\") {\n\t\t\t\truntime.recordGoalUsage(runtime.activeGoal, ctx, false);\n\t\t\t}\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t}\n\t\truntime.clearContinuationTracking();\n\t\truntime.clearPendingGoalPrompts();\n\t\truntime.clearAgentRun();\n\t\truntime.guardAbortGoalId = undefined;\n\t\truntime.clearGoalRecovery();\n\t\truntime.clearBudgetWrapUp();\n\t\truntime.clearStaleGoalToolCallBlock();\n\t\truntime.activeGoal = undefined;\n\t\truntime.legacyQueueState = undefined;\n\t\truntime.legacyExperimentalGoalsSetting = false;\n\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\truntime.clearCompletionStatusTimer();\n\t\truntime.clearTerminalDetails();\n\t\truntime.releaseWorkflow();\n\t\truntime.unbindWorkflowSession(shutdownSession);\n\t});\n\n\tpi.on(\"session_before_compact\", (event, ctx) => {\n\t\tif (runtime.activeGoal?.status === \"budget_limited\") {\n\t\t\tif ((event as { willRetry?: boolean }).willRetry === true) return { cancel: true as const };\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.activeGoal?.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\treturn;\n\t\t}\n\t\tif (!runtime.recordGoalUsage(runtime.activeGoal, ctx)) return;\n\t\truntime.cancelContinuationWork();\n\t\truntime.persistGoal(runtime.activeGoal);\n\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\tif (runtime.limitActiveGoalForBudget(ctx, false)) return { cancel: true as const };\n\t});\n\n\tpi.on(\"session_compact\", async (event, ctx) => {\n\t\tif (runtime.activeGoal?.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\truntime.clearGoalRecovery();\n\t\t\treturn;\n\t\t}\n\n\t\tconst restoredState = loadGoalStateFromSession(ctx);\n\t\tif (restoredState.goal?.id === runtime.activeGoal.id) {\n\t\t\truntime.activeGoal = restoredState.goal;\n\t\t}\n\t\tconst usageRecorded = runtime.recordGoalUsage(runtime.activeGoal, ctx);\n\t\tif (usageRecorded) {\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t}\n\t\tif (runtime.limitActiveGoalForBudget(ctx, false)) return;\n\t\tconst compactedGoalId = runtime.activeGoal.id;\n\t\truntime.ensureGoalContextContract(ctx, runtime.activeGoal);\n\t\tif (\n\t\t\truntime.activeGoal?.id !== compactedGoalId ||\n\t\t\truntime.activeGoal.status !== \"active\" ||\n\t\t\t!runtime.ownsWorkflow(runtime.activeGoal)\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tif (!usageRecorded) return;\n\n\t\tconst wasPiRetry = runtime.isPiOwnedCompactionRetry(event, runtime.activeGoal.id);\n\t\tif (wasPiRetry) return;\n\t\truntime.clearGoalRecoveryForGoal(runtime.activeGoal.id);\n\t\truntime.requestContinuation(runtime.activeGoal);\n\t\t// Pi emits session_compact before it clears its manual-compaction controller,\n\t\t// so sendUserMessage still rejects inside this hook even when ctx reports idle.\n\t\t// Defer one task; threshold compaction retains the intent for agent_settled\n\t\t// when Pi is still busy.\n\t\truntime.scheduleContinuationDispatch(ctx, runtime.activeGoal.id);\n\t});\n\n\tpi.on(\"input\", (event, ctx) => {\n\t\tif (event.source === \"extension\") {\n\t\t\tif (\n\t\t\t\truntime.consumeCancelledGoalPrompt(event.text) ||\n\t\t\t\truntime.consumeCancelledContinuationPrompt(event.text) ||\n\t\t\t\truntime.consumeStaleOwnedGoalPrompt(event.text)\n\t\t\t) {\n\t\t\t\treturn { action: \"handled\" as const };\n\t\t\t}\n\t\t\t// Streaming input is queued before its model work starts. Keep owned\n\t\t\t// markers pending for message_start, and track non-goal delivery mode so a\n\t\t\t// steer cannot consume a later follow-up's cleanup protection.\n\t\t\tif (runtime.acceptOwnedInputBoundary(event.text)) return;\n\t\t\truntime.supersedeOwnedInputCollision(event.text);\n\t\t\tif (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);\n\t\t\tif (event.streamingBehavior === \"steer\" || event.streamingBehavior === \"followUp\") {\n\t\t\t\truntime.noteQueuedNonGoalInput(event.text, event.streamingBehavior);\n\t\t\t}\n\t\t\truntime.clearGoalRecovery();\n\t\t\treturn;\n\t\t}\n\t\tif (/^\\/goal(?:\\s|$)/u.test(event.text.trimStart())) return;\n\t\tif (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);\n\t\tif (event.streamingBehavior === \"followUp\") {\n\t\t\truntime.noteQueuedNonGoalInput(event.text, \"followUp\", true);\n\t\t\treturn;\n\t\t}\n\t\tif (event.streamingBehavior === \"steer\") {\n\t\t\truntime.noteQueuedNonGoalInput(event.text, \"steer\");\n\t\t}\n\t\truntime.clearGoalRecovery();\n\t\truntime.clearBudgetWrapUp();\n\t\truntime.clearStaleGoalToolCallBlock();\n\t\truntime.resetActiveSafetyEpoch(ctx);\n\t});\n\n\tpi.on(\"message_start\", (event, ctx) => {\n\t\tconst message = event.message as { role?: unknown; content?: unknown };\n\t\tif (\n\t\t\tmessage.role === \"assistant\" &&\n\t\t\truntime.activeGoal?.status === \"paused\" &&\n\t\t\truntime.guardAbortGoalId === runtime.activeGoal.id\n\t\t) {\n\t\t\tabortCurrentTurn(ctx);\n\t\t\treturn;\n\t\t}\n\t\tif (message.role === \"custom\") {\n\t\t\tif (Reflect.get(message, \"customType\") === GOAL_CONTRACT_MESSAGE_TYPE) return;\n\t\t\tif (runtime.isActiveBudgetWrapUpMessage(message)) return;\n\t\t\tif (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);\n\t\t\tif (runtime.guardAbortGoalId === runtime.activeGoal?.id) {\n\t\t\t\truntime.guardAbortGoalId = undefined;\n\t\t\t}\n\t\t\tbeginNonGoalFollowUp(ctx, false);\n\t\t\treturn;\n\t\t}\n\t\tif (message.role !== \"user\") return;\n\t\tconst prompt = Array.isArray(message.content)\n\t\t\t? message.content\n\t\t\t\t\t.filter(\n\t\t\t\t\t\t(part) => part && typeof part === \"object\" && Reflect.get(part, \"type\") === \"text\",\n\t\t\t\t\t)\n\t\t\t\t\t.map((part) => Reflect.get(part as object, \"text\"))\n\t\t\t\t\t.filter((text): text is string => typeof text === \"string\")\n\t\t\t\t\t.join(\"\\n\")\n\t\t\t: typeof message.content === \"string\"\n\t\t\t\t? message.content\n\t\t\t\t: \"\";\n\t\tconst ownedPrompt = runtime.consumeOwnedGoalPrompt(prompt);\n\t\tconst ownedPromptBoundary = runtime.hasOwnedPromptBoundary(prompt);\n\t\tconst queuedNonGoalInput = runtime.consumeQueuedNonGoalInput(prompt, !ownedPromptBoundary);\n\t\tif (!ownedPrompt) {\n\t\t\tif (queuedNonGoalInput?.behavior === \"followUp\") {\n\t\t\t\tbeginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (\n\t\t\truntime.activeGoal?.id !== ownedPrompt.goalId ||\n\t\t\t!runtime.ownsWorkflow(runtime.activeGoal)\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.agentRunGoalId !== undefined && runtime.agentRunGoalId !== ownedPrompt.goalId) {\n\t\t\truntime.activeGoal.baselineTokens = Math.max(\n\t\t\t\t0,\n\t\t\t\tcurrentTokenTotal(ctx) - runtime.activeGoal.tokensUsed,\n\t\t\t);\n\t\t}\n\t\truntime.beginAgentRun(ownedPrompt.goalId, \"manual\");\n\t\tif (ownedPrompt.resetSafetyEpoch) {\n\t\t\truntime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);\n\t\t}\n\t\truntime.persistGoal(runtime.activeGoal);\n\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t});\n\n\tpi.on(\"context\", (event, ctx) => {\n\t\tconst keptMessages = event.messages.filter((message) =>\n\t\t\truntime.keepBudgetWrapUpMessage(message),\n\t\t);\n\t\tconst hasGoalContractHistory =\n\t\t\tkeptMessages.some(isGoalContextContract) || runtime.hasGoalContextContractHistory(ctx);\n\t\tconst messages =\n\t\t\truntime.activeGoal?.status === \"active\" && runtime.ownsWorkflow(runtime.activeGoal)\n\t\t\t\t? reconcileGoalContextContract(keptMessages, runtime.activeGoal)\n\t\t\t\t: hasGoalContractHistory\n\t\t\t\t\t? reconcileInactiveGoalContextContract(keptMessages)\n\t\t\t\t\t: keptMessages;\n\t\tif (\n\t\t\truntime.activeGoal?.status === \"paused\" &&\n\t\t\truntime.guardAbortGoalId === runtime.activeGoal.id\n\t\t) {\n\t\t\t// A current custom follow-up clears the guard at message_start. Otherwise,\n\t\t\t// context transformation aborts before the provider adapter receives the signal.\n\t\t\tabortCurrentTurn(ctx);\n\t\t}\n\t\tif (messages !== keptMessages || keptMessages.length !== event.messages.length) {\n\t\t\treturn { messages: messages as typeof event.messages };\n\t\t}\n\t});\n\n\tpi.on(\"tool_call\", (event, ctx) => {\n\t\truntime.markAgentToolAttempted();\n\t\tif (\n\t\t\truntime.activeGoal?.status === \"budget_limited\" &&\n\t\t\truntime.budgetWrapUp?.goalId === runtime.activeGoal.id &&\n\t\t\tevent.toolName !== \"goal_complete\"\n\t\t) {\n\t\t\t// A blocked tool result would normally trigger another model call. Abort the\n\t\t\t// wrap-up instead so a tool-seeking model cannot create an unbounded loop.\n\t\t\tabortCurrentTurn(ctx);\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason: \"Goal token budget is exhausted; only goal_complete is allowed during wrap-up.\",\n\t\t\t};\n\t\t}\n\t\tif (!runtime.staleGoalToolCallsBlocked) return;\n\t\tif (!runtime.activeGoal || !blocksStaleGoalToolCalls(runtime.activeGoal.status)) {\n\t\t\truntime.clearStaleGoalToolCallBlock();\n\t\t\treturn;\n\t\t}\n\t\t// A blocked tool result would normally trigger another model call. Abort the\n\t\t// current turn so a tool-seeking model cannot create an unbounded loop that\n\t\t// burns provider quota while the goal is stopped.\n\t\tabortCurrentTurn(ctx);\n\t\treturn {\n\t\t\tblock: true,\n\t\t\treason: \"Blocked stale /goal tool call after the goal stopped or was interrupted.\",\n\t\t};\n\t});\n\n\tpi.on(\"tool_execution_end\", (_event, ctx) => {\n\t\tif (\n\t\t\truntime.activeGoal?.status === \"budget_limited\" &&\n\t\t\truntime.budgetWrapUp?.goalId === runtime.activeGoal.id &&\n\t\t\t!runtime.budgetWrapUp.delivered\n\t\t) {\n\t\t\truntime.queueBudgetWrapUp(ctx, runtime.activeGoal);\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.activeGoal?.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\treturn;\n\t\t}\n\n\t\t// AgentSession persists assistant message_end before tool execution events,\n\t\t// so the completed assistant call's usage is authoritative at this boundary.\n\t\tif (!runtime.recordGoalUsage(runtime.activeGoal, ctx)) return;\n\t\truntime.persistGoal(runtime.activeGoal);\n\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\tif (runtime.limitActiveGoalForBudget(ctx, true)) return;\n\t\tif (!runtime.goalToolsAvailable()) runtime.pauseGoalForUnavailableTools(ctx);\n\t});\n\n\tpi.on(\"before_agent_start\", (event, ctx) => {\n\t\truntime.clearAgentRun();\n\t\t// Pi-owned retries emit agent_start directly. Reaching a normal prompt\n\t\t// boundary means cleanup no longer owns the next run, so the hard-cap guard\n\t\t// must not abort it.\n\t\tif (runtime.guardAbortGoalId) runtime.guardAbortGoalId = undefined;\n\t\tconst goalPrompt = runtime.consumeOwnedGoalPrompt(event.prompt);\n\t\tconst goalPromptGoalId = goalPrompt?.goalId;\n\t\tconst continuationGoalId = goalPromptGoalId\n\t\t\t? undefined\n\t\t\t: runtime.markContinuationStarted(event.prompt);\n\t\tconst ownedPromptGoalId = goalPromptGoalId ?? continuationGoalId;\n\t\tconst ownedPromptBoundary = runtime.hasOwnedPromptBoundary(event.prompt);\n\t\tconst activeBudgetWrapUp = runtime.hasActiveBudgetWrapUp();\n\t\tconst activeGoalRecovery = runtime.hasActiveGoalRecovery();\n\t\tconst queuedNonGoalInput = activeBudgetWrapUp\n\t\t\t? undefined\n\t\t\t: runtime.consumeQueuedNonGoalInput(\n\t\t\t\t\tevent.prompt,\n\t\t\t\t\t!activeGoalRecovery && ownedPromptGoalId === undefined && !ownedPromptBoundary,\n\t\t\t\t);\n\t\tif (queuedNonGoalInput?.behavior === \"followUp\") {\n\t\t\tbeginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);\n\t\t}\n\t\tif (!ownedPromptGoalId && !ownedPromptBoundary) {\n\t\t\truntime.supersedeOwnedInputCollision(event.prompt);\n\t\t\tif (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);\n\t\t}\n\t\tif (runtime.activeGoal?.status === \"active\" && !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\truntime.cancelContinuationWork();\n\t\t\truntime.clearGoalRecovery();\n\t\t\tabortCurrentTurn(ctx);\n\t\t\treturn;\n\t\t}\n\t\tconst runOrigin = continuationGoalId\n\t\t\t? \"automatic\"\n\t\t\t: activeGoalRecovery && runtime.goalRecovery?.automaticOwner\n\t\t\t\t? \"automatic\"\n\t\t\t\t: \"manual\";\n\t\tif (activeBudgetWrapUp && runtime.activeGoal) {\n\t\t\truntime.beginAgentRun(runtime.activeGoal.id, \"manual\");\n\t\t\treturn goalContractBoundaryResult(ctx);\n\t\t}\n\t\tif (ownedPromptGoalId && ownedPromptGoalId !== runtime.activeGoal?.id) {\n\t\t\truntime.beginAgentRun(ownedPromptGoalId, runOrigin);\n\t\t\tif (runtime.activeGoal?.status === \"active\" && !runtime.goalToolsAvailable()) {\n\t\t\t\truntime.pauseGoalForUnavailableTools(ctx, false);\n\t\t\t}\n\t\t\tabortCurrentTurn(ctx);\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.activeGoal?.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\treturn goalContractBoundaryResult(ctx);\n\t\t}\n\t\truntime.beginAgentRun(runtime.activeGoal.id, runOrigin);\n\t\tif (!runtime.goalToolsAvailable()) {\n\t\t\truntime.pauseGoalForUnavailableTools(ctx, ownedPromptGoalId !== undefined);\n\t\t\treturn goalContractBoundaryResult(ctx);\n\t\t}\n\t\tif (goalPrompt?.resetSafetyEpoch && goalPromptGoalId === runtime.activeGoal.id) {\n\t\t\truntime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t}\n\t\treturn goalContractBoundaryResult(ctx, runtime.activeGoal);\n\t});\n\n\tpi.on(\"agent_start\", (_event, _ctx) => {\n\t\tconst activeGoal = runtime.activeGoal;\n\t\tif (\n\t\t\tactiveGoal &&\n\t\t\truntime.guardAbortGoalId === activeGoal.id &&\n\t\t\tactiveGoal.status === \"paused\"\n\t\t) {\n\t\t\tif (runtime.consumeQueuedNonGoalFollowUpForAgentStart()) {\n\t\t\t\truntime.guardAbortGoalId = undefined;\n\t\t\t\truntime.clearStaleGoalToolCallBlock();\n\t\t\t\truntime.beginAgentRun(null, undefined);\n\t\t\t}\n\t\t\t// Unknown runs defer cleanup until their message/context boundary: custom\n\t\t\t// follow-ups have no input event, while bare recovery is aborted pre-provider.\n\t\t\treturn;\n\t\t}\n\t\truntime.beginRecoveryRunIfNeeded();\n\t});\n\n\tpi.on(\"turn_end\", (event, ctx) => {\n\t\truntime.recordAutomaticTurn(ctx, event.message);\n\t\t// Terminal Goal tools transition state synchronously, but their inactive contract\n\t\t// must wait until Pi has persisted the real tool result at this turn boundary.\n\t\tif (runtime.activeGoal?.status !== \"active\") {\n\t\t\truntime.ensureInactiveGoalContextContract(ctx);\n\t\t}\n\t});\n\n\tpi.on(\"agent_end\", (event, ctx) => {\n\t\tconst run = runtime.finishAgentRun();\n\t\tif (run.goalId === null) return;\n\t\tif (!runtime.canRecordGoalUsage() && !runtime.hasActiveBudgetWrapUp()) return;\n\t\tif (run.goalId && run.goalId !== runtime.activeGoal?.id) return;\n\t\tif (!runtime.activeGoal) return;\n\t\tif (\n\t\t\truntime.activeGoal.status === \"budget_limited\" &&\n\t\t\truntime.budgetWrapUp?.goalId === runtime.activeGoal.id\n\t\t) {\n\t\t\truntime.recordGoalUsage(runtime.activeGoal, ctx);\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t\truntime.clearBudgetWrapUp();\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.activeGoal.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst goalId = runtime.activeGoal.id;\n\t\tconst alreadyAwaitingContinuation = runtime.hasContinuationWorkForGoal(goalId);\n\t\tconst finalAssistant = findFinalAssistantMessage(event.messages);\n\n\t\tif (!alreadyAwaitingContinuation) runtime.activeGoal = incrementGoal(runtime.activeGoal);\n\t\truntime.recordGoalUsage(runtime.activeGoal, ctx);\n\n\t\tif (finalAssistant?.stopReason === \"aborted\") {\n\t\t\truntime.clearGoalRecoveryForGoal(goalId);\n\t\t\tstopGoalAfterAgentEnd(ctx, runtime.activeGoal, finalAssistant, \"paused\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (finalAssistant?.stopReason === \"error\") {\n\t\t\tif (isRetryableGoalInterruption(finalAssistant)) {\n\t\t\t\tif (run.origin === \"automatic\" && runtime.enforceAutomaticTurnLimit(ctx, true)) return;\n\t\t\t\tif (runtime.limitActiveGoalForBudget(ctx, false)) return;\n\t\t\t\tif (!runtime.goalToolsAvailable()) {\n\t\t\t\t\truntime.pauseGoalForUnavailableTools(ctx);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\truntime.goalRecovery = {\n\t\t\t\t\tgoalId,\n\t\t\t\t\tkind: isGoalContextOverflow(finalAssistant) ? \"compaction_retry\" : \"provider_retry\",\n\t\t\t\t\tautomaticOwner: run.origin === \"automatic\",\n\t\t\t\t\terrorMessage: finalAssistant.errorMessage,\n\t\t\t\t};\n\t\t\t\truntime.cancelContinuationWork();\n\t\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\truntime.clearGoalRecoveryForGoal(goalId);\n\t\t\tstopGoalAfterAgentEnd(\n\t\t\t\tctx,\n\t\t\t\truntime.activeGoal,\n\t\t\t\tfinalAssistant,\n\t\t\t\tisUsageLimitedGoalInterruption(finalAssistant) ? \"usage_limited\" : \"blocked\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\truntime.clearGoalRecoveryForGoal(goalId);\n\n\t\tif (runtime.limitActiveGoalForBudget(ctx, false)) return;\n\t\tif (!runtime.goalToolsAvailable()) {\n\t\t\truntime.pauseGoalForUnavailableTools(ctx);\n\t\t\treturn;\n\t\t}\n\t\tif (\n\t\t\trun.origin === \"automatic\" &&\n\t\t\truntime.recordAutomaticRunProgress(\n\t\t\t\tctx,\n\t\t\t\tgoalId,\n\t\t\t\tevent.messages,\n\t\t\t\trun.toolAttempted || hasAssistantToolCall(event.messages),\n\t\t\t)\n\t\t) {\n\t\t\treturn;\n\t\t}\n\n\t\truntime.persistGoal(runtime.activeGoal);\n\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\n\t\tconst currentGoal = runtime.activeGoal;\n\t\tif (!currentGoal || currentGoal.id !== goalId || currentGoal.status !== \"active\") return;\n\t\truntime.requestContinuation(currentGoal);\n\t});\n\n\tpi.on(\"agent_settled\", (_event, ctx) => {\n\t\tif (runtime.activeGoal?.status === \"active\" && !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\truntime.cancelContinuationWork();\n\t\t\truntime.clearGoalRecovery();\n\t\t\truntime.clearSettledSafetyTracking();\n\t\t\treturn;\n\t\t}\n\t\truntime.finalizeSettledRecovery(ctx);\n\t\tconst resumedWait = runtime.dispatchDueGoalWait(ctx);\n\t\tif (!resumedWait) runtime.dispatchContinuationIfSettled(ctx);\n\t\truntime.clearSettledSafetyTracking();\n\t});\n\n\tfunction goalContractBoundaryResult(ctx: StatusContext, goal?: ActiveGoal) {\n\t\tconst message = runtime.goalContextContractForPrompt(ctx, goal);\n\t\treturn message ? { message } : undefined;\n\t}\n\n\tfunction beginNonGoalFollowUp(ctx: StatusContext, resetSafetyEpoch: boolean) {\n\t\truntime.clearGoalRecovery();\n\t\truntime.clearStaleGoalToolCallBlock();\n\t\tif (resetSafetyEpoch) runtime.clearBudgetWrapUp();\n\t\tconst activeGoalId =\n\t\t\truntime.activeGoal?.status === \"active\" ? runtime.activeGoal.id : undefined;\n\t\truntime.beginAgentRun(activeGoalId ?? null, activeGoalId ? \"manual\" : undefined);\n\t\tif (resetSafetyEpoch && activeGoalId) runtime.resetActiveSafetyEpoch(ctx);\n\t}\n\n\tfunction stopGoalAfterAgentEnd(\n\t\tctx: StatusContext,\n\t\tgoal: ActiveGoal,\n\t\tassistant: AssistantMessageLike,\n\t\tstatus: \"paused\" | \"blocked\" | \"usage_limited\",\n\t) {\n\t\tconst stoppedGoal = runtime.stopActiveGoal(ctx, {\n\t\t\tkind: \"agent_interruption\",\n\t\t\texpectedGoalId: goal.id,\n\t\t\tstatus,\n\t\t\treason: assistant.errorMessage ?? `goal ${status} after agent interruption`,\n\t\t});\n\t\tif (!stoppedGoal) return;\n\n\t\tconst details = assistant.errorMessage\n\t\t\t? ` (${truncateNotification(assistant.errorMessage)})`\n\t\t\t: \"\";\n\t\tif (status === \"paused\") {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal paused after interruption${details}. Run /goal resume to continue.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (status === \"usage_limited\") {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal stopped after provider usage limit${details}. Run /goal resume when usage is available.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tnotifyTerminal(\n\t\t\tctx.ui,\n\t\t\t`Goal blocked after agent error${details}. Resolve the blocker or run /goal resume to retry.`,\n\t\t\t\"warning\",\n\t\t);\n\t}\n}\n", "import type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport { validateObjective } from \"./command.js\";\nimport type { GoalCommandController } from \"./commands.js\";\nimport {\n\tformatError,\n\ttype GoalRuntime,\n\ttype GoalStateSnapshot,\n\tisTerminalGoalStatus,\n\ttype StatusContext,\n} from \"./runtime.js\";\n\nexport const GOAL_RUN_START_CHANNEL = \"pi-goal:start\";\nexport const GOAL_RUN_CANCEL_CHANNEL = \"pi-goal:cancel\";\n\nconst RUN_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;\nconst MAX_CANCEL_REASON_LENGTH = 1_000;\n\nexport type GoalRunStatus = Exclude<GoalStateSnapshot[\"status\"], \"queued\">;\nexport type GoalRunErrorCode =\n\t| \"RPC_DISABLED\"\n\t| \"INVALID_REQUEST\"\n\t| \"NO_ACTIVE_SESSION\"\n\t| \"RUN_ID_IN_USE\"\n\t| \"RUN_NOT_FOUND\"\n\t| \"GOAL_ALREADY_EXISTS\"\n\t| \"ACTIVATION_FAILED\"\n\t| \"SUPERSEDED\";\n\nexport type GoalRunEvent =\n\t| {\n\t\t\ttype: \"state\";\n\t\t\trunId: string;\n\t\t\tgoalId: string;\n\t\t\tstatus: GoalRunStatus;\n\t\t\tsummary?: string;\n\t\t\treason?: string;\n\t }\n\t| {\n\t\t\ttype: \"error\";\n\t\t\trunId: string;\n\t\t\toperation: \"start\" | \"cancel\";\n\t\t\terror: { code: GoalRunErrorCode; message: string };\n\t };\n\ninterface GoalRunStartPayload {\n\trunId: string;\n\tobjective: string;\n\ttokenBudget?: number;\n}\n\ninterface BoundSession {\n\tgeneration: number;\n\tctx: StatusContext;\n}\n\ninterface ManagedRun {\n\trunId: string;\n\tgeneration: number;\n\tgoalId?: string;\n\tlastStatus?: GoalRunStatus;\n\tclosed: boolean;\n\tcancelRequested: boolean;\n\tcancelReason?: string;\n}\n\nexport function goalRunEventChannel(runId: string) {\n\treturn `pi-goal:event:${runId}`;\n}\n\nfunction isPayloadRecord(data: unknown): data is object {\n\tif (!data || typeof data !== \"object\") return false;\n\ttry {\n\t\treturn !Array.isArray(data);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction readPayloadProperty(\n\tdata: object,\n\tkey: \"runId\" | \"objective\" | \"tokenBudget\" | \"reason\",\n): { ok: true; value: unknown } | { ok: false } {\n\ttry {\n\t\treturn { ok: true, value: Reflect.get(data, key) };\n\t} catch {\n\t\treturn { ok: false };\n\t}\n}\n\nfunction parseRunId(data: unknown): string | undefined {\n\tif (!isPayloadRecord(data)) return undefined;\n\tconst runId = readPayloadProperty(data, \"runId\");\n\treturn runId.ok && typeof runId.value === \"string\" && RUN_ID_PATTERN.test(runId.value)\n\t\t? runId.value\n\t\t: undefined;\n}\n\nfunction currentActiveGoal(runtime: GoalRuntime) {\n\treturn runtime.activeGoal;\n}\n\nfunction parseStartPayload(data: unknown): string | Omit<GoalRunStartPayload, \"runId\"> {\n\tif (!isPayloadRecord(data)) return \"start payload must be an object\";\n\tconst objectiveValue = readPayloadProperty(data, \"objective\");\n\tif (!objectiveValue.ok || typeof objectiveValue.value !== \"string\") {\n\t\treturn \"objective must be a string\";\n\t}\n\tconst objective = objectiveValue.value.trim();\n\tconst objectiveError = validateObjective(objective);\n\tif (objectiveError) return objectiveError;\n\tconst tokenBudgetValue = readPayloadProperty(data, \"tokenBudget\");\n\tif (\n\t\t!tokenBudgetValue.ok ||\n\t\t(tokenBudgetValue.value !== undefined &&\n\t\t\t(typeof tokenBudgetValue.value !== \"number\" ||\n\t\t\t\t!Number.isFinite(tokenBudgetValue.value) ||\n\t\t\t\t!Number.isSafeInteger(tokenBudgetValue.value) ||\n\t\t\t\ttokenBudgetValue.value <= 0))\n\t) {\n\t\treturn \"tokenBudget must be a positive integer\";\n\t}\n\treturn { objective, tokenBudget: tokenBudgetValue.value as number | undefined };\n}\n\nfunction parseCancelReason(data: unknown): string | undefined | { error: string } {\n\tif (!isPayloadRecord(data)) return { error: \"cancel payload must be an object\" };\n\tconst reasonValue = readPayloadProperty(data, \"reason\");\n\tif (\n\t\t!reasonValue.ok ||\n\t\t(reasonValue.value !== undefined && typeof reasonValue.value !== \"string\")\n\t) {\n\t\treturn { error: \"reason must be a string\" };\n\t}\n\tif (reasonValue.value === undefined) return undefined;\n\tconst reason = reasonValue.value.trim();\n\tif (reason.length > MAX_CANCEL_REASON_LENGTH) {\n\t\treturn { error: `reason must be at most ${MAX_CANCEL_REASON_LENGTH} characters` };\n\t}\n\treturn reason || undefined;\n}\n\nexport class GoalRunController {\n\tprivate readonly runtime: GoalRuntime;\n\tprivate readonly commands: GoalCommandController;\n\tprivate generation = 0;\n\tprivate session?: BoundSession;\n\tprivate run?: ManagedRun;\n\tprivate readonly usedRunIds = new Set<string>();\n\n\tconstructor(runtime: GoalRuntime, commands: GoalCommandController) {\n\t\tthis.runtime = runtime;\n\t\tthis.commands = commands;\n\t\tthis.runtime.setGoalStateSink((snapshot) => this.handleGoalState(snapshot));\n\t}\n\n\tregister(pi: ExtensionAPI) {\n\t\tpi.events.on(GOAL_RUN_START_CHANNEL, (data) => this.handleStart(data));\n\t\tpi.events.on(GOAL_RUN_CANCEL_CHANNEL, (data) => {\n\t\t\tthis.handleCancel(data);\n\t\t});\n\t}\n\n\tbindSession(ctx: StatusContext) {\n\t\tthis.generation += 1;\n\t\tthis.session = { generation: this.generation, ctx };\n\t\tthis.closeCurrentRun();\n\t\tthis.usedRunIds.clear();\n\t}\n\n\tunbindSession() {\n\t\tthis.generation += 1;\n\t\tthis.session = undefined;\n\t\tthis.closeCurrentRun();\n\t\tthis.usedRunIds.clear();\n\t}\n\n\tprivate async handleStart(data: unknown) {\n\t\tconst runId = parseRunId(data);\n\t\tif (!runId) return;\n\t\tconst session = this.session;\n\t\tif (!session) {\n\t\t\tthis.emitError(runId, \"start\", \"NO_ACTIVE_SESSION\", \"No active pi-goal session.\");\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.settings.rpc.enabled) {\n\t\t\tthis.emitError(runId, \"start\", \"RPC_DISABLED\", \"Managed run RPC is disabled.\");\n\t\t\treturn;\n\t\t}\n\t\tif (this.usedRunIds.has(runId)) {\n\t\t\tthis.emitError(runId, \"start\", \"RUN_ID_IN_USE\", \"runId was already used in this session.\");\n\t\t\treturn;\n\t\t}\n\t\tconst parsed = parseStartPayload(data);\n\t\tif (typeof parsed === \"string\") {\n\t\t\tthis.emitError(runId, \"start\", \"INVALID_REQUEST\", parsed);\n\t\t\treturn;\n\t\t}\n\t\tif (this.session !== session || this.generation !== session.generation) {\n\t\t\tthis.emitError(\n\t\t\t\trunId,\n\t\t\t\t\"start\",\n\t\t\t\t\"SUPERSEDED\",\n\t\t\t\t\"The pi-goal session changed while validating the request.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (this.usedRunIds.has(runId)) {\n\t\t\tthis.emitError(runId, \"start\", \"RUN_ID_IN_USE\", \"runId was already used in this session.\");\n\t\t\treturn;\n\t\t}\n\t\tif (this.runtime.activeGoal || (this.run && !this.run.closed)) {\n\t\t\tthis.emitError(runId, \"start\", \"GOAL_ALREADY_EXISTS\", \"A Goal already exists.\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst run: ManagedRun = {\n\t\t\trunId,\n\t\t\tgeneration: session.generation,\n\t\t\tclosed: false,\n\t\t\tcancelRequested: false,\n\t\t};\n\t\tthis.run = run;\n\t\tthis.usedRunIds.add(runId);\n\n\t\ttry {\n\t\t\tconst activation = await this.commands.startGoal(\n\t\t\t\tparsed.objective,\n\t\t\t\tparsed.tokenBudget,\n\t\t\t\tsession.ctx,\n\t\t\t\t(goal) => {\n\t\t\t\t\tif (this.ownsRun(run, session.generation)) run.goalId = goal.id;\n\t\t\t\t},\n\t\t\t\t() => this.ownsRun(run, session.generation),\n\t\t\t);\n\t\t\tif (activation?.kind === \"busy\" && this.ownsRun(run, session.generation)) {\n\t\t\t\tthis.closeCurrentRun();\n\t\t\t\tthis.emitError(\n\t\t\t\t\trunId,\n\t\t\t\t\t\"start\",\n\t\t\t\t\t\"ACTIVATION_FAILED\",\n\t\t\t\t\t\"Another workflow is active in this session. End it before starting Goal.\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (this.ownsRun(run, session.generation)) {\n\t\t\t\tthis.closeCurrentRun();\n\t\t\t\tthis.emitError(\n\t\t\t\t\trunId,\n\t\t\t\t\t\"start\",\n\t\t\t\t\t\"ACTIVATION_FAILED\",\n\t\t\t\t\t`Goal activation failed: ${formatError(error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.ownsRun(run, session.generation)) return;\n\t\tif (!run.goalId) {\n\t\t\tthis.closeCurrentRun();\n\t\t\tthis.emitError(runId, \"start\", \"ACTIVATION_FAILED\", \"Goal activation did not create a Goal.\");\n\t\t\treturn;\n\t\t}\n\t\tif (currentActiveGoal(this.runtime)?.id !== run.goalId) {\n\t\t\tthis.closeCurrentRun();\n\t\t\tthis.emitError(runId, \"start\", \"SUPERSEDED\", \"The managed Goal was superseded.\");\n\t\t\treturn;\n\t\t}\n\t\tif (run.cancelRequested) this.cancelActiveRun(run, session, run.cancelReason);\n\t}\n\n\tprivate handleCancel(data: unknown) {\n\t\tconst runId = parseRunId(data);\n\t\tif (!runId) return;\n\t\tconst session = this.session;\n\t\tif (!session) {\n\t\t\tthis.emitError(runId, \"cancel\", \"NO_ACTIVE_SESSION\", \"No active pi-goal session.\");\n\t\t\treturn;\n\t\t}\n\t\tconst reason = parseCancelReason(data);\n\t\tif (reason && typeof reason === \"object\") {\n\t\t\tthis.emitError(runId, \"cancel\", \"INVALID_REQUEST\", reason.error);\n\t\t\treturn;\n\t\t}\n\t\tconst run = this.run;\n\t\tif (!run || run.closed || run.runId !== runId || run.generation !== session.generation) {\n\t\t\tthis.emitError(runId, \"cancel\", \"RUN_NOT_FOUND\", \"No active managed run matches runId.\");\n\t\t\treturn;\n\t\t}\n\t\tif (!run.goalId) {\n\t\t\trun.cancelRequested = true;\n\t\t\trun.cancelReason = reason;\n\t\t\treturn;\n\t\t}\n\t\tthis.cancelActiveRun(run, session, reason);\n\t}\n\n\tprivate cancelActiveRun(run: ManagedRun, session: BoundSession, reason: string | undefined) {\n\t\tif (!this.ownsRun(run, session.generation)) return;\n\t\tconst goal = this.runtime.activeGoal;\n\t\tif (!goal || goal.id !== run.goalId) {\n\t\t\tthis.closeCurrentRun();\n\t\t\tthis.emitError(run.runId, \"cancel\", \"SUPERSEDED\", \"The managed Goal was superseded.\");\n\t\t\treturn;\n\t\t}\n\t\tif (goal.status !== \"active\") {\n\t\t\tthis.closeCurrentRun();\n\t\t\tthis.emitError(run.runId, \"cancel\", \"RUN_NOT_FOUND\", \"The managed run is no longer active.\");\n\t\t\treturn;\n\t\t}\n\t\tthis.runtime.setTerminalReason(goal.id, reason ?? \"goal cancelled by managed run\");\n\t\tthis.commands.pauseGoal(session.ctx);\n\t}\n\n\tprivate handleGoalState(snapshot: GoalStateSnapshot) {\n\t\tconst run = this.run;\n\t\tif (!run || run.closed || !run.goalId) return;\n\t\tif (run.goalId !== snapshot.goalId) {\n\t\t\tif (currentActiveGoal(this.runtime)?.id !== snapshot.goalId) return;\n\t\t\tthis.publishStateEvent(run, {\n\t\t\t\tgoalId: run.goalId,\n\t\t\t\tstatus: \"cleared\",\n\t\t\t\treason: \"managed Goal superseded by another Goal\",\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (snapshot.status === \"queued\" || run.lastStatus === snapshot.status) return;\n\t\tthis.publishStateEvent(run, snapshot);\n\t}\n\n\tprivate publishStateEvent(\n\t\trun: ManagedRun,\n\t\tsnapshot: Pick<GoalStateSnapshot, \"goalId\" | \"status\" | \"summary\" | \"reason\">,\n\t) {\n\t\tconst status = snapshot.status;\n\t\tif (status === \"queued\") return;\n\t\trun.lastStatus = status;\n\t\tconst event: GoalRunEvent = {\n\t\t\ttype: \"state\",\n\t\t\trunId: run.runId,\n\t\t\tgoalId: snapshot.goalId,\n\t\t\tstatus,\n\t\t\t...(snapshot.summary ? { summary: snapshot.summary } : {}),\n\t\t\t...(snapshot.reason ? { reason: snapshot.reason } : {}),\n\t\t};\n\t\tif (!isTerminalGoalStatus(status)) {\n\t\t\tthis.runtime.pi.events.emit(goalRunEventChannel(run.runId), event);\n\t\t\treturn;\n\t\t}\n\n\t\trun.closed = true;\n\t\tthis.run = undefined;\n\t\tconst generation = run.generation;\n\t\t// Active stays synchronous so a listener can cancel before kickoff. Terminal\n\t\t// publication waits until the transition finishes, preventing listener work\n\t\t// from being overwritten by the old transition's remaining UI or cleanup.\n\t\tqueueMicrotask(() => {\n\t\t\tif (this.generation !== generation) return;\n\t\t\tthis.runtime.pi.events.emit(goalRunEventChannel(run.runId), event);\n\t\t});\n\t}\n\n\tprivate emitError(\n\t\trunId: string,\n\t\toperation: \"start\" | \"cancel\",\n\t\tcode: GoalRunErrorCode,\n\t\tmessage: string,\n\t) {\n\t\tthis.runtime.pi.events.emit(goalRunEventChannel(runId), {\n\t\t\ttype: \"error\",\n\t\t\trunId,\n\t\t\toperation,\n\t\t\terror: { code, message },\n\t\t} satisfies GoalRunEvent);\n\t}\n\n\tprivate ownsRun(run: ManagedRun, generation: number) {\n\t\treturn (\n\t\t\tthis.session?.generation === generation &&\n\t\t\tthis.generation === generation &&\n\t\t\tthis.run === run &&\n\t\t\t!run.closed\n\t\t);\n\t}\n\n\tprivate closeCurrentRun() {\n\t\tif (this.run) this.run.closed = true;\n\t\tthis.run = undefined;\n\t}\n}\n", "import {\n\tDEFAULT_MAX_BYTES,\n\tDEFAULT_MAX_LINES,\n\tdefineTool,\n\ttype ExtensionAPI,\n\tgetMarkdownTheme,\n\ttruncateHead,\n} from \"@earendil-works/pi-coding-agent\";\nimport { Markdown } from \"@earendil-works/pi-tui\";\nimport { Type } from \"typebox\";\nimport { notifyTerminal, safeTerminalText } from \"./errors.js\";\nimport {\n\tformatStatus,\n\tGOAL_BLOCKED_TOOL,\n\tGOAL_COMPLETE_TOOL,\n\tGOAL_WAIT_TOOL,\n\ttype GoalRuntime,\n\tgoalIdRejectionReason,\n\tisContradictoryCompletionSummary,\n\tMAX_GOAL_ID_LENGTH,\n\tSTATUS_KEY,\n\ttransitionGoal,\n\ttruncateNotification,\n} from \"./runtime.js\";\nimport {\n\tcreateGoalWait,\n\tMAX_GOAL_WAIT_DELAY_MS,\n\tMAX_GOAL_WAIT_REASON_LENGTH,\n\tMIN_GOAL_WAIT_DELAY_MS,\n\tresolveGoalWaitDelay,\n} from \"./wait.js\";\n\ninterface GoalCompleteDetails {\n\tgoal: string;\n\tgoal_id: string;\n\tsummary: string;\n}\n\ninterface GoalBlockedDetails {\n\tgoal: string;\n\tgoal_id: string;\n\treason: string;\n\tevidence: string;\n\trepeated_turns: number;\n}\n\ninterface GoalWaitDetails {\n\tgoal: string;\n\tgoal_id: string;\n\treason: string;\n\trequested_resume_after_ms?: number;\n\tresume_after_ms?: number;\n\tresume_at?: number;\n}\n\nconst MAX_GOAL_TEXT_LENGTH = 4_000;\nconst MAX_COMPLETION_SUMMARY_LENGTH = 4_000;\nconst MAX_BLOCKER_REASON_LENGTH = 1_000;\nconst MAX_BLOCKER_EVIDENCE_LENGTH = 4_000;\n\nexport function registerGoalTools(pi: ExtensionAPI, runtime: GoalRuntime) {\n\tconst goalCompleteTool = defineTool({\n\t\tname: GOAL_COMPLETE_TOOL,\n\t\tlabel: \"Goal Complete\",\n\t\tdescription:\n\t\t\t\"Mark an active /goal complete only when the latest effective Goal contract explicitly says Goal mode is active, supplies the matching current goal_id, and every requirement is verified. Tool visibility alone does not activate Goal mode. Never call for ordinary work, partial progress, blockers, failures, or unverified work.\",\n\t\tparameters: Type.Object({\n\t\t\tgoal_id: Type.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tmaxLength: MAX_GOAL_ID_LENGTH,\n\t\t\t\tdescription:\n\t\t\t\t\t\"The exact goal_id shown in the current active /goal prompt. Used only to reject stale completion calls from older turns.\",\n\t\t\t}),\n\t\t\tsummary: Type.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tmaxLength: MAX_COMPLETION_SUMMARY_LENGTH,\n\t\t\t\tdescription:\n\t\t\t\t\t\"State what was completed and what evidence verified it. Do not use this tool to report partial progress, blockers, failures, or remaining work.\",\n\t\t\t}),\n\t\t}),\n\t\trenderResult(result) {\n\t\t\treturn renderGoalCompletion(result);\n\t\t},\n\t\tasync execute(_toolCallId, params, _signal, _onUpdate, ctx) {\n\t\t\tconst completedGoal = runtime.activeGoal;\n\t\t\tconst goal = completedGoal?.text ?? \"unknown goal\";\n\t\t\tconst requestedGoalId = typeof params.goal_id === \"string\" ? params.goal_id.trim() : \"\";\n\t\t\tconst summary = typeof params.summary === \"string\" ? params.summary.trim() : \"\";\n\n\t\t\tif (!completedGoal) {\n\t\t\t\tconst rejection = \"Goal completion rejected: no active goal.\";\n\t\t\t\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst completingDuringBudgetWrapUp = runtime.hasActiveBudgetWrapUp();\n\t\t\tif (completedGoal.status === \"active\" && !runtime.ownsWorkflow(completedGoal)) {\n\t\t\t\tconst rejection = \"Goal completion rejected: active Goal no longer owns its workflow.\";\n\t\t\t\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (!runtime.canRecordGoalUsage() && !completingDuringBudgetWrapUp) {\n\t\t\t\tconst rejection = \"Goal completion rejected: current run does not own the active goal.\";\n\t\t\t\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst staleGoalRejection = goalIdRejectionReason(completedGoal, requestedGoalId);\n\t\t\tif (staleGoalRejection) {\n\t\t\t\tconst rejection = `Goal completion rejected: ${staleGoalRejection}.`;\n\t\t\t\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\t\t\t\tif (completingDuringBudgetWrapUp) {\n\t\t\t\t\truntime.recordGoalUsage(completedGoal, ctx);\n\t\t\t\t\truntime.persistGoal(completedGoal);\n\t\t\t\t\truntime.updateStatus(ctx, completedGoal);\n\t\t\t\t\truntime.clearBudgetWrapUp();\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\n\t\t\t\t\tterminate: completingDuringBudgetWrapUp || undefined,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (completedGoal.status !== \"active\" && !completingDuringBudgetWrapUp) {\n\t\t\t\tconst rejection = `Goal completion rejected: goal is ${completedGoal.status}, not active.`;\n\t\t\t\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst rejectionReason = !summary\n\t\t\t\t? \"summary is empty\"\n\t\t\t\t: summary.length > MAX_COMPLETION_SUMMARY_LENGTH\n\t\t\t\t\t? \"summary is too long\"\n\t\t\t\t\t: isContradictoryCompletionSummary(summary)\n\t\t\t\t\t\t? \"summary says the goal is not complete\"\n\t\t\t\t\t\t: undefined;\n\t\t\tif (rejectionReason) {\n\t\t\t\truntime.recordGoalUsage(completedGoal, ctx);\n\t\t\t\truntime.persistGoal(completedGoal);\n\t\t\t\truntime.updateStatus(ctx, completedGoal);\n\t\t\t\tconst rejection = `Goal completion rejected: ${rejectionReason}.`;\n\t\t\t\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\t\t\t\tif (completingDuringBudgetWrapUp) runtime.clearBudgetWrapUp();\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\n\t\t\t\t\tterminate: completingDuringBudgetWrapUp || undefined,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\truntime.clearGoalWaitTimer();\n\t\t\truntime.activeGoal = transitionGoal(completedGoal, \"complete\");\n\t\t\truntime.setCompletionSummary(runtime.activeGoal.id, summary);\n\t\t\truntime.recordGoalUsage(runtime.activeGoal, ctx);\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\n\t\t\tctx.ui.setStatus(STATUS_KEY, formatStatus(runtime.activeGoal));\n\t\t\truntime.clearCompletedGoal(ctx);\n\t\t\truntime.showCompletionStatus(ctx);\n\t\t\tnotifyTerminal(ctx.ui, `Goal complete: ${goal}`, \"info\");\n\n\t\t\treturn {\n\t\t\t\tcontent: toolContent(`Goal complete: ${summary}`),\n\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\n\t\t\t\tterminate: true,\n\t\t\t};\n\t\t},\n\t});\n\n\tconst goalBlockedTool = defineTool({\n\t\tname: GOAL_BLOCKED_TOOL,\n\t\tlabel: \"Goal Blocked\",\n\t\tdescription:\n\t\t\t\"Stop an active /goal only when the latest effective Goal contract explicitly says Goal mode is active, supplies the matching current goal_id, and the same evidenced external blocker recurred for at least three consecutive Goal turns. Tool visibility alone does not activate Goal mode. Never call for ordinary clarification, uncertainty, incomplete work, or recoverable failures.\",\n\t\tparameters: Type.Object({\n\t\t\tgoal_id: Type.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tmaxLength: MAX_GOAL_ID_LENGTH,\n\t\t\t\tdescription: \"The exact goal_id shown in the current active /goal prompt.\",\n\t\t\t}),\n\t\t\treason: Type.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tmaxLength: MAX_BLOCKER_REASON_LENGTH,\n\t\t\t\tdescription: \"The specific user or external action required to unblock the goal.\",\n\t\t\t}),\n\t\t\tevidence: Type.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tmaxLength: MAX_BLOCKER_EVIDENCE_LENGTH,\n\t\t\t\tdescription: \"Concrete evidence from the repeated attempts that proves the impasse.\",\n\t\t\t}),\n\t\t\trepeated_turns: Type.Integer({\n\t\t\t\tminimum: 3,\n\t\t\t\tdescription: \"Number of separate turns spent trying to resolve this same blocker.\",\n\t\t\t}),\n\t\t}),\n\t\tasync execute(_toolCallId, params, _signal, _onUpdate, ctx) {\n\t\t\tconst blockedGoal = runtime.activeGoal;\n\t\t\tconst goal = blockedGoal?.text ?? \"unknown goal\";\n\t\t\tconst requestedGoalId = typeof params.goal_id === \"string\" ? params.goal_id.trim() : \"\";\n\t\t\tconst reason = typeof params.reason === \"string\" ? params.reason.trim() : \"\";\n\t\t\tconst evidence = typeof params.evidence === \"string\" ? params.evidence.trim() : \"\";\n\t\t\tconst repeatedTurns =\n\t\t\t\ttypeof params.repeated_turns === \"number\" ? params.repeated_turns : Number.NaN;\n\t\t\tconst reject = (rejectionReason: string, terminate = false) => {\n\t\t\t\tconst rejection = `goal_blocked rejected: ${rejectionReason}.`;\n\t\t\t\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: blockerDetails(goal, requestedGoalId, reason, evidence, repeatedTurns),\n\t\t\t\t\t...(terminate ? { terminate: true as const } : {}),\n\t\t\t\t};\n\t\t\t};\n\n\t\t\tif (!blockedGoal) return reject(\"no active goal\");\n\t\t\tif (!runtime.canRecordGoalUsage()) {\n\t\t\t\treturn reject(\"current run does not own the active goal\");\n\t\t\t}\n\t\t\tconst staleGoalRejection = goalIdRejectionReason(blockedGoal, requestedGoalId);\n\t\t\tif (staleGoalRejection) return reject(staleGoalRejection);\n\t\t\tif (blockedGoal.status !== \"active\") {\n\t\t\t\treturn reject(`goal is ${blockedGoal.status}, not active`);\n\t\t\t}\n\t\t\tif (!runtime.ownsWorkflow(blockedGoal))\n\t\t\t\treturn reject(\"active Goal no longer owns its workflow\");\n\t\t\tif (!reason) return reject(\"reason is empty\");\n\t\t\tif (reason.length > MAX_BLOCKER_REASON_LENGTH) return reject(\"reason is too long\");\n\t\t\tif (!evidence) return reject(\"evidence is empty\");\n\t\t\tif (evidence.length > MAX_BLOCKER_EVIDENCE_LENGTH) return reject(\"evidence is too long\");\n\t\t\tif (!Number.isInteger(repeatedTurns)) return reject(\"repeated_turns must be a whole number\");\n\t\t\tif (repeatedTurns < 3) return reject(\"repeated_turns must be at least 3\");\n\n\t\t\tconst stoppedGoal = runtime.stopActiveGoal(ctx, {\n\t\t\t\tkind: \"blocker_report\",\n\t\t\t\texpectedGoalId: blockedGoal.id,\n\t\t\t\treason,\n\t\t\t});\n\t\t\tif (!stoppedGoal) return reject(\"active goal changed before blocker transition\");\n\t\t\tnotifyTerminal(ctx.ui, `Goal blocked: ${truncateNotification(reason)}`, \"warning\");\n\n\t\t\treturn {\n\t\t\t\tcontent: toolContent(`Goal blocked: ${reason}`),\n\t\t\t\tdetails: blockerDetails(goal, requestedGoalId, reason, evidence, repeatedTurns),\n\t\t\t\tterminate: true,\n\t\t\t};\n\t\t},\n\t});\n\n\tconst goalWaitTool = defineTool({\n\t\tname: GOAL_WAIT_TOOL,\n\t\tlabel: \"Goal Wait\",\n\t\tdescription: `Keep an active /goal quiet only when the latest effective Goal contract explicitly says Goal mode is active, supplies the matching current goal_id, and progress depends on an arranged external wake event or one safety deadline. Tool visibility alone does not activate Goal mode. Call goal_wait alone. Requests below ${MIN_GOAL_WAIT_DELAY_MS}ms are clamped to ${MIN_GOAL_WAIT_DELAY_MS}ms. Never call for ordinary unfinished work.`,\n\t\tparameters: Type.Object({\n\t\t\tgoal_id: Type.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tmaxLength: MAX_GOAL_ID_LENGTH,\n\t\t\t\tdescription: \"The exact goal_id shown in the current active /goal prompt.\",\n\t\t\t}),\n\t\t\treason: Type.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tmaxLength: MAX_GOAL_WAIT_REASON_LENGTH,\n\t\t\t\tdescription: \"Why the goal is waiting and which external event should wake it.\",\n\t\t\t}),\n\t\t\tresume_after_ms: Type.Optional(\n\t\t\t\tType.Integer({\n\t\t\t\t\tminimum: 1,\n\t\t\t\t\tmaximum: MAX_GOAL_WAIT_DELAY_MS,\n\t\t\t\t\tdescription: `Optional safety deadline in milliseconds that requests one continuation if no wake message arrives. Values below ${MIN_GOAL_WAIT_DELAY_MS} are accepted but clamped to ${MIN_GOAL_WAIT_DELAY_MS}.`,\n\t\t\t\t}),\n\t\t\t),\n\t\t}),\n\t\tasync execute(_toolCallId, params, _signal, _onUpdate, ctx) {\n\t\t\tconst activeGoal = runtime.activeGoal;\n\t\t\tconst goal = activeGoal?.text ?? \"unknown goal\";\n\t\t\tconst requestedGoalId = typeof params.goal_id === \"string\" ? params.goal_id.trim() : \"\";\n\t\t\tconst reason = typeof params.reason === \"string\" ? params.reason.trim() : \"\";\n\t\t\tconst resumeAfterMs =\n\t\t\t\ttypeof params.resume_after_ms === \"number\" ? params.resume_after_ms : undefined;\n\t\t\tconst reject = (rejectionReason: string) => {\n\t\t\t\tconst rejection = `goal_wait rejected: ${rejectionReason}.`;\n\t\t\t\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: waitDetails(goal, requestedGoalId, reason, resumeAfterMs),\n\t\t\t\t};\n\t\t\t};\n\n\t\t\tif (!activeGoal) return reject(\"no active goal\");\n\t\t\tif (!runtime.canRecordGoalUsage()) {\n\t\t\t\treturn reject(\"current run does not own the active goal\");\n\t\t\t}\n\t\t\tconst staleGoalRejection = goalIdRejectionReason(activeGoal, requestedGoalId);\n\t\t\tif (staleGoalRejection) return reject(staleGoalRejection);\n\t\t\tif (activeGoal.status !== \"active\") {\n\t\t\t\treturn reject(`goal is ${activeGoal.status}, not active`);\n\t\t\t}\n\t\t\tif (!runtime.ownsWorkflow(activeGoal))\n\t\t\t\treturn reject(\"active Goal no longer owns its workflow\");\n\t\t\tif (activeGoal.waiting) return reject(\"goal is already waiting\");\n\t\t\tif (!reason) return reject(\"reason is empty\");\n\t\t\tif (reason.length > MAX_GOAL_WAIT_REASON_LENGTH) return reject(\"reason is too long\");\n\t\t\tif (\n\t\t\t\tresumeAfterMs !== undefined &&\n\t\t\t\t(!Number.isInteger(resumeAfterMs) ||\n\t\t\t\t\tresumeAfterMs < 1 ||\n\t\t\t\t\tresumeAfterMs > MAX_GOAL_WAIT_DELAY_MS)\n\t\t\t) {\n\t\t\t\treturn reject(`resume_after_ms must be a whole number from 1 to ${MAX_GOAL_WAIT_DELAY_MS}`);\n\t\t\t}\n\n\t\t\tconst { requestedMs, effectiveMs } = resolveGoalWaitDelay(resumeAfterMs);\n\t\t\tconst waiting = createGoalWait(reason, resumeAfterMs);\n\t\t\tconst waitingGoal = runtime.enterGoalWait(ctx, activeGoal.id, waiting);\n\t\t\tif (!waitingGoal) return reject(\"active goal changed before waiting transition\");\n\t\t\tconst clamped = requestedMs !== undefined && effectiveMs !== requestedMs;\n\t\t\tnotifyTerminal(ctx.ui, `Goal waiting: ${truncateNotification(reason)}`, \"info\");\n\t\t\treturn {\n\t\t\t\tcontent: toolContent(\n\t\t\t\t\tclamped\n\t\t\t\t\t\t? `Goal waiting: ${reason}\\nRequested resume_after_ms ${requestedMs} was clamped to ${effectiveMs}.`\n\t\t\t\t\t\t: `Goal waiting: ${reason}`,\n\t\t\t\t),\n\t\t\t\tdetails: waitDetails(\n\t\t\t\t\tgoal,\n\t\t\t\t\trequestedGoalId,\n\t\t\t\t\treason,\n\t\t\t\t\teffectiveMs,\n\t\t\t\t\twaiting.resumeAt,\n\t\t\t\t\tclamped ? requestedMs : undefined,\n\t\t\t\t),\n\t\t\t\tterminate: true,\n\t\t\t};\n\t\t},\n\t});\n\n\tpi.registerTool(goalCompleteTool);\n\tpi.registerTool(goalBlockedTool);\n\tpi.registerTool(goalWaitTool);\n}\n\ninterface GoalCompletionRenderResult {\n\tcontent: Array<{ type: string; text?: string }>;\n\tdetails?: unknown;\n}\n\nexport function goalCompletionMarkdown(result: GoalCompletionRenderResult) {\n\tconst content = result.content\n\t\t.filter((block) => block.type === \"text\" && typeof block.text === \"string\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\")\n\t\t.trim();\n\tconst completionPrefix = \"Goal complete:\";\n\tif (!content.startsWith(completionPrefix)) return content;\n\n\tconst details = result.details;\n\tconst summary =\n\t\tdetails &&\n\t\ttypeof details === \"object\" &&\n\t\t\"summary\" in details &&\n\t\ttypeof details.summary === \"string\"\n\t\t\t? details.summary\n\t\t\t: content.slice(completionPrefix.length);\n\tconst safeSummary = safeTerminalText(summary);\n\treturn safeSummary ? `**Goal complete**\\n\\n${safeSummary}` : \"**Goal complete**\";\n}\n\nexport function renderGoalCompletion(result: GoalCompletionRenderResult) {\n\treturn new Markdown(goalCompletionMarkdown(result), 0, 0, getMarkdownTheme());\n}\n\nfunction toolContent(text: string) {\n\treturn [\n\t\t{\n\t\t\ttype: \"text\" as const,\n\t\t\ttext: truncateHead(safeTerminalText(text), {\n\t\t\t\tmaxBytes: DEFAULT_MAX_BYTES,\n\t\t\t\tmaxLines: DEFAULT_MAX_LINES,\n\t\t\t}).content,\n\t\t},\n\t];\n}\n\nfunction completionDetails(goal: string, goalId: string, summary: string): GoalCompleteDetails {\n\treturn {\n\t\tgoal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),\n\t\tgoal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),\n\t\tsummary: summary.slice(0, MAX_COMPLETION_SUMMARY_LENGTH),\n\t};\n}\n\nfunction blockerDetails(\n\tgoal: string,\n\tgoalId: string,\n\treason: string,\n\tevidence: string,\n\trepeatedTurns: number,\n): GoalBlockedDetails {\n\treturn {\n\t\tgoal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),\n\t\tgoal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),\n\t\treason: reason.slice(0, MAX_BLOCKER_REASON_LENGTH),\n\t\tevidence: evidence.slice(0, MAX_BLOCKER_EVIDENCE_LENGTH),\n\t\trepeated_turns: Number.isFinite(repeatedTurns) ? repeatedTurns : 0,\n\t};\n}\n\nfunction waitDetails(\n\tgoal: string,\n\tgoalId: string,\n\treason: string,\n\tresumeAfterMs: number | undefined,\n\tresumeAt?: number,\n\trequestedResumeAfterMs?: number,\n): GoalWaitDetails {\n\treturn {\n\t\tgoal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),\n\t\tgoal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),\n\t\treason: reason.slice(0, MAX_GOAL_WAIT_REASON_LENGTH),\n\t\t...(requestedResumeAfterMs === undefined\n\t\t\t? {}\n\t\t\t: { requested_resume_after_ms: requestedResumeAfterMs }),\n\t\t...(resumeAfterMs === undefined ? {} : { resume_after_ms: resumeAfterMs }),\n\t\t...(resumeAt === undefined ? {} : { resume_at: resumeAt }),\n\t};\n}\n", "import type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport { registerGoalCommand } from \"./command-registration.js\";\nimport { GoalCommandController } from \"./commands.js\";\nimport { registerGoalLifecycle } from \"./lifecycle.js\";\nimport { GoalRunController } from \"./run-protocol.js\";\nimport { GoalRuntime } from \"./runtime.js\";\nimport { registerGoalTools } from \"./tools.js\";\n\ninterface GoalOptions {\n\tsettingsPath?: string;\n}\n\nfunction registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {\n\tconst runtime = new GoalRuntime(pi);\n\tconst commands = new GoalCommandController(runtime);\n\tconst runController = new GoalRunController(runtime, commands);\n\n\t// Keep registration order explicit: managed-run bus listeners exist before tools,\n\t// command routing, and session lifecycle bind the per-factory runtime.\n\trunController.register(pi);\n\tregisterGoalTools(pi, runtime);\n\tregisterGoalCommand(pi, runtime, commands, options);\n\tregisterGoalLifecycle(pi, runtime, runController, options);\n}\n\nexport default function goal(pi: ExtensionAPI, options: GoalOptions = {}) {\n\tregisterGoalRuntime(pi, options);\n}\n\nexport {\n\tassistantUsageTokens,\n\tcumulativeAssistantTokens,\n\tformatDuration,\n\tformatTokenCount,\n} from \"./accounting.js\";\n\nexport {\n\tcompleteGoalArguments,\n\tparseCommand,\n\tparseTokenBudget,\n\tvalidateObjective,\n} from \"./command.js\";\n\nexport { buildGoalSystemPrompt } from \"./prompts.js\";\n\nexport {\n\tfindFinalAssistantMessage,\n\tformatStatus,\n\tisContradictoryCompletionSummary,\n\tisRetryableGoalInterruption,\n\tisUsageLimitedGoalInterruption,\n} from \"./runtime.js\";\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeO,SAAS,oBACf,IACA,SACA,UACA,UAA0C,CAAC,GAC1C;AACD,QAAM,kBAAkB;AAAA,IACvB,QAAQ,oBAAoB,MAAM,OAAO,2BAAW;AAAA,EACrD;AACA,QAAM,mBAAmB;AAAA,IACxB,QAAQ,qBAAqB,MAAM,OAAO,kCAAkB;AAAA,EAC7D;AAEA,KAAG,gBAAgB,QAAQ;AAAA,IAC1B,aAAa;AAAA,IACb,wBAAwB,CAAC,WAAW,sBAAsB,MAAM;AAAA,IAChE,SAAS,OAAO,MAAM,QAAQ;AAC7B,UAAI,QAAQ,wBAAwB,KAAK,sBAAsB,IAAI,GAAG;AACrE,kCAA0B,KAAK,OAAO;AACtC;AAAA,MACD;AACA,YAAM,SAAS,aAAa,IAAI;AAChC,UAAI,OAAO,WAAW,UAAU;AAC/B,2BAAmB,QAAQ,GAAG;AAC9B;AAAA,MACD;AACA,UAAI,OAAO,SAAS,UAAU,KAAK,KAAK,MAAM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UAAU,IAAI,YAAY,EAAE;AAClC,QAAM,WAAW,IAAI,sBAAsB,OAAO;AAClD,QAAM,gBAAgB,IAAI,kBAAkB,SAAS,QAAQ;AAI7D,gBAAc,SAAS,EAAE;AACzB,oBAAkB,IAAI,OAAO;AAC7B,sBAAoB,IAAI,SAAS,UAAU,OAAO;AAClD,wBAAsB,IAAI,SAAS,eAAe,OAAO;AAC1D;AAEe,SAAR,KAAsB,IAAkB,UAAuB,CAAC,GAAG;AACzE,sBAAoB,IAAI,OAAO;AAChC;",
|
|
6
6
|
"names": ["goal", "goal", "goal"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@narumitw/pi-goal",
|
|
3
|
-
"version": "0.54.
|
|
3
|
+
"version": "0.54.4",
|
|
4
4
|
"description": "Pi extension for autonomous single-objective /goal completion.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -23,9 +23,6 @@
|
|
|
23
23
|
"./dist/index.ts"
|
|
24
24
|
]
|
|
25
25
|
},
|
|
26
|
-
"piExtension": {
|
|
27
|
-
"lifecycle": "stable"
|
|
28
|
-
},
|
|
29
26
|
"scripts": {
|
|
30
27
|
"build": "node scripts/build-runtime.mjs",
|
|
31
28
|
"check": "npm run build && biome check . && npm run typecheck",
|
|
@@ -41,12 +38,12 @@
|
|
|
41
38
|
"typebox": "*"
|
|
42
39
|
},
|
|
43
40
|
"devDependencies": {
|
|
44
|
-
"@biomejs/biome": "2.5.
|
|
45
|
-
"@earendil-works/pi-ai": "0.84.
|
|
46
|
-
"@earendil-works/pi-coding-agent": "0.84.
|
|
47
|
-
"@earendil-works/pi-tui": "0.84.
|
|
41
|
+
"@biomejs/biome": "2.5.11",
|
|
42
|
+
"@earendil-works/pi-ai": "0.84.4",
|
|
43
|
+
"@earendil-works/pi-coding-agent": "0.84.4",
|
|
44
|
+
"@earendil-works/pi-tui": "0.84.4",
|
|
48
45
|
"esbuild": "0.28.2",
|
|
49
|
-
"typebox": "1.3.
|
|
46
|
+
"typebox": "1.3.20",
|
|
50
47
|
"typescript": "7.0.2"
|
|
51
48
|
},
|
|
52
49
|
"dependencies": {
|
package/src/tools.ts
CHANGED
|
@@ -3,8 +3,10 @@ import {
|
|
|
3
3
|
DEFAULT_MAX_LINES,
|
|
4
4
|
defineTool,
|
|
5
5
|
type ExtensionAPI,
|
|
6
|
+
getMarkdownTheme,
|
|
6
7
|
truncateHead,
|
|
7
8
|
} from "@earendil-works/pi-coding-agent";
|
|
9
|
+
import { Markdown } from "@earendil-works/pi-tui";
|
|
8
10
|
import { Type } from "typebox";
|
|
9
11
|
import { notifyTerminal, safeTerminalText } from "./errors.js";
|
|
10
12
|
import {
|
|
@@ -76,6 +78,9 @@ export function registerGoalTools(pi: ExtensionAPI, runtime: GoalRuntime) {
|
|
|
76
78
|
"State what was completed and what evidence verified it. Do not use this tool to report partial progress, blockers, failures, or remaining work.",
|
|
77
79
|
}),
|
|
78
80
|
}),
|
|
81
|
+
renderResult(result) {
|
|
82
|
+
return renderGoalCompletion(result);
|
|
83
|
+
},
|
|
79
84
|
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
80
85
|
const completedGoal = runtime.activeGoal;
|
|
81
86
|
const goal = completedGoal?.text ?? "unknown goal";
|
|
@@ -346,6 +351,36 @@ export function registerGoalTools(pi: ExtensionAPI, runtime: GoalRuntime) {
|
|
|
346
351
|
pi.registerTool(goalWaitTool);
|
|
347
352
|
}
|
|
348
353
|
|
|
354
|
+
interface GoalCompletionRenderResult {
|
|
355
|
+
content: Array<{ type: string; text?: string }>;
|
|
356
|
+
details?: unknown;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
export function goalCompletionMarkdown(result: GoalCompletionRenderResult) {
|
|
360
|
+
const content = result.content
|
|
361
|
+
.filter((block) => block.type === "text" && typeof block.text === "string")
|
|
362
|
+
.map((block) => block.text)
|
|
363
|
+
.join("\n")
|
|
364
|
+
.trim();
|
|
365
|
+
const completionPrefix = "Goal complete:";
|
|
366
|
+
if (!content.startsWith(completionPrefix)) return content;
|
|
367
|
+
|
|
368
|
+
const details = result.details;
|
|
369
|
+
const summary =
|
|
370
|
+
details &&
|
|
371
|
+
typeof details === "object" &&
|
|
372
|
+
"summary" in details &&
|
|
373
|
+
typeof details.summary === "string"
|
|
374
|
+
? details.summary
|
|
375
|
+
: content.slice(completionPrefix.length);
|
|
376
|
+
const safeSummary = safeTerminalText(summary);
|
|
377
|
+
return safeSummary ? `**Goal complete**\n\n${safeSummary}` : "**Goal complete**";
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
export function renderGoalCompletion(result: GoalCompletionRenderResult) {
|
|
381
|
+
return new Markdown(goalCompletionMarkdown(result), 0, 0, getMarkdownTheme());
|
|
382
|
+
}
|
|
383
|
+
|
|
349
384
|
function toolContent(text: string) {
|
|
350
385
|
return [
|
|
351
386
|
{
|