@narumitw/pi-goal 0.27.0 → 0.27.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.27.0",
3
+ "version": "0.27.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
@@ -22,6 +22,7 @@ import {
22
22
  hasPendingMessages,
23
23
  isResumableGoalStatus,
24
24
  nextGoalInstance,
25
+ queueGoalSafetyReset,
25
26
  STATUS_KEY,
26
27
  type StatusContext,
27
28
  stoppedStatusLabel,
@@ -372,7 +373,9 @@ export class GoalCommandController {
372
373
  this.runtime.clearGoalRecovery();
373
374
  this.runtime.clearBudgetWrapUp();
374
375
  this.runtime.clearStaleGoalToolCallBlock();
375
- this.runtime.activeGoal = transitionGoal(nextGoalInstance(this.runtime.activeGoal), "active");
376
+ this.runtime.activeGoal = queueGoalSafetyReset(
377
+ transitionGoal(nextGoalInstance(this.runtime.activeGoal), "active"),
378
+ );
376
379
  this.runtime.persistGoal(this.runtime.activeGoal);
377
380
  this.runtime.updateStatus(ctx, this.runtime.activeGoal);
378
381
  if (this.runtime.activeGoal.status !== "active") {
@@ -444,7 +447,7 @@ export class GoalCommandController {
444
447
  this.runtime.clearBudgetWrapUp();
445
448
  const previousStatus = this.runtime.activeGoal.status;
446
449
  const rotatedGoal = nextGoalInstance(this.runtime.activeGoal);
447
- const nextGoal = transitionGoal(
450
+ const transitionedGoal = transitionGoal(
448
451
  {
449
452
  ...rotatedGoal,
450
453
  text: objective,
@@ -452,6 +455,10 @@ export class GoalCommandController {
452
455
  },
453
456
  editedGoalStatus(previousStatus),
454
457
  );
458
+ const nextGoal =
459
+ transitionedGoal.status === "active"
460
+ ? queueGoalSafetyReset(transitionedGoal)
461
+ : transitionedGoal;
455
462
  const goalToolVisibilityBeforeActivation =
456
463
  nextGoal.status === "active" ? this.runtime.snapshotGoalToolVisibility() : undefined;
457
464
  if (nextGoal.status === "active") {
package/src/goal.ts CHANGED
@@ -526,6 +526,11 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
526
526
  }
527
527
  if (runtime.pendingQueueAction) await dispatchPendingQueueActionIfSettled(ctx);
528
528
  if (runtime.activeGoal) {
529
+ if (runtime.activeGoal.status === "active" && runtime.activeGoal.safetyResetPending) {
530
+ // Resume/edit activation is persisted before its queued prompt starts. A
531
+ // reload must commit that promised reset before enforcing the old limits.
532
+ runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
533
+ }
529
534
  if (runtime.activeGoal.status === "active") {
530
535
  updateGoalUsage(runtime.activeGoal, ctx);
531
536
  if (limitActiveGoalForBudget(ctx, false)) return;
@@ -688,6 +693,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
688
693
  return;
689
694
  }
690
695
  if (message.role === "custom") {
696
+ if (runtime.isActiveBudgetWrapUpMessage(message)) return;
691
697
  if (runtime.guardAbortGoalId === runtime.activeGoal?.id) {
692
698
  runtime.guardAbortGoalId = undefined;
693
699
  }
@@ -697,15 +703,18 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
697
703
  if (message.role !== "user") return;
698
704
  const prompt = Array.isArray(message.content)
699
705
  ? message.content
700
- .filter((part) => part && typeof part === "object" && Reflect.get(part, "type") === "text")
706
+ .filter(
707
+ (part) => part && typeof part === "object" && Reflect.get(part, "type") === "text",
708
+ )
701
709
  .map((part) => Reflect.get(part as object, "text"))
702
710
  .filter((text): text is string => typeof text === "string")
703
711
  .join("\n")
704
712
  : typeof message.content === "string"
705
713
  ? message.content
706
714
  : "";
707
- const queuedNonGoalInput = runtime.consumeQueuedNonGoalInput(prompt);
708
715
  const ownedPrompt = consumePendingGoalPrompt(prompt);
716
+ const ownedPromptBoundary = runtime.hasOwnedPromptBoundary(prompt);
717
+ const queuedNonGoalInput = runtime.consumeQueuedNonGoalInput(prompt, !ownedPromptBoundary);
709
718
  if (!ownedPrompt) {
710
719
  if (queuedNonGoalInput?.behavior === "followUp") {
711
720
  beginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);
@@ -808,12 +817,18 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
808
817
  const goalPromptGoalId = goalPrompt?.goalId;
809
818
  const continuationGoalId = goalPromptGoalId ? undefined : markContinuationStarted(event.prompt);
810
819
  const ownedPromptGoalId = goalPromptGoalId ?? continuationGoalId;
820
+ const ownedPromptBoundary = runtime.hasOwnedPromptBoundary(event.prompt);
811
821
  const activeBudgetWrapUp = runtime.hasActiveBudgetWrapUp();
812
- const queuedNonGoalInput = runtime.consumeQueuedNonGoalInput(event.prompt);
822
+ const activeGoalRecovery = runtime.hasActiveGoalRecovery();
823
+ const queuedNonGoalInput = activeBudgetWrapUp
824
+ ? undefined
825
+ : runtime.consumeQueuedNonGoalInput(
826
+ event.prompt,
827
+ !activeGoalRecovery && ownedPromptGoalId === undefined && !ownedPromptBoundary,
828
+ );
813
829
  if (queuedNonGoalInput?.behavior === "followUp") {
814
830
  beginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);
815
831
  }
816
- const activeGoalRecovery = runtime.hasActiveGoalRecovery();
817
832
  const runOrigin = continuationGoalId
818
833
  ? "automatic"
819
834
  : activeGoalRecovery && runtime.goalRecovery?.automaticOwner
@@ -878,7 +893,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
878
893
  };
879
894
  });
880
895
 
881
- pi.on("agent_start", (_event, ctx) => {
896
+ pi.on("agent_start", (_event, _ctx) => {
882
897
  if (runtime.queueFrozen) return;
883
898
  const activeGoal = runtime.activeGoal;
884
899
  if (
@@ -33,6 +33,7 @@ export interface ActiveGoal {
33
33
  toolFreeRepeatCount: number;
34
34
  lastToolFreeOutputFingerprint?: string;
35
35
  safetyPauseCause?: SafetyPauseCause;
36
+ safetyResetPending?: boolean;
36
37
  }
37
38
 
38
39
  export type PendingQueueAction =
@@ -235,6 +236,7 @@ export function normalizeLoadedGoal(goal: ActiveGoal): ActiveGoal {
235
236
  toolFreeRepeatCount: normalizeSafetyCounter(goal.toolFreeRepeatCount),
236
237
  lastToolFreeOutputFingerprint: normalizeOutputFingerprint(goal.lastToolFreeOutputFingerprint),
237
238
  safetyPauseCause: normalizeSafetyPauseCause(goal.safetyPauseCause),
239
+ safetyResetPending: goal.safetyResetPending === true ? true : undefined,
238
240
  };
239
241
  }
240
242
 
@@ -292,7 +294,8 @@ function isGoal(value: unknown): value is ActiveGoal {
292
294
  typeof value.tokensUsed === "number" &&
293
295
  typeof value.timeUsedSeconds === "number" &&
294
296
  typeof value.baselineTokens === "number" &&
295
- (value.activeStartedAt === undefined || typeof value.activeStartedAt === "number")
297
+ (value.activeStartedAt === undefined || typeof value.activeStartedAt === "number") &&
298
+ (value.safetyResetPending === undefined || typeof value.safetyResetPending === "boolean")
296
299
  );
297
300
  }
298
301
 
package/src/queue.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { checkpointGoalActiveTime } from "./accounting.js";
3
3
  import type { ActiveGoal } from "./persistence.js";
4
+ import { resetGoalSafetyEpoch } from "./safety.js";
4
5
 
5
6
  export interface GoalQueueResult {
6
7
  goal: ActiveGoal | undefined;
@@ -94,5 +95,5 @@ export function activateQueuedGoal(
94
95
  if (activated.tokenBudget !== undefined && activated.tokensUsed >= activated.tokenBudget) {
95
96
  return { ...activated, status: "budget_limited", activeStartedAt: undefined };
96
97
  }
97
- return activated;
98
+ return activated.safetyResetPending ? resetGoalSafetyEpoch(activated) : activated;
98
99
  }
package/src/runtime.ts CHANGED
@@ -20,7 +20,10 @@ import {
20
20
  serializeGoalState,
21
21
  } from "./persistence.js";
22
22
  import { buildContinuePrompt, type GoalStatus } from "./prompts.js";
23
- import { nextToolFreeRepeatState } from "./safety.js";
23
+ import { nextToolFreeRepeatState, resetGoalSafetyEpoch } from "./safety.js";
24
+
25
+ export { queueGoalSafetyReset, resetGoalSafetyEpoch } from "./safety.js";
26
+
24
27
  import { DEFAULT_GOAL_SETTINGS, type GoalSettings } from "./settings.js";
25
28
 
26
29
  export interface ContinuationTicket {
@@ -167,7 +170,9 @@ export class GoalRuntime {
167
170
  /** Exact lazy goal tools this runtime removed and may restore on a mode change. */
168
171
  goalToolsHiddenByPolicy = new Set<string>();
169
172
  pendingGoalPromptMarkers = new Map<string, PendingGoalPrompt>();
173
+ claimedGoalPromptMarkers = new Set<string>();
170
174
  cancelledContinuationMarkers = new Set<string>();
175
+ claimedContinuationMarkers = new Set<string>();
171
176
  pendingNonGoalInputs: PendingNonGoalInput[] = [];
172
177
 
173
178
  readonly pi: ExtensionAPI;
@@ -340,23 +345,31 @@ export class GoalRuntime {
340
345
  this.terminalDetails = undefined;
341
346
  }
342
347
 
343
- keepBudgetWrapUpMessage(message: unknown) {
344
- if (!message || typeof message !== "object") return true;
348
+ isActiveBudgetWrapUpMessage(message: unknown) {
349
+ if (!message || typeof message !== "object") return false;
345
350
  const candidate = message as {
346
351
  role?: unknown;
347
352
  customType?: unknown;
348
353
  details?: { goalId?: unknown };
349
354
  };
350
- if (candidate.role !== "custom" || candidate.customType !== BUDGET_WRAP_UP_MESSAGE_TYPE) {
351
- return true;
352
- }
353
355
  return (
356
+ candidate.role === "custom" &&
357
+ candidate.customType === BUDGET_WRAP_UP_MESSAGE_TYPE &&
354
358
  typeof candidate.details?.goalId === "string" &&
355
359
  candidate.details.goalId === this.budgetWrapUp?.goalId &&
356
360
  candidate.details.goalId === this.activeGoal?.id
357
361
  );
358
362
  }
359
363
 
364
+ keepBudgetWrapUpMessage(message: unknown) {
365
+ if (!message || typeof message !== "object") return true;
366
+ const candidate = message as { role?: unknown; customType?: unknown };
367
+ if (candidate.role !== "custom" || candidate.customType !== BUDGET_WRAP_UP_MESSAGE_TYPE) {
368
+ return true;
369
+ }
370
+ return this.isActiveBudgetWrapUpMessage(message);
371
+ }
372
+
360
373
  queueBudgetWrapUp(ctx: StatusContext, goal: ActiveGoal) {
361
374
  if (!this.budgetWrapUp || this.budgetWrapUp.goalId !== goal.id) {
362
375
  this.budgetWrapUp = { goalId: goal.id, delivered: false };
@@ -520,6 +533,8 @@ export class GoalRuntime {
520
533
  clearSettledSafetyTracking() {
521
534
  this.guardAbortGoalId = undefined;
522
535
  this.pendingNonGoalInputs = [];
536
+ this.claimedGoalPromptMarkers.clear();
537
+ this.claimedContinuationMarkers.clear();
523
538
  this.clearAgentRun();
524
539
  }
525
540
 
@@ -541,10 +556,12 @@ export class GoalRuntime {
541
556
  this.continuationIntent = undefined;
542
557
  this.continuationDelivery = undefined;
543
558
  this.cancelledContinuationMarkers.clear();
559
+ this.claimedContinuationMarkers.clear();
544
560
  }
545
561
 
546
562
  clearPendingGoalPrompts() {
547
563
  this.pendingGoalPromptMarkers.clear();
564
+ this.claimedGoalPromptMarkers.clear();
548
565
  this.pendingNonGoalInputs = [];
549
566
  }
550
567
 
@@ -578,6 +595,23 @@ export class GoalRuntime {
578
595
  return marker ? this.pendingGoalPromptMarkers.has(marker) : false;
579
596
  }
580
597
 
598
+ hasOwnedPromptBoundary(prompt: string) {
599
+ const goalMarker = extractGoalPromptMarker(prompt);
600
+ if (
601
+ goalMarker &&
602
+ (this.pendingGoalPromptMarkers.has(goalMarker) ||
603
+ this.claimedGoalPromptMarkers.has(goalMarker))
604
+ ) {
605
+ return true;
606
+ }
607
+ const continuationMarker = extractContinuationMarker(prompt);
608
+ return Boolean(
609
+ continuationMarker &&
610
+ (this.continuationDelivery?.marker === continuationMarker ||
611
+ this.claimedContinuationMarkers.has(continuationMarker)),
612
+ );
613
+ }
614
+
581
615
  consumeStaleOwnedGoalPrompt(prompt: string) {
582
616
  const marker = extractGoalPromptMarker(prompt);
583
617
  if (!marker) return false;
@@ -595,11 +629,7 @@ export class GoalRuntime {
595
629
  return true;
596
630
  }
597
631
 
598
- noteQueuedNonGoalInput(
599
- prompt: string,
600
- behavior: "steer" | "followUp",
601
- resetSafetyEpoch = false,
602
- ) {
632
+ noteQueuedNonGoalInput(prompt: string, behavior: "steer" | "followUp", resetSafetyEpoch = false) {
603
633
  this.pendingNonGoalInputs.push({
604
634
  behavior,
605
635
  fingerprint: inputFingerprint(prompt),
@@ -610,7 +640,7 @@ export class GoalRuntime {
610
640
  }
611
641
  }
612
642
 
613
- consumeQueuedNonGoalInput(prompt: string) {
643
+ consumeQueuedNonGoalInput(prompt: string, allowDeliveryFallback = true) {
614
644
  if (typeof prompt !== "string") return undefined;
615
645
  const fingerprint = inputFingerprint(prompt);
616
646
  // Pi delivers steers before follow-ups. Prefer a matching steer even when an
@@ -618,24 +648,34 @@ export class GoalRuntime {
618
648
  const steerIndex = this.pendingNonGoalInputs.findIndex(
619
649
  (pending) => pending.behavior === "steer" && pending.fingerprint === fingerprint,
620
650
  );
621
- const index =
651
+ const exactIndex =
622
652
  steerIndex >= 0
623
653
  ? steerIndex
624
654
  : this.pendingNonGoalInputs.findIndex(
625
- (pending) =>
626
- pending.behavior === "followUp" && pending.fingerprint === fingerprint,
655
+ (pending) => pending.behavior === "followUp" && pending.fingerprint === fingerprint,
627
656
  );
628
- if (index < 0) return undefined;
629
- return this.pendingNonGoalInputs.splice(index, 1)[0];
657
+ if (exactIndex >= 0) return this.pendingNonGoalInputs.splice(exactIndex, 1)[0];
658
+ if (!allowDeliveryFallback) return undefined;
659
+
660
+ // Skills, templates, and later input handlers can transform the raw text after
661
+ // pi-goal records it. Fall back to Pi's delivery priority as a bounded marker:
662
+ // steers drain before follow-ups, and settlement clears stale entries.
663
+ const fallbackSteerIndex = this.pendingNonGoalInputs.findIndex(
664
+ (pending) => pending.behavior === "steer",
665
+ );
666
+ const fallbackIndex =
667
+ fallbackSteerIndex >= 0
668
+ ? fallbackSteerIndex
669
+ : this.pendingNonGoalInputs.findIndex((pending) => pending.behavior === "followUp");
670
+ if (fallbackIndex < 0) return undefined;
671
+ return this.pendingNonGoalInputs.splice(fallbackIndex, 1)[0];
630
672
  }
631
673
 
632
674
  consumeQueuedNonGoalFollowUpForAgentStart() {
633
675
  // A pending steer owns the next intra-run boundary. Do not let a later
634
676
  // follow-up suppress cleanup until all earlier-priority steers have started.
635
677
  if (this.pendingNonGoalInputs.some((pending) => pending.behavior === "steer")) return false;
636
- const index = this.pendingNonGoalInputs.findIndex(
637
- (pending) => pending.behavior === "followUp",
638
- );
678
+ const index = this.pendingNonGoalInputs.findIndex((pending) => pending.behavior === "followUp");
639
679
  if (index < 0) return false;
640
680
  this.pendingNonGoalInputs.splice(index, 1);
641
681
  return true;
@@ -650,7 +690,10 @@ export class GoalRuntime {
650
690
  this.cancelContinuationWork();
651
691
  return undefined;
652
692
  }
653
- if (this.continuationDelivery?.marker === marker) this.continuationDelivery = undefined;
693
+ if (this.continuationDelivery?.marker === marker) {
694
+ this.continuationDelivery = undefined;
695
+ this.rememberClaimedContinuationMarker(marker);
696
+ }
654
697
  return marker.split(":", 1)[0];
655
698
  }
656
699
 
@@ -840,11 +883,7 @@ export class GoalRuntime {
840
883
  this.completionStatusTimer = undefined;
841
884
  }
842
885
 
843
- private rememberPendingGoalPrompt(
844
- goalId: string,
845
- prompt: string,
846
- resetSafetyEpoch: boolean,
847
- ) {
886
+ private rememberPendingGoalPrompt(goalId: string, prompt: string, resetSafetyEpoch: boolean) {
848
887
  const marker = randomUUID();
849
888
  this.pendingGoalPromptMarkers.set(marker, { goalId, resetSafetyEpoch });
850
889
  if (this.pendingGoalPromptMarkers.size > MAX_PENDING_GOAL_PROMPTS) {
@@ -859,9 +898,24 @@ export class GoalRuntime {
859
898
  if (!marker) return undefined;
860
899
  const pending = this.pendingGoalPromptMarkers.get(marker);
861
900
  this.pendingGoalPromptMarkers.delete(marker);
901
+ if (pending) this.rememberClaimedGoalPromptMarker(marker);
862
902
  return pending;
863
903
  }
864
904
 
905
+ private rememberClaimedGoalPromptMarker(marker: string) {
906
+ this.claimedGoalPromptMarkers.add(marker);
907
+ if (this.claimedGoalPromptMarkers.size <= MAX_PENDING_GOAL_PROMPTS) return;
908
+ const oldest = this.claimedGoalPromptMarkers.values().next().value;
909
+ if (oldest) this.claimedGoalPromptMarkers.delete(oldest);
910
+ }
911
+
912
+ private rememberClaimedContinuationMarker(marker: string) {
913
+ this.claimedContinuationMarkers.add(marker);
914
+ if (this.claimedContinuationMarkers.size <= MAX_CANCELLED_CONTINUATION_PROMPTS) return;
915
+ const oldest = this.claimedContinuationMarkers.values().next().value;
916
+ if (oldest) this.claimedContinuationMarkers.delete(oldest);
917
+ }
918
+
865
919
  consumeOwnedGoalPrompt(prompt: string) {
866
920
  return this.consumePendingGoalPrompt(prompt);
867
921
  }
@@ -914,16 +968,6 @@ export function nextGoalInstance(goal: ActiveGoal): ActiveGoal {
914
968
  return { ...goal, id: randomUUID(), updatedAt: Date.now() };
915
969
  }
916
970
 
917
- export function resetGoalSafetyEpoch(goal: ActiveGoal): ActiveGoal {
918
- return {
919
- ...goal,
920
- automaticModelTurns: 0,
921
- toolFreeRepeatCount: 0,
922
- lastToolFreeOutputFingerprint: undefined,
923
- safetyPauseCause: undefined,
924
- };
925
- }
926
-
927
971
  export function editedGoalStatus(status: GoalStatus): GoalStatus {
928
972
  if (status === "paused" || status === "blocked" || status === "usage_limited") return status;
929
973
  return "active";
package/src/safety.ts CHANGED
@@ -1,10 +1,26 @@
1
1
  import { createHash } from "node:crypto";
2
+ import type { ActiveGoal } from "./persistence.js";
2
3
 
3
4
  export interface ToolFreeRepeatState {
4
5
  toolFreeRepeatCount: number;
5
6
  lastToolFreeOutputFingerprint?: string;
6
7
  }
7
8
 
9
+ export function queueGoalSafetyReset(goal: ActiveGoal): ActiveGoal {
10
+ return { ...goal, safetyResetPending: true };
11
+ }
12
+
13
+ export function resetGoalSafetyEpoch(goal: ActiveGoal): ActiveGoal {
14
+ return {
15
+ ...goal,
16
+ automaticModelTurns: 0,
17
+ toolFreeRepeatCount: 0,
18
+ lastToolFreeOutputFingerprint: undefined,
19
+ safetyPauseCause: undefined,
20
+ safetyResetPending: undefined,
21
+ };
22
+ }
23
+
8
24
  export function nextToolFreeRepeatState(
9
25
  current: ToolFreeRepeatState,
10
26
  messages: readonly unknown[],