@narumitw/pi-goal 0.54.3 → 0.54.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +117 -190
  2. package/dist/chunks/{chunk-QWIUWKRW.js → chunk-VJ5LR26S.js} +57 -77
  3. package/dist/chunks/chunk-VJ5LR26S.js.map +7 -0
  4. package/dist/chunks/{chunk-UQRRW4CY.js → chunk-WQIA35U2.js} +6 -5
  5. package/dist/chunks/chunk-WQIA35U2.js.map +7 -0
  6. package/dist/chunks/{menu-WEFDREGC.js → menu-JMGWQZIT.js} +7 -22
  7. package/dist/chunks/menu-JMGWQZIT.js.map +7 -0
  8. package/dist/chunks/{settings-ui-MVYTTBHW.js → settings-ui-JG3PFRB5.js} +6 -18
  9. package/dist/chunks/settings-ui-JG3PFRB5.js.map +7 -0
  10. package/dist/index.ts +111 -126
  11. package/dist/index.ts.map +2 -2
  12. package/docs/managing-goals.md +47 -0
  13. package/docs/settings.md +91 -0
  14. package/package.json +55 -58
  15. package/src/accounting.ts +62 -66
  16. package/src/command-registration.ts +104 -102
  17. package/src/command.ts +101 -112
  18. package/src/commands.ts +465 -501
  19. package/src/errors.ts +127 -122
  20. package/src/goal-contract.ts +64 -64
  21. package/src/goal.ts +25 -25
  22. package/src/lifecycle.ts +615 -628
  23. package/src/markers.ts +6 -6
  24. package/src/menu.ts +565 -591
  25. package/src/persistence.ts +177 -192
  26. package/src/prompts.ts +53 -67
  27. package/src/run-protocol.ts +299 -325
  28. package/src/runtime.ts +1422 -1495
  29. package/src/safety.ts +51 -51
  30. package/src/settings-ui.ts +366 -393
  31. package/src/settings.ts +134 -147
  32. package/src/tool-policy.ts +6 -6
  33. package/src/tools.ts +371 -347
  34. package/src/wait.ts +47 -51
  35. package/src/workflow-mutex.ts +68 -68
  36. package/dist/chunks/chunk-QWIUWKRW.js.map +0 -7
  37. package/dist/chunks/chunk-UQRRW4CY.js.map +0 -7
  38. package/dist/chunks/menu-WEFDREGC.js.map +0 -7
  39. package/dist/chunks/settings-ui-MVYTTBHW.js.map +0 -7
package/src/lifecycle.ts CHANGED
@@ -2,648 +2,635 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { currentTokenTotal } from "./accounting.js";
3
3
  import { notifyTerminal } from "./errors.js";
4
4
  import {
5
- GOAL_CONTRACT_MESSAGE_TYPE,
6
- isGoalContextContract,
7
- reconcileGoalContextContract,
8
- reconcileInactiveGoalContextContract,
5
+ GOAL_CONTRACT_MESSAGE_TYPE,
6
+ isGoalContextContract,
7
+ reconcileGoalContextContract,
8
+ reconcileInactiveGoalContextContract,
9
9
  } from "./goal-contract.js";
10
10
  import { type ActiveGoal, loadGoalStateFromSession } from "./persistence.js";
11
11
  import type { GoalRunController } from "./run-protocol.js";
12
12
  import {
13
- type AssistantMessageLike,
14
- abortCurrentTurn,
15
- blocksStaleGoalToolCalls,
16
- findFinalAssistantMessage,
17
- type GoalRuntime,
18
- incrementGoal,
19
- isGoalContextOverflow,
20
- isRetryableGoalInterruption,
21
- isUsageLimitedGoalInterruption,
22
- resetGoalSafetyEpoch,
23
- STATUS_KEY,
24
- type StatusContext,
25
- transitionGoal,
26
- truncateNotification,
13
+ type AssistantMessageLike,
14
+ abortCurrentTurn,
15
+ blocksStaleGoalToolCalls,
16
+ findFinalAssistantMessage,
17
+ type GoalRuntime,
18
+ incrementGoal,
19
+ isGoalContextOverflow,
20
+ isRetryableGoalInterruption,
21
+ isUsageLimitedGoalInterruption,
22
+ resetGoalSafetyEpoch,
23
+ STATUS_KEY,
24
+ type StatusContext,
25
+ transitionGoal,
26
+ truncateNotification,
27
27
  } from "./runtime.js";
28
28
  import { hasAssistantToolCall } from "./safety.js";
29
29
  import { DEFAULT_GOAL_SETTINGS, readGoalSettings } from "./settings.js";
30
30
 
31
31
  const REMOVED_QUEUE_SETTING_WARNING =
32
- "Ordered goal queue has been removed. Use /goal edit to reprioritize an active objective, or start /goal <objectives> if no active goal exists.";
32
+ "Ordered goal queue has been removed. Use /goal edit to reprioritize an active objective, or start /goal <objectives> if no active goal exists.";
33
33
  const REMOVED_PERSISTED_QUEUE_WARNING =
34
- "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.";
34
+ "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.";
35
35
 
36
36
  interface GoalLifecycleOptions {
37
- settingsPath?: string;
37
+ settingsPath?: string;
38
38
  }
39
39
 
40
40
  export function registerGoalLifecycle(
41
- pi: ExtensionAPI,
42
- runtime: GoalRuntime,
43
- runController: GoalRunController,
44
- options: GoalLifecycleOptions = {},
41
+ pi: ExtensionAPI,
42
+ runtime: GoalRuntime,
43
+ runController: GoalRunController,
44
+ options: GoalLifecycleOptions = {},
45
45
  ) {
46
- pi.on("session_start", async (_event, ctx) => {
47
- runtime.bindWorkflowSession(ctx.sessionManager);
48
- runtime.replaceMenuSession();
49
- runtime.clearCompletionStatusTimer();
50
- runtime.clearContinuationTracking();
51
- runtime.clearGoalWaitTimer();
52
- runtime.clearPendingGoalPrompts();
53
- runtime.clearAgentRun();
54
- runtime.guardAbortGoalId = undefined;
55
- runtime.clearGoalRecovery();
56
- runtime.clearBudgetWrapUp();
57
- runtime.clearStaleGoalToolCallBlock();
58
- runtime.legacyQueueState = undefined;
59
- runtime.legacyExperimentalGoalsSetting = false;
60
- runtime.clearTerminalDetails();
61
- const settingsResult = readGoalSettings(options.settingsPath);
62
- const loaded = loadGoalStateFromSession(ctx);
63
- runtime.settings =
64
- settingsResult.kind === "loaded" ? settingsResult.settings : DEFAULT_GOAL_SETTINGS;
65
- runtime.settingsLoadIssue = settingsResult.kind === "invalid" ? settingsResult : undefined;
66
- runtime.activeGoal = undefined;
67
- runtime.legacyQueueState = loaded.legacyQueueState;
68
- runtime.legacyExperimentalGoalsSetting =
69
- settingsResult.kind !== "invalid" && settingsResult.legacyExperimentalGoals;
70
- runController.bindSession(ctx);
71
-
72
- if (settingsResult.kind === "invalid") {
73
- notifyTerminal(
74
- ctx.ui,
75
- `pi-goal settings ignored: ${settingsResult.reason}. Using default settings.`,
76
- "warning",
77
- );
78
- }
79
- if (runtime.legacyExperimentalGoalsSetting && !runtime.legacyQueueState) {
80
- notifyTerminal(ctx.ui, REMOVED_QUEUE_SETTING_WARNING, "warning");
81
- }
82
-
83
- if (loaded.goal?.status === "active") {
84
- if (!runtime.acquireWorkflow()) {
85
- runtime.activeGoal = transitionGoal(loaded.goal, "paused");
86
- runtime.persistGoal(runtime.activeGoal);
87
- runtime.ensureInactiveGoalContextContract(ctx);
88
- runtime.updateStatus(ctx, runtime.activeGoal);
89
- notifyTerminal(
90
- ctx.ui,
91
- "Goal was paused during restore because another workflow is active in this session. Resume it after the other workflow ends.",
92
- "warning",
93
- );
94
- return;
95
- }
96
- runtime.activeGoal = loaded.goal;
97
- if (runtime.activeGoal.safetyResetPending) {
98
- // Resume/edit activation is persisted before its owned prompt starts. A
99
- // reload must commit that promised reset before enforcing the old limits.
100
- runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
101
- }
102
- runtime.recordGoalUsage(runtime.activeGoal, ctx);
103
- if (runtime.limitActiveGoalForBudget(ctx, false)) return;
104
- if (runtime.enforceAutomaticTurnLimit(ctx, false) || runtime.enforceNoProgressLimit(ctx)) {
105
- return;
106
- }
107
- if (!runtime.goalToolsAvailable()) {
108
- runtime.pauseGoalForUnavailableTools(ctx, false);
109
- return;
110
- }
111
- runtime.persistGoal(runtime.activeGoal);
112
- if (!runtime.ownsWorkflow(runtime.activeGoal)) return;
113
- const restoredGoalId = runtime.activeGoal.id;
114
- runtime.ensureGoalContextContract(ctx, runtime.activeGoal);
115
- if (
116
- runtime.activeGoal?.id !== restoredGoalId ||
117
- runtime.activeGoal.status !== "active" ||
118
- !runtime.ownsWorkflow(runtime.activeGoal)
119
- ) {
120
- return;
121
- }
122
- runtime.updateStatus(ctx, runtime.activeGoal);
123
- runtime.restoreGoalWaitTimer(ctx);
124
- return;
125
- }
126
-
127
- runtime.activeGoal = loaded.goal;
128
- if (runtime.legacyQueueState) {
129
- ctx.ui.setStatus(STATUS_KEY, undefined);
130
- notifyTerminal(ctx.ui, REMOVED_PERSISTED_QUEUE_WARNING, "warning");
131
- return;
132
- }
133
- if (runtime.activeGoal) {
134
- runtime.persistGoal(runtime.activeGoal);
135
- runtime.ensureInactiveGoalContextContract(ctx);
136
- runtime.updateStatus(ctx, runtime.activeGoal);
137
- } else {
138
- runtime.ensureInactiveGoalContextContract(ctx);
139
- ctx.ui.setStatus(STATUS_KEY, undefined);
140
- }
141
- });
142
-
143
- pi.on("session_shutdown", (_event, ctx) => {
144
- const shutdownSession = ctx.sessionManager;
145
- runController.unbindSession();
146
- runtime.closeMenuSession();
147
- runtime.clearGoalWaitTimer();
148
- if (runtime.activeGoal) {
149
- if (runtime.activeGoal.status === "active") {
150
- runtime.recordGoalUsage(runtime.activeGoal, ctx, false);
151
- }
152
- runtime.persistGoal(runtime.activeGoal);
153
- }
154
- runtime.clearContinuationTracking();
155
- runtime.clearPendingGoalPrompts();
156
- runtime.clearAgentRun();
157
- runtime.guardAbortGoalId = undefined;
158
- runtime.clearGoalRecovery();
159
- runtime.clearBudgetWrapUp();
160
- runtime.clearStaleGoalToolCallBlock();
161
- runtime.activeGoal = undefined;
162
- runtime.legacyQueueState = undefined;
163
- runtime.legacyExperimentalGoalsSetting = false;
164
- ctx.ui.setStatus(STATUS_KEY, undefined);
165
- runtime.clearCompletionStatusTimer();
166
- runtime.clearTerminalDetails();
167
- runtime.releaseWorkflow();
168
- runtime.unbindWorkflowSession(shutdownSession);
169
- });
170
-
171
- pi.on("session_before_compact", (event, ctx) => {
172
- if (runtime.activeGoal?.status === "budget_limited") {
173
- if ((event as { willRetry?: boolean }).willRetry === true) return { cancel: true as const };
174
- return;
175
- }
176
- if (runtime.activeGoal?.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
177
- return;
178
- }
179
- if (!runtime.recordGoalUsage(runtime.activeGoal, ctx)) return;
180
- runtime.cancelContinuationWork();
181
- runtime.persistGoal(runtime.activeGoal);
182
- runtime.updateStatus(ctx, runtime.activeGoal);
183
- if (runtime.limitActiveGoalForBudget(ctx, false)) return { cancel: true as const };
184
- });
185
-
186
- pi.on("session_compact", async (event, ctx) => {
187
- if (runtime.activeGoal?.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
188
- runtime.clearGoalRecovery();
189
- return;
190
- }
191
-
192
- const restoredState = loadGoalStateFromSession(ctx);
193
- if (restoredState.goal?.id === runtime.activeGoal.id) {
194
- runtime.activeGoal = restoredState.goal;
195
- }
196
- const usageRecorded = runtime.recordGoalUsage(runtime.activeGoal, ctx);
197
- if (usageRecorded) {
198
- runtime.persistGoal(runtime.activeGoal);
199
- runtime.updateStatus(ctx, runtime.activeGoal);
200
- }
201
- if (runtime.limitActiveGoalForBudget(ctx, false)) return;
202
- const compactedGoalId = runtime.activeGoal.id;
203
- runtime.ensureGoalContextContract(ctx, runtime.activeGoal);
204
- if (
205
- runtime.activeGoal?.id !== compactedGoalId ||
206
- runtime.activeGoal.status !== "active" ||
207
- !runtime.ownsWorkflow(runtime.activeGoal)
208
- ) {
209
- return;
210
- }
211
- if (!usageRecorded) return;
212
-
213
- const wasPiRetry = runtime.isPiOwnedCompactionRetry(event, runtime.activeGoal.id);
214
- if (wasPiRetry) return;
215
- runtime.clearGoalRecoveryForGoal(runtime.activeGoal.id);
216
- runtime.requestContinuation(runtime.activeGoal);
217
- // Pi emits session_compact before it clears its manual-compaction controller,
218
- // so sendUserMessage still rejects inside this hook even when ctx reports idle.
219
- // Defer one task; threshold compaction retains the intent for agent_settled
220
- // when Pi is still busy.
221
- runtime.scheduleContinuationDispatch(ctx, runtime.activeGoal.id);
222
- });
223
-
224
- pi.on("input", (event, ctx) => {
225
- if (event.source === "extension") {
226
- if (
227
- runtime.consumeCancelledGoalPrompt(event.text) ||
228
- runtime.consumeCancelledContinuationPrompt(event.text) ||
229
- runtime.consumeStaleOwnedGoalPrompt(event.text)
230
- ) {
231
- return { action: "handled" as const };
232
- }
233
- // Streaming input is queued before its model work starts. Keep owned
234
- // markers pending for message_start, and track non-goal delivery mode so a
235
- // steer cannot consume a later follow-up's cleanup protection.
236
- if (runtime.acceptOwnedInputBoundary(event.text)) return;
237
- runtime.supersedeOwnedInputCollision(event.text);
238
- if (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);
239
- if (event.streamingBehavior === "steer" || event.streamingBehavior === "followUp") {
240
- runtime.noteQueuedNonGoalInput(event.text, event.streamingBehavior);
241
- }
242
- runtime.clearGoalRecovery();
243
- return;
244
- }
245
- if (/^\/goal(?:\s|$)/u.test(event.text.trimStart())) return;
246
- if (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);
247
- if (event.streamingBehavior === "followUp") {
248
- runtime.noteQueuedNonGoalInput(event.text, "followUp", true);
249
- return;
250
- }
251
- if (event.streamingBehavior === "steer") {
252
- runtime.noteQueuedNonGoalInput(event.text, "steer");
253
- }
254
- runtime.clearGoalRecovery();
255
- runtime.clearBudgetWrapUp();
256
- runtime.clearStaleGoalToolCallBlock();
257
- runtime.resetActiveSafetyEpoch(ctx);
258
- });
259
-
260
- pi.on("message_start", (event, ctx) => {
261
- const message = event.message as { role?: unknown; content?: unknown };
262
- if (
263
- message.role === "assistant" &&
264
- runtime.activeGoal?.status === "paused" &&
265
- runtime.guardAbortGoalId === runtime.activeGoal.id
266
- ) {
267
- abortCurrentTurn(ctx);
268
- return;
269
- }
270
- if (message.role === "custom") {
271
- if (Reflect.get(message, "customType") === GOAL_CONTRACT_MESSAGE_TYPE) return;
272
- if (runtime.isActiveBudgetWrapUpMessage(message)) return;
273
- if (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);
274
- if (runtime.guardAbortGoalId === runtime.activeGoal?.id) {
275
- runtime.guardAbortGoalId = undefined;
276
- }
277
- beginNonGoalFollowUp(ctx, false);
278
- return;
279
- }
280
- if (message.role !== "user") return;
281
- const prompt = Array.isArray(message.content)
282
- ? message.content
283
- .filter(
284
- (part) => part && typeof part === "object" && Reflect.get(part, "type") === "text",
285
- )
286
- .map((part) => Reflect.get(part as object, "text"))
287
- .filter((text): text is string => typeof text === "string")
288
- .join("\n")
289
- : typeof message.content === "string"
290
- ? message.content
291
- : "";
292
- const ownedPrompt = runtime.consumeOwnedGoalPrompt(prompt);
293
- const ownedPromptBoundary = runtime.hasOwnedPromptBoundary(prompt);
294
- const queuedNonGoalInput = runtime.consumeQueuedNonGoalInput(prompt, !ownedPromptBoundary);
295
- if (!ownedPrompt) {
296
- if (queuedNonGoalInput?.behavior === "followUp") {
297
- beginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);
298
- }
299
- return;
300
- }
301
- if (
302
- runtime.activeGoal?.id !== ownedPrompt.goalId ||
303
- !runtime.ownsWorkflow(runtime.activeGoal)
304
- ) {
305
- return;
306
- }
307
- if (runtime.agentRunGoalId !== undefined && runtime.agentRunGoalId !== ownedPrompt.goalId) {
308
- runtime.activeGoal.baselineTokens = Math.max(
309
- 0,
310
- currentTokenTotal(ctx) - runtime.activeGoal.tokensUsed,
311
- );
312
- }
313
- runtime.beginAgentRun(ownedPrompt.goalId, "manual");
314
- if (ownedPrompt.resetSafetyEpoch) {
315
- runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
316
- }
317
- runtime.persistGoal(runtime.activeGoal);
318
- runtime.updateStatus(ctx, runtime.activeGoal);
319
- });
320
-
321
- pi.on("context", (event, ctx) => {
322
- const keptMessages = event.messages.filter((message) =>
323
- runtime.keepBudgetWrapUpMessage(message),
324
- );
325
- const hasGoalContractHistory =
326
- keptMessages.some(isGoalContextContract) || runtime.hasGoalContextContractHistory(ctx);
327
- const messages =
328
- runtime.activeGoal?.status === "active" && runtime.ownsWorkflow(runtime.activeGoal)
329
- ? reconcileGoalContextContract(keptMessages, runtime.activeGoal)
330
- : hasGoalContractHistory
331
- ? reconcileInactiveGoalContextContract(keptMessages)
332
- : keptMessages;
333
- if (
334
- runtime.activeGoal?.status === "paused" &&
335
- runtime.guardAbortGoalId === runtime.activeGoal.id
336
- ) {
337
- // A current custom follow-up clears the guard at message_start. Otherwise,
338
- // context transformation aborts before the provider adapter receives the signal.
339
- abortCurrentTurn(ctx);
340
- }
341
- if (messages !== keptMessages || keptMessages.length !== event.messages.length) {
342
- return { messages: messages as typeof event.messages };
343
- }
344
- });
345
-
346
- pi.on("tool_call", (event, ctx) => {
347
- runtime.markAgentToolAttempted();
348
- if (
349
- runtime.activeGoal?.status === "budget_limited" &&
350
- runtime.budgetWrapUp?.goalId === runtime.activeGoal.id &&
351
- event.toolName !== "goal_complete"
352
- ) {
353
- // A blocked tool result would normally trigger another model call. Abort the
354
- // wrap-up instead so a tool-seeking model cannot create an unbounded loop.
355
- abortCurrentTurn(ctx);
356
- return {
357
- block: true,
358
- reason: "Goal token budget is exhausted; only goal_complete is allowed during wrap-up.",
359
- };
360
- }
361
- if (!runtime.staleGoalToolCallsBlocked) return;
362
- if (!runtime.activeGoal || !blocksStaleGoalToolCalls(runtime.activeGoal.status)) {
363
- runtime.clearStaleGoalToolCallBlock();
364
- return;
365
- }
366
- // A blocked tool result would normally trigger another model call. Abort the
367
- // current turn so a tool-seeking model cannot create an unbounded loop that
368
- // burns provider quota while the goal is stopped.
369
- abortCurrentTurn(ctx);
370
- return {
371
- block: true,
372
- reason: "Blocked stale /goal tool call after the goal stopped or was interrupted.",
373
- };
374
- });
375
-
376
- pi.on("tool_execution_end", (_event, ctx) => {
377
- if (
378
- runtime.activeGoal?.status === "budget_limited" &&
379
- runtime.budgetWrapUp?.goalId === runtime.activeGoal.id &&
380
- !runtime.budgetWrapUp.delivered
381
- ) {
382
- runtime.queueBudgetWrapUp(ctx, runtime.activeGoal);
383
- return;
384
- }
385
- if (runtime.activeGoal?.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
386
- return;
387
- }
388
-
389
- // AgentSession persists assistant message_end before tool execution events,
390
- // so the completed assistant call's usage is authoritative at this boundary.
391
- if (!runtime.recordGoalUsage(runtime.activeGoal, ctx)) return;
392
- runtime.persistGoal(runtime.activeGoal);
393
- runtime.updateStatus(ctx, runtime.activeGoal);
394
- if (runtime.limitActiveGoalForBudget(ctx, true)) return;
395
- if (!runtime.goalToolsAvailable()) runtime.pauseGoalForUnavailableTools(ctx);
396
- });
397
-
398
- pi.on("before_agent_start", (event, ctx) => {
399
- runtime.clearAgentRun();
400
- // Pi-owned retries emit agent_start directly. Reaching a normal prompt
401
- // boundary means cleanup no longer owns the next run, so the hard-cap guard
402
- // must not abort it.
403
- if (runtime.guardAbortGoalId) runtime.guardAbortGoalId = undefined;
404
- const goalPrompt = runtime.consumeOwnedGoalPrompt(event.prompt);
405
- const goalPromptGoalId = goalPrompt?.goalId;
406
- const continuationGoalId = goalPromptGoalId
407
- ? undefined
408
- : runtime.markContinuationStarted(event.prompt);
409
- const ownedPromptGoalId = goalPromptGoalId ?? continuationGoalId;
410
- const ownedPromptBoundary = runtime.hasOwnedPromptBoundary(event.prompt);
411
- const activeBudgetWrapUp = runtime.hasActiveBudgetWrapUp();
412
- const activeGoalRecovery = runtime.hasActiveGoalRecovery();
413
- const queuedNonGoalInput = activeBudgetWrapUp
414
- ? undefined
415
- : runtime.consumeQueuedNonGoalInput(
416
- event.prompt,
417
- !activeGoalRecovery && ownedPromptGoalId === undefined && !ownedPromptBoundary,
418
- );
419
- if (queuedNonGoalInput?.behavior === "followUp") {
420
- beginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);
421
- }
422
- if (!ownedPromptGoalId && !ownedPromptBoundary) {
423
- runtime.supersedeOwnedInputCollision(event.prompt);
424
- if (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);
425
- }
426
- if (runtime.activeGoal?.status === "active" && !runtime.ownsWorkflow(runtime.activeGoal)) {
427
- runtime.cancelContinuationWork();
428
- runtime.clearGoalRecovery();
429
- abortCurrentTurn(ctx);
430
- return;
431
- }
432
- const runOrigin = continuationGoalId
433
- ? "automatic"
434
- : activeGoalRecovery && runtime.goalRecovery?.automaticOwner
435
- ? "automatic"
436
- : "manual";
437
- if (activeBudgetWrapUp && runtime.activeGoal) {
438
- runtime.beginAgentRun(runtime.activeGoal.id, "manual");
439
- return goalContractBoundaryResult(ctx);
440
- }
441
- if (ownedPromptGoalId && ownedPromptGoalId !== runtime.activeGoal?.id) {
442
- runtime.beginAgentRun(ownedPromptGoalId, runOrigin);
443
- if (runtime.activeGoal?.status === "active" && !runtime.goalToolsAvailable()) {
444
- runtime.pauseGoalForUnavailableTools(ctx, false);
445
- }
446
- abortCurrentTurn(ctx);
447
- return;
448
- }
449
- if (runtime.activeGoal?.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
450
- return goalContractBoundaryResult(ctx);
451
- }
452
- runtime.beginAgentRun(runtime.activeGoal.id, runOrigin);
453
- if (!runtime.goalToolsAvailable()) {
454
- runtime.pauseGoalForUnavailableTools(ctx, ownedPromptGoalId !== undefined);
455
- return goalContractBoundaryResult(ctx);
456
- }
457
- if (goalPrompt?.resetSafetyEpoch && goalPromptGoalId === runtime.activeGoal.id) {
458
- runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
459
- runtime.persistGoal(runtime.activeGoal);
460
- runtime.updateStatus(ctx, runtime.activeGoal);
461
- }
462
- return goalContractBoundaryResult(ctx, runtime.activeGoal);
463
- });
464
-
465
- pi.on("agent_start", (_event, _ctx) => {
466
- const activeGoal = runtime.activeGoal;
467
- if (
468
- activeGoal &&
469
- runtime.guardAbortGoalId === activeGoal.id &&
470
- activeGoal.status === "paused"
471
- ) {
472
- if (runtime.consumeQueuedNonGoalFollowUpForAgentStart()) {
473
- runtime.guardAbortGoalId = undefined;
474
- runtime.clearStaleGoalToolCallBlock();
475
- runtime.beginAgentRun(null, undefined);
476
- }
477
- // Unknown runs defer cleanup until their message/context boundary: custom
478
- // follow-ups have no input event, while bare recovery is aborted pre-provider.
479
- return;
480
- }
481
- runtime.beginRecoveryRunIfNeeded();
482
- });
483
-
484
- pi.on("turn_end", (event, ctx) => {
485
- runtime.recordAutomaticTurn(ctx, event.message);
486
- // Terminal Goal tools transition state synchronously, but their inactive contract
487
- // must wait until Pi has persisted the real tool result at this turn boundary.
488
- if (runtime.activeGoal?.status !== "active") {
489
- runtime.ensureInactiveGoalContextContract(ctx);
490
- }
491
- });
492
-
493
- pi.on("agent_end", (event, ctx) => {
494
- const run = runtime.finishAgentRun();
495
- if (run.goalId === null) return;
496
- if (!runtime.canRecordGoalUsage() && !runtime.hasActiveBudgetWrapUp()) return;
497
- if (run.goalId && run.goalId !== runtime.activeGoal?.id) return;
498
- if (!runtime.activeGoal) return;
499
- if (
500
- runtime.activeGoal.status === "budget_limited" &&
501
- runtime.budgetWrapUp?.goalId === runtime.activeGoal.id
502
- ) {
503
- runtime.recordGoalUsage(runtime.activeGoal, ctx);
504
- runtime.persistGoal(runtime.activeGoal);
505
- runtime.updateStatus(ctx, runtime.activeGoal);
506
- runtime.clearBudgetWrapUp();
507
- return;
508
- }
509
- if (runtime.activeGoal.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
510
- return;
511
- }
512
-
513
- const goalId = runtime.activeGoal.id;
514
- const alreadyAwaitingContinuation = runtime.hasContinuationWorkForGoal(goalId);
515
- const finalAssistant = findFinalAssistantMessage(event.messages);
516
-
517
- if (!alreadyAwaitingContinuation) runtime.activeGoal = incrementGoal(runtime.activeGoal);
518
- runtime.recordGoalUsage(runtime.activeGoal, ctx);
519
-
520
- if (finalAssistant?.stopReason === "aborted") {
521
- runtime.clearGoalRecoveryForGoal(goalId);
522
- stopGoalAfterAgentEnd(ctx, runtime.activeGoal, finalAssistant, "paused");
523
- return;
524
- }
525
-
526
- if (finalAssistant?.stopReason === "error") {
527
- if (isRetryableGoalInterruption(finalAssistant)) {
528
- if (run.origin === "automatic" && runtime.enforceAutomaticTurnLimit(ctx, true)) return;
529
- if (runtime.limitActiveGoalForBudget(ctx, false)) return;
530
- if (!runtime.goalToolsAvailable()) {
531
- runtime.pauseGoalForUnavailableTools(ctx);
532
- return;
533
- }
534
- runtime.goalRecovery = {
535
- goalId,
536
- kind: isGoalContextOverflow(finalAssistant) ? "compaction_retry" : "provider_retry",
537
- automaticOwner: run.origin === "automatic",
538
- errorMessage: finalAssistant.errorMessage,
539
- };
540
- runtime.cancelContinuationWork();
541
- runtime.persistGoal(runtime.activeGoal);
542
- runtime.updateStatus(ctx, runtime.activeGoal);
543
- return;
544
- }
545
- runtime.clearGoalRecoveryForGoal(goalId);
546
- stopGoalAfterAgentEnd(
547
- ctx,
548
- runtime.activeGoal,
549
- finalAssistant,
550
- isUsageLimitedGoalInterruption(finalAssistant) ? "usage_limited" : "blocked",
551
- );
552
- return;
553
- }
554
-
555
- runtime.clearGoalRecoveryForGoal(goalId);
556
-
557
- if (runtime.limitActiveGoalForBudget(ctx, false)) return;
558
- if (!runtime.goalToolsAvailable()) {
559
- runtime.pauseGoalForUnavailableTools(ctx);
560
- return;
561
- }
562
- if (
563
- run.origin === "automatic" &&
564
- runtime.recordAutomaticRunProgress(
565
- ctx,
566
- goalId,
567
- event.messages,
568
- run.toolAttempted || hasAssistantToolCall(event.messages),
569
- )
570
- ) {
571
- return;
572
- }
573
-
574
- runtime.persistGoal(runtime.activeGoal);
575
- runtime.updateStatus(ctx, runtime.activeGoal);
576
-
577
- const currentGoal = runtime.activeGoal;
578
- if (!currentGoal || currentGoal.id !== goalId || currentGoal.status !== "active") return;
579
- runtime.requestContinuation(currentGoal);
580
- });
581
-
582
- pi.on("agent_settled", (_event, ctx) => {
583
- if (runtime.activeGoal?.status === "active" && !runtime.ownsWorkflow(runtime.activeGoal)) {
584
- runtime.cancelContinuationWork();
585
- runtime.clearGoalRecovery();
586
- runtime.clearSettledSafetyTracking();
587
- return;
588
- }
589
- runtime.finalizeSettledRecovery(ctx);
590
- const resumedWait = runtime.dispatchDueGoalWait(ctx);
591
- if (!resumedWait) runtime.dispatchContinuationIfSettled(ctx);
592
- runtime.clearSettledSafetyTracking();
593
- });
594
-
595
- function goalContractBoundaryResult(ctx: StatusContext, goal?: ActiveGoal) {
596
- const message = runtime.goalContextContractForPrompt(ctx, goal);
597
- return message ? { message } : undefined;
598
- }
599
-
600
- function beginNonGoalFollowUp(ctx: StatusContext, resetSafetyEpoch: boolean) {
601
- runtime.clearGoalRecovery();
602
- runtime.clearStaleGoalToolCallBlock();
603
- if (resetSafetyEpoch) runtime.clearBudgetWrapUp();
604
- const activeGoalId =
605
- runtime.activeGoal?.status === "active" ? runtime.activeGoal.id : undefined;
606
- runtime.beginAgentRun(activeGoalId ?? null, activeGoalId ? "manual" : undefined);
607
- if (resetSafetyEpoch && activeGoalId) runtime.resetActiveSafetyEpoch(ctx);
608
- }
609
-
610
- function stopGoalAfterAgentEnd(
611
- ctx: StatusContext,
612
- goal: ActiveGoal,
613
- assistant: AssistantMessageLike,
614
- status: "paused" | "blocked" | "usage_limited",
615
- ) {
616
- const stoppedGoal = runtime.stopActiveGoal(ctx, {
617
- kind: "agent_interruption",
618
- expectedGoalId: goal.id,
619
- status,
620
- reason: assistant.errorMessage ?? `goal ${status} after agent interruption`,
621
- });
622
- if (!stoppedGoal) return;
623
-
624
- const details = assistant.errorMessage
625
- ? ` (${truncateNotification(assistant.errorMessage)})`
626
- : "";
627
- if (status === "paused") {
628
- notifyTerminal(
629
- ctx.ui,
630
- `Goal paused after interruption${details}. Run /goal resume to continue.`,
631
- "warning",
632
- );
633
- return;
634
- }
635
- if (status === "usage_limited") {
636
- notifyTerminal(
637
- ctx.ui,
638
- `Goal stopped after provider usage limit${details}. Run /goal resume when usage is available.`,
639
- "warning",
640
- );
641
- return;
642
- }
643
- notifyTerminal(
644
- ctx.ui,
645
- `Goal blocked after agent error${details}. Resolve the blocker or run /goal resume to retry.`,
646
- "warning",
647
- );
648
- }
46
+ // Pi invalidates this module's ExtensionContext when the session is replaced
47
+ // or reloaded, but detached prompts and queued emits can still invoke these
48
+ // handlers afterward. After session_shutdown every ctx getter throws a stale
49
+ // context error, so late handlers must return before touching ctx. The flag
50
+ // starts true so handlers keep working on runners where session_start was
51
+ // never emitted (for example late extension loading).
52
+ let sessionActive = true;
53
+ pi.on("session_start", async (_event, ctx) => {
54
+ sessionActive = true;
55
+ runtime.bindWorkflowSession(ctx.sessionManager);
56
+ runtime.replaceMenuSession();
57
+ runtime.clearCompletionStatusTimer();
58
+ runtime.clearContinuationTracking();
59
+ runtime.clearGoalWaitTimer();
60
+ runtime.clearPendingGoalPrompts();
61
+ runtime.clearAgentRun();
62
+ runtime.guardAbortGoalId = undefined;
63
+ runtime.clearGoalRecovery();
64
+ runtime.clearBudgetWrapUp();
65
+ runtime.clearStaleGoalToolCallBlock();
66
+ runtime.legacyQueueState = undefined;
67
+ runtime.legacyExperimentalGoalsSetting = false;
68
+ runtime.clearTerminalDetails();
69
+ const settingsResult = readGoalSettings(options.settingsPath);
70
+ const loaded = loadGoalStateFromSession(ctx);
71
+ runtime.settings = settingsResult.kind === "loaded" ? settingsResult.settings : DEFAULT_GOAL_SETTINGS;
72
+ runtime.settingsLoadIssue = settingsResult.kind === "invalid" ? settingsResult : undefined;
73
+ runtime.activeGoal = undefined;
74
+ runtime.legacyQueueState = loaded.legacyQueueState;
75
+ runtime.legacyExperimentalGoalsSetting =
76
+ settingsResult.kind !== "invalid" && settingsResult.legacyExperimentalGoals;
77
+ runController.bindSession(ctx);
78
+
79
+ if (settingsResult.kind === "invalid") {
80
+ notifyTerminal(ctx.ui, `pi-goal settings ignored: ${settingsResult.reason}. Using default settings.`, "warning");
81
+ }
82
+ if (runtime.legacyExperimentalGoalsSetting && !runtime.legacyQueueState) {
83
+ notifyTerminal(ctx.ui, REMOVED_QUEUE_SETTING_WARNING, "warning");
84
+ }
85
+
86
+ if (loaded.goal?.status === "active") {
87
+ if (!runtime.acquireWorkflow()) {
88
+ runtime.activeGoal = transitionGoal(loaded.goal, "paused");
89
+ runtime.persistGoal(runtime.activeGoal);
90
+ runtime.ensureInactiveGoalContextContract(ctx);
91
+ runtime.updateStatus(ctx, runtime.activeGoal);
92
+ notifyTerminal(
93
+ ctx.ui,
94
+ "Goal was paused during restore because another workflow is active in this session. Resume it after the other workflow ends.",
95
+ "warning",
96
+ );
97
+ return;
98
+ }
99
+ runtime.activeGoal = loaded.goal;
100
+ if (runtime.activeGoal.safetyResetPending) {
101
+ // Resume/edit activation is persisted before its owned prompt starts. A
102
+ // reload must commit that promised reset before enforcing the old limits.
103
+ runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
104
+ }
105
+ runtime.recordGoalUsage(runtime.activeGoal, ctx);
106
+ if (runtime.limitActiveGoalForBudget(ctx, false)) return;
107
+ if (runtime.enforceAutomaticTurnLimit(ctx, false) || runtime.enforceNoProgressLimit(ctx)) {
108
+ return;
109
+ }
110
+ if (!runtime.goalToolsAvailable()) {
111
+ runtime.pauseGoalForUnavailableTools(ctx, false);
112
+ return;
113
+ }
114
+ runtime.persistGoal(runtime.activeGoal);
115
+ if (!runtime.ownsWorkflow(runtime.activeGoal)) return;
116
+ const restoredGoalId = runtime.activeGoal.id;
117
+ runtime.ensureGoalContextContract(ctx, runtime.activeGoal);
118
+ if (
119
+ runtime.activeGoal?.id !== restoredGoalId ||
120
+ runtime.activeGoal.status !== "active" ||
121
+ !runtime.ownsWorkflow(runtime.activeGoal)
122
+ ) {
123
+ return;
124
+ }
125
+ runtime.updateStatus(ctx, runtime.activeGoal);
126
+ runtime.restoreGoalWaitTimer(ctx);
127
+ return;
128
+ }
129
+
130
+ runtime.activeGoal = loaded.goal;
131
+ if (runtime.legacyQueueState) {
132
+ ctx.ui.setStatus(STATUS_KEY, undefined);
133
+ notifyTerminal(ctx.ui, REMOVED_PERSISTED_QUEUE_WARNING, "warning");
134
+ return;
135
+ }
136
+ if (runtime.activeGoal) {
137
+ runtime.persistGoal(runtime.activeGoal);
138
+ runtime.ensureInactiveGoalContextContract(ctx);
139
+ runtime.updateStatus(ctx, runtime.activeGoal);
140
+ } else {
141
+ runtime.ensureInactiveGoalContextContract(ctx);
142
+ ctx.ui.setStatus(STATUS_KEY, undefined);
143
+ }
144
+ });
145
+
146
+ pi.on("session_shutdown", (_event, ctx) => {
147
+ sessionActive = false;
148
+ const shutdownSession = ctx.sessionManager;
149
+ runController.unbindSession();
150
+ runtime.closeMenuSession();
151
+ runtime.clearGoalWaitTimer();
152
+ if (runtime.activeGoal) {
153
+ if (runtime.activeGoal.status === "active") {
154
+ runtime.recordGoalUsage(runtime.activeGoal, ctx, false);
155
+ }
156
+ runtime.persistGoal(runtime.activeGoal);
157
+ }
158
+ runtime.clearContinuationTracking();
159
+ runtime.clearPendingGoalPrompts();
160
+ runtime.clearAgentRun();
161
+ runtime.guardAbortGoalId = undefined;
162
+ runtime.clearGoalRecovery();
163
+ runtime.clearBudgetWrapUp();
164
+ runtime.clearStaleGoalToolCallBlock();
165
+ runtime.activeGoal = undefined;
166
+ runtime.legacyQueueState = undefined;
167
+ runtime.legacyExperimentalGoalsSetting = false;
168
+ ctx.ui.setStatus(STATUS_KEY, undefined);
169
+ runtime.clearCompletionStatusTimer();
170
+ runtime.clearTerminalDetails();
171
+ runtime.releaseWorkflow();
172
+ runtime.unbindWorkflowSession(shutdownSession);
173
+ });
174
+
175
+ pi.on("session_before_compact", (event, ctx) => {
176
+ if (!sessionActive) return;
177
+ if (runtime.activeGoal?.status === "budget_limited") {
178
+ if ((event as { willRetry?: boolean }).willRetry === true) return { cancel: true as const };
179
+ return;
180
+ }
181
+ if (runtime.activeGoal?.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
182
+ return;
183
+ }
184
+ if (!runtime.recordGoalUsage(runtime.activeGoal, ctx)) return;
185
+ runtime.cancelContinuationWork();
186
+ runtime.persistGoal(runtime.activeGoal);
187
+ runtime.updateStatus(ctx, runtime.activeGoal);
188
+ if (runtime.limitActiveGoalForBudget(ctx, false)) return { cancel: true as const };
189
+ });
190
+
191
+ pi.on("session_compact", async (event, ctx) => {
192
+ if (!sessionActive) return;
193
+ if (runtime.activeGoal?.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
194
+ runtime.clearGoalRecovery();
195
+ return;
196
+ }
197
+
198
+ const restoredState = loadGoalStateFromSession(ctx);
199
+ if (restoredState.goal?.id === runtime.activeGoal.id) {
200
+ runtime.activeGoal = restoredState.goal;
201
+ }
202
+ const usageRecorded = runtime.recordGoalUsage(runtime.activeGoal, ctx);
203
+ if (usageRecorded) {
204
+ runtime.persistGoal(runtime.activeGoal);
205
+ runtime.updateStatus(ctx, runtime.activeGoal);
206
+ }
207
+ if (runtime.limitActiveGoalForBudget(ctx, false)) return;
208
+ const compactedGoalId = runtime.activeGoal.id;
209
+ runtime.ensureGoalContextContract(ctx, runtime.activeGoal);
210
+ if (
211
+ runtime.activeGoal?.id !== compactedGoalId ||
212
+ runtime.activeGoal.status !== "active" ||
213
+ !runtime.ownsWorkflow(runtime.activeGoal)
214
+ ) {
215
+ return;
216
+ }
217
+ if (!usageRecorded) return;
218
+
219
+ const wasPiRetry = runtime.isPiOwnedCompactionRetry(event, runtime.activeGoal.id);
220
+ if (wasPiRetry) return;
221
+ runtime.clearGoalRecoveryForGoal(runtime.activeGoal.id);
222
+ runtime.requestContinuation(runtime.activeGoal);
223
+ // Pi emits session_compact before it clears its manual-compaction controller,
224
+ // so sendUserMessage still rejects inside this hook even when ctx reports idle.
225
+ // Defer one task; threshold compaction retains the intent for agent_settled
226
+ // when Pi is still busy.
227
+ runtime.scheduleContinuationDispatch(ctx, runtime.activeGoal.id);
228
+ });
229
+
230
+ pi.on("input", (event, ctx) => {
231
+ if (!sessionActive) return;
232
+ if (event.source === "extension") {
233
+ if (
234
+ runtime.consumeCancelledGoalPrompt(event.text) ||
235
+ runtime.consumeCancelledContinuationPrompt(event.text) ||
236
+ runtime.consumeStaleOwnedGoalPrompt(event.text)
237
+ ) {
238
+ return { action: "handled" as const };
239
+ }
240
+ // Streaming input is queued before its model work starts. Keep owned
241
+ // markers pending for message_start, and track non-goal delivery mode so a
242
+ // steer cannot consume a later follow-up's cleanup protection.
243
+ if (runtime.acceptOwnedInputBoundary(event.text)) return;
244
+ runtime.supersedeOwnedInputCollision(event.text);
245
+ if (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);
246
+ if (event.streamingBehavior === "steer" || event.streamingBehavior === "followUp") {
247
+ runtime.noteQueuedNonGoalInput(event.text, event.streamingBehavior);
248
+ }
249
+ runtime.clearGoalRecovery();
250
+ return;
251
+ }
252
+ if (/^\/goal(?:\s|$)/u.test(event.text.trimStart())) return;
253
+ if (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);
254
+ if (event.streamingBehavior === "followUp") {
255
+ runtime.noteQueuedNonGoalInput(event.text, "followUp", true);
256
+ return;
257
+ }
258
+ if (event.streamingBehavior === "steer") {
259
+ runtime.noteQueuedNonGoalInput(event.text, "steer");
260
+ }
261
+ runtime.clearGoalRecovery();
262
+ runtime.clearBudgetWrapUp();
263
+ runtime.clearStaleGoalToolCallBlock();
264
+ runtime.resetActiveSafetyEpoch(ctx);
265
+ });
266
+
267
+ pi.on("message_start", (event, ctx) => {
268
+ if (!sessionActive) return;
269
+ const message = event.message as { role?: unknown; content?: unknown };
270
+ if (
271
+ message.role === "assistant" &&
272
+ runtime.activeGoal?.status === "paused" &&
273
+ runtime.guardAbortGoalId === runtime.activeGoal.id
274
+ ) {
275
+ abortCurrentTurn(ctx);
276
+ return;
277
+ }
278
+ if (message.role === "custom") {
279
+ if (Reflect.get(message, "customType") === GOAL_CONTRACT_MESSAGE_TYPE) return;
280
+ if (runtime.isActiveBudgetWrapUpMessage(message)) return;
281
+ if (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);
282
+ if (runtime.guardAbortGoalId === runtime.activeGoal?.id) {
283
+ runtime.guardAbortGoalId = undefined;
284
+ }
285
+ beginNonGoalFollowUp(ctx, false);
286
+ return;
287
+ }
288
+ if (message.role !== "user") return;
289
+ const prompt = Array.isArray(message.content)
290
+ ? message.content
291
+ .filter((part) => part && typeof part === "object" && Reflect.get(part, "type") === "text")
292
+ .map((part) => Reflect.get(part as object, "text"))
293
+ .filter((text): text is string => typeof text === "string")
294
+ .join("\n")
295
+ : typeof message.content === "string"
296
+ ? message.content
297
+ : "";
298
+ const ownedPrompt = runtime.consumeOwnedGoalPrompt(prompt);
299
+ const ownedPromptBoundary = runtime.hasOwnedPromptBoundary(prompt);
300
+ const queuedNonGoalInput = runtime.consumeQueuedNonGoalInput(prompt, !ownedPromptBoundary);
301
+ if (!ownedPrompt) {
302
+ if (queuedNonGoalInput?.behavior === "followUp") {
303
+ beginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);
304
+ }
305
+ return;
306
+ }
307
+ if (runtime.activeGoal?.id !== ownedPrompt.goalId || !runtime.ownsWorkflow(runtime.activeGoal)) {
308
+ return;
309
+ }
310
+ if (runtime.agentRunGoalId !== undefined && runtime.agentRunGoalId !== ownedPrompt.goalId) {
311
+ runtime.activeGoal.baselineTokens = Math.max(0, currentTokenTotal(ctx) - runtime.activeGoal.tokensUsed);
312
+ }
313
+ runtime.beginAgentRun(ownedPrompt.goalId, "manual");
314
+ if (ownedPrompt.resetSafetyEpoch) {
315
+ runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
316
+ }
317
+ runtime.persistGoal(runtime.activeGoal);
318
+ runtime.updateStatus(ctx, runtime.activeGoal);
319
+ });
320
+
321
+ pi.on("context", (event, ctx) => {
322
+ if (!sessionActive) return;
323
+ const keptMessages = event.messages.filter((message) => runtime.keepBudgetWrapUpMessage(message));
324
+ const hasGoalContractHistory =
325
+ keptMessages.some(isGoalContextContract) || runtime.hasGoalContextContractHistory(ctx);
326
+ const messages =
327
+ runtime.activeGoal?.status === "active" && runtime.ownsWorkflow(runtime.activeGoal)
328
+ ? reconcileGoalContextContract(keptMessages, runtime.activeGoal)
329
+ : hasGoalContractHistory
330
+ ? reconcileInactiveGoalContextContract(keptMessages)
331
+ : keptMessages;
332
+ if (runtime.activeGoal?.status === "paused" && runtime.guardAbortGoalId === runtime.activeGoal.id) {
333
+ // A current custom follow-up clears the guard at message_start. Otherwise,
334
+ // context transformation aborts before the provider adapter receives the signal.
335
+ abortCurrentTurn(ctx);
336
+ }
337
+ if (messages !== keptMessages || keptMessages.length !== event.messages.length) {
338
+ return { messages: messages as typeof event.messages };
339
+ }
340
+ });
341
+
342
+ pi.on("tool_call", (event, ctx) => {
343
+ if (!sessionActive) return;
344
+ runtime.markAgentToolAttempted();
345
+ if (
346
+ runtime.activeGoal?.status === "budget_limited" &&
347
+ runtime.budgetWrapUp?.goalId === runtime.activeGoal.id &&
348
+ event.toolName !== "goal_complete"
349
+ ) {
350
+ // A blocked tool result would normally trigger another model call. Abort the
351
+ // wrap-up instead so a tool-seeking model cannot create an unbounded loop.
352
+ abortCurrentTurn(ctx);
353
+ return {
354
+ block: true,
355
+ reason: "Goal token budget is exhausted; only goal_complete is allowed during wrap-up.",
356
+ };
357
+ }
358
+ if (!runtime.staleGoalToolCallsBlocked) return;
359
+ if (!runtime.activeGoal || !blocksStaleGoalToolCalls(runtime.activeGoal.status)) {
360
+ runtime.clearStaleGoalToolCallBlock();
361
+ return;
362
+ }
363
+ // A blocked tool result would normally trigger another model call. Abort the
364
+ // current turn so a tool-seeking model cannot create an unbounded loop that
365
+ // burns provider quota while the goal is stopped.
366
+ abortCurrentTurn(ctx);
367
+ return {
368
+ block: true,
369
+ reason: "Blocked stale /goal tool call after the goal stopped or was interrupted.",
370
+ };
371
+ });
372
+
373
+ pi.on("tool_execution_end", (_event, ctx) => {
374
+ if (!sessionActive) return;
375
+ if (
376
+ runtime.activeGoal?.status === "budget_limited" &&
377
+ runtime.budgetWrapUp?.goalId === runtime.activeGoal.id &&
378
+ !runtime.budgetWrapUp.delivered
379
+ ) {
380
+ runtime.queueBudgetWrapUp(ctx, runtime.activeGoal);
381
+ return;
382
+ }
383
+ if (runtime.activeGoal?.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
384
+ return;
385
+ }
386
+
387
+ // AgentSession persists assistant message_end before tool execution events,
388
+ // so the completed assistant call's usage is authoritative at this boundary.
389
+ if (!runtime.recordGoalUsage(runtime.activeGoal, ctx)) return;
390
+ runtime.persistGoal(runtime.activeGoal);
391
+ runtime.updateStatus(ctx, runtime.activeGoal);
392
+ if (runtime.limitActiveGoalForBudget(ctx, true)) return;
393
+ if (!runtime.goalToolsAvailable()) runtime.pauseGoalForUnavailableTools(ctx);
394
+ });
395
+
396
+ pi.on("before_agent_start", (event, ctx) => {
397
+ if (!sessionActive) return;
398
+ runtime.clearAgentRun();
399
+ // Pi-owned retries emit agent_start directly. Reaching a normal prompt
400
+ // boundary means cleanup no longer owns the next run, so the hard-cap guard
401
+ // must not abort it.
402
+ if (runtime.guardAbortGoalId) runtime.guardAbortGoalId = undefined;
403
+ const goalPrompt = runtime.consumeOwnedGoalPrompt(event.prompt);
404
+ const goalPromptGoalId = goalPrompt?.goalId;
405
+ const continuationGoalId = goalPromptGoalId ? undefined : runtime.markContinuationStarted(event.prompt);
406
+ const ownedPromptGoalId = goalPromptGoalId ?? continuationGoalId;
407
+ const ownedPromptBoundary = runtime.hasOwnedPromptBoundary(event.prompt);
408
+ const activeBudgetWrapUp = runtime.hasActiveBudgetWrapUp();
409
+ const activeGoalRecovery = runtime.hasActiveGoalRecovery();
410
+ const queuedNonGoalInput = activeBudgetWrapUp
411
+ ? undefined
412
+ : runtime.consumeQueuedNonGoalInput(
413
+ event.prompt,
414
+ !activeGoalRecovery && ownedPromptGoalId === undefined && !ownedPromptBoundary,
415
+ );
416
+ if (queuedNonGoalInput?.behavior === "followUp") {
417
+ beginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);
418
+ }
419
+ if (!ownedPromptGoalId && !ownedPromptBoundary) {
420
+ runtime.supersedeOwnedInputCollision(event.prompt);
421
+ if (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);
422
+ }
423
+ if (runtime.activeGoal?.status === "active" && !runtime.ownsWorkflow(runtime.activeGoal)) {
424
+ runtime.cancelContinuationWork();
425
+ runtime.clearGoalRecovery();
426
+ abortCurrentTurn(ctx);
427
+ return;
428
+ }
429
+ const runOrigin = continuationGoalId
430
+ ? "automatic"
431
+ : activeGoalRecovery && runtime.goalRecovery?.automaticOwner
432
+ ? "automatic"
433
+ : "manual";
434
+ if (activeBudgetWrapUp && runtime.activeGoal) {
435
+ runtime.beginAgentRun(runtime.activeGoal.id, "manual");
436
+ return goalContractBoundaryResult(ctx);
437
+ }
438
+ if (ownedPromptGoalId && ownedPromptGoalId !== runtime.activeGoal?.id) {
439
+ runtime.beginAgentRun(ownedPromptGoalId, runOrigin);
440
+ if (runtime.activeGoal?.status === "active" && !runtime.goalToolsAvailable()) {
441
+ runtime.pauseGoalForUnavailableTools(ctx, false);
442
+ }
443
+ abortCurrentTurn(ctx);
444
+ return;
445
+ }
446
+ if (runtime.activeGoal?.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
447
+ return goalContractBoundaryResult(ctx);
448
+ }
449
+ runtime.beginAgentRun(runtime.activeGoal.id, runOrigin);
450
+ if (!runtime.goalToolsAvailable()) {
451
+ runtime.pauseGoalForUnavailableTools(ctx, ownedPromptGoalId !== undefined);
452
+ return goalContractBoundaryResult(ctx);
453
+ }
454
+ if (goalPrompt?.resetSafetyEpoch && goalPromptGoalId === runtime.activeGoal.id) {
455
+ runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
456
+ runtime.persistGoal(runtime.activeGoal);
457
+ runtime.updateStatus(ctx, runtime.activeGoal);
458
+ }
459
+ return goalContractBoundaryResult(ctx, runtime.activeGoal);
460
+ });
461
+
462
+ pi.on("agent_start", (_event, _ctx) => {
463
+ if (!sessionActive) return;
464
+ const activeGoal = runtime.activeGoal;
465
+ if (activeGoal && runtime.guardAbortGoalId === activeGoal.id && activeGoal.status === "paused") {
466
+ if (runtime.consumeQueuedNonGoalFollowUpForAgentStart()) {
467
+ runtime.guardAbortGoalId = undefined;
468
+ runtime.clearStaleGoalToolCallBlock();
469
+ runtime.beginAgentRun(null, undefined);
470
+ }
471
+ // Unknown runs defer cleanup until their message/context boundary: custom
472
+ // follow-ups have no input event, while bare recovery is aborted pre-provider.
473
+ return;
474
+ }
475
+ runtime.beginRecoveryRunIfNeeded();
476
+ });
477
+
478
+ pi.on("turn_end", (event, ctx) => {
479
+ if (!sessionActive) return;
480
+ runtime.recordAutomaticTurn(ctx, event.message);
481
+ // Terminal Goal tools transition state synchronously, but their inactive contract
482
+ // must wait until Pi has persisted the real tool result at this turn boundary.
483
+ if (runtime.activeGoal?.status !== "active") {
484
+ runtime.ensureInactiveGoalContextContract(ctx);
485
+ }
486
+ });
487
+
488
+ pi.on("agent_end", (event, ctx) => {
489
+ if (!sessionActive) return;
490
+ const run = runtime.finishAgentRun();
491
+ if (run.goalId === null) return;
492
+ if (!runtime.canRecordGoalUsage() && !runtime.hasActiveBudgetWrapUp()) return;
493
+ if (run.goalId && run.goalId !== runtime.activeGoal?.id) return;
494
+ if (!runtime.activeGoal) return;
495
+ if (runtime.activeGoal.status === "budget_limited" && runtime.budgetWrapUp?.goalId === runtime.activeGoal.id) {
496
+ runtime.recordGoalUsage(runtime.activeGoal, ctx);
497
+ runtime.persistGoal(runtime.activeGoal);
498
+ runtime.updateStatus(ctx, runtime.activeGoal);
499
+ runtime.clearBudgetWrapUp();
500
+ return;
501
+ }
502
+ if (runtime.activeGoal.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
503
+ return;
504
+ }
505
+
506
+ const goalId = runtime.activeGoal.id;
507
+ const alreadyAwaitingContinuation = runtime.hasContinuationWorkForGoal(goalId);
508
+ const finalAssistant = findFinalAssistantMessage(event.messages);
509
+
510
+ if (!alreadyAwaitingContinuation) runtime.activeGoal = incrementGoal(runtime.activeGoal);
511
+ runtime.recordGoalUsage(runtime.activeGoal, ctx);
512
+
513
+ if (finalAssistant?.stopReason === "aborted") {
514
+ runtime.clearGoalRecoveryForGoal(goalId);
515
+ stopGoalAfterAgentEnd(ctx, runtime.activeGoal, finalAssistant, "paused");
516
+ return;
517
+ }
518
+
519
+ if (finalAssistant?.stopReason === "error") {
520
+ if (isRetryableGoalInterruption(finalAssistant)) {
521
+ if (run.origin === "automatic" && runtime.enforceAutomaticTurnLimit(ctx, true)) return;
522
+ if (runtime.limitActiveGoalForBudget(ctx, false)) return;
523
+ if (!runtime.goalToolsAvailable()) {
524
+ runtime.pauseGoalForUnavailableTools(ctx);
525
+ return;
526
+ }
527
+ runtime.goalRecovery = {
528
+ goalId,
529
+ kind: isGoalContextOverflow(finalAssistant) ? "compaction_retry" : "provider_retry",
530
+ automaticOwner: run.origin === "automatic",
531
+ errorMessage: finalAssistant.errorMessage,
532
+ };
533
+ runtime.cancelContinuationWork();
534
+ runtime.persistGoal(runtime.activeGoal);
535
+ runtime.updateStatus(ctx, runtime.activeGoal);
536
+ return;
537
+ }
538
+ runtime.clearGoalRecoveryForGoal(goalId);
539
+ stopGoalAfterAgentEnd(
540
+ ctx,
541
+ runtime.activeGoal,
542
+ finalAssistant,
543
+ isUsageLimitedGoalInterruption(finalAssistant) ? "usage_limited" : "blocked",
544
+ );
545
+ return;
546
+ }
547
+
548
+ runtime.clearGoalRecoveryForGoal(goalId);
549
+
550
+ if (runtime.limitActiveGoalForBudget(ctx, false)) return;
551
+ if (!runtime.goalToolsAvailable()) {
552
+ runtime.pauseGoalForUnavailableTools(ctx);
553
+ return;
554
+ }
555
+ if (
556
+ run.origin === "automatic" &&
557
+ runtime.recordAutomaticRunProgress(
558
+ ctx,
559
+ goalId,
560
+ event.messages,
561
+ run.toolAttempted || hasAssistantToolCall(event.messages),
562
+ )
563
+ ) {
564
+ return;
565
+ }
566
+
567
+ runtime.persistGoal(runtime.activeGoal);
568
+ runtime.updateStatus(ctx, runtime.activeGoal);
569
+
570
+ const currentGoal = runtime.activeGoal;
571
+ if (!currentGoal || currentGoal.id !== goalId || currentGoal.status !== "active") return;
572
+ runtime.requestContinuation(currentGoal);
573
+ });
574
+
575
+ pi.on("agent_settled", (_event, ctx) => {
576
+ if (!sessionActive) return;
577
+ if (runtime.activeGoal?.status === "active" && !runtime.ownsWorkflow(runtime.activeGoal)) {
578
+ runtime.cancelContinuationWork();
579
+ runtime.clearGoalRecovery();
580
+ runtime.clearSettledSafetyTracking();
581
+ return;
582
+ }
583
+ runtime.finalizeSettledRecovery(ctx);
584
+ const resumedWait = runtime.dispatchDueGoalWait(ctx);
585
+ if (!resumedWait) runtime.dispatchContinuationIfSettled(ctx);
586
+ runtime.clearSettledSafetyTracking();
587
+ });
588
+
589
+ function goalContractBoundaryResult(ctx: StatusContext, goal?: ActiveGoal) {
590
+ const message = runtime.goalContextContractForPrompt(ctx, goal);
591
+ return message ? { message } : undefined;
592
+ }
593
+
594
+ function beginNonGoalFollowUp(ctx: StatusContext, resetSafetyEpoch: boolean) {
595
+ runtime.clearGoalRecovery();
596
+ runtime.clearStaleGoalToolCallBlock();
597
+ if (resetSafetyEpoch) runtime.clearBudgetWrapUp();
598
+ const activeGoalId = runtime.activeGoal?.status === "active" ? runtime.activeGoal.id : undefined;
599
+ runtime.beginAgentRun(activeGoalId ?? null, activeGoalId ? "manual" : undefined);
600
+ if (resetSafetyEpoch && activeGoalId) runtime.resetActiveSafetyEpoch(ctx);
601
+ }
602
+
603
+ function stopGoalAfterAgentEnd(
604
+ ctx: StatusContext,
605
+ goal: ActiveGoal,
606
+ assistant: AssistantMessageLike,
607
+ status: "paused" | "blocked" | "usage_limited",
608
+ ) {
609
+ const stoppedGoal = runtime.stopActiveGoal(ctx, {
610
+ kind: "agent_interruption",
611
+ expectedGoalId: goal.id,
612
+ status,
613
+ reason: assistant.errorMessage ?? `goal ${status} after agent interruption`,
614
+ });
615
+ if (!stoppedGoal) return;
616
+
617
+ const details = assistant.errorMessage ? ` (${truncateNotification(assistant.errorMessage)})` : "";
618
+ if (status === "paused") {
619
+ notifyTerminal(ctx.ui, `Goal paused after interruption${details}. Run /goal resume to continue.`, "warning");
620
+ return;
621
+ }
622
+ if (status === "usage_limited") {
623
+ notifyTerminal(
624
+ ctx.ui,
625
+ `Goal stopped after provider usage limit${details}. Run /goal resume when usage is available.`,
626
+ "warning",
627
+ );
628
+ return;
629
+ }
630
+ notifyTerminal(
631
+ ctx.ui,
632
+ `Goal blocked after agent error${details}. Resolve the blocker or run /goal resume to retry.`,
633
+ "warning",
634
+ );
635
+ }
649
636
  }