@narumitw/pi-goal 0.20.0 → 0.27.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.
package/src/goal.ts CHANGED
@@ -6,6 +6,7 @@ import { GoalCommandController } from "./commands.js";
6
6
  import { type ActiveGoal, loadGoalStateFromSession } from "./persistence.js";
7
7
  import { buildGoalPrompt, buildGoalSystemPrompt } from "./prompts.js";
8
8
  import { activateQueuedGoal } from "./queue.js";
9
+ import { GoalRpcController } from "./rpc.js";
9
10
  import {
10
11
  type AssistantMessageLike,
11
12
  abortCurrentTurn,
@@ -22,11 +23,13 @@ import {
22
23
  isGoalContextOverflow,
23
24
  isRetryableGoalInterruption,
24
25
  isUsageLimitedGoalInterruption,
26
+ resetGoalSafetyEpoch,
25
27
  STATUS_KEY,
26
28
  type StatusContext,
27
29
  transitionGoal,
28
30
  truncateNotification,
29
31
  } from "./runtime.js";
32
+ import { hasAssistantToolCall } from "./safety.js";
30
33
  import { DEFAULT_GOAL_SETTINGS, readGoalSettings } from "./settings.js";
31
34
 
32
35
  // goal.ts is the Pi-facing composition root: it keeps tool contracts and event
@@ -56,19 +59,11 @@ const EXPERIMENTAL_GOALS_WARNING =
56
59
  const MAX_BLOCKER_REASON_LENGTH = 1_000;
57
60
  const MAX_BLOCKER_EVIDENCE_LENGTH = 4_000;
58
61
 
59
- type AgentSettledHandler = (event: unknown, ctx: StatusContext) => unknown;
60
-
61
- function onAgentSettled(pi: ExtensionAPI, handler: AgentSettledHandler) {
62
- (
63
- pi as unknown as {
64
- on(event: "agent_settled", callback: AgentSettledHandler): void;
65
- }
66
- ).on("agent_settled", handler);
67
- }
68
-
69
62
  function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
70
63
  const runtime = new GoalRuntime(pi);
71
64
  const commands = new GoalCommandController(runtime);
65
+ const rpc = new GoalRpcController(runtime, commands);
66
+ rpc.register(pi);
72
67
 
73
68
  // Bind per-factory runtime operations once so event orchestration stays concise
74
69
  // without reintroducing module-global mutable state.
@@ -100,6 +95,10 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
100
95
  const consumePendingGoalPrompt = runtime.consumeOwnedGoalPrompt.bind(runtime);
101
96
  const markContinuationStarted = runtime.markContinuationStarted.bind(runtime);
102
97
  const hasContinuationWorkForGoal = runtime.hasContinuationWorkForGoal.bind(runtime);
98
+ const recordAutomaticTurn = runtime.recordAutomaticTurn.bind(runtime);
99
+ const recordAutomaticRunProgress = runtime.recordAutomaticRunProgress.bind(runtime);
100
+ const enforceAutomaticTurnLimit = runtime.enforceAutomaticTurnLimit.bind(runtime);
101
+ const enforceNoProgressLimit = runtime.enforceNoProgressLimit.bind(runtime);
103
102
  const clearActiveGoal = runtime.clearActiveGoal.bind(runtime);
104
103
  const showCompletionStatus = runtime.showCompletionStatus.bind(runtime);
105
104
  const restoreGoalToolsHiddenByPolicy = runtime.restoreGoalToolsHiddenByPolicy.bind(runtime);
@@ -108,7 +107,8 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
108
107
  ctx: StatusContext,
109
108
  goalId: string,
110
109
  prompt: string,
111
- ) => runtime.sendOwnedGoalPrompt(ctx, goalId, prompt);
110
+ resetSafetyEpoch = true,
111
+ ) => runtime.sendOwnedGoalPrompt(ctx, goalId, prompt, resetSafetyEpoch);
112
112
  const dispatchPendingQueueActionIfSettled =
113
113
  commands.dispatchPendingQueueActionIfSettled.bind(commands);
114
114
 
@@ -225,6 +225,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
225
225
  }
226
226
 
227
227
  runtime.activeGoal = transitionGoal(completedGoal, "complete");
228
+ runtime.setCompletionSummary(runtime.activeGoal.id, summary);
228
229
  updateGoalUsage(runtime.activeGoal, ctx);
229
230
  if (runtime.pendingQueueAction?.kind === "prioritize") {
230
231
  persistGoal(runtime.activeGoal);
@@ -368,6 +369,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
368
369
  clearGoalRecoveryForGoal(blockedGoal.id);
369
370
  blockStaleGoalToolCalls();
370
371
  runtime.activeGoal = transitionGoal(blockedGoal, "blocked");
372
+ runtime.setTerminalReason(runtime.activeGoal.id, reason);
371
373
  persistGoal(runtime.activeGoal);
372
374
  updateStatus(ctx, runtime.activeGoal);
373
375
  ctx.ui.notify(`Goal blocked: ${truncateNotification(reason)}`, "warning");
@@ -459,13 +461,16 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
459
461
  clearCompletionStatusTimer();
460
462
  clearContinuationTracking();
461
463
  clearPendingGoalPrompts();
462
- runtime.agentRunGoalId = undefined;
464
+ runtime.clearAgentRun();
465
+ runtime.guardAbortGoalId = undefined;
463
466
  clearGoalRecovery();
464
467
  clearBudgetWrapUp();
465
468
  clearStaleGoalToolCallBlock();
466
469
  runtime.queuedGoals = [];
467
470
  runtime.pendingQueueAction = undefined;
468
471
  runtime.queueFrozen = false;
472
+ runtime.clearTerminalDetails();
473
+ rpc.bindSession(ctx);
469
474
  const previousToolVisibility = runtime.settings.toolVisibility;
470
475
  const settingsResult = readGoalSettings(options.settingsPath);
471
476
  runtime.settings =
@@ -524,6 +529,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
524
529
  if (runtime.activeGoal.status === "active") {
525
530
  updateGoalUsage(runtime.activeGoal, ctx);
526
531
  if (limitActiveGoalForBudget(ctx, false)) return;
532
+ if (enforceAutomaticTurnLimit(ctx, false) || enforceNoProgressLimit(ctx)) return;
527
533
  }
528
534
  if (runtime.settings.toolVisibility === "after-first-goal") {
529
535
  // Registered tools are already active on an unrestricted fresh runtime.
@@ -545,6 +551,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
545
551
  ctx,
546
552
  restoredGoal.id,
547
553
  buildGoalPrompt(restoredGoal),
554
+ false, // Reloaded queue activation preserves its persisted safety epoch.
548
555
  );
549
556
  if (!sent && runtime.activeGoal?.id === restoredGoal.id) {
550
557
  runtime.activeGoal = transitionGoal(restoredGoal, "paused");
@@ -570,7 +577,8 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
570
577
  }
571
578
  clearContinuationTracking();
572
579
  clearPendingGoalPrompts();
573
- runtime.agentRunGoalId = undefined;
580
+ runtime.clearAgentRun();
581
+ runtime.guardAbortGoalId = undefined;
574
582
  clearGoalRecovery();
575
583
  clearBudgetWrapUp();
576
584
  clearStaleGoalToolCallBlock();
@@ -580,6 +588,8 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
580
588
  runtime.queueFrozen = false;
581
589
  ctx.ui.setStatus(STATUS_KEY, undefined);
582
590
  clearCompletionStatusTimer();
591
+ runtime.clearTerminalDetails();
592
+ rpc.unbindSession();
583
593
  });
584
594
 
585
595
  pi.on("session_before_compact", (event, ctx) => {
@@ -624,8 +634,8 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
624
634
  if (limitActiveGoalForBudget(ctx, false)) return;
625
635
 
626
636
  const wasPiRetry = isPiOwnedCompactionRetry(event, runtime.activeGoal.id);
627
- clearGoalRecoveryForGoal(runtime.activeGoal.id);
628
637
  if (wasPiRetry) return;
638
+ clearGoalRecoveryForGoal(runtime.activeGoal.id);
629
639
  requestContinuation(runtime.activeGoal);
630
640
  // Manual compaction does not emit agent_settled. This common dispatcher is
631
641
  // therefore the narrow fallback; threshold compaction leaves the intent for
@@ -633,7 +643,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
633
643
  dispatchContinuationIfSettled(ctx);
634
644
  });
635
645
 
636
- pi.on("input", (event) => {
646
+ pi.on("input", (event, ctx) => {
637
647
  if (event.source === "extension") {
638
648
  if (
639
649
  consumeCancelledContinuationPrompt(event.text) ||
@@ -642,22 +652,98 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
642
652
  return { action: "handled" as const };
643
653
  }
644
654
  if (runtime.queueFrozen) return;
655
+ // Streaming input is queued before its model work starts. Keep owned
656
+ // markers pending for message_start, and track non-goal delivery mode so a
657
+ // steer cannot consume a later follow-up's cleanup protection.
658
+ if (runtime.hasPendingOwnedGoalPrompt(event.text)) return;
659
+ if (event.streamingBehavior === "steer" || event.streamingBehavior === "followUp") {
660
+ runtime.noteQueuedNonGoalInput(event.text, event.streamingBehavior);
661
+ }
645
662
  clearGoalRecovery();
646
663
  return;
647
664
  }
648
665
  if (runtime.queueFrozen) return;
649
666
  if (/^\/goal(?:\s|$)/u.test(event.text.trimStart())) return;
667
+ if (event.streamingBehavior === "followUp") {
668
+ runtime.noteQueuedNonGoalInput(event.text, "followUp", true);
669
+ return;
670
+ }
671
+ if (event.streamingBehavior === "steer") {
672
+ runtime.noteQueuedNonGoalInput(event.text, "steer");
673
+ }
650
674
  clearGoalRecovery();
651
675
  clearBudgetWrapUp();
652
676
  clearStaleGoalToolCallBlock();
677
+ runtime.resetActiveSafetyEpoch(ctx);
678
+ });
679
+
680
+ pi.on("message_start", (event, ctx) => {
681
+ const message = event.message as { role?: unknown; content?: unknown };
682
+ if (
683
+ message.role === "assistant" &&
684
+ runtime.activeGoal?.status === "paused" &&
685
+ runtime.guardAbortGoalId === runtime.activeGoal.id
686
+ ) {
687
+ abortCurrentTurn(ctx);
688
+ return;
689
+ }
690
+ if (message.role === "custom") {
691
+ if (runtime.guardAbortGoalId === runtime.activeGoal?.id) {
692
+ runtime.guardAbortGoalId = undefined;
693
+ }
694
+ beginNonGoalFollowUp(ctx, false);
695
+ return;
696
+ }
697
+ if (message.role !== "user") return;
698
+ const prompt = Array.isArray(message.content)
699
+ ? message.content
700
+ .filter((part) => part && typeof part === "object" && Reflect.get(part, "type") === "text")
701
+ .map((part) => Reflect.get(part as object, "text"))
702
+ .filter((text): text is string => typeof text === "string")
703
+ .join("\n")
704
+ : typeof message.content === "string"
705
+ ? message.content
706
+ : "";
707
+ const queuedNonGoalInput = runtime.consumeQueuedNonGoalInput(prompt);
708
+ const ownedPrompt = consumePendingGoalPrompt(prompt);
709
+ if (!ownedPrompt) {
710
+ if (queuedNonGoalInput?.behavior === "followUp") {
711
+ beginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);
712
+ }
713
+ return;
714
+ }
715
+ if (runtime.activeGoal?.id !== ownedPrompt.goalId || runtime.activeGoal.status !== "active") {
716
+ return;
717
+ }
718
+ if (runtime.agentRunGoalId !== undefined && runtime.agentRunGoalId !== ownedPrompt.goalId) {
719
+ runtime.activeGoal.baselineTokens = Math.max(
720
+ 0,
721
+ currentTokenTotal(ctx) - runtime.activeGoal.tokensUsed,
722
+ );
723
+ }
724
+ runtime.beginAgentRun(ownedPrompt.goalId, "manual");
725
+ if (ownedPrompt.resetSafetyEpoch) {
726
+ runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
727
+ }
728
+ persistGoal(runtime.activeGoal);
729
+ updateStatus(ctx, runtime.activeGoal);
653
730
  });
654
731
 
655
- pi.on("context", (event) => {
732
+ pi.on("context", (event, ctx) => {
656
733
  const messages = event.messages.filter((message) => keepBudgetWrapUpMessage(message));
734
+ if (
735
+ runtime.activeGoal?.status === "paused" &&
736
+ runtime.guardAbortGoalId === runtime.activeGoal.id
737
+ ) {
738
+ // A current custom follow-up clears the guard at message_start. Otherwise,
739
+ // context transformation aborts before the provider adapter receives the signal.
740
+ abortCurrentTurn(ctx);
741
+ }
657
742
  if (messages.length !== event.messages.length) return { messages };
658
743
  });
659
744
 
660
745
  pi.on("tool_call", (event, ctx) => {
746
+ runtime.markAgentToolAttempted();
661
747
  if (runtime.queueFrozen) {
662
748
  if (!isGoalToolName(event.toolName)) return;
663
749
  return {
@@ -712,15 +798,27 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
712
798
  });
713
799
 
714
800
  pi.on("before_agent_start", (event, ctx) => {
715
- if (runtime.queueFrozen) {
716
- runtime.agentRunGoalId = undefined;
717
- return;
718
- }
719
- const goalPromptGoalId = consumePendingGoalPrompt(event.prompt);
801
+ runtime.clearAgentRun();
802
+ if (runtime.queueFrozen) return;
803
+ // Pi-owned retries emit agent_start directly. Reaching a normal prompt
804
+ // boundary means cleanup no longer owns the next run, so the hard-cap guard
805
+ // must not abort it.
806
+ if (runtime.guardAbortGoalId) runtime.guardAbortGoalId = undefined;
807
+ const goalPrompt = consumePendingGoalPrompt(event.prompt);
808
+ const goalPromptGoalId = goalPrompt?.goalId;
720
809
  const continuationGoalId = goalPromptGoalId ? undefined : markContinuationStarted(event.prompt);
721
810
  const ownedPromptGoalId = goalPromptGoalId ?? continuationGoalId;
722
811
  const activeBudgetWrapUp = runtime.hasActiveBudgetWrapUp();
812
+ const queuedNonGoalInput = runtime.consumeQueuedNonGoalInput(event.prompt);
813
+ if (queuedNonGoalInput?.behavior === "followUp") {
814
+ beginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);
815
+ }
723
816
  const activeGoalRecovery = runtime.hasActiveGoalRecovery();
817
+ const runOrigin = continuationGoalId
818
+ ? "automatic"
819
+ : activeGoalRecovery && runtime.goalRecovery?.automaticOwner
820
+ ? "automatic"
821
+ : "manual";
724
822
  if (
725
823
  runtime.pendingQueueAction?.kind === "prioritize" &&
726
824
  !activeBudgetWrapUp &&
@@ -739,56 +837,77 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
739
837
  updateStatus(ctx, runtime.activeGoal);
740
838
  }
741
839
  }
742
- runtime.agentRunGoalId = null;
840
+ runtime.beginAgentRun(null, undefined);
743
841
  if (ownedPromptGoalId) abortCurrentTurn(ctx);
744
842
  return;
745
843
  }
746
844
  if (activeBudgetWrapUp && runtime.activeGoal) {
747
- runtime.agentRunGoalId = runtime.activeGoal.id;
845
+ runtime.beginAgentRun(runtime.activeGoal.id, "manual");
748
846
  return;
749
847
  }
750
848
  if (
751
849
  runtime.pendingQueueAction?.kind === "advance" &&
752
850
  runtime.pendingQueueAction.goalId === runtime.activeGoal?.id
753
851
  ) {
754
- runtime.agentRunGoalId = ownedPromptGoalId ?? runtime.activeGoal.id;
852
+ runtime.beginAgentRun(ownedPromptGoalId ?? runtime.activeGoal.id, runOrigin);
755
853
  if (ownedPromptGoalId) abortCurrentTurn(ctx);
756
854
  return;
757
855
  }
758
856
  if (ownedPromptGoalId && ownedPromptGoalId !== runtime.activeGoal?.id) {
759
- runtime.agentRunGoalId = ownedPromptGoalId;
857
+ runtime.beginAgentRun(ownedPromptGoalId, runOrigin);
760
858
  if (runtime.activeGoal?.status === "active" && !goalToolsAvailable()) {
761
859
  pauseGoalForUnavailableTools(ctx, false);
762
860
  }
763
861
  abortCurrentTurn(ctx);
764
862
  return;
765
863
  }
766
- if (runtime.activeGoal?.status !== "active") {
767
- runtime.agentRunGoalId = undefined;
768
- return;
769
- }
770
- runtime.agentRunGoalId = runtime.activeGoal.id;
864
+ if (runtime.activeGoal?.status !== "active") return;
865
+ runtime.beginAgentRun(runtime.activeGoal.id, runOrigin);
771
866
  if (!goalToolsAvailable()) {
772
867
  pauseGoalForUnavailableTools(ctx, ownedPromptGoalId !== undefined);
773
868
  return;
774
869
  }
870
+ if (goalPrompt?.resetSafetyEpoch && goalPromptGoalId === runtime.activeGoal.id) {
871
+ runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
872
+ persistGoal(runtime.activeGoal);
873
+ updateStatus(ctx, runtime.activeGoal);
874
+ }
775
875
 
776
876
  return {
777
877
  systemPrompt: `${event.systemPrompt}\n\n${buildGoalSystemPrompt(runtime.activeGoal)}`,
778
878
  };
779
879
  });
780
880
 
781
- pi.on("agent_end", (event, ctx) => {
881
+ pi.on("agent_start", (_event, ctx) => {
782
882
  if (runtime.queueFrozen) return;
783
- const agentRunGoalId = runtime.agentRunGoalId;
784
- runtime.agentRunGoalId = undefined;
883
+ const activeGoal = runtime.activeGoal;
785
884
  if (
786
- agentRunGoalId === null ||
787
- (!runtime.canRecordGoalUsage() && !runtime.hasActiveBudgetWrapUp())
885
+ activeGoal &&
886
+ runtime.guardAbortGoalId === activeGoal.id &&
887
+ activeGoal.status === "paused"
788
888
  ) {
889
+ if (runtime.consumeQueuedNonGoalFollowUpForAgentStart()) {
890
+ runtime.guardAbortGoalId = undefined;
891
+ clearStaleGoalToolCallBlock();
892
+ runtime.beginAgentRun(null, undefined);
893
+ }
894
+ // Unknown runs defer cleanup until their message/context boundary: custom
895
+ // follow-ups have no input event, while bare recovery is aborted pre-provider.
789
896
  return;
790
897
  }
791
- if (agentRunGoalId && agentRunGoalId !== runtime.activeGoal?.id) return;
898
+ runtime.beginRecoveryRunIfNeeded();
899
+ });
900
+
901
+ pi.on("turn_end", (event, ctx) => {
902
+ if (runtime.queueFrozen) return;
903
+ recordAutomaticTurn(ctx, event.message);
904
+ });
905
+
906
+ pi.on("agent_end", (event, ctx) => {
907
+ const run = runtime.finishAgentRun();
908
+ if (runtime.queueFrozen || run.goalId === null) return;
909
+ if (!runtime.canRecordGoalUsage() && !runtime.hasActiveBudgetWrapUp()) return;
910
+ if (run.goalId && run.goalId !== runtime.activeGoal?.id) return;
792
911
  if (!runtime.activeGoal) return;
793
912
  if (
794
913
  runtime.activeGoal.status === "budget_limited" &&
@@ -826,6 +945,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
826
945
 
827
946
  if (finalAssistant?.stopReason === "error") {
828
947
  if (isRetryableGoalInterruption(finalAssistant)) {
948
+ if (run.origin === "automatic" && enforceAutomaticTurnLimit(ctx, true)) return;
829
949
  if (limitActiveGoalForBudget(ctx, false)) return;
830
950
  if (!goalToolsAvailable()) {
831
951
  pauseGoalForUnavailableTools(ctx);
@@ -834,6 +954,8 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
834
954
  runtime.goalRecovery = {
835
955
  goalId,
836
956
  kind: isGoalContextOverflow(finalAssistant) ? "compaction_retry" : "provider_retry",
957
+ automaticOwner: run.origin === "automatic",
958
+ errorMessage: finalAssistant.errorMessage,
837
959
  };
838
960
  cancelContinuationWork();
839
961
  persistGoal(runtime.activeGoal);
@@ -857,6 +979,17 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
857
979
  pauseGoalForUnavailableTools(ctx);
858
980
  return;
859
981
  }
982
+ if (
983
+ run.origin === "automatic" &&
984
+ recordAutomaticRunProgress(
985
+ ctx,
986
+ goalId,
987
+ event.messages,
988
+ run.toolAttempted || hasAssistantToolCall(event.messages),
989
+ )
990
+ ) {
991
+ return;
992
+ }
860
993
 
861
994
  persistGoal(runtime.activeGoal);
862
995
  updateStatus(ctx, runtime.activeGoal);
@@ -867,17 +1000,30 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
867
1000
  requestContinuation(currentGoal);
868
1001
  });
869
1002
 
870
- onAgentSettled(pi, (_event, ctx) => {
871
- if (runtime.queueFrozen) return;
872
- if (!runtime.pendingQueueAction) {
873
- dispatchContinuationIfSettled(ctx);
1003
+ pi.on("agent_settled", async (_event, ctx) => {
1004
+ if (runtime.queueFrozen) {
1005
+ runtime.clearSettledSafetyTracking();
874
1006
  return;
875
1007
  }
876
- return dispatchPendingQueueActionIfSettled(ctx).then((dispatched) => {
877
- if (!dispatched) dispatchContinuationIfSettled(ctx);
878
- });
1008
+ runtime.finalizeSettledRecovery(ctx);
1009
+ let dispatchedQueueAction = false;
1010
+ if (runtime.pendingQueueAction) {
1011
+ dispatchedQueueAction = await dispatchPendingQueueActionIfSettled(ctx);
1012
+ }
1013
+ if (!dispatchedQueueAction) dispatchContinuationIfSettled(ctx);
1014
+ runtime.clearSettledSafetyTracking();
879
1015
  });
880
1016
 
1017
+ function beginNonGoalFollowUp(ctx: StatusContext, resetSafetyEpoch: boolean) {
1018
+ clearGoalRecovery();
1019
+ clearStaleGoalToolCallBlock();
1020
+ if (resetSafetyEpoch) clearBudgetWrapUp();
1021
+ const activeGoalId =
1022
+ runtime.activeGoal?.status === "active" ? runtime.activeGoal.id : undefined;
1023
+ runtime.beginAgentRun(activeGoalId ?? null, activeGoalId ? "manual" : undefined);
1024
+ if (resetSafetyEpoch && activeGoalId) runtime.resetActiveSafetyEpoch(ctx);
1025
+ }
1026
+
881
1027
  function hasPendingSkipForGoal(goalId: string) {
882
1028
  return (
883
1029
  runtime.pendingQueueAction?.kind === "advance" &&
@@ -897,6 +1043,10 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
897
1043
  blockStaleGoalToolCalls();
898
1044
  abortCurrentTurn(ctx);
899
1045
  runtime.activeGoal = transitionGoal(goal, status);
1046
+ runtime.setTerminalReason(
1047
+ runtime.activeGoal.id,
1048
+ assistant.errorMessage ?? `goal ${status} after agent interruption`,
1049
+ );
900
1050
  persistGoal(runtime.activeGoal);
901
1051
  updateStatus(ctx, runtime.activeGoal);
902
1052
 
package/src/markers.ts ADDED
@@ -0,0 +1,25 @@
1
+ const GOAL_PROMPT_MARKER_PREFIX = "pi-goal-prompt:";
2
+ const CONTINUATION_MARKER_PREFIX = "pi-goal-continuation:";
3
+
4
+ const GOAL_PROMPT_MARKER_PATTERN = new RegExp(
5
+ `<!--\\s*${escapeRegExpText(GOAL_PROMPT_MARKER_PREFIX)}([^\\s>]+)\\s*-->`,
6
+ );
7
+ const CONTINUATION_MARKER_PATTERN = new RegExp(
8
+ `<!--\\s*${escapeRegExpText(CONTINUATION_MARKER_PREFIX)}([^\\s>]+)\\s*-->`,
9
+ );
10
+
11
+ export function extractGoalPromptMarker(prompt: string) {
12
+ return GOAL_PROMPT_MARKER_PATTERN.exec(prompt)?.[1];
13
+ }
14
+
15
+ export function extractContinuationMarker(prompt: string) {
16
+ return CONTINUATION_MARKER_PATTERN.exec(prompt)?.[1];
17
+ }
18
+
19
+ export function appendGoalPromptMarker(prompt: string, marker: string) {
20
+ return `${prompt}\n\n<!-- ${GOAL_PROMPT_MARKER_PREFIX}${marker} -->`;
21
+ }
22
+
23
+ function escapeRegExpText(value: string) {
24
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
25
+ }
@@ -15,6 +15,8 @@ const STATE_FILE = join(
15
15
  "pi-goal-state.json",
16
16
  );
17
17
 
18
+ export type SafetyPauseCause = "continuation_limit" | "no_progress";
19
+
18
20
  export interface ActiveGoal {
19
21
  id: string;
20
22
  text: string;
@@ -27,6 +29,10 @@ export interface ActiveGoal {
27
29
  timeUsedSeconds: number;
28
30
  baselineTokens: number;
29
31
  activeStartedAt?: number;
32
+ automaticModelTurns: number;
33
+ toolFreeRepeatCount: number;
34
+ lastToolFreeOutputFingerprint?: string;
35
+ safetyPauseCause?: SafetyPauseCause;
30
36
  }
31
37
 
32
38
  export type PendingQueueAction =
@@ -225,9 +231,25 @@ export function normalizeLoadedGoal(goal: ActiveGoal): ActiveGoal {
225
231
  timeUsedSeconds: nonNegativeFiniteNumber(goal.timeUsedSeconds),
226
232
  baselineTokens: nonNegativeFiniteNumber(goal.baselineTokens),
227
233
  activeStartedAt: goal.status === "active" ? now : undefined,
234
+ automaticModelTurns: normalizeSafetyCounter(goal.automaticModelTurns),
235
+ toolFreeRepeatCount: normalizeSafetyCounter(goal.toolFreeRepeatCount),
236
+ lastToolFreeOutputFingerprint: normalizeOutputFingerprint(goal.lastToolFreeOutputFingerprint),
237
+ safetyPauseCause: normalizeSafetyPauseCause(goal.safetyPauseCause),
228
238
  };
229
239
  }
230
240
 
241
+ function normalizeSafetyCounter(value: unknown) {
242
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;
243
+ }
244
+
245
+ function normalizeOutputFingerprint(value: unknown) {
246
+ return typeof value === "string" && /^[a-f0-9]{64}$/u.test(value) ? value : undefined;
247
+ }
248
+
249
+ function normalizeSafetyPauseCause(value: unknown): SafetyPauseCause | undefined {
250
+ return value === "continuation_limit" || value === "no_progress" ? value : undefined;
251
+ }
252
+
231
253
  export function clearLegacyPersistedGoal(cwd: string) {
232
254
  if (!existsSync(STATE_FILE)) return;
233
255
  const goals = readState();
package/src/queue.ts CHANGED
@@ -27,6 +27,8 @@ export function createQueuedGoal(
27
27
  tokensUsed: 0,
28
28
  timeUsedSeconds: 0,
29
29
  baselineTokens: 0,
30
+ automaticModelTurns: 0,
31
+ toolFreeRepeatCount: 0,
30
32
  };
31
33
  }
32
34