@narumitw/pi-goal 0.34.1 → 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,7 +9,9 @@ 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.
@@ -70,7 +72,9 @@ built-in defaults without creating the file:
70
72
  }
71
73
  ```
72
74
 
73
- Use `/goal` → **Settings…** in the TUI to create or update the file interactively, or create and edit it directly. The screen keeps all four controls on one level in task order:
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:
74
78
 
75
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.
76
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.
@@ -118,7 +122,12 @@ Tool visibility is a baseline, not ownership of Pi's global active-tool list. Pl
118
122
  /goal skip
119
123
  ```
120
124
 
121
- - 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. An active goal shows automatic-response state as **_used_ automatic responses · Unlimited** or **_used_/_limit_ automatic responses**. Status, Settings, Help, queue management, Clear, and Close remain shallow, labeled routes. Arrow keys navigate, Enter selects, and Escape cancels or returns 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.
122
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.
123
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.
124
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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-goal",
3
- "version": "0.34.1",
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
@@ -61,6 +61,8 @@ const EXPERIMENTAL_GOALS_WARNING =
61
61
  const MAX_BLOCKER_REASON_LENGTH = 1_000;
62
62
  const MAX_BLOCKER_EVIDENCE_LENGTH = 4_000;
63
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.
64
66
  function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
65
67
  const runtime = new GoalRuntime(pi);
66
68
  const commands = new GoalCommandController(runtime);
@@ -471,6 +473,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
471
473
  });
472
474
 
473
475
  pi.on("session_start", async (_event, ctx) => {
476
+ runtime.replaceMenuSession();
474
477
  clearCompletionStatusTimer();
475
478
  clearContinuationTracking();
476
479
  clearPendingGoalPrompts();
@@ -589,6 +592,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
589
592
  });
590
593
 
591
594
  pi.on("session_shutdown", (_event, ctx) => {
595
+ runtime.closeMenuSession();
592
596
  if (runtime.activeGoal) {
593
597
  if (!runtime.queueFrozen && runtime.activeGoal.status === "active") {
594
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;
@@ -120,57 +137,132 @@ export async function showGoalManager(
120
137
  commands.showGoal(ctx);
121
138
  return;
122
139
  }
123
- while (true) {
124
- refreshGoalMenuState(runtime, ctx);
125
- const state = buildGoalMenuState(runtime);
126
- const displayedGoal = runtime.activeGoal;
127
- const selected = await ctx.ui.select(state.title, state.actions);
128
- if (!selected || selected === GOAL_MENU_ACTIONS.close) return;
129
- switch (selected) {
130
- 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 () => {
131
216
  await startFromMenu(commands, ctx);
132
- return;
133
- case GOAL_MENU_ACTIONS.startBudget:
217
+ return { kind: "close" };
218
+ },
219
+ "start-budget": async () => {
134
220
  await startFromMenu(commands, ctx, true);
135
- return;
136
- case GOAL_MENU_ACTIONS.pause:
137
- 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
+ }
138
227
  commands.pauseGoal(ctx);
139
- return;
140
- case GOAL_MENU_ACTIONS.resume:
141
- 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
+ }
142
234
  await commands.resumeGoal(ctx);
143
- return;
144
- case GOAL_MENU_ACTIONS.increaseBudget:
145
- 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
+ }
146
241
  await increaseBudget(runtime, commands, ctx);
147
- return;
148
- case GOAL_MENU_ACTIONS.edit:
149
- 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
+ }
150
248
  await editFromMenu(runtime, commands, ctx);
151
- return;
152
- case GOAL_MENU_ACTIONS.replace:
249
+ return { kind: "close" };
250
+ },
251
+ replace: async () => {
153
252
  await startFromMenu(commands, ctx);
154
- return;
155
- case GOAL_MENU_ACTIONS.status:
156
- commands.showGoal(ctx);
157
- return;
158
- case GOAL_MENU_ACTIONS.queue:
159
- if ((await showQueueMenu(runtime, commands, ctx)) === "back") continue;
160
- return;
161
- case GOAL_MENU_ACTIONS.settings:
253
+ return { kind: "close" };
254
+ },
255
+ settings: async () => {
162
256
  await showSettings(ctx);
163
- continue;
164
- case GOAL_MENU_ACTIONS.help:
165
- ctx.ui.notify(goalHelp(), "info");
166
- return;
167
- case GOAL_MENU_ACTIONS.clear: {
257
+ return { kind: "stay" };
258
+ },
259
+ clear: async () => {
168
260
  const previewedQueue = goalQueueIdentity(
169
261
  runtime.activeGoal,
170
262
  runtime.queuedGoals,
171
263
  runtime.pendingQueueAction,
172
264
  );
173
- if (!(await confirmClear(runtime, ctx))) continue;
265
+ if (!(await confirmClear(runtime, ctx))) return { kind: "stay" };
174
266
  if (
175
267
  goalQueueIdentity(runtime.activeGoal, runtime.queuedGoals, runtime.pendingQueueAction) !==
176
268
  previewedQueue
@@ -179,13 +271,90 @@ export async function showGoalManager(
179
271
  "The goal queue changed while the dialog was open. Reopen /goal and try again.",
180
272
  "warning",
181
273
  );
182
- continue;
274
+ return { kind: "stay" };
183
275
  }
184
276
  commands.clearGoal(ctx);
185
- return;
186
- }
187
- }
188
- }
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" };
189
358
  }
190
359
 
191
360
  function refreshGoalMenuState(runtime: GoalMenuRuntimeView, ctx: ExtensionCommandContext) {
@@ -276,66 +445,6 @@ async function askTokenBudget(ctx: ExtensionCommandContext, current?: number) {
276
445
  return budget;
277
446
  }
278
447
 
279
- async function showQueueMenu(
280
- runtime: GoalMenuRuntimeView,
281
- commands: GoalCommandController,
282
- ctx: ExtensionCommandContext,
283
- ) {
284
- const goal = runtime.activeGoal;
285
- if (!goal) return;
286
- const actions: string[] = [QUEUE_ACTIONS.add, QUEUE_ACTIONS.prioritize];
287
- if (runtime.queuedGoals.length > 0) actions.push(QUEUE_ACTIONS.skip, QUEUE_ACTIONS.dropLast);
288
- actions.push(QUEUE_ACTIONS.back);
289
- const selected = await ctx.ui.select(
290
- `Goal queue · ${runtime.queuedGoals.length + 1} total\nCurrent: ${safeGoalMenuText(goal.text)}`,
291
- actions,
292
- );
293
- if (!selected || selected === QUEUE_ACTIONS.back) return "back" as const;
294
- if (selected === QUEUE_ACTIONS.add) {
295
- const objective = (await ctx.ui.editor("Add goal to queue", ""))?.trim();
296
- if (objective) await commands.addGoal(objective, undefined, ctx);
297
- return;
298
- }
299
- if (selected === QUEUE_ACTIONS.prioritize) {
300
- const objective = (await ctx.ui.editor("Prioritize goal", ""))?.trim();
301
- if (!objective || !requireCurrentQueueHead(runtime, goal, ctx)) return;
302
- const confirmed = await ctx.ui.confirm(
303
- "Prioritize goal?",
304
- `New priority goal:\n${safeGoalMenuText(objective, 4_000)}\n\nCurrent goal moved to the queue:\n${safeGoalMenuText(goal.text, 4_000)}`,
305
- );
306
- if (confirmed && requireCurrentQueueHead(runtime, goal, ctx)) {
307
- await commands.prioritizeGoal(objective, undefined, ctx);
308
- }
309
- return;
310
- }
311
- if (selected === QUEUE_ACTIONS.skip) {
312
- const next = runtime.queuedGoals[0];
313
- const nextEffect = !next
314
- ? "No goal remains"
315
- : next.status === "queued"
316
- ? `Start next goal:\n${safeGoalMenuText(next.text, 4_000)}`
317
- : `Next goal remains ${displayStatus(next.status).toLowerCase()}:\n${safeGoalMenuText(next.text, 4_000)}`;
318
- const confirmed = await ctx.ui.confirm(
319
- "Skip current goal?",
320
- `Remove current goal:\n${safeGoalMenuText(goal.text, 4_000)}\n\n${nextEffect}`,
321
- );
322
- if (confirmed && requireCurrentQueueSelection(runtime, goal, next, "first", ctx)) {
323
- await commands.skipGoal(ctx);
324
- }
325
- return;
326
- }
327
- if (selected === QUEUE_ACTIONS.dropLast) {
328
- const last = runtime.queuedGoals.at(-1) ?? goal;
329
- const confirmed = await ctx.ui.confirm(
330
- "Drop last goal?",
331
- `Remove from queue:\n${safeGoalMenuText(last.text, 4_000)}`,
332
- );
333
- if (confirmed && requireCurrentQueueSelection(runtime, goal, last, "last", ctx)) {
334
- commands.dropLastGoal(ctx);
335
- }
336
- }
337
- }
338
-
339
448
  async function confirmClear(runtime: GoalMenuRuntimeView, ctx: ExtensionCommandContext) {
340
449
  const goals = [runtime.activeGoal, ...runtime.queuedGoals].filter(
341
450
  (goal): goal is ActiveGoal => goal !== undefined,
package/src/runtime.ts CHANGED
@@ -169,6 +169,9 @@ const CONTRADICTORY_COMPLETION_PATTERNS = [
169
169
  // and the cross-cutting invariants used by command and lifecycle orchestration.
170
170
  // Keep this state machine cohesive despite its size: prompt ownership, continuation,
171
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.
172
175
  export class GoalRuntime {
173
176
  settings: GoalSettings = DEFAULT_GOAL_SETTINGS;
174
177
  settingsLoadIssue?: GoalSettingsLoadIssue;
@@ -199,6 +202,8 @@ export class GoalRuntime {
199
202
  cancelledContinuationMarkers = new Set<string>();
200
203
  claimedContinuationMarkers = new Set<string>();
201
204
  pendingNonGoalInputs: PendingNonGoalInput[] = [];
205
+ menuGeneration = 0;
206
+ menuController = new AbortController();
202
207
 
203
208
  readonly pi: ExtensionAPI;
204
209
 
@@ -206,6 +211,17 @@ export class GoalRuntime {
206
211
  this.pi = pi;
207
212
  }
208
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
+
209
225
  canRecordGoalUsage(goalId?: string) {
210
226
  return (
211
227
  this.agentRunGoalId !== null &&
@@ -1,21 +1,6 @@
1
1
  import { join } from "node:path";
2
- import {
3
- type ExtensionCommandContext,
4
- getAgentDir,
5
- getSelectListTheme,
6
- getSettingsListTheme,
7
- } from "@earendil-works/pi-coding-agent";
8
- import {
9
- type Component,
10
- Container,
11
- matchesKey,
12
- type SelectItem,
13
- SelectList,
14
- type SettingItem,
15
- SettingsList,
16
- Text,
17
- truncateToWidth,
18
- } 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";
19
4
  import { checkpointGoalActiveTime } from "./accounting.js";
20
5
  import { abortCurrentTurn, type GoalRuntime, STATUS_KEY } from "./runtime.js";
21
6
  import {
@@ -37,23 +22,6 @@ interface GoalSettingsApplyOptions {
37
22
 
38
23
  type LimitField = "automaticTurns" | "noProgressTurns";
39
24
  type LimitSelection = "unlimited" | "default" | "custom" | "off";
40
- type SettingsScreenResult =
41
- | {
42
- kind: "limit";
43
- field: LimitField;
44
- selection: LimitSelection;
45
- activeGoalId: string | null;
46
- }
47
- | { kind: "queue"; enabled: boolean }
48
- | undefined;
49
-
50
- interface LimitChoiceStyles {
51
- title: (text: string) => string;
52
- muted: (text: string) => string;
53
- }
54
-
55
- type EnqueueSettingsChange = (operation: () => void | Promise<void>) => Promise<void>;
56
-
57
25
  export async function showGoalSettings(
58
26
  runtime: GoalRuntime,
59
27
  ctx: ExtensionCommandContext,
@@ -64,70 +32,278 @@ export async function showGoalSettings(
64
32
  ctx.ui.notify(`Edit pi-goal settings manually: ${safeTerminalText(settingsPath)}`, "info");
65
33
  return;
66
34
  }
67
-
68
- while (true) {
69
- const result = await showSettingsScreen(runtime, ctx, settingsPath, options);
70
- if (!result) return;
71
- if (result.kind === "queue") {
72
- const next = await nextQueueSettings(runtime, ctx, result.enabled);
73
- if (!next) continue;
74
- const wasFrozen = runtime.queueFrozen;
75
- try {
76
- applyGoalSettings(runtime, next, ctx, {
77
- save: (settings) => (options.save ?? saveGoalSettings)(settings, settingsPath),
78
- });
79
- if (wasFrozen && !runtime.queueFrozen) {
80
- try {
81
- await options.onQueueUnfrozen?.(ctx);
82
- } catch (error) {
83
- ctx.ui.notify(
84
- `Goal queue enabled, but automatic resume failed: ${safeTerminalText(formatError(error))}. Reopen /goal to retry.`,
85
- "warning",
86
- );
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
+ }
87
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" };
88
177
  }
89
- ctx.ui.notify(`Ordered goal queue: ${result.enabled ? "Experimental" : "Off"}.`, "info");
90
- } catch (error) {
91
- notifySettingsFailure(ctx, settingsPath, error);
92
- }
93
- return;
94
- }
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
+ }
95
188
 
96
- if ((runtime.activeGoal?.id ?? null) !== result.activeGoalId) {
97
- ctx.ui.notify(
98
- "The active goal changed while the safety setting was open. No settings were changed.",
99
- "warning",
100
- );
101
- continue;
102
- }
103
- const previous = runtime.settings.continuationLimits[result.field];
104
- const limit = await resolveLimitSelection(result, previous, ctx);
105
- if (limit === undefined || limit === previous) continue;
106
- if ((runtime.activeGoal?.id ?? null) !== result.activeGoalId) {
107
- ctx.ui.notify(
108
- "The active goal changed while editing the safety setting. No settings were changed.",
109
- "warning",
110
- );
111
- continue;
112
- }
113
- const confirmation = await confirmLowerActiveLimit(runtime, ctx, result.field, limit);
114
- if (!confirmation.apply) continue;
115
- if (confirmation.goalId !== undefined && runtime.activeGoal?.id !== confirmation.goalId) {
116
- ctx.ui.notify(
117
- "The active goal changed while confirming the limit. No settings were changed.",
118
- "warning",
119
- );
120
- continue;
121
- }
122
- const next = withLimit(runtime.settings, result.field, limit);
123
- try {
124
- applyGoalSettings(runtime, next, ctx, {
125
- save: (settings) => (options.save ?? saveGoalSettings)(settings, settingsPath),
126
- });
127
- ctx.ui.notify(formatLimitSuccess(result.field, limit), "info");
128
- } catch (error) {
129
- notifySettingsFailure(ctx, settingsPath, error);
130
- }
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",
276
+ );
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 };
131
307
  }
132
308
  }
133
309
 
@@ -189,313 +365,19 @@ export function formatGoalLimit(value: number | null) {
189
365
  return value === null ? "Unlimited" : String(value);
190
366
  }
191
367
 
192
- async function showSettingsScreen(
193
- runtime: GoalRuntime,
194
- ctx: ExtensionCommandContext,
195
- settingsPath: string,
196
- options: GoalSettingsUiOptions,
197
- ): Promise<SettingsScreenResult> {
198
- if (runtime.settingsLoadIssue?.kind === "invalid") {
199
- return showReadOnlySettingsScreen(runtime, ctx, settingsPath);
200
- }
201
-
202
- let saveQueue = Promise.resolve();
203
- const enqueueSettingsChange: EnqueueSettingsChange = (operation) => {
204
- const queued = saveQueue.then(operation);
205
- saveQueue = queued.catch(() => undefined);
206
- return queued;
207
- };
208
- return ctx.ui.custom<SettingsScreenResult>((tui, theme, _keybindings, done) => {
209
- const container = new Container();
210
- container.addChild(
211
- dynamicText("Pi Goal Settings", (text) => theme.fg("accent", theme.bold(text))),
212
- );
213
- container.addChild(
214
- dynamicText(`User settings · ${safeTerminalText(settingsPath)}`, (text) =>
215
- theme.fg("muted", text),
216
- ),
217
- );
218
- let closing = false;
219
- const closeAfterSaves = (result: SettingsScreenResult) => {
220
- if (closing) return;
221
- closing = true;
222
- void saveQueue.then(() => done(result));
223
- };
224
- const requestRender = () => tui.requestRender();
225
- const previewGoalIds = new Map<LimitField, string | null>();
226
- const styles: LimitChoiceStyles = {
227
- title: (text) => theme.fg("accent", theme.bold(text)),
228
- muted: (text) => theme.fg("muted", text),
229
- };
230
- let limitChoiceOpen = false;
231
- const items: SettingItem[] = [
232
- limitItem(
233
- "automaticTurns",
234
- "Automatic work",
235
- "Choose whether Goal can continue without a response-count cap.",
236
- runtime.settings.continuationLimits.automaticTurns,
237
- (doneSelection) => {
238
- previewGoalIds.set("automaticTurns", runtime.activeGoal?.id ?? null);
239
- limitChoiceOpen = true;
240
- return createLimitChoiceComponent(runtime, "automaticTurns", styles, (selection) => {
241
- limitChoiceOpen = false;
242
- doneSelection(selection);
243
- });
244
- },
245
- ),
246
- limitItem(
247
- "noProgressTurns",
248
- "No-progress guard",
249
- "Pause after repeated or empty tool-free automatic runs.",
250
- runtime.settings.continuationLimits.noProgressTurns,
251
- (doneSelection) => {
252
- previewGoalIds.set("noProgressTurns", runtime.activeGoal?.id ?? null);
253
- limitChoiceOpen = true;
254
- return createLimitChoiceComponent(runtime, "noProgressTurns", styles, (selection) => {
255
- limitChoiceOpen = false;
256
- doneSelection(selection);
257
- });
258
- },
259
- ),
260
- {
261
- id: "toolVisibility",
262
- label: "Goal tools",
263
- description: "Keep terminal Goal tools visible, or reveal them after the first goal.",
264
- currentValue: visibilityLabel(runtime.settings.toolVisibility),
265
- values: ["Always", "After first goal"],
266
- },
267
- {
268
- id: "experimentalGoals",
269
- label: "Ordered goal queue",
270
- description: "Enable experimental add, prioritize, skip, and drop-last workflows.",
271
- currentValue: runtime.settings.experimental.goals ? "Experimental" : "Off",
272
- values: ["Off", "Experimental"],
273
- },
274
- ];
275
- const latestRequested = new Map<string, string>();
276
- let settingsList: SettingsList;
277
- settingsList = new SettingsList(
278
- items,
279
- Math.min(items.length + 2, 15),
280
- goalSettingsListTheme("Goal menu"),
281
- (id, newValue) => {
282
- if (closing) return;
283
- if (id === "automaticTurns" || id === "noProgressTurns") {
284
- if (!isLimitSelection(newValue)) return;
285
- closeAfterSaves({
286
- kind: "limit",
287
- field: id,
288
- selection: newValue,
289
- activeGoalId: previewGoalIds.get(id) ?? null,
290
- });
291
- return;
292
- }
293
- if (id === "experimentalGoals") {
294
- closeAfterSaves({ kind: "queue", enabled: newValue === "Experimental" });
295
- return;
296
- }
297
- if (id !== "toolVisibility") return;
298
- latestRequested.set(id, newValue);
299
- void enqueueSettingsChange(async () => {
300
- const previousValue = visibilityLabel(runtime.settings.toolVisibility);
301
- try {
302
- const next = {
303
- ...structuredClone(runtime.settings),
304
- toolVisibility: newValue === "Always" ? "always" : "after-first-goal",
305
- } satisfies GoalSettings;
306
- applyGoalSettings(runtime, next, ctx, {
307
- save: (value) => (options.save ?? saveGoalSettings)(value, settingsPath),
308
- });
309
- requestRender();
310
- ctx.ui.notify(`Goal tools: ${newValue}.`, "info");
311
- } catch (error) {
312
- if (latestRequested.get(id) === newValue) {
313
- settingsList.updateValue(id, previousValue);
314
- }
315
- notifySettingsFailure(ctx, settingsPath, error);
316
- }
317
- });
318
- },
319
- () => closeAfterSaves(undefined),
320
- { enableSearch: false },
321
- );
322
- container.addChild(goalSettingsListComponent(settingsList, () => limitChoiceOpen));
323
- return {
324
- render: (width: number) => container.render(width),
325
- invalidate: () => container.invalidate(),
326
- handleInput(data: string) {
327
- if (closing) return;
328
- settingsList.handleInput?.(data);
329
- tui.requestRender();
330
- },
331
- };
332
- });
333
- }
334
-
335
- function showReadOnlySettingsScreen(
336
- runtime: GoalRuntime,
337
- ctx: ExtensionCommandContext,
338
- settingsPath: string,
339
- ): Promise<SettingsScreenResult> {
340
- return ctx.ui.custom<SettingsScreenResult>((_tui, theme, keybindings, done) => {
341
- const container = new Container();
342
- container.addChild(
343
- dynamicText("Pi Goal Settings · Read only", (text) => theme.fg("accent", theme.bold(text))),
344
- );
345
- container.addChild(
346
- dynamicText(
347
- `Invalid settings file. Pi-goal is using built-in defaults. Fix ${safeTerminalText(settingsPath)} and run /reload. The file will not be overwritten.`,
348
- (text) => theme.fg("warning", text),
349
- ),
350
- );
351
- container.addChild(
352
- dynamicText(() =>
353
- [
354
- `Automatic work: ${formatAutomaticWork(runtime.settings.continuationLimits.automaticTurns)}`,
355
- `No-progress guard: ${formatNoProgressProtection(runtime.settings.continuationLimits.noProgressTurns)}`,
356
- `Goal tools: ${visibilityLabel(runtime.settings.toolVisibility)}`,
357
- `Ordered goal queue: ${runtime.settings.experimental.goals ? "Experimental" : "Off"}`,
358
- ].join("\n"),
359
- ),
360
- );
361
- container.addChild(dynamicText("Esc back to Goal menu", (text) => theme.fg("dim", text)));
362
- return {
363
- render: (width: number) => container.render(width),
364
- invalidate: () => container.invalidate(),
365
- handleInput(data: string) {
366
- if (
367
- keybindings.matches(data, "tui.select.cancel") ||
368
- matchesKey(data, "escape") ||
369
- matchesKey(data, "ctrl+c")
370
- ) {
371
- done(undefined);
372
- }
373
- },
374
- };
375
- });
376
- }
377
-
378
- function createLimitChoiceComponent(
379
- runtime: GoalRuntime,
380
- field: LimitField,
381
- styles: LimitChoiceStyles,
382
- done: (selectedValue?: string) => void,
383
- ): Component {
384
- const value = runtime.settings.continuationLimits[field];
385
- const goal = runtime.activeGoal;
386
- const items = limitChoices(field, value, goal?.automaticModelTurns);
387
- const selectionItems = items.map(({ value: itemValue, label }) => ({
388
- value: itemValue,
389
- label,
390
- }));
391
- const descriptions = new Map(items.map((item) => [item.value, item.description ?? ""]));
392
- const container = new Container();
393
- container.addChild(
394
- dynamicText(field === "automaticTurns" ? "Automatic work" : "No-progress guard", styles.title),
395
- );
396
- container.addChild(
397
- dynamicText(
398
- field === "automaticTurns"
399
- ? `Current: ${formatAutomaticWork(value)}`
400
- : `Current: ${formatNoProgressProtection(value)}`,
401
- styles.muted,
402
- ),
403
- );
404
- if (goal) {
405
- container.addChild(
406
- dynamicText(
407
- field === "automaticTurns"
408
- ? `Active goal: ${goal.automaticModelTurns} automatic responses used`
409
- : `Active goal: ${goal.toolFreeRepeatCount} repeated or empty runs detected`,
410
- styles.muted,
411
- ),
412
- );
413
- }
414
- const selectedIndex = selectedLimitChoiceIndex(field, value);
415
- const selectList = new SelectList(
416
- selectionItems,
417
- Math.min(selectionItems.length, 8),
418
- getSelectListTheme(),
419
- );
420
- selectList.setSelectedIndex(selectedIndex);
421
- let selectedDescription = descriptions.get(selectionItems[selectedIndex]?.value ?? "") ?? "";
422
- const description = dynamicText(() => selectedDescription, styles.muted);
423
- selectList.onSelectionChange = (item) => {
424
- selectedDescription = descriptions.get(item.value) ?? "";
425
- };
426
- selectList.onSelect = (item) => done(item.value);
427
- selectList.onCancel = () => done();
428
- container.addChild(selectList);
429
- container.addChild(description);
430
- container.addChild(dynamicText("↑↓ navigate · Enter select · Esc back", styles.muted));
431
- return {
432
- render: (width: number) => container.render(width),
433
- invalidate: () => container.invalidate(),
434
- handleInput(data: string) {
435
- selectList.handleInput(data);
436
- },
437
- };
438
- }
439
-
440
- function limitChoices(
441
- field: LimitField,
442
- value: number | null,
443
- automaticTurnsUsed: number | undefined,
444
- ): SelectItem[] {
445
- if (field === "automaticTurns") {
446
- const unlimitedDescription =
447
- value === null
448
- ? "No response-count cap. Completion, manual pause, blockers, provider limits, and other configured guards still apply."
449
- : automaticTurnsUsed === undefined
450
- ? `Remove the current ${value}-response cap. Goal work will have no response-count cap; other configured stop conditions remain.`
451
- : `Remove the current ${value}-response cap. The active goal has used ${automaticTurnsUsed} responses; other configured stop conditions remain.`;
452
- return [
453
- { value: "unlimited", label: "Unlimited (default)", description: unlimitedDescription },
454
- {
455
- value: "custom",
456
- label: "Set a maximum…",
457
- description: "Pause after a whole number of Goal-owned automatic responses.",
458
- },
459
- ];
460
- }
461
- const defaultLimit = DEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns;
462
- return [
463
- {
464
- value: "default",
465
- label: `After ${defaultLimit} repeated runs (default)`,
466
- description: "Pause after the default number of repeated or empty tool-free runs.",
467
- },
468
- {
469
- value: "custom",
470
- label: "Set threshold…",
471
- description: "Choose a whole number of repeated or empty runs before pausing.",
472
- },
473
- {
474
- value: "off",
475
- label: "Off",
476
- description: "Do not pause based on repeated or empty tool-free runs.",
477
- },
478
- ];
479
- }
480
-
481
- function selectedLimitChoiceIndex(field: LimitField, value: number | null) {
482
- if (field === "automaticTurns") return value === null ? 0 : 1;
483
- if (value === null) return 2;
484
- return value === DEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns ? 0 : 1;
485
- }
486
-
487
368
  async function resolveLimitSelection(
488
- result: Extract<SettingsScreenResult, { kind: "limit" }>,
369
+ field: LimitField,
370
+ selection: LimitSelection,
489
371
  previous: number | null,
490
372
  ctx: ExtensionCommandContext,
491
373
  ): Promise<number | null | undefined> {
492
- if (result.selection === "unlimited" || result.selection === "off") return null;
493
- if (result.selection === "default") {
374
+ if (selection === "unlimited" || selection === "off") return null;
375
+ if (selection === "default") {
494
376
  return DEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns;
495
377
  }
496
378
  while (true) {
497
379
  const raw = await ctx.ui.input(
498
- result.field === "automaticTurns"
380
+ field === "automaticTurns"
499
381
  ? "Maximum automatic responses (whole number greater than 0)"
500
382
  : "Repeated-run threshold (whole number greater than 0)",
501
383
  previous === null ? "Positive whole number" : String(previous),
@@ -504,7 +386,7 @@ async function resolveLimitSelection(
504
386
  const parsed = parseGoalLimit(raw);
505
387
  if (parsed !== undefined) return parsed;
506
388
  ctx.ui.notify(
507
- `Enter a whole number greater than 0. Choose ${result.field === "automaticTurns" ? "Unlimited" : "Off"} from the previous screen if you do not want a limit.`,
389
+ `Enter a whole number greater than 0. Choose ${field === "automaticTurns" ? "Unlimited" : "Off"} from the previous screen if you do not want a limit.`,
508
390
  "warning",
509
391
  );
510
392
  }
@@ -638,25 +520,6 @@ function withLimit(settings: GoalSettings, field: LimitField, value: number | nu
638
520
  };
639
521
  }
640
522
 
641
- function limitItem(
642
- id: LimitField,
643
- label: string,
644
- description: string,
645
- value: number | null,
646
- submenu: (done: (selectedValue?: string) => void) => Component,
647
- ): SettingItem {
648
- return {
649
- id,
650
- label,
651
- description,
652
- currentValue:
653
- id === "automaticTurns"
654
- ? formatAutomaticSettingValue(value)
655
- : formatNoProgressSettingValue(value),
656
- submenu: (_currentValue, done) => submenu(done),
657
- };
658
- }
659
-
660
523
  function formatAutomaticSettingValue(value: number | null) {
661
524
  return value === null ? "Unlimited" : `≤${value}`;
662
525
  }
@@ -681,18 +544,6 @@ function formatLimitSuccess(field: LimitField, value: number | null) {
681
544
  : `No-progress guard: ${formatNoProgressProtection(value)}.`;
682
545
  }
683
546
 
684
- function goalSettingsListTheme(backTarget: string) {
685
- const theme = getSettingsListTheme();
686
- return {
687
- ...theme,
688
- hint(text: string) {
689
- return text.includes("Enter/Space to change")
690
- ? theme.hint(` Enter/Space to select · Esc back to ${backTarget}`)
691
- : theme.hint(text);
692
- },
693
- };
694
- }
695
-
696
547
  function isLimitSelection(value: string): value is LimitSelection {
697
548
  return value === "unlimited" || value === "default" || value === "custom" || value === "off";
698
549
  }
@@ -720,33 +571,6 @@ function notifySettingsFailure(ctx: ExtensionCommandContext, settingsPath: strin
720
571
  );
721
572
  }
722
573
 
723
- function goalSettingsListComponent(
724
- settingsList: SettingsList,
725
- isLimitChoiceOpen: () => boolean,
726
- ): Component {
727
- return {
728
- render(width: number) {
729
- // Reclaim one of SettingsList's two trailing cells so a safe 16-digit cap stays exact at 40 columns.
730
- const renderWidth = isLimitChoiceOpen() ? width : width + 1;
731
- return settingsList.render(renderWidth).map((line) => truncateToWidth(line, width, ""));
732
- },
733
- invalidate: () => settingsList.invalidate(),
734
- };
735
- }
736
-
737
- function dynamicText(
738
- content: string | (() => string),
739
- style: (text: string) => string = (text) => text,
740
- ): Component {
741
- return {
742
- render(width: number) {
743
- const value = typeof content === "function" ? content() : content;
744
- return new Text(style(value), 1, 0).render(width);
745
- },
746
- invalidate() {},
747
- };
748
- }
749
-
750
574
  function safeTerminalText(value: string) {
751
575
  return [...value]
752
576
  .map((character) => {