@narumitw/pi-goal 0.15.1 → 0.17.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 ADDED
@@ -0,0 +1,860 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import {
3
+ isContextOverflow,
4
+ type AssistantMessage as PiAssistantMessage,
5
+ type Usage,
6
+ } from "@earendil-works/pi-ai";
7
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
8
+ import {
9
+ assistantUsageTokens,
10
+ checkpointGoalActiveTime,
11
+ formatDuration,
12
+ formatTokenCount,
13
+ nonNegativeFiniteNumber,
14
+ updateGoalUsage,
15
+ } from "./accounting.js";
16
+ import {
17
+ type ActiveGoal,
18
+ clearLegacyPersistedGoal,
19
+ type PendingQueueAction,
20
+ serializeGoalState,
21
+ } from "./persistence.js";
22
+ import { buildContinuePrompt, type GoalStatus } from "./prompts.js";
23
+ import { DEFAULT_GOAL_SETTINGS, type GoalSettings } from "./settings.js";
24
+
25
+ export type AgentStopReason = "stop" | "length" | "toolUse" | "error" | "aborted";
26
+
27
+ export interface ContinuationTicket {
28
+ goalId: string;
29
+ iteration: number;
30
+ marker: string;
31
+ prompt: string;
32
+ }
33
+
34
+ export interface BudgetWrapUp {
35
+ goalId: string;
36
+ delivered: boolean;
37
+ }
38
+
39
+ export type GoalRecoveryKind = "provider_retry" | "compaction_retry";
40
+
41
+ export interface GoalRecovery {
42
+ goalId: string;
43
+ kind: GoalRecoveryKind;
44
+ }
45
+
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;
56
+ }
57
+
58
+ export interface StatusContext {
59
+ cwd: string;
60
+ ui: {
61
+ confirm: (title: string, message: string) => Promise<boolean>;
62
+ notify: (message: string, level?: "info" | "warning" | "error") => void;
63
+ setStatus: (key: string, value: string | undefined) => void;
64
+ };
65
+ isIdle?: () => boolean;
66
+ hasPendingMessages?: () => boolean;
67
+ abort?: () => void;
68
+ sessionManager?: unknown;
69
+ }
70
+
71
+ export interface GoalToolVisibilitySnapshot {
72
+ activeTools: string[];
73
+ goalToolsUnlocked: boolean;
74
+ goalToolsHiddenByPolicy: string[];
75
+ }
76
+
77
+ export const STATUS_KEY = "goal";
78
+ export const GOAL_STATE_ENTRY_TYPE = "goal-state";
79
+ export const GOAL_COMPLETE_TOOL = "goal_complete";
80
+ export const GOAL_BLOCKED_TOOL = "goal_blocked";
81
+ export const GOAL_TOOL_NAMES = [GOAL_COMPLETE_TOOL, GOAL_BLOCKED_TOOL] as const;
82
+
83
+ const MAX_CANCELLED_CONTINUATION_PROMPTS = 20;
84
+ const MAX_PENDING_GOAL_PROMPTS = 20;
85
+ const GOAL_PROMPT_MARKER_PREFIX = "pi-goal-prompt:";
86
+ const CONTINUATION_MARKER_PREFIX = "pi-goal-continuation:";
87
+ const BUDGET_WRAP_UP_MESSAGE_TYPE = "goal-budget-wrap-up";
88
+ const BUDGET_WRAP_UP_PROMPT =
89
+ "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.";
90
+ const CONTRADICTORY_COMPLETION_PATTERNS = [
91
+ /(?<!could\s)\bnot\s+(?:yet\s+)?(?:complete|completed|done|finished)\b/i,
92
+ /\bstill\s+(?:incomplete|failing|failing\s+tests?|fails?)\b/i,
93
+ /\btests?\s+(?:still\s+)?fail(?:ing)?\b/i,
94
+ ] 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
+ // One instance belongs to one extension factory. It owns all mutable session state
114
+ // and the cross-cutting invariants used by command and lifecycle orchestration.
115
+ export class GoalRuntime {
116
+ settings: GoalSettings = DEFAULT_GOAL_SETTINGS;
117
+ activeGoal?: ActiveGoal;
118
+ queuedGoals: ActiveGoal[] = [];
119
+ pendingQueueAction?: PendingQueueAction;
120
+ queueFrozen = false;
121
+ completionStatusTimer?: NodeJS.Timeout;
122
+ continuationIntent?: ContinuationTicket;
123
+ continuationDelivery?: ContinuationTicket;
124
+ goalRecovery?: GoalRecovery;
125
+ budgetWrapUp?: BudgetWrapUp;
126
+ /** `null` marks a run that must not be charged to the active goal. */
127
+ agentRunGoalId?: string | null;
128
+ staleGoalToolCallsBlocked = false;
129
+ /** Once true, goal tools stay in the active set for this runtime (prompt-cache stable). */
130
+ goalToolsUnlocked = false;
131
+ /** Exact lazy goal tools this runtime removed and may restore on a mode change. */
132
+ goalToolsHiddenByPolicy = new Set<string>();
133
+ pendingGoalPromptMarkers = new Map<string, string>();
134
+ cancelledContinuationMarkers = new Set<string>();
135
+
136
+ readonly pi: ExtensionAPI;
137
+
138
+ constructor(pi: ExtensionAPI) {
139
+ this.pi = pi;
140
+ }
141
+
142
+ canRecordGoalUsage() {
143
+ return (
144
+ this.agentRunGoalId !== null &&
145
+ !(
146
+ this.pendingQueueAction?.kind === "prioritize" &&
147
+ this.pendingQueueAction.displacedUsageFinalized === true
148
+ )
149
+ );
150
+ }
151
+
152
+ hasActiveBudgetWrapUp() {
153
+ return (
154
+ this.activeGoal?.status === "budget_limited" &&
155
+ this.budgetWrapUp?.goalId === this.activeGoal.id &&
156
+ this.budgetWrapUp.delivered
157
+ );
158
+ }
159
+
160
+ hasActiveGoalRecovery() {
161
+ return Boolean(this.activeGoal && this.goalRecovery?.goalId === this.activeGoal.id);
162
+ }
163
+
164
+ recordGoalUsage(
165
+ goal: ActiveGoal,
166
+ ctx: StatusContext,
167
+ checkpointActiveTime = goal.status === "active",
168
+ ) {
169
+ if (!this.canRecordGoalUsage()) return false;
170
+ updateGoalUsage(goal, ctx, checkpointActiveTime);
171
+ return true;
172
+ }
173
+
174
+ requestContinuation(goal: ActiveGoal) {
175
+ if (this.hasContinuationWorkForGoal(goal.id)) return false;
176
+ const marker = continuationMarker(goal);
177
+ this.continuationIntent = {
178
+ goalId: goal.id,
179
+ iteration: goal.iteration,
180
+ marker,
181
+ prompt: buildContinuePrompt(goal, marker),
182
+ };
183
+ return true;
184
+ }
185
+
186
+ dispatchContinuationIfSettled(ctx: StatusContext) {
187
+ const intent = this.continuationIntent;
188
+ if (!intent) return false;
189
+ if (this.activeGoal?.status === "active" && !this.goalToolsAvailable()) {
190
+ this.pauseGoalForUnavailableTools(ctx);
191
+ return false;
192
+ }
193
+ if (
194
+ !this.activeGoal ||
195
+ this.activeGoal.id !== intent.goalId ||
196
+ this.activeGoal.status !== "active"
197
+ ) {
198
+ this.continuationIntent = undefined;
199
+ return false;
200
+ }
201
+ if (ctx.isIdle?.() !== true || hasPendingMessages(ctx)) return false;
202
+
203
+ this.continuationIntent = undefined;
204
+ this.continuationDelivery = intent;
205
+ try {
206
+ this.pi.sendUserMessage(intent.prompt);
207
+ return true;
208
+ } catch (error) {
209
+ if (this.continuationDelivery?.marker === intent.marker) {
210
+ this.continuationDelivery = undefined;
211
+ }
212
+ if (this.activeGoal?.id === intent.goalId && this.activeGoal.status === "active") {
213
+ this.continuationIntent = intent;
214
+ }
215
+ ctx.ui.notify(`Goal prompt failed: ${formatError(error)}`, "error");
216
+ return false;
217
+ }
218
+ }
219
+
220
+ hasContinuationWorkForGoal(goalId: string) {
221
+ return (
222
+ this.continuationIntent?.goalId === goalId || this.continuationDelivery?.goalId === goalId
223
+ );
224
+ }
225
+
226
+ updateStatus(ctx: StatusContext, goal: ActiveGoal) {
227
+ this.clearCompletionStatusTimer();
228
+ ctx.ui.setStatus(STATUS_KEY, formatStatus(goal));
229
+ }
230
+
231
+ blockStaleGoalToolCalls() {
232
+ this.staleGoalToolCallsBlocked = true;
233
+ }
234
+
235
+ clearStaleGoalToolCallBlock() {
236
+ this.staleGoalToolCallsBlocked = false;
237
+ }
238
+
239
+ clearGoalRecovery() {
240
+ this.goalRecovery = undefined;
241
+ }
242
+
243
+ clearBudgetWrapUp() {
244
+ this.budgetWrapUp = undefined;
245
+ }
246
+
247
+ keepBudgetWrapUpMessage(message: unknown) {
248
+ if (!message || typeof message !== "object") return true;
249
+ const candidate = message as {
250
+ role?: unknown;
251
+ customType?: unknown;
252
+ details?: { goalId?: unknown };
253
+ };
254
+ if (candidate.role !== "custom" || candidate.customType !== BUDGET_WRAP_UP_MESSAGE_TYPE) {
255
+ return true;
256
+ }
257
+ return (
258
+ typeof candidate.details?.goalId === "string" &&
259
+ candidate.details.goalId === this.budgetWrapUp?.goalId &&
260
+ candidate.details.goalId === this.activeGoal?.id
261
+ );
262
+ }
263
+
264
+ queueBudgetWrapUp(ctx: StatusContext, goal: ActiveGoal) {
265
+ if (!this.budgetWrapUp || this.budgetWrapUp.goalId !== goal.id) {
266
+ this.budgetWrapUp = { goalId: goal.id, delivered: false };
267
+ }
268
+ if (this.budgetWrapUp.delivered) return true;
269
+ this.budgetWrapUp.delivered = true;
270
+ try {
271
+ this.pi.sendMessage(
272
+ {
273
+ customType: BUDGET_WRAP_UP_MESSAGE_TYPE,
274
+ content: BUDGET_WRAP_UP_PROMPT,
275
+ display: true,
276
+ details: { goalId: goal.id },
277
+ },
278
+ { deliverAs: "steer" },
279
+ );
280
+ return true;
281
+ } catch (error) {
282
+ this.budgetWrapUp.delivered = false;
283
+ ctx.ui.notify(`Goal budget wrap-up failed: ${formatError(error)}`, "error");
284
+ return false;
285
+ }
286
+ }
287
+
288
+ limitActiveGoalForBudget(ctx: StatusContext, sendWrapUp: boolean) {
289
+ const goal = this.activeGoal;
290
+ if (
291
+ goal?.status !== "active" ||
292
+ goal.tokenBudget === undefined ||
293
+ goal.tokensUsed < goal.tokenBudget
294
+ ) {
295
+ return false;
296
+ }
297
+
298
+ this.cancelContinuationWork();
299
+ this.clearGoalRecoveryForGoal(goal.id);
300
+ this.clearBudgetWrapUp();
301
+ this.activeGoal = transitionGoal(goal, "budget_limited");
302
+ this.persistGoal(this.activeGoal);
303
+ this.updateStatus(ctx, this.activeGoal);
304
+ ctx.ui.notify(`Goal token budget reached: ${formatBudget(this.activeGoal)}`, "warning");
305
+ if (sendWrapUp) this.queueBudgetWrapUp(ctx, this.activeGoal);
306
+ return true;
307
+ }
308
+
309
+ clearGoalRecoveryForGoal(goalId: string) {
310
+ if (this.goalRecovery?.goalId === goalId) this.goalRecovery = undefined;
311
+ }
312
+
313
+ isPiOwnedCompactionRetry(event: unknown, goalId: string) {
314
+ const compaction = event as { reason?: unknown; willRetry?: unknown };
315
+ if (compaction.willRetry === true) return true;
316
+ return (
317
+ this.goalRecovery?.goalId === goalId &&
318
+ this.goalRecovery.kind === "compaction_retry" &&
319
+ (compaction.reason === undefined || compaction.reason === "overflow")
320
+ );
321
+ }
322
+
323
+ clearContinuationTracking() {
324
+ this.continuationIntent = undefined;
325
+ this.continuationDelivery = undefined;
326
+ this.cancelledContinuationMarkers.clear();
327
+ }
328
+
329
+ clearPendingGoalPrompts() {
330
+ this.pendingGoalPromptMarkers.clear();
331
+ }
332
+
333
+ async sendOwnedGoalPrompt(ctx: StatusContext, goalId: string, prompt: string) {
334
+ const pending = this.rememberPendingGoalPrompt(goalId, prompt);
335
+ const sent = await sendPrompt(this.pi, ctx, pending.prompt);
336
+ if (!sent) this.pendingGoalPromptMarkers.delete(pending.marker);
337
+ return sent;
338
+ }
339
+
340
+ cancelContinuationWork() {
341
+ if (this.continuationDelivery) {
342
+ this.rememberCancelledContinuationMarker(this.continuationDelivery.marker);
343
+ }
344
+ this.continuationIntent = undefined;
345
+ this.continuationDelivery = undefined;
346
+ }
347
+
348
+ consumeCancelledContinuationPrompt(prompt: string) {
349
+ const marker = extractContinuationMarker(prompt);
350
+ return marker ? this.cancelledContinuationMarkers.delete(marker) : false;
351
+ }
352
+
353
+ markContinuationStarted(prompt: string) {
354
+ const marker = extractContinuationMarker(prompt);
355
+ if (!marker) {
356
+ // A user, retry, or another extension started newer work. Cancel both an
357
+ // unsent intent and a delivery that may have lost the non-atomic idle race;
358
+ // the newer work's agent_end will record a fresh intent.
359
+ this.cancelContinuationWork();
360
+ return undefined;
361
+ }
362
+ if (this.continuationDelivery?.marker === marker) this.continuationDelivery = undefined;
363
+ return marker.split(":", 1)[0];
364
+ }
365
+
366
+ persistGoal(goal: ActiveGoal) {
367
+ this.pi.appendEntry(
368
+ GOAL_STATE_ENTRY_TYPE,
369
+ serializeGoalState(goal, this.queuedGoals, this.pendingQueueAction),
370
+ );
371
+ }
372
+
373
+ clearPersistedGoal(cwd: string) {
374
+ this.pi.appendEntry(GOAL_STATE_ENTRY_TYPE, serializeGoalState(undefined, [], undefined));
375
+ clearLegacyPersistedGoal(cwd);
376
+ }
377
+
378
+ clearActiveGoal(ctx: StatusContext) {
379
+ this.cancelContinuationWork();
380
+ this.clearGoalRecovery();
381
+ this.clearBudgetWrapUp();
382
+ this.clearStaleGoalToolCallBlock();
383
+ this.activeGoal = undefined;
384
+ this.queuedGoals = [];
385
+ this.pendingQueueAction = undefined;
386
+ this.queueFrozen = false;
387
+ this.clearPersistedGoal(ctx.cwd);
388
+ ctx.ui.setStatus(STATUS_KEY, undefined);
389
+ // Do not clear goalToolsUnlocked: after first activation, keep tools visible
390
+ // for the rest of this extension runtime to avoid repeated goal-tool schema
391
+ // churn within the same runtime.
392
+ }
393
+
394
+ isGoalToolName(name: string) {
395
+ return (GOAL_TOOL_NAMES as readonly string[]).includes(name);
396
+ }
397
+
398
+ goalToolsAvailable() {
399
+ const active = new Set(this.pi.getActiveTools());
400
+ return GOAL_TOOL_NAMES.every((name) => active.has(name));
401
+ }
402
+
403
+ hideGoalToolsIfLocked() {
404
+ if (this.goalToolsUnlocked) return;
405
+ const active = this.pi.getActiveTools();
406
+ const hidden = active.filter((name) => this.isGoalToolName(name));
407
+ if (hidden.length === 0) return;
408
+ this.pi.setActiveTools(active.filter((name) => !this.isGoalToolName(name)));
409
+ for (const name of hidden) this.goalToolsHiddenByPolicy.add(name);
410
+ }
411
+
412
+ restoreGoalToolsHiddenByPolicy() {
413
+ const activeBeforeRestore = this.pi.getActiveTools();
414
+ const activeSet = new Set(activeBeforeRestore);
415
+ const missingOwnedTools = [...this.goalToolsHiddenByPolicy].filter(
416
+ (name) => !activeSet.has(name),
417
+ );
418
+ if (missingOwnedTools.length === 0) {
419
+ this.goalToolsHiddenByPolicy.clear();
420
+ return;
421
+ }
422
+ try {
423
+ this.pi.setActiveTools([...activeBeforeRestore, ...missingOwnedTools]);
424
+ const restored = new Set(this.pi.getActiveTools());
425
+ if (missingOwnedTools.some((name) => !restored.has(name))) {
426
+ throw new Error("the active tool policy rejected a previously hidden goal tool");
427
+ }
428
+ this.goalToolsHiddenByPolicy.clear();
429
+ } catch (error) {
430
+ this.pi.setActiveTools(activeBeforeRestore);
431
+ throw error;
432
+ }
433
+ }
434
+
435
+ assertGoalToolsAvailable() {
436
+ if (this.goalToolsAvailable()) return;
437
+ throw new Error(
438
+ "goal_complete and goal_blocked are unavailable; include them in the active tool allowlist or leave the restrictive tool mode first.",
439
+ );
440
+ }
441
+
442
+ ensureGoalToolsVisible() {
443
+ const active = this.pi.getActiveTools();
444
+ const activeSet = new Set(active);
445
+ const missing = GOAL_TOOL_NAMES.filter((name) => !activeSet.has(name));
446
+ if (missing.length > 0) this.pi.setActiveTools([...active, ...missing]);
447
+ this.assertGoalToolsAvailable();
448
+ }
449
+
450
+ prepareGoalToolsForActivation(ctx: StatusContext) {
451
+ if (this.settings.toolVisibility === "after-first-goal") {
452
+ if (!this.goalToolsAvailable() && ctx.isIdle?.() !== true) {
453
+ throw new Error("wait until Pi is idle before revealing the goal tools");
454
+ }
455
+ this.revealGoalTools();
456
+ return;
457
+ }
458
+ this.assertGoalToolsAvailable();
459
+ }
460
+
461
+ /** Mark lazy tools permanently desired for this runtime and make them active now. */
462
+ revealGoalTools() {
463
+ const activeBeforeReveal = this.pi.getActiveTools();
464
+ const wasUnlocked = this.goalToolsUnlocked;
465
+ try {
466
+ this.ensureGoalToolsVisible();
467
+ this.goalToolsUnlocked = true;
468
+ this.goalToolsHiddenByPolicy.clear();
469
+ } catch (error) {
470
+ this.pi.setActiveTools(activeBeforeReveal);
471
+ this.goalToolsUnlocked = wasUnlocked;
472
+ throw error;
473
+ }
474
+ }
475
+
476
+ snapshotGoalToolVisibility(): GoalToolVisibilitySnapshot {
477
+ return {
478
+ activeTools: this.pi.getActiveTools(),
479
+ goalToolsUnlocked: this.goalToolsUnlocked,
480
+ goalToolsHiddenByPolicy: [...this.goalToolsHiddenByPolicy],
481
+ };
482
+ }
483
+
484
+ restoreGoalToolVisibility(snapshot: GoalToolVisibilitySnapshot) {
485
+ this.pi.setActiveTools(snapshot.activeTools);
486
+ this.goalToolsUnlocked = snapshot.goalToolsUnlocked;
487
+ this.goalToolsHiddenByPolicy.clear();
488
+ for (const name of snapshot.goalToolsHiddenByPolicy) {
489
+ this.goalToolsHiddenByPolicy.add(name);
490
+ }
491
+ }
492
+
493
+ pauseGoalForUnavailableTools(ctx: StatusContext, abortTurn = true, recordUsage = true) {
494
+ const goal = this.activeGoal;
495
+ if (goal?.status !== "active") return false;
496
+ if (recordUsage) this.recordGoalUsage(goal, ctx);
497
+ this.cancelContinuationWork();
498
+ this.clearGoalRecoveryForGoal(goal.id);
499
+ this.clearBudgetWrapUp();
500
+ if (abortTurn) {
501
+ this.blockStaleGoalToolCalls();
502
+ abortCurrentTurn(ctx);
503
+ } else {
504
+ this.clearStaleGoalToolCallBlock();
505
+ }
506
+ this.activeGoal = transitionGoal(goal, "paused");
507
+ this.persistGoal(this.activeGoal);
508
+ this.updateStatus(ctx, this.activeGoal);
509
+ ctx.ui.notify(
510
+ "Goal tools are unavailable, so the active goal was paused. Restore the tools and run /goal resume.",
511
+ "warning",
512
+ );
513
+ return true;
514
+ }
515
+
516
+ showCompletionStatus(ctx: StatusContext) {
517
+ this.clearCompletionStatusTimer();
518
+ ctx.ui.setStatus(STATUS_KEY, "complete");
519
+ this.completionStatusTimer = setTimeout(() => {
520
+ this.completionStatusTimer = undefined;
521
+ try {
522
+ ctx.ui.setStatus(STATUS_KEY, undefined);
523
+ } catch {
524
+ // The completion status is best-effort; the captured ctx may be stale after
525
+ // session replacement or reload before this timer fires.
526
+ }
527
+ }, 8_000);
528
+ }
529
+
530
+ clearCompletionStatusTimer() {
531
+ if (!this.completionStatusTimer) return;
532
+ clearTimeout(this.completionStatusTimer);
533
+ this.completionStatusTimer = undefined;
534
+ }
535
+
536
+ private rememberPendingGoalPrompt(goalId: string, prompt: string) {
537
+ const marker = randomUUID();
538
+ this.pendingGoalPromptMarkers.set(marker, goalId);
539
+ if (this.pendingGoalPromptMarkers.size > MAX_PENDING_GOAL_PROMPTS) {
540
+ const oldest = this.pendingGoalPromptMarkers.keys().next().value;
541
+ if (oldest) this.pendingGoalPromptMarkers.delete(oldest);
542
+ }
543
+ return { marker, prompt: `${prompt}\n\n<!-- ${GOAL_PROMPT_MARKER_PREFIX}${marker} -->` };
544
+ }
545
+
546
+ private consumePendingGoalPrompt(prompt: string) {
547
+ const marker = extractGoalPromptMarker(prompt);
548
+ if (!marker) return undefined;
549
+ const goalId = this.pendingGoalPromptMarkers.get(marker);
550
+ this.pendingGoalPromptMarkers.delete(marker);
551
+ return goalId;
552
+ }
553
+
554
+ consumeOwnedGoalPrompt(prompt: string) {
555
+ return this.consumePendingGoalPrompt(prompt);
556
+ }
557
+
558
+ private rememberCancelledContinuationMarker(marker: string) {
559
+ this.cancelledContinuationMarkers.add(marker);
560
+ if (this.cancelledContinuationMarkers.size <= MAX_CANCELLED_CONTINUATION_PROMPTS) return;
561
+ const oldest = this.cancelledContinuationMarkers.values().next().value;
562
+ if (oldest) this.cancelledContinuationMarkers.delete(oldest);
563
+ }
564
+ }
565
+
566
+ export function createGoal(
567
+ text: string,
568
+ tokenBudget: number | undefined,
569
+ baselineTokens: number,
570
+ ): ActiveGoal {
571
+ const now = Date.now();
572
+ return {
573
+ id: randomUUID(),
574
+ text,
575
+ status: "active",
576
+ startedAt: now,
577
+ updatedAt: now,
578
+ iteration: 0,
579
+ tokenBudget,
580
+ tokensUsed: 0,
581
+ timeUsedSeconds: 0,
582
+ baselineTokens,
583
+ activeStartedAt: now,
584
+ };
585
+ }
586
+
587
+ export function transitionGoal(goal: ActiveGoal, requestedStatus: GoalStatus): ActiveGoal {
588
+ const now = Date.now();
589
+ const status =
590
+ requestedStatus === "active" &&
591
+ goal.tokenBudget !== undefined &&
592
+ goal.tokensUsed >= goal.tokenBudget
593
+ ? "budget_limited"
594
+ : requestedStatus;
595
+ const next = { ...goal, status, updatedAt: now };
596
+ checkpointGoalActiveTime(next, now, status === "active");
597
+ return next;
598
+ }
599
+
600
+ export function nextGoalInstance(goal: ActiveGoal): ActiveGoal {
601
+ return { ...goal, id: randomUUID(), updatedAt: Date.now() };
602
+ }
603
+
604
+ export function editedGoalStatus(status: GoalStatus): GoalStatus {
605
+ if (status === "paused" || status === "blocked" || status === "usage_limited") return status;
606
+ return "active";
607
+ }
608
+
609
+ export function incrementGoal(goal: ActiveGoal): ActiveGoal {
610
+ return { ...goal, iteration: goal.iteration + 1, updatedAt: Date.now() };
611
+ }
612
+
613
+ export function formatStatus(goal: ActiveGoal | undefined) {
614
+ if (!goal) return undefined;
615
+ if (goal.status === "complete") return "complete";
616
+ if (goal.status === "queued") return "queued";
617
+ if (goal.status === "paused") return "paused";
618
+ if (goal.status === "blocked") return "blocked";
619
+ if (goal.status === "usage_limited") return "usage";
620
+ if (goal.status === "budget_limited") return `budget ${formatBudget(goal)}`;
621
+ if (goal.tokenBudget !== undefined) return `active ${formatBudget(goal)}`;
622
+ return `active ${formatDuration(goal.timeUsedSeconds)}`;
623
+ }
624
+
625
+ export function formatBudget(goal: ActiveGoal) {
626
+ return `${formatTokenCount(goal.tokensUsed)}/${formatTokenCount(goal.tokenBudget ?? 0)}`;
627
+ }
628
+
629
+ export function goalSummary(
630
+ goal: ActiveGoal,
631
+ queuedGoals: readonly ActiveGoal[] = [],
632
+ experimentalGoals = false,
633
+ queueFrozen = false,
634
+ ) {
635
+ const summary = [
636
+ `Goal: ${goal.text}`,
637
+ `Status: ${queueFrozen ? "queue off" : goal.status}`,
638
+ `Iteration: ${goal.iteration}`,
639
+ `Active elapsed: ${formatDuration(goal.timeUsedSeconds)}`,
640
+ `Tokens: ${goal.tokenBudget === undefined ? formatTokenCount(goal.tokensUsed) : formatBudget(goal)}`,
641
+ ];
642
+ if (experimentalGoals || queuedGoals.length > 0 || queueFrozen) {
643
+ summary.push(
644
+ `Goals (${queuedGoals.length + 1}):`,
645
+ ...[goal, ...queuedGoals].map(
646
+ (queuedGoal, index) => `${index + 1}. [${queuedGoal.status}] ${queuedGoal.text}`,
647
+ ),
648
+ );
649
+ }
650
+ if (queueFrozen) {
651
+ summary.push(
652
+ "Queue is frozen. Re-enable experimental.goals and run /reload, or use /goal clear.",
653
+ "Commands: /goal, /goal clear",
654
+ );
655
+ } else {
656
+ summary.push(`Commands: ${goalCommandHint(goal.status, experimentalGoals)}`);
657
+ }
658
+ return summary.join("\n");
659
+ }
660
+
661
+ export function hasPendingMessages(ctx: StatusContext) {
662
+ return ctx.hasPendingMessages?.() ?? false;
663
+ }
664
+
665
+ export function abortCurrentTurn(ctx: StatusContext) {
666
+ try {
667
+ ctx.abort?.();
668
+ } catch {
669
+ // Best effort: stale goal guards still prevent follow-on tool calls.
670
+ }
671
+ }
672
+
673
+ export function blocksStaleGoalToolCalls(status: GoalStatus) {
674
+ return status === "paused" || status === "blocked" || status === "usage_limited";
675
+ }
676
+
677
+ export function isResumableGoalStatus(status: GoalStatus) {
678
+ return blocksStaleGoalToolCalls(status) || status === "budget_limited";
679
+ }
680
+
681
+ export function stoppedStatusLabel(status: GoalStatus) {
682
+ if (status === "usage_limited") return "usage-limited";
683
+ if (status === "budget_limited") return "budget-limited";
684
+ return status;
685
+ }
686
+
687
+ export function isContradictoryCompletionSummary(summary: string) {
688
+ return CONTRADICTORY_COMPLETION_PATTERNS.some((pattern) => pattern.test(summary));
689
+ }
690
+
691
+ export function goalIdRejectionReason(goal: ActiveGoal, requestedGoalId: string) {
692
+ if (!requestedGoalId) return "missing goal_id";
693
+ if (requestedGoalId !== goal.id) return "goal_id does not match the active goal";
694
+ return undefined;
695
+ }
696
+
697
+ export function isUsageLimitedGoalInterruption(assistant: AssistantMessageLike) {
698
+ const errorMessage = assistant.errorMessage;
699
+ return (
700
+ assistant.stopReason === "error" &&
701
+ typeof errorMessage === "string" &&
702
+ USAGE_LIMIT_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(errorMessage))
703
+ );
704
+ }
705
+
706
+ export function isRetryableGoalInterruption(assistant: AssistantMessageLike) {
707
+ if (assistant.stopReason !== "error") return false;
708
+ if (!assistant.errorMessage) return false;
709
+ if (
710
+ isUsageLimitedGoalInterruption(assistant) ||
711
+ NON_RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage)
712
+ ) {
713
+ return false;
714
+ }
715
+ return (
716
+ isGoalContextOverflow(assistant) ||
717
+ RETRYABLE_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(assistant.errorMessage ?? ""))
718
+ );
719
+ }
720
+
721
+ export function isGoalContextOverflow(assistant: AssistantMessageLike) {
722
+ return isContextOverflow(toPiAssistantMessage(assistant));
723
+ }
724
+
725
+ export function findFinalAssistantMessage(messages: unknown[]): AssistantMessageLike | undefined {
726
+ for (let i = messages.length - 1; i >= 0; i--) {
727
+ const message = messages[i];
728
+ if (!message || typeof message !== "object") continue;
729
+ const candidate = message as Record<string, unknown>;
730
+ if (candidate.role !== "assistant") continue;
731
+ const assistant: AssistantMessageLike = {
732
+ role: "assistant",
733
+ stopReason: isAgentStopReason(candidate.stopReason) ? candidate.stopReason : undefined,
734
+ errorMessage: typeof candidate.errorMessage === "string" ? candidate.errorMessage : undefined,
735
+ };
736
+ if (Array.isArray(candidate.content)) {
737
+ assistant.content = candidate.content as PiAssistantMessage["content"];
738
+ }
739
+ if (typeof candidate.api === "string") assistant.api = candidate.api;
740
+ if (typeof candidate.provider === "string") assistant.provider = candidate.provider;
741
+ if (typeof candidate.model === "string") assistant.model = candidate.model;
742
+ if (typeof candidate.timestamp === "number") assistant.timestamp = candidate.timestamp;
743
+ const usage = normalizeUsage(candidate.usage);
744
+ if (usage) assistant.usage = usage;
745
+ return assistant;
746
+ }
747
+ return undefined;
748
+ }
749
+
750
+ export function formatError(error: unknown) {
751
+ return truncateNotification(error instanceof Error ? error.message : String(error));
752
+ }
753
+
754
+ export function truncateNotification(value: string) {
755
+ return value.length > 160 ? `${value.slice(0, 157)}...` : value;
756
+ }
757
+
758
+ async function sendPrompt(pi: ExtensionAPI, ctx: StatusContext, prompt: string) {
759
+ try {
760
+ const sent = ctx.isIdle?.()
761
+ ? (pi.sendUserMessage(prompt) as void | Promise<void>)
762
+ : (pi.sendUserMessage(prompt, { deliverAs: "followUp" }) as void | Promise<void>);
763
+ await sent;
764
+ return true;
765
+ } catch (error) {
766
+ ctx.ui.notify(`Goal prompt failed: ${formatError(error)}`, "error");
767
+ return false;
768
+ }
769
+ }
770
+
771
+ function goalCommandHint(status: GoalStatus, experimentalGoals = false) {
772
+ const queueCommands = experimentalGoals
773
+ ? ", /goal add <objective>, /goal prioritize <objective>, /goal drop-last, /goal skip"
774
+ : "";
775
+ if (status === "active") {
776
+ return `/goal edit <objective>, /goal pause, /goal clear${queueCommands}`;
777
+ }
778
+ if (isResumableGoalStatus(status)) {
779
+ return `/goal edit <objective>, /goal resume, /goal clear${queueCommands}`;
780
+ }
781
+ return `/goal edit <objective>, /goal clear${queueCommands}`;
782
+ }
783
+
784
+ function toPiAssistantMessage(assistant: AssistantMessageLike): PiAssistantMessage {
785
+ return {
786
+ role: "assistant",
787
+ content: assistant.content ?? [],
788
+ api: assistant.api ?? "openai-responses",
789
+ provider: assistant.provider ?? "unknown",
790
+ model: assistant.model ?? "unknown",
791
+ usage: assistant.usage ?? zeroUsage(),
792
+ stopReason: assistant.stopReason ?? "error",
793
+ errorMessage: assistant.errorMessage,
794
+ timestamp: assistant.timestamp ?? Date.now(),
795
+ };
796
+ }
797
+
798
+ function zeroUsage(): Usage {
799
+ return {
800
+ input: 0,
801
+ output: 0,
802
+ cacheRead: 0,
803
+ cacheWrite: 0,
804
+ totalTokens: 0,
805
+ cost: {
806
+ input: 0,
807
+ output: 0,
808
+ cacheRead: 0,
809
+ cacheWrite: 0,
810
+ total: 0,
811
+ },
812
+ };
813
+ }
814
+
815
+ function continuationMarker(goal: ActiveGoal) {
816
+ return `${goal.id}:${goal.iteration}:${randomUUID()}`;
817
+ }
818
+
819
+ function escapeRegExpText(value: string) {
820
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
821
+ }
822
+
823
+ const GOAL_PROMPT_MARKER_PATTERN = new RegExp(
824
+ `<!--\\s*${escapeRegExpText(GOAL_PROMPT_MARKER_PREFIX)}([^\\s>]+)\\s*-->`,
825
+ );
826
+ const CONTINUATION_MARKER_PATTERN = new RegExp(
827
+ `<!--\\s*${escapeRegExpText(CONTINUATION_MARKER_PREFIX)}([^\\s>]+)\\s*-->`,
828
+ );
829
+
830
+ function extractGoalPromptMarker(prompt: string) {
831
+ return GOAL_PROMPT_MARKER_PATTERN.exec(prompt)?.[1];
832
+ }
833
+
834
+ function extractContinuationMarker(prompt: string) {
835
+ return CONTINUATION_MARKER_PATTERN.exec(prompt)?.[1];
836
+ }
837
+
838
+ function isAgentStopReason(value: unknown): value is AgentStopReason {
839
+ return ["stop", "length", "toolUse", "error", "aborted"].includes(String(value));
840
+ }
841
+
842
+ function normalizeUsage(value: unknown): Usage | undefined {
843
+ if (!value || typeof value !== "object") return undefined;
844
+ const usage = value as Partial<Usage>;
845
+ if (typeof usage.input !== "number" || typeof usage.output !== "number") return undefined;
846
+ return {
847
+ input: nonNegativeFiniteNumber(usage.input),
848
+ output: nonNegativeFiniteNumber(usage.output),
849
+ cacheRead: nonNegativeFiniteNumber(usage.cacheRead),
850
+ cacheWrite: nonNegativeFiniteNumber(usage.cacheWrite),
851
+ totalTokens: assistantUsageTokens(usage),
852
+ cost: {
853
+ input: usage.cost?.input ?? 0,
854
+ output: usage.cost?.output ?? 0,
855
+ cacheRead: usage.cost?.cacheRead ?? 0,
856
+ cacheWrite: usage.cost?.cacheWrite ?? 0,
857
+ total: usage.cost?.total ?? 0,
858
+ },
859
+ };
860
+ }