@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/README.md +29 -11
- package/package.json +3 -3
- package/src/commands.ts +3 -1
- package/src/errors.ts +147 -0
- package/src/goal.ts +180 -43
- package/src/markers.ts +25 -0
- package/src/persistence.ts +22 -0
- package/src/queue.ts +2 -0
- package/src/runtime.ts +300 -185
- package/src/safety.ts +62 -0
- package/src/settings.ts +41 -0
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
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
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 {
|
|
@@ -122,10 +119,20 @@ interface GoalTerminalDetails {
|
|
|
122
119
|
reason?: string;
|
|
123
120
|
}
|
|
124
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
|
+
|
|
125
133
|
const MAX_CANCELLED_CONTINUATION_PROMPTS = 20;
|
|
126
134
|
const MAX_PENDING_GOAL_PROMPTS = 20;
|
|
127
|
-
const
|
|
128
|
-
const CONTINUATION_MARKER_PREFIX = "pi-goal-continuation:";
|
|
135
|
+
const MAX_PENDING_NON_GOAL_INPUTS = 20;
|
|
129
136
|
const BUDGET_WRAP_UP_MESSAGE_TYPE = "goal-budget-wrap-up";
|
|
130
137
|
const BUDGET_WRAP_UP_PROMPT =
|
|
131
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.";
|
|
@@ -134,24 +141,6 @@ const CONTRADICTORY_COMPLETION_PATTERNS = [
|
|
|
134
141
|
/\bstill\s+(?:incomplete|failing|failing\s+tests?|fails?)\b/i,
|
|
135
142
|
/\btests?\s+(?:still\s+)?fail(?:ing)?\b/i,
|
|
136
143
|
] as const;
|
|
137
|
-
const USAGE_LIMIT_GOAL_ERROR_PATTERNS = [
|
|
138
|
-
/usage[_\s-]*(?:limit|cap)|chatgpt.{0,32}usage/i,
|
|
139
|
-
/quota.{0,32}(?:reached|exceeded|exhausted|depleted)|(?:reached|exceeded|exhausted|depleted).{0,32}quota/i,
|
|
140
|
-
/insufficient[_\s-]*(?:quota|credits?)|out of credits|out of budget|available balance|payment required/i,
|
|
141
|
-
/(?:credit|balance).{0,32}(?:low|exhausted|depleted)|billing/i,
|
|
142
|
-
] as const;
|
|
143
|
-
const NON_RETRYABLE_GOAL_ERROR_RE =
|
|
144
|
-
/multi-auth rotation failed|credentials tried|unauthori[sz]ed|invalid api key/i;
|
|
145
|
-
// Pi 0.79 does not export its assistant-error retry classifier. Keep this
|
|
146
|
-
// compatibility mirror aligned with Pi's public retry utility in newer versions.
|
|
147
|
-
const RETRYABLE_GOAL_ERROR_PATTERNS = [
|
|
148
|
-
/overloaded|rate.?limit|too many requests|\b(?:429|500|502|503|504)\b|service.?unavailable|server.?error|internal.?error/i,
|
|
149
|
-
/provider.?returned.?error|you can retry your request|try your request again|please retry your request/i,
|
|
150
|
-
/network.?error|connection.?(?:error|refused|lost)|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up/i,
|
|
151
|
-
/timed? out|timeout|terminated|websocket.?(?:closed|error)|ended without|stream ended before message_stop|http2 request did not get a response|retry delay/i,
|
|
152
|
-
/context[_\s-]*length[_\s-]*exceeded|input exceeds the context window/i,
|
|
153
|
-
] as const;
|
|
154
|
-
|
|
155
144
|
// One instance belongs to one extension factory. It owns all mutable session state
|
|
156
145
|
// and the cross-cutting invariants used by command and lifecycle orchestration.
|
|
157
146
|
export class GoalRuntime {
|
|
@@ -169,13 +158,17 @@ export class GoalRuntime {
|
|
|
169
158
|
budgetWrapUp?: BudgetWrapUp;
|
|
170
159
|
/** `null` marks a run that must not be charged to the active goal. */
|
|
171
160
|
agentRunGoalId?: string | null;
|
|
161
|
+
agentRunOrigin?: GoalRunOrigin;
|
|
162
|
+
agentRunToolAttempted = false;
|
|
163
|
+
guardAbortGoalId?: string;
|
|
172
164
|
staleGoalToolCallsBlocked = false;
|
|
173
165
|
/** Once true, goal tools stay in the active set for this runtime (prompt-cache stable). */
|
|
174
166
|
goalToolsUnlocked = false;
|
|
175
167
|
/** Exact lazy goal tools this runtime removed and may restore on a mode change. */
|
|
176
168
|
goalToolsHiddenByPolicy = new Set<string>();
|
|
177
|
-
pendingGoalPromptMarkers = new Map<string,
|
|
169
|
+
pendingGoalPromptMarkers = new Map<string, PendingGoalPrompt>();
|
|
178
170
|
cancelledContinuationMarkers = new Set<string>();
|
|
171
|
+
pendingNonGoalInputs: PendingNonGoalInput[] = [];
|
|
179
172
|
|
|
180
173
|
readonly pi: ExtensionAPI;
|
|
181
174
|
|
|
@@ -183,9 +176,12 @@ export class GoalRuntime {
|
|
|
183
176
|
this.pi = pi;
|
|
184
177
|
}
|
|
185
178
|
|
|
186
|
-
canRecordGoalUsage() {
|
|
179
|
+
canRecordGoalUsage(goalId?: string) {
|
|
187
180
|
return (
|
|
188
181
|
this.agentRunGoalId !== null &&
|
|
182
|
+
(goalId === undefined ||
|
|
183
|
+
this.agentRunGoalId === undefined ||
|
|
184
|
+
this.agentRunGoalId === goalId) &&
|
|
189
185
|
!(
|
|
190
186
|
this.pendingQueueAction?.kind === "prioritize" &&
|
|
191
187
|
this.pendingQueueAction.displacedUsageFinalized === true
|
|
@@ -205,12 +201,53 @@ export class GoalRuntime {
|
|
|
205
201
|
return Boolean(this.activeGoal && this.goalRecovery?.goalId === this.activeGoal.id);
|
|
206
202
|
}
|
|
207
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
|
+
|
|
208
245
|
recordGoalUsage(
|
|
209
246
|
goal: ActiveGoal,
|
|
210
247
|
ctx: StatusContext,
|
|
211
248
|
checkpointActiveTime = goal.status === "active",
|
|
212
249
|
) {
|
|
213
|
-
if (!this.canRecordGoalUsage()) return false;
|
|
250
|
+
if (!this.canRecordGoalUsage(goal.id)) return false;
|
|
214
251
|
updateGoalUsage(goal, ctx, checkpointActiveTime);
|
|
215
252
|
return true;
|
|
216
253
|
}
|
|
@@ -242,6 +279,9 @@ export class GoalRuntime {
|
|
|
242
279
|
this.continuationIntent = undefined;
|
|
243
280
|
return false;
|
|
244
281
|
}
|
|
282
|
+
if (this.enforceAutomaticTurnLimit(ctx, false) || this.enforceNoProgressLimit(ctx)) {
|
|
283
|
+
return false;
|
|
284
|
+
}
|
|
245
285
|
if (ctx.isIdle?.() !== true || hasPendingMessages(ctx)) return false;
|
|
246
286
|
|
|
247
287
|
this.continuationIntent = undefined;
|
|
@@ -366,6 +406,123 @@ export class GoalRuntime {
|
|
|
366
406
|
return true;
|
|
367
407
|
}
|
|
368
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
|
+
|
|
369
526
|
clearGoalRecoveryForGoal(goalId: string) {
|
|
370
527
|
if (this.goalRecovery?.goalId === goalId) this.goalRecovery = undefined;
|
|
371
528
|
}
|
|
@@ -388,10 +545,16 @@ export class GoalRuntime {
|
|
|
388
545
|
|
|
389
546
|
clearPendingGoalPrompts() {
|
|
390
547
|
this.pendingGoalPromptMarkers.clear();
|
|
548
|
+
this.pendingNonGoalInputs = [];
|
|
391
549
|
}
|
|
392
550
|
|
|
393
|
-
async sendOwnedGoalPrompt(
|
|
394
|
-
|
|
551
|
+
async sendOwnedGoalPrompt(
|
|
552
|
+
ctx: StatusContext,
|
|
553
|
+
goalId: string,
|
|
554
|
+
prompt: string,
|
|
555
|
+
resetSafetyEpoch = true,
|
|
556
|
+
) {
|
|
557
|
+
const pending = this.rememberPendingGoalPrompt(goalId, prompt, resetSafetyEpoch);
|
|
395
558
|
const sent = await sendPrompt(this.pi, ctx, pending.prompt);
|
|
396
559
|
if (!sent) this.pendingGoalPromptMarkers.delete(pending.marker);
|
|
397
560
|
return sent;
|
|
@@ -410,15 +573,20 @@ export class GoalRuntime {
|
|
|
410
573
|
return marker ? this.cancelledContinuationMarkers.delete(marker) : false;
|
|
411
574
|
}
|
|
412
575
|
|
|
576
|
+
hasPendingOwnedGoalPrompt(prompt: string) {
|
|
577
|
+
const marker = extractGoalPromptMarker(prompt);
|
|
578
|
+
return marker ? this.pendingGoalPromptMarkers.has(marker) : false;
|
|
579
|
+
}
|
|
580
|
+
|
|
413
581
|
consumeStaleOwnedGoalPrompt(prompt: string) {
|
|
414
582
|
const marker = extractGoalPromptMarker(prompt);
|
|
415
583
|
if (!marker) return false;
|
|
416
|
-
const
|
|
417
|
-
if (!
|
|
584
|
+
const pending = this.pendingGoalPromptMarkers.get(marker);
|
|
585
|
+
if (!pending) return false;
|
|
418
586
|
if (
|
|
419
587
|
!this.queueFrozen &&
|
|
420
588
|
!this.pendingQueueAction &&
|
|
421
|
-
this.activeGoal?.id === goalId &&
|
|
589
|
+
this.activeGoal?.id === pending.goalId &&
|
|
422
590
|
this.activeGoal.status === "active"
|
|
423
591
|
) {
|
|
424
592
|
return false;
|
|
@@ -427,6 +595,52 @@ export class GoalRuntime {
|
|
|
427
595
|
return true;
|
|
428
596
|
}
|
|
429
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
|
+
|
|
430
644
|
markContinuationStarted(prompt: string) {
|
|
431
645
|
const marker = extractContinuationMarker(prompt);
|
|
432
646
|
if (!marker) {
|
|
@@ -626,22 +840,26 @@ export class GoalRuntime {
|
|
|
626
840
|
this.completionStatusTimer = undefined;
|
|
627
841
|
}
|
|
628
842
|
|
|
629
|
-
private rememberPendingGoalPrompt(
|
|
843
|
+
private rememberPendingGoalPrompt(
|
|
844
|
+
goalId: string,
|
|
845
|
+
prompt: string,
|
|
846
|
+
resetSafetyEpoch: boolean,
|
|
847
|
+
) {
|
|
630
848
|
const marker = randomUUID();
|
|
631
|
-
this.pendingGoalPromptMarkers.set(marker, goalId);
|
|
849
|
+
this.pendingGoalPromptMarkers.set(marker, { goalId, resetSafetyEpoch });
|
|
632
850
|
if (this.pendingGoalPromptMarkers.size > MAX_PENDING_GOAL_PROMPTS) {
|
|
633
851
|
const oldest = this.pendingGoalPromptMarkers.keys().next().value;
|
|
634
852
|
if (oldest) this.pendingGoalPromptMarkers.delete(oldest);
|
|
635
853
|
}
|
|
636
|
-
return { marker, prompt:
|
|
854
|
+
return { marker, prompt: appendGoalPromptMarker(prompt, marker) };
|
|
637
855
|
}
|
|
638
856
|
|
|
639
857
|
private consumePendingGoalPrompt(prompt: string) {
|
|
640
858
|
const marker = extractGoalPromptMarker(prompt);
|
|
641
859
|
if (!marker) return undefined;
|
|
642
|
-
const
|
|
860
|
+
const pending = this.pendingGoalPromptMarkers.get(marker);
|
|
643
861
|
this.pendingGoalPromptMarkers.delete(marker);
|
|
644
|
-
return
|
|
862
|
+
return pending;
|
|
645
863
|
}
|
|
646
864
|
|
|
647
865
|
consumeOwnedGoalPrompt(prompt: string) {
|
|
@@ -674,6 +892,8 @@ export function createGoal(
|
|
|
674
892
|
timeUsedSeconds: 0,
|
|
675
893
|
baselineTokens,
|
|
676
894
|
activeStartedAt: now,
|
|
895
|
+
automaticModelTurns: 0,
|
|
896
|
+
toolFreeRepeatCount: 0,
|
|
677
897
|
};
|
|
678
898
|
}
|
|
679
899
|
|
|
@@ -694,6 +914,16 @@ export function nextGoalInstance(goal: ActiveGoal): ActiveGoal {
|
|
|
694
914
|
return { ...goal, id: randomUUID(), updatedAt: Date.now() };
|
|
695
915
|
}
|
|
696
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
|
+
|
|
697
927
|
export function editedGoalStatus(status: GoalStatus): GoalStatus {
|
|
698
928
|
if (status === "paused" || status === "blocked" || status === "usage_limited") return status;
|
|
699
929
|
return "active";
|
|
@@ -729,9 +959,15 @@ export function goalSummary(
|
|
|
729
959
|
`Goal: ${goal.text}`,
|
|
730
960
|
`Status: ${queueFrozen ? "queue off" : goal.status}`,
|
|
731
961
|
`Iteration: ${goal.iteration}`,
|
|
962
|
+
`Automatic model responses: ${goal.automaticModelTurns}`,
|
|
732
963
|
`Active elapsed: ${formatDuration(goal.timeUsedSeconds)}`,
|
|
733
964
|
`Tokens: ${goal.tokenBudget === undefined ? formatTokenCount(goal.tokensUsed) : formatBudget(goal)}`,
|
|
734
965
|
];
|
|
966
|
+
if (goal.safetyPauseCause) {
|
|
967
|
+
summary.push(
|
|
968
|
+
`Safety pause: ${goal.safetyPauseCause === "continuation_limit" ? "automatic response limit" : "no progress"}`,
|
|
969
|
+
);
|
|
970
|
+
}
|
|
735
971
|
if (experimentalGoals || queuedGoals.length > 0 || queueFrozen) {
|
|
736
972
|
summary.push(
|
|
737
973
|
`Goals (${queuedGoals.length + 1}):`,
|
|
@@ -787,65 +1023,8 @@ export function goalIdRejectionReason(goal: ActiveGoal, requestedGoalId: string)
|
|
|
787
1023
|
return undefined;
|
|
788
1024
|
}
|
|
789
1025
|
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
return (
|
|
793
|
-
assistant.stopReason === "error" &&
|
|
794
|
-
typeof errorMessage === "string" &&
|
|
795
|
-
USAGE_LIMIT_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(errorMessage))
|
|
796
|
-
);
|
|
797
|
-
}
|
|
798
|
-
|
|
799
|
-
export function isRetryableGoalInterruption(assistant: AssistantMessageLike) {
|
|
800
|
-
if (assistant.stopReason !== "error") return false;
|
|
801
|
-
if (!assistant.errorMessage) return false;
|
|
802
|
-
if (
|
|
803
|
-
isUsageLimitedGoalInterruption(assistant) ||
|
|
804
|
-
NON_RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage)
|
|
805
|
-
) {
|
|
806
|
-
return false;
|
|
807
|
-
}
|
|
808
|
-
return (
|
|
809
|
-
isGoalContextOverflow(assistant) ||
|
|
810
|
-
RETRYABLE_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(assistant.errorMessage ?? ""))
|
|
811
|
-
);
|
|
812
|
-
}
|
|
813
|
-
|
|
814
|
-
export function isGoalContextOverflow(assistant: AssistantMessageLike) {
|
|
815
|
-
return isContextOverflow(toPiAssistantMessage(assistant));
|
|
816
|
-
}
|
|
817
|
-
|
|
818
|
-
export function findFinalAssistantMessage(messages: unknown[]): AssistantMessageLike | undefined {
|
|
819
|
-
for (let i = messages.length - 1; i >= 0; i--) {
|
|
820
|
-
const message = messages[i];
|
|
821
|
-
if (!message || typeof message !== "object") continue;
|
|
822
|
-
const candidate = message as Record<string, unknown>;
|
|
823
|
-
if (candidate.role !== "assistant") continue;
|
|
824
|
-
const assistant: AssistantMessageLike = {
|
|
825
|
-
role: "assistant",
|
|
826
|
-
stopReason: isAgentStopReason(candidate.stopReason) ? candidate.stopReason : undefined,
|
|
827
|
-
errorMessage: typeof candidate.errorMessage === "string" ? candidate.errorMessage : undefined,
|
|
828
|
-
};
|
|
829
|
-
if (Array.isArray(candidate.content)) {
|
|
830
|
-
assistant.content = candidate.content as PiAssistantMessage["content"];
|
|
831
|
-
}
|
|
832
|
-
if (typeof candidate.api === "string") assistant.api = candidate.api;
|
|
833
|
-
if (typeof candidate.provider === "string") assistant.provider = candidate.provider;
|
|
834
|
-
if (typeof candidate.model === "string") assistant.model = candidate.model;
|
|
835
|
-
if (typeof candidate.timestamp === "number") assistant.timestamp = candidate.timestamp;
|
|
836
|
-
const usage = normalizeUsage(candidate.usage);
|
|
837
|
-
if (usage) assistant.usage = usage;
|
|
838
|
-
return assistant;
|
|
839
|
-
}
|
|
840
|
-
return undefined;
|
|
841
|
-
}
|
|
842
|
-
|
|
843
|
-
export function formatError(error: unknown) {
|
|
844
|
-
return truncateNotification(error instanceof Error ? error.message : String(error));
|
|
845
|
-
}
|
|
846
|
-
|
|
847
|
-
export function truncateNotification(value: string) {
|
|
848
|
-
return value.length > 160 ? `${value.slice(0, 157)}...` : value;
|
|
1026
|
+
function inputFingerprint(prompt: string) {
|
|
1027
|
+
return createHash("sha256").update(prompt, "utf8").digest("hex");
|
|
849
1028
|
}
|
|
850
1029
|
|
|
851
1030
|
async function sendPrompt(pi: ExtensionAPI, ctx: StatusContext, prompt: string) {
|
|
@@ -871,80 +1050,16 @@ function goalCommandHint(status: GoalStatus, experimentalGoals = false) {
|
|
|
871
1050
|
return `/goal edit <objective>, /goal clear${queueCommands}`;
|
|
872
1051
|
}
|
|
873
1052
|
|
|
874
|
-
function toPiAssistantMessage(assistant: AssistantMessageLike): PiAssistantMessage {
|
|
875
|
-
return {
|
|
876
|
-
role: "assistant",
|
|
877
|
-
content: assistant.content ?? [],
|
|
878
|
-
api: assistant.api ?? "openai-responses",
|
|
879
|
-
provider: assistant.provider ?? "unknown",
|
|
880
|
-
model: assistant.model ?? "unknown",
|
|
881
|
-
usage: assistant.usage ?? zeroUsage(),
|
|
882
|
-
stopReason: assistant.stopReason ?? "error",
|
|
883
|
-
errorMessage: assistant.errorMessage,
|
|
884
|
-
timestamp: assistant.timestamp ?? Date.now(),
|
|
885
|
-
};
|
|
886
|
-
}
|
|
887
|
-
|
|
888
|
-
function zeroUsage(): Usage {
|
|
889
|
-
return {
|
|
890
|
-
input: 0,
|
|
891
|
-
output: 0,
|
|
892
|
-
cacheRead: 0,
|
|
893
|
-
cacheWrite: 0,
|
|
894
|
-
totalTokens: 0,
|
|
895
|
-
cost: {
|
|
896
|
-
input: 0,
|
|
897
|
-
output: 0,
|
|
898
|
-
cacheRead: 0,
|
|
899
|
-
cacheWrite: 0,
|
|
900
|
-
total: 0,
|
|
901
|
-
},
|
|
902
|
-
};
|
|
903
|
-
}
|
|
904
|
-
|
|
905
1053
|
function continuationMarker(goal: ActiveGoal) {
|
|
906
1054
|
return `${goal.id}:${goal.iteration}:${randomUUID()}`;
|
|
907
1055
|
}
|
|
908
1056
|
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
);
|
|
919
|
-
|
|
920
|
-
function extractGoalPromptMarker(prompt: string) {
|
|
921
|
-
return GOAL_PROMPT_MARKER_PATTERN.exec(prompt)?.[1];
|
|
922
|
-
}
|
|
923
|
-
|
|
924
|
-
function extractContinuationMarker(prompt: string) {
|
|
925
|
-
return CONTINUATION_MARKER_PATTERN.exec(prompt)?.[1];
|
|
926
|
-
}
|
|
927
|
-
|
|
928
|
-
function isAgentStopReason(value: unknown): value is AgentStopReason {
|
|
929
|
-
return ["stop", "length", "toolUse", "error", "aborted"].includes(String(value));
|
|
930
|
-
}
|
|
931
|
-
|
|
932
|
-
function normalizeUsage(value: unknown): Usage | undefined {
|
|
933
|
-
if (!value || typeof value !== "object") return undefined;
|
|
934
|
-
const usage = value as Partial<Usage>;
|
|
935
|
-
if (typeof usage.input !== "number" || typeof usage.output !== "number") return undefined;
|
|
936
|
-
return {
|
|
937
|
-
input: nonNegativeFiniteNumber(usage.input),
|
|
938
|
-
output: nonNegativeFiniteNumber(usage.output),
|
|
939
|
-
cacheRead: nonNegativeFiniteNumber(usage.cacheRead),
|
|
940
|
-
cacheWrite: nonNegativeFiniteNumber(usage.cacheWrite),
|
|
941
|
-
totalTokens: assistantUsageTokens(usage),
|
|
942
|
-
cost: {
|
|
943
|
-
input: usage.cost?.input ?? 0,
|
|
944
|
-
output: usage.cost?.output ?? 0,
|
|
945
|
-
cacheRead: usage.cost?.cacheRead ?? 0,
|
|
946
|
-
cacheWrite: usage.cost?.cacheWrite ?? 0,
|
|
947
|
-
total: usage.cost?.total ?? 0,
|
|
948
|
-
},
|
|
949
|
-
};
|
|
950
|
-
}
|
|
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";
|