@narumitw/pi-goal 0.16.0 → 0.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-goal",
3
- "version": "0.16.0",
3
+ "version": "0.17.1",
4
4
  "description": "Pi extension for autonomous /goal completion with opt-in experimental ordered queues.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/commands.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { currentTokenTotal, updateGoalUsage } from "./accounting.js";
1
+ import { currentTokenTotal } from "./accounting.js";
2
2
  import { validateObjective } from "./command.js";
3
3
  import { buildGoalPrompt, buildObjectiveUpdatedPrompt, buildResumePrompt } from "./prompts.js";
4
4
  import {
@@ -30,7 +30,11 @@ import {
30
30
  // User-command mutations are kept separate from Pi event wiring. Every controller
31
31
  // receives exactly one per-factory GoalRuntime, preserving session isolation.
32
32
  export class GoalCommandController {
33
- constructor(private readonly runtime: GoalRuntime) {}
33
+ private readonly runtime: GoalRuntime;
34
+
35
+ constructor(runtime: GoalRuntime) {
36
+ this.runtime = runtime;
37
+ }
34
38
 
35
39
  async startGoal(objective: string, tokenBudget: number | undefined, ctx: StatusContext) {
36
40
  const validationError = validateObjective(objective);
@@ -85,7 +89,7 @@ export class GoalCommandController {
85
89
  rolledBackStartedGoal = true;
86
90
  if (existingGoal) {
87
91
  this.runtime.queuedGoals = existingQueuedGoals;
88
- updateGoalUsage(existingGoal, ctx);
92
+ this.runtime.recordGoalUsage(existingGoal, ctx);
89
93
  if (existingGoal.status === "active") {
90
94
  abortCurrentTurn(ctx);
91
95
  this.runtime.activeGoal = transitionGoal(existingGoal, "paused");
@@ -184,7 +188,7 @@ export class GoalCommandController {
184
188
  ctx.ui.notify(`Goal skipped: ${currentGoal.text}. No goals remain.`, "warning");
185
189
  return;
186
190
  }
187
- if (currentGoal.status === "active") updateGoalUsage(currentGoal, ctx);
191
+ if (currentGoal.status === "active") this.runtime.recordGoalUsage(currentGoal, ctx);
188
192
  this.runtime.cancelContinuationWork();
189
193
  this.runtime.clearGoalRecovery();
190
194
  this.runtime.clearBudgetWrapUp();
@@ -208,7 +212,12 @@ export class GoalCommandController {
208
212
  if (ctx.isIdle?.() !== true || hasPendingMessages(ctx)) return false;
209
213
  if (pending.kind === "prioritize") {
210
214
  this.runtime.pendingQueueAction = undefined;
211
- return this.activatePrioritizedGoal(pending.objective, pending.tokenBudget, ctx);
215
+ return this.activatePrioritizedGoal(
216
+ pending.objective,
217
+ pending.tokenBudget,
218
+ ctx,
219
+ pending.displacedUsageFinalized === true,
220
+ );
212
221
  }
213
222
  if (
214
223
  !this.runtime.activeGoal ||
@@ -309,7 +318,7 @@ export class GoalCommandController {
309
318
  );
310
319
  return;
311
320
  }
312
- updateGoalUsage(this.runtime.activeGoal, ctx);
321
+ this.runtime.recordGoalUsage(this.runtime.activeGoal, ctx);
313
322
  this.runtime.cancelContinuationWork();
314
323
  this.runtime.clearBudgetWrapUp();
315
324
  this.runtime.blockStaleGoalToolCalls();
@@ -420,7 +429,7 @@ export class GoalCommandController {
420
429
  return;
421
430
  }
422
431
 
423
- updateGoalUsage(this.runtime.activeGoal, ctx);
432
+ this.runtime.recordGoalUsage(this.runtime.activeGoal, ctx);
424
433
  const previousGoal = { ...this.runtime.activeGoal };
425
434
  this.runtime.cancelContinuationWork();
426
435
  this.runtime.clearGoalRecovery();
@@ -496,7 +505,7 @@ export class GoalCommandController {
496
505
  return;
497
506
  }
498
507
  if (!this.runtime.queueFrozen) {
499
- updateGoalUsage(this.runtime.activeGoal, ctx);
508
+ this.runtime.recordGoalUsage(this.runtime.activeGoal, ctx);
500
509
  this.runtime.persistGoal(this.runtime.activeGoal);
501
510
  this.runtime.updateStatus(ctx, this.runtime.activeGoal);
502
511
  }
@@ -515,13 +524,16 @@ export class GoalCommandController {
515
524
  objective: string,
516
525
  tokenBudget: number | undefined,
517
526
  ctx: StatusContext,
527
+ displacedUsageFinalized = false,
518
528
  ) {
519
529
  const currentGoal = this.runtime.activeGoal;
520
530
  if (!currentGoal) {
521
531
  await this.startGoal(objective, tokenBudget, ctx);
522
532
  return true;
523
533
  }
524
- if (currentGoal.status === "active") updateGoalUsage(currentGoal, ctx);
534
+ if (currentGoal.status === "active" && !displacedUsageFinalized) {
535
+ this.runtime.recordGoalUsage(currentGoal, ctx);
536
+ }
525
537
  const previousGoal = { ...currentGoal };
526
538
  const previousQueue = [...this.runtime.queuedGoals];
527
539
  const visibilityBeforeActivation = this.runtime.snapshotGoalToolVisibility();
@@ -532,14 +544,19 @@ export class GoalCommandController {
532
544
  if (currentGoal.status === "complete") {
533
545
  // Completion already committed, so retain the priority intent for a
534
546
  // later /reload after the tool policy is restored.
535
- this.runtime.pendingQueueAction = { kind: "prioritize", objective, tokenBudget };
547
+ this.runtime.pendingQueueAction = {
548
+ kind: "prioritize",
549
+ objective,
550
+ tokenBudget,
551
+ ...(displacedUsageFinalized ? { displacedUsageFinalized: true } : {}),
552
+ };
536
553
  this.runtime.persistGoal(currentGoal);
537
554
  } else {
538
555
  // Roll back an activation that never started. An active displaced goal
539
556
  // cannot continue safely without its terminal tools, so make it resumable.
540
557
  this.runtime.pendingQueueAction = undefined;
541
558
  if (currentGoal.status === "active") {
542
- this.runtime.pauseGoalForUnavailableTools(ctx);
559
+ this.runtime.pauseGoalForUnavailableTools(ctx, true, !displacedUsageFinalized);
543
560
  } else {
544
561
  this.runtime.persistGoal(currentGoal);
545
562
  }
package/src/goal.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { defineTool, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { Type } from "typebox";
3
- import { currentTokenTotal, updateGoalUsage } from "./accounting.js";
3
+ import { currentTokenTotal } from "./accounting.js";
4
4
  import { completeGoalArguments, parseCommand } from "./command.js";
5
5
  import { GoalCommandController } from "./commands.js";
6
6
  import { type ActiveGoal, loadGoalStateFromSession } from "./persistence.js";
@@ -69,6 +69,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
69
69
  const clearBudgetWrapUp = runtime.clearBudgetWrapUp.bind(runtime);
70
70
  const clearStaleGoalToolCallBlock = runtime.clearStaleGoalToolCallBlock.bind(runtime);
71
71
  const persistGoal = runtime.persistGoal.bind(runtime);
72
+ const updateGoalUsage = runtime.recordGoalUsage.bind(runtime);
72
73
  const updateStatus = runtime.updateStatus.bind(runtime);
73
74
  const limitActiveGoalForBudget = runtime.limitActiveGoalForBudget.bind(runtime);
74
75
  const hideGoalToolsIfLocked = runtime.hideGoalToolsIfLocked.bind(runtime);
@@ -138,11 +139,15 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
138
139
  details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
139
140
  };
140
141
  }
141
-
142
- const completingDuringBudgetWrapUp =
143
- completedGoal.status === "budget_limited" &&
144
- runtime.budgetWrapUp?.goalId === completedGoal.id &&
145
- runtime.budgetWrapUp.delivered;
142
+ const completingDuringBudgetWrapUp = runtime.hasActiveBudgetWrapUp();
143
+ if (!runtime.canRecordGoalUsage() && !completingDuringBudgetWrapUp) {
144
+ const rejection = "Goal completion rejected: current run does not own the active goal.";
145
+ ctx.ui.notify(rejection, "warning");
146
+ return {
147
+ content: [{ type: "text", text: rejection }],
148
+ details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
149
+ };
150
+ }
146
151
  if (hasPendingSkipForGoal(completedGoal.id)) {
147
152
  updateGoalUsage(completedGoal, ctx);
148
153
  persistGoal(completedGoal);
@@ -324,6 +329,9 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
324
329
  };
325
330
 
326
331
  if (!blockedGoal) return reject("no active goal");
332
+ if (!runtime.canRecordGoalUsage()) {
333
+ return reject("current run does not own the active goal");
334
+ }
327
335
  if (hasPendingSkipForGoal(blockedGoal.id)) {
328
336
  updateGoalUsage(blockedGoal, ctx);
329
337
  persistGoal(blockedGoal);
@@ -498,7 +506,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
498
506
  let startRestoredQueuedGoal = false;
499
507
  if (runtime.activeGoal?.status === "queued" && !runtime.pendingQueueAction) {
500
508
  runtime.activeGoal = activateQueuedGoal(runtime.activeGoal, currentTokenTotal(ctx));
501
- startRestoredQueuedGoal = true;
509
+ startRestoredQueuedGoal = runtime.activeGoal.status === "active";
502
510
  }
503
511
  if (runtime.pendingQueueAction) await dispatchPendingQueueActionIfSettled(ctx);
504
512
  if (runtime.activeGoal) {
@@ -570,7 +578,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
570
578
  return;
571
579
  }
572
580
  if (runtime.activeGoal?.status !== "active") return;
573
- updateGoalUsage(runtime.activeGoal, ctx);
581
+ if (!updateGoalUsage(runtime.activeGoal, ctx)) return;
574
582
  cancelContinuationWork();
575
583
  persistGoal(runtime.activeGoal);
576
584
  updateStatus(ctx, runtime.activeGoal);
@@ -592,13 +600,16 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
592
600
  runtime.queuedGoals = restoredState.queue;
593
601
  runtime.pendingQueueAction = restoredState.pendingAction;
594
602
  }
595
- updateGoalUsage(runtime.activeGoal, ctx);
596
- persistGoal(runtime.activeGoal);
597
- updateStatus(ctx, runtime.activeGoal);
603
+ const usageRecorded = updateGoalUsage(runtime.activeGoal, ctx);
604
+ if (usageRecorded) {
605
+ persistGoal(runtime.activeGoal);
606
+ updateStatus(ctx, runtime.activeGoal);
607
+ }
598
608
  if (runtime.pendingQueueAction) {
599
609
  await dispatchPendingQueueActionIfSettled(ctx);
600
610
  return;
601
611
  }
612
+ if (!usageRecorded) return;
602
613
  if (limitActiveGoalForBudget(ctx, false)) return;
603
614
 
604
615
  const wasPiRetry = isPiOwnedCompactionRetry(event, runtime.activeGoal.id);
@@ -615,6 +626,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
615
626
  if (runtime.queueFrozen) return;
616
627
  if (event.source === "extension") {
617
628
  if (consumeCancelledContinuationPrompt(event.text)) return { action: "handled" as const };
629
+ clearGoalRecovery();
618
630
  return;
619
631
  }
620
632
  if (/^\/goal(?:\s|$)/u.test(event.text.trimStart())) return;
@@ -675,7 +687,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
675
687
 
676
688
  // AgentSession persists assistant message_end before tool execution events,
677
689
  // so the completed assistant call's usage is authoritative at this boundary.
678
- updateGoalUsage(runtime.activeGoal, ctx);
690
+ if (!updateGoalUsage(runtime.activeGoal, ctx)) return;
679
691
  persistGoal(runtime.activeGoal);
680
692
  updateStatus(ctx, runtime.activeGoal);
681
693
  if (limitActiveGoalForBudget(ctx, true)) return;
@@ -690,6 +702,34 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
690
702
  const goalPromptGoalId = consumePendingGoalPrompt(event.prompt);
691
703
  const continuationGoalId = goalPromptGoalId ? undefined : markContinuationStarted(event.prompt);
692
704
  const ownedPromptGoalId = goalPromptGoalId ?? continuationGoalId;
705
+ const activeBudgetWrapUp = runtime.hasActiveBudgetWrapUp();
706
+ const activeGoalRecovery = runtime.hasActiveGoalRecovery();
707
+ if (
708
+ runtime.pendingQueueAction?.kind === "prioritize" &&
709
+ !activeBudgetWrapUp &&
710
+ !activeGoalRecovery
711
+ ) {
712
+ // A turn that starts after priority intent is committed belongs to neither
713
+ // the displaced goal nor the not-yet-activated urgent goal. Persist the
714
+ // displaced goal's final accounting boundary so reload cannot absorb this run.
715
+ if (!runtime.pendingQueueAction.displacedUsageFinalized) {
716
+ if (runtime.activeGoal?.status === "active") {
717
+ updateGoalUsage(runtime.activeGoal, ctx, false);
718
+ }
719
+ runtime.pendingQueueAction.displacedUsageFinalized = true;
720
+ if (runtime.activeGoal) {
721
+ persistGoal(runtime.activeGoal);
722
+ updateStatus(ctx, runtime.activeGoal);
723
+ }
724
+ }
725
+ runtime.agentRunGoalId = null;
726
+ if (ownedPromptGoalId) abortCurrentTurn(ctx);
727
+ return;
728
+ }
729
+ if (activeBudgetWrapUp && runtime.activeGoal) {
730
+ runtime.agentRunGoalId = runtime.activeGoal.id;
731
+ return;
732
+ }
693
733
  if (
694
734
  runtime.pendingQueueAction?.kind === "advance" &&
695
735
  runtime.pendingQueueAction.goalId === runtime.activeGoal?.id
@@ -725,6 +765,12 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
725
765
  if (runtime.queueFrozen) return;
726
766
  const agentRunGoalId = runtime.agentRunGoalId;
727
767
  runtime.agentRunGoalId = undefined;
768
+ if (
769
+ agentRunGoalId === null ||
770
+ (!runtime.canRecordGoalUsage() && !runtime.hasActiveBudgetWrapUp())
771
+ ) {
772
+ return;
773
+ }
728
774
  if (agentRunGoalId && agentRunGoalId !== runtime.activeGoal?.id) return;
729
775
  if (!runtime.activeGoal) return;
730
776
  if (
@@ -34,6 +34,7 @@ export type PendingQueueAction =
34
34
  kind: "prioritize";
35
35
  objective: string;
36
36
  tokenBudget?: number;
37
+ displacedUsageFinalized?: boolean;
37
38
  }
38
39
  | {
39
40
  kind: "advance";
@@ -158,11 +159,18 @@ function loadLegacyGoalsState(data: unknown): LoadedGoalState {
158
159
  function normalizePendingQueueAction(value: unknown): PendingQueueAction | undefined {
159
160
  if (!isRecord(value)) return undefined;
160
161
  if (value.kind === "prioritize") {
161
- if (!validObjective(value.objective)) return undefined;
162
+ if (
163
+ !validObjective(value.objective) ||
164
+ (Object.hasOwn(value, "displacedUsageFinalized") &&
165
+ typeof value.displacedUsageFinalized !== "boolean")
166
+ ) {
167
+ return undefined;
168
+ }
162
169
  return {
163
170
  kind: "prioritize",
164
171
  objective: value.objective,
165
172
  tokenBudget: normalizeTokenBudget(value.tokenBudget),
173
+ ...(value.displacedUsageFinalized === true ? { displacedUsageFinalized: true } : {}),
166
174
  };
167
175
  }
168
176
  if (value.kind === "advance") {
package/src/runtime.ts CHANGED
@@ -123,7 +123,8 @@ export class GoalRuntime {
123
123
  continuationDelivery?: ContinuationTicket;
124
124
  goalRecovery?: GoalRecovery;
125
125
  budgetWrapUp?: BudgetWrapUp;
126
- agentRunGoalId?: string;
126
+ /** `null` marks a run that must not be charged to the active goal. */
127
+ agentRunGoalId?: string | null;
127
128
  staleGoalToolCallsBlocked = false;
128
129
  /** Once true, goal tools stay in the active set for this runtime (prompt-cache stable). */
129
130
  goalToolsUnlocked = false;
@@ -132,7 +133,43 @@ export class GoalRuntime {
132
133
  pendingGoalPromptMarkers = new Map<string, string>();
133
134
  cancelledContinuationMarkers = new Set<string>();
134
135
 
135
- constructor(readonly pi: ExtensionAPI) {}
136
+ readonly pi: ExtensionAPI;
137
+
138
+ constructor(pi: ExtensionAPI) {
139
+ this.pi = pi;
140
+ }
141
+
142
+ canRecordGoalUsage() {
143
+ return (
144
+ this.agentRunGoalId !== null &&
145
+ !(
146
+ this.pendingQueueAction?.kind === "prioritize" &&
147
+ this.pendingQueueAction.displacedUsageFinalized === true
148
+ )
149
+ );
150
+ }
151
+
152
+ hasActiveBudgetWrapUp() {
153
+ return (
154
+ this.activeGoal?.status === "budget_limited" &&
155
+ this.budgetWrapUp?.goalId === this.activeGoal.id &&
156
+ this.budgetWrapUp.delivered
157
+ );
158
+ }
159
+
160
+ hasActiveGoalRecovery() {
161
+ return Boolean(this.activeGoal && this.goalRecovery?.goalId === this.activeGoal.id);
162
+ }
163
+
164
+ recordGoalUsage(
165
+ goal: ActiveGoal,
166
+ ctx: StatusContext,
167
+ checkpointActiveTime = goal.status === "active",
168
+ ) {
169
+ if (!this.canRecordGoalUsage()) return false;
170
+ updateGoalUsage(goal, ctx, checkpointActiveTime);
171
+ return true;
172
+ }
136
173
 
137
174
  requestContinuation(goal: ActiveGoal) {
138
175
  if (this.hasContinuationWorkForGoal(goal.id)) return false;
@@ -166,7 +203,7 @@ export class GoalRuntime {
166
203
  this.continuationIntent = undefined;
167
204
  this.continuationDelivery = intent;
168
205
  try {
169
- this.pi.sendUserMessage(intent.prompt);
206
+ this.pi.sendUserMessage(intent.prompt, { deliverAs: "followUp" });
170
207
  return true;
171
208
  } catch (error) {
172
209
  if (this.continuationDelivery?.marker === intent.marker) {
@@ -453,10 +490,10 @@ export class GoalRuntime {
453
490
  }
454
491
  }
455
492
 
456
- pauseGoalForUnavailableTools(ctx: StatusContext, abortTurn = true) {
493
+ pauseGoalForUnavailableTools(ctx: StatusContext, abortTurn = true, recordUsage = true) {
457
494
  const goal = this.activeGoal;
458
495
  if (goal?.status !== "active") return false;
459
- updateGoalUsage(goal, ctx);
496
+ if (recordUsage) this.recordGoalUsage(goal, ctx);
460
497
  this.cancelContinuationWork();
461
498
  this.clearGoalRecoveryForGoal(goal.id);
462
499
  this.clearBudgetWrapUp();
@@ -720,10 +757,7 @@ export function truncateNotification(value: string) {
720
757
 
721
758
  async function sendPrompt(pi: ExtensionAPI, ctx: StatusContext, prompt: string) {
722
759
  try {
723
- const sent = ctx.isIdle?.()
724
- ? (pi.sendUserMessage(prompt) as void | Promise<void>)
725
- : (pi.sendUserMessage(prompt, { deliverAs: "followUp" }) as void | Promise<void>);
726
- await sent;
760
+ await pi.sendUserMessage(prompt, { deliverAs: "followUp" });
727
761
  return true;
728
762
  } catch (error) {
729
763
  ctx.ui.notify(`Goal prompt failed: ${formatError(error)}`, "error");