@narumitw/pi-goal 0.9.1 → 0.10.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 +8 -6
  2. package/package.json +5 -4
  3. package/src/goal.ts +150 -9
package/README.md CHANGED
@@ -17,9 +17,11 @@ Goal mode uses Codex-like persistence instructions and keeps sending guarded con
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
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 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.
20
+ - Pauses and aborts queued goal work when the user pauses a goal or Pi reports a non-retryable aborted/errored assistant turn.
21
+ - Keeps retryable provider interruptions and Pi compaction retries active without enqueueing duplicate goal continuations while Pi retries.
22
+ - Preserves active goals across manual, threshold, and overflow compaction.
23
+ - Guards auto-follow-ups so duplicate, replaced, paused, cleared, completed, or budget-limited goals are not continued.
24
+ - Blocks stale tool calls after pause or non-retryable interruption.
23
25
  - Encourages requirement-by-requirement verification before the goal is marked complete.
24
26
 
25
27
  ## 📦 Install
@@ -56,9 +58,9 @@ pi -e ./extensions/pi-goal
56
58
  - `/goal <goal_to_complete>` starts goal mode. If another unfinished goal exists, Pi asks for confirmation before replacing it with a new active goal and resetting its usage counters.
57
59
  - `/goal --tokens 100k <goal_to_complete>` starts or replaces goal mode with a token budget. `k` and `m` suffixes are accepted, for example `100k` or `1.5m`.
58
60
  - `/goal edit <goal_to_complete>` updates the existing goal objective without resetting usage counters. Active goals stay active, paused goals stay paused, and budget-limited goals remain budget-limited if their budget is still exhausted.
59
- - `/goal pause` stops prompt injection and auto-continuation without forgetting the goal.
61
+ - `/goal pause` stops prompt injection and auto-continuation, aborts the current turn, and keeps the goal for later resume.
60
62
  - `/goal resume` resumes a paused or budget-limited goal when the token budget allows it, then queues a resume prompt so work continues.
61
- - `/goal clear` cancels the current goal and also removes any legacy persisted state for the current working directory.
63
+ - `/goal clear` clears the current goal state, status, pending continuation, and legacy persisted state for the current working directory without aborting any in-flight agent turn.
62
64
 
63
65
  Goal objectives are limited to 4,000 characters. Put longer instructions in a file and reference the file path from `/goal`.
64
66
 
@@ -84,7 +86,7 @@ While a goal is active, `pi-goal` injects persistence rules and exposes `goal_co
84
86
 
85
87
  ## 🛑 Interruption and queued-input behavior
86
88
 
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.
89
+ On user pause, abort, or non-retryable error, `pi-goal` pauses the goal, aborts stale work, and blocks stale tool calls until the next user prompt (non-extension input), `/goal resume`, or `/goal clear`. On `/goal clear`, it clears goal state, pending continuation markers, and any stale tool-call block; it does not abort the current turn. Retryable provider interruptions and overflow compaction retries stay active while Pi retries; no extra continuation is queued.
88
90
 
89
91
  ## 🧠 Use cases
90
92
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-goal",
3
- "version": "0.9.1",
3
+ "version": "0.10.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",
@@ -28,11 +28,12 @@
28
28
  "typecheck": "tsc --noEmit"
29
29
  },
30
30
  "dependencies": {
31
- "typebox": "^1.1.37"
31
+ "typebox": "^1.3.3"
32
32
  },
33
33
  "devDependencies": {
34
- "@biomejs/biome": "2.4.14",
35
- "@earendil-works/pi-coding-agent": "0.79.8",
34
+ "@biomejs/biome": "2.5.2",
35
+ "@earendil-works/pi-ai": "0.80.3",
36
+ "@earendil-works/pi-coding-agent": "0.80.3",
36
37
  "typescript": "6.0.3"
37
38
  },
38
39
  "repository": {
package/src/goal.ts CHANGED
@@ -3,6 +3,11 @@ import { dirname, join } from "node:path";
3
3
  import process from "node:process";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { defineTool, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
+ import {
7
+ isContextOverflow,
8
+ type AssistantMessage as PiAssistantMessage,
9
+ type Usage,
10
+ } from "@earendil-works/pi-ai";
6
11
  import { Type } from "typebox";
7
12
 
8
13
  type GoalStatus = "active" | "paused" | "budget_limited" | "complete";
@@ -33,10 +38,23 @@ interface ContinuationPending {
33
38
  prompt: string;
34
39
  }
35
40
 
41
+ type GoalRecoveryKind = "provider_retry" | "compaction_retry";
42
+
43
+ interface GoalRecovery {
44
+ goalId: string;
45
+ kind: GoalRecoveryKind;
46
+ }
47
+
36
48
  interface AssistantMessageLike {
37
49
  role: "assistant";
38
50
  stopReason?: AgentStopReason;
39
51
  errorMessage?: string;
52
+ content?: PiAssistantMessage["content"];
53
+ api?: PiAssistantMessage["api"];
54
+ provider?: PiAssistantMessage["provider"];
55
+ model?: string;
56
+ usage?: Usage;
57
+ timestamp?: number;
40
58
  }
41
59
 
42
60
  interface GoalStateEntryData {
@@ -104,6 +122,7 @@ let activeGoal: ActiveGoal | undefined;
104
122
  let completionStatusTimer: NodeJS.Timeout | undefined;
105
123
  let extensionApi: ExtensionAPI | undefined;
106
124
  let continuationPending: ContinuationPending | undefined;
125
+ let goalRecovery: GoalRecovery | undefined;
107
126
  let staleGoalToolCallsBlocked = false;
108
127
  const cancelledContinuationMarkers = new Set<string>();
109
128
 
@@ -221,6 +240,7 @@ export default function goal(pi: ExtensionAPI) {
221
240
  pi.on("session_start", (_event, ctx) => {
222
241
  clearCompletionStatusTimer();
223
242
  clearContinuationTracking();
243
+ clearGoalRecovery();
224
244
  clearStaleGoalToolCallBlock();
225
245
  activeGoal = loadGoalFromSession(ctx);
226
246
  if (activeGoal) updateStatus(ctx, activeGoal);
@@ -230,24 +250,56 @@ export default function goal(pi: ExtensionAPI) {
230
250
  pi.on("session_shutdown", (_event, ctx) => {
231
251
  if (activeGoal) persistGoal(activeGoal);
232
252
  clearContinuationTracking();
253
+ clearGoalRecovery();
233
254
  clearStaleGoalToolCallBlock();
234
255
  ctx.ui.setStatus(STATUS_KEY, undefined);
235
256
  clearCompletionStatusTimer();
236
257
  });
237
258
 
259
+ pi.on("session_before_compact", (_event, ctx) => {
260
+ if (!activeGoal || activeGoal.status !== "active") return;
261
+ updateGoalUsage(activeGoal, ctx);
262
+ cancelContinuationPending();
263
+ persistGoal(activeGoal);
264
+ updateStatus(ctx, activeGoal);
265
+ });
266
+
267
+ pi.on("session_compact", async (event, ctx) => {
268
+ if (!activeGoal || activeGoal.status !== "active") {
269
+ clearGoalRecovery();
270
+ return;
271
+ }
272
+
273
+ const restoredGoal = loadGoalFromSession(ctx);
274
+ if (restoredGoal?.id === activeGoal.id) activeGoal = restoredGoal;
275
+ updateGoalUsage(activeGoal, ctx);
276
+ persistGoal(activeGoal);
277
+ updateStatus(ctx, activeGoal);
278
+
279
+ const wasPiRetry = isPiOwnedCompactionRetry(event, activeGoal.id);
280
+ clearGoalRecoveryForGoal(activeGoal.id);
281
+ if (wasPiRetry || hasPendingMessages(ctx)) return;
282
+ await sendContinuationPrompt(pi, ctx, activeGoal);
283
+ });
284
+
238
285
  pi.on("input", (event) => {
239
286
  if (event.source === "extension") {
240
287
  if (consumeCancelledContinuationPrompt(event.text)) return { action: "handled" as const };
241
288
  return;
242
289
  }
290
+ clearGoalRecovery();
243
291
  clearStaleGoalToolCallBlock();
244
292
  });
245
293
 
246
294
  pi.on("tool_call", () => {
247
295
  if (!staleGoalToolCallsBlocked) return;
296
+ if (!activeGoal || activeGoal.status !== "paused") {
297
+ clearStaleGoalToolCallBlock();
298
+ return;
299
+ }
248
300
  return {
249
301
  block: true,
250
- reason: "Blocked stale /goal tool call after the goal was paused or cleared.",
302
+ reason: "Blocked stale /goal tool call after the goal was paused or interrupted.",
251
303
  };
252
304
  });
253
305
 
@@ -272,15 +324,22 @@ export default function goal(pi: ExtensionAPI) {
272
324
 
273
325
  if (finalAssistant?.stopReason === "aborted" || finalAssistant?.stopReason === "error") {
274
326
  if (isRetryableGoalInterruption(finalAssistant)) {
275
- forgetContinuationPending();
327
+ goalRecovery = {
328
+ goalId,
329
+ kind: isGoalContextOverflow(finalAssistant) ? "compaction_retry" : "provider_retry",
330
+ };
331
+ cancelContinuationPending();
276
332
  persistGoal(activeGoal);
277
333
  updateStatus(ctx, activeGoal);
278
334
  return;
279
335
  }
336
+ clearGoalRecoveryForGoal(goalId);
280
337
  pauseGoalAfterAgentEnd(ctx, activeGoal, finalAssistant);
281
338
  return;
282
339
  }
283
340
 
341
+ clearGoalRecoveryForGoal(goalId);
342
+
284
343
  if (activeGoal.tokenBudget !== undefined && activeGoal.tokensUsed >= activeGoal.tokenBudget) {
285
344
  cancelContinuationPending();
286
345
  activeGoal = transitionGoal(activeGoal, "budget_limited");
@@ -330,6 +389,7 @@ async function startGoal(
330
389
  }
331
390
 
332
391
  cancelContinuationPending();
392
+ clearGoalRecovery();
333
393
  clearStaleGoalToolCallBlock();
334
394
  activeGoal = createGoal(objective, tokenBudget, currentTokenTotal(ctx));
335
395
  persistGoal(activeGoal);
@@ -365,6 +425,7 @@ async function resumeGoal(pi: ExtensionAPI, ctx: StatusContext) {
365
425
  ctx.ui.notify(`Goal is ${activeGoal.status}; only paused or budget-limited goals can be resumed.`, "warning");
366
426
  return;
367
427
  }
428
+ clearGoalRecovery();
368
429
  clearStaleGoalToolCallBlock();
369
430
  activeGoal = transitionGoal(activeGoal, "active");
370
431
  persistGoal(activeGoal);
@@ -381,14 +442,14 @@ function clearGoal(ctx: StatusContext) {
381
442
  if (!activeGoal) {
382
443
  ctx.ui.notify("No active goal.", "info");
383
444
  cancelContinuationPending();
445
+ clearGoalRecovery();
446
+ clearStaleGoalToolCallBlock();
384
447
  clearPersistedGoal(ctx.cwd);
385
448
  ctx.ui.setStatus(STATUS_KEY, undefined);
386
449
  return;
387
450
  }
388
451
 
389
452
  const stoppedGoal = activeGoal.text;
390
- blockStaleGoalToolCalls();
391
- abortCurrentTurn(ctx);
392
453
  clearActiveGoal(ctx);
393
454
  ctx.ui.notify(`Goal cleared: ${stoppedGoal}`, "warning");
394
455
  }
@@ -411,6 +472,7 @@ async function editGoal(
411
472
 
412
473
  updateGoalUsage(activeGoal, ctx);
413
474
  cancelContinuationPending();
475
+ clearGoalRecovery();
414
476
  activeGoal = normalizeGoalForBudget({
415
477
  ...activeGoal,
416
478
  text: objective,
@@ -735,8 +797,22 @@ function clearStaleGoalToolCallBlock() {
735
797
  staleGoalToolCallsBlocked = false;
736
798
  }
737
799
 
738
- function forgetContinuationPending() {
739
- continuationPending = undefined;
800
+ function clearGoalRecovery() {
801
+ goalRecovery = undefined;
802
+ }
803
+
804
+ function clearGoalRecoveryForGoal(goalId: string) {
805
+ if (goalRecovery?.goalId === goalId) goalRecovery = undefined;
806
+ }
807
+
808
+ function isPiOwnedCompactionRetry(event: unknown, goalId: string) {
809
+ const compaction = event as { reason?: unknown; willRetry?: unknown };
810
+ if (compaction.willRetry === true) return true;
811
+ return (
812
+ goalRecovery?.goalId === goalId &&
813
+ goalRecovery.kind === "compaction_retry" &&
814
+ (compaction.reason === undefined || compaction.reason === "overflow")
815
+ );
740
816
  }
741
817
 
742
818
  export function isContradictoryCompletionSummary(summary: string) {
@@ -747,7 +823,42 @@ export function isRetryableGoalInterruption(assistant: AssistantMessageLike) {
747
823
  if (assistant.stopReason !== "error") return false;
748
824
  if (!assistant.errorMessage) return false;
749
825
  if (NON_RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage)) return false;
750
- return RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage);
826
+ return isGoalContextOverflow(assistant) || RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage);
827
+ }
828
+
829
+ function isGoalContextOverflow(assistant: AssistantMessageLike) {
830
+ return isContextOverflow(toPiAssistantMessage(assistant));
831
+ }
832
+
833
+ function toPiAssistantMessage(assistant: AssistantMessageLike): PiAssistantMessage {
834
+ return {
835
+ role: "assistant",
836
+ content: assistant.content ?? [],
837
+ api: assistant.api ?? "openai-responses",
838
+ provider: assistant.provider ?? "unknown",
839
+ model: assistant.model ?? "unknown",
840
+ usage: assistant.usage ?? zeroUsage(),
841
+ stopReason: assistant.stopReason ?? "error",
842
+ errorMessage: assistant.errorMessage,
843
+ timestamp: assistant.timestamp ?? Date.now(),
844
+ };
845
+ }
846
+
847
+ function zeroUsage(): Usage {
848
+ return {
849
+ input: 0,
850
+ output: 0,
851
+ cacheRead: 0,
852
+ cacheWrite: 0,
853
+ totalTokens: 0,
854
+ cost: {
855
+ input: 0,
856
+ output: 0,
857
+ cacheRead: 0,
858
+ cacheWrite: 0,
859
+ total: 0,
860
+ },
861
+ };
751
862
  }
752
863
 
753
864
  function clearContinuationTracking() {
@@ -778,7 +889,7 @@ function markContinuationDelivered(prompt: string) {
778
889
  }
779
890
 
780
891
  function continuationMarker(goal: ActiveGoal) {
781
- return `${goal.id}:${goal.iteration}`;
892
+ return `${goal.id}:${goal.iteration}:${randomUUID()}`;
782
893
  }
783
894
 
784
895
  function continuationMarkerComment(marker: string) {
@@ -803,11 +914,19 @@ export function findFinalAssistantMessage(messages: unknown[]): AssistantMessage
803
914
  if (!message || typeof message !== "object") continue;
804
915
  const candidate = message as Record<string, unknown>;
805
916
  if (candidate.role !== "assistant") continue;
806
- return {
917
+ const assistant: AssistantMessageLike = {
807
918
  role: "assistant",
808
919
  stopReason: isAgentStopReason(candidate.stopReason) ? candidate.stopReason : undefined,
809
920
  errorMessage: typeof candidate.errorMessage === "string" ? candidate.errorMessage : undefined,
810
921
  };
922
+ if (Array.isArray(candidate.content)) assistant.content = candidate.content as PiAssistantMessage["content"];
923
+ if (typeof candidate.api === "string") assistant.api = candidate.api;
924
+ if (typeof candidate.provider === "string") assistant.provider = candidate.provider;
925
+ if (typeof candidate.model === "string") assistant.model = candidate.model;
926
+ if (typeof candidate.timestamp === "number") assistant.timestamp = candidate.timestamp;
927
+ const usage = normalizeUsage(candidate.usage);
928
+ if (usage) assistant.usage = usage;
929
+ return assistant;
811
930
  }
812
931
  return undefined;
813
932
  }
@@ -816,6 +935,26 @@ function isAgentStopReason(value: unknown): value is AgentStopReason {
816
935
  return ["stop", "length", "toolUse", "error", "aborted"].includes(String(value));
817
936
  }
818
937
 
938
+ function normalizeUsage(value: unknown): Usage | undefined {
939
+ if (!value || typeof value !== "object") return undefined;
940
+ const usage = value as Partial<Usage>;
941
+ if (typeof usage.input !== "number" || typeof usage.output !== "number") return undefined;
942
+ return {
943
+ input: usage.input,
944
+ output: usage.output,
945
+ cacheRead: usage.cacheRead ?? 0,
946
+ cacheWrite: usage.cacheWrite ?? 0,
947
+ totalTokens: usage.totalTokens ?? usage.input + usage.output + (usage.cacheRead ?? 0),
948
+ cost: {
949
+ input: usage.cost?.input ?? 0,
950
+ output: usage.cost?.output ?? 0,
951
+ cacheRead: usage.cost?.cacheRead ?? 0,
952
+ cacheWrite: usage.cost?.cacheWrite ?? 0,
953
+ total: usage.cost?.total ?? 0,
954
+ },
955
+ };
956
+ }
957
+
819
958
  function escapeXmlText(value: string) {
820
959
  return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
821
960
  }
@@ -869,6 +1008,8 @@ function loadGoalFromSession(ctx: StatusContext): ActiveGoal | undefined {
869
1008
 
870
1009
  function clearActiveGoal(ctx: StatusContext) {
871
1010
  cancelContinuationPending();
1011
+ clearGoalRecovery();
1012
+ clearStaleGoalToolCallBlock();
872
1013
  activeGoal = undefined;
873
1014
  clearPersistedGoal(ctx.cwd);
874
1015
  ctx.ui.setStatus(STATUS_KEY, undefined);