@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/runtime.ts CHANGED
@@ -1,29 +1,28 @@
1
- import { randomUUID } from "node:crypto";
2
- import {
3
- isContextOverflow,
4
- type AssistantMessage as PiAssistantMessage,
5
- type Usage,
6
- } from "@earendil-works/pi-ai";
1
+ import { createHash, randomUUID } from "node:crypto";
7
2
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
8
3
  import {
9
- assistantUsageTokens,
10
4
  checkpointGoalActiveTime,
11
5
  formatDuration,
12
6
  formatTokenCount,
13
- nonNegativeFiniteNumber,
14
7
  updateGoalUsage,
15
8
  } from "./accounting.js";
9
+ import { formatError, truncateNotification } from "./errors.js";
10
+ import {
11
+ appendGoalPromptMarker,
12
+ extractContinuationMarker,
13
+ extractGoalPromptMarker,
14
+ } from "./markers.js";
16
15
  import {
17
16
  type ActiveGoal,
18
17
  clearLegacyPersistedGoal,
19
18
  type PendingQueueAction,
19
+ type SafetyPauseCause,
20
20
  serializeGoalState,
21
21
  } from "./persistence.js";
22
22
  import { buildContinuePrompt, type GoalStatus } from "./prompts.js";
23
+ import { nextToolFreeRepeatState } from "./safety.js";
23
24
  import { DEFAULT_GOAL_SETTINGS, type GoalSettings } from "./settings.js";
24
25
 
25
- export type AgentStopReason = "stop" | "length" | "toolUse" | "error" | "aborted";
26
-
27
26
  export interface ContinuationTicket {
28
27
  goalId: string;
29
28
  iteration: number;
@@ -38,21 +37,19 @@ export interface BudgetWrapUp {
38
37
 
39
38
  export type GoalRecoveryKind = "provider_retry" | "compaction_retry";
40
39
 
40
+ export type GoalRunOrigin = "manual" | "automatic";
41
+
41
42
  export interface GoalRecovery {
42
43
  goalId: string;
43
44
  kind: GoalRecoveryKind;
45
+ automaticOwner: boolean;
46
+ errorMessage?: string;
44
47
  }
45
48
 
46
- export interface AssistantMessageLike {
47
- role: "assistant";
48
- stopReason?: AgentStopReason;
49
- errorMessage?: string;
50
- content?: PiAssistantMessage["content"];
51
- api?: PiAssistantMessage["api"];
52
- provider?: PiAssistantMessage["provider"];
53
- model?: string;
54
- usage?: Usage;
55
- timestamp?: number;
49
+ export interface CompletedGoalRun {
50
+ goalId?: string | null;
51
+ origin?: GoalRunOrigin;
52
+ toolAttempted: boolean;
56
53
  }
57
54
 
58
55
  export interface StatusContext {
@@ -80,10 +77,62 @@ export const GOAL_COMPLETE_TOOL = "goal_complete";
80
77
  export const GOAL_BLOCKED_TOOL = "goal_blocked";
81
78
  export const GOAL_TOOL_NAMES = [GOAL_COMPLETE_TOOL, GOAL_BLOCKED_TOOL] as const;
82
79
 
80
+ /** Cross-extension event channel carrying the canonical persisted goal state. */
81
+ export const GOAL_STATE_EVENT_CHANNEL = "pi-goal:state";
82
+
83
+ /** State values broadcast to cross-extension listeners. */
84
+ export type GoalStateEventStatus = GoalStatus | "cleared";
85
+
86
+ /** Payload emitted on {@link GOAL_STATE_EVENT_CHANNEL} whenever goal state persists. */
87
+ export interface GoalStateEventPayload {
88
+ goalId: string;
89
+ status: GoalStateEventStatus;
90
+ summary?: string;
91
+ reason?: string;
92
+ }
93
+
94
+ /** Terminal statuses broadcast to cross-extension listeners. */
95
+ export function isTerminalGoalStatus(status: GoalStateEventStatus): boolean {
96
+ return status !== "active" && status !== "queued";
97
+ }
98
+
99
+ /**
100
+ * Build the cross-extension state payload from the canonical goal plus the most
101
+ * recent completion summary or blocked/failure reason, without re-deriving state.
102
+ */
103
+ export function buildGoalStateEvent(
104
+ goal: ActiveGoal,
105
+ summary: string | undefined,
106
+ reason: string | undefined,
107
+ ): GoalStateEventPayload {
108
+ const payload: GoalStateEventPayload = { goalId: goal.id, status: goal.status };
109
+ if (goal.status === "complete" && summary) payload.summary = summary;
110
+ else if (goal.status !== "complete" && isTerminalGoalStatus(goal.status) && reason) {
111
+ payload.reason = reason;
112
+ }
113
+ return payload;
114
+ }
115
+
116
+ interface GoalTerminalDetails {
117
+ goalId: string;
118
+ summary?: string;
119
+ reason?: string;
120
+ }
121
+
122
+ interface PendingGoalPrompt {
123
+ goalId: string;
124
+ resetSafetyEpoch: boolean;
125
+ }
126
+
127
+ interface PendingNonGoalInput {
128
+ behavior: "steer" | "followUp";
129
+ fingerprint: string;
130
+ resetSafetyEpoch: boolean;
131
+ }
132
+
83
133
  const MAX_CANCELLED_CONTINUATION_PROMPTS = 20;
84
134
  const MAX_PENDING_GOAL_PROMPTS = 20;
85
- const GOAL_PROMPT_MARKER_PREFIX = "pi-goal-prompt:";
86
- const CONTINUATION_MARKER_PREFIX = "pi-goal-continuation:";
135
+ const MAX_PENDING_NON_GOAL_INPUTS = 20;
87
136
  const BUDGET_WRAP_UP_MESSAGE_TYPE = "goal-budget-wrap-up";
88
137
  const BUDGET_WRAP_UP_PROMPT =
89
138
  "The active /goal token budget is exhausted. Stop substantive work and do not call substantive tools. Summarize progress, verified results, remaining work, and blockers concisely. Treat completion as unproven. Do not call goal_complete unless authoritative, requirement-by-requirement evidence already proves every requirement is complete. Weak, indirect, or missing evidence is not enough. Budget exhaustion is not completion.";
@@ -92,29 +141,13 @@ const CONTRADICTORY_COMPLETION_PATTERNS = [
92
141
  /\bstill\s+(?:incomplete|failing|failing\s+tests?|fails?)\b/i,
93
142
  /\btests?\s+(?:still\s+)?fail(?:ing)?\b/i,
94
143
  ] as const;
95
- const USAGE_LIMIT_GOAL_ERROR_PATTERNS = [
96
- /usage[_\s-]*(?:limit|cap)|chatgpt.{0,32}usage/i,
97
- /quota.{0,32}(?:reached|exceeded|exhausted|depleted)|(?:reached|exceeded|exhausted|depleted).{0,32}quota/i,
98
- /insufficient[_\s-]*(?:quota|credits?)|out of credits|out of budget|available balance|payment required/i,
99
- /(?:credit|balance).{0,32}(?:low|exhausted|depleted)|billing/i,
100
- ] as const;
101
- const NON_RETRYABLE_GOAL_ERROR_RE =
102
- /multi-auth rotation failed|credentials tried|unauthori[sz]ed|invalid api key/i;
103
- // Pi 0.79 does not export its assistant-error retry classifier. Keep this
104
- // compatibility mirror aligned with Pi's public retry utility in newer versions.
105
- const RETRYABLE_GOAL_ERROR_PATTERNS = [
106
- /overloaded|rate.?limit|too many requests|\b(?:429|500|502|503|504)\b|service.?unavailable|server.?error|internal.?error/i,
107
- /provider.?returned.?error|you can retry your request|try your request again|please retry your request/i,
108
- /network.?error|connection.?(?:error|refused|lost)|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up/i,
109
- /timed? out|timeout|terminated|websocket.?(?:closed|error)|ended without|stream ended before message_stop|http2 request did not get a response|retry delay/i,
110
- /context[_\s-]*length[_\s-]*exceeded|input exceeds the context window/i,
111
- ] as const;
112
-
113
144
  // One instance belongs to one extension factory. It owns all mutable session state
114
145
  // and the cross-cutting invariants used by command and lifecycle orchestration.
115
146
  export class GoalRuntime {
116
147
  settings: GoalSettings = DEFAULT_GOAL_SETTINGS;
117
148
  activeGoal?: ActiveGoal;
149
+ /** Terminal details captured for the matching cross-extension state event. */
150
+ private terminalDetails?: GoalTerminalDetails;
118
151
  queuedGoals: ActiveGoal[] = [];
119
152
  pendingQueueAction?: PendingQueueAction;
120
153
  queueFrozen = false;
@@ -125,13 +158,17 @@ export class GoalRuntime {
125
158
  budgetWrapUp?: BudgetWrapUp;
126
159
  /** `null` marks a run that must not be charged to the active goal. */
127
160
  agentRunGoalId?: string | null;
161
+ agentRunOrigin?: GoalRunOrigin;
162
+ agentRunToolAttempted = false;
163
+ guardAbortGoalId?: string;
128
164
  staleGoalToolCallsBlocked = false;
129
165
  /** Once true, goal tools stay in the active set for this runtime (prompt-cache stable). */
130
166
  goalToolsUnlocked = false;
131
167
  /** Exact lazy goal tools this runtime removed and may restore on a mode change. */
132
168
  goalToolsHiddenByPolicy = new Set<string>();
133
- pendingGoalPromptMarkers = new Map<string, string>();
169
+ pendingGoalPromptMarkers = new Map<string, PendingGoalPrompt>();
134
170
  cancelledContinuationMarkers = new Set<string>();
171
+ pendingNonGoalInputs: PendingNonGoalInput[] = [];
135
172
 
136
173
  readonly pi: ExtensionAPI;
137
174
 
@@ -139,9 +176,12 @@ export class GoalRuntime {
139
176
  this.pi = pi;
140
177
  }
141
178
 
142
- canRecordGoalUsage() {
179
+ canRecordGoalUsage(goalId?: string) {
143
180
  return (
144
181
  this.agentRunGoalId !== null &&
182
+ (goalId === undefined ||
183
+ this.agentRunGoalId === undefined ||
184
+ this.agentRunGoalId === goalId) &&
145
185
  !(
146
186
  this.pendingQueueAction?.kind === "prioritize" &&
147
187
  this.pendingQueueAction.displacedUsageFinalized === true
@@ -161,12 +201,53 @@ export class GoalRuntime {
161
201
  return Boolean(this.activeGoal && this.goalRecovery?.goalId === this.activeGoal.id);
162
202
  }
163
203
 
204
+ beginAgentRun(goalId: string | null | undefined, origin: GoalRunOrigin | undefined) {
205
+ this.agentRunGoalId = goalId;
206
+ this.agentRunOrigin = origin;
207
+ this.agentRunToolAttempted = false;
208
+ }
209
+
210
+ beginRecoveryRunIfNeeded() {
211
+ if (this.agentRunGoalId !== undefined || !this.activeGoal) return;
212
+ const recovery = this.goalRecovery;
213
+ if (!recovery || recovery.goalId !== this.activeGoal.id) return;
214
+ this.beginAgentRun(recovery.goalId, recovery.automaticOwner ? "automatic" : "manual");
215
+ }
216
+
217
+ markAgentToolAttempted() {
218
+ if (this.agentRunGoalId !== undefined) this.agentRunToolAttempted = true;
219
+ }
220
+
221
+ finishAgentRun(): CompletedGoalRun {
222
+ const run = {
223
+ goalId: this.agentRunGoalId,
224
+ origin: this.agentRunOrigin,
225
+ toolAttempted: this.agentRunToolAttempted,
226
+ };
227
+ this.clearAgentRun();
228
+ return run;
229
+ }
230
+
231
+ clearAgentRun() {
232
+ this.agentRunGoalId = undefined;
233
+ this.agentRunOrigin = undefined;
234
+ this.agentRunToolAttempted = false;
235
+ }
236
+
237
+ reclassifyAgentRunAsManual() {
238
+ if (this.agentRunGoalId !== undefined) this.agentRunOrigin = "manual";
239
+ }
240
+
241
+ isAutomaticRunForGoal(goalId: string) {
242
+ return this.agentRunGoalId === goalId && this.agentRunOrigin === "automatic";
243
+ }
244
+
164
245
  recordGoalUsage(
165
246
  goal: ActiveGoal,
166
247
  ctx: StatusContext,
167
248
  checkpointActiveTime = goal.status === "active",
168
249
  ) {
169
- if (!this.canRecordGoalUsage()) return false;
250
+ if (!this.canRecordGoalUsage(goal.id)) return false;
170
251
  updateGoalUsage(goal, ctx, checkpointActiveTime);
171
252
  return true;
172
253
  }
@@ -198,6 +279,9 @@ export class GoalRuntime {
198
279
  this.continuationIntent = undefined;
199
280
  return false;
200
281
  }
282
+ if (this.enforceAutomaticTurnLimit(ctx, false) || this.enforceNoProgressLimit(ctx)) {
283
+ return false;
284
+ }
201
285
  if (ctx.isIdle?.() !== true || hasPendingMessages(ctx)) return false;
202
286
 
203
287
  this.continuationIntent = undefined;
@@ -244,6 +328,18 @@ export class GoalRuntime {
244
328
  this.budgetWrapUp = undefined;
245
329
  }
246
330
 
331
+ setCompletionSummary(goalId: string, summary: string) {
332
+ this.terminalDetails = { goalId, summary };
333
+ }
334
+
335
+ setTerminalReason(goalId: string, reason: string) {
336
+ this.terminalDetails = { goalId, reason };
337
+ }
338
+
339
+ clearTerminalDetails() {
340
+ this.terminalDetails = undefined;
341
+ }
342
+
247
343
  keepBudgetWrapUpMessage(message: unknown) {
248
344
  if (!message || typeof message !== "object") return true;
249
345
  const candidate = message as {
@@ -299,6 +395,10 @@ export class GoalRuntime {
299
395
  this.clearGoalRecoveryForGoal(goal.id);
300
396
  this.clearBudgetWrapUp();
301
397
  this.activeGoal = transitionGoal(goal, "budget_limited");
398
+ this.setTerminalReason(
399
+ this.activeGoal.id,
400
+ `token budget reached (${formatBudget(this.activeGoal)})`,
401
+ );
302
402
  this.persistGoal(this.activeGoal);
303
403
  this.updateStatus(ctx, this.activeGoal);
304
404
  ctx.ui.notify(`Goal token budget reached: ${formatBudget(this.activeGoal)}`, "warning");
@@ -306,6 +406,123 @@ export class GoalRuntime {
306
406
  return true;
307
407
  }
308
408
 
409
+ recordAutomaticTurn(ctx: StatusContext, message: unknown) {
410
+ const goal = this.activeGoal;
411
+ if (goal?.status !== "active" || !this.isAutomaticRunForGoal(goal.id)) return false;
412
+ const candidate = message as { role?: unknown; stopReason?: unknown } | undefined;
413
+ if (candidate?.role === "assistant" && candidate.stopReason === "aborted") return false;
414
+ goal.automaticModelTurns = Math.min(Number.MAX_SAFE_INTEGER, goal.automaticModelTurns + 1);
415
+ this.recordGoalUsage(goal, ctx);
416
+ this.persistGoal(goal);
417
+ this.updateStatus(ctx, goal);
418
+ // Terminal errors need agent_end classification before a safety pause can
419
+ // choose between usage_limited, blocked, or retryable cleanup.
420
+ if (candidate?.role === "assistant" && candidate.stopReason === "error") return false;
421
+ return this.enforceAutomaticTurnLimit(ctx, true);
422
+ }
423
+
424
+ recordAutomaticRunProgress(
425
+ ctx: StatusContext,
426
+ goalId: string,
427
+ messages: readonly unknown[],
428
+ toolAttempted: boolean,
429
+ ) {
430
+ const goal = this.activeGoal;
431
+ if (goal?.id !== goalId || goal.status !== "active") return false;
432
+ const next = nextToolFreeRepeatState(goal, messages, toolAttempted);
433
+ goal.toolFreeRepeatCount = next.toolFreeRepeatCount;
434
+ goal.lastToolFreeOutputFingerprint = next.lastToolFreeOutputFingerprint;
435
+ this.persistGoal(goal);
436
+ this.updateStatus(ctx, goal);
437
+ const limit = this.settings.continuationLimits.noProgressTurns;
438
+ if (limit === null || goal.toolFreeRepeatCount < limit) return false;
439
+ return this.pauseGoalForSafety(ctx, "no_progress", false);
440
+ }
441
+
442
+ enforceAutomaticTurnLimit(ctx: StatusContext, abortTurn: boolean) {
443
+ const goal = this.activeGoal;
444
+ const limit = this.settings.continuationLimits.automaticTurns;
445
+ if (goal?.status !== "active" || limit === null || goal.automaticModelTurns < limit) {
446
+ return false;
447
+ }
448
+ return this.pauseGoalForSafety(ctx, "continuation_limit", abortTurn);
449
+ }
450
+
451
+ enforceNoProgressLimit(ctx: StatusContext) {
452
+ const goal = this.activeGoal;
453
+ const limit = this.settings.continuationLimits.noProgressTurns;
454
+ if (goal?.status !== "active" || limit === null || goal.toolFreeRepeatCount < limit) {
455
+ return false;
456
+ }
457
+ return this.pauseGoalForSafety(ctx, "no_progress", false);
458
+ }
459
+
460
+ pauseGoalForSafety(ctx: StatusContext, cause: SafetyPauseCause, abortTurn: boolean) {
461
+ const goal = this.activeGoal;
462
+ if (goal?.status !== "active") return false;
463
+ this.cancelContinuationWork();
464
+ this.clearGoalRecoveryForGoal(goal.id);
465
+ this.clearBudgetWrapUp();
466
+ this.blockStaleGoalToolCalls();
467
+ if (abortTurn) {
468
+ this.guardAbortGoalId = goal.id;
469
+ abortCurrentTurn(ctx);
470
+ }
471
+ this.activeGoal = transitionGoal({ ...goal, safetyPauseCause: cause }, "paused");
472
+ const count =
473
+ cause === "continuation_limit"
474
+ ? `${this.activeGoal.automaticModelTurns} automatic model responses`
475
+ : `no progress across ${this.activeGoal.toolFreeRepeatCount} automatic runs`;
476
+ this.setTerminalReason(
477
+ this.activeGoal.id,
478
+ `${cause} (${count}; ${formatTokenCount(this.activeGoal.tokensUsed)} tokens)`,
479
+ );
480
+ this.persistGoal(this.activeGoal);
481
+ this.updateStatus(ctx, this.activeGoal);
482
+ ctx.ui.notify(
483
+ `Goal paused: ${count}; ${formatTokenCount(this.activeGoal.tokensUsed)} cumulative tokens. Run /goal resume to continue.`,
484
+ "warning",
485
+ );
486
+ return true;
487
+ }
488
+
489
+ resetActiveSafetyEpoch(ctx: StatusContext) {
490
+ const goal = this.activeGoal;
491
+ if (goal?.status !== "active") return false;
492
+ this.activeGoal = resetGoalSafetyEpoch(goal);
493
+ this.reclassifyAgentRunAsManual();
494
+ this.persistGoal(this.activeGoal);
495
+ this.updateStatus(ctx, this.activeGoal);
496
+ return true;
497
+ }
498
+
499
+ finalizeSettledRecovery(ctx: StatusContext) {
500
+ const recovery = this.goalRecovery;
501
+ if (!recovery) return false;
502
+ this.goalRecovery = undefined;
503
+ const goal = this.activeGoal;
504
+ if (goal?.id !== recovery.goalId || goal.status !== "active") return false;
505
+ this.cancelContinuationWork();
506
+ this.clearBudgetWrapUp();
507
+ this.blockStaleGoalToolCalls();
508
+ this.activeGoal = transitionGoal(goal, "blocked");
509
+ const details = recovery.errorMessage ? `: ${truncateNotification(recovery.errorMessage)}` : "";
510
+ this.setTerminalReason(this.activeGoal.id, `agent error after retries${details}`);
511
+ this.persistGoal(this.activeGoal);
512
+ this.updateStatus(ctx, this.activeGoal);
513
+ ctx.ui.notify(
514
+ `Goal blocked after agent error retries were exhausted${details}. Resolve the blocker or run /goal resume to retry.`,
515
+ "warning",
516
+ );
517
+ return true;
518
+ }
519
+
520
+ clearSettledSafetyTracking() {
521
+ this.guardAbortGoalId = undefined;
522
+ this.pendingNonGoalInputs = [];
523
+ this.clearAgentRun();
524
+ }
525
+
309
526
  clearGoalRecoveryForGoal(goalId: string) {
310
527
  if (this.goalRecovery?.goalId === goalId) this.goalRecovery = undefined;
311
528
  }
@@ -328,10 +545,16 @@ export class GoalRuntime {
328
545
 
329
546
  clearPendingGoalPrompts() {
330
547
  this.pendingGoalPromptMarkers.clear();
548
+ this.pendingNonGoalInputs = [];
331
549
  }
332
550
 
333
- async sendOwnedGoalPrompt(ctx: StatusContext, goalId: string, prompt: string) {
334
- const pending = this.rememberPendingGoalPrompt(goalId, prompt);
551
+ async sendOwnedGoalPrompt(
552
+ ctx: StatusContext,
553
+ goalId: string,
554
+ prompt: string,
555
+ resetSafetyEpoch = true,
556
+ ) {
557
+ const pending = this.rememberPendingGoalPrompt(goalId, prompt, resetSafetyEpoch);
335
558
  const sent = await sendPrompt(this.pi, ctx, pending.prompt);
336
559
  if (!sent) this.pendingGoalPromptMarkers.delete(pending.marker);
337
560
  return sent;
@@ -350,15 +573,20 @@ export class GoalRuntime {
350
573
  return marker ? this.cancelledContinuationMarkers.delete(marker) : false;
351
574
  }
352
575
 
576
+ hasPendingOwnedGoalPrompt(prompt: string) {
577
+ const marker = extractGoalPromptMarker(prompt);
578
+ return marker ? this.pendingGoalPromptMarkers.has(marker) : false;
579
+ }
580
+
353
581
  consumeStaleOwnedGoalPrompt(prompt: string) {
354
582
  const marker = extractGoalPromptMarker(prompt);
355
583
  if (!marker) return false;
356
- const goalId = this.pendingGoalPromptMarkers.get(marker);
357
- if (!goalId) return false;
584
+ const pending = this.pendingGoalPromptMarkers.get(marker);
585
+ if (!pending) return false;
358
586
  if (
359
587
  !this.queueFrozen &&
360
588
  !this.pendingQueueAction &&
361
- this.activeGoal?.id === goalId &&
589
+ this.activeGoal?.id === pending.goalId &&
362
590
  this.activeGoal.status === "active"
363
591
  ) {
364
592
  return false;
@@ -367,6 +595,52 @@ export class GoalRuntime {
367
595
  return true;
368
596
  }
369
597
 
598
+ noteQueuedNonGoalInput(
599
+ prompt: string,
600
+ behavior: "steer" | "followUp",
601
+ resetSafetyEpoch = false,
602
+ ) {
603
+ this.pendingNonGoalInputs.push({
604
+ behavior,
605
+ fingerprint: inputFingerprint(prompt),
606
+ resetSafetyEpoch,
607
+ });
608
+ if (this.pendingNonGoalInputs.length > MAX_PENDING_NON_GOAL_INPUTS) {
609
+ this.pendingNonGoalInputs.shift();
610
+ }
611
+ }
612
+
613
+ consumeQueuedNonGoalInput(prompt: string) {
614
+ if (typeof prompt !== "string") return undefined;
615
+ const fingerprint = inputFingerprint(prompt);
616
+ // Pi delivers steers before follow-ups. Prefer a matching steer even when an
617
+ // identical follow-up was queued first so it cannot steal follow-up ownership.
618
+ const steerIndex = this.pendingNonGoalInputs.findIndex(
619
+ (pending) => pending.behavior === "steer" && pending.fingerprint === fingerprint,
620
+ );
621
+ const index =
622
+ steerIndex >= 0
623
+ ? steerIndex
624
+ : this.pendingNonGoalInputs.findIndex(
625
+ (pending) =>
626
+ pending.behavior === "followUp" && pending.fingerprint === fingerprint,
627
+ );
628
+ if (index < 0) return undefined;
629
+ return this.pendingNonGoalInputs.splice(index, 1)[0];
630
+ }
631
+
632
+ consumeQueuedNonGoalFollowUpForAgentStart() {
633
+ // A pending steer owns the next intra-run boundary. Do not let a later
634
+ // follow-up suppress cleanup until all earlier-priority steers have started.
635
+ if (this.pendingNonGoalInputs.some((pending) => pending.behavior === "steer")) return false;
636
+ const index = this.pendingNonGoalInputs.findIndex(
637
+ (pending) => pending.behavior === "followUp",
638
+ );
639
+ if (index < 0) return false;
640
+ this.pendingNonGoalInputs.splice(index, 1);
641
+ return true;
642
+ }
643
+
370
644
  markContinuationStarted(prompt: string) {
371
645
  const marker = extractContinuationMarker(prompt);
372
646
  if (!marker) {
@@ -381,18 +655,34 @@ export class GoalRuntime {
381
655
  }
382
656
 
383
657
  persistGoal(goal: ActiveGoal) {
658
+ if (!isTerminalGoalStatus(goal.status) || this.terminalDetails?.goalId !== goal.id) {
659
+ this.clearTerminalDetails();
660
+ }
384
661
  this.pi.appendEntry(
385
662
  GOAL_STATE_ENTRY_TYPE,
386
663
  serializeGoalState(goal, this.queuedGoals, this.pendingQueueAction),
387
664
  );
665
+ this.pi.events.emit(
666
+ GOAL_STATE_EVENT_CHANNEL,
667
+ buildGoalStateEvent(goal, this.terminalDetails?.summary, this.terminalDetails?.reason),
668
+ );
388
669
  }
389
670
 
390
- clearPersistedGoal(cwd: string) {
671
+ clearPersistedGoal(cwd: string, clearedGoal?: ActiveGoal, reason = "goal cleared") {
391
672
  this.pi.appendEntry(GOAL_STATE_ENTRY_TYPE, serializeGoalState(undefined, [], undefined));
673
+ if (clearedGoal) {
674
+ this.pi.events.emit(GOAL_STATE_EVENT_CHANNEL, {
675
+ goalId: clearedGoal.id,
676
+ status: "cleared",
677
+ reason,
678
+ } satisfies GoalStateEventPayload);
679
+ }
680
+ this.clearTerminalDetails();
392
681
  clearLegacyPersistedGoal(cwd);
393
682
  }
394
683
 
395
- clearActiveGoal(ctx: StatusContext) {
684
+ clearActiveGoal(ctx: StatusContext, reason = "goal cleared") {
685
+ const clearedGoal = this.activeGoal;
396
686
  this.cancelContinuationWork();
397
687
  this.clearGoalRecovery();
398
688
  this.clearBudgetWrapUp();
@@ -401,7 +691,7 @@ export class GoalRuntime {
401
691
  this.queuedGoals = [];
402
692
  this.pendingQueueAction = undefined;
403
693
  this.queueFrozen = false;
404
- this.clearPersistedGoal(ctx.cwd);
694
+ this.clearPersistedGoal(ctx.cwd, clearedGoal, reason);
405
695
  ctx.ui.setStatus(STATUS_KEY, undefined);
406
696
  // Do not clear goalToolsUnlocked: after first activation, keep tools visible
407
697
  // for the rest of this extension runtime to avoid repeated goal-tool schema
@@ -550,22 +840,26 @@ export class GoalRuntime {
550
840
  this.completionStatusTimer = undefined;
551
841
  }
552
842
 
553
- private rememberPendingGoalPrompt(goalId: string, prompt: string) {
843
+ private rememberPendingGoalPrompt(
844
+ goalId: string,
845
+ prompt: string,
846
+ resetSafetyEpoch: boolean,
847
+ ) {
554
848
  const marker = randomUUID();
555
- this.pendingGoalPromptMarkers.set(marker, goalId);
849
+ this.pendingGoalPromptMarkers.set(marker, { goalId, resetSafetyEpoch });
556
850
  if (this.pendingGoalPromptMarkers.size > MAX_PENDING_GOAL_PROMPTS) {
557
851
  const oldest = this.pendingGoalPromptMarkers.keys().next().value;
558
852
  if (oldest) this.pendingGoalPromptMarkers.delete(oldest);
559
853
  }
560
- return { marker, prompt: `${prompt}\n\n<!-- ${GOAL_PROMPT_MARKER_PREFIX}${marker} -->` };
854
+ return { marker, prompt: appendGoalPromptMarker(prompt, marker) };
561
855
  }
562
856
 
563
857
  private consumePendingGoalPrompt(prompt: string) {
564
858
  const marker = extractGoalPromptMarker(prompt);
565
859
  if (!marker) return undefined;
566
- const goalId = this.pendingGoalPromptMarkers.get(marker);
860
+ const pending = this.pendingGoalPromptMarkers.get(marker);
567
861
  this.pendingGoalPromptMarkers.delete(marker);
568
- return goalId;
862
+ return pending;
569
863
  }
570
864
 
571
865
  consumeOwnedGoalPrompt(prompt: string) {
@@ -598,6 +892,8 @@ export function createGoal(
598
892
  timeUsedSeconds: 0,
599
893
  baselineTokens,
600
894
  activeStartedAt: now,
895
+ automaticModelTurns: 0,
896
+ toolFreeRepeatCount: 0,
601
897
  };
602
898
  }
603
899
 
@@ -618,6 +914,16 @@ export function nextGoalInstance(goal: ActiveGoal): ActiveGoal {
618
914
  return { ...goal, id: randomUUID(), updatedAt: Date.now() };
619
915
  }
620
916
 
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
+
621
927
  export function editedGoalStatus(status: GoalStatus): GoalStatus {
622
928
  if (status === "paused" || status === "blocked" || status === "usage_limited") return status;
623
929
  return "active";
@@ -653,9 +959,15 @@ export function goalSummary(
653
959
  `Goal: ${goal.text}`,
654
960
  `Status: ${queueFrozen ? "queue off" : goal.status}`,
655
961
  `Iteration: ${goal.iteration}`,
962
+ `Automatic model responses: ${goal.automaticModelTurns}`,
656
963
  `Active elapsed: ${formatDuration(goal.timeUsedSeconds)}`,
657
964
  `Tokens: ${goal.tokenBudget === undefined ? formatTokenCount(goal.tokensUsed) : formatBudget(goal)}`,
658
965
  ];
966
+ if (goal.safetyPauseCause) {
967
+ summary.push(
968
+ `Safety pause: ${goal.safetyPauseCause === "continuation_limit" ? "automatic response limit" : "no progress"}`,
969
+ );
970
+ }
659
971
  if (experimentalGoals || queuedGoals.length > 0 || queueFrozen) {
660
972
  summary.push(
661
973
  `Goals (${queuedGoals.length + 1}):`,
@@ -711,65 +1023,8 @@ export function goalIdRejectionReason(goal: ActiveGoal, requestedGoalId: string)
711
1023
  return undefined;
712
1024
  }
713
1025
 
714
- export function isUsageLimitedGoalInterruption(assistant: AssistantMessageLike) {
715
- const errorMessage = assistant.errorMessage;
716
- return (
717
- assistant.stopReason === "error" &&
718
- typeof errorMessage === "string" &&
719
- USAGE_LIMIT_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(errorMessage))
720
- );
721
- }
722
-
723
- export function isRetryableGoalInterruption(assistant: AssistantMessageLike) {
724
- if (assistant.stopReason !== "error") return false;
725
- if (!assistant.errorMessage) return false;
726
- if (
727
- isUsageLimitedGoalInterruption(assistant) ||
728
- NON_RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage)
729
- ) {
730
- return false;
731
- }
732
- return (
733
- isGoalContextOverflow(assistant) ||
734
- RETRYABLE_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(assistant.errorMessage ?? ""))
735
- );
736
- }
737
-
738
- export function isGoalContextOverflow(assistant: AssistantMessageLike) {
739
- return isContextOverflow(toPiAssistantMessage(assistant));
740
- }
741
-
742
- export function findFinalAssistantMessage(messages: unknown[]): AssistantMessageLike | undefined {
743
- for (let i = messages.length - 1; i >= 0; i--) {
744
- const message = messages[i];
745
- if (!message || typeof message !== "object") continue;
746
- const candidate = message as Record<string, unknown>;
747
- if (candidate.role !== "assistant") continue;
748
- const assistant: AssistantMessageLike = {
749
- role: "assistant",
750
- stopReason: isAgentStopReason(candidate.stopReason) ? candidate.stopReason : undefined,
751
- errorMessage: typeof candidate.errorMessage === "string" ? candidate.errorMessage : undefined,
752
- };
753
- if (Array.isArray(candidate.content)) {
754
- assistant.content = candidate.content as PiAssistantMessage["content"];
755
- }
756
- if (typeof candidate.api === "string") assistant.api = candidate.api;
757
- if (typeof candidate.provider === "string") assistant.provider = candidate.provider;
758
- if (typeof candidate.model === "string") assistant.model = candidate.model;
759
- if (typeof candidate.timestamp === "number") assistant.timestamp = candidate.timestamp;
760
- const usage = normalizeUsage(candidate.usage);
761
- if (usage) assistant.usage = usage;
762
- return assistant;
763
- }
764
- return undefined;
765
- }
766
-
767
- export function formatError(error: unknown) {
768
- return truncateNotification(error instanceof Error ? error.message : String(error));
769
- }
770
-
771
- export function truncateNotification(value: string) {
772
- return value.length > 160 ? `${value.slice(0, 157)}...` : value;
1026
+ function inputFingerprint(prompt: string) {
1027
+ return createHash("sha256").update(prompt, "utf8").digest("hex");
773
1028
  }
774
1029
 
775
1030
  async function sendPrompt(pi: ExtensionAPI, ctx: StatusContext, prompt: string) {
@@ -795,80 +1050,16 @@ function goalCommandHint(status: GoalStatus, experimentalGoals = false) {
795
1050
  return `/goal edit <objective>, /goal clear${queueCommands}`;
796
1051
  }
797
1052
 
798
- function toPiAssistantMessage(assistant: AssistantMessageLike): PiAssistantMessage {
799
- return {
800
- role: "assistant",
801
- content: assistant.content ?? [],
802
- api: assistant.api ?? "openai-responses",
803
- provider: assistant.provider ?? "unknown",
804
- model: assistant.model ?? "unknown",
805
- usage: assistant.usage ?? zeroUsage(),
806
- stopReason: assistant.stopReason ?? "error",
807
- errorMessage: assistant.errorMessage,
808
- timestamp: assistant.timestamp ?? Date.now(),
809
- };
810
- }
811
-
812
- function zeroUsage(): Usage {
813
- return {
814
- input: 0,
815
- output: 0,
816
- cacheRead: 0,
817
- cacheWrite: 0,
818
- totalTokens: 0,
819
- cost: {
820
- input: 0,
821
- output: 0,
822
- cacheRead: 0,
823
- cacheWrite: 0,
824
- total: 0,
825
- },
826
- };
827
- }
828
-
829
1053
  function continuationMarker(goal: ActiveGoal) {
830
1054
  return `${goal.id}:${goal.iteration}:${randomUUID()}`;
831
1055
  }
832
1056
 
833
- function escapeRegExpText(value: string) {
834
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
835
- }
836
-
837
- const GOAL_PROMPT_MARKER_PATTERN = new RegExp(
838
- `<!--\\s*${escapeRegExpText(GOAL_PROMPT_MARKER_PREFIX)}([^\\s>]+)\\s*-->`,
839
- );
840
- const CONTINUATION_MARKER_PATTERN = new RegExp(
841
- `<!--\\s*${escapeRegExpText(CONTINUATION_MARKER_PREFIX)}([^\\s>]+)\\s*-->`,
842
- );
843
-
844
- function extractGoalPromptMarker(prompt: string) {
845
- return GOAL_PROMPT_MARKER_PATTERN.exec(prompt)?.[1];
846
- }
847
-
848
- function extractContinuationMarker(prompt: string) {
849
- return CONTINUATION_MARKER_PATTERN.exec(prompt)?.[1];
850
- }
851
-
852
- function isAgentStopReason(value: unknown): value is AgentStopReason {
853
- return ["stop", "length", "toolUse", "error", "aborted"].includes(String(value));
854
- }
855
-
856
- function normalizeUsage(value: unknown): Usage | undefined {
857
- if (!value || typeof value !== "object") return undefined;
858
- const usage = value as Partial<Usage>;
859
- if (typeof usage.input !== "number" || typeof usage.output !== "number") return undefined;
860
- return {
861
- input: nonNegativeFiniteNumber(usage.input),
862
- output: nonNegativeFiniteNumber(usage.output),
863
- cacheRead: nonNegativeFiniteNumber(usage.cacheRead),
864
- cacheWrite: nonNegativeFiniteNumber(usage.cacheWrite),
865
- totalTokens: assistantUsageTokens(usage),
866
- cost: {
867
- input: usage.cost?.input ?? 0,
868
- output: usage.cost?.output ?? 0,
869
- cacheRead: usage.cost?.cacheRead ?? 0,
870
- cacheWrite: usage.cost?.cacheWrite ?? 0,
871
- total: usage.cost?.total ?? 0,
872
- },
873
- };
874
- }
1057
+ export type { AssistantMessageLike } from "./errors.js";
1058
+ export {
1059
+ findFinalAssistantMessage,
1060
+ formatError,
1061
+ isGoalContextOverflow,
1062
+ isRetryableGoalInterruption,
1063
+ isUsageLimitedGoalInterruption,
1064
+ truncateNotification,
1065
+ } from "./errors.js";