@narumitw/pi-goal 0.31.0 → 0.34.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -13,7 +13,7 @@ Goal mode uses Codex-like persistence instructions and sends guarded continuatio
13
13
  - Keeps direct goal management available through `/goal` subcommands: `status`, `pause`, `resume`, `clear`, and `edit`.
14
14
  - Exposes only one top-level command: `/goal`, including when ordered goals are enabled.
15
15
  - 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.
16
+ - Leaves automatic response count unlimited by default; set `continuationLimits.automaticTurns` to a positive whole number when an authoritative response cap is wanted.
17
17
  - Pauses after three consecutive empty or normalized-identical tool-free automatic runs, while distinct short output and tool activity reset the repeat detector.
18
18
  - Supports optional token budgets such as `/goal --tokens 100k <goal>`, using provider-reported total-token accounting with a cache-inclusive compatibility fallback.
19
19
  - Tracks distinct `active`, `paused`, `blocked`, `usage_limited`, `budget_limited`, and `complete` states.
@@ -54,8 +54,8 @@ pi -e ./extensions/pi-goal
54
54
 
55
55
  ## ⚙️ Configuration
56
56
 
57
- On the first session start, pi-goal automatically creates `~/.pi/agent/pi-goal.json`
58
- with the complete current defaults:
57
+ Settings are optional. When `~/.pi/agent/pi-goal.json` is absent, pi-goal uses these
58
+ built-in defaults without creating the file:
59
59
 
60
60
  ```json
61
61
  {
@@ -64,13 +64,20 @@ with the complete current defaults:
64
64
  "goals": false
65
65
  },
66
66
  "continuationLimits": {
67
- "automaticTurns": 25,
67
+ "automaticTurns": null,
68
68
  "noProgressTurns": 3
69
69
  }
70
70
  }
71
71
  ```
72
72
 
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.
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:
74
+
75
+ - **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
+ - **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.
77
+ - **Goal tools** controls whether terminal Goal tools are always visible or appear after the first goal.
78
+ - **Ordered goal queue** controls the experimental ordered-goal workflows.
79
+
80
+ 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
81
 
75
82
  `toolVisibility` accepts:
76
83
 
@@ -79,18 +86,14 @@ Use `/goal` → **Settings…** in the TUI to edit these values interactively, o
79
86
 
80
87
  `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
88
 
82
- `continuationLimits` controls the default-on runaway guards:
89
+ `continuationLimits` controls the runaway guards:
83
90
 
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.
91
+ - `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
92
  - `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
93
 
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.
94
+ 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
95
 
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"`
96
+ 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
97
  restores only the exact tools that pi-goal previously hid, while switching to
95
98
  `"after-first-goal"` locks a runtime that has no unfinished goal.
96
99
 
@@ -115,7 +118,7 @@ Tool visibility is a baseline, not ownership of Pi's global active-tool list. Pl
115
118
  /goal skip
116
119
  ```
117
120
 
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.
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.
119
122
  - 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
123
  - 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
124
  - `/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 +170,7 @@ For each persisted assistant message, `pi-goal` uses finite, non-negative `usage
167
170
 
168
171
  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
172
 
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`.
173
+ 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
174
 
172
175
  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
176
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-goal",
3
- "version": "0.31.0",
3
+ "version": "0.34.1",
4
4
  "description": "Pi extension for autonomous /goal completion with opt-in experimental ordered queues.",
5
5
  "type": "module",
6
6
  "license": "MIT",
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 =
@@ -487,22 +486,15 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
487
486
  runtime.clearTerminalDetails();
488
487
  rpc.bindSession(ctx);
489
488
  const previousToolVisibility = runtime.settings.toolVisibility;
490
- const settingsResult = loadOrCreateGoalSettings(
491
- options.settingsPath,
492
- options.settingsFileSystem,
493
- );
489
+ const settingsResult = readGoalSettings(options.settingsPath);
494
490
  runtime.settings =
495
491
  settingsResult.kind === "loaded" ? settingsResult.settings : DEFAULT_GOAL_SETTINGS;
492
+ runtime.settingsLoadIssue = settingsResult.kind === "invalid" ? settingsResult : undefined;
496
493
  if (settingsResult.kind === "invalid") {
497
494
  ctx.ui.notify(
498
495
  `pi-goal settings ignored: ${settingsResult.reason}. Using default settings.`,
499
496
  "warning",
500
497
  );
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
498
  }
507
499
  if (runtime.settings.experimental.goals) {
508
500
  ctx.ui.notify(EXPERIMENTAL_GOALS_WARNING, "warning");
package/src/menu.ts CHANGED
@@ -56,12 +56,17 @@ export function buildGoalMenuState(runtime: GoalMenuRuntimeView): GoalMenuState
56
56
  : runtime.pendingQueueAction
57
57
  ? "Waiting for Pi to settle"
58
58
  : displayStatus(goal?.status);
59
+ const automaticTurnLimit = runtime.settings.continuationLimits.automaticTurns;
60
+ const automaticResponses =
61
+ automaticTurnLimit === null
62
+ ? `${goal?.automaticModelTurns ?? 0} automatic responses · Unlimited`
63
+ : `${goal?.automaticModelTurns ?? 0}/${automaticTurnLimit} automatic responses`;
59
64
  const details = goal
60
65
  ? [
61
66
  goal.tokenBudget === undefined
62
67
  ? formatDuration(goal.timeUsedSeconds)
63
68
  : `${formatTokenCount(goal.tokensUsed)}/${formatTokenCount(goal.tokenBudget)}`,
64
- `${goal.automaticModelTurns} automatic responses`,
69
+ automaticResponses,
65
70
  ...(queueCount > 0 ? [`${queueCount} queued`] : []),
66
71
  ].join(" · ")
67
72
  : "No goal is currently set";
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;
@@ -167,6 +171,7 @@ const CONTRADICTORY_COMPLETION_PATTERNS = [
167
171
  // budget, safety, and tool-policy transitions share ordering-sensitive invariants.
168
172
  export class GoalRuntime {
169
173
  settings: GoalSettings = DEFAULT_GOAL_SETTINGS;
174
+ settingsLoadIssue?: GoalSettingsLoadIssue;
170
175
  activeGoal?: ActiveGoal;
171
176
  /** Terminal details captured for the matching cross-extension state event. */
172
177
  private terminalDetails?: GoalTerminalDetails;
@@ -2,12 +2,28 @@ import { join } from "node:path";
2
2
  import {
3
3
  type ExtensionCommandContext,
4
4
  getAgentDir,
5
+ getSelectListTheme,
5
6
  getSettingsListTheme,
6
7
  } from "@earendil-works/pi-coding-agent";
7
- import { Container, type SettingItem, SettingsList, Text } from "@earendil-works/pi-tui";
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";
8
19
  import { checkpointGoalActiveTime } from "./accounting.js";
9
20
  import { abortCurrentTurn, type GoalRuntime, STATUS_KEY } from "./runtime.js";
10
- import { GOAL_SETTINGS_FILE, type GoalSettings, saveGoalSettings } from "./settings.js";
21
+ import {
22
+ DEFAULT_GOAL_SETTINGS,
23
+ GOAL_SETTINGS_FILE,
24
+ type GoalSettings,
25
+ saveGoalSettings,
26
+ } from "./settings.js";
11
27
 
12
28
  interface GoalSettingsUiOptions {
13
29
  settingsPath?: string;
@@ -20,11 +36,24 @@ interface GoalSettingsApplyOptions {
20
36
  }
21
37
 
22
38
  type LimitField = "automaticTurns" | "noProgressTurns";
39
+ type LimitSelection = "unlimited" | "default" | "custom" | "off";
23
40
  type SettingsScreenResult =
24
- | { kind: "limit"; field: LimitField }
41
+ | {
42
+ kind: "limit";
43
+ field: LimitField;
44
+ selection: LimitSelection;
45
+ activeGoalId: string | null;
46
+ }
25
47
  | { kind: "queue"; enabled: boolean }
26
48
  | undefined;
27
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
+
28
57
  export async function showGoalSettings(
29
58
  runtime: GoalRuntime,
30
59
  ctx: ExtensionCommandContext,
@@ -41,7 +70,7 @@ export async function showGoalSettings(
41
70
  if (!result) return;
42
71
  if (result.kind === "queue") {
43
72
  const next = await nextQueueSettings(runtime, ctx, result.enabled);
44
- if (!next) return;
73
+ if (!next) continue;
45
74
  const wasFrozen = runtime.queueFrozen;
46
75
  try {
47
76
  applyGoalSettings(runtime, next, ctx, {
@@ -52,27 +81,33 @@ export async function showGoalSettings(
52
81
  await options.onQueueUnfrozen?.(ctx);
53
82
  } catch (error) {
54
83
  ctx.ui.notify(
55
- `Goal queue enabled, but automatic resume failed: ${formatError(error)}. Reopen /goal to retry.`,
84
+ `Goal queue enabled, but automatic resume failed: ${safeTerminalText(formatError(error))}. Reopen /goal to retry.`,
56
85
  "warning",
57
86
  );
58
87
  }
59
88
  }
60
89
  ctx.ui.notify(`Ordered goal queue: ${result.enabled ? "Experimental" : "Off"}.`, "info");
61
90
  } catch (error) {
62
- ctx.ui.notify(`pi-goal settings save failed: ${formatError(error)}`, "error");
91
+ notifySettingsFailure(ctx, settingsPath, error);
63
92
  }
64
93
  return;
65
94
  }
66
95
 
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
+ }
67
103
  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),
71
- );
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");
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
+ );
76
111
  continue;
77
112
  }
78
113
  const confirmation = await confirmLowerActiveLimit(runtime, ctx, result.field, limit);
@@ -89,12 +124,9 @@ export async function showGoalSettings(
89
124
  applyGoalSettings(runtime, next, ctx, {
90
125
  save: (settings) => (options.save ?? saveGoalSettings)(settings, settingsPath),
91
126
  });
92
- ctx.ui.notify(
93
- `${result.field === "automaticTurns" ? "Automatic response" : "No-progress"} limit: ${formatGoalLimit(limit)}.`,
94
- "info",
95
- );
127
+ ctx.ui.notify(formatLimitSuccess(result.field, limit), "info");
96
128
  } catch (error) {
97
- ctx.ui.notify(`pi-goal settings save failed: ${formatError(error)}`, "error");
129
+ notifySettingsFailure(ctx, settingsPath, error);
98
130
  }
99
131
  }
100
132
  }
@@ -146,9 +178,8 @@ export function applyGoalSettings(
146
178
  }
147
179
  }
148
180
 
149
- export function parseGoalLimit(value: string): number | null | undefined {
150
- const normalized = value.trim().toLowerCase();
151
- if (normalized === "unlimited" || normalized === "off") return null;
181
+ export function parseGoalLimit(value: string): number | undefined {
182
+ const normalized = value.trim();
152
183
  if (!/^\d+$/u.test(normalized)) return undefined;
153
184
  const parsed = Number(normalized);
154
185
  return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
@@ -164,58 +195,99 @@ async function showSettingsScreen(
164
195
  settingsPath: string,
165
196
  options: GoalSettingsUiOptions,
166
197
  ): Promise<SettingsScreenResult> {
198
+ if (runtime.settingsLoadIssue?.kind === "invalid") {
199
+ return showReadOnlySettingsScreen(runtime, ctx, settingsPath);
200
+ }
201
+
167
202
  let saveQueue = Promise.resolve();
168
- const latestRequested = new Map<string, string>();
203
+ const enqueueSettingsChange: EnqueueSettingsChange = (operation) => {
204
+ const queued = saveQueue.then(operation);
205
+ saveQueue = queued.catch(() => undefined);
206
+ return queued;
207
+ };
169
208
  return ctx.ui.custom<SettingsScreenResult>((tui, theme, _keybindings, done) => {
170
- const settings = runtime.settings;
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;
171
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
+ ),
172
260
  {
173
261
  id: "toolVisibility",
174
262
  label: "Goal tools",
175
263
  description: "Keep terminal Goal tools visible, or reveal them after the first goal.",
176
- currentValue: visibilityLabel(settings.toolVisibility),
264
+ currentValue: visibilityLabel(runtime.settings.toolVisibility),
177
265
  values: ["Always", "After first goal"],
178
266
  },
179
267
  {
180
268
  id: "experimentalGoals",
181
269
  label: "Ordered goal queue",
182
270
  description: "Enable experimental add, prioritize, skip, and drop-last workflows.",
183
- currentValue: settings.experimental.goals ? "Experimental" : "Off",
271
+ currentValue: runtime.settings.experimental.goals ? "Experimental" : "Off",
184
272
  values: ["Off", "Experimental"],
185
273
  },
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
274
  ];
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
- );
275
+ const latestRequested = new Map<string, string>();
204
276
  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
277
  settingsList = new SettingsList(
212
278
  items,
213
279
  Math.min(items.length + 2, 15),
214
- getSettingsListTheme(),
280
+ goalSettingsListTheme("Goal menu"),
215
281
  (id, newValue) => {
216
282
  if (closing) return;
217
- if ((id === "automaticTurns" || id === "noProgressTurns") && newValue === "Edit…") {
218
- closeAfterSaves({ kind: "limit", field: id });
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
+ });
219
291
  return;
220
292
  }
221
293
  if (id === "experimentalGoals") {
@@ -224,7 +296,7 @@ async function showSettingsScreen(
224
296
  }
225
297
  if (id !== "toolVisibility") return;
226
298
  latestRequested.set(id, newValue);
227
- const operation = saveQueue.then(async () => {
299
+ void enqueueSettingsChange(async () => {
228
300
  const previousValue = visibilityLabel(runtime.settings.toolVisibility);
229
301
  try {
230
302
  const next = {
@@ -234,24 +306,20 @@ async function showSettingsScreen(
234
306
  applyGoalSettings(runtime, next, ctx, {
235
307
  save: (value) => (options.save ?? saveGoalSettings)(value, settingsPath),
236
308
  });
309
+ requestRender();
237
310
  ctx.ui.notify(`Goal tools: ${newValue}.`, "info");
238
311
  } catch (error) {
239
312
  if (latestRequested.get(id) === newValue) {
240
313
  settingsList.updateValue(id, previousValue);
241
314
  }
242
- ctx.ui.notify(`pi-goal settings save failed: ${formatError(error)}`, "error");
243
- tui.requestRender();
315
+ notifySettingsFailure(ctx, settingsPath, error);
244
316
  }
245
317
  });
246
- saveQueue = operation.catch(() => undefined);
247
318
  },
248
319
  () => closeAfterSaves(undefined),
249
320
  { enableSearch: false },
250
321
  );
251
- container.addChild(settingsList);
252
- container.addChild(
253
- new Text(theme.fg("dim", "↑↓ navigate · enter/space change · esc close"), 1, 0),
254
- );
322
+ container.addChild(goalSettingsListComponent(settingsList, () => limitChoiceOpen));
255
323
  return {
256
324
  render: (width: number) => container.render(width),
257
325
  invalidate: () => container.invalidate(),
@@ -264,6 +332,184 @@ async function showSettingsScreen(
264
332
  });
265
333
  }
266
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
+ async function resolveLimitSelection(
488
+ result: Extract<SettingsScreenResult, { kind: "limit" }>,
489
+ previous: number | null,
490
+ ctx: ExtensionCommandContext,
491
+ ): Promise<number | null | undefined> {
492
+ if (result.selection === "unlimited" || result.selection === "off") return null;
493
+ if (result.selection === "default") {
494
+ return DEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns;
495
+ }
496
+ while (true) {
497
+ const raw = await ctx.ui.input(
498
+ result.field === "automaticTurns"
499
+ ? "Maximum automatic responses (whole number greater than 0)"
500
+ : "Repeated-run threshold (whole number greater than 0)",
501
+ previous === null ? "Positive whole number" : String(previous),
502
+ );
503
+ if (raw === undefined) return undefined;
504
+ const parsed = parseGoalLimit(raw);
505
+ if (parsed !== undefined) return parsed;
506
+ 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.`,
508
+ "warning",
509
+ );
510
+ }
511
+ }
512
+
267
513
  async function nextQueueSettings(
268
514
  runtime: GoalRuntime,
269
515
  ctx: ExtensionCommandContext,
@@ -378,7 +624,7 @@ async function confirmLowerActiveLimit(
378
624
  if (used < limit) return { apply: true };
379
625
  return {
380
626
  apply: await ctx.ui.confirm(
381
- "Apply reached safety limit?",
627
+ "Apply limit and pause now?",
382
628
  `The active goal has already used ${used}. Setting this limit to ${limit} will pause it immediately without deleting progress.`,
383
629
  ),
384
630
  goalId: goal.id,
@@ -392,15 +638,63 @@ function withLimit(settings: GoalSettings, field: LimitField, value: number | nu
392
638
  };
393
639
  }
394
640
 
395
- function limitItem(id: LimitField, label: string, description: string, value: number | null) {
396
- const currentValue = formatGoalLimit(value);
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 {
397
648
  return {
398
649
  id,
399
650
  label,
400
651
  description,
401
- currentValue,
402
- values: [currentValue, "Edit…"],
403
- } satisfies SettingItem;
652
+ currentValue:
653
+ id === "automaticTurns"
654
+ ? formatAutomaticSettingValue(value)
655
+ : formatNoProgressSettingValue(value),
656
+ submenu: (_currentValue, done) => submenu(done),
657
+ };
658
+ }
659
+
660
+ function formatAutomaticSettingValue(value: number | null) {
661
+ return value === null ? "Unlimited" : `≤${value}`;
662
+ }
663
+
664
+ function formatNoProgressSettingValue(value: number | null) {
665
+ if (value === null) return "Off";
666
+ return `${value} ${value === 1 ? "run" : "runs"}`;
667
+ }
668
+
669
+ function formatAutomaticWork(value: number | null) {
670
+ return value === null ? "Unlimited" : `Up to ${value} responses`;
671
+ }
672
+
673
+ function formatNoProgressProtection(value: number | null) {
674
+ if (value === null) return "Off";
675
+ return `After ${value} repeated ${value === 1 ? "run" : "runs"}`;
676
+ }
677
+
678
+ function formatLimitSuccess(field: LimitField, value: number | null) {
679
+ return field === "automaticTurns"
680
+ ? `Automatic work: ${formatAutomaticWork(value)}.`
681
+ : `No-progress guard: ${formatNoProgressProtection(value)}.`;
682
+ }
683
+
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
+ function isLimitSelection(value: string): value is LimitSelection {
697
+ return value === "unlimited" || value === "default" || value === "custom" || value === "off";
404
698
  }
405
699
 
406
700
  function visibilityLabel(value: GoalSettings["toolVisibility"]) {
@@ -415,6 +709,44 @@ function retainedGoalCount(runtime: GoalRuntime) {
415
709
  );
416
710
  }
417
711
 
712
+ function notifySettingsFailure(ctx: ExtensionCommandContext, settingsPath: string, error: unknown) {
713
+ const path = safeTerminalText(settingsPath);
714
+ const detail = safeTerminalText(formatError(error));
715
+ ctx.ui.notify(
716
+ error instanceof AggregateError
717
+ ? `Could not apply Goal settings, and rollback was incomplete. Check ${path}, run /reload, and verify the effective settings before retrying: ${detail}`
718
+ : `Could not save Goal settings; the previous value remains. Check ${path} and retry: ${detail}`,
719
+ "error",
720
+ );
721
+ }
722
+
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
+
418
750
  function safeTerminalText(value: string) {
419
751
  return [...value]
420
752
  .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
  }