@narumitw/pi-goal 0.48.0 → 0.49.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.
@@ -1,6 +1,5 @@
1
1
  import { join } from "node:path";
2
2
  import { type ExtensionCommandContext, getAgentDir } from "@earendil-works/pi-coding-agent";
3
- import { defineMenu, runMenu } from "@narumitw/pi-tui-kit";
4
3
  import { checkpointGoalActiveTime } from "./accounting.js";
5
4
  import { abortCurrentTurn, type GoalRuntime, STATUS_KEY } from "./runtime.js";
6
5
  import {
@@ -12,6 +11,7 @@ import {
12
11
 
13
12
  interface GoalSettingsUiOptions {
14
13
  settingsPath?: string;
14
+ initialScreen?: "settings" | "automatic";
15
15
  save?: (settings: GoalSettings, settingsPath: string) => void;
16
16
  onQueueUnfrozen?: (ctx: ExtensionCommandContext) => Promise<void>;
17
17
  }
@@ -33,6 +33,10 @@ export async function showGoalSettings(
33
33
  return;
34
34
  }
35
35
  const generation = runtime.menuGeneration;
36
+ const isMenuCurrent = () =>
37
+ generation === runtime.menuGeneration && !runtime.menuController.signal.aborted;
38
+ const { defineMenu, runMenu } = await import("@narumitw/pi-tui-kit");
39
+ if (!isMenuCurrent()) return;
36
40
  const invalid = runtime.settingsLoadIssue?.kind === "invalid";
37
41
  const previewGoalIds = new Map<LimitField, string | null>();
38
42
  type Screen = "settings" | "automatic" | "no-progress" | "invalid";
@@ -45,7 +49,7 @@ export async function showGoalSettings(
45
49
  | "set-queue"
46
50
  | "set-rpc";
47
51
  const menu = defineMenu<undefined, Screen, Action, ExtensionCommandContext>({
48
- start: invalid ? "invalid" : "settings",
52
+ start: invalid ? "invalid" : (options.initialScreen ?? "settings"),
49
53
  screens: {
50
54
  settings: () => ({
51
55
  kind: "settings",
@@ -54,8 +58,8 @@ export async function showGoalSettings(
54
58
  items: [
55
59
  {
56
60
  id: "automaticTurns",
57
- label: "Automatic work",
58
- description: "Choose whether Goal can continue without a response-count cap.",
61
+ label: "Automatic-work limit",
62
+ description: "Pause automatic Goal work after a visible number of model responses.",
59
63
  currentValue: formatAutomaticSettingValue(
60
64
  runtime.settings.continuationLimits.automaticTurns,
61
65
  ),
@@ -104,7 +108,7 @@ export async function showGoalSettings(
104
108
  title: "Pi Goal Settings · Read only",
105
109
  lines: [
106
110
  `Invalid settings file. Pi-goal is using built-in defaults. Fix ${safeTerminalText(settingsPath)} and run /reload. The file will not be overwritten.`,
107
- `Automatic work: ${formatAutomaticWork(runtime.settings.continuationLimits.automaticTurns)}`,
111
+ `Automatic-work limit: ${formatAutomaticWork(runtime.settings.continuationLimits.automaticTurns)}`,
108
112
  `No-progress guard: ${formatNoProgressProtection(runtime.settings.continuationLimits.noProgressTurns)}`,
109
113
  `Goal tools: ${visibilityLabel(runtime.settings.toolVisibility)}`,
110
114
  `Ordered goal queue: ${runtime.settings.experimental.goals ? "Experimental" : "Off"}`,
@@ -131,6 +135,7 @@ export async function showGoalSettings(
131
135
  "automaticTurns",
132
136
  itemId,
133
137
  previewGoalIds.get("automaticTurns") ?? null,
138
+ isMenuCurrent,
134
139
  ),
135
140
  "choose-no-progress": async ({ itemId }) =>
136
141
  applyLimitChoice(
@@ -141,6 +146,7 @@ export async function showGoalSettings(
141
146
  "noProgressTurns",
142
147
  itemId,
143
148
  previewGoalIds.get("noProgressTurns") ?? null,
149
+ isMenuCurrent,
144
150
  ),
145
151
  "set-visibility": async ({ value }) => {
146
152
  const nextVisibility = value === "Always" ? "always" : "after-first-goal";
@@ -210,8 +216,7 @@ export async function showGoalSettings(
210
216
  await runMenu(ctx, menu, {
211
217
  getState: () => undefined,
212
218
  signal: runtime.menuController.signal,
213
- isCurrent: () =>
214
- generation === runtime.menuGeneration && !runtime.menuController.signal.aborted,
219
+ isCurrent: isMenuCurrent,
215
220
  });
216
221
  }
217
222
 
@@ -224,11 +229,16 @@ function limitChoiceScreen(
224
229
  const goal = runtime.activeGoal;
225
230
  return {
226
231
  kind: "actions" as const,
227
- title: field === "automaticTurns" ? "Automatic work" : "No-progress guard",
232
+ title: field === "automaticTurns" ? "Automatic-work limit" : "No-progress guard",
228
233
  lines: [
229
234
  field === "automaticTurns"
230
235
  ? `Current: ${formatAutomaticWork(value)}`
231
236
  : `Current: ${formatNoProgressProtection(value)}`,
237
+ ...(field === "automaticTurns"
238
+ ? [
239
+ `Set a whole-number response limit for each automatic-work epoch. Default: ${DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns}.`,
240
+ ]
241
+ : []),
232
242
  ...(goal
233
243
  ? [
234
244
  field === "automaticTurns"
@@ -260,12 +270,12 @@ function limitChoices(
260
270
  ? `Remove the current ${value}-response cap. Goal work will have no response-count cap; other configured stop conditions remain.`
261
271
  : `Remove the current ${value}-response cap. The active goal has used ${automaticTurnsUsed} responses; other configured stop conditions remain.`;
262
272
  return [
263
- { value: "unlimited", label: "Unlimited (default)", description: unlimitedDescription },
264
273
  {
265
274
  value: "custom",
266
- label: "Set a maximum…",
267
- description: "Pause after a whole number of Goal-owned automatic responses.",
275
+ label: "Set response limit…",
276
+ description: `Choose a whole-number response limit for each automatic-work epoch. Default: ${DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns}.`,
268
277
  },
278
+ { value: "unlimited", label: "Unlimited…", description: unlimitedDescription },
269
279
  ];
270
280
  }
271
281
  const defaultLimit = DEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns;
@@ -296,8 +306,9 @@ async function applyLimitChoice(
296
306
  field: LimitField,
297
307
  itemId: string,
298
308
  activeGoalId: string | null,
309
+ isCurrent: () => boolean,
299
310
  ) {
300
- if (!isLimitSelection(itemId)) return { kind: "rejected" as const };
311
+ if (!isCurrent() || !isLimitSelection(itemId)) return { kind: "rejected" as const };
301
312
  if ((runtime.activeGoal?.id ?? null) !== activeGoalId) {
302
313
  ctx.ui.notify(
303
314
  "The active goal changed while the safety setting was open. No settings were changed.",
@@ -306,7 +317,8 @@ async function applyLimitChoice(
306
317
  return { kind: "rejected" as const };
307
318
  }
308
319
  const previous = runtime.settings.continuationLimits[field];
309
- const limit = await resolveLimitSelection(field, itemId, previous, ctx);
320
+ const limit = await resolveLimitSelection(field, itemId, previous, ctx, isCurrent);
321
+ if (!isCurrent()) return { kind: "rejected" as const };
310
322
  if (limit === undefined || limit === previous) return { kind: "back" as const };
311
323
  if ((runtime.activeGoal?.id ?? null) !== activeGoalId) {
312
324
  ctx.ui.notify(
@@ -316,7 +328,7 @@ async function applyLimitChoice(
316
328
  return { kind: "rejected" as const };
317
329
  }
318
330
  const confirmation = await confirmLowerActiveLimit(runtime, ctx, field, limit);
319
- if (!confirmation.apply) return { kind: "rejected" as const };
331
+ if (!isCurrent() || !confirmation.apply) return { kind: "rejected" as const };
320
332
  if (confirmation.goalId !== undefined && runtime.activeGoal?.id !== confirmation.goalId) {
321
333
  ctx.ui.notify(
322
334
  "The active goal changed while confirming the limit. No settings were changed.",
@@ -354,6 +366,9 @@ export function applyGoalSettings(
354
366
  const abortOwnedRun = activeGoalId !== undefined && runtime.agentRunGoalId === activeGoalId;
355
367
  const pausedByAutomaticLimit = runtime.enforceAutomaticTurnLimit(ctx, abortOwnedRun);
356
368
  if (!pausedByAutomaticLimit) runtime.enforceNoProgressLimit(ctx, abortOwnedRun);
369
+ if (runtime.activeGoal && !runtime.queueFrozen) {
370
+ runtime.updateStatus(ctx, runtime.activeGoal);
371
+ }
357
372
  } catch (error) {
358
373
  const rollbackErrors: unknown[] = [];
359
374
  try {
@@ -399,19 +414,32 @@ async function resolveLimitSelection(
399
414
  selection: LimitSelection,
400
415
  previous: number | null,
401
416
  ctx: ExtensionCommandContext,
417
+ isCurrent: () => boolean,
402
418
  ): Promise<number | null | undefined> {
403
- if (selection === "unlimited" || selection === "off") return null;
419
+ if (selection === "off") return null;
420
+ if (selection === "unlimited") {
421
+ if (previous === null) return null;
422
+ const confirmed = await ctx.ui.confirm(
423
+ "Allow Unlimited automatic work?",
424
+ "Tool loops can continue without a response-count limit and may consume substantial tokens and provider cost. Completion, manual pause, blockers, provider limits, and the no-progress guard still apply.",
425
+ );
426
+ return isCurrent() && confirmed ? null : undefined;
427
+ }
404
428
  if (selection === "default") {
405
- return DEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns;
429
+ return DEFAULT_GOAL_SETTINGS.continuationLimits[field];
406
430
  }
407
431
  while (true) {
408
- const raw = await ctx.ui.input(
432
+ const raw =
409
433
  field === "automaticTurns"
410
- ? "Maximum automatic responses (whole number greater than 0)"
411
- : "Repeated-run threshold (whole number greater than 0)",
412
- previous === null ? "Positive whole number" : String(previous),
413
- );
414
- if (raw === undefined) return undefined;
434
+ ? await ctx.ui.editor(
435
+ `Automatic-work response limit (whole number greater than 0) · Default: ${DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns}`,
436
+ String(previous ?? DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns),
437
+ )
438
+ : await ctx.ui.input(
439
+ "Repeated-run threshold (whole number greater than 0)",
440
+ previous === null ? "Positive whole number" : String(previous),
441
+ );
442
+ if (!isCurrent() || raw === undefined) return undefined;
415
443
  const parsed = parseGoalLimit(raw);
416
444
  if (parsed !== undefined) return parsed;
417
445
  ctx.ui.notify(
@@ -456,25 +484,12 @@ function applyToolVisibility(
456
484
  next: GoalSettings,
457
485
  ctx: ExtensionCommandContext,
458
486
  ) {
459
- if (previous.toolVisibility === next.toolVisibility) return;
460
- if (next.toolVisibility === "always") {
461
- if (runtime.goalToolsHiddenByPolicy.size > 0 && ctx.isIdle() !== true) {
462
- throw new Error("Wait for Pi to become idle before revealing Goal tools.");
463
- }
464
- runtime.restoreGoalToolsHiddenByPolicy();
465
- runtime.goalToolsUnlocked = true;
466
- return;
467
- }
468
- if (runtime.activeGoal) {
469
- runtime.goalToolsUnlocked = true;
470
- runtime.goalToolsHiddenByPolicy.clear();
471
- return;
472
- }
473
- if (ctx.isIdle() !== true) {
474
- throw new Error("Wait for Pi to become idle before hiding Goal tools.");
475
- }
476
- runtime.goalToolsUnlocked = false;
477
- runtime.hideGoalToolsIfLocked();
487
+ runtime.toolPolicy.applyVisibilityChange(
488
+ previous.toolVisibility,
489
+ next.toolVisibility,
490
+ runtime.activeGoal !== undefined,
491
+ ctx,
492
+ );
478
493
  }
479
494
 
480
495
  function applyQueueSetting(runtime: GoalRuntime, ctx: ExtensionCommandContext) {
@@ -550,7 +565,7 @@ function withLimit(settings: GoalSettings, field: LimitField, value: number | nu
550
565
  }
551
566
 
552
567
  function formatAutomaticSettingValue(value: number | null) {
553
- return value === null ? "Unlimited" : `≤${value}`;
568
+ return value === null ? "Unlimited" : `${value} responses`;
554
569
  }
555
570
 
556
571
  function formatNoProgressSettingValue(value: number | null) {
@@ -569,7 +584,7 @@ function formatNoProgressProtection(value: number | null) {
569
584
 
570
585
  function formatLimitSuccess(field: LimitField, value: number | null) {
571
586
  return field === "automaticTurns"
572
- ? `Automatic work: ${formatAutomaticWork(value)}.`
587
+ ? `Automatic-work limit: ${formatAutomaticWork(value)}.`
573
588
  : `No-progress guard: ${formatNoProgressProtection(value)}.`;
574
589
  }
575
590
 
package/src/settings.ts CHANGED
@@ -27,7 +27,7 @@ export const DEFAULT_GOAL_SETTINGS: GoalSettings = {
27
27
  toolVisibility: "always",
28
28
  experimental: { goals: false },
29
29
  rpc: { enabled: false },
30
- continuationLimits: { automaticTurns: null, noProgressTurns: 3 },
30
+ continuationLimits: { automaticTurns: 25, noProgressTurns: 3 },
31
31
  };
32
32
 
33
33
  export type GoalSettingsLoadResult =
@@ -0,0 +1,178 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import type { GoalToolVisibility } from "./settings.js";
3
+
4
+ export const GOAL_COMPLETE_TOOL = "goal_complete";
5
+ export const GOAL_BLOCKED_TOOL = "goal_blocked";
6
+ export const GOAL_TOOL_NAMES = [GOAL_COMPLETE_TOOL, GOAL_BLOCKED_TOOL] as const;
7
+
8
+ export interface GoalToolVisibilitySnapshot {
9
+ activeTools: string[];
10
+ goalToolsUnlocked: boolean;
11
+ goalToolsHiddenByPolicy: string[];
12
+ }
13
+
14
+ interface ToolPolicyContext {
15
+ isIdle?: () => boolean;
16
+ }
17
+
18
+ export class GoalToolPolicy {
19
+ private unlocked = false;
20
+ private readonly hiddenByPolicy = new Set<string>();
21
+ private readonly pi: ExtensionAPI;
22
+
23
+ constructor(pi: ExtensionAPI) {
24
+ this.pi = pi;
25
+ }
26
+
27
+ isUnlocked() {
28
+ return this.unlocked;
29
+ }
30
+
31
+ hasHiddenTools() {
32
+ return this.hiddenByPolicy.size > 0;
33
+ }
34
+
35
+ isGoalToolName(name: string) {
36
+ return (GOAL_TOOL_NAMES as readonly string[]).includes(name);
37
+ }
38
+
39
+ toolsAvailable() {
40
+ const active = new Set(this.pi.getActiveTools());
41
+ return GOAL_TOOL_NAMES.every((name) => active.has(name));
42
+ }
43
+
44
+ lock() {
45
+ this.unlocked = false;
46
+ }
47
+
48
+ unlock() {
49
+ this.unlocked = true;
50
+ }
51
+
52
+ unlockAndForgetHidden() {
53
+ this.unlocked = true;
54
+ this.hiddenByPolicy.clear();
55
+ }
56
+
57
+ hideIfLocked() {
58
+ if (this.unlocked) return;
59
+ const active = this.pi.getActiveTools();
60
+ const hidden = active.filter((name) => this.isGoalToolName(name));
61
+ if (hidden.length === 0) return;
62
+ this.pi.setActiveTools(active.filter((name) => !this.isGoalToolName(name)));
63
+ for (const name of hidden) this.hiddenByPolicy.add(name);
64
+ }
65
+
66
+ restoreHidden() {
67
+ const activeBeforeRestore = this.pi.getActiveTools();
68
+ const activeSet = new Set(activeBeforeRestore);
69
+ const missingOwnedTools = [...this.hiddenByPolicy].filter((name) => !activeSet.has(name));
70
+ if (missingOwnedTools.length === 0) {
71
+ this.hiddenByPolicy.clear();
72
+ return;
73
+ }
74
+ try {
75
+ this.pi.setActiveTools([...activeBeforeRestore, ...missingOwnedTools]);
76
+ const restored = new Set(this.pi.getActiveTools());
77
+ if (missingOwnedTools.some((name) => !restored.has(name))) {
78
+ throw new Error("the active tool policy rejected a previously hidden goal tool");
79
+ }
80
+ this.hiddenByPolicy.clear();
81
+ } catch (error) {
82
+ this.pi.setActiveTools(activeBeforeRestore);
83
+ throw error;
84
+ }
85
+ }
86
+
87
+ prepareActivation(visibility: GoalToolVisibility, ctx: ToolPolicyContext) {
88
+ if (visibility === "after-first-goal") {
89
+ if (!this.toolsAvailable() && ctx.isIdle?.() !== true) {
90
+ throw new Error("wait until Pi is idle before revealing the goal tools");
91
+ }
92
+ this.reveal();
93
+ return;
94
+ }
95
+ this.assertAvailable();
96
+ }
97
+
98
+ prepareSessionStart(visibility: GoalToolVisibility, previous: GoalToolVisibility) {
99
+ if (visibility === "after-first-goal" && previous === "always") this.lock();
100
+ if (visibility !== "always") return;
101
+ try {
102
+ if (this.hasHiddenTools()) this.restoreHidden();
103
+ } finally {
104
+ // Always mode remains unlocked even when an external restrictive policy
105
+ // prevents restoration; retained ownership lets a later session retry.
106
+ this.unlock();
107
+ }
108
+ }
109
+
110
+ reconcileRestoredState(visibility: GoalToolVisibility, hasUnfinishedGoal: boolean) {
111
+ if (visibility !== "after-first-goal") return;
112
+ if (hasUnfinishedGoal) this.unlockAndForgetHidden();
113
+ else if (!this.unlocked) this.hideIfLocked();
114
+ }
115
+
116
+ applyVisibilityChange(
117
+ previous: GoalToolVisibility,
118
+ next: GoalToolVisibility,
119
+ hasUnfinishedGoal: boolean,
120
+ ctx: ToolPolicyContext,
121
+ ) {
122
+ if (previous === next) return;
123
+ if (next === "always") {
124
+ if (this.hasHiddenTools() && ctx.isIdle?.() !== true) {
125
+ throw new Error("Wait for Pi to become idle before revealing Goal tools.");
126
+ }
127
+ this.restoreHidden();
128
+ this.unlock();
129
+ return;
130
+ }
131
+ if (hasUnfinishedGoal) {
132
+ this.unlockAndForgetHidden();
133
+ return;
134
+ }
135
+ if (ctx.isIdle?.() !== true) {
136
+ throw new Error("Wait for Pi to become idle before hiding Goal tools.");
137
+ }
138
+ this.lock();
139
+ this.hideIfLocked();
140
+ }
141
+
142
+ snapshot(): GoalToolVisibilitySnapshot {
143
+ return {
144
+ activeTools: this.pi.getActiveTools(),
145
+ goalToolsUnlocked: this.unlocked,
146
+ goalToolsHiddenByPolicy: [...this.hiddenByPolicy],
147
+ };
148
+ }
149
+
150
+ restore(snapshot: GoalToolVisibilitySnapshot) {
151
+ this.pi.setActiveTools(snapshot.activeTools);
152
+ this.unlocked = snapshot.goalToolsUnlocked;
153
+ this.hiddenByPolicy.clear();
154
+ for (const name of snapshot.goalToolsHiddenByPolicy) this.hiddenByPolicy.add(name);
155
+ }
156
+
157
+ private reveal() {
158
+ const snapshot = this.snapshot();
159
+ try {
160
+ const active = this.pi.getActiveTools();
161
+ const activeSet = new Set(active);
162
+ const missing = GOAL_TOOL_NAMES.filter((name) => !activeSet.has(name));
163
+ if (missing.length > 0) this.pi.setActiveTools([...active, ...missing]);
164
+ this.assertAvailable();
165
+ this.unlockAndForgetHidden();
166
+ } catch (error) {
167
+ this.restore(snapshot);
168
+ throw error;
169
+ }
170
+ }
171
+
172
+ private assertAvailable() {
173
+ if (this.toolsAvailable()) return;
174
+ throw new Error(
175
+ "goal_complete and goal_blocked are unavailable; include them in the active tool allowlist or leave the restrictive tool mode first.",
176
+ );
177
+ }
178
+ }