@narumitw/pi-goal 0.27.0 → 0.27.2
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 +14 -3
- package/package.json +1 -1
- package/src/commands.ts +9 -2
- package/src/goal.ts +31 -7
- package/src/persistence.ts +4 -1
- package/src/queue.ts +2 -1
- package/src/runtime.ts +80 -36
- package/src/safety.ts +16 -0
- package/src/settings.ts +65 -2
package/README.md
CHANGED
|
@@ -54,7 +54,8 @@ pi -e ./extensions/pi-goal
|
|
|
54
54
|
|
|
55
55
|
## ⚙️ Configuration
|
|
56
56
|
|
|
57
|
-
|
|
57
|
+
On the first session start, pi-goal automatically creates `~/.pi/agent/pi-goal.json`
|
|
58
|
+
with the complete current defaults:
|
|
58
59
|
|
|
59
60
|
```json
|
|
60
61
|
{
|
|
@@ -69,6 +70,8 @@ Configuration is optional. Create `~/.pi/agent/pi-goal.json` only when overridin
|
|
|
69
70
|
}
|
|
70
71
|
```
|
|
71
72
|
|
|
73
|
+
Edit this generated file only when overriding the defaults.
|
|
74
|
+
|
|
72
75
|
`toolVisibility` accepts:
|
|
73
76
|
|
|
74
77
|
- `"always"` (default) — pi-goal does not proactively hide `goal_complete` or `goal_blocked`, keeping the tool schema stable from session startup.
|
|
@@ -82,8 +85,16 @@ Configuration is optional. Create `~/.pi/agent/pi-goal.json` only when overridin
|
|
|
82
85
|
- `noProgressTurns` is a positive safe integer and defaults to `3`. At the end of an automatic run, pi-goal compares visible assistant text after Unicode normalization, lowercasing, control-character removal, and whitespace collapse. Thinking and tool blocks are excluded; empty and punctuation-only output are equivalent. Consecutive empty or identical tool-free outputs increment the repeat count. Different non-empty output starts a new run at one, and any attempted tool call resets it. Set this field to `null` to disable only this heuristic.
|
|
83
86
|
|
|
84
87
|
Settings are reread at Pi startup, session replacement, and `/reload`; the file is not watched live.
|
|
85
|
-
|
|
86
|
-
|
|
88
|
+
A missing file is created during any of those session starts, while an existing file is read without
|
|
89
|
+
being rewritten. Initialization publishes the generated file atomically and never overwrites a file
|
|
90
|
+
created concurrently by another process.
|
|
91
|
+
|
|
92
|
+
Omitted fields use the defaults above. Invalid or malformed existing settings are never overwritten;
|
|
93
|
+
they produce a warning and fall back to all defaults. If the default file cannot be created, pi-goal
|
|
94
|
+
warns, continues with the built-in defaults, and retries on the next session start. Reload Pi after
|
|
95
|
+
changing the file. If a live runtime reloads settings, switching `toolVisibility` to `"always"`
|
|
96
|
+
restores only the exact tools that pi-goal previously hid, while switching to
|
|
97
|
+
`"after-first-goal"` locks a runtime that has no unfinished goal.
|
|
87
98
|
|
|
88
99
|
Tool visibility is a baseline, not ownership of Pi's global active-tool list. Plan mode or another restrictive policy may temporarily hide the tools. pi-goal does not fight that policy on restore or on every turn: activation is rejected if both tools cannot be made available, and an already-active goal is paused without automatic continuation if they disappear. The pause aborts a Goal-owned kickoff, resume, active-edit, or automatic-continuation prompt, but it does not cancel or stale-block an unrelated user or extension turn, including startup follow-ups after a restrictive restore.
|
|
89
100
|
|
package/package.json
CHANGED
package/src/commands.ts
CHANGED
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
hasPendingMessages,
|
|
23
23
|
isResumableGoalStatus,
|
|
24
24
|
nextGoalInstance,
|
|
25
|
+
queueGoalSafetyReset,
|
|
25
26
|
STATUS_KEY,
|
|
26
27
|
type StatusContext,
|
|
27
28
|
stoppedStatusLabel,
|
|
@@ -372,7 +373,9 @@ export class GoalCommandController {
|
|
|
372
373
|
this.runtime.clearGoalRecovery();
|
|
373
374
|
this.runtime.clearBudgetWrapUp();
|
|
374
375
|
this.runtime.clearStaleGoalToolCallBlock();
|
|
375
|
-
this.runtime.activeGoal =
|
|
376
|
+
this.runtime.activeGoal = queueGoalSafetyReset(
|
|
377
|
+
transitionGoal(nextGoalInstance(this.runtime.activeGoal), "active"),
|
|
378
|
+
);
|
|
376
379
|
this.runtime.persistGoal(this.runtime.activeGoal);
|
|
377
380
|
this.runtime.updateStatus(ctx, this.runtime.activeGoal);
|
|
378
381
|
if (this.runtime.activeGoal.status !== "active") {
|
|
@@ -444,7 +447,7 @@ export class GoalCommandController {
|
|
|
444
447
|
this.runtime.clearBudgetWrapUp();
|
|
445
448
|
const previousStatus = this.runtime.activeGoal.status;
|
|
446
449
|
const rotatedGoal = nextGoalInstance(this.runtime.activeGoal);
|
|
447
|
-
const
|
|
450
|
+
const transitionedGoal = transitionGoal(
|
|
448
451
|
{
|
|
449
452
|
...rotatedGoal,
|
|
450
453
|
text: objective,
|
|
@@ -452,6 +455,10 @@ export class GoalCommandController {
|
|
|
452
455
|
},
|
|
453
456
|
editedGoalStatus(previousStatus),
|
|
454
457
|
);
|
|
458
|
+
const nextGoal =
|
|
459
|
+
transitionedGoal.status === "active"
|
|
460
|
+
? queueGoalSafetyReset(transitionedGoal)
|
|
461
|
+
: transitionedGoal;
|
|
455
462
|
const goalToolVisibilityBeforeActivation =
|
|
456
463
|
nextGoal.status === "active" ? this.runtime.snapshotGoalToolVisibility() : undefined;
|
|
457
464
|
if (nextGoal.status === "active") {
|
package/src/goal.ts
CHANGED
|
@@ -30,7 +30,7 @@ import {
|
|
|
30
30
|
truncateNotification,
|
|
31
31
|
} from "./runtime.js";
|
|
32
32
|
import { hasAssistantToolCall } from "./safety.js";
|
|
33
|
-
import { DEFAULT_GOAL_SETTINGS,
|
|
33
|
+
import { DEFAULT_GOAL_SETTINGS, loadOrCreateGoalSettings } from "./settings.js";
|
|
34
34
|
|
|
35
35
|
// goal.ts is the Pi-facing composition root: it keeps tool contracts and event
|
|
36
36
|
// ordering together. Per-session mechanisms live in runtime.ts, while user command
|
|
@@ -52,6 +52,7 @@ interface GoalBlockedDetails {
|
|
|
52
52
|
|
|
53
53
|
interface GoalOptions {
|
|
54
54
|
settingsPath?: string;
|
|
55
|
+
settingsFileSystem?: Parameters<typeof loadOrCreateGoalSettings>[1];
|
|
55
56
|
}
|
|
56
57
|
|
|
57
58
|
const EXPERIMENTAL_GOALS_WARNING =
|
|
@@ -472,7 +473,10 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
|
|
|
472
473
|
runtime.clearTerminalDetails();
|
|
473
474
|
rpc.bindSession(ctx);
|
|
474
475
|
const previousToolVisibility = runtime.settings.toolVisibility;
|
|
475
|
-
const settingsResult =
|
|
476
|
+
const settingsResult = loadOrCreateGoalSettings(
|
|
477
|
+
options.settingsPath,
|
|
478
|
+
options.settingsFileSystem,
|
|
479
|
+
);
|
|
476
480
|
runtime.settings =
|
|
477
481
|
settingsResult.kind === "loaded" ? settingsResult.settings : DEFAULT_GOAL_SETTINGS;
|
|
478
482
|
if (settingsResult.kind === "invalid") {
|
|
@@ -480,6 +484,11 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
|
|
|
480
484
|
`pi-goal settings ignored: ${settingsResult.reason}. Using default settings.`,
|
|
481
485
|
"warning",
|
|
482
486
|
);
|
|
487
|
+
} else if (settingsResult.kind === "create-failed") {
|
|
488
|
+
ctx.ui.notify(
|
|
489
|
+
`Could not create pi-goal settings: ${settingsResult.reason}. Using default settings.`,
|
|
490
|
+
"warning",
|
|
491
|
+
);
|
|
483
492
|
}
|
|
484
493
|
if (runtime.settings.experimental.goals) {
|
|
485
494
|
ctx.ui.notify(EXPERIMENTAL_GOALS_WARNING, "warning");
|
|
@@ -526,6 +535,11 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
|
|
|
526
535
|
}
|
|
527
536
|
if (runtime.pendingQueueAction) await dispatchPendingQueueActionIfSettled(ctx);
|
|
528
537
|
if (runtime.activeGoal) {
|
|
538
|
+
if (runtime.activeGoal.status === "active" && runtime.activeGoal.safetyResetPending) {
|
|
539
|
+
// Resume/edit activation is persisted before its queued prompt starts. A
|
|
540
|
+
// reload must commit that promised reset before enforcing the old limits.
|
|
541
|
+
runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
|
|
542
|
+
}
|
|
529
543
|
if (runtime.activeGoal.status === "active") {
|
|
530
544
|
updateGoalUsage(runtime.activeGoal, ctx);
|
|
531
545
|
if (limitActiveGoalForBudget(ctx, false)) return;
|
|
@@ -688,6 +702,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
|
|
|
688
702
|
return;
|
|
689
703
|
}
|
|
690
704
|
if (message.role === "custom") {
|
|
705
|
+
if (runtime.isActiveBudgetWrapUpMessage(message)) return;
|
|
691
706
|
if (runtime.guardAbortGoalId === runtime.activeGoal?.id) {
|
|
692
707
|
runtime.guardAbortGoalId = undefined;
|
|
693
708
|
}
|
|
@@ -697,15 +712,18 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
|
|
|
697
712
|
if (message.role !== "user") return;
|
|
698
713
|
const prompt = Array.isArray(message.content)
|
|
699
714
|
? message.content
|
|
700
|
-
.filter(
|
|
715
|
+
.filter(
|
|
716
|
+
(part) => part && typeof part === "object" && Reflect.get(part, "type") === "text",
|
|
717
|
+
)
|
|
701
718
|
.map((part) => Reflect.get(part as object, "text"))
|
|
702
719
|
.filter((text): text is string => typeof text === "string")
|
|
703
720
|
.join("\n")
|
|
704
721
|
: typeof message.content === "string"
|
|
705
722
|
? message.content
|
|
706
723
|
: "";
|
|
707
|
-
const queuedNonGoalInput = runtime.consumeQueuedNonGoalInput(prompt);
|
|
708
724
|
const ownedPrompt = consumePendingGoalPrompt(prompt);
|
|
725
|
+
const ownedPromptBoundary = runtime.hasOwnedPromptBoundary(prompt);
|
|
726
|
+
const queuedNonGoalInput = runtime.consumeQueuedNonGoalInput(prompt, !ownedPromptBoundary);
|
|
709
727
|
if (!ownedPrompt) {
|
|
710
728
|
if (queuedNonGoalInput?.behavior === "followUp") {
|
|
711
729
|
beginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);
|
|
@@ -808,12 +826,18 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
|
|
|
808
826
|
const goalPromptGoalId = goalPrompt?.goalId;
|
|
809
827
|
const continuationGoalId = goalPromptGoalId ? undefined : markContinuationStarted(event.prompt);
|
|
810
828
|
const ownedPromptGoalId = goalPromptGoalId ?? continuationGoalId;
|
|
829
|
+
const ownedPromptBoundary = runtime.hasOwnedPromptBoundary(event.prompt);
|
|
811
830
|
const activeBudgetWrapUp = runtime.hasActiveBudgetWrapUp();
|
|
812
|
-
const
|
|
831
|
+
const activeGoalRecovery = runtime.hasActiveGoalRecovery();
|
|
832
|
+
const queuedNonGoalInput = activeBudgetWrapUp
|
|
833
|
+
? undefined
|
|
834
|
+
: runtime.consumeQueuedNonGoalInput(
|
|
835
|
+
event.prompt,
|
|
836
|
+
!activeGoalRecovery && ownedPromptGoalId === undefined && !ownedPromptBoundary,
|
|
837
|
+
);
|
|
813
838
|
if (queuedNonGoalInput?.behavior === "followUp") {
|
|
814
839
|
beginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);
|
|
815
840
|
}
|
|
816
|
-
const activeGoalRecovery = runtime.hasActiveGoalRecovery();
|
|
817
841
|
const runOrigin = continuationGoalId
|
|
818
842
|
? "automatic"
|
|
819
843
|
: activeGoalRecovery && runtime.goalRecovery?.automaticOwner
|
|
@@ -878,7 +902,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
|
|
|
878
902
|
};
|
|
879
903
|
});
|
|
880
904
|
|
|
881
|
-
pi.on("agent_start", (_event,
|
|
905
|
+
pi.on("agent_start", (_event, _ctx) => {
|
|
882
906
|
if (runtime.queueFrozen) return;
|
|
883
907
|
const activeGoal = runtime.activeGoal;
|
|
884
908
|
if (
|
package/src/persistence.ts
CHANGED
|
@@ -33,6 +33,7 @@ export interface ActiveGoal {
|
|
|
33
33
|
toolFreeRepeatCount: number;
|
|
34
34
|
lastToolFreeOutputFingerprint?: string;
|
|
35
35
|
safetyPauseCause?: SafetyPauseCause;
|
|
36
|
+
safetyResetPending?: boolean;
|
|
36
37
|
}
|
|
37
38
|
|
|
38
39
|
export type PendingQueueAction =
|
|
@@ -235,6 +236,7 @@ export function normalizeLoadedGoal(goal: ActiveGoal): ActiveGoal {
|
|
|
235
236
|
toolFreeRepeatCount: normalizeSafetyCounter(goal.toolFreeRepeatCount),
|
|
236
237
|
lastToolFreeOutputFingerprint: normalizeOutputFingerprint(goal.lastToolFreeOutputFingerprint),
|
|
237
238
|
safetyPauseCause: normalizeSafetyPauseCause(goal.safetyPauseCause),
|
|
239
|
+
safetyResetPending: goal.safetyResetPending === true ? true : undefined,
|
|
238
240
|
};
|
|
239
241
|
}
|
|
240
242
|
|
|
@@ -292,7 +294,8 @@ function isGoal(value: unknown): value is ActiveGoal {
|
|
|
292
294
|
typeof value.tokensUsed === "number" &&
|
|
293
295
|
typeof value.timeUsedSeconds === "number" &&
|
|
294
296
|
typeof value.baselineTokens === "number" &&
|
|
295
|
-
(value.activeStartedAt === undefined || typeof value.activeStartedAt === "number")
|
|
297
|
+
(value.activeStartedAt === undefined || typeof value.activeStartedAt === "number") &&
|
|
298
|
+
(value.safetyResetPending === undefined || typeof value.safetyResetPending === "boolean")
|
|
296
299
|
);
|
|
297
300
|
}
|
|
298
301
|
|
package/src/queue.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import { checkpointGoalActiveTime } from "./accounting.js";
|
|
3
3
|
import type { ActiveGoal } from "./persistence.js";
|
|
4
|
+
import { resetGoalSafetyEpoch } from "./safety.js";
|
|
4
5
|
|
|
5
6
|
export interface GoalQueueResult {
|
|
6
7
|
goal: ActiveGoal | undefined;
|
|
@@ -94,5 +95,5 @@ export function activateQueuedGoal(
|
|
|
94
95
|
if (activated.tokenBudget !== undefined && activated.tokensUsed >= activated.tokenBudget) {
|
|
95
96
|
return { ...activated, status: "budget_limited", activeStartedAt: undefined };
|
|
96
97
|
}
|
|
97
|
-
return activated;
|
|
98
|
+
return activated.safetyResetPending ? resetGoalSafetyEpoch(activated) : activated;
|
|
98
99
|
}
|
package/src/runtime.ts
CHANGED
|
@@ -20,7 +20,10 @@ import {
|
|
|
20
20
|
serializeGoalState,
|
|
21
21
|
} from "./persistence.js";
|
|
22
22
|
import { buildContinuePrompt, type GoalStatus } from "./prompts.js";
|
|
23
|
-
import { nextToolFreeRepeatState } from "./safety.js";
|
|
23
|
+
import { nextToolFreeRepeatState, resetGoalSafetyEpoch } from "./safety.js";
|
|
24
|
+
|
|
25
|
+
export { queueGoalSafetyReset, resetGoalSafetyEpoch } from "./safety.js";
|
|
26
|
+
|
|
24
27
|
import { DEFAULT_GOAL_SETTINGS, type GoalSettings } from "./settings.js";
|
|
25
28
|
|
|
26
29
|
export interface ContinuationTicket {
|
|
@@ -167,7 +170,9 @@ export class GoalRuntime {
|
|
|
167
170
|
/** Exact lazy goal tools this runtime removed and may restore on a mode change. */
|
|
168
171
|
goalToolsHiddenByPolicy = new Set<string>();
|
|
169
172
|
pendingGoalPromptMarkers = new Map<string, PendingGoalPrompt>();
|
|
173
|
+
claimedGoalPromptMarkers = new Set<string>();
|
|
170
174
|
cancelledContinuationMarkers = new Set<string>();
|
|
175
|
+
claimedContinuationMarkers = new Set<string>();
|
|
171
176
|
pendingNonGoalInputs: PendingNonGoalInput[] = [];
|
|
172
177
|
|
|
173
178
|
readonly pi: ExtensionAPI;
|
|
@@ -340,23 +345,31 @@ export class GoalRuntime {
|
|
|
340
345
|
this.terminalDetails = undefined;
|
|
341
346
|
}
|
|
342
347
|
|
|
343
|
-
|
|
344
|
-
if (!message || typeof message !== "object") return
|
|
348
|
+
isActiveBudgetWrapUpMessage(message: unknown) {
|
|
349
|
+
if (!message || typeof message !== "object") return false;
|
|
345
350
|
const candidate = message as {
|
|
346
351
|
role?: unknown;
|
|
347
352
|
customType?: unknown;
|
|
348
353
|
details?: { goalId?: unknown };
|
|
349
354
|
};
|
|
350
|
-
if (candidate.role !== "custom" || candidate.customType !== BUDGET_WRAP_UP_MESSAGE_TYPE) {
|
|
351
|
-
return true;
|
|
352
|
-
}
|
|
353
355
|
return (
|
|
356
|
+
candidate.role === "custom" &&
|
|
357
|
+
candidate.customType === BUDGET_WRAP_UP_MESSAGE_TYPE &&
|
|
354
358
|
typeof candidate.details?.goalId === "string" &&
|
|
355
359
|
candidate.details.goalId === this.budgetWrapUp?.goalId &&
|
|
356
360
|
candidate.details.goalId === this.activeGoal?.id
|
|
357
361
|
);
|
|
358
362
|
}
|
|
359
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
|
+
|
|
360
373
|
queueBudgetWrapUp(ctx: StatusContext, goal: ActiveGoal) {
|
|
361
374
|
if (!this.budgetWrapUp || this.budgetWrapUp.goalId !== goal.id) {
|
|
362
375
|
this.budgetWrapUp = { goalId: goal.id, delivered: false };
|
|
@@ -520,6 +533,8 @@ export class GoalRuntime {
|
|
|
520
533
|
clearSettledSafetyTracking() {
|
|
521
534
|
this.guardAbortGoalId = undefined;
|
|
522
535
|
this.pendingNonGoalInputs = [];
|
|
536
|
+
this.claimedGoalPromptMarkers.clear();
|
|
537
|
+
this.claimedContinuationMarkers.clear();
|
|
523
538
|
this.clearAgentRun();
|
|
524
539
|
}
|
|
525
540
|
|
|
@@ -541,10 +556,12 @@ export class GoalRuntime {
|
|
|
541
556
|
this.continuationIntent = undefined;
|
|
542
557
|
this.continuationDelivery = undefined;
|
|
543
558
|
this.cancelledContinuationMarkers.clear();
|
|
559
|
+
this.claimedContinuationMarkers.clear();
|
|
544
560
|
}
|
|
545
561
|
|
|
546
562
|
clearPendingGoalPrompts() {
|
|
547
563
|
this.pendingGoalPromptMarkers.clear();
|
|
564
|
+
this.claimedGoalPromptMarkers.clear();
|
|
548
565
|
this.pendingNonGoalInputs = [];
|
|
549
566
|
}
|
|
550
567
|
|
|
@@ -578,6 +595,23 @@ export class GoalRuntime {
|
|
|
578
595
|
return marker ? this.pendingGoalPromptMarkers.has(marker) : false;
|
|
579
596
|
}
|
|
580
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
|
+
|
|
581
615
|
consumeStaleOwnedGoalPrompt(prompt: string) {
|
|
582
616
|
const marker = extractGoalPromptMarker(prompt);
|
|
583
617
|
if (!marker) return false;
|
|
@@ -595,11 +629,7 @@ export class GoalRuntime {
|
|
|
595
629
|
return true;
|
|
596
630
|
}
|
|
597
631
|
|
|
598
|
-
noteQueuedNonGoalInput(
|
|
599
|
-
prompt: string,
|
|
600
|
-
behavior: "steer" | "followUp",
|
|
601
|
-
resetSafetyEpoch = false,
|
|
602
|
-
) {
|
|
632
|
+
noteQueuedNonGoalInput(prompt: string, behavior: "steer" | "followUp", resetSafetyEpoch = false) {
|
|
603
633
|
this.pendingNonGoalInputs.push({
|
|
604
634
|
behavior,
|
|
605
635
|
fingerprint: inputFingerprint(prompt),
|
|
@@ -610,7 +640,7 @@ export class GoalRuntime {
|
|
|
610
640
|
}
|
|
611
641
|
}
|
|
612
642
|
|
|
613
|
-
consumeQueuedNonGoalInput(prompt: string) {
|
|
643
|
+
consumeQueuedNonGoalInput(prompt: string, allowDeliveryFallback = true) {
|
|
614
644
|
if (typeof prompt !== "string") return undefined;
|
|
615
645
|
const fingerprint = inputFingerprint(prompt);
|
|
616
646
|
// Pi delivers steers before follow-ups. Prefer a matching steer even when an
|
|
@@ -618,24 +648,34 @@ export class GoalRuntime {
|
|
|
618
648
|
const steerIndex = this.pendingNonGoalInputs.findIndex(
|
|
619
649
|
(pending) => pending.behavior === "steer" && pending.fingerprint === fingerprint,
|
|
620
650
|
);
|
|
621
|
-
const
|
|
651
|
+
const exactIndex =
|
|
622
652
|
steerIndex >= 0
|
|
623
653
|
? steerIndex
|
|
624
654
|
: this.pendingNonGoalInputs.findIndex(
|
|
625
|
-
(pending) =>
|
|
626
|
-
pending.behavior === "followUp" && pending.fingerprint === fingerprint,
|
|
655
|
+
(pending) => pending.behavior === "followUp" && pending.fingerprint === fingerprint,
|
|
627
656
|
);
|
|
628
|
-
if (
|
|
629
|
-
|
|
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];
|
|
630
672
|
}
|
|
631
673
|
|
|
632
674
|
consumeQueuedNonGoalFollowUpForAgentStart() {
|
|
633
675
|
// A pending steer owns the next intra-run boundary. Do not let a later
|
|
634
676
|
// follow-up suppress cleanup until all earlier-priority steers have started.
|
|
635
677
|
if (this.pendingNonGoalInputs.some((pending) => pending.behavior === "steer")) return false;
|
|
636
|
-
const index = this.pendingNonGoalInputs.findIndex(
|
|
637
|
-
(pending) => pending.behavior === "followUp",
|
|
638
|
-
);
|
|
678
|
+
const index = this.pendingNonGoalInputs.findIndex((pending) => pending.behavior === "followUp");
|
|
639
679
|
if (index < 0) return false;
|
|
640
680
|
this.pendingNonGoalInputs.splice(index, 1);
|
|
641
681
|
return true;
|
|
@@ -650,7 +690,10 @@ export class GoalRuntime {
|
|
|
650
690
|
this.cancelContinuationWork();
|
|
651
691
|
return undefined;
|
|
652
692
|
}
|
|
653
|
-
if (this.continuationDelivery?.marker === marker)
|
|
693
|
+
if (this.continuationDelivery?.marker === marker) {
|
|
694
|
+
this.continuationDelivery = undefined;
|
|
695
|
+
this.rememberClaimedContinuationMarker(marker);
|
|
696
|
+
}
|
|
654
697
|
return marker.split(":", 1)[0];
|
|
655
698
|
}
|
|
656
699
|
|
|
@@ -840,11 +883,7 @@ export class GoalRuntime {
|
|
|
840
883
|
this.completionStatusTimer = undefined;
|
|
841
884
|
}
|
|
842
885
|
|
|
843
|
-
private rememberPendingGoalPrompt(
|
|
844
|
-
goalId: string,
|
|
845
|
-
prompt: string,
|
|
846
|
-
resetSafetyEpoch: boolean,
|
|
847
|
-
) {
|
|
886
|
+
private rememberPendingGoalPrompt(goalId: string, prompt: string, resetSafetyEpoch: boolean) {
|
|
848
887
|
const marker = randomUUID();
|
|
849
888
|
this.pendingGoalPromptMarkers.set(marker, { goalId, resetSafetyEpoch });
|
|
850
889
|
if (this.pendingGoalPromptMarkers.size > MAX_PENDING_GOAL_PROMPTS) {
|
|
@@ -859,9 +898,24 @@ export class GoalRuntime {
|
|
|
859
898
|
if (!marker) return undefined;
|
|
860
899
|
const pending = this.pendingGoalPromptMarkers.get(marker);
|
|
861
900
|
this.pendingGoalPromptMarkers.delete(marker);
|
|
901
|
+
if (pending) this.rememberClaimedGoalPromptMarker(marker);
|
|
862
902
|
return pending;
|
|
863
903
|
}
|
|
864
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);
|
|
917
|
+
}
|
|
918
|
+
|
|
865
919
|
consumeOwnedGoalPrompt(prompt: string) {
|
|
866
920
|
return this.consumePendingGoalPrompt(prompt);
|
|
867
921
|
}
|
|
@@ -914,16 +968,6 @@ export function nextGoalInstance(goal: ActiveGoal): ActiveGoal {
|
|
|
914
968
|
return { ...goal, id: randomUUID(), updatedAt: Date.now() };
|
|
915
969
|
}
|
|
916
970
|
|
|
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
|
-
|
|
927
971
|
export function editedGoalStatus(status: GoalStatus): GoalStatus {
|
|
928
972
|
if (status === "paused" || status === "blocked" || status === "usage_limited") return status;
|
|
929
973
|
return "active";
|
package/src/safety.ts
CHANGED
|
@@ -1,10 +1,26 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
+
import type { ActiveGoal } from "./persistence.js";
|
|
2
3
|
|
|
3
4
|
export interface ToolFreeRepeatState {
|
|
4
5
|
toolFreeRepeatCount: number;
|
|
5
6
|
lastToolFreeOutputFingerprint?: string;
|
|
6
7
|
}
|
|
7
8
|
|
|
9
|
+
export function queueGoalSafetyReset(goal: ActiveGoal): ActiveGoal {
|
|
10
|
+
return { ...goal, safetyResetPending: true };
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function resetGoalSafetyEpoch(goal: ActiveGoal): ActiveGoal {
|
|
14
|
+
return {
|
|
15
|
+
...goal,
|
|
16
|
+
automaticModelTurns: 0,
|
|
17
|
+
toolFreeRepeatCount: 0,
|
|
18
|
+
lastToolFreeOutputFingerprint: undefined,
|
|
19
|
+
safetyPauseCause: undefined,
|
|
20
|
+
safetyResetPending: undefined,
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
|
|
8
24
|
export function nextToolFreeRepeatState(
|
|
9
25
|
current: ToolFreeRepeatState,
|
|
10
26
|
messages: readonly unknown[],
|
package/src/settings.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { linkSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { basename, dirname, join } from "node:path";
|
|
3
4
|
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
4
5
|
|
|
5
6
|
export const GOAL_SETTINGS_FILE = "pi-goal.json";
|
|
@@ -25,11 +26,24 @@ export const DEFAULT_GOAL_SETTINGS: GoalSettings = {
|
|
|
25
26
|
continuationLimits: { automaticTurns: 25, noProgressTurns: 3 },
|
|
26
27
|
};
|
|
27
28
|
|
|
29
|
+
export const DEFAULT_GOAL_SETTINGS_DOCUMENT = `${JSON.stringify(DEFAULT_GOAL_SETTINGS, null, 2)}\n`;
|
|
30
|
+
|
|
28
31
|
export type GoalSettingsLoadResult =
|
|
29
32
|
| { kind: "missing" }
|
|
30
33
|
| { kind: "invalid"; reason: string }
|
|
31
34
|
| { kind: "loaded"; settings: GoalSettings };
|
|
32
35
|
|
|
36
|
+
export type GoalSettingsInitializationResult =
|
|
37
|
+
| Exclude<GoalSettingsLoadResult, { kind: "missing" }>
|
|
38
|
+
| { kind: "create-failed"; reason: string };
|
|
39
|
+
|
|
40
|
+
interface GoalSettingsInitializationFileSystem {
|
|
41
|
+
mkdirSync: typeof mkdirSync;
|
|
42
|
+
writeFileSync: typeof writeFileSync;
|
|
43
|
+
linkSync: typeof linkSync;
|
|
44
|
+
rmSync: typeof rmSync;
|
|
45
|
+
}
|
|
46
|
+
|
|
33
47
|
export function normalizeGoalSettings(value: unknown): GoalSettings | undefined {
|
|
34
48
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined;
|
|
35
49
|
const toolVisibility = Object.hasOwn(value, "toolVisibility")
|
|
@@ -95,6 +109,51 @@ function normalizeContinuationLimit(
|
|
|
95
109
|
return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;
|
|
96
110
|
}
|
|
97
111
|
|
|
112
|
+
export function loadOrCreateGoalSettings(
|
|
113
|
+
settingsPath = join(getAgentDir(), GOAL_SETTINGS_FILE),
|
|
114
|
+
overrides: Partial<GoalSettingsInitializationFileSystem> = {},
|
|
115
|
+
): GoalSettingsInitializationResult {
|
|
116
|
+
const loaded = readGoalSettings(settingsPath);
|
|
117
|
+
if (loaded.kind !== "missing") return loaded;
|
|
118
|
+
|
|
119
|
+
const fs = { mkdirSync, writeFileSync, linkSync, rmSync, ...overrides };
|
|
120
|
+
const temporaryPath = join(
|
|
121
|
+
dirname(settingsPath),
|
|
122
|
+
`.${basename(settingsPath)}.${randomUUID()}.tmp`,
|
|
123
|
+
);
|
|
124
|
+
try {
|
|
125
|
+
fs.mkdirSync(dirname(settingsPath), { recursive: true });
|
|
126
|
+
fs.writeFileSync(temporaryPath, DEFAULT_GOAL_SETTINGS_DOCUMENT, {
|
|
127
|
+
encoding: "utf8",
|
|
128
|
+
flag: "wx",
|
|
129
|
+
});
|
|
130
|
+
try {
|
|
131
|
+
fs.linkSync(temporaryPath, settingsPath);
|
|
132
|
+
} catch (error) {
|
|
133
|
+
if (!isAlreadyExistsError(error)) throw error;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const published = readGoalSettings(settingsPath);
|
|
137
|
+
return published.kind === "missing"
|
|
138
|
+
? {
|
|
139
|
+
kind: "create-failed",
|
|
140
|
+
reason: `${settingsPath}: settings file disappeared during initialization`,
|
|
141
|
+
}
|
|
142
|
+
: published;
|
|
143
|
+
} catch (error) {
|
|
144
|
+
return {
|
|
145
|
+
kind: "create-failed",
|
|
146
|
+
reason: `${settingsPath}: ${formatError(error)}`,
|
|
147
|
+
};
|
|
148
|
+
} finally {
|
|
149
|
+
try {
|
|
150
|
+
fs.rmSync(temporaryPath, { force: true });
|
|
151
|
+
} catch {
|
|
152
|
+
// Best-effort cleanup must not replace the initialization result.
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
98
157
|
export function readGoalSettings(
|
|
99
158
|
settingsPath = join(getAgentDir(), GOAL_SETTINGS_FILE),
|
|
100
159
|
): GoalSettingsLoadResult {
|
|
@@ -120,6 +179,10 @@ function isNodeError(error: unknown): error is NodeJS.ErrnoException {
|
|
|
120
179
|
return error instanceof Error && "code" in error;
|
|
121
180
|
}
|
|
122
181
|
|
|
182
|
+
function isAlreadyExistsError(error: unknown): boolean {
|
|
183
|
+
return isNodeError(error) && error.code === "EEXIST";
|
|
184
|
+
}
|
|
185
|
+
|
|
123
186
|
function formatError(error: unknown) {
|
|
124
187
|
return error instanceof Error ? error.message : String(error);
|
|
125
188
|
}
|