@narumitw/pi-goal 0.24.0 → 0.27.1
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 +12 -3
- package/src/errors.ts +147 -0
- package/src/goal.ts +195 -43
- package/src/markers.ts +25 -0
- package/src/persistence.ts +26 -1
- package/src/queue.ts +4 -1
- package/src/runtime.ts +350 -191
- package/src/safety.ts +78 -0
- package/src/settings.ts +41 -0
package/src/runtime.ts
CHANGED
|
@@ -1,28 +1,30 @@
|
|
|
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 {
|
|
23
|
+
import { nextToolFreeRepeatState, resetGoalSafetyEpoch } from "./safety.js";
|
|
24
24
|
|
|
25
|
-
export
|
|
25
|
+
export { queueGoalSafetyReset, resetGoalSafetyEpoch } from "./safety.js";
|
|
26
|
+
|
|
27
|
+
import { DEFAULT_GOAL_SETTINGS, type GoalSettings } from "./settings.js";
|
|
26
28
|
|
|
27
29
|
export interface ContinuationTicket {
|
|
28
30
|
goalId: string;
|
|
@@ -38,21 +40,19 @@ export interface BudgetWrapUp {
|
|
|
38
40
|
|
|
39
41
|
export type GoalRecoveryKind = "provider_retry" | "compaction_retry";
|
|
40
42
|
|
|
43
|
+
export type GoalRunOrigin = "manual" | "automatic";
|
|
44
|
+
|
|
41
45
|
export interface GoalRecovery {
|
|
42
46
|
goalId: string;
|
|
43
47
|
kind: GoalRecoveryKind;
|
|
48
|
+
automaticOwner: boolean;
|
|
49
|
+
errorMessage?: string;
|
|
44
50
|
}
|
|
45
51
|
|
|
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;
|
|
52
|
+
export interface CompletedGoalRun {
|
|
53
|
+
goalId?: string | null;
|
|
54
|
+
origin?: GoalRunOrigin;
|
|
55
|
+
toolAttempted: boolean;
|
|
56
56
|
}
|
|
57
57
|
|
|
58
58
|
export interface StatusContext {
|
|
@@ -122,10 +122,20 @@ interface GoalTerminalDetails {
|
|
|
122
122
|
reason?: string;
|
|
123
123
|
}
|
|
124
124
|
|
|
125
|
+
interface PendingGoalPrompt {
|
|
126
|
+
goalId: string;
|
|
127
|
+
resetSafetyEpoch: boolean;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
interface PendingNonGoalInput {
|
|
131
|
+
behavior: "steer" | "followUp";
|
|
132
|
+
fingerprint: string;
|
|
133
|
+
resetSafetyEpoch: boolean;
|
|
134
|
+
}
|
|
135
|
+
|
|
125
136
|
const MAX_CANCELLED_CONTINUATION_PROMPTS = 20;
|
|
126
137
|
const MAX_PENDING_GOAL_PROMPTS = 20;
|
|
127
|
-
const
|
|
128
|
-
const CONTINUATION_MARKER_PREFIX = "pi-goal-continuation:";
|
|
138
|
+
const MAX_PENDING_NON_GOAL_INPUTS = 20;
|
|
129
139
|
const BUDGET_WRAP_UP_MESSAGE_TYPE = "goal-budget-wrap-up";
|
|
130
140
|
const BUDGET_WRAP_UP_PROMPT =
|
|
131
141
|
"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 +144,6 @@ const CONTRADICTORY_COMPLETION_PATTERNS = [
|
|
|
134
144
|
/\bstill\s+(?:incomplete|failing|failing\s+tests?|fails?)\b/i,
|
|
135
145
|
/\btests?\s+(?:still\s+)?fail(?:ing)?\b/i,
|
|
136
146
|
] 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
147
|
// One instance belongs to one extension factory. It owns all mutable session state
|
|
156
148
|
// and the cross-cutting invariants used by command and lifecycle orchestration.
|
|
157
149
|
export class GoalRuntime {
|
|
@@ -169,13 +161,19 @@ export class GoalRuntime {
|
|
|
169
161
|
budgetWrapUp?: BudgetWrapUp;
|
|
170
162
|
/** `null` marks a run that must not be charged to the active goal. */
|
|
171
163
|
agentRunGoalId?: string | null;
|
|
164
|
+
agentRunOrigin?: GoalRunOrigin;
|
|
165
|
+
agentRunToolAttempted = false;
|
|
166
|
+
guardAbortGoalId?: string;
|
|
172
167
|
staleGoalToolCallsBlocked = false;
|
|
173
168
|
/** Once true, goal tools stay in the active set for this runtime (prompt-cache stable). */
|
|
174
169
|
goalToolsUnlocked = false;
|
|
175
170
|
/** Exact lazy goal tools this runtime removed and may restore on a mode change. */
|
|
176
171
|
goalToolsHiddenByPolicy = new Set<string>();
|
|
177
|
-
pendingGoalPromptMarkers = new Map<string,
|
|
172
|
+
pendingGoalPromptMarkers = new Map<string, PendingGoalPrompt>();
|
|
173
|
+
claimedGoalPromptMarkers = new Set<string>();
|
|
178
174
|
cancelledContinuationMarkers = new Set<string>();
|
|
175
|
+
claimedContinuationMarkers = new Set<string>();
|
|
176
|
+
pendingNonGoalInputs: PendingNonGoalInput[] = [];
|
|
179
177
|
|
|
180
178
|
readonly pi: ExtensionAPI;
|
|
181
179
|
|
|
@@ -183,9 +181,12 @@ export class GoalRuntime {
|
|
|
183
181
|
this.pi = pi;
|
|
184
182
|
}
|
|
185
183
|
|
|
186
|
-
canRecordGoalUsage() {
|
|
184
|
+
canRecordGoalUsage(goalId?: string) {
|
|
187
185
|
return (
|
|
188
186
|
this.agentRunGoalId !== null &&
|
|
187
|
+
(goalId === undefined ||
|
|
188
|
+
this.agentRunGoalId === undefined ||
|
|
189
|
+
this.agentRunGoalId === goalId) &&
|
|
189
190
|
!(
|
|
190
191
|
this.pendingQueueAction?.kind === "prioritize" &&
|
|
191
192
|
this.pendingQueueAction.displacedUsageFinalized === true
|
|
@@ -205,12 +206,53 @@ export class GoalRuntime {
|
|
|
205
206
|
return Boolean(this.activeGoal && this.goalRecovery?.goalId === this.activeGoal.id);
|
|
206
207
|
}
|
|
207
208
|
|
|
209
|
+
beginAgentRun(goalId: string | null | undefined, origin: GoalRunOrigin | undefined) {
|
|
210
|
+
this.agentRunGoalId = goalId;
|
|
211
|
+
this.agentRunOrigin = origin;
|
|
212
|
+
this.agentRunToolAttempted = false;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
beginRecoveryRunIfNeeded() {
|
|
216
|
+
if (this.agentRunGoalId !== undefined || !this.activeGoal) return;
|
|
217
|
+
const recovery = this.goalRecovery;
|
|
218
|
+
if (!recovery || recovery.goalId !== this.activeGoal.id) return;
|
|
219
|
+
this.beginAgentRun(recovery.goalId, recovery.automaticOwner ? "automatic" : "manual");
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
markAgentToolAttempted() {
|
|
223
|
+
if (this.agentRunGoalId !== undefined) this.agentRunToolAttempted = true;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
finishAgentRun(): CompletedGoalRun {
|
|
227
|
+
const run = {
|
|
228
|
+
goalId: this.agentRunGoalId,
|
|
229
|
+
origin: this.agentRunOrigin,
|
|
230
|
+
toolAttempted: this.agentRunToolAttempted,
|
|
231
|
+
};
|
|
232
|
+
this.clearAgentRun();
|
|
233
|
+
return run;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
clearAgentRun() {
|
|
237
|
+
this.agentRunGoalId = undefined;
|
|
238
|
+
this.agentRunOrigin = undefined;
|
|
239
|
+
this.agentRunToolAttempted = false;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
reclassifyAgentRunAsManual() {
|
|
243
|
+
if (this.agentRunGoalId !== undefined) this.agentRunOrigin = "manual";
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
isAutomaticRunForGoal(goalId: string) {
|
|
247
|
+
return this.agentRunGoalId === goalId && this.agentRunOrigin === "automatic";
|
|
248
|
+
}
|
|
249
|
+
|
|
208
250
|
recordGoalUsage(
|
|
209
251
|
goal: ActiveGoal,
|
|
210
252
|
ctx: StatusContext,
|
|
211
253
|
checkpointActiveTime = goal.status === "active",
|
|
212
254
|
) {
|
|
213
|
-
if (!this.canRecordGoalUsage()) return false;
|
|
255
|
+
if (!this.canRecordGoalUsage(goal.id)) return false;
|
|
214
256
|
updateGoalUsage(goal, ctx, checkpointActiveTime);
|
|
215
257
|
return true;
|
|
216
258
|
}
|
|
@@ -242,6 +284,9 @@ export class GoalRuntime {
|
|
|
242
284
|
this.continuationIntent = undefined;
|
|
243
285
|
return false;
|
|
244
286
|
}
|
|
287
|
+
if (this.enforceAutomaticTurnLimit(ctx, false) || this.enforceNoProgressLimit(ctx)) {
|
|
288
|
+
return false;
|
|
289
|
+
}
|
|
245
290
|
if (ctx.isIdle?.() !== true || hasPendingMessages(ctx)) return false;
|
|
246
291
|
|
|
247
292
|
this.continuationIntent = undefined;
|
|
@@ -300,23 +345,31 @@ export class GoalRuntime {
|
|
|
300
345
|
this.terminalDetails = undefined;
|
|
301
346
|
}
|
|
302
347
|
|
|
303
|
-
|
|
304
|
-
if (!message || typeof message !== "object") return
|
|
348
|
+
isActiveBudgetWrapUpMessage(message: unknown) {
|
|
349
|
+
if (!message || typeof message !== "object") return false;
|
|
305
350
|
const candidate = message as {
|
|
306
351
|
role?: unknown;
|
|
307
352
|
customType?: unknown;
|
|
308
353
|
details?: { goalId?: unknown };
|
|
309
354
|
};
|
|
310
|
-
if (candidate.role !== "custom" || candidate.customType !== BUDGET_WRAP_UP_MESSAGE_TYPE) {
|
|
311
|
-
return true;
|
|
312
|
-
}
|
|
313
355
|
return (
|
|
356
|
+
candidate.role === "custom" &&
|
|
357
|
+
candidate.customType === BUDGET_WRAP_UP_MESSAGE_TYPE &&
|
|
314
358
|
typeof candidate.details?.goalId === "string" &&
|
|
315
359
|
candidate.details.goalId === this.budgetWrapUp?.goalId &&
|
|
316
360
|
candidate.details.goalId === this.activeGoal?.id
|
|
317
361
|
);
|
|
318
362
|
}
|
|
319
363
|
|
|
364
|
+
keepBudgetWrapUpMessage(message: unknown) {
|
|
365
|
+
if (!message || typeof message !== "object") return true;
|
|
366
|
+
const candidate = message as { role?: unknown; customType?: unknown };
|
|
367
|
+
if (candidate.role !== "custom" || candidate.customType !== BUDGET_WRAP_UP_MESSAGE_TYPE) {
|
|
368
|
+
return true;
|
|
369
|
+
}
|
|
370
|
+
return this.isActiveBudgetWrapUpMessage(message);
|
|
371
|
+
}
|
|
372
|
+
|
|
320
373
|
queueBudgetWrapUp(ctx: StatusContext, goal: ActiveGoal) {
|
|
321
374
|
if (!this.budgetWrapUp || this.budgetWrapUp.goalId !== goal.id) {
|
|
322
375
|
this.budgetWrapUp = { goalId: goal.id, delivered: false };
|
|
@@ -366,6 +419,125 @@ export class GoalRuntime {
|
|
|
366
419
|
return true;
|
|
367
420
|
}
|
|
368
421
|
|
|
422
|
+
recordAutomaticTurn(ctx: StatusContext, message: unknown) {
|
|
423
|
+
const goal = this.activeGoal;
|
|
424
|
+
if (goal?.status !== "active" || !this.isAutomaticRunForGoal(goal.id)) return false;
|
|
425
|
+
const candidate = message as { role?: unknown; stopReason?: unknown } | undefined;
|
|
426
|
+
if (candidate?.role === "assistant" && candidate.stopReason === "aborted") return false;
|
|
427
|
+
goal.automaticModelTurns = Math.min(Number.MAX_SAFE_INTEGER, goal.automaticModelTurns + 1);
|
|
428
|
+
this.recordGoalUsage(goal, ctx);
|
|
429
|
+
this.persistGoal(goal);
|
|
430
|
+
this.updateStatus(ctx, goal);
|
|
431
|
+
// Terminal errors need agent_end classification before a safety pause can
|
|
432
|
+
// choose between usage_limited, blocked, or retryable cleanup.
|
|
433
|
+
if (candidate?.role === "assistant" && candidate.stopReason === "error") return false;
|
|
434
|
+
return this.enforceAutomaticTurnLimit(ctx, true);
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
recordAutomaticRunProgress(
|
|
438
|
+
ctx: StatusContext,
|
|
439
|
+
goalId: string,
|
|
440
|
+
messages: readonly unknown[],
|
|
441
|
+
toolAttempted: boolean,
|
|
442
|
+
) {
|
|
443
|
+
const goal = this.activeGoal;
|
|
444
|
+
if (goal?.id !== goalId || goal.status !== "active") return false;
|
|
445
|
+
const next = nextToolFreeRepeatState(goal, messages, toolAttempted);
|
|
446
|
+
goal.toolFreeRepeatCount = next.toolFreeRepeatCount;
|
|
447
|
+
goal.lastToolFreeOutputFingerprint = next.lastToolFreeOutputFingerprint;
|
|
448
|
+
this.persistGoal(goal);
|
|
449
|
+
this.updateStatus(ctx, goal);
|
|
450
|
+
const limit = this.settings.continuationLimits.noProgressTurns;
|
|
451
|
+
if (limit === null || goal.toolFreeRepeatCount < limit) return false;
|
|
452
|
+
return this.pauseGoalForSafety(ctx, "no_progress", false);
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
enforceAutomaticTurnLimit(ctx: StatusContext, abortTurn: boolean) {
|
|
456
|
+
const goal = this.activeGoal;
|
|
457
|
+
const limit = this.settings.continuationLimits.automaticTurns;
|
|
458
|
+
if (goal?.status !== "active" || limit === null || goal.automaticModelTurns < limit) {
|
|
459
|
+
return false;
|
|
460
|
+
}
|
|
461
|
+
return this.pauseGoalForSafety(ctx, "continuation_limit", abortTurn);
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
enforceNoProgressLimit(ctx: StatusContext) {
|
|
465
|
+
const goal = this.activeGoal;
|
|
466
|
+
const limit = this.settings.continuationLimits.noProgressTurns;
|
|
467
|
+
if (goal?.status !== "active" || limit === null || goal.toolFreeRepeatCount < limit) {
|
|
468
|
+
return false;
|
|
469
|
+
}
|
|
470
|
+
return this.pauseGoalForSafety(ctx, "no_progress", false);
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
pauseGoalForSafety(ctx: StatusContext, cause: SafetyPauseCause, abortTurn: boolean) {
|
|
474
|
+
const goal = this.activeGoal;
|
|
475
|
+
if (goal?.status !== "active") return false;
|
|
476
|
+
this.cancelContinuationWork();
|
|
477
|
+
this.clearGoalRecoveryForGoal(goal.id);
|
|
478
|
+
this.clearBudgetWrapUp();
|
|
479
|
+
this.blockStaleGoalToolCalls();
|
|
480
|
+
if (abortTurn) {
|
|
481
|
+
this.guardAbortGoalId = goal.id;
|
|
482
|
+
abortCurrentTurn(ctx);
|
|
483
|
+
}
|
|
484
|
+
this.activeGoal = transitionGoal({ ...goal, safetyPauseCause: cause }, "paused");
|
|
485
|
+
const count =
|
|
486
|
+
cause === "continuation_limit"
|
|
487
|
+
? `${this.activeGoal.automaticModelTurns} automatic model responses`
|
|
488
|
+
: `no progress across ${this.activeGoal.toolFreeRepeatCount} automatic runs`;
|
|
489
|
+
this.setTerminalReason(
|
|
490
|
+
this.activeGoal.id,
|
|
491
|
+
`${cause} (${count}; ${formatTokenCount(this.activeGoal.tokensUsed)} tokens)`,
|
|
492
|
+
);
|
|
493
|
+
this.persistGoal(this.activeGoal);
|
|
494
|
+
this.updateStatus(ctx, this.activeGoal);
|
|
495
|
+
ctx.ui.notify(
|
|
496
|
+
`Goal paused: ${count}; ${formatTokenCount(this.activeGoal.tokensUsed)} cumulative tokens. Run /goal resume to continue.`,
|
|
497
|
+
"warning",
|
|
498
|
+
);
|
|
499
|
+
return true;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
resetActiveSafetyEpoch(ctx: StatusContext) {
|
|
503
|
+
const goal = this.activeGoal;
|
|
504
|
+
if (goal?.status !== "active") return false;
|
|
505
|
+
this.activeGoal = resetGoalSafetyEpoch(goal);
|
|
506
|
+
this.reclassifyAgentRunAsManual();
|
|
507
|
+
this.persistGoal(this.activeGoal);
|
|
508
|
+
this.updateStatus(ctx, this.activeGoal);
|
|
509
|
+
return true;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
finalizeSettledRecovery(ctx: StatusContext) {
|
|
513
|
+
const recovery = this.goalRecovery;
|
|
514
|
+
if (!recovery) return false;
|
|
515
|
+
this.goalRecovery = undefined;
|
|
516
|
+
const goal = this.activeGoal;
|
|
517
|
+
if (goal?.id !== recovery.goalId || goal.status !== "active") return false;
|
|
518
|
+
this.cancelContinuationWork();
|
|
519
|
+
this.clearBudgetWrapUp();
|
|
520
|
+
this.blockStaleGoalToolCalls();
|
|
521
|
+
this.activeGoal = transitionGoal(goal, "blocked");
|
|
522
|
+
const details = recovery.errorMessage ? `: ${truncateNotification(recovery.errorMessage)}` : "";
|
|
523
|
+
this.setTerminalReason(this.activeGoal.id, `agent error after retries${details}`);
|
|
524
|
+
this.persistGoal(this.activeGoal);
|
|
525
|
+
this.updateStatus(ctx, this.activeGoal);
|
|
526
|
+
ctx.ui.notify(
|
|
527
|
+
`Goal blocked after agent error retries were exhausted${details}. Resolve the blocker or run /goal resume to retry.`,
|
|
528
|
+
"warning",
|
|
529
|
+
);
|
|
530
|
+
return true;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
clearSettledSafetyTracking() {
|
|
534
|
+
this.guardAbortGoalId = undefined;
|
|
535
|
+
this.pendingNonGoalInputs = [];
|
|
536
|
+
this.claimedGoalPromptMarkers.clear();
|
|
537
|
+
this.claimedContinuationMarkers.clear();
|
|
538
|
+
this.clearAgentRun();
|
|
539
|
+
}
|
|
540
|
+
|
|
369
541
|
clearGoalRecoveryForGoal(goalId: string) {
|
|
370
542
|
if (this.goalRecovery?.goalId === goalId) this.goalRecovery = undefined;
|
|
371
543
|
}
|
|
@@ -384,14 +556,22 @@ export class GoalRuntime {
|
|
|
384
556
|
this.continuationIntent = undefined;
|
|
385
557
|
this.continuationDelivery = undefined;
|
|
386
558
|
this.cancelledContinuationMarkers.clear();
|
|
559
|
+
this.claimedContinuationMarkers.clear();
|
|
387
560
|
}
|
|
388
561
|
|
|
389
562
|
clearPendingGoalPrompts() {
|
|
390
563
|
this.pendingGoalPromptMarkers.clear();
|
|
564
|
+
this.claimedGoalPromptMarkers.clear();
|
|
565
|
+
this.pendingNonGoalInputs = [];
|
|
391
566
|
}
|
|
392
567
|
|
|
393
|
-
async sendOwnedGoalPrompt(
|
|
394
|
-
|
|
568
|
+
async sendOwnedGoalPrompt(
|
|
569
|
+
ctx: StatusContext,
|
|
570
|
+
goalId: string,
|
|
571
|
+
prompt: string,
|
|
572
|
+
resetSafetyEpoch = true,
|
|
573
|
+
) {
|
|
574
|
+
const pending = this.rememberPendingGoalPrompt(goalId, prompt, resetSafetyEpoch);
|
|
395
575
|
const sent = await sendPrompt(this.pi, ctx, pending.prompt);
|
|
396
576
|
if (!sent) this.pendingGoalPromptMarkers.delete(pending.marker);
|
|
397
577
|
return sent;
|
|
@@ -410,15 +590,37 @@ export class GoalRuntime {
|
|
|
410
590
|
return marker ? this.cancelledContinuationMarkers.delete(marker) : false;
|
|
411
591
|
}
|
|
412
592
|
|
|
593
|
+
hasPendingOwnedGoalPrompt(prompt: string) {
|
|
594
|
+
const marker = extractGoalPromptMarker(prompt);
|
|
595
|
+
return marker ? this.pendingGoalPromptMarkers.has(marker) : false;
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
hasOwnedPromptBoundary(prompt: string) {
|
|
599
|
+
const goalMarker = extractGoalPromptMarker(prompt);
|
|
600
|
+
if (
|
|
601
|
+
goalMarker &&
|
|
602
|
+
(this.pendingGoalPromptMarkers.has(goalMarker) ||
|
|
603
|
+
this.claimedGoalPromptMarkers.has(goalMarker))
|
|
604
|
+
) {
|
|
605
|
+
return true;
|
|
606
|
+
}
|
|
607
|
+
const continuationMarker = extractContinuationMarker(prompt);
|
|
608
|
+
return Boolean(
|
|
609
|
+
continuationMarker &&
|
|
610
|
+
(this.continuationDelivery?.marker === continuationMarker ||
|
|
611
|
+
this.claimedContinuationMarkers.has(continuationMarker)),
|
|
612
|
+
);
|
|
613
|
+
}
|
|
614
|
+
|
|
413
615
|
consumeStaleOwnedGoalPrompt(prompt: string) {
|
|
414
616
|
const marker = extractGoalPromptMarker(prompt);
|
|
415
617
|
if (!marker) return false;
|
|
416
|
-
const
|
|
417
|
-
if (!
|
|
618
|
+
const pending = this.pendingGoalPromptMarkers.get(marker);
|
|
619
|
+
if (!pending) return false;
|
|
418
620
|
if (
|
|
419
621
|
!this.queueFrozen &&
|
|
420
622
|
!this.pendingQueueAction &&
|
|
421
|
-
this.activeGoal?.id === goalId &&
|
|
623
|
+
this.activeGoal?.id === pending.goalId &&
|
|
422
624
|
this.activeGoal.status === "active"
|
|
423
625
|
) {
|
|
424
626
|
return false;
|
|
@@ -427,6 +629,58 @@ export class GoalRuntime {
|
|
|
427
629
|
return true;
|
|
428
630
|
}
|
|
429
631
|
|
|
632
|
+
noteQueuedNonGoalInput(prompt: string, behavior: "steer" | "followUp", resetSafetyEpoch = false) {
|
|
633
|
+
this.pendingNonGoalInputs.push({
|
|
634
|
+
behavior,
|
|
635
|
+
fingerprint: inputFingerprint(prompt),
|
|
636
|
+
resetSafetyEpoch,
|
|
637
|
+
});
|
|
638
|
+
if (this.pendingNonGoalInputs.length > MAX_PENDING_NON_GOAL_INPUTS) {
|
|
639
|
+
this.pendingNonGoalInputs.shift();
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
consumeQueuedNonGoalInput(prompt: string, allowDeliveryFallback = true) {
|
|
644
|
+
if (typeof prompt !== "string") return undefined;
|
|
645
|
+
const fingerprint = inputFingerprint(prompt);
|
|
646
|
+
// Pi delivers steers before follow-ups. Prefer a matching steer even when an
|
|
647
|
+
// identical follow-up was queued first so it cannot steal follow-up ownership.
|
|
648
|
+
const steerIndex = this.pendingNonGoalInputs.findIndex(
|
|
649
|
+
(pending) => pending.behavior === "steer" && pending.fingerprint === fingerprint,
|
|
650
|
+
);
|
|
651
|
+
const exactIndex =
|
|
652
|
+
steerIndex >= 0
|
|
653
|
+
? steerIndex
|
|
654
|
+
: this.pendingNonGoalInputs.findIndex(
|
|
655
|
+
(pending) => pending.behavior === "followUp" && pending.fingerprint === fingerprint,
|
|
656
|
+
);
|
|
657
|
+
if (exactIndex >= 0) return this.pendingNonGoalInputs.splice(exactIndex, 1)[0];
|
|
658
|
+
if (!allowDeliveryFallback) return undefined;
|
|
659
|
+
|
|
660
|
+
// Skills, templates, and later input handlers can transform the raw text after
|
|
661
|
+
// pi-goal records it. Fall back to Pi's delivery priority as a bounded marker:
|
|
662
|
+
// steers drain before follow-ups, and settlement clears stale entries.
|
|
663
|
+
const fallbackSteerIndex = this.pendingNonGoalInputs.findIndex(
|
|
664
|
+
(pending) => pending.behavior === "steer",
|
|
665
|
+
);
|
|
666
|
+
const fallbackIndex =
|
|
667
|
+
fallbackSteerIndex >= 0
|
|
668
|
+
? fallbackSteerIndex
|
|
669
|
+
: this.pendingNonGoalInputs.findIndex((pending) => pending.behavior === "followUp");
|
|
670
|
+
if (fallbackIndex < 0) return undefined;
|
|
671
|
+
return this.pendingNonGoalInputs.splice(fallbackIndex, 1)[0];
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
consumeQueuedNonGoalFollowUpForAgentStart() {
|
|
675
|
+
// A pending steer owns the next intra-run boundary. Do not let a later
|
|
676
|
+
// follow-up suppress cleanup until all earlier-priority steers have started.
|
|
677
|
+
if (this.pendingNonGoalInputs.some((pending) => pending.behavior === "steer")) return false;
|
|
678
|
+
const index = this.pendingNonGoalInputs.findIndex((pending) => pending.behavior === "followUp");
|
|
679
|
+
if (index < 0) return false;
|
|
680
|
+
this.pendingNonGoalInputs.splice(index, 1);
|
|
681
|
+
return true;
|
|
682
|
+
}
|
|
683
|
+
|
|
430
684
|
markContinuationStarted(prompt: string) {
|
|
431
685
|
const marker = extractContinuationMarker(prompt);
|
|
432
686
|
if (!marker) {
|
|
@@ -436,7 +690,10 @@ export class GoalRuntime {
|
|
|
436
690
|
this.cancelContinuationWork();
|
|
437
691
|
return undefined;
|
|
438
692
|
}
|
|
439
|
-
if (this.continuationDelivery?.marker === marker)
|
|
693
|
+
if (this.continuationDelivery?.marker === marker) {
|
|
694
|
+
this.continuationDelivery = undefined;
|
|
695
|
+
this.rememberClaimedContinuationMarker(marker);
|
|
696
|
+
}
|
|
440
697
|
return marker.split(":", 1)[0];
|
|
441
698
|
}
|
|
442
699
|
|
|
@@ -626,22 +883,37 @@ export class GoalRuntime {
|
|
|
626
883
|
this.completionStatusTimer = undefined;
|
|
627
884
|
}
|
|
628
885
|
|
|
629
|
-
private rememberPendingGoalPrompt(goalId: string, prompt: string) {
|
|
886
|
+
private rememberPendingGoalPrompt(goalId: string, prompt: string, resetSafetyEpoch: boolean) {
|
|
630
887
|
const marker = randomUUID();
|
|
631
|
-
this.pendingGoalPromptMarkers.set(marker, goalId);
|
|
888
|
+
this.pendingGoalPromptMarkers.set(marker, { goalId, resetSafetyEpoch });
|
|
632
889
|
if (this.pendingGoalPromptMarkers.size > MAX_PENDING_GOAL_PROMPTS) {
|
|
633
890
|
const oldest = this.pendingGoalPromptMarkers.keys().next().value;
|
|
634
891
|
if (oldest) this.pendingGoalPromptMarkers.delete(oldest);
|
|
635
892
|
}
|
|
636
|
-
return { marker, prompt:
|
|
893
|
+
return { marker, prompt: appendGoalPromptMarker(prompt, marker) };
|
|
637
894
|
}
|
|
638
895
|
|
|
639
896
|
private consumePendingGoalPrompt(prompt: string) {
|
|
640
897
|
const marker = extractGoalPromptMarker(prompt);
|
|
641
898
|
if (!marker) return undefined;
|
|
642
|
-
const
|
|
899
|
+
const pending = this.pendingGoalPromptMarkers.get(marker);
|
|
643
900
|
this.pendingGoalPromptMarkers.delete(marker);
|
|
644
|
-
|
|
901
|
+
if (pending) this.rememberClaimedGoalPromptMarker(marker);
|
|
902
|
+
return pending;
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
private rememberClaimedGoalPromptMarker(marker: string) {
|
|
906
|
+
this.claimedGoalPromptMarkers.add(marker);
|
|
907
|
+
if (this.claimedGoalPromptMarkers.size <= MAX_PENDING_GOAL_PROMPTS) return;
|
|
908
|
+
const oldest = this.claimedGoalPromptMarkers.values().next().value;
|
|
909
|
+
if (oldest) this.claimedGoalPromptMarkers.delete(oldest);
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
private rememberClaimedContinuationMarker(marker: string) {
|
|
913
|
+
this.claimedContinuationMarkers.add(marker);
|
|
914
|
+
if (this.claimedContinuationMarkers.size <= MAX_CANCELLED_CONTINUATION_PROMPTS) return;
|
|
915
|
+
const oldest = this.claimedContinuationMarkers.values().next().value;
|
|
916
|
+
if (oldest) this.claimedContinuationMarkers.delete(oldest);
|
|
645
917
|
}
|
|
646
918
|
|
|
647
919
|
consumeOwnedGoalPrompt(prompt: string) {
|
|
@@ -674,6 +946,8 @@ export function createGoal(
|
|
|
674
946
|
timeUsedSeconds: 0,
|
|
675
947
|
baselineTokens,
|
|
676
948
|
activeStartedAt: now,
|
|
949
|
+
automaticModelTurns: 0,
|
|
950
|
+
toolFreeRepeatCount: 0,
|
|
677
951
|
};
|
|
678
952
|
}
|
|
679
953
|
|
|
@@ -729,9 +1003,15 @@ export function goalSummary(
|
|
|
729
1003
|
`Goal: ${goal.text}`,
|
|
730
1004
|
`Status: ${queueFrozen ? "queue off" : goal.status}`,
|
|
731
1005
|
`Iteration: ${goal.iteration}`,
|
|
1006
|
+
`Automatic model responses: ${goal.automaticModelTurns}`,
|
|
732
1007
|
`Active elapsed: ${formatDuration(goal.timeUsedSeconds)}`,
|
|
733
1008
|
`Tokens: ${goal.tokenBudget === undefined ? formatTokenCount(goal.tokensUsed) : formatBudget(goal)}`,
|
|
734
1009
|
];
|
|
1010
|
+
if (goal.safetyPauseCause) {
|
|
1011
|
+
summary.push(
|
|
1012
|
+
`Safety pause: ${goal.safetyPauseCause === "continuation_limit" ? "automatic response limit" : "no progress"}`,
|
|
1013
|
+
);
|
|
1014
|
+
}
|
|
735
1015
|
if (experimentalGoals || queuedGoals.length > 0 || queueFrozen) {
|
|
736
1016
|
summary.push(
|
|
737
1017
|
`Goals (${queuedGoals.length + 1}):`,
|
|
@@ -787,65 +1067,8 @@ export function goalIdRejectionReason(goal: ActiveGoal, requestedGoalId: string)
|
|
|
787
1067
|
return undefined;
|
|
788
1068
|
}
|
|
789
1069
|
|
|
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;
|
|
1070
|
+
function inputFingerprint(prompt: string) {
|
|
1071
|
+
return createHash("sha256").update(prompt, "utf8").digest("hex");
|
|
849
1072
|
}
|
|
850
1073
|
|
|
851
1074
|
async function sendPrompt(pi: ExtensionAPI, ctx: StatusContext, prompt: string) {
|
|
@@ -871,80 +1094,16 @@ function goalCommandHint(status: GoalStatus, experimentalGoals = false) {
|
|
|
871
1094
|
return `/goal edit <objective>, /goal clear${queueCommands}`;
|
|
872
1095
|
}
|
|
873
1096
|
|
|
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
1097
|
function continuationMarker(goal: ActiveGoal) {
|
|
906
1098
|
return `${goal.id}:${goal.iteration}:${randomUUID()}`;
|
|
907
1099
|
}
|
|
908
1100
|
|
|
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
|
-
}
|
|
1101
|
+
export type { AssistantMessageLike } from "./errors.js";
|
|
1102
|
+
export {
|
|
1103
|
+
findFinalAssistantMessage,
|
|
1104
|
+
formatError,
|
|
1105
|
+
isGoalContextOverflow,
|
|
1106
|
+
isRetryableGoalInterruption,
|
|
1107
|
+
isUsageLimitedGoalInterruption,
|
|
1108
|
+
truncateNotification,
|
|
1109
|
+
} from "./errors.js";
|