@narumitw/pi-goal 0.24.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
@@ -23,11 +23,13 @@ import {
23
23
  isGoalContextOverflow,
24
24
  isRetryableGoalInterruption,
25
25
  isUsageLimitedGoalInterruption,
26
+ resetGoalSafetyEpoch,
26
27
  STATUS_KEY,
27
28
  type StatusContext,
28
29
  transitionGoal,
29
30
  truncateNotification,
30
31
  } from "./runtime.js";
32
+ import { hasAssistantToolCall } from "./safety.js";
31
33
  import { DEFAULT_GOAL_SETTINGS, readGoalSettings } from "./settings.js";
32
34
 
33
35
  // goal.ts is the Pi-facing composition root: it keeps tool contracts and event
@@ -57,16 +59,6 @@ const EXPERIMENTAL_GOALS_WARNING =
57
59
  const MAX_BLOCKER_REASON_LENGTH = 1_000;
58
60
  const MAX_BLOCKER_EVIDENCE_LENGTH = 4_000;
59
61
 
60
- type AgentSettledHandler = (event: unknown, ctx: StatusContext) => unknown;
61
-
62
- function onAgentSettled(pi: ExtensionAPI, handler: AgentSettledHandler) {
63
- (
64
- pi as unknown as {
65
- on(event: "agent_settled", callback: AgentSettledHandler): void;
66
- }
67
- ).on("agent_settled", handler);
68
- }
69
-
70
62
  function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
71
63
  const runtime = new GoalRuntime(pi);
72
64
  const commands = new GoalCommandController(runtime);
@@ -103,6 +95,10 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
103
95
  const consumePendingGoalPrompt = runtime.consumeOwnedGoalPrompt.bind(runtime);
104
96
  const markContinuationStarted = runtime.markContinuationStarted.bind(runtime);
105
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);
106
102
  const clearActiveGoal = runtime.clearActiveGoal.bind(runtime);
107
103
  const showCompletionStatus = runtime.showCompletionStatus.bind(runtime);
108
104
  const restoreGoalToolsHiddenByPolicy = runtime.restoreGoalToolsHiddenByPolicy.bind(runtime);
@@ -111,7 +107,8 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
111
107
  ctx: StatusContext,
112
108
  goalId: string,
113
109
  prompt: string,
114
- ) => runtime.sendOwnedGoalPrompt(ctx, goalId, prompt);
110
+ resetSafetyEpoch = true,
111
+ ) => runtime.sendOwnedGoalPrompt(ctx, goalId, prompt, resetSafetyEpoch);
115
112
  const dispatchPendingQueueActionIfSettled =
116
113
  commands.dispatchPendingQueueActionIfSettled.bind(commands);
117
114
 
@@ -464,7 +461,8 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
464
461
  clearCompletionStatusTimer();
465
462
  clearContinuationTracking();
466
463
  clearPendingGoalPrompts();
467
- runtime.agentRunGoalId = undefined;
464
+ runtime.clearAgentRun();
465
+ runtime.guardAbortGoalId = undefined;
468
466
  clearGoalRecovery();
469
467
  clearBudgetWrapUp();
470
468
  clearStaleGoalToolCallBlock();
@@ -531,6 +529,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
531
529
  if (runtime.activeGoal.status === "active") {
532
530
  updateGoalUsage(runtime.activeGoal, ctx);
533
531
  if (limitActiveGoalForBudget(ctx, false)) return;
532
+ if (enforceAutomaticTurnLimit(ctx, false) || enforceNoProgressLimit(ctx)) return;
534
533
  }
535
534
  if (runtime.settings.toolVisibility === "after-first-goal") {
536
535
  // Registered tools are already active on an unrestricted fresh runtime.
@@ -552,6 +551,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
552
551
  ctx,
553
552
  restoredGoal.id,
554
553
  buildGoalPrompt(restoredGoal),
554
+ false, // Reloaded queue activation preserves its persisted safety epoch.
555
555
  );
556
556
  if (!sent && runtime.activeGoal?.id === restoredGoal.id) {
557
557
  runtime.activeGoal = transitionGoal(restoredGoal, "paused");
@@ -577,7 +577,8 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
577
577
  }
578
578
  clearContinuationTracking();
579
579
  clearPendingGoalPrompts();
580
- runtime.agentRunGoalId = undefined;
580
+ runtime.clearAgentRun();
581
+ runtime.guardAbortGoalId = undefined;
581
582
  clearGoalRecovery();
582
583
  clearBudgetWrapUp();
583
584
  clearStaleGoalToolCallBlock();
@@ -633,8 +634,8 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
633
634
  if (limitActiveGoalForBudget(ctx, false)) return;
634
635
 
635
636
  const wasPiRetry = isPiOwnedCompactionRetry(event, runtime.activeGoal.id);
636
- clearGoalRecoveryForGoal(runtime.activeGoal.id);
637
637
  if (wasPiRetry) return;
638
+ clearGoalRecoveryForGoal(runtime.activeGoal.id);
638
639
  requestContinuation(runtime.activeGoal);
639
640
  // Manual compaction does not emit agent_settled. This common dispatcher is
640
641
  // therefore the narrow fallback; threshold compaction leaves the intent for
@@ -642,7 +643,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
642
643
  dispatchContinuationIfSettled(ctx);
643
644
  });
644
645
 
645
- pi.on("input", (event) => {
646
+ pi.on("input", (event, ctx) => {
646
647
  if (event.source === "extension") {
647
648
  if (
648
649
  consumeCancelledContinuationPrompt(event.text) ||
@@ -651,22 +652,98 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
651
652
  return { action: "handled" as const };
652
653
  }
653
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
+ }
654
662
  clearGoalRecovery();
655
663
  return;
656
664
  }
657
665
  if (runtime.queueFrozen) return;
658
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
+ }
659
674
  clearGoalRecovery();
660
675
  clearBudgetWrapUp();
661
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);
662
730
  });
663
731
 
664
- pi.on("context", (event) => {
732
+ pi.on("context", (event, ctx) => {
665
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
+ }
666
742
  if (messages.length !== event.messages.length) return { messages };
667
743
  });
668
744
 
669
745
  pi.on("tool_call", (event, ctx) => {
746
+ runtime.markAgentToolAttempted();
670
747
  if (runtime.queueFrozen) {
671
748
  if (!isGoalToolName(event.toolName)) return;
672
749
  return {
@@ -721,15 +798,27 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
721
798
  });
722
799
 
723
800
  pi.on("before_agent_start", (event, ctx) => {
724
- if (runtime.queueFrozen) {
725
- runtime.agentRunGoalId = undefined;
726
- return;
727
- }
728
- 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;
729
809
  const continuationGoalId = goalPromptGoalId ? undefined : markContinuationStarted(event.prompt);
730
810
  const ownedPromptGoalId = goalPromptGoalId ?? continuationGoalId;
731
811
  const activeBudgetWrapUp = runtime.hasActiveBudgetWrapUp();
812
+ const queuedNonGoalInput = runtime.consumeQueuedNonGoalInput(event.prompt);
813
+ if (queuedNonGoalInput?.behavior === "followUp") {
814
+ beginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);
815
+ }
732
816
  const activeGoalRecovery = runtime.hasActiveGoalRecovery();
817
+ const runOrigin = continuationGoalId
818
+ ? "automatic"
819
+ : activeGoalRecovery && runtime.goalRecovery?.automaticOwner
820
+ ? "automatic"
821
+ : "manual";
733
822
  if (
734
823
  runtime.pendingQueueAction?.kind === "prioritize" &&
735
824
  !activeBudgetWrapUp &&
@@ -748,56 +837,77 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
748
837
  updateStatus(ctx, runtime.activeGoal);
749
838
  }
750
839
  }
751
- runtime.agentRunGoalId = null;
840
+ runtime.beginAgentRun(null, undefined);
752
841
  if (ownedPromptGoalId) abortCurrentTurn(ctx);
753
842
  return;
754
843
  }
755
844
  if (activeBudgetWrapUp && runtime.activeGoal) {
756
- runtime.agentRunGoalId = runtime.activeGoal.id;
845
+ runtime.beginAgentRun(runtime.activeGoal.id, "manual");
757
846
  return;
758
847
  }
759
848
  if (
760
849
  runtime.pendingQueueAction?.kind === "advance" &&
761
850
  runtime.pendingQueueAction.goalId === runtime.activeGoal?.id
762
851
  ) {
763
- runtime.agentRunGoalId = ownedPromptGoalId ?? runtime.activeGoal.id;
852
+ runtime.beginAgentRun(ownedPromptGoalId ?? runtime.activeGoal.id, runOrigin);
764
853
  if (ownedPromptGoalId) abortCurrentTurn(ctx);
765
854
  return;
766
855
  }
767
856
  if (ownedPromptGoalId && ownedPromptGoalId !== runtime.activeGoal?.id) {
768
- runtime.agentRunGoalId = ownedPromptGoalId;
857
+ runtime.beginAgentRun(ownedPromptGoalId, runOrigin);
769
858
  if (runtime.activeGoal?.status === "active" && !goalToolsAvailable()) {
770
859
  pauseGoalForUnavailableTools(ctx, false);
771
860
  }
772
861
  abortCurrentTurn(ctx);
773
862
  return;
774
863
  }
775
- if (runtime.activeGoal?.status !== "active") {
776
- runtime.agentRunGoalId = undefined;
777
- return;
778
- }
779
- runtime.agentRunGoalId = runtime.activeGoal.id;
864
+ if (runtime.activeGoal?.status !== "active") return;
865
+ runtime.beginAgentRun(runtime.activeGoal.id, runOrigin);
780
866
  if (!goalToolsAvailable()) {
781
867
  pauseGoalForUnavailableTools(ctx, ownedPromptGoalId !== undefined);
782
868
  return;
783
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
+ }
784
875
 
785
876
  return {
786
877
  systemPrompt: `${event.systemPrompt}\n\n${buildGoalSystemPrompt(runtime.activeGoal)}`,
787
878
  };
788
879
  });
789
880
 
790
- pi.on("agent_end", (event, ctx) => {
881
+ pi.on("agent_start", (_event, ctx) => {
791
882
  if (runtime.queueFrozen) return;
792
- const agentRunGoalId = runtime.agentRunGoalId;
793
- runtime.agentRunGoalId = undefined;
883
+ const activeGoal = runtime.activeGoal;
794
884
  if (
795
- agentRunGoalId === null ||
796
- (!runtime.canRecordGoalUsage() && !runtime.hasActiveBudgetWrapUp())
885
+ activeGoal &&
886
+ runtime.guardAbortGoalId === activeGoal.id &&
887
+ activeGoal.status === "paused"
797
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.
798
896
  return;
799
897
  }
800
- 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;
801
911
  if (!runtime.activeGoal) return;
802
912
  if (
803
913
  runtime.activeGoal.status === "budget_limited" &&
@@ -835,6 +945,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
835
945
 
836
946
  if (finalAssistant?.stopReason === "error") {
837
947
  if (isRetryableGoalInterruption(finalAssistant)) {
948
+ if (run.origin === "automatic" && enforceAutomaticTurnLimit(ctx, true)) return;
838
949
  if (limitActiveGoalForBudget(ctx, false)) return;
839
950
  if (!goalToolsAvailable()) {
840
951
  pauseGoalForUnavailableTools(ctx);
@@ -843,6 +954,8 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
843
954
  runtime.goalRecovery = {
844
955
  goalId,
845
956
  kind: isGoalContextOverflow(finalAssistant) ? "compaction_retry" : "provider_retry",
957
+ automaticOwner: run.origin === "automatic",
958
+ errorMessage: finalAssistant.errorMessage,
846
959
  };
847
960
  cancelContinuationWork();
848
961
  persistGoal(runtime.activeGoal);
@@ -866,6 +979,17 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
866
979
  pauseGoalForUnavailableTools(ctx);
867
980
  return;
868
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
+ }
869
993
 
870
994
  persistGoal(runtime.activeGoal);
871
995
  updateStatus(ctx, runtime.activeGoal);
@@ -876,17 +1000,30 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
876
1000
  requestContinuation(currentGoal);
877
1001
  });
878
1002
 
879
- onAgentSettled(pi, (_event, ctx) => {
880
- if (runtime.queueFrozen) return;
881
- if (!runtime.pendingQueueAction) {
882
- dispatchContinuationIfSettled(ctx);
1003
+ pi.on("agent_settled", async (_event, ctx) => {
1004
+ if (runtime.queueFrozen) {
1005
+ runtime.clearSettledSafetyTracking();
883
1006
  return;
884
1007
  }
885
- return dispatchPendingQueueActionIfSettled(ctx).then((dispatched) => {
886
- if (!dispatched) dispatchContinuationIfSettled(ctx);
887
- });
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();
888
1015
  });
889
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
+
890
1027
  function hasPendingSkipForGoal(goalId: string) {
891
1028
  return (
892
1029
  runtime.pendingQueueAction?.kind === "advance" &&
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