@narumitw/pi-goal 0.9.0 → 0.9.2

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 +2 -1
  3. package/src/goal.ts +144 -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). On `/goal clear`, it only clears goal state and pending continuation markers; 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.0",
3
+ "version": "0.9.2",
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",
@@ -32,6 +32,7 @@
32
32
  },
33
33
  "devDependencies": {
34
34
  "@biomejs/biome": "2.4.14",
35
+ "@earendil-works/pi-ai": "0.79.8",
35
36
  "@earendil-works/pi-coding-agent": "0.79.8",
36
37
  "typescript": "6.0.3"
37
38
  },
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,16 +250,44 @@ 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
 
@@ -247,7 +295,7 @@ export default function goal(pi: ExtensionAPI) {
247
295
  if (!staleGoalToolCallsBlocked) return;
248
296
  return {
249
297
  block: true,
250
- reason: "Blocked stale /goal tool call after the goal was paused or cleared.",
298
+ reason: "Blocked stale /goal tool call after the goal was paused or interrupted.",
251
299
  };
252
300
  });
253
301
 
@@ -272,15 +320,22 @@ export default function goal(pi: ExtensionAPI) {
272
320
 
273
321
  if (finalAssistant?.stopReason === "aborted" || finalAssistant?.stopReason === "error") {
274
322
  if (isRetryableGoalInterruption(finalAssistant)) {
275
- forgetContinuationPending();
323
+ goalRecovery = {
324
+ goalId,
325
+ kind: isGoalContextOverflow(finalAssistant) ? "compaction_retry" : "provider_retry",
326
+ };
327
+ cancelContinuationPending();
276
328
  persistGoal(activeGoal);
277
329
  updateStatus(ctx, activeGoal);
278
330
  return;
279
331
  }
332
+ clearGoalRecoveryForGoal(goalId);
280
333
  pauseGoalAfterAgentEnd(ctx, activeGoal, finalAssistant);
281
334
  return;
282
335
  }
283
336
 
337
+ clearGoalRecoveryForGoal(goalId);
338
+
284
339
  if (activeGoal.tokenBudget !== undefined && activeGoal.tokensUsed >= activeGoal.tokenBudget) {
285
340
  cancelContinuationPending();
286
341
  activeGoal = transitionGoal(activeGoal, "budget_limited");
@@ -330,6 +385,7 @@ async function startGoal(
330
385
  }
331
386
 
332
387
  cancelContinuationPending();
388
+ clearGoalRecovery();
333
389
  clearStaleGoalToolCallBlock();
334
390
  activeGoal = createGoal(objective, tokenBudget, currentTokenTotal(ctx));
335
391
  persistGoal(activeGoal);
@@ -365,6 +421,7 @@ async function resumeGoal(pi: ExtensionAPI, ctx: StatusContext) {
365
421
  ctx.ui.notify(`Goal is ${activeGoal.status}; only paused or budget-limited goals can be resumed.`, "warning");
366
422
  return;
367
423
  }
424
+ clearGoalRecovery();
368
425
  clearStaleGoalToolCallBlock();
369
426
  activeGoal = transitionGoal(activeGoal, "active");
370
427
  persistGoal(activeGoal);
@@ -381,14 +438,13 @@ function clearGoal(ctx: StatusContext) {
381
438
  if (!activeGoal) {
382
439
  ctx.ui.notify("No active goal.", "info");
383
440
  cancelContinuationPending();
441
+ clearGoalRecovery();
384
442
  clearPersistedGoal(ctx.cwd);
385
443
  ctx.ui.setStatus(STATUS_KEY, undefined);
386
444
  return;
387
445
  }
388
446
 
389
447
  const stoppedGoal = activeGoal.text;
390
- blockStaleGoalToolCalls();
391
- abortCurrentTurn(ctx);
392
448
  clearActiveGoal(ctx);
393
449
  ctx.ui.notify(`Goal cleared: ${stoppedGoal}`, "warning");
394
450
  }
@@ -411,6 +467,7 @@ async function editGoal(
411
467
 
412
468
  updateGoalUsage(activeGoal, ctx);
413
469
  cancelContinuationPending();
470
+ clearGoalRecovery();
414
471
  activeGoal = normalizeGoalForBudget({
415
472
  ...activeGoal,
416
473
  text: objective,
@@ -735,8 +792,22 @@ function clearStaleGoalToolCallBlock() {
735
792
  staleGoalToolCallsBlocked = false;
736
793
  }
737
794
 
738
- function forgetContinuationPending() {
739
- continuationPending = undefined;
795
+ function clearGoalRecovery() {
796
+ goalRecovery = undefined;
797
+ }
798
+
799
+ function clearGoalRecoveryForGoal(goalId: string) {
800
+ if (goalRecovery?.goalId === goalId) goalRecovery = undefined;
801
+ }
802
+
803
+ function isPiOwnedCompactionRetry(event: unknown, goalId: string) {
804
+ const compaction = event as { reason?: unknown; willRetry?: unknown };
805
+ if (compaction.willRetry === true) return true;
806
+ return (
807
+ goalRecovery?.goalId === goalId &&
808
+ goalRecovery.kind === "compaction_retry" &&
809
+ (compaction.reason === undefined || compaction.reason === "overflow")
810
+ );
740
811
  }
741
812
 
742
813
  export function isContradictoryCompletionSummary(summary: string) {
@@ -747,7 +818,42 @@ export function isRetryableGoalInterruption(assistant: AssistantMessageLike) {
747
818
  if (assistant.stopReason !== "error") return false;
748
819
  if (!assistant.errorMessage) return false;
749
820
  if (NON_RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage)) return false;
750
- return RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage);
821
+ return isGoalContextOverflow(assistant) || RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage);
822
+ }
823
+
824
+ function isGoalContextOverflow(assistant: AssistantMessageLike) {
825
+ return isContextOverflow(toPiAssistantMessage(assistant));
826
+ }
827
+
828
+ function toPiAssistantMessage(assistant: AssistantMessageLike): PiAssistantMessage {
829
+ return {
830
+ role: "assistant",
831
+ content: assistant.content ?? [],
832
+ api: assistant.api ?? "openai-responses",
833
+ provider: assistant.provider ?? "unknown",
834
+ model: assistant.model ?? "unknown",
835
+ usage: assistant.usage ?? zeroUsage(),
836
+ stopReason: assistant.stopReason ?? "error",
837
+ errorMessage: assistant.errorMessage,
838
+ timestamp: assistant.timestamp ?? Date.now(),
839
+ };
840
+ }
841
+
842
+ function zeroUsage(): Usage {
843
+ return {
844
+ input: 0,
845
+ output: 0,
846
+ cacheRead: 0,
847
+ cacheWrite: 0,
848
+ totalTokens: 0,
849
+ cost: {
850
+ input: 0,
851
+ output: 0,
852
+ cacheRead: 0,
853
+ cacheWrite: 0,
854
+ total: 0,
855
+ },
856
+ };
751
857
  }
752
858
 
753
859
  function clearContinuationTracking() {
@@ -778,7 +884,7 @@ function markContinuationDelivered(prompt: string) {
778
884
  }
779
885
 
780
886
  function continuationMarker(goal: ActiveGoal) {
781
- return `${goal.id}:${goal.iteration}`;
887
+ return `${goal.id}:${goal.iteration}:${randomUUID()}`;
782
888
  }
783
889
 
784
890
  function continuationMarkerComment(marker: string) {
@@ -803,11 +909,19 @@ export function findFinalAssistantMessage(messages: unknown[]): AssistantMessage
803
909
  if (!message || typeof message !== "object") continue;
804
910
  const candidate = message as Record<string, unknown>;
805
911
  if (candidate.role !== "assistant") continue;
806
- return {
912
+ const assistant: AssistantMessageLike = {
807
913
  role: "assistant",
808
914
  stopReason: isAgentStopReason(candidate.stopReason) ? candidate.stopReason : undefined,
809
915
  errorMessage: typeof candidate.errorMessage === "string" ? candidate.errorMessage : undefined,
810
916
  };
917
+ if (Array.isArray(candidate.content)) assistant.content = candidate.content as PiAssistantMessage["content"];
918
+ if (typeof candidate.api === "string") assistant.api = candidate.api;
919
+ if (typeof candidate.provider === "string") assistant.provider = candidate.provider;
920
+ if (typeof candidate.model === "string") assistant.model = candidate.model;
921
+ if (typeof candidate.timestamp === "number") assistant.timestamp = candidate.timestamp;
922
+ const usage = normalizeUsage(candidate.usage);
923
+ if (usage) assistant.usage = usage;
924
+ return assistant;
811
925
  }
812
926
  return undefined;
813
927
  }
@@ -816,6 +930,26 @@ function isAgentStopReason(value: unknown): value is AgentStopReason {
816
930
  return ["stop", "length", "toolUse", "error", "aborted"].includes(String(value));
817
931
  }
818
932
 
933
+ function normalizeUsage(value: unknown): Usage | undefined {
934
+ if (!value || typeof value !== "object") return undefined;
935
+ const usage = value as Partial<Usage>;
936
+ if (typeof usage.input !== "number" || typeof usage.output !== "number") return undefined;
937
+ return {
938
+ input: usage.input,
939
+ output: usage.output,
940
+ cacheRead: usage.cacheRead ?? 0,
941
+ cacheWrite: usage.cacheWrite ?? 0,
942
+ totalTokens: usage.totalTokens ?? usage.input + usage.output + (usage.cacheRead ?? 0),
943
+ cost: {
944
+ input: usage.cost?.input ?? 0,
945
+ output: usage.cost?.output ?? 0,
946
+ cacheRead: usage.cost?.cacheRead ?? 0,
947
+ cacheWrite: usage.cost?.cacheWrite ?? 0,
948
+ total: usage.cost?.total ?? 0,
949
+ },
950
+ };
951
+ }
952
+
819
953
  function escapeXmlText(value: string) {
820
954
  return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
821
955
  }
@@ -869,6 +1003,7 @@ function loadGoalFromSession(ctx: StatusContext): ActiveGoal | undefined {
869
1003
 
870
1004
  function clearActiveGoal(ctx: StatusContext) {
871
1005
  cancelContinuationPending();
1006
+ clearGoalRecovery();
872
1007
  activeGoal = undefined;
873
1008
  clearPersistedGoal(ctx.cwd);
874
1009
  ctx.ui.setStatus(STATUS_KEY, undefined);