@narumitw/pi-goal 0.54.17 → 0.55.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/CHANGELOG.md +17 -0
- package/README.md +21 -11
- package/dist/chunks/{chunk-MHW7VEET.ts → chunk-7RO3AIWI.ts} +457 -33
- package/dist/chunks/chunk-7RO3AIWI.ts.map +7 -0
- package/dist/chunks/{chunk-ZLKWPYIF.ts → chunk-OPW4T4QN.ts} +6 -1
- package/dist/chunks/{chunk-ZLKWPYIF.ts.map → chunk-OPW4T4QN.ts.map} +2 -2
- package/dist/chunks/{menu-3AYWQ637.ts → menu-P4DPWLVL.ts} +3 -3
- package/dist/chunks/{settings-ui-RVQTWGJ5.ts → settings-ui-X5XS74CD.ts} +39 -3
- package/dist/chunks/settings-ui-X5XS74CD.ts.map +7 -0
- package/dist/index.ts +14 -8
- package/dist/index.ts.map +2 -2
- package/docs/continuation-lifecycle.md +81 -11
- package/docs/managing-goals.md +18 -0
- package/docs/settings.md +48 -2
- package/package.json +3 -3
- package/src/lifecycle.ts +12 -3
- package/src/runtime.ts +175 -30
- package/src/settings-ui.ts +51 -2
- package/src/settings.ts +9 -0
- package/src/usage-limit-recovery.ts +162 -0
- package/src/usage-reset.ts +309 -0
- package/src/wait.ts +21 -1
- package/dist/chunks/chunk-MHW7VEET.ts.map +0 -7
- package/dist/chunks/settings-ui-RVQTWGJ5.ts.map +0 -7
- /package/dist/chunks/{menu-3AYWQ637.ts.map → menu-P4DPWLVL.ts.map} +0 -0
package/src/runtime.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
-
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
3
|
import { checkpointGoalActiveTime, formatDuration, formatTokenCount, updateGoalUsage } from "./accounting.js";
|
|
4
4
|
import {
|
|
5
|
+
findFinalAssistantMessage,
|
|
5
6
|
formatError,
|
|
6
7
|
isStaleContextError,
|
|
7
8
|
isUsageLimitedGoalInterruption,
|
|
@@ -32,7 +33,8 @@ export { queueGoalSafetyReset, resetGoalSafetyEpoch } from "./safety.js";
|
|
|
32
33
|
|
|
33
34
|
import { DEFAULT_GOAL_SETTINGS, type GoalSettings, type GoalSettingsLoadIssue } from "./settings.js";
|
|
34
35
|
import { assertGoalToolsAvailable, goalToolsAvailable } from "./tool-policy.js";
|
|
35
|
-
import {
|
|
36
|
+
import { UsageLimitRecovery } from "./usage-limit-recovery.js";
|
|
37
|
+
import { type GoalWait, GoalWaitTimer, type UsageLimitScope } from "./wait.js";
|
|
36
38
|
import { WorkflowMutex, type WorkflowMutexOwner } from "./workflow-mutex.js";
|
|
37
39
|
|
|
38
40
|
export {
|
|
@@ -47,6 +49,7 @@ export interface ContinuationTicket {
|
|
|
47
49
|
iteration: number;
|
|
48
50
|
marker: string;
|
|
49
51
|
prompt: string;
|
|
52
|
+
usageLimitRetry?: UsageLimitScope;
|
|
50
53
|
}
|
|
51
54
|
|
|
52
55
|
export interface BudgetWrapUp {
|
|
@@ -63,12 +66,14 @@ export interface GoalRecovery {
|
|
|
63
66
|
kind: GoalRecoveryKind;
|
|
64
67
|
automaticOwner: boolean;
|
|
65
68
|
errorMessage?: string;
|
|
69
|
+
usageLimitScope?: UsageLimitScope;
|
|
66
70
|
}
|
|
67
71
|
|
|
68
72
|
export interface CompletedGoalRun {
|
|
69
73
|
goalId?: string | null;
|
|
70
74
|
origin?: GoalRunOrigin;
|
|
71
75
|
toolAttempted: boolean;
|
|
76
|
+
usageLimitRetry?: UsageLimitScope;
|
|
72
77
|
}
|
|
73
78
|
|
|
74
79
|
type StoppedGoalStatus = "paused" | "blocked" | "usage_limited" | "budget_limited";
|
|
@@ -121,6 +126,7 @@ export interface StatusContext {
|
|
|
121
126
|
hasPendingMessages?: () => boolean;
|
|
122
127
|
abort?: () => void;
|
|
123
128
|
sessionManager?: unknown;
|
|
129
|
+
model?: ExtensionContext["model"];
|
|
124
130
|
}
|
|
125
131
|
|
|
126
132
|
export const STATUS_KEY = "goal";
|
|
@@ -225,6 +231,9 @@ export class GoalRuntime {
|
|
|
225
231
|
/** Terminal details captured for the matching persisted-state snapshot. */
|
|
226
232
|
private terminalDetails?: GoalTerminalDetails;
|
|
227
233
|
private goalStateSink?: (snapshot: GoalStateSnapshot) => void;
|
|
234
|
+
private settingsStatePublications?: GoalStateSnapshot[];
|
|
235
|
+
private settingsCommitEffects?: Array<() => void>;
|
|
236
|
+
readonly usageLimitRecovery: UsageLimitRecovery;
|
|
228
237
|
legacyQueueState?: LegacyQueueState;
|
|
229
238
|
legacyExperimentalGoalsSetting = false;
|
|
230
239
|
completionStatusTimer?: NodeJS.Timeout;
|
|
@@ -247,11 +256,14 @@ export class GoalRuntime {
|
|
|
247
256
|
agentRunGoalId?: string | null;
|
|
248
257
|
agentRunOrigin?: GoalRunOrigin;
|
|
249
258
|
agentRunToolAttempted = false;
|
|
259
|
+
agentRunUsageLimitRetry?: UsageLimitScope;
|
|
260
|
+
private agentRunResponseSeen = false;
|
|
250
261
|
guardAbortGoalId?: string;
|
|
251
262
|
staleGoalToolCallsBlocked = false;
|
|
252
263
|
private readonly workflowMutex: WorkflowMutex;
|
|
253
264
|
private workflowOwner?: WorkflowMutexOwner;
|
|
254
265
|
private workflowSession?: object;
|
|
266
|
+
private workflowSessionId?: unknown;
|
|
255
267
|
private pendingGoalContract?: PendingGoalContract;
|
|
256
268
|
pendingGoalPromptMarkers = new Map<string, PendingGoalPrompt>();
|
|
257
269
|
claimedGoalPromptMarkers = new Map<string, string>();
|
|
@@ -267,6 +279,7 @@ export class GoalRuntime {
|
|
|
267
279
|
constructor(pi: ExtensionAPI) {
|
|
268
280
|
this.pi = pi;
|
|
269
281
|
this.workflowMutex = new WorkflowMutex(pi);
|
|
282
|
+
this.usageLimitRecovery = new UsageLimitRecovery(this);
|
|
270
283
|
}
|
|
271
284
|
|
|
272
285
|
goalToolsAvailable() {
|
|
@@ -280,6 +293,7 @@ export class GoalRuntime {
|
|
|
280
293
|
bindWorkflowSession(session: object) {
|
|
281
294
|
this.pendingGoalContract = undefined;
|
|
282
295
|
this.workflowSession = session;
|
|
296
|
+
this.workflowSessionId = goalWaitSessionId(session);
|
|
283
297
|
this.workflowOwner = undefined;
|
|
284
298
|
this.workflowMutex.bindSession(session);
|
|
285
299
|
}
|
|
@@ -290,10 +304,15 @@ export class GoalRuntime {
|
|
|
290
304
|
this.workflowMutex.unbindSession(session);
|
|
291
305
|
this.workflowOwner = undefined;
|
|
292
306
|
this.workflowSession = undefined;
|
|
307
|
+
this.workflowSessionId = undefined;
|
|
293
308
|
}
|
|
294
309
|
|
|
295
310
|
acquireWorkflow(session?: unknown) {
|
|
296
|
-
if (
|
|
311
|
+
if (
|
|
312
|
+
session &&
|
|
313
|
+
typeof session === "object" &&
|
|
314
|
+
(this.workflowSession !== session || this.workflowSessionId !== goalWaitSessionId(session))
|
|
315
|
+
) {
|
|
297
316
|
this.bindWorkflowSession(session);
|
|
298
317
|
}
|
|
299
318
|
if (this.workflowMutex.isOwner(this.workflowOwner)) return true;
|
|
@@ -304,7 +323,15 @@ export class GoalRuntime {
|
|
|
304
323
|
}
|
|
305
324
|
|
|
306
325
|
ownsWorkflow(goal: ActiveGoal | undefined = this.activeGoal) {
|
|
307
|
-
|
|
326
|
+
try {
|
|
327
|
+
return (
|
|
328
|
+
goal?.status === "active" &&
|
|
329
|
+
this.workflowMutex.isOwner(this.workflowOwner) &&
|
|
330
|
+
this.workflowSessionId === goalWaitSessionId(this.workflowSession)
|
|
331
|
+
);
|
|
332
|
+
} catch {
|
|
333
|
+
return false;
|
|
334
|
+
}
|
|
308
335
|
}
|
|
309
336
|
|
|
310
337
|
releaseWorkflow() {
|
|
@@ -322,6 +349,10 @@ export class GoalRuntime {
|
|
|
322
349
|
}
|
|
323
350
|
|
|
324
351
|
private publishGoalState(snapshot: GoalStateSnapshot) {
|
|
352
|
+
if (this.settingsStatePublications) {
|
|
353
|
+
this.settingsStatePublications.push(snapshot);
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
325
356
|
try {
|
|
326
357
|
this.goalStateSink?.(snapshot);
|
|
327
358
|
} catch {
|
|
@@ -329,13 +360,52 @@ export class GoalRuntime {
|
|
|
329
360
|
}
|
|
330
361
|
}
|
|
331
362
|
|
|
363
|
+
/** Publish managed-run transitions only after the settings transaction commits. */
|
|
364
|
+
withSettingsPublication(apply: () => void) {
|
|
365
|
+
const previous = this.settingsStatePublications;
|
|
366
|
+
const previousEffects = this.settingsCommitEffects;
|
|
367
|
+
const pending: GoalStateSnapshot[] = [];
|
|
368
|
+
const effects: Array<() => void> = [];
|
|
369
|
+
this.settingsStatePublications = pending;
|
|
370
|
+
this.settingsCommitEffects = effects;
|
|
371
|
+
try {
|
|
372
|
+
apply();
|
|
373
|
+
} catch (error) {
|
|
374
|
+
this.settingsStatePublications = previous;
|
|
375
|
+
this.settingsCommitEffects = previousEffects;
|
|
376
|
+
throw error;
|
|
377
|
+
}
|
|
378
|
+
this.settingsStatePublications = previous;
|
|
379
|
+
this.settingsCommitEffects = previousEffects;
|
|
380
|
+
if (previousEffects) previousEffects.push(...effects);
|
|
381
|
+
else for (const effect of effects) effect();
|
|
382
|
+
for (const snapshot of pending) this.publishGoalState(snapshot);
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
private afterSettingsCommit(ctx: StatusContext, goalId: string, effect: () => void) {
|
|
386
|
+
if (!this.settingsCommitEffects) {
|
|
387
|
+
effect();
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
this.settingsCommitEffects.push(() => {
|
|
391
|
+
if (this.activeGoal?.id !== goalId) return;
|
|
392
|
+
try {
|
|
393
|
+
effect();
|
|
394
|
+
} catch (error) {
|
|
395
|
+
notifyWhenSessionAlive(ctx, `Goal settings saved, but cleanup failed: ${formatError(error)}`, "error");
|
|
396
|
+
}
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
|
|
332
400
|
replaceMenuSession() {
|
|
401
|
+
this.usageLimitRecovery.cancel();
|
|
333
402
|
this.menuGeneration += 1;
|
|
334
403
|
this.menuController.abort(new DOMException("Goal session replaced", "AbortError"));
|
|
335
404
|
this.menuController = new AbortController();
|
|
336
405
|
}
|
|
337
406
|
|
|
338
407
|
closeMenuSession() {
|
|
408
|
+
this.usageLimitRecovery.cancel();
|
|
339
409
|
this.menuGeneration += 1;
|
|
340
410
|
this.menuController.abort(new DOMException("Goal session shut down", "AbortError"));
|
|
341
411
|
}
|
|
@@ -359,10 +429,16 @@ export class GoalRuntime {
|
|
|
359
429
|
return Boolean(this.activeGoal && this.goalRecovery?.goalId === this.activeGoal.id);
|
|
360
430
|
}
|
|
361
431
|
|
|
362
|
-
beginAgentRun(
|
|
432
|
+
beginAgentRun(
|
|
433
|
+
goalId: string | null | undefined,
|
|
434
|
+
origin: GoalRunOrigin | undefined,
|
|
435
|
+
usageLimitRetry?: UsageLimitScope,
|
|
436
|
+
) {
|
|
363
437
|
this.agentRunGoalId = goalId;
|
|
364
438
|
this.agentRunOrigin = origin;
|
|
365
439
|
this.agentRunToolAttempted = false;
|
|
440
|
+
this.agentRunUsageLimitRetry = usageLimitRetry;
|
|
441
|
+
this.agentRunResponseSeen = false;
|
|
366
442
|
}
|
|
367
443
|
|
|
368
444
|
beginRecoveryRunIfNeeded() {
|
|
@@ -381,6 +457,7 @@ export class GoalRuntime {
|
|
|
381
457
|
goalId: this.agentRunGoalId,
|
|
382
458
|
origin: this.agentRunOrigin,
|
|
383
459
|
toolAttempted: this.agentRunToolAttempted,
|
|
460
|
+
usageLimitRetry: this.agentRunUsageLimitRetry,
|
|
384
461
|
};
|
|
385
462
|
this.clearAgentRun();
|
|
386
463
|
return run;
|
|
@@ -390,6 +467,8 @@ export class GoalRuntime {
|
|
|
390
467
|
this.agentRunGoalId = undefined;
|
|
391
468
|
this.agentRunOrigin = undefined;
|
|
392
469
|
this.agentRunToolAttempted = false;
|
|
470
|
+
this.agentRunUsageLimitRetry = undefined;
|
|
471
|
+
this.agentRunResponseSeen = false;
|
|
393
472
|
}
|
|
394
473
|
|
|
395
474
|
reclassifyAgentRunAsManual() {
|
|
@@ -410,7 +489,7 @@ export class GoalRuntime {
|
|
|
410
489
|
return true;
|
|
411
490
|
}
|
|
412
491
|
|
|
413
|
-
requestContinuation(goal: ActiveGoal) {
|
|
492
|
+
requestContinuation(goal: ActiveGoal, usageLimitRetry?: UsageLimitScope) {
|
|
414
493
|
if (!this.ownsWorkflow(goal)) return false;
|
|
415
494
|
if (goal.waiting || this.hasContinuationWorkForGoal(goal.id)) return false;
|
|
416
495
|
const marker = continuationMarker(goal);
|
|
@@ -419,13 +498,14 @@ export class GoalRuntime {
|
|
|
419
498
|
iteration: goal.iteration,
|
|
420
499
|
marker,
|
|
421
500
|
prompt: buildContinuePrompt(goal, marker),
|
|
501
|
+
...(usageLimitRetry ? { usageLimitRetry } : {}),
|
|
422
502
|
};
|
|
423
503
|
return true;
|
|
424
504
|
}
|
|
425
505
|
|
|
426
506
|
dispatchContinuationIfSettled(ctx: StatusContext) {
|
|
427
507
|
const intent = this.continuationIntent;
|
|
428
|
-
if (!this.ownsWorkflow()) {
|
|
508
|
+
if (!this.ownsWorkflow() || (this.workflowSession && ctx.sessionManager !== this.workflowSession)) {
|
|
429
509
|
this.cancelContinuationWork();
|
|
430
510
|
return false;
|
|
431
511
|
}
|
|
@@ -443,7 +523,11 @@ export class GoalRuntime {
|
|
|
443
523
|
this.continuationIntent = undefined;
|
|
444
524
|
return false;
|
|
445
525
|
}
|
|
446
|
-
if (
|
|
526
|
+
if (
|
|
527
|
+
this.limitActiveGoalForBudget(ctx, false) ||
|
|
528
|
+
this.enforceAutomaticTurnLimit(ctx, false) ||
|
|
529
|
+
this.enforceNoProgressLimit(ctx)
|
|
530
|
+
) {
|
|
447
531
|
return false;
|
|
448
532
|
}
|
|
449
533
|
if (ctx.isIdle?.() !== true || hasPendingMessages(ctx)) return false;
|
|
@@ -483,10 +567,13 @@ export class GoalRuntime {
|
|
|
483
567
|
activeStartedAt: undefined,
|
|
484
568
|
updatedAt: Date.now(),
|
|
485
569
|
};
|
|
486
|
-
this.
|
|
487
|
-
this.
|
|
570
|
+
const waitingGoal = this.activeGoal;
|
|
571
|
+
this.persistGoal(waitingGoal);
|
|
572
|
+
if (this.activeGoal !== waitingGoal || !this.ownsWorkflow(waitingGoal)) return undefined;
|
|
573
|
+
this.updateStatus(ctx, waitingGoal);
|
|
574
|
+
if (this.activeGoal !== waitingGoal || !this.ownsWorkflow(waitingGoal)) return undefined;
|
|
488
575
|
this.restoreGoalWaitTimer(ctx);
|
|
489
|
-
return
|
|
576
|
+
return waitingGoal;
|
|
490
577
|
}
|
|
491
578
|
|
|
492
579
|
clearGoalWait(ctx: StatusContext, goalId: string) {
|
|
@@ -498,9 +585,10 @@ export class GoalRuntime {
|
|
|
498
585
|
checkpointGoalActiveTime(nextGoal, now, true);
|
|
499
586
|
nextGoal.updatedAt = now;
|
|
500
587
|
this.activeGoal = nextGoal;
|
|
501
|
-
this.persistGoal(
|
|
502
|
-
this.
|
|
503
|
-
|
|
588
|
+
this.persistGoal(nextGoal);
|
|
589
|
+
if (this.activeGoal !== nextGoal || !this.ownsWorkflow(nextGoal)) return false;
|
|
590
|
+
this.updateStatus(ctx, nextGoal);
|
|
591
|
+
return this.activeGoal === nextGoal && this.ownsWorkflow(nextGoal);
|
|
504
592
|
}
|
|
505
593
|
|
|
506
594
|
restoreGoalWaitTimer(ctx: StatusContext) {
|
|
@@ -509,16 +597,26 @@ export class GoalRuntime {
|
|
|
509
597
|
if (!this.ownsWorkflow(goal)) return false;
|
|
510
598
|
const resumeAt = goal?.status === "active" ? goal.waiting?.resumeAt : undefined;
|
|
511
599
|
if (!goal || resumeAt === undefined) return false;
|
|
600
|
+
if (this.usageLimitRecovery.stopIfDisabled(ctx)) return false;
|
|
601
|
+
if (goal.waiting && !this.usageLimitRecovery.matches(ctx, goal.waiting)) {
|
|
602
|
+
this.usageLimitRecovery.modelChanged(ctx);
|
|
603
|
+
return false;
|
|
604
|
+
}
|
|
512
605
|
this.scheduleGoalWaitTimer(ctx, goal.id, resumeAt);
|
|
513
606
|
return true;
|
|
514
607
|
}
|
|
515
608
|
|
|
516
609
|
dispatchDueGoalWait(ctx: StatusContext) {
|
|
517
610
|
const goal = this.activeGoal;
|
|
518
|
-
if (!this.ownsWorkflow(goal)) return false;
|
|
611
|
+
if (!this.ownsWorkflow(goal) || (this.workflowSession && ctx.sessionManager !== this.workflowSession)) return false;
|
|
519
612
|
const waiting = goal?.status === "active" ? goal.waiting : undefined;
|
|
520
613
|
const resumeAt = waiting?.resumeAt;
|
|
521
614
|
if (!goal || !waiting || resumeAt === undefined) return false;
|
|
615
|
+
if (this.usageLimitRecovery.stopIfDisabled(ctx)) return false;
|
|
616
|
+
if (!this.usageLimitRecovery.matches(ctx, waiting)) {
|
|
617
|
+
this.usageLimitRecovery.modelChanged(ctx);
|
|
618
|
+
return false;
|
|
619
|
+
}
|
|
522
620
|
const retry = this.goalWaitDeadlineRetry;
|
|
523
621
|
const matchingRetry = retry?.goalId === goal.id && retry.resumeAt === resumeAt ? retry : undefined;
|
|
524
622
|
if (matchingRetry?.exhausted) return false;
|
|
@@ -530,7 +628,7 @@ export class GoalRuntime {
|
|
|
530
628
|
if (!this.clearGoalWait(ctx, goal.id)) return false;
|
|
531
629
|
const resumedGoal = this.activeGoal;
|
|
532
630
|
if (!resumedGoal || resumedGoal.id !== goal.id || resumedGoal.status !== "active") return false;
|
|
533
|
-
this.requestContinuation(resumedGoal);
|
|
631
|
+
this.requestContinuation(resumedGoal, waiting.usageLimit);
|
|
534
632
|
const dispatched = this.dispatchContinuationIfSettled(ctx);
|
|
535
633
|
if (dispatched) return true;
|
|
536
634
|
if (
|
|
@@ -544,17 +642,21 @@ export class GoalRuntime {
|
|
|
544
642
|
}
|
|
545
643
|
|
|
546
644
|
clearGoalWaitTimer() {
|
|
645
|
+
this.usageLimitRecovery.cancel();
|
|
547
646
|
this.goalWaitTimer.clear();
|
|
548
647
|
this.goalWaitDeadlineRetry = undefined;
|
|
549
648
|
}
|
|
550
649
|
|
|
551
650
|
private scheduleGoalWaitTimer(ctx: StatusContext, goalId: string, wakeAt: number) {
|
|
552
651
|
const generation = this.menuGeneration;
|
|
652
|
+
const session = ctx.sessionManager;
|
|
653
|
+
const sessionId = goalWaitSessionId(session);
|
|
553
654
|
this.goalWaitTimer.schedule(wakeAt, () => {
|
|
554
655
|
if (generation !== this.menuGeneration || this.activeGoal?.id !== goalId || !this.ownsWorkflow(this.activeGoal)) {
|
|
555
656
|
return;
|
|
556
657
|
}
|
|
557
658
|
try {
|
|
659
|
+
if (ctx.sessionManager !== session || goalWaitSessionId(session) !== sessionId) return;
|
|
558
660
|
this.dispatchDueGoalWait(ctx);
|
|
559
661
|
} catch (error) {
|
|
560
662
|
notifyWhenSessionAlive(ctx, `Goal wait deadline failed: ${formatError(error)}`, "error");
|
|
@@ -613,7 +715,7 @@ export class GoalRuntime {
|
|
|
613
715
|
this.clearGoalRecoveryForGoal(goal.id);
|
|
614
716
|
this.clearBudgetWrapUp();
|
|
615
717
|
this.blockStaleGoalToolCalls();
|
|
616
|
-
abortCurrentTurn(ctx);
|
|
718
|
+
this.afterSettingsCommit(ctx, goal.id, () => abortCurrentTurn(ctx));
|
|
617
719
|
status = "paused";
|
|
618
720
|
break;
|
|
619
721
|
case "budget_limit":
|
|
@@ -621,7 +723,7 @@ export class GoalRuntime {
|
|
|
621
723
|
this.clearGoalRecoveryForGoal(goal.id);
|
|
622
724
|
this.clearBudgetWrapUp();
|
|
623
725
|
this.blockStaleGoalToolCalls();
|
|
624
|
-
abortCurrentTurn(ctx);
|
|
726
|
+
this.afterSettingsCommit(ctx, goal.id, () => abortCurrentTurn(ctx));
|
|
625
727
|
status = "budget_limited";
|
|
626
728
|
terminalReason = request.reason;
|
|
627
729
|
break;
|
|
@@ -632,7 +734,7 @@ export class GoalRuntime {
|
|
|
632
734
|
this.blockStaleGoalToolCalls();
|
|
633
735
|
if (request.abortTurn) {
|
|
634
736
|
this.guardAbortGoalId = goal.id;
|
|
635
|
-
abortCurrentTurn(ctx);
|
|
737
|
+
this.afterSettingsCommit(ctx, goal.id, () => abortCurrentTurn(ctx));
|
|
636
738
|
}
|
|
637
739
|
goal = { ...goal, safetyPauseCause: request.cause };
|
|
638
740
|
status = "paused";
|
|
@@ -653,7 +755,7 @@ export class GoalRuntime {
|
|
|
653
755
|
this.clearBudgetWrapUp();
|
|
654
756
|
if (request.abortTurn) {
|
|
655
757
|
this.blockStaleGoalToolCalls();
|
|
656
|
-
abortCurrentTurn(ctx);
|
|
758
|
+
this.afterSettingsCommit(ctx, goal.id, () => abortCurrentTurn(ctx));
|
|
657
759
|
} else {
|
|
658
760
|
this.clearStaleGoalToolCallBlock();
|
|
659
761
|
}
|
|
@@ -672,13 +774,13 @@ export class GoalRuntime {
|
|
|
672
774
|
this.cancelContinuationWork();
|
|
673
775
|
this.clearBudgetWrapUp();
|
|
674
776
|
this.blockStaleGoalToolCalls();
|
|
675
|
-
abortCurrentTurn(ctx);
|
|
777
|
+
this.afterSettingsCommit(ctx, goal.id, () => abortCurrentTurn(ctx));
|
|
676
778
|
status = request.status;
|
|
677
779
|
terminalReason = request.reason;
|
|
678
780
|
break;
|
|
679
781
|
case "activation_rollback":
|
|
680
782
|
goal = request.restoreGoal;
|
|
681
|
-
if (request.abortTurn) abortCurrentTurn(ctx);
|
|
783
|
+
if (request.abortTurn) this.afterSettingsCommit(ctx, goal.id, () => abortCurrentTurn(ctx));
|
|
682
784
|
this.blockStaleGoalToolCalls();
|
|
683
785
|
status = "paused";
|
|
684
786
|
break;
|
|
@@ -688,10 +790,16 @@ export class GoalRuntime {
|
|
|
688
790
|
if (terminalReason !== undefined) this.setTerminalReason(this.activeGoal.id, terminalReason);
|
|
689
791
|
const stoppedGoal = this.activeGoal;
|
|
690
792
|
this.persistGoal(stoppedGoal);
|
|
691
|
-
if (request.kind !== "blocker_report")
|
|
793
|
+
if (request.kind !== "blocker_report") {
|
|
794
|
+
this.afterSettingsCommit(ctx, stoppedGoal.id, () => {
|
|
795
|
+
if (this.activeGoal?.status !== "active") this.ensureInactiveGoalContextContract(ctx);
|
|
796
|
+
});
|
|
797
|
+
}
|
|
692
798
|
if (this.activeGoal?.id === stoppedGoal.id && this.activeGoal.status === stoppedGoal.status) {
|
|
693
799
|
this.updateStatus(ctx, stoppedGoal);
|
|
694
|
-
this.
|
|
800
|
+
this.afterSettingsCommit(ctx, stoppedGoal.id, () => {
|
|
801
|
+
if (this.activeGoal?.status === stoppedGoal.status) this.releaseWorkflow();
|
|
802
|
+
});
|
|
695
803
|
}
|
|
696
804
|
return stoppedGoal;
|
|
697
805
|
}
|
|
@@ -794,10 +902,34 @@ export class GoalRuntime {
|
|
|
794
902
|
|
|
795
903
|
recordAutomaticTurn(ctx: StatusContext, message: unknown) {
|
|
796
904
|
const goal = this.activeGoal;
|
|
797
|
-
if (goal?.status !== "active"
|
|
798
|
-
const candidate = message
|
|
799
|
-
if (
|
|
800
|
-
|
|
905
|
+
if (goal?.status !== "active") return false;
|
|
906
|
+
const candidate = findFinalAssistantMessage([message]);
|
|
907
|
+
if (
|
|
908
|
+
this.agentRunGoalId === goal.id &&
|
|
909
|
+
candidate &&
|
|
910
|
+
candidate.stopReason !== "error" &&
|
|
911
|
+
candidate.stopReason !== "aborted"
|
|
912
|
+
) {
|
|
913
|
+
// A successful native response has recovered, even in a manual-origin run
|
|
914
|
+
// or a tool loop that has not reached agent_end yet. Keep native ownership,
|
|
915
|
+
// but retire the quota-policy scope before settings or model events run.
|
|
916
|
+
if (this.goalRecovery?.goalId === goal.id) this.goalRecovery.usageLimitScope = undefined;
|
|
917
|
+
this.agentRunUsageLimitRetry = undefined;
|
|
918
|
+
}
|
|
919
|
+
if (!this.isAutomaticRunForGoal(goal.id)) return false;
|
|
920
|
+
if (candidate?.stopReason === "aborted") return false;
|
|
921
|
+
const quotaRejected =
|
|
922
|
+
this.agentRunUsageLimitRetry !== undefined &&
|
|
923
|
+
!this.agentRunResponseSeen &&
|
|
924
|
+
!this.agentRunToolAttempted &&
|
|
925
|
+
candidate &&
|
|
926
|
+
isUsageLimitedGoalInterruption(candidate) &&
|
|
927
|
+
(candidate.content ?? []).every((block) => block.type === "text" && block.text.trim() === "");
|
|
928
|
+
this.agentRunResponseSeen = true;
|
|
929
|
+
if (!quotaRejected) {
|
|
930
|
+
this.agentRunUsageLimitRetry = undefined;
|
|
931
|
+
goal.automaticModelTurns = Math.min(Number.MAX_SAFE_INTEGER, goal.automaticModelTurns + 1);
|
|
932
|
+
}
|
|
801
933
|
this.recordGoalUsage(goal, ctx);
|
|
802
934
|
this.persistGoal(goal);
|
|
803
935
|
this.updateStatus(ctx, goal);
|
|
@@ -890,6 +1022,13 @@ export class GoalRuntime {
|
|
|
890
1022
|
stopReason: "error",
|
|
891
1023
|
errorMessage: recovery?.errorMessage,
|
|
892
1024
|
});
|
|
1025
|
+
if (
|
|
1026
|
+
!aborted &&
|
|
1027
|
+
usageLimited &&
|
|
1028
|
+
this.settings.retryUsageLimits &&
|
|
1029
|
+
this.usageLimitRecovery.enter(ctx, recovery?.errorMessage, recovery?.usageLimitScope)
|
|
1030
|
+
)
|
|
1031
|
+
return true;
|
|
893
1032
|
if (!aborted && !usageLimited && recovery && recovery.kind !== "compaction_retry") {
|
|
894
1033
|
// Native post-run work can change limits or tool availability after agent_end.
|
|
895
1034
|
if (
|
|
@@ -1042,6 +1181,7 @@ export class GoalRuntime {
|
|
|
1042
1181
|
}
|
|
1043
1182
|
|
|
1044
1183
|
cancelContinuationWork() {
|
|
1184
|
+
this.usageLimitRecovery.cancel();
|
|
1045
1185
|
this.clearContinuationDispatchTimer();
|
|
1046
1186
|
if (this.continuationDelivery) {
|
|
1047
1187
|
this.rememberCancelledContinuationMarker(this.continuationDelivery);
|
|
@@ -1230,7 +1370,7 @@ export class GoalRuntime {
|
|
|
1230
1370
|
if (preservesOwnedPromptAtTerminalBoundary(prompt, delivery.prompt)) {
|
|
1231
1371
|
this.continuationDelivery = undefined;
|
|
1232
1372
|
this.rememberClaimedContinuationMarker(marker, prompt);
|
|
1233
|
-
return marker.split(":", 1)[0];
|
|
1373
|
+
return { goalId: marker.split(":", 1)[0], usageLimitRetry: delivery.usageLimitRetry };
|
|
1234
1374
|
}
|
|
1235
1375
|
}
|
|
1236
1376
|
const cancelledPrompt = this.cancelledContinuationMarkers.get(marker);
|
|
@@ -1238,7 +1378,7 @@ export class GoalRuntime {
|
|
|
1238
1378
|
this.claimedContinuationMarkers.get(marker) === fingerprint ||
|
|
1239
1379
|
(cancelledPrompt && preservesOwnedPromptAtTerminalBoundary(prompt, cancelledPrompt))
|
|
1240
1380
|
) {
|
|
1241
|
-
return marker.split(":", 1)[0];
|
|
1381
|
+
return { goalId: marker.split(":", 1)[0], usageLimitRetry: undefined };
|
|
1242
1382
|
}
|
|
1243
1383
|
this.cancelContinuationWork();
|
|
1244
1384
|
return undefined;
|
|
@@ -1579,6 +1719,11 @@ export function goalIdRejectionReason(goal: ActiveGoal, requestedGoalId: string)
|
|
|
1579
1719
|
return undefined;
|
|
1580
1720
|
}
|
|
1581
1721
|
|
|
1722
|
+
function goalWaitSessionId(session: unknown): unknown {
|
|
1723
|
+
const manager = session as { getSessionId?: () => unknown } | undefined;
|
|
1724
|
+
return typeof manager?.getSessionId === "function" ? manager.getSessionId() : undefined;
|
|
1725
|
+
}
|
|
1726
|
+
|
|
1582
1727
|
function preservesOwnedPromptAtTerminalBoundary(prompt: string, ownedPrompt: string) {
|
|
1583
1728
|
// Earlier input handlers may prefix a live pi-goal message before this runtime
|
|
1584
1729
|
// can fingerprint it. Require the complete generated prompt as the terminal
|
package/src/settings-ui.ts
CHANGED
|
@@ -33,7 +33,13 @@ export async function showGoalSettings(
|
|
|
33
33
|
const invalid = runtime.settingsLoadIssue?.kind === "invalid";
|
|
34
34
|
const previewGoalIds = new Map<LimitField, string | null>();
|
|
35
35
|
type Screen = "settings" | "automatic" | "no-progress" | "invalid";
|
|
36
|
-
type Action =
|
|
36
|
+
type Action =
|
|
37
|
+
| "open-automatic"
|
|
38
|
+
| "open-no-progress"
|
|
39
|
+
| "choose-automatic"
|
|
40
|
+
| "choose-no-progress"
|
|
41
|
+
| "set-retry-usage-limits"
|
|
42
|
+
| "set-rpc";
|
|
37
43
|
const menu = defineMenu<undefined, Screen, Action, ExtensionCommandContext>({
|
|
38
44
|
start: invalid ? "invalid" : (options.initialScreen ?? "settings"),
|
|
39
45
|
screens: {
|
|
@@ -56,6 +62,15 @@ export async function showGoalSettings(
|
|
|
56
62
|
currentValue: formatNoProgressSettingValue(runtime.settings.continuationLimits.noProgressTurns),
|
|
57
63
|
action: "open-no-progress",
|
|
58
64
|
},
|
|
65
|
+
{
|
|
66
|
+
id: "retryUsageLimits",
|
|
67
|
+
label: "Retry usage limits",
|
|
68
|
+
description:
|
|
69
|
+
"Automatically retry usage limits. Repeated provider requests can incur charges. Billing or credit failures can wait indefinitely. Use a 15-minute fallback without a usable reset time.",
|
|
70
|
+
currentValue: runtime.settings.retryUsageLimits ? "On" : "Off",
|
|
71
|
+
values: ["Off", "On"],
|
|
72
|
+
action: "set-retry-usage-limits",
|
|
73
|
+
},
|
|
59
74
|
{
|
|
60
75
|
id: "rpcEnabled",
|
|
61
76
|
label: "Managed run RPC",
|
|
@@ -76,6 +91,7 @@ export async function showGoalSettings(
|
|
|
76
91
|
`Invalid settings file. Pi-goal is using built-in defaults. Fix ${safeTerminalText(settingsPath)} and run /reload. The file will not be overwritten.`,
|
|
77
92
|
`Automatic-work limit: ${formatAutomaticWork(runtime.settings.continuationLimits.automaticTurns)}`,
|
|
78
93
|
`No-progress guard: ${formatNoProgressProtection(runtime.settings.continuationLimits.noProgressTurns)}`,
|
|
94
|
+
`Retry usage limits: ${runtime.settings.retryUsageLimits ? "On" : "Off"}`,
|
|
79
95
|
`Managed run RPC: ${runtime.settings.rpc.enabled ? "On" : "Off"}`,
|
|
80
96
|
],
|
|
81
97
|
hint: "back",
|
|
@@ -112,6 +128,24 @@ export async function showGoalSettings(
|
|
|
112
128
|
previewGoalIds.get("noProgressTurns") ?? null,
|
|
113
129
|
isMenuCurrent,
|
|
114
130
|
),
|
|
131
|
+
"set-retry-usage-limits": async ({ value }) => {
|
|
132
|
+
const enabled = value === "On";
|
|
133
|
+
if (enabled === runtime.settings.retryUsageLimits) return { kind: "stay" };
|
|
134
|
+
try {
|
|
135
|
+
const next = {
|
|
136
|
+
...structuredClone(runtime.settings),
|
|
137
|
+
retryUsageLimits: enabled,
|
|
138
|
+
} satisfies GoalSettings;
|
|
139
|
+
applyGoalSettings(runtime, next, ctx, {
|
|
140
|
+
save: (settings) => (options.save ?? saveGoalSettings)(settings, settingsPath),
|
|
141
|
+
});
|
|
142
|
+
notifyTerminal(ctx.ui, `Retry usage limits: ${enabled ? "On" : "Off"}.`, "info");
|
|
143
|
+
return { kind: "stay" };
|
|
144
|
+
} catch (error) {
|
|
145
|
+
notifySettingsFailure(ctx, settingsPath, error);
|
|
146
|
+
return { kind: "rejected" };
|
|
147
|
+
}
|
|
148
|
+
},
|
|
115
149
|
"set-rpc": async ({ value }) => {
|
|
116
150
|
const enabled = value === "On";
|
|
117
151
|
if (enabled === runtime.settings.rpc.enabled) return { kind: "stay" };
|
|
@@ -267,24 +301,37 @@ export function applyGoalSettings(
|
|
|
267
301
|
next: GoalSettings,
|
|
268
302
|
ctx: ExtensionCommandContext,
|
|
269
303
|
options: GoalSettingsApplyOptions = {},
|
|
304
|
+
) {
|
|
305
|
+
runtime.withSettingsPublication(() => applyGoalSettingsTransaction(runtime, next, ctx, options));
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function applyGoalSettingsTransaction(
|
|
309
|
+
runtime: GoalRuntime,
|
|
310
|
+
next: GoalSettings,
|
|
311
|
+
ctx: ExtensionCommandContext,
|
|
312
|
+
options: GoalSettingsApplyOptions,
|
|
270
313
|
) {
|
|
271
314
|
const snapshot = runtime.snapshotSettingsApplicationState();
|
|
272
315
|
let fileSaved = false;
|
|
316
|
+
let applyingRuntime = false;
|
|
273
317
|
try {
|
|
274
318
|
runtime.settings = structuredClone(next);
|
|
275
319
|
options.save?.(next);
|
|
276
320
|
fileSaved = options.save !== undefined;
|
|
321
|
+
applyingRuntime = true;
|
|
277
322
|
const activeGoalId = runtime.activeGoal?.id;
|
|
278
323
|
const abortOwnedRun = activeGoalId !== undefined && runtime.agentRunGoalId === activeGoalId;
|
|
279
324
|
const pausedByAutomaticLimit = runtime.enforceAutomaticTurnLimit(ctx, abortOwnedRun);
|
|
280
325
|
if (!pausedByAutomaticLimit) runtime.enforceNoProgressLimit(ctx, abortOwnedRun);
|
|
326
|
+
runtime.usageLimitRecovery.stopIfDisabled(ctx);
|
|
281
327
|
if (runtime.activeGoal) {
|
|
282
328
|
runtime.updateStatus(ctx, runtime.activeGoal);
|
|
283
329
|
}
|
|
284
330
|
} catch (error) {
|
|
285
331
|
const rollbackErrors: unknown[] = [];
|
|
286
332
|
try {
|
|
287
|
-
runtime.restoreSettingsApplicationState(snapshot);
|
|
333
|
+
if (applyingRuntime) runtime.restoreSettingsApplicationState(snapshot);
|
|
334
|
+
else runtime.settings = structuredClone(snapshot.settings);
|
|
288
335
|
} catch (rollbackError) {
|
|
289
336
|
rollbackErrors.push(rollbackError);
|
|
290
337
|
}
|
|
@@ -294,6 +341,8 @@ export function applyGoalSettings(
|
|
|
294
341
|
} catch (rollbackError) {
|
|
295
342
|
rollbackErrors.push(rollbackError);
|
|
296
343
|
}
|
|
344
|
+
}
|
|
345
|
+
if (applyingRuntime) {
|
|
297
346
|
try {
|
|
298
347
|
restorePersistedRuntime(runtime, ctx);
|
|
299
348
|
} catch (rollbackError) {
|
package/src/settings.ts
CHANGED
|
@@ -8,6 +8,7 @@ export const GOAL_SETTINGS_FILE = "pi-goal.json";
|
|
|
8
8
|
export type ContinuationLimit = number | null;
|
|
9
9
|
|
|
10
10
|
export interface GoalSettings {
|
|
11
|
+
retryUsageLimits: boolean;
|
|
11
12
|
rpc: {
|
|
12
13
|
enabled: boolean;
|
|
13
14
|
};
|
|
@@ -18,6 +19,7 @@ export interface GoalSettings {
|
|
|
18
19
|
}
|
|
19
20
|
|
|
20
21
|
export const DEFAULT_GOAL_SETTINGS: GoalSettings = {
|
|
22
|
+
retryUsageLimits: false,
|
|
21
23
|
rpc: { enabled: false },
|
|
22
24
|
continuationLimits: { automaticTurns: 25, noProgressTurns: 3 },
|
|
23
25
|
};
|
|
@@ -39,6 +41,11 @@ interface GoalSettingsSaveFileSystem {
|
|
|
39
41
|
export function normalizeGoalSettings(value: unknown): GoalSettings | undefined {
|
|
40
42
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined;
|
|
41
43
|
|
|
44
|
+
const retryUsageLimits = Object.hasOwn(value, "retryUsageLimits")
|
|
45
|
+
? Reflect.get(value, "retryUsageLimits")
|
|
46
|
+
: DEFAULT_GOAL_SETTINGS.retryUsageLimits;
|
|
47
|
+
if (typeof retryUsageLimits !== "boolean") return undefined;
|
|
48
|
+
|
|
42
49
|
const rpcValue = Object.hasOwn(value, "rpc") ? Reflect.get(value, "rpc") : undefined;
|
|
43
50
|
if (rpcValue !== undefined && (typeof rpcValue !== "object" || rpcValue === null || Array.isArray(rpcValue))) {
|
|
44
51
|
return undefined;
|
|
@@ -75,6 +82,7 @@ export function normalizeGoalSettings(value: unknown): GoalSettings | undefined
|
|
|
75
82
|
if (automaticTurns === undefined || noProgressTurns === undefined) return undefined;
|
|
76
83
|
|
|
77
84
|
return {
|
|
85
|
+
retryUsageLimits,
|
|
78
86
|
rpc: { enabled: rpcEnabled },
|
|
79
87
|
continuationLimits: { automaticTurns, noProgressTurns },
|
|
80
88
|
};
|
|
@@ -113,6 +121,7 @@ export function saveGoalSettings(
|
|
|
113
121
|
const document = `${JSON.stringify(
|
|
114
122
|
{
|
|
115
123
|
...raw,
|
|
124
|
+
retryUsageLimits: normalized.retryUsageLimits,
|
|
116
125
|
rpc: { ...rpc, enabled: normalized.rpc.enabled },
|
|
117
126
|
continuationLimits: {
|
|
118
127
|
...continuationLimits,
|