@narumitw/pi-goal 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +6 -11
  2. package/package.json +1 -1
  3. package/src/goal.ts +115 -9
package/README.md CHANGED
@@ -15,10 +15,11 @@ Goal mode uses Codex-like persistence instructions and keeps sending guarded con
15
15
  - Supports optional token budgets such as `/goal --tokens 100k <goal>`.
16
16
  - Tracks `active`, `paused`, `budget_limited`, and `complete` states.
17
17
  - Stores goal state in the current Pi session, following Codex's thread-owned goal model instead of using a global per-directory goal.
18
- - Registers a `goal_complete` tool for explicit completion.
18
+ - Registers a `goal_complete` tool for explicit completion, and rejects plainly contradictory completion summaries such as “not complete” or “tests still fail”.
19
19
  - Automatically prompts the agent to continue if an active turn ends early, directly triggering the next turn when Pi is idle and no pending messages are queued.
20
- - Pauses instead of auto-continuing when Pi reports an aborted or errored assistant turn.
21
- - Guards auto-follow-ups so duplicate, replaced, paused, cleared, completed, or budget-limited goals are not continued.
20
+ - Pauses and aborts queued goal work when the user pauses/clears a goal or Pi reports a non-retryable aborted/errored assistant turn.
21
+ - Keeps retryable provider interruptions active without enqueueing duplicate goal continuations while Pi retries.
22
+ - Guards auto-follow-ups and stale tool calls so duplicate, replaced, paused, cleared, completed, or budget-limited goals are not continued.
22
23
  - Encourages requirement-by-requirement verification before the goal is marked complete.
23
24
 
24
25
  ## 📦 Install
@@ -79,17 +80,11 @@ Older versions wrote unfinished goals to `~/.pi/agent/pi-goal-state.json` keyed
79
80
 
80
81
  ## ✅ How completion works
81
82
 
82
- The extension registers a `goal_complete` tool. While a goal is active, the system prompt uses Codex-like persistence rules: keep going until the goal is resolved end-to-end, treat current files, command output, tests, and external state as authoritative, avoid redefining the goal into a smaller task, and call `goal_complete` only after requirement-by-requirement verification.
83
-
84
- If an agent turn ends before `goal_complete` is called, the extension records elapsed time and token usage, checks the budget, verifies that the same goal id is still active, and sends a continuation prompt only when no user or extension messages are already pending. When Pi is already idle, this directly triggers the next turn; otherwise it is queued as a follow-up until the agent finishes current work. A continuation-pending guard prevents repeated end events from enqueueing duplicate continuations.
83
+ While a goal is active, `pi-goal` injects persistence rules and exposes `goal_complete`. If a turn ends before completion, it records usage and sends one guarded continuation only when no other messages are pending. Empty or plainly contradictory completion summaries are rejected as a state-safety guard, not as proof of completion.
85
84
 
86
85
  ## 🛑 Interruption and queued-input behavior
87
86
 
88
- When Pi reports the final assistant message with `stopReason: "aborted"` or `stopReason: "error"`, `pi-goal` records usage, changes the goal to `paused`, and does not auto-continue. Run `/goal resume` to continue after reviewing the interruption or error.
89
-
90
- If user or extension messages are already queued at the end of a goal turn, those messages take priority and `pi-goal` skips that automatic continuation. Active goal instructions are still injected into the next agent turn, and normal continuation can resume after pending work finishes.
91
-
92
- Queued automatic continuation prompts are tracked by goal id and iteration. If a queued continuation is invalidated by `/goal pause`, `/goal clear`, `/goal edit`, replacement, or completion before delivery, the extension handles that stale prompt instead of letting it restart old goal work.
87
+ On user pause/clear, abort, or non-retryable error, `pi-goal` pauses or clears the goal, aborts stale work, and blocks cancelled-goal tool calls until the next user prompt (non-extension input). Retryable provider interruptions stay active while Pi retries; no extra continuation is queued.
93
88
 
94
89
  ## 🧠 Use cases
95
90
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-goal",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "Pi extension that keeps working on a /goal until the agent marks it complete.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/goal.ts CHANGED
@@ -64,6 +64,7 @@ interface StatusContext {
64
64
  };
65
65
  isIdle?: () => boolean;
66
66
  hasPendingMessages?: () => boolean;
67
+ abort?: () => void;
67
68
  sessionManager?: unknown;
68
69
  }
69
70
 
@@ -72,6 +73,15 @@ const GOAL_STATE_ENTRY_TYPE = "goal-state";
72
73
  const MAX_OBJECTIVE_LENGTH = 4_000;
73
74
  const MAX_CANCELLED_CONTINUATION_PROMPTS = 20;
74
75
  const CONTINUATION_MARKER_PREFIX = "pi-goal-continuation:";
76
+ const CONTRADICTORY_COMPLETION_PATTERNS = [
77
+ /(?<!could\s)\bnot\s+(?:yet\s+)?(?:complete|completed|done|finished)\b/i,
78
+ /\bstill\s+(?:incomplete|failing|failing\s+tests?|fails?)\b/i,
79
+ /\btests?\s+(?:still\s+)?fail(?:ing)?\b/i,
80
+ ] as const;
81
+ const NON_RETRYABLE_GOAL_ERROR_RE =
82
+ /usage[_\s-]*limit|chatgpt usage limit|multi-auth rotation failed|credentials tried|unauthori[sz]ed|invalid api key/i;
83
+ const RETRYABLE_GOAL_ERROR_RE =
84
+ /websocket closed|sse response headers timed out|headers timed out|context[_\s-]*length[_\s-]*exceeded|input exceeds the context window|provider returned error/i;
75
85
  const GOAL_ARGUMENT_COMPLETIONS: readonly GoalArgumentCompletion[] = [
76
86
  { value: "pause", label: "pause", description: "Pause the active goal" },
77
87
  { value: "resume", label: "resume", description: "Resume a paused or budget-limited goal" },
@@ -94,35 +104,70 @@ let activeGoal: ActiveGoal | undefined;
94
104
  let completionStatusTimer: NodeJS.Timeout | undefined;
95
105
  let extensionApi: ExtensionAPI | undefined;
96
106
  let continuationPending: ContinuationPending | undefined;
107
+ let staleGoalToolCallsBlocked = false;
97
108
  const cancelledContinuationMarkers = new Set<string>();
98
109
 
99
110
  const goalCompleteTool = defineTool({
100
111
  name: "goal_complete",
101
112
  label: "Goal Complete",
102
113
  description:
103
- "Mark the active /goal as complete. Only call this after the requested goal is fully done and verified.",
114
+ "Mark the active /goal as complete after all required work is done and verified. Do not use for partial progress, blockers, failing, or unverified work.",
104
115
  promptSnippet: "Mark the active /goal as complete after fully finishing and verifying it",
105
116
  promptGuidelines: [
106
117
  "When a /goal is active, keep working until the goal is complete; do not stop with only a plan or partial progress.",
107
118
  "Before calling goal_complete, audit the active goal requirement by requirement against the current files, command output, tests, or external state.",
108
- "Call goal_complete only after the requested goal is fully implemented, verified, and no known required work remains.",
119
+ "Call goal_complete only after the requested goal is fully implemented, verified, and no known required work remains; otherwise keep working.",
109
120
  ],
110
121
  parameters: Type.Object({
111
122
  summary: Type.String({
112
- description: "Concise summary of what was completed and how it was verified.",
123
+ description:
124
+ "State what was completed and what evidence verified it. Do not use this tool to report partial progress, blockers, failures, or remaining work.",
113
125
  }),
114
126
  }),
115
127
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
116
128
  const completedGoal = activeGoal;
129
+ const goal = completedGoal?.text ?? "unknown goal";
130
+ const summary = params.summary.trim();
131
+
132
+ if (!completedGoal) {
133
+ const rejection = "Goal completion rejected: no active goal.";
134
+ ctx.ui.notify(rejection, "warning");
135
+
136
+ return {
137
+ content: [{ type: "text", text: rejection }],
138
+ details: { goal, summary } satisfies GoalCompleteDetails,
139
+ };
140
+ }
141
+
142
+ const rejectionReason = !summary
143
+ ? "summary is empty"
144
+ : isContradictoryCompletionSummary(summary)
145
+ ? "summary says the goal is not complete"
146
+ : undefined;
147
+ if (rejectionReason) {
148
+ updateGoalUsage(completedGoal, ctx);
149
+ persistGoal(completedGoal);
150
+ updateStatus(ctx, completedGoal);
151
+ const rejection = `Goal completion rejected: ${rejectionReason}.`;
152
+ ctx.ui.notify(rejection, "warning");
153
+
154
+ return {
155
+ content: [
156
+ {
157
+ type: "text",
158
+ text: rejection,
159
+ },
160
+ ],
161
+ details: { goal, summary } satisfies GoalCompleteDetails,
162
+ };
163
+ }
164
+
117
165
  if (completedGoal) {
118
166
  activeGoal = transitionGoal(completedGoal, "complete");
119
167
  updateGoalUsage(activeGoal, ctx);
120
168
  persistGoal(activeGoal);
121
169
  }
122
170
 
123
- const goal = completedGoal?.text ?? "unknown goal";
124
- const summary = params.summary.trim();
125
-
126
171
  ctx.ui.setStatus(STATUS_KEY, completedGoal ? formatStatus(activeGoal) : undefined);
127
172
  clearActiveGoal(ctx);
128
173
  showCompletionStatus(ctx);
@@ -176,6 +221,7 @@ export default function goal(pi: ExtensionAPI) {
176
221
  pi.on("session_start", (_event, ctx) => {
177
222
  clearCompletionStatusTimer();
178
223
  clearContinuationTracking();
224
+ clearStaleGoalToolCallBlock();
179
225
  activeGoal = loadGoalFromSession(ctx);
180
226
  if (activeGoal) updateStatus(ctx, activeGoal);
181
227
  else ctx.ui.setStatus(STATUS_KEY, undefined);
@@ -184,13 +230,25 @@ export default function goal(pi: ExtensionAPI) {
184
230
  pi.on("session_shutdown", (_event, ctx) => {
185
231
  if (activeGoal) persistGoal(activeGoal);
186
232
  clearContinuationTracking();
233
+ clearStaleGoalToolCallBlock();
187
234
  ctx.ui.setStatus(STATUS_KEY, undefined);
188
235
  clearCompletionStatusTimer();
189
236
  });
190
237
 
191
238
  pi.on("input", (event) => {
192
- if (event.source !== "extension") return;
193
- if (consumeCancelledContinuationPrompt(event.text)) return { action: "handled" as const };
239
+ if (event.source === "extension") {
240
+ if (consumeCancelledContinuationPrompt(event.text)) return { action: "handled" as const };
241
+ return;
242
+ }
243
+ clearStaleGoalToolCallBlock();
244
+ });
245
+
246
+ pi.on("tool_call", () => {
247
+ if (!staleGoalToolCallsBlocked) return;
248
+ return {
249
+ block: true,
250
+ reason: "Blocked stale /goal tool call after the goal was paused or cleared.",
251
+ };
194
252
  });
195
253
 
196
254
  pi.on("before_agent_start", (event) => {
@@ -213,6 +271,12 @@ export default function goal(pi: ExtensionAPI) {
213
271
  updateGoalUsage(activeGoal, ctx);
214
272
 
215
273
  if (finalAssistant?.stopReason === "aborted" || finalAssistant?.stopReason === "error") {
274
+ if (isRetryableGoalInterruption(finalAssistant)) {
275
+ forgetContinuationPending();
276
+ persistGoal(activeGoal);
277
+ updateStatus(ctx, activeGoal);
278
+ return;
279
+ }
216
280
  pauseGoalAfterAgentEnd(ctx, activeGoal, finalAssistant);
217
281
  return;
218
282
  }
@@ -266,6 +330,7 @@ async function startGoal(
266
330
  }
267
331
 
268
332
  cancelContinuationPending();
333
+ clearStaleGoalToolCallBlock();
269
334
  activeGoal = createGoal(objective, tokenBudget, currentTokenTotal(ctx));
270
335
  persistGoal(activeGoal);
271
336
  updateStatus(ctx, activeGoal);
@@ -283,6 +348,8 @@ function pauseGoal(ctx: StatusContext) {
283
348
  return;
284
349
  }
285
350
  cancelContinuationPending();
351
+ blockStaleGoalToolCalls();
352
+ abortCurrentTurn(ctx);
286
353
  activeGoal = transitionGoal(activeGoal, "paused");
287
354
  persistGoal(activeGoal);
288
355
  updateStatus(ctx, activeGoal);
@@ -298,6 +365,7 @@ async function resumeGoal(pi: ExtensionAPI, ctx: StatusContext) {
298
365
  ctx.ui.notify(`Goal is ${activeGoal.status}; only paused or budget-limited goals can be resumed.`, "warning");
299
366
  return;
300
367
  }
368
+ clearStaleGoalToolCallBlock();
301
369
  activeGoal = transitionGoal(activeGoal, "active");
302
370
  persistGoal(activeGoal);
303
371
  updateStatus(ctx, activeGoal);
@@ -319,6 +387,8 @@ function clearGoal(ctx: StatusContext) {
319
387
  }
320
388
 
321
389
  const stoppedGoal = activeGoal.text;
390
+ blockStaleGoalToolCalls();
391
+ abortCurrentTurn(ctx);
322
392
  clearActiveGoal(ctx);
323
393
  ctx.ui.notify(`Goal cleared: ${stoppedGoal}`, "warning");
324
394
  }
@@ -351,7 +421,10 @@ async function editGoal(
351
421
  persistGoal(activeGoal);
352
422
  updateStatus(ctx, activeGoal);
353
423
  ctx.ui.notify(`Goal updated: ${objective}`, "info");
354
- if (activeGoal.status === "active") await sendObjectiveUpdatedPrompt(pi, ctx, activeGoal);
424
+ if (activeGoal.status === "active") {
425
+ clearStaleGoalToolCallBlock();
426
+ await sendObjectiveUpdatedPrompt(pi, ctx, activeGoal);
427
+ }
355
428
  }
356
429
 
357
430
  function showGoal(ctx: StatusContext) {
@@ -411,6 +484,8 @@ function pauseGoalAfterAgentEnd(
411
484
  assistant: AssistantMessageLike,
412
485
  ) {
413
486
  cancelContinuationPending();
487
+ blockStaleGoalToolCalls();
488
+ abortCurrentTurn(ctx);
414
489
  activeGoal = transitionGoal(goal, "paused");
415
490
  persistGoal(activeGoal);
416
491
  updateStatus(ctx, activeGoal);
@@ -644,6 +719,37 @@ function hasPendingMessages(ctx: StatusContext) {
644
719
  return ctx.hasPendingMessages?.() ?? false;
645
720
  }
646
721
 
722
+ function abortCurrentTurn(ctx: StatusContext) {
723
+ try {
724
+ ctx.abort?.();
725
+ } catch {
726
+ // Best effort: stale goal guards still prevent follow-on tool calls.
727
+ }
728
+ }
729
+
730
+ function blockStaleGoalToolCalls() {
731
+ staleGoalToolCallsBlocked = true;
732
+ }
733
+
734
+ function clearStaleGoalToolCallBlock() {
735
+ staleGoalToolCallsBlocked = false;
736
+ }
737
+
738
+ function forgetContinuationPending() {
739
+ continuationPending = undefined;
740
+ }
741
+
742
+ export function isContradictoryCompletionSummary(summary: string) {
743
+ return CONTRADICTORY_COMPLETION_PATTERNS.some((pattern) => pattern.test(summary));
744
+ }
745
+
746
+ export function isRetryableGoalInterruption(assistant: AssistantMessageLike) {
747
+ if (assistant.stopReason !== "error") return false;
748
+ if (!assistant.errorMessage) return false;
749
+ if (NON_RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage)) return false;
750
+ return RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage);
751
+ }
752
+
647
753
  function clearContinuationTracking() {
648
754
  continuationPending = undefined;
649
755
  cancelledContinuationMarkers.clear();