@narumitw/pi-goal 0.31.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,11 +9,13 @@ Goal mode uses Codex-like persistence instructions and sends guarded continuatio
9
9
  ## ✨ Features
10
10
 
11
11
  - Adds `/goal <goal_to_complete>` to start goal mode, with confirmation before replacing an existing goal.
12
- - Bare `/goal` opens a current-state manager in the TUI, with guided start, pause, resume, edit, queue, settings, status, help, and destructive-action confirmation; RPC mode retains observable status notifications.
12
+ - Bare `/goal` opens a standard current-state manager in the TUI, with guided start, pause,
13
+ resume, edit, queue, settings, status, help, and destructive-action confirmation; RPC mode retains
14
+ observable status notifications.
13
15
  - Keeps direct goal management available through `/goal` subcommands: `status`, `pause`, `resume`, `clear`, and `edit`.
14
16
  - Exposes only one top-level command: `/goal`, including when ordered goals are enabled.
15
17
  - Optionally adds ordered-goal operations through `/goal add`, `prioritize`, `drop-last`, and `skip`, while accepting `push`, `unshift`, `pop`, and `shift` as hidden compatibility aliases.
16
- - Bounds automatic work by default to 25 normal model responses, including responses inside automatic tool loops and Pi-owned retry/compaction recovery; set `continuationLimits.automaticTurns` explicitly to `null` only when unbounded automatic work is intended.
18
+ - Leaves automatic response count unlimited by default; set `continuationLimits.automaticTurns` to a positive whole number when an authoritative response cap is wanted.
17
19
  - Pauses after three consecutive empty or normalized-identical tool-free automatic runs, while distinct short output and tool activity reset the repeat detector.
18
20
  - Supports optional token budgets such as `/goal --tokens 100k <goal>`, using provider-reported total-token accounting with a cache-inclusive compatibility fallback.
19
21
  - Tracks distinct `active`, `paused`, `blocked`, `usage_limited`, `budget_limited`, and `complete` states.
@@ -54,8 +56,8 @@ pi -e ./extensions/pi-goal
54
56
 
55
57
  ## ⚙️ Configuration
56
58
 
57
- On the first session start, pi-goal automatically creates `~/.pi/agent/pi-goal.json`
58
- with the complete current defaults:
59
+ Settings are optional. When `~/.pi/agent/pi-goal.json` is absent, pi-goal uses these
60
+ built-in defaults without creating the file:
59
61
 
60
62
  ```json
61
63
  {
@@ -64,13 +66,22 @@ with the complete current defaults:
64
66
  "goals": false
65
67
  },
66
68
  "continuationLimits": {
67
- "automaticTurns": 25,
69
+ "automaticTurns": null,
68
70
  "noProgressTurns": 3
69
71
  }
70
72
  }
71
73
  ```
72
74
 
73
- Use `/goal` → **Settings…** in the TUI to edit these values interactively, or edit the generated file directly. Interactive changes are serialized, written atomically, preserve unknown fields, and apply to the current runtime. Tool-visibility changes that would alter the active tool schema are rejected while Pi is busy; retry after Pi settles. Escape closes the settings screen without reverting changes that were already saved.
75
+ Use `/goal` → **Settings…** in the TUI to create or update the file interactively, or create
76
+ and edit it directly. The standard Settings screen keeps all four controls on one level in task
77
+ order; the two safety limits open standard choice screens:
78
+
79
+ - **Automatic work** shows **Unlimited** or an exact **≤_N_** response cap. Choose **Unlimited** directly, or choose **Set a maximum…** and enter a safe whole number greater than zero.
80
+ - **No-progress guard** shows **_N_ runs** or **Off**. Choose the default threshold, **Off**, or **Set threshold…** and enter a safe whole number greater than zero.
81
+ - **Goal tools** controls whether terminal Goal tools are always visible or appear after the first goal.
82
+ - **Ordered goal queue** controls the experimental ordered-goal workflows.
83
+
84
+ Custom number inputs reject zero, negative numbers, decimals, text, and unsafe integers without saving; use the explicit **Unlimited** or **Off** choice instead. Interactive changes are serialized, written atomically, preserve unknown fields, and apply to the current runtime. A successful change updates the visible state immediately. A failed save restores the prior value and reports the settings path so it can be retried. Tool-visibility changes that would alter the active tool schema are rejected while Pi is busy; retry after Pi settles. Escape returns to the previous screen without reverting changes that were already saved.
74
85
 
75
86
  `toolVisibility` accepts:
76
87
 
@@ -79,18 +90,14 @@ Use `/goal` → **Settings…** in the TUI to edit these values interactively, o
79
90
 
80
91
  `experimental.goals` accepts a boolean and defaults to `false`. Set it to `true` to enable the ordered-goal subcommands and automatic queue advancement described below. Enabled sessions show one warning because command behavior and persisted queue state remain experimental.
81
92
 
82
- `continuationLimits` controls the default-on runaway guards:
93
+ `continuationLimits` controls the runaway guards:
83
94
 
84
- - `automaticTurns` is a positive safe integer and defaults to `25`. It counts every completed normal `turn_end` owned by automatically started Goal work, including model responses inside tool loops and matching Pi-owned retries. The user-triggered kickoff, resume, edit, and ordinary user runs are not charged. At the limit, the goal becomes `paused` with cause `continuation_limit`, pending continuation/recovery is cancelled, and the current operation is aborted. Pi may invoke a provider adapter once more with an already-aborted signal to produce its synthetic terminal event; that event is not counted and cannot resume Goal work. Set this field to `null` to remove the authoritative hard bound.
95
+ - `automaticTurns` accepts a positive safe integer or `null` and defaults to `null` (unlimited). When configured, it counts every completed normal `turn_end` owned by automatically started Goal work, including model responses inside tool loops and matching Pi-owned retries. The user-triggered kickoff, resume, edit, and ordinary user runs are not charged. At the limit, the goal becomes `paused` with cause `continuation_limit`, pending continuation/recovery is cancelled, and the current operation is aborted. Pi may invoke a provider adapter once more with an already-aborted signal to produce its synthetic terminal event; that event is not counted and cannot resume Goal work. Set this field to `null` to remove the authoritative hard bound.
85
96
  - `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.
86
97
 
87
- Settings are reread at Pi startup, session replacement, and `/reload`; direct external file edits are not watched live, while changes made through the Goal menu apply immediately. A missing file is created during any of those session starts, while an existing file is read without being rewritten. Initialization publishes the generated file atomically and never overwrites a file
88
- created concurrently by another process.
98
+ Settings are reread at Pi startup, session replacement, and `/reload`; direct external file edits are not watched live, while changes made through the Goal menu apply immediately. A missing file remains absent and uses the built-in defaults. The first successful settings change creates the file atomically; later saves preserve unknown fields.
89
99
 
90
- Omitted fields use the defaults above. Invalid or malformed existing settings are never overwritten;
91
- they produce a warning and fall back to all defaults. If the default file cannot be created, pi-goal
92
- warns, continues with the built-in defaults, and retries on the next session start. Reload Pi after
93
- changing the file. If a live runtime reloads settings, switching `toolVisibility` to `"always"`
100
+ Omitted fields use the defaults above. Invalid or malformed existing settings are never overwritten; they produce a warning and fall back to all defaults. In the TUI, Goal Settings becomes a read-only summary that identifies the invalid file and directs the user to fix it and run `/reload`. Reload Pi after changing the file. If a live runtime reloads settings, switching `toolVisibility` to `"always"`
94
101
  restores only the exact tools that pi-goal previously hid, while switching to
95
102
  `"after-first-goal"` locks a runtime that has no unfinished goal.
96
103
 
@@ -115,7 +122,12 @@ Tool visibility is a baseline, not ownership of Pi's global active-tool list. Pl
115
122
  /goal skip
116
123
  ```
117
124
 
118
- - In the TUI, `/goal` opens a state-aware manager. Its first action follows the current state: start when empty, pause when active, resume when stopped, or increase the budget when exhausted. Status, Settings, Help, queue management, Clear, and Close remain shallow, labeled routes. Arrow keys navigate, Enter selects, and Escape cancels or closes without changing state.
125
+ - In the TUI, `/goal` opens a standard state-aware manager. Its first action follows the current
126
+ state: start when empty, pause when active, resume when stopped, or increase the budget when
127
+ exhausted. An active goal shows automatic-response state as **_used_ automatic responses ·
128
+ Unlimited** or **_used_/_limit_ automatic responses**. Status, Settings, Help, queue management,
129
+ invalid-settings guidance, Clear, and Close remain shallow, labeled routes. Arrow keys navigate,
130
+ Enter selects, Escape goes Back, and Ctrl+C closes the full flow.
119
131
  - In RPC mode, bare `/goal` and `/goal status` report the current summary through an observable notification without opening terminal UI. Pi exposes no extension-command output channel in print or JSON mode, so those routes reject with an explicit unsupported-mode error instead of misreporting stderr as status output.
120
132
  - Menu-driven Replace, Clear, Prioritize, Skip, and Drop last actions preview the exact affected goals and require confirmation. Existing direct routes remain immediate for compatibility and automation.
121
133
  - `/goal <goal_to_complete>` starts goal mode. If another unfinished goal exists, Pi asks for confirmation before replacing it with a new active goal and resetting its usage counters. Failed kickoff delivery clears a new goal or restores the prior goal; a previously active goal is restored as paused.
@@ -167,7 +179,7 @@ For each persisted assistant message, `pi-goal` uses finite, non-negative `usage
167
179
 
168
180
  Provider usage becomes authoritative only when an assistant message finishes, so a budget can overshoot by one model call. When completed tool activity first exposes exhaustion, the goal transitions once to `budget_limited`, cancels continuation, and queues one bounded custom wrap-up instruction before the next model call. The instruction permits only a concise progress/results/blockers summary; a substantive tool attempt is blocked and aborts the remaining wrap-up. A rejected `goal_complete` also terminates the wrap-up, while accepted completion still requires existing evidence that proves every requirement—budget exhaustion itself never means completion. If exhaustion is first visible at `agent_end` and no turn remains, the extension stops without creating another model turn.
169
181
 
170
- The automatic-response cap is a call-count boundary, not a fixed cost ceiling: context size, cache pricing, output length, and provider rates vary, and the 25th response is still retained. No default token budget is imposed. For stricter spend control, combine the default circuit breakers with `/goal --tokens`.
182
+ When configured, the automatic-response cap is a call-count boundary, not a fixed cost ceiling: context size, cache pricing, output length, and provider rates vary, and the final capped response is still retained. No default automatic-response cap or token budget is imposed. For stricter spend control, configure `automaticTurns` and/or use `/goal --tokens`.
171
183
 
172
184
  Elapsed time is accumulated only while status is `active`. Pause, blocked, usage-limited, budget-limited, shutdown, and offline periods do not increase it. Legacy session entries are migrated by preserving their accumulated seconds and starting a fresh active clock when loaded.
173
185
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-goal",
3
- "version": "0.31.0",
3
+ "version": "0.38.0",
4
4
  "description": "Pi extension for autonomous /goal completion with opt-in experimental ordered queues.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -30,6 +30,7 @@
30
30
  "typecheck": "tsc --noEmit"
31
31
  },
32
32
  "dependencies": {
33
+ "@narumitw/pi-tui-kit": "<1",
33
34
  "typebox": "^1.3.8"
34
35
  },
35
36
  "peerDependencies": {
package/src/goal.ts CHANGED
@@ -31,7 +31,7 @@ import {
31
31
  truncateNotification,
32
32
  } from "./runtime.js";
33
33
  import { hasAssistantToolCall } from "./safety.js";
34
- import { DEFAULT_GOAL_SETTINGS, loadOrCreateGoalSettings } from "./settings.js";
34
+ import { DEFAULT_GOAL_SETTINGS, readGoalSettings } from "./settings.js";
35
35
  import { showGoalSettings } from "./settings-ui.js";
36
36
 
37
37
  // goal.ts remains the Pi-facing composition root despite its size because tool contracts and
@@ -54,7 +54,6 @@ interface GoalBlockedDetails {
54
54
 
55
55
  interface GoalOptions {
56
56
  settingsPath?: string;
57
- settingsFileSystem?: Parameters<typeof loadOrCreateGoalSettings>[1];
58
57
  }
59
58
 
60
59
  const EXPERIMENTAL_GOALS_WARNING =
@@ -62,6 +61,8 @@ const EXPERIMENTAL_GOALS_WARNING =
62
61
  const MAX_BLOCKER_REASON_LENGTH = 1_000;
63
62
  const MAX_BLOCKER_EVIDENCE_LENGTH = 4_000;
64
63
 
64
+ // Cohesion justification: command, tool, continuation, and lifecycle handlers coordinate one
65
+ // guarded Goal state machine whose ordering and stale-turn invariants share the same closures.
65
66
  function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
66
67
  const runtime = new GoalRuntime(pi);
67
68
  const commands = new GoalCommandController(runtime);
@@ -472,6 +473,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
472
473
  });
473
474
 
474
475
  pi.on("session_start", async (_event, ctx) => {
476
+ runtime.replaceMenuSession();
475
477
  clearCompletionStatusTimer();
476
478
  clearContinuationTracking();
477
479
  clearPendingGoalPrompts();
@@ -487,22 +489,15 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
487
489
  runtime.clearTerminalDetails();
488
490
  rpc.bindSession(ctx);
489
491
  const previousToolVisibility = runtime.settings.toolVisibility;
490
- const settingsResult = loadOrCreateGoalSettings(
491
- options.settingsPath,
492
- options.settingsFileSystem,
493
- );
492
+ const settingsResult = readGoalSettings(options.settingsPath);
494
493
  runtime.settings =
495
494
  settingsResult.kind === "loaded" ? settingsResult.settings : DEFAULT_GOAL_SETTINGS;
495
+ runtime.settingsLoadIssue = settingsResult.kind === "invalid" ? settingsResult : undefined;
496
496
  if (settingsResult.kind === "invalid") {
497
497
  ctx.ui.notify(
498
498
  `pi-goal settings ignored: ${settingsResult.reason}. Using default settings.`,
499
499
  "warning",
500
500
  );
501
- } else if (settingsResult.kind === "create-failed") {
502
- ctx.ui.notify(
503
- `Could not create pi-goal settings: ${settingsResult.reason}. Using default settings.`,
504
- "warning",
505
- );
506
501
  }
507
502
  if (runtime.settings.experimental.goals) {
508
503
  ctx.ui.notify(EXPERIMENTAL_GOALS_WARNING, "warning");
@@ -597,6 +592,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
597
592
  });
598
593
 
599
594
  pi.on("session_shutdown", (_event, ctx) => {
595
+ runtime.closeMenuSession();
600
596
  if (runtime.activeGoal) {
601
597
  if (!runtime.queueFrozen && runtime.activeGoal.status === "active") {
602
598
  updateGoalUsage(runtime.activeGoal, ctx, false);
package/src/menu.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
+ import { type ActionMenuItem, defineMenu, runMenu } from "@narumitw/pi-tui-kit";
2
3
  import { formatDuration } from "./accounting.js";
3
4
  import { parseTokenBudget } from "./command.js";
4
5
  import type { GoalCommandController } from "./commands.js";
5
6
  import type { ActiveGoal, PendingQueueAction } from "./persistence.js";
6
7
  import { goalQueueIdentity } from "./queue.js";
7
- import type { GoalRuntime } from "./runtime.js";
8
+ import { type GoalRuntime, goalSummary } from "./runtime.js";
8
9
 
9
10
  export const GOAL_MENU_ACTIONS = {
10
11
  start: "Start a goal…",
@@ -47,6 +48,22 @@ export interface GoalMenuState {
47
48
  }
48
49
 
49
50
  type ShowSettings = (ctx: ExtensionCommandContext) => Promise<void>;
51
+ type GoalMenuScreen = "main" | "queue" | "status" | "help";
52
+ type GoalMenuAction =
53
+ | "start"
54
+ | "start-budget"
55
+ | "pause"
56
+ | "resume"
57
+ | "increase-budget"
58
+ | "edit"
59
+ | "replace"
60
+ | "settings"
61
+ | "clear"
62
+ | "queue-add"
63
+ | "queue-prioritize"
64
+ | "queue-skip"
65
+ | "queue-drop"
66
+ | "back";
50
67
 
51
68
  export function buildGoalMenuState(runtime: GoalMenuRuntimeView): GoalMenuState {
52
69
  const goal = runtime.activeGoal;
@@ -56,12 +73,17 @@ export function buildGoalMenuState(runtime: GoalMenuRuntimeView): GoalMenuState
56
73
  : runtime.pendingQueueAction
57
74
  ? "Waiting for Pi to settle"
58
75
  : displayStatus(goal?.status);
76
+ const automaticTurnLimit = runtime.settings.continuationLimits.automaticTurns;
77
+ const automaticResponses =
78
+ automaticTurnLimit === null
79
+ ? `${goal?.automaticModelTurns ?? 0} automatic responses · Unlimited`
80
+ : `${goal?.automaticModelTurns ?? 0}/${automaticTurnLimit} automatic responses`;
59
81
  const details = goal
60
82
  ? [
61
83
  goal.tokenBudget === undefined
62
84
  ? formatDuration(goal.timeUsedSeconds)
63
85
  : `${formatTokenCount(goal.tokensUsed)}/${formatTokenCount(goal.tokenBudget)}`,
64
- `${goal.automaticModelTurns} automatic responses`,
86
+ automaticResponses,
65
87
  ...(queueCount > 0 ? [`${queueCount} queued`] : []),
66
88
  ].join(" · ")
67
89
  : "No goal is currently set";
@@ -115,57 +137,132 @@ export async function showGoalManager(
115
137
  commands.showGoal(ctx);
116
138
  return;
117
139
  }
118
- while (true) {
119
- refreshGoalMenuState(runtime, ctx);
120
- const state = buildGoalMenuState(runtime);
121
- const displayedGoal = runtime.activeGoal;
122
- const selected = await ctx.ui.select(state.title, state.actions);
123
- if (!selected || selected === GOAL_MENU_ACTIONS.close) return;
124
- switch (selected) {
125
- case GOAL_MENU_ACTIONS.start:
140
+ const owner = runtime as GoalRuntime;
141
+ const generation = owner.menuGeneration;
142
+ const ownerSignal = owner.menuController?.signal;
143
+ let displayedGoal: ActiveGoal | undefined;
144
+ let displayedQueueHead: ActiveGoal | undefined;
145
+ let displayedQueueFirst: ActiveGoal | undefined;
146
+ let displayedQueueLast: ActiveGoal | undefined;
147
+ const menu = defineMenu<undefined, GoalMenuScreen, GoalMenuAction, ExtensionCommandContext>({
148
+ start: "main",
149
+ screens: {
150
+ main: () => {
151
+ refreshGoalMenuState(runtime, ctx);
152
+ const state = buildGoalMenuState(runtime);
153
+ displayedGoal = runtime.activeGoal;
154
+ return {
155
+ kind: "actions",
156
+ title: "Goal",
157
+ lines: state.title.split("\n").slice(1),
158
+ items: state.actions.map(goalMainMenuItem),
159
+ hint: "close",
160
+ };
161
+ },
162
+ queue: () => {
163
+ displayedQueueHead = runtime.activeGoal;
164
+ displayedQueueFirst = runtime.queuedGoals[0];
165
+ displayedQueueLast = runtime.queuedGoals.at(-1) ?? runtime.activeGoal;
166
+ return {
167
+ kind: "actions",
168
+ title: "Goal queue",
169
+ lines: [
170
+ `${runtime.queuedGoals.length + (runtime.activeGoal ? 1 : 0)} total`,
171
+ ...(runtime.activeGoal
172
+ ? [`Current: ${safeGoalMenuText(runtime.activeGoal.text)}`]
173
+ : []),
174
+ ],
175
+ items: [
176
+ { id: "add", label: QUEUE_ACTIONS.add, action: "queue-add" },
177
+ { id: "prioritize", label: QUEUE_ACTIONS.prioritize, action: "queue-prioritize" },
178
+ ...(runtime.queuedGoals.length > 0
179
+ ? [
180
+ { id: "skip", label: QUEUE_ACTIONS.skip, action: "queue-skip" as const },
181
+ {
182
+ id: "drop-last",
183
+ label: QUEUE_ACTIONS.dropLast,
184
+ action: "queue-drop" as const,
185
+ },
186
+ ]
187
+ : []),
188
+ { id: "back", label: QUEUE_ACTIONS.back, action: "back" },
189
+ ],
190
+ hint: "back",
191
+ };
192
+ },
193
+ status: () => ({
194
+ kind: "detail",
195
+ title: "Goal status",
196
+ lines: runtime.activeGoal
197
+ ? goalSummary(
198
+ runtime.activeGoal,
199
+ runtime.queuedGoals,
200
+ runtime.settings.experimental.goals,
201
+ runtime.queueFrozen,
202
+ runtime.pendingQueueAction,
203
+ ).split("\n")
204
+ : ["No goal is currently set."],
205
+ hint: "back",
206
+ }),
207
+ help: () => ({
208
+ kind: "detail",
209
+ title: "Goal help",
210
+ lines: goalHelp().split("\n").slice(1),
211
+ hint: "back",
212
+ }),
213
+ },
214
+ actions: {
215
+ start: async () => {
126
216
  await startFromMenu(commands, ctx);
127
- return;
128
- case GOAL_MENU_ACTIONS.startBudget:
217
+ return { kind: "close" };
218
+ },
219
+ "start-budget": async () => {
129
220
  await startFromMenu(commands, ctx, true);
130
- return;
131
- case GOAL_MENU_ACTIONS.pause:
132
- if (!displayedGoal || !requireCurrentMenuGoal(runtime, displayedGoal, ctx)) continue;
221
+ return { kind: "close" };
222
+ },
223
+ pause: async () => {
224
+ if (!displayedGoal || !requireCurrentMenuGoal(runtime, displayedGoal, ctx)) {
225
+ return { kind: "stay" };
226
+ }
133
227
  commands.pauseGoal(ctx);
134
- return;
135
- case GOAL_MENU_ACTIONS.resume:
136
- if (!displayedGoal || !requireCurrentMenuGoal(runtime, displayedGoal, ctx)) continue;
228
+ return { kind: "close" };
229
+ },
230
+ resume: async () => {
231
+ if (!displayedGoal || !requireCurrentMenuGoal(runtime, displayedGoal, ctx)) {
232
+ return { kind: "stay" };
233
+ }
137
234
  await commands.resumeGoal(ctx);
138
- return;
139
- case GOAL_MENU_ACTIONS.increaseBudget:
140
- if (!displayedGoal || !requireCurrentMenuGoal(runtime, displayedGoal, ctx)) continue;
235
+ return { kind: "close" };
236
+ },
237
+ "increase-budget": async () => {
238
+ if (!displayedGoal || !requireCurrentMenuGoal(runtime, displayedGoal, ctx)) {
239
+ return { kind: "stay" };
240
+ }
141
241
  await increaseBudget(runtime, commands, ctx);
142
- return;
143
- case GOAL_MENU_ACTIONS.edit:
144
- if (!displayedGoal || !requireCurrentMenuGoal(runtime, displayedGoal, ctx)) continue;
242
+ return { kind: "close" };
243
+ },
244
+ edit: async () => {
245
+ if (!displayedGoal || !requireCurrentMenuGoal(runtime, displayedGoal, ctx)) {
246
+ return { kind: "stay" };
247
+ }
145
248
  await editFromMenu(runtime, commands, ctx);
146
- return;
147
- case GOAL_MENU_ACTIONS.replace:
249
+ return { kind: "close" };
250
+ },
251
+ replace: async () => {
148
252
  await startFromMenu(commands, ctx);
149
- return;
150
- case GOAL_MENU_ACTIONS.status:
151
- commands.showGoal(ctx);
152
- return;
153
- case GOAL_MENU_ACTIONS.queue:
154
- if ((await showQueueMenu(runtime, commands, ctx)) === "back") continue;
155
- return;
156
- case GOAL_MENU_ACTIONS.settings:
253
+ return { kind: "close" };
254
+ },
255
+ settings: async () => {
157
256
  await showSettings(ctx);
158
- continue;
159
- case GOAL_MENU_ACTIONS.help:
160
- ctx.ui.notify(goalHelp(), "info");
161
- return;
162
- case GOAL_MENU_ACTIONS.clear: {
257
+ return { kind: "stay" };
258
+ },
259
+ clear: async () => {
163
260
  const previewedQueue = goalQueueIdentity(
164
261
  runtime.activeGoal,
165
262
  runtime.queuedGoals,
166
263
  runtime.pendingQueueAction,
167
264
  );
168
- if (!(await confirmClear(runtime, ctx))) continue;
265
+ if (!(await confirmClear(runtime, ctx))) return { kind: "stay" };
169
266
  if (
170
267
  goalQueueIdentity(runtime.activeGoal, runtime.queuedGoals, runtime.pendingQueueAction) !==
171
268
  previewedQueue
@@ -174,13 +271,90 @@ export async function showGoalManager(
174
271
  "The goal queue changed while the dialog was open. Reopen /goal and try again.",
175
272
  "warning",
176
273
  );
177
- continue;
274
+ return { kind: "stay" };
178
275
  }
179
276
  commands.clearGoal(ctx);
180
- return;
181
- }
182
- }
183
- }
277
+ return { kind: "close" };
278
+ },
279
+ "queue-add": async () => {
280
+ const objective = (await ctx.ui.editor("Add goal to queue", ""))?.trim();
281
+ if (objective) await commands.addGoal(objective, undefined, ctx);
282
+ return { kind: "close" };
283
+ },
284
+ "queue-prioritize": async () => {
285
+ const goal = displayedQueueHead;
286
+ if (!goal) return { kind: "stay" };
287
+ const objective = (await ctx.ui.editor("Prioritize goal", ""))?.trim();
288
+ if (!objective || !requireCurrentQueueHead(runtime, goal, ctx)) return { kind: "stay" };
289
+ const confirmed = await ctx.ui.confirm(
290
+ "Prioritize goal?",
291
+ `New priority goal:\n${safeGoalMenuText(objective, 4_000)}\n\nCurrent goal moved to the queue:\n${safeGoalMenuText(goal.text, 4_000)}`,
292
+ );
293
+ if (confirmed && requireCurrentQueueHead(runtime, goal, ctx)) {
294
+ await commands.prioritizeGoal(objective, undefined, ctx);
295
+ }
296
+ return { kind: "close" };
297
+ },
298
+ "queue-skip": async () => {
299
+ const goal = displayedQueueHead;
300
+ if (!goal) return { kind: "stay" };
301
+ const next = displayedQueueFirst;
302
+ const nextEffect = !next
303
+ ? "No goal remains"
304
+ : next.status === "queued"
305
+ ? `Start next goal:\n${safeGoalMenuText(next.text, 4_000)}`
306
+ : `Next goal remains ${displayStatus(next.status).toLowerCase()}:\n${safeGoalMenuText(next.text, 4_000)}`;
307
+ const confirmed = await ctx.ui.confirm(
308
+ "Skip current goal?",
309
+ `Remove current goal:\n${safeGoalMenuText(goal.text, 4_000)}\n\n${nextEffect}`,
310
+ );
311
+ if (confirmed && requireCurrentQueueSelection(runtime, goal, next, "first", ctx)) {
312
+ await commands.skipGoal(ctx);
313
+ }
314
+ return { kind: "close" };
315
+ },
316
+ "queue-drop": async () => {
317
+ const goal = displayedQueueHead;
318
+ const last = displayedQueueLast;
319
+ if (!goal || !last) return { kind: "stay" };
320
+ const confirmed = await ctx.ui.confirm(
321
+ "Drop last goal?",
322
+ `Remove from queue:\n${safeGoalMenuText(last.text, 4_000)}`,
323
+ );
324
+ if (confirmed && requireCurrentQueueSelection(runtime, goal, last, "last", ctx)) {
325
+ commands.dropLastGoal(ctx);
326
+ }
327
+ return { kind: "close" };
328
+ },
329
+ back: async () => ({ kind: "back" }),
330
+ },
331
+ });
332
+ await runMenu(ctx, menu, {
333
+ getState: () => undefined,
334
+ signal: ownerSignal,
335
+ isCurrent: () =>
336
+ owner.menuController === undefined ||
337
+ (generation === owner.menuGeneration && !owner.menuController.signal.aborted),
338
+ });
339
+ }
340
+
341
+ function goalMainMenuItem(label: string): ActionMenuItem<GoalMenuScreen, GoalMenuAction> {
342
+ if (label === GOAL_MENU_ACTIONS.status) return { id: "status", label, to: "status" as const };
343
+ if (label === GOAL_MENU_ACTIONS.queue) return { id: "queue", label, to: "queue" as const };
344
+ if (label === GOAL_MENU_ACTIONS.help) return { id: "help", label, to: "help" as const };
345
+ if (label === GOAL_MENU_ACTIONS.close) return { id: "close", label, close: true as const };
346
+ const actions = new Map<string, GoalMenuAction>([
347
+ [GOAL_MENU_ACTIONS.start, "start"],
348
+ [GOAL_MENU_ACTIONS.startBudget, "start-budget"],
349
+ [GOAL_MENU_ACTIONS.pause, "pause"],
350
+ [GOAL_MENU_ACTIONS.resume, "resume"],
351
+ [GOAL_MENU_ACTIONS.increaseBudget, "increase-budget"],
352
+ [GOAL_MENU_ACTIONS.edit, "edit"],
353
+ [GOAL_MENU_ACTIONS.replace, "replace"],
354
+ [GOAL_MENU_ACTIONS.settings, "settings"],
355
+ [GOAL_MENU_ACTIONS.clear, "clear"],
356
+ ]);
357
+ return { id: actions.get(label) ?? label, label, action: actions.get(label) ?? "settings" };
184
358
  }
185
359
 
186
360
  function refreshGoalMenuState(runtime: GoalMenuRuntimeView, ctx: ExtensionCommandContext) {
@@ -271,66 +445,6 @@ async function askTokenBudget(ctx: ExtensionCommandContext, current?: number) {
271
445
  return budget;
272
446
  }
273
447
 
274
- async function showQueueMenu(
275
- runtime: GoalMenuRuntimeView,
276
- commands: GoalCommandController,
277
- ctx: ExtensionCommandContext,
278
- ) {
279
- const goal = runtime.activeGoal;
280
- if (!goal) return;
281
- const actions: string[] = [QUEUE_ACTIONS.add, QUEUE_ACTIONS.prioritize];
282
- if (runtime.queuedGoals.length > 0) actions.push(QUEUE_ACTIONS.skip, QUEUE_ACTIONS.dropLast);
283
- actions.push(QUEUE_ACTIONS.back);
284
- const selected = await ctx.ui.select(
285
- `Goal queue · ${runtime.queuedGoals.length + 1} total\nCurrent: ${safeGoalMenuText(goal.text)}`,
286
- actions,
287
- );
288
- if (!selected || selected === QUEUE_ACTIONS.back) return "back" as const;
289
- if (selected === QUEUE_ACTIONS.add) {
290
- const objective = (await ctx.ui.editor("Add goal to queue", ""))?.trim();
291
- if (objective) await commands.addGoal(objective, undefined, ctx);
292
- return;
293
- }
294
- if (selected === QUEUE_ACTIONS.prioritize) {
295
- const objective = (await ctx.ui.editor("Prioritize goal", ""))?.trim();
296
- if (!objective || !requireCurrentQueueHead(runtime, goal, ctx)) return;
297
- const confirmed = await ctx.ui.confirm(
298
- "Prioritize goal?",
299
- `New priority goal:\n${safeGoalMenuText(objective, 4_000)}\n\nCurrent goal moved to the queue:\n${safeGoalMenuText(goal.text, 4_000)}`,
300
- );
301
- if (confirmed && requireCurrentQueueHead(runtime, goal, ctx)) {
302
- await commands.prioritizeGoal(objective, undefined, ctx);
303
- }
304
- return;
305
- }
306
- if (selected === QUEUE_ACTIONS.skip) {
307
- const next = runtime.queuedGoals[0];
308
- const nextEffect = !next
309
- ? "No goal remains"
310
- : next.status === "queued"
311
- ? `Start next goal:\n${safeGoalMenuText(next.text, 4_000)}`
312
- : `Next goal remains ${displayStatus(next.status).toLowerCase()}:\n${safeGoalMenuText(next.text, 4_000)}`;
313
- const confirmed = await ctx.ui.confirm(
314
- "Skip current goal?",
315
- `Remove current goal:\n${safeGoalMenuText(goal.text, 4_000)}\n\n${nextEffect}`,
316
- );
317
- if (confirmed && requireCurrentQueueSelection(runtime, goal, next, "first", ctx)) {
318
- await commands.skipGoal(ctx);
319
- }
320
- return;
321
- }
322
- if (selected === QUEUE_ACTIONS.dropLast) {
323
- const last = runtime.queuedGoals.at(-1) ?? goal;
324
- const confirmed = await ctx.ui.confirm(
325
- "Drop last goal?",
326
- `Remove from queue:\n${safeGoalMenuText(last.text, 4_000)}`,
327
- );
328
- if (confirmed && requireCurrentQueueSelection(runtime, goal, last, "last", ctx)) {
329
- commands.dropLastGoal(ctx);
330
- }
331
- }
332
- }
333
-
334
448
  async function confirmClear(runtime: GoalMenuRuntimeView, ctx: ExtensionCommandContext) {
335
449
  const goals = [runtime.activeGoal, ...runtime.queuedGoals].filter(
336
450
  (goal): goal is ActiveGoal => goal !== undefined,
package/src/runtime.ts CHANGED
@@ -24,7 +24,11 @@ import { nextToolFreeRepeatState, resetGoalSafetyEpoch } from "./safety.js";
24
24
 
25
25
  export { queueGoalSafetyReset, resetGoalSafetyEpoch } from "./safety.js";
26
26
 
27
- import { DEFAULT_GOAL_SETTINGS, type GoalSettings } from "./settings.js";
27
+ import {
28
+ DEFAULT_GOAL_SETTINGS,
29
+ type GoalSettings,
30
+ type GoalSettingsLoadIssue,
31
+ } from "./settings.js";
28
32
 
29
33
  export interface ContinuationTicket {
30
34
  goalId: string;
@@ -165,8 +169,12 @@ const CONTRADICTORY_COMPLETION_PATTERNS = [
165
169
  // and the cross-cutting invariants used by command and lifecycle orchestration.
166
170
  // Keep this state machine cohesive despite its size: prompt ownership, continuation,
167
171
  // budget, safety, and tool-policy transitions share ordering-sensitive invariants.
172
+ // Cohesion justification: Goal transitions, continuation ownership, queue state, and budget/retry
173
+ // recovery share one generation-guarded runtime; separating them would duplicate stale-turn and
174
+ // persistence invariants across modules.
168
175
  export class GoalRuntime {
169
176
  settings: GoalSettings = DEFAULT_GOAL_SETTINGS;
177
+ settingsLoadIssue?: GoalSettingsLoadIssue;
170
178
  activeGoal?: ActiveGoal;
171
179
  /** Terminal details captured for the matching cross-extension state event. */
172
180
  private terminalDetails?: GoalTerminalDetails;
@@ -194,6 +202,8 @@ export class GoalRuntime {
194
202
  cancelledContinuationMarkers = new Set<string>();
195
203
  claimedContinuationMarkers = new Set<string>();
196
204
  pendingNonGoalInputs: PendingNonGoalInput[] = [];
205
+ menuGeneration = 0;
206
+ menuController = new AbortController();
197
207
 
198
208
  readonly pi: ExtensionAPI;
199
209
 
@@ -201,6 +211,17 @@ export class GoalRuntime {
201
211
  this.pi = pi;
202
212
  }
203
213
 
214
+ replaceMenuSession() {
215
+ this.menuGeneration += 1;
216
+ this.menuController.abort(new DOMException("Goal session replaced", "AbortError"));
217
+ this.menuController = new AbortController();
218
+ }
219
+
220
+ closeMenuSession() {
221
+ this.menuGeneration += 1;
222
+ this.menuController.abort(new DOMException("Goal session shut down", "AbortError"));
223
+ }
224
+
204
225
  canRecordGoalUsage(goalId?: string) {
205
226
  return (
206
227
  this.agentRunGoalId !== null &&
@@ -1,13 +1,14 @@
1
1
  import { join } from "node:path";
2
- import {
3
- type ExtensionCommandContext,
4
- getAgentDir,
5
- getSettingsListTheme,
6
- } from "@earendil-works/pi-coding-agent";
7
- import { Container, type SettingItem, SettingsList, Text } from "@earendil-works/pi-tui";
2
+ import { type ExtensionCommandContext, getAgentDir } from "@earendil-works/pi-coding-agent";
3
+ import { defineMenu, runMenu } from "@narumitw/pi-tui-kit";
8
4
  import { checkpointGoalActiveTime } from "./accounting.js";
9
5
  import { abortCurrentTurn, type GoalRuntime, STATUS_KEY } from "./runtime.js";
10
- import { GOAL_SETTINGS_FILE, type GoalSettings, saveGoalSettings } from "./settings.js";
6
+ import {
7
+ DEFAULT_GOAL_SETTINGS,
8
+ GOAL_SETTINGS_FILE,
9
+ type GoalSettings,
10
+ saveGoalSettings,
11
+ } from "./settings.js";
11
12
 
12
13
  interface GoalSettingsUiOptions {
13
14
  settingsPath?: string;
@@ -20,11 +21,7 @@ interface GoalSettingsApplyOptions {
20
21
  }
21
22
 
22
23
  type LimitField = "automaticTurns" | "noProgressTurns";
23
- type SettingsScreenResult =
24
- | { kind: "limit"; field: LimitField }
25
- | { kind: "queue"; enabled: boolean }
26
- | undefined;
27
-
24
+ type LimitSelection = "unlimited" | "default" | "custom" | "off";
28
25
  export async function showGoalSettings(
29
26
  runtime: GoalRuntime,
30
27
  ctx: ExtensionCommandContext,
@@ -35,67 +32,278 @@ export async function showGoalSettings(
35
32
  ctx.ui.notify(`Edit pi-goal settings manually: ${safeTerminalText(settingsPath)}`, "info");
36
33
  return;
37
34
  }
38
-
39
- while (true) {
40
- const result = await showSettingsScreen(runtime, ctx, settingsPath, options);
41
- if (!result) return;
42
- if (result.kind === "queue") {
43
- const next = await nextQueueSettings(runtime, ctx, result.enabled);
44
- if (!next) return;
45
- const wasFrozen = runtime.queueFrozen;
46
- try {
47
- applyGoalSettings(runtime, next, ctx, {
48
- save: (settings) => (options.save ?? saveGoalSettings)(settings, settingsPath),
49
- });
50
- if (wasFrozen && !runtime.queueFrozen) {
51
- try {
52
- await options.onQueueUnfrozen?.(ctx);
53
- } catch (error) {
54
- ctx.ui.notify(
55
- `Goal queue enabled, but automatic resume failed: ${formatError(error)}. Reopen /goal to retry.`,
56
- "warning",
57
- );
35
+ const generation = runtime.menuGeneration;
36
+ const invalid = runtime.settingsLoadIssue?.kind === "invalid";
37
+ const previewGoalIds = new Map<LimitField, string | null>();
38
+ type Screen = "settings" | "automatic" | "no-progress" | "invalid";
39
+ type Action =
40
+ | "open-automatic"
41
+ | "open-no-progress"
42
+ | "choose-automatic"
43
+ | "choose-no-progress"
44
+ | "set-visibility"
45
+ | "set-queue";
46
+ const menu = defineMenu<undefined, Screen, Action, ExtensionCommandContext>({
47
+ start: invalid ? "invalid" : "settings",
48
+ screens: {
49
+ settings: () => ({
50
+ kind: "settings",
51
+ title: "Pi Goal Settings",
52
+ lines: [`User settings · ${safeTerminalText(settingsPath)}`],
53
+ items: [
54
+ {
55
+ id: "automaticTurns",
56
+ label: "Automatic work",
57
+ description: "Choose whether Goal can continue without a response-count cap.",
58
+ currentValue: formatAutomaticSettingValue(
59
+ runtime.settings.continuationLimits.automaticTurns,
60
+ ),
61
+ action: "open-automatic",
62
+ },
63
+ {
64
+ id: "noProgressTurns",
65
+ label: "No-progress guard",
66
+ description: "Pause after repeated or empty tool-free automatic runs.",
67
+ currentValue: formatNoProgressSettingValue(
68
+ runtime.settings.continuationLimits.noProgressTurns,
69
+ ),
70
+ action: "open-no-progress",
71
+ },
72
+ {
73
+ id: "toolVisibility",
74
+ label: "Goal tools",
75
+ description: "Keep terminal Goal tools visible, or reveal them after the first goal.",
76
+ currentValue: visibilityLabel(runtime.settings.toolVisibility),
77
+ values: ["Always", "After first goal"],
78
+ action: "set-visibility",
79
+ },
80
+ {
81
+ id: "experimentalGoals",
82
+ label: "Ordered goal queue",
83
+ description: "Enable experimental add, prioritize, skip, and drop-last workflows.",
84
+ currentValue: runtime.settings.experimental.goals ? "Experimental" : "Off",
85
+ values: ["Off", "Experimental"],
86
+ action: "set-queue",
87
+ },
88
+ ],
89
+ }),
90
+ automatic: () => limitChoiceScreen(runtime, "automaticTurns", "choose-automatic"),
91
+ "no-progress": () => limitChoiceScreen(runtime, "noProgressTurns", "choose-no-progress"),
92
+ invalid: () => ({
93
+ kind: "detail",
94
+ title: "Pi Goal Settings · Read only",
95
+ lines: [
96
+ `Invalid settings file. Pi-goal is using built-in defaults. Fix ${safeTerminalText(settingsPath)} and run /reload. The file will not be overwritten.`,
97
+ `Automatic work: ${formatAutomaticWork(runtime.settings.continuationLimits.automaticTurns)}`,
98
+ `No-progress guard: ${formatNoProgressProtection(runtime.settings.continuationLimits.noProgressTurns)}`,
99
+ `Goal tools: ${visibilityLabel(runtime.settings.toolVisibility)}`,
100
+ `Ordered goal queue: ${runtime.settings.experimental.goals ? "Experimental" : "Off"}`,
101
+ ],
102
+ hint: "back",
103
+ }),
104
+ },
105
+ actions: {
106
+ "open-automatic": async () => {
107
+ previewGoalIds.set("automaticTurns", runtime.activeGoal?.id ?? null);
108
+ return { kind: "to", screen: "automatic" };
109
+ },
110
+ "open-no-progress": async () => {
111
+ previewGoalIds.set("noProgressTurns", runtime.activeGoal?.id ?? null);
112
+ return { kind: "to", screen: "no-progress" };
113
+ },
114
+ "choose-automatic": async ({ itemId }) =>
115
+ applyLimitChoice(
116
+ runtime,
117
+ ctx,
118
+ options,
119
+ settingsPath,
120
+ "automaticTurns",
121
+ itemId,
122
+ previewGoalIds.get("automaticTurns") ?? null,
123
+ ),
124
+ "choose-no-progress": async ({ itemId }) =>
125
+ applyLimitChoice(
126
+ runtime,
127
+ ctx,
128
+ options,
129
+ settingsPath,
130
+ "noProgressTurns",
131
+ itemId,
132
+ previewGoalIds.get("noProgressTurns") ?? null,
133
+ ),
134
+ "set-visibility": async ({ value }) => {
135
+ const nextVisibility = value === "Always" ? "always" : "after-first-goal";
136
+ if (nextVisibility === runtime.settings.toolVisibility) return { kind: "stay" };
137
+ try {
138
+ const next = {
139
+ ...structuredClone(runtime.settings),
140
+ toolVisibility: nextVisibility,
141
+ } satisfies GoalSettings;
142
+ applyGoalSettings(runtime, next, ctx, {
143
+ save: (settings) => (options.save ?? saveGoalSettings)(settings, settingsPath),
144
+ });
145
+ ctx.ui.notify(`Goal tools: ${value}.`, "info");
146
+ return { kind: "stay" };
147
+ } catch (error) {
148
+ notifySettingsFailure(ctx, settingsPath, error);
149
+ return { kind: "rejected" };
150
+ }
151
+ },
152
+ "set-queue": async ({ value }) => {
153
+ const enabled = value === "Experimental";
154
+ if (enabled === runtime.settings.experimental.goals) return { kind: "stay" };
155
+ const next = await nextQueueSettings(runtime, ctx, enabled);
156
+ if (!next) return { kind: "rejected" };
157
+ const wasFrozen = runtime.queueFrozen;
158
+ try {
159
+ applyGoalSettings(runtime, next, ctx, {
160
+ save: (settings) => (options.save ?? saveGoalSettings)(settings, settingsPath),
161
+ });
162
+ if (wasFrozen && !runtime.queueFrozen) {
163
+ try {
164
+ await options.onQueueUnfrozen?.(ctx);
165
+ } catch (error) {
166
+ ctx.ui.notify(
167
+ `Goal queue enabled, but automatic resume failed: ${safeTerminalText(formatError(error))}. Reopen /goal to retry.`,
168
+ "warning",
169
+ );
170
+ }
58
171
  }
172
+ ctx.ui.notify(`Ordered goal queue: ${enabled ? "Experimental" : "Off"}.`, "info");
173
+ return { kind: "stay" };
174
+ } catch (error) {
175
+ notifySettingsFailure(ctx, settingsPath, error);
176
+ return { kind: "rejected" };
59
177
  }
60
- ctx.ui.notify(`Ordered goal queue: ${result.enabled ? "Experimental" : "Off"}.`, "info");
61
- } catch (error) {
62
- ctx.ui.notify(`pi-goal settings save failed: ${formatError(error)}`, "error");
63
- }
64
- return;
65
- }
178
+ },
179
+ },
180
+ });
181
+ await runMenu(ctx, menu, {
182
+ getState: () => undefined,
183
+ signal: runtime.menuController.signal,
184
+ isCurrent: () =>
185
+ generation === runtime.menuGeneration && !runtime.menuController.signal.aborted,
186
+ });
187
+ }
66
188
 
67
- const previous = runtime.settings.continuationLimits[result.field];
68
- const raw = await ctx.ui.input(
69
- result.field === "automaticTurns" ? "Automatic response limit" : "No-progress run limit",
70
- formatGoalLimit(previous),
189
+ function limitChoiceScreen(
190
+ runtime: GoalRuntime,
191
+ field: LimitField,
192
+ action: "choose-automatic" | "choose-no-progress",
193
+ ) {
194
+ const value = runtime.settings.continuationLimits[field];
195
+ const goal = runtime.activeGoal;
196
+ return {
197
+ kind: "actions" as const,
198
+ title: field === "automaticTurns" ? "Automatic work" : "No-progress guard",
199
+ lines: [
200
+ field === "automaticTurns"
201
+ ? `Current: ${formatAutomaticWork(value)}`
202
+ : `Current: ${formatNoProgressProtection(value)}`,
203
+ ...(goal
204
+ ? [
205
+ field === "automaticTurns"
206
+ ? `Active goal: ${goal.automaticModelTurns} automatic responses used`
207
+ : `Active goal: ${goal.toolFreeRepeatCount} repeated or empty runs detected`,
208
+ ]
209
+ : []),
210
+ ],
211
+ items: limitChoices(field, value, goal?.automaticModelTurns).map((item) => ({
212
+ id: item.value,
213
+ label: item.label,
214
+ description: item.description,
215
+ action,
216
+ })),
217
+ hint: "back" as const,
218
+ };
219
+ }
220
+
221
+ function limitChoices(
222
+ field: LimitField,
223
+ value: number | null,
224
+ automaticTurnsUsed: number | undefined,
225
+ ): Array<{ value: LimitSelection; label: string; description: string }> {
226
+ if (field === "automaticTurns") {
227
+ const unlimitedDescription =
228
+ value === null
229
+ ? "No response-count cap. Completion, manual pause, blockers, provider limits, and other configured guards still apply."
230
+ : automaticTurnsUsed === undefined
231
+ ? `Remove the current ${value}-response cap. Goal work will have no response-count cap; other configured stop conditions remain.`
232
+ : `Remove the current ${value}-response cap. The active goal has used ${automaticTurnsUsed} responses; other configured stop conditions remain.`;
233
+ return [
234
+ { value: "unlimited", label: "Unlimited (default)", description: unlimitedDescription },
235
+ {
236
+ value: "custom",
237
+ label: "Set a maximum…",
238
+ description: "Pause after a whole number of Goal-owned automatic responses.",
239
+ },
240
+ ];
241
+ }
242
+ const defaultLimit = DEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns;
243
+ return [
244
+ {
245
+ value: "default",
246
+ label: `After ${defaultLimit} repeated runs (default)`,
247
+ description: "Pause after the default number of repeated or empty tool-free runs.",
248
+ },
249
+ {
250
+ value: "custom",
251
+ label: "Set threshold…",
252
+ description: "Choose a whole number of repeated or empty runs before pausing.",
253
+ },
254
+ {
255
+ value: "off",
256
+ label: "Off",
257
+ description: "Do not pause based on repeated or empty tool-free runs.",
258
+ },
259
+ ];
260
+ }
261
+
262
+ async function applyLimitChoice(
263
+ runtime: GoalRuntime,
264
+ ctx: ExtensionCommandContext,
265
+ options: GoalSettingsUiOptions,
266
+ settingsPath: string,
267
+ field: LimitField,
268
+ itemId: string,
269
+ activeGoalId: string | null,
270
+ ) {
271
+ if (!isLimitSelection(itemId)) return { kind: "rejected" as const };
272
+ if ((runtime.activeGoal?.id ?? null) !== activeGoalId) {
273
+ ctx.ui.notify(
274
+ "The active goal changed while the safety setting was open. No settings were changed.",
275
+ "warning",
71
276
  );
72
- if (raw === undefined) continue;
73
- const limit = parseGoalLimit(raw);
74
- if (limit === undefined) {
75
- ctx.ui.notify("Enter a positive whole number or Unlimited.", "warning");
76
- continue;
77
- }
78
- const confirmation = await confirmLowerActiveLimit(runtime, ctx, result.field, limit);
79
- if (!confirmation.apply) continue;
80
- if (confirmation.goalId !== undefined && runtime.activeGoal?.id !== confirmation.goalId) {
81
- ctx.ui.notify(
82
- "The active goal changed while confirming the limit. No settings were changed.",
83
- "warning",
84
- );
85
- continue;
86
- }
87
- const next = withLimit(runtime.settings, result.field, limit);
88
- try {
89
- applyGoalSettings(runtime, next, ctx, {
90
- save: (settings) => (options.save ?? saveGoalSettings)(settings, settingsPath),
91
- });
92
- ctx.ui.notify(
93
- `${result.field === "automaticTurns" ? "Automatic response" : "No-progress"} limit: ${formatGoalLimit(limit)}.`,
94
- "info",
95
- );
96
- } catch (error) {
97
- ctx.ui.notify(`pi-goal settings save failed: ${formatError(error)}`, "error");
98
- }
277
+ return { kind: "rejected" as const };
278
+ }
279
+ const previous = runtime.settings.continuationLimits[field];
280
+ const limit = await resolveLimitSelection(field, itemId, previous, ctx);
281
+ if (limit === undefined || limit === previous) return { kind: "back" as const };
282
+ if ((runtime.activeGoal?.id ?? null) !== activeGoalId) {
283
+ ctx.ui.notify(
284
+ "The active goal changed while editing the safety setting. No settings were changed.",
285
+ "warning",
286
+ );
287
+ return { kind: "rejected" as const };
288
+ }
289
+ const confirmation = await confirmLowerActiveLimit(runtime, ctx, field, limit);
290
+ if (!confirmation.apply) return { kind: "rejected" as const };
291
+ if (confirmation.goalId !== undefined && runtime.activeGoal?.id !== confirmation.goalId) {
292
+ ctx.ui.notify(
293
+ "The active goal changed while confirming the limit. No settings were changed.",
294
+ "warning",
295
+ );
296
+ return { kind: "rejected" as const };
297
+ }
298
+ try {
299
+ applyGoalSettings(runtime, withLimit(runtime.settings, field, limit), ctx, {
300
+ save: (settings) => (options.save ?? saveGoalSettings)(settings, settingsPath),
301
+ });
302
+ ctx.ui.notify(formatLimitSuccess(field, limit), "info");
303
+ return { kind: "back" as const };
304
+ } catch (error) {
305
+ notifySettingsFailure(ctx, settingsPath, error);
306
+ return { kind: "rejected" as const };
99
307
  }
100
308
  }
101
309
 
@@ -146,9 +354,8 @@ export function applyGoalSettings(
146
354
  }
147
355
  }
148
356
 
149
- export function parseGoalLimit(value: string): number | null | undefined {
150
- const normalized = value.trim().toLowerCase();
151
- if (normalized === "unlimited" || normalized === "off") return null;
357
+ export function parseGoalLimit(value: string): number | undefined {
358
+ const normalized = value.trim();
152
359
  if (!/^\d+$/u.test(normalized)) return undefined;
153
360
  const parsed = Number(normalized);
154
361
  return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
@@ -158,110 +365,31 @@ export function formatGoalLimit(value: number | null) {
158
365
  return value === null ? "Unlimited" : String(value);
159
366
  }
160
367
 
161
- async function showSettingsScreen(
162
- runtime: GoalRuntime,
368
+ async function resolveLimitSelection(
369
+ field: LimitField,
370
+ selection: LimitSelection,
371
+ previous: number | null,
163
372
  ctx: ExtensionCommandContext,
164
- settingsPath: string,
165
- options: GoalSettingsUiOptions,
166
- ): Promise<SettingsScreenResult> {
167
- let saveQueue = Promise.resolve();
168
- const latestRequested = new Map<string, string>();
169
- return ctx.ui.custom<SettingsScreenResult>((tui, theme, _keybindings, done) => {
170
- const settings = runtime.settings;
171
- const items: SettingItem[] = [
172
- {
173
- id: "toolVisibility",
174
- label: "Goal tools",
175
- description: "Keep terminal Goal tools visible, or reveal them after the first goal.",
176
- currentValue: visibilityLabel(settings.toolVisibility),
177
- values: ["Always", "After first goal"],
178
- },
179
- {
180
- id: "experimentalGoals",
181
- label: "Ordered goal queue",
182
- description: "Enable experimental add, prioritize, skip, and drop-last workflows.",
183
- currentValue: settings.experimental.goals ? "Experimental" : "Off",
184
- values: ["Off", "Experimental"],
185
- },
186
- limitItem(
187
- "automaticTurns",
188
- "Automatic response limit",
189
- "Pause after this many Goal-owned automatic model responses.",
190
- settings.continuationLimits.automaticTurns,
191
- ),
192
- limitItem(
193
- "noProgressTurns",
194
- "No-progress limit",
195
- "Pause after this many repeated or empty tool-free automatic runs.",
196
- settings.continuationLimits.noProgressTurns,
197
- ),
198
- ];
199
- const container = new Container();
200
- container.addChild(new Text(theme.fg("accent", theme.bold("Pi Goal Settings")), 1, 0));
201
- container.addChild(
202
- new Text(theme.fg("muted", `User settings · ${safeTerminalText(settingsPath)}`), 1, 0),
203
- );
204
- let settingsList: SettingsList;
205
- let closing = false;
206
- const closeAfterSaves = (result: SettingsScreenResult) => {
207
- if (closing) return;
208
- closing = true;
209
- void saveQueue.then(() => done(result));
210
- };
211
- settingsList = new SettingsList(
212
- items,
213
- Math.min(items.length + 2, 15),
214
- getSettingsListTheme(),
215
- (id, newValue) => {
216
- if (closing) return;
217
- if ((id === "automaticTurns" || id === "noProgressTurns") && newValue === "Edit…") {
218
- closeAfterSaves({ kind: "limit", field: id });
219
- return;
220
- }
221
- if (id === "experimentalGoals") {
222
- closeAfterSaves({ kind: "queue", enabled: newValue === "Experimental" });
223
- return;
224
- }
225
- if (id !== "toolVisibility") return;
226
- latestRequested.set(id, newValue);
227
- const operation = saveQueue.then(async () => {
228
- const previousValue = visibilityLabel(runtime.settings.toolVisibility);
229
- try {
230
- const next = {
231
- ...structuredClone(runtime.settings),
232
- toolVisibility: newValue === "Always" ? "always" : "after-first-goal",
233
- } satisfies GoalSettings;
234
- applyGoalSettings(runtime, next, ctx, {
235
- save: (value) => (options.save ?? saveGoalSettings)(value, settingsPath),
236
- });
237
- ctx.ui.notify(`Goal tools: ${newValue}.`, "info");
238
- } catch (error) {
239
- if (latestRequested.get(id) === newValue) {
240
- settingsList.updateValue(id, previousValue);
241
- }
242
- ctx.ui.notify(`pi-goal settings save failed: ${formatError(error)}`, "error");
243
- tui.requestRender();
244
- }
245
- });
246
- saveQueue = operation.catch(() => undefined);
247
- },
248
- () => closeAfterSaves(undefined),
249
- { enableSearch: false },
373
+ ): Promise<number | null | undefined> {
374
+ if (selection === "unlimited" || selection === "off") return null;
375
+ if (selection === "default") {
376
+ return DEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns;
377
+ }
378
+ while (true) {
379
+ const raw = await ctx.ui.input(
380
+ field === "automaticTurns"
381
+ ? "Maximum automatic responses (whole number greater than 0)"
382
+ : "Repeated-run threshold (whole number greater than 0)",
383
+ previous === null ? "Positive whole number" : String(previous),
250
384
  );
251
- container.addChild(settingsList);
252
- container.addChild(
253
- new Text(theme.fg("dim", "↑↓ navigate · enter/space change · esc close"), 1, 0),
385
+ if (raw === undefined) return undefined;
386
+ const parsed = parseGoalLimit(raw);
387
+ if (parsed !== undefined) return parsed;
388
+ ctx.ui.notify(
389
+ `Enter a whole number greater than 0. Choose ${field === "automaticTurns" ? "Unlimited" : "Off"} from the previous screen if you do not want a limit.`,
390
+ "warning",
254
391
  );
255
- return {
256
- render: (width: number) => container.render(width),
257
- invalidate: () => container.invalidate(),
258
- handleInput(data: string) {
259
- if (closing) return;
260
- settingsList.handleInput?.(data);
261
- tui.requestRender();
262
- },
263
- };
264
- });
392
+ }
265
393
  }
266
394
 
267
395
  async function nextQueueSettings(
@@ -378,7 +506,7 @@ async function confirmLowerActiveLimit(
378
506
  if (used < limit) return { apply: true };
379
507
  return {
380
508
  apply: await ctx.ui.confirm(
381
- "Apply reached safety limit?",
509
+ "Apply limit and pause now?",
382
510
  `The active goal has already used ${used}. Setting this limit to ${limit} will pause it immediately without deleting progress.`,
383
511
  ),
384
512
  goalId: goal.id,
@@ -392,15 +520,32 @@ function withLimit(settings: GoalSettings, field: LimitField, value: number | nu
392
520
  };
393
521
  }
394
522
 
395
- function limitItem(id: LimitField, label: string, description: string, value: number | null) {
396
- const currentValue = formatGoalLimit(value);
397
- return {
398
- id,
399
- label,
400
- description,
401
- currentValue,
402
- values: [currentValue, "Edit…"],
403
- } satisfies SettingItem;
523
+ function formatAutomaticSettingValue(value: number | null) {
524
+ return value === null ? "Unlimited" : `≤${value}`;
525
+ }
526
+
527
+ function formatNoProgressSettingValue(value: number | null) {
528
+ if (value === null) return "Off";
529
+ return `${value} ${value === 1 ? "run" : "runs"}`;
530
+ }
531
+
532
+ function formatAutomaticWork(value: number | null) {
533
+ return value === null ? "Unlimited" : `Up to ${value} responses`;
534
+ }
535
+
536
+ function formatNoProgressProtection(value: number | null) {
537
+ if (value === null) return "Off";
538
+ return `After ${value} repeated ${value === 1 ? "run" : "runs"}`;
539
+ }
540
+
541
+ function formatLimitSuccess(field: LimitField, value: number | null) {
542
+ return field === "automaticTurns"
543
+ ? `Automatic work: ${formatAutomaticWork(value)}.`
544
+ : `No-progress guard: ${formatNoProgressProtection(value)}.`;
545
+ }
546
+
547
+ function isLimitSelection(value: string): value is LimitSelection {
548
+ return value === "unlimited" || value === "default" || value === "custom" || value === "off";
404
549
  }
405
550
 
406
551
  function visibilityLabel(value: GoalSettings["toolVisibility"]) {
@@ -415,6 +560,17 @@ function retainedGoalCount(runtime: GoalRuntime) {
415
560
  );
416
561
  }
417
562
 
563
+ function notifySettingsFailure(ctx: ExtensionCommandContext, settingsPath: string, error: unknown) {
564
+ const path = safeTerminalText(settingsPath);
565
+ const detail = safeTerminalText(formatError(error));
566
+ ctx.ui.notify(
567
+ error instanceof AggregateError
568
+ ? `Could not apply Goal settings, and rollback was incomplete. Check ${path}, run /reload, and verify the effective settings before retrying: ${detail}`
569
+ : `Could not save Goal settings; the previous value remains. Check ${path} and retry: ${detail}`,
570
+ "error",
571
+ );
572
+ }
573
+
418
574
  function safeTerminalText(value: string) {
419
575
  return [...value]
420
576
  .map((character) => {
package/src/settings.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { linkSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { basename, dirname, join } from "node:path";
4
4
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
5
5
 
@@ -23,26 +23,15 @@ export interface GoalSettings {
23
23
  export const DEFAULT_GOAL_SETTINGS: GoalSettings = {
24
24
  toolVisibility: "always",
25
25
  experimental: { goals: false },
26
- continuationLimits: { automaticTurns: 25, noProgressTurns: 3 },
26
+ continuationLimits: { automaticTurns: null, noProgressTurns: 3 },
27
27
  };
28
28
 
29
- export const DEFAULT_GOAL_SETTINGS_DOCUMENT = `${JSON.stringify(DEFAULT_GOAL_SETTINGS, null, 2)}\n`;
30
-
31
29
  export type GoalSettingsLoadResult =
32
30
  | { kind: "missing" }
33
31
  | { kind: "invalid"; reason: string }
34
32
  | { kind: "loaded"; settings: GoalSettings };
35
33
 
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
- }
34
+ export type GoalSettingsLoadIssue = Extract<GoalSettingsLoadResult, { kind: "invalid" }>;
46
35
 
47
36
  interface GoalSettingsSaveFileSystem {
48
37
  mkdirSync: typeof mkdirSync;
@@ -116,51 +105,6 @@ function normalizeContinuationLimit(
116
105
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;
117
106
  }
118
107
 
119
- export function loadOrCreateGoalSettings(
120
- settingsPath = join(getAgentDir(), GOAL_SETTINGS_FILE),
121
- overrides: Partial<GoalSettingsInitializationFileSystem> = {},
122
- ): GoalSettingsInitializationResult {
123
- const loaded = readGoalSettings(settingsPath);
124
- if (loaded.kind !== "missing") return loaded;
125
-
126
- const fs = { mkdirSync, writeFileSync, linkSync, rmSync, ...overrides };
127
- const temporaryPath = join(
128
- dirname(settingsPath),
129
- `.${basename(settingsPath)}.${randomUUID()}.tmp`,
130
- );
131
- try {
132
- fs.mkdirSync(dirname(settingsPath), { recursive: true });
133
- fs.writeFileSync(temporaryPath, DEFAULT_GOAL_SETTINGS_DOCUMENT, {
134
- encoding: "utf8",
135
- flag: "wx",
136
- });
137
- try {
138
- fs.linkSync(temporaryPath, settingsPath);
139
- } catch (error) {
140
- if (!isAlreadyExistsError(error)) throw error;
141
- }
142
-
143
- const published = readGoalSettings(settingsPath);
144
- return published.kind === "missing"
145
- ? {
146
- kind: "create-failed",
147
- reason: `${settingsPath}: settings file disappeared during initialization`,
148
- }
149
- : published;
150
- } catch (error) {
151
- return {
152
- kind: "create-failed",
153
- reason: `${settingsPath}: ${formatError(error)}`,
154
- };
155
- } finally {
156
- try {
157
- fs.rmSync(temporaryPath, { force: true });
158
- } catch {
159
- // Best-effort cleanup must not replace the initialization result.
160
- }
161
- }
162
- }
163
-
164
108
  export function saveGoalSettings(
165
109
  settings: GoalSettings,
166
110
  settingsPath = join(getAgentDir(), GOAL_SETTINGS_FILE),
@@ -248,10 +192,6 @@ function isNodeError(error: unknown): error is NodeJS.ErrnoException {
248
192
  return error instanceof Error && "code" in error;
249
193
  }
250
194
 
251
- function isAlreadyExistsError(error: unknown): boolean {
252
- return isNodeError(error) && error.code === "EEXIST";
253
- }
254
-
255
195
  function formatError(error: unknown) {
256
196
  return error instanceof Error ? error.message : String(error);
257
197
  }