@narumitw/pi-goal 0.54.4 → 0.54.5

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.
Files changed (39) hide show
  1. package/README.md +41 -166
  2. package/dist/chunks/{chunk-QWIUWKRW.js → chunk-VJ5LR26S.js} +57 -77
  3. package/dist/chunks/chunk-VJ5LR26S.js.map +7 -0
  4. package/dist/chunks/{chunk-UQRRW4CY.js → chunk-WQIA35U2.js} +6 -5
  5. package/dist/chunks/chunk-WQIA35U2.js.map +7 -0
  6. package/dist/chunks/{menu-WEFDREGC.js → menu-JMGWQZIT.js} +7 -22
  7. package/dist/chunks/menu-JMGWQZIT.js.map +7 -0
  8. package/dist/chunks/{settings-ui-MVYTTBHW.js → settings-ui-JG3PFRB5.js} +6 -18
  9. package/dist/chunks/settings-ui-JG3PFRB5.js.map +7 -0
  10. package/dist/index.ts +92 -126
  11. package/dist/index.ts.map +2 -2
  12. package/docs/managing-goals.md +47 -0
  13. package/docs/settings.md +91 -0
  14. package/package.json +55 -55
  15. package/src/accounting.ts +62 -66
  16. package/src/command-registration.ts +104 -102
  17. package/src/command.ts +101 -112
  18. package/src/commands.ts +465 -501
  19. package/src/errors.ts +127 -122
  20. package/src/goal-contract.ts +64 -64
  21. package/src/goal.ts +25 -25
  22. package/src/lifecycle.ts +615 -628
  23. package/src/markers.ts +6 -6
  24. package/src/menu.ts +565 -591
  25. package/src/persistence.ts +177 -192
  26. package/src/prompts.ts +53 -67
  27. package/src/run-protocol.ts +299 -325
  28. package/src/runtime.ts +1422 -1495
  29. package/src/safety.ts +51 -51
  30. package/src/settings-ui.ts +366 -393
  31. package/src/settings.ts +134 -147
  32. package/src/tool-policy.ts +6 -6
  33. package/src/tools.ts +360 -371
  34. package/src/wait.ts +47 -51
  35. package/src/workflow-mutex.ts +68 -68
  36. package/dist/chunks/chunk-QWIUWKRW.js.map +0 -7
  37. package/dist/chunks/chunk-UQRRW4CY.js.map +0 -7
  38. package/dist/chunks/menu-WEFDREGC.js.map +0 -7
  39. package/dist/chunks/settings-ui-MVYTTBHW.js.map +0 -7
@@ -2,463 +2,436 @@ import { join } from "node:path";
2
2
  import { type ExtensionCommandContext, getAgentDir } from "@earendil-works/pi-coding-agent";
3
3
  import { notifyTerminal, safeTerminalText } from "./errors.js";
4
4
  import type { GoalRuntime } from "./runtime.js";
5
- import {
6
- DEFAULT_GOAL_SETTINGS,
7
- GOAL_SETTINGS_FILE,
8
- type GoalSettings,
9
- saveGoalSettings,
10
- } from "./settings.js";
5
+ import { DEFAULT_GOAL_SETTINGS, GOAL_SETTINGS_FILE, type GoalSettings, saveGoalSettings } from "./settings.js";
11
6
 
12
7
  interface GoalSettingsUiOptions {
13
- settingsPath?: string;
14
- initialScreen?: "settings" | "automatic";
15
- save?: (settings: GoalSettings, settingsPath: string) => void;
8
+ settingsPath?: string;
9
+ initialScreen?: "settings" | "automatic";
10
+ save?: (settings: GoalSettings, settingsPath: string) => void;
16
11
  }
17
12
 
18
13
  interface GoalSettingsApplyOptions {
19
- save?: (settings: GoalSettings) => void;
14
+ save?: (settings: GoalSettings) => void;
20
15
  }
21
16
 
22
17
  type LimitField = "automaticTurns" | "noProgressTurns";
23
18
  type LimitSelection = "unlimited" | "default" | "custom" | "off";
24
19
  export async function showGoalSettings(
25
- runtime: GoalRuntime,
26
- ctx: ExtensionCommandContext,
27
- options: GoalSettingsUiOptions = {},
20
+ runtime: GoalRuntime,
21
+ ctx: ExtensionCommandContext,
22
+ options: GoalSettingsUiOptions = {},
28
23
  ) {
29
- const settingsPath = options.settingsPath ?? join(getAgentDir(), GOAL_SETTINGS_FILE);
30
- if (ctx.mode !== "tui") {
31
- notifyTerminal(
32
- ctx.ui,
33
- `Edit pi-goal settings manually: ${safeTerminalText(settingsPath)}`,
34
- "info",
35
- );
36
- return;
37
- }
38
- const generation = runtime.menuGeneration;
39
- const isMenuCurrent = () =>
40
- generation === runtime.menuGeneration && !runtime.menuController.signal.aborted;
41
- const { defineMenu, runMenu } = await import("@narumitw/pi-tui-kit");
42
- if (!isMenuCurrent()) return;
43
- const invalid = runtime.settingsLoadIssue?.kind === "invalid";
44
- const previewGoalIds = new Map<LimitField, string | null>();
45
- type Screen = "settings" | "automatic" | "no-progress" | "invalid";
46
- type Action =
47
- | "open-automatic"
48
- | "open-no-progress"
49
- | "choose-automatic"
50
- | "choose-no-progress"
51
- | "set-rpc";
52
- const menu = defineMenu<undefined, Screen, Action, ExtensionCommandContext>({
53
- start: invalid ? "invalid" : (options.initialScreen ?? "settings"),
54
- screens: {
55
- settings: () => ({
56
- kind: "settings",
57
- title: "Pi Goal Settings",
58
- lines: [`User settings · ${safeTerminalText(settingsPath)}`],
59
- items: [
60
- {
61
- id: "automaticTurns",
62
- label: "Automatic-work limit",
63
- description: "Pause automatic Goal work after a visible number of model responses.",
64
- currentValue: formatAutomaticSettingValue(
65
- runtime.settings.continuationLimits.automaticTurns,
66
- ),
67
- action: "open-automatic",
68
- },
69
- {
70
- id: "noProgressTurns",
71
- label: "No-progress guard",
72
- description: "Pause after repeated or empty tool-free automatic runs.",
73
- currentValue: formatNoProgressSettingValue(
74
- runtime.settings.continuationLimits.noProgressTurns,
75
- ),
76
- action: "open-no-progress",
77
- },
78
- {
79
- id: "rpcEnabled",
80
- label: "Managed run RPC",
81
- description:
82
- "Allow trusted installed extensions to start and cancel Goal runs; this is not an extension sandbox.",
83
- currentValue: runtime.settings.rpc.enabled ? "On" : "Off",
84
- values: ["Off", "On"],
85
- action: "set-rpc",
86
- },
87
- ],
88
- }),
89
- automatic: () => limitChoiceScreen(runtime, "automaticTurns", "choose-automatic"),
90
- "no-progress": () => limitChoiceScreen(runtime, "noProgressTurns", "choose-no-progress"),
91
- invalid: () => ({
92
- kind: "detail",
93
- title: "Pi Goal Settings · Read only",
94
- lines: [
95
- `Invalid settings file. Pi-goal is using built-in defaults. Fix ${safeTerminalText(settingsPath)} and run /reload. The file will not be overwritten.`,
96
- `Automatic-work limit: ${formatAutomaticWork(runtime.settings.continuationLimits.automaticTurns)}`,
97
- `No-progress guard: ${formatNoProgressProtection(runtime.settings.continuationLimits.noProgressTurns)}`,
98
- `Managed run RPC: ${runtime.settings.rpc.enabled ? "On" : "Off"}`,
99
- ],
100
- hint: "back",
101
- }),
102
- },
103
- actions: {
104
- "open-automatic": async () => {
105
- previewGoalIds.set("automaticTurns", runtime.activeGoal?.id ?? null);
106
- return { kind: "to", screen: "automatic" };
107
- },
108
- "open-no-progress": async () => {
109
- previewGoalIds.set("noProgressTurns", runtime.activeGoal?.id ?? null);
110
- return { kind: "to", screen: "no-progress" };
111
- },
112
- "choose-automatic": async ({ itemId }) =>
113
- applyLimitChoice(
114
- runtime,
115
- ctx,
116
- options,
117
- settingsPath,
118
- "automaticTurns",
119
- itemId,
120
- previewGoalIds.get("automaticTurns") ?? null,
121
- isMenuCurrent,
122
- ),
123
- "choose-no-progress": async ({ itemId }) =>
124
- applyLimitChoice(
125
- runtime,
126
- ctx,
127
- options,
128
- settingsPath,
129
- "noProgressTurns",
130
- itemId,
131
- previewGoalIds.get("noProgressTurns") ?? null,
132
- isMenuCurrent,
133
- ),
134
- "set-rpc": async ({ value }) => {
135
- const enabled = value === "On";
136
- if (enabled === runtime.settings.rpc.enabled) return { kind: "stay" };
137
- try {
138
- const next = {
139
- ...structuredClone(runtime.settings),
140
- rpc: { enabled },
141
- } satisfies GoalSettings;
142
- applyGoalSettings(runtime, next, ctx, {
143
- save: (settings) => (options.save ?? saveGoalSettings)(settings, settingsPath),
144
- });
145
- notifyTerminal(ctx.ui, `Managed run RPC: ${enabled ? "On" : "Off"}.`, "info");
146
- return { kind: "stay" };
147
- } catch (error) {
148
- notifySettingsFailure(ctx, settingsPath, error);
149
- return { kind: "rejected" };
150
- }
151
- },
152
- },
153
- });
154
- await runMenu(ctx, menu, {
155
- getState: () => undefined,
156
- signal: runtime.menuController.signal,
157
- isCurrent: isMenuCurrent,
158
- });
24
+ const settingsPath = options.settingsPath ?? join(getAgentDir(), GOAL_SETTINGS_FILE);
25
+ if (ctx.mode !== "tui") {
26
+ notifyTerminal(ctx.ui, `Edit pi-goal settings manually: ${safeTerminalText(settingsPath)}`, "info");
27
+ return;
28
+ }
29
+ const generation = runtime.menuGeneration;
30
+ const isMenuCurrent = () => generation === runtime.menuGeneration && !runtime.menuController.signal.aborted;
31
+ const { defineMenu, runMenu } = await import("@narumitw/pi-tui-kit");
32
+ if (!isMenuCurrent()) return;
33
+ const invalid = runtime.settingsLoadIssue?.kind === "invalid";
34
+ const previewGoalIds = new Map<LimitField, string | null>();
35
+ type Screen = "settings" | "automatic" | "no-progress" | "invalid";
36
+ type Action = "open-automatic" | "open-no-progress" | "choose-automatic" | "choose-no-progress" | "set-rpc";
37
+ const menu = defineMenu<undefined, Screen, Action, ExtensionCommandContext>({
38
+ start: invalid ? "invalid" : (options.initialScreen ?? "settings"),
39
+ screens: {
40
+ settings: () => ({
41
+ kind: "settings",
42
+ title: "Pi Goal Settings",
43
+ lines: [`User settings · ${safeTerminalText(settingsPath)}`],
44
+ items: [
45
+ {
46
+ id: "automaticTurns",
47
+ label: "Automatic-work limit",
48
+ description: "Pause automatic Goal work after a visible number of model responses.",
49
+ currentValue: formatAutomaticSettingValue(runtime.settings.continuationLimits.automaticTurns),
50
+ action: "open-automatic",
51
+ },
52
+ {
53
+ id: "noProgressTurns",
54
+ label: "No-progress guard",
55
+ description: "Pause after repeated or empty tool-free automatic runs.",
56
+ currentValue: formatNoProgressSettingValue(runtime.settings.continuationLimits.noProgressTurns),
57
+ action: "open-no-progress",
58
+ },
59
+ {
60
+ id: "rpcEnabled",
61
+ label: "Managed run RPC",
62
+ description:
63
+ "Allow trusted installed extensions to start and cancel Goal runs; this is not an extension sandbox.",
64
+ currentValue: runtime.settings.rpc.enabled ? "On" : "Off",
65
+ values: ["Off", "On"],
66
+ action: "set-rpc",
67
+ },
68
+ ],
69
+ }),
70
+ automatic: () => limitChoiceScreen(runtime, "automaticTurns", "choose-automatic"),
71
+ "no-progress": () => limitChoiceScreen(runtime, "noProgressTurns", "choose-no-progress"),
72
+ invalid: () => ({
73
+ kind: "detail",
74
+ title: "Pi Goal Settings · Read only",
75
+ lines: [
76
+ `Invalid settings file. Pi-goal is using built-in defaults. Fix ${safeTerminalText(settingsPath)} and run /reload. The file will not be overwritten.`,
77
+ `Automatic-work limit: ${formatAutomaticWork(runtime.settings.continuationLimits.automaticTurns)}`,
78
+ `No-progress guard: ${formatNoProgressProtection(runtime.settings.continuationLimits.noProgressTurns)}`,
79
+ `Managed run RPC: ${runtime.settings.rpc.enabled ? "On" : "Off"}`,
80
+ ],
81
+ hint: "back",
82
+ }),
83
+ },
84
+ actions: {
85
+ "open-automatic": async () => {
86
+ previewGoalIds.set("automaticTurns", runtime.activeGoal?.id ?? null);
87
+ return { kind: "to", screen: "automatic" };
88
+ },
89
+ "open-no-progress": async () => {
90
+ previewGoalIds.set("noProgressTurns", runtime.activeGoal?.id ?? null);
91
+ return { kind: "to", screen: "no-progress" };
92
+ },
93
+ "choose-automatic": async ({ itemId }) =>
94
+ applyLimitChoice(
95
+ runtime,
96
+ ctx,
97
+ options,
98
+ settingsPath,
99
+ "automaticTurns",
100
+ itemId,
101
+ previewGoalIds.get("automaticTurns") ?? null,
102
+ isMenuCurrent,
103
+ ),
104
+ "choose-no-progress": async ({ itemId }) =>
105
+ applyLimitChoice(
106
+ runtime,
107
+ ctx,
108
+ options,
109
+ settingsPath,
110
+ "noProgressTurns",
111
+ itemId,
112
+ previewGoalIds.get("noProgressTurns") ?? null,
113
+ isMenuCurrent,
114
+ ),
115
+ "set-rpc": async ({ value }) => {
116
+ const enabled = value === "On";
117
+ if (enabled === runtime.settings.rpc.enabled) return { kind: "stay" };
118
+ try {
119
+ const next = {
120
+ ...structuredClone(runtime.settings),
121
+ rpc: { enabled },
122
+ } satisfies GoalSettings;
123
+ applyGoalSettings(runtime, next, ctx, {
124
+ save: (settings) => (options.save ?? saveGoalSettings)(settings, settingsPath),
125
+ });
126
+ notifyTerminal(ctx.ui, `Managed run RPC: ${enabled ? "On" : "Off"}.`, "info");
127
+ return { kind: "stay" };
128
+ } catch (error) {
129
+ notifySettingsFailure(ctx, settingsPath, error);
130
+ return { kind: "rejected" };
131
+ }
132
+ },
133
+ },
134
+ });
135
+ await runMenu(ctx, menu, {
136
+ getState: () => undefined,
137
+ signal: runtime.menuController.signal,
138
+ isCurrent: isMenuCurrent,
139
+ });
159
140
  }
160
141
 
161
- function limitChoiceScreen(
162
- runtime: GoalRuntime,
163
- field: LimitField,
164
- action: "choose-automatic" | "choose-no-progress",
165
- ) {
166
- const value = runtime.settings.continuationLimits[field];
167
- const goal = runtime.activeGoal;
168
- return {
169
- kind: "actions" as const,
170
- title: field === "automaticTurns" ? "Automatic-work limit" : "No-progress guard",
171
- lines: [
172
- field === "automaticTurns"
173
- ? `Current: ${formatAutomaticWork(value)}`
174
- : `Current: ${formatNoProgressProtection(value)}`,
175
- ...(field === "automaticTurns"
176
- ? [
177
- `Set a whole-number response limit for each automatic-work epoch. Default: ${DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns}.`,
178
- ]
179
- : []),
180
- ...(goal
181
- ? [
182
- field === "automaticTurns"
183
- ? `Active goal: ${goal.automaticModelTurns} automatic responses used`
184
- : `Active goal: ${goal.toolFreeRepeatCount} repeated or empty runs detected`,
185
- ]
186
- : []),
187
- ],
188
- items: limitChoices(field, value, goal?.automaticModelTurns).map((item) => ({
189
- id: item.value,
190
- label: item.label,
191
- description: item.description,
192
- action,
193
- })),
194
- hint: "back" as const,
195
- };
142
+ function limitChoiceScreen(runtime: GoalRuntime, field: LimitField, action: "choose-automatic" | "choose-no-progress") {
143
+ const value = runtime.settings.continuationLimits[field];
144
+ const goal = runtime.activeGoal;
145
+ return {
146
+ kind: "actions" as const,
147
+ title: field === "automaticTurns" ? "Automatic-work limit" : "No-progress guard",
148
+ lines: [
149
+ field === "automaticTurns"
150
+ ? `Current: ${formatAutomaticWork(value)}`
151
+ : `Current: ${formatNoProgressProtection(value)}`,
152
+ ...(field === "automaticTurns"
153
+ ? [
154
+ `Set a whole-number response limit for each automatic-work epoch. Default: ${DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns}.`,
155
+ ]
156
+ : []),
157
+ ...(goal
158
+ ? [
159
+ field === "automaticTurns"
160
+ ? `Active goal: ${goal.automaticModelTurns} automatic responses used`
161
+ : `Active goal: ${goal.toolFreeRepeatCount} repeated or empty runs detected`,
162
+ ]
163
+ : []),
164
+ ],
165
+ items: limitChoices(field, value, goal?.automaticModelTurns).map((item) => ({
166
+ id: item.value,
167
+ label: item.label,
168
+ description: item.description,
169
+ action,
170
+ })),
171
+ hint: "back" as const,
172
+ };
196
173
  }
197
174
 
198
175
  function limitChoices(
199
- field: LimitField,
200
- value: number | null,
201
- automaticTurnsUsed: number | undefined,
176
+ field: LimitField,
177
+ value: number | null,
178
+ automaticTurnsUsed: number | undefined,
202
179
  ): Array<{ value: LimitSelection; label: string; description: string }> {
203
- if (field === "automaticTurns") {
204
- const unlimitedDescription =
205
- value === null
206
- ? "No response-count cap. Completion, manual pause, blockers, provider limits, and other configured guards still apply."
207
- : automaticTurnsUsed === undefined
208
- ? `Remove the current ${value}-response cap. Goal work will have no response-count cap; other configured stop conditions remain.`
209
- : `Remove the current ${value}-response cap. The active goal has used ${automaticTurnsUsed} responses; other configured stop conditions remain.`;
210
- return [
211
- {
212
- value: "custom",
213
- label: "Set response limit…",
214
- description: `Choose a whole-number response limit for each automatic-work epoch. Default: ${DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns}.`,
215
- },
216
- { value: "unlimited", label: "Unlimited…", description: unlimitedDescription },
217
- ];
218
- }
219
- const defaultLimit = DEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns;
220
- return [
221
- {
222
- value: "default",
223
- label: `After ${defaultLimit} repeated runs (default)`,
224
- description: "Pause after the default number of repeated or empty tool-free runs.",
225
- },
226
- {
227
- value: "custom",
228
- label: "Set threshold…",
229
- description: "Choose a whole number of repeated or empty runs before pausing.",
230
- },
231
- {
232
- value: "off",
233
- label: "Off",
234
- description: "Do not pause based on repeated or empty tool-free runs.",
235
- },
236
- ];
180
+ if (field === "automaticTurns") {
181
+ const unlimitedDescription =
182
+ value === null
183
+ ? "No response-count cap. Completion, manual pause, blockers, provider limits, and other configured guards still apply."
184
+ : automaticTurnsUsed === undefined
185
+ ? `Remove the current ${value}-response cap. Goal work will have no response-count cap; other configured stop conditions remain.`
186
+ : `Remove the current ${value}-response cap. The active goal has used ${automaticTurnsUsed} responses; other configured stop conditions remain.`;
187
+ return [
188
+ {
189
+ value: "custom",
190
+ label: "Set response limit…",
191
+ description: `Choose a whole-number response limit for each automatic-work epoch. Default: ${DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns}.`,
192
+ },
193
+ { value: "unlimited", label: "Unlimited…", description: unlimitedDescription },
194
+ ];
195
+ }
196
+ const defaultLimit = DEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns;
197
+ return [
198
+ {
199
+ value: "default",
200
+ label: `After ${defaultLimit} repeated runs (default)`,
201
+ description: "Pause after the default number of repeated or empty tool-free runs.",
202
+ },
203
+ {
204
+ value: "custom",
205
+ label: "Set threshold…",
206
+ description: "Choose a whole number of repeated or empty runs before pausing.",
207
+ },
208
+ {
209
+ value: "off",
210
+ label: "Off",
211
+ description: "Do not pause based on repeated or empty tool-free runs.",
212
+ },
213
+ ];
237
214
  }
238
215
 
239
216
  async function applyLimitChoice(
240
- runtime: GoalRuntime,
241
- ctx: ExtensionCommandContext,
242
- options: GoalSettingsUiOptions,
243
- settingsPath: string,
244
- field: LimitField,
245
- itemId: string,
246
- activeGoalId: string | null,
247
- isCurrent: () => boolean,
217
+ runtime: GoalRuntime,
218
+ ctx: ExtensionCommandContext,
219
+ options: GoalSettingsUiOptions,
220
+ settingsPath: string,
221
+ field: LimitField,
222
+ itemId: string,
223
+ activeGoalId: string | null,
224
+ isCurrent: () => boolean,
248
225
  ) {
249
- if (!isCurrent() || !isLimitSelection(itemId)) return { kind: "rejected" as const };
250
- if ((runtime.activeGoal?.id ?? null) !== activeGoalId) {
251
- notifyTerminal(
252
- ctx.ui,
253
- "The active goal changed while the safety setting was open. No settings were changed.",
254
- "warning",
255
- );
256
- return { kind: "rejected" as const };
257
- }
258
- const previous = runtime.settings.continuationLimits[field];
259
- const limit = await resolveLimitSelection(field, itemId, previous, ctx, isCurrent);
260
- if (!isCurrent()) return { kind: "rejected" as const };
261
- if (limit === undefined || limit === previous) return { kind: "back" as const };
262
- if ((runtime.activeGoal?.id ?? null) !== activeGoalId) {
263
- notifyTerminal(
264
- ctx.ui,
265
- "The active goal changed while editing the safety setting. No settings were changed.",
266
- "warning",
267
- );
268
- return { kind: "rejected" as const };
269
- }
270
- const confirmation = await confirmLowerActiveLimit(runtime, ctx, field, limit);
271
- if (!isCurrent() || !confirmation.apply) return { kind: "rejected" as const };
272
- if (confirmation.goalId !== undefined && runtime.activeGoal?.id !== confirmation.goalId) {
273
- notifyTerminal(
274
- ctx.ui,
275
- "The active goal changed while confirming the limit. No settings were changed.",
276
- "warning",
277
- );
278
- return { kind: "rejected" as const };
279
- }
280
- try {
281
- applyGoalSettings(runtime, withLimit(runtime.settings, field, limit), ctx, {
282
- save: (settings) => (options.save ?? saveGoalSettings)(settings, settingsPath),
283
- });
284
- notifyTerminal(ctx.ui, formatLimitSuccess(field, limit), "info");
285
- return { kind: "back" as const };
286
- } catch (error) {
287
- notifySettingsFailure(ctx, settingsPath, error);
288
- return { kind: "rejected" as const };
289
- }
226
+ if (!isCurrent() || !isLimitSelection(itemId)) return { kind: "rejected" as const };
227
+ if ((runtime.activeGoal?.id ?? null) !== activeGoalId) {
228
+ notifyTerminal(
229
+ ctx.ui,
230
+ "The active goal changed while the safety setting was open. No settings were changed.",
231
+ "warning",
232
+ );
233
+ return { kind: "rejected" as const };
234
+ }
235
+ const previous = runtime.settings.continuationLimits[field];
236
+ const limit = await resolveLimitSelection(field, itemId, previous, ctx, isCurrent);
237
+ if (!isCurrent()) return { kind: "rejected" as const };
238
+ if (limit === undefined || limit === previous) return { kind: "back" as const };
239
+ if ((runtime.activeGoal?.id ?? null) !== activeGoalId) {
240
+ notifyTerminal(
241
+ ctx.ui,
242
+ "The active goal changed while editing the safety setting. No settings were changed.",
243
+ "warning",
244
+ );
245
+ return { kind: "rejected" as const };
246
+ }
247
+ const confirmation = await confirmLowerActiveLimit(runtime, ctx, field, limit);
248
+ if (!isCurrent() || !confirmation.apply) return { kind: "rejected" as const };
249
+ if (confirmation.goalId !== undefined && runtime.activeGoal?.id !== confirmation.goalId) {
250
+ notifyTerminal(ctx.ui, "The active goal changed while confirming the limit. No settings were changed.", "warning");
251
+ return { kind: "rejected" as const };
252
+ }
253
+ try {
254
+ applyGoalSettings(runtime, withLimit(runtime.settings, field, limit), ctx, {
255
+ save: (settings) => (options.save ?? saveGoalSettings)(settings, settingsPath),
256
+ });
257
+ notifyTerminal(ctx.ui, formatLimitSuccess(field, limit), "info");
258
+ return { kind: "back" as const };
259
+ } catch (error) {
260
+ notifySettingsFailure(ctx, settingsPath, error);
261
+ return { kind: "rejected" as const };
262
+ }
290
263
  }
291
264
 
292
265
  export function applyGoalSettings(
293
- runtime: GoalRuntime,
294
- next: GoalSettings,
295
- ctx: ExtensionCommandContext,
296
- options: GoalSettingsApplyOptions = {},
266
+ runtime: GoalRuntime,
267
+ next: GoalSettings,
268
+ ctx: ExtensionCommandContext,
269
+ options: GoalSettingsApplyOptions = {},
297
270
  ) {
298
- const snapshot = runtime.snapshotSettingsApplicationState();
299
- let fileSaved = false;
300
- try {
301
- runtime.settings = structuredClone(next);
302
- options.save?.(next);
303
- fileSaved = options.save !== undefined;
304
- const activeGoalId = runtime.activeGoal?.id;
305
- const abortOwnedRun = activeGoalId !== undefined && runtime.agentRunGoalId === activeGoalId;
306
- const pausedByAutomaticLimit = runtime.enforceAutomaticTurnLimit(ctx, abortOwnedRun);
307
- if (!pausedByAutomaticLimit) runtime.enforceNoProgressLimit(ctx, abortOwnedRun);
308
- if (runtime.activeGoal) {
309
- runtime.updateStatus(ctx, runtime.activeGoal);
310
- }
311
- } catch (error) {
312
- const rollbackErrors: unknown[] = [];
313
- try {
314
- runtime.restoreSettingsApplicationState(snapshot);
315
- } catch (rollbackError) {
316
- rollbackErrors.push(rollbackError);
317
- }
318
- if (fileSaved) {
319
- try {
320
- options.save?.(snapshot.settings);
321
- } catch (rollbackError) {
322
- rollbackErrors.push(rollbackError);
323
- }
324
- try {
325
- restorePersistedRuntime(runtime, ctx);
326
- } catch (rollbackError) {
327
- rollbackErrors.push(rollbackError);
328
- }
329
- }
330
- if (rollbackErrors.length > 0) {
331
- throw new AggregateError(
332
- [error, ...rollbackErrors],
333
- `pi-goal settings application failed and rollback was incomplete: ${formatError(error)}`,
334
- );
335
- }
336
- throw error;
337
- }
271
+ const snapshot = runtime.snapshotSettingsApplicationState();
272
+ let fileSaved = false;
273
+ try {
274
+ runtime.settings = structuredClone(next);
275
+ options.save?.(next);
276
+ fileSaved = options.save !== undefined;
277
+ const activeGoalId = runtime.activeGoal?.id;
278
+ const abortOwnedRun = activeGoalId !== undefined && runtime.agentRunGoalId === activeGoalId;
279
+ const pausedByAutomaticLimit = runtime.enforceAutomaticTurnLimit(ctx, abortOwnedRun);
280
+ if (!pausedByAutomaticLimit) runtime.enforceNoProgressLimit(ctx, abortOwnedRun);
281
+ if (runtime.activeGoal) {
282
+ runtime.updateStatus(ctx, runtime.activeGoal);
283
+ }
284
+ } catch (error) {
285
+ const rollbackErrors: unknown[] = [];
286
+ try {
287
+ runtime.restoreSettingsApplicationState(snapshot);
288
+ } catch (rollbackError) {
289
+ rollbackErrors.push(rollbackError);
290
+ }
291
+ if (fileSaved) {
292
+ try {
293
+ options.save?.(snapshot.settings);
294
+ } catch (rollbackError) {
295
+ rollbackErrors.push(rollbackError);
296
+ }
297
+ try {
298
+ restorePersistedRuntime(runtime, ctx);
299
+ } catch (rollbackError) {
300
+ rollbackErrors.push(rollbackError);
301
+ }
302
+ }
303
+ if (rollbackErrors.length > 0) {
304
+ throw new AggregateError(
305
+ [error, ...rollbackErrors],
306
+ `pi-goal settings application failed and rollback was incomplete: ${formatError(error)}`,
307
+ );
308
+ }
309
+ throw error;
310
+ }
338
311
  }
339
312
 
340
313
  export function parseGoalLimit(value: string): number | undefined {
341
- const normalized = value.trim();
342
- if (!/^\d+$/u.test(normalized)) return undefined;
343
- const parsed = Number(normalized);
344
- return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
314
+ const normalized = value.trim();
315
+ if (!/^\d+$/u.test(normalized)) return undefined;
316
+ const parsed = Number(normalized);
317
+ return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
345
318
  }
346
319
 
347
320
  async function resolveLimitSelection(
348
- field: LimitField,
349
- selection: LimitSelection,
350
- previous: number | null,
351
- ctx: ExtensionCommandContext,
352
- isCurrent: () => boolean,
321
+ field: LimitField,
322
+ selection: LimitSelection,
323
+ previous: number | null,
324
+ ctx: ExtensionCommandContext,
325
+ isCurrent: () => boolean,
353
326
  ): Promise<number | null | undefined> {
354
- if (selection === "off") return null;
355
- if (selection === "unlimited") {
356
- if (previous === null) return null;
357
- const confirmed = await ctx.ui.confirm(
358
- "Allow Unlimited automatic work?",
359
- "Tool loops can continue without a response-count limit and may consume substantial tokens and provider cost. Completion, manual pause, blockers, provider limits, and the no-progress guard still apply.",
360
- );
361
- return isCurrent() && confirmed ? null : undefined;
362
- }
363
- if (selection === "default") {
364
- return DEFAULT_GOAL_SETTINGS.continuationLimits[field];
365
- }
366
- while (true) {
367
- const raw =
368
- field === "automaticTurns"
369
- ? await ctx.ui.editor(
370
- `Automatic-work response limit (whole number greater than 0) · Default: ${DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns}`,
371
- String(previous ?? DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns),
372
- )
373
- : await ctx.ui.input(
374
- "Repeated-run threshold (whole number greater than 0)",
375
- previous === null ? "Positive whole number" : String(previous),
376
- );
377
- if (!isCurrent() || raw === undefined) return undefined;
378
- const parsed = parseGoalLimit(raw);
379
- if (parsed !== undefined) return parsed;
380
- notifyTerminal(
381
- ctx.ui,
382
- `Enter a whole number greater than 0. Choose ${field === "automaticTurns" ? "Unlimited" : "Off"} from the previous screen if you do not want a limit.`,
383
- "warning",
384
- );
385
- }
327
+ if (selection === "off") return null;
328
+ if (selection === "unlimited") {
329
+ if (previous === null) return null;
330
+ const confirmed = await ctx.ui.confirm(
331
+ "Allow Unlimited automatic work?",
332
+ "Tool loops can continue without a response-count limit and may consume substantial tokens and provider cost. Completion, manual pause, blockers, provider limits, and the no-progress guard still apply.",
333
+ );
334
+ return isCurrent() && confirmed ? null : undefined;
335
+ }
336
+ if (selection === "default") {
337
+ return DEFAULT_GOAL_SETTINGS.continuationLimits[field];
338
+ }
339
+ while (true) {
340
+ const raw =
341
+ field === "automaticTurns"
342
+ ? await ctx.ui.editor(
343
+ `Automatic-work response limit (whole number greater than 0) · Default: ${DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns}`,
344
+ String(previous ?? DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns),
345
+ )
346
+ : await ctx.ui.input(
347
+ "Repeated-run threshold (whole number greater than 0)",
348
+ previous === null ? "Positive whole number" : String(previous),
349
+ );
350
+ if (!isCurrent() || raw === undefined) return undefined;
351
+ const parsed = parseGoalLimit(raw);
352
+ if (parsed !== undefined) return parsed;
353
+ notifyTerminal(
354
+ ctx.ui,
355
+ `Enter a whole number greater than 0. Choose ${field === "automaticTurns" ? "Unlimited" : "Off"} from the previous screen if you do not want a limit.`,
356
+ "warning",
357
+ );
358
+ }
386
359
  }
387
360
 
388
361
  function restorePersistedRuntime(runtime: GoalRuntime, ctx: ExtensionCommandContext) {
389
- if (runtime.activeGoal) {
390
- runtime.persistGoal(runtime.activeGoal);
391
- runtime.updateStatus(ctx, runtime.activeGoal);
392
- runtime.restoreGoalWaitTimer(ctx);
393
- }
362
+ if (runtime.activeGoal) {
363
+ runtime.persistGoal(runtime.activeGoal);
364
+ runtime.updateStatus(ctx, runtime.activeGoal);
365
+ runtime.restoreGoalWaitTimer(ctx);
366
+ }
394
367
  }
395
368
 
396
369
  async function confirmLowerActiveLimit(
397
- runtime: GoalRuntime,
398
- ctx: ExtensionCommandContext,
399
- field: LimitField,
400
- limit: number | null,
370
+ runtime: GoalRuntime,
371
+ ctx: ExtensionCommandContext,
372
+ field: LimitField,
373
+ limit: number | null,
401
374
  ) {
402
- const goal = runtime.activeGoal;
403
- if (goal?.status !== "active" || limit === null) return { apply: true };
404
- const used = field === "automaticTurns" ? goal.automaticModelTurns : goal.toolFreeRepeatCount;
405
- if (used < limit) return { apply: true };
406
- return {
407
- apply: await ctx.ui.confirm(
408
- "Apply limit and pause now?",
409
- `The active goal has already used ${used}. Setting this limit to ${limit} will pause it immediately without deleting progress.`,
410
- ),
411
- goalId: goal.id,
412
- };
375
+ const goal = runtime.activeGoal;
376
+ if (goal?.status !== "active" || limit === null) return { apply: true };
377
+ const used = field === "automaticTurns" ? goal.automaticModelTurns : goal.toolFreeRepeatCount;
378
+ if (used < limit) return { apply: true };
379
+ return {
380
+ apply: await ctx.ui.confirm(
381
+ "Apply limit and pause now?",
382
+ `The active goal has already used ${used}. Setting this limit to ${limit} will pause it immediately without deleting progress.`,
383
+ ),
384
+ goalId: goal.id,
385
+ };
413
386
  }
414
387
 
415
388
  function withLimit(settings: GoalSettings, field: LimitField, value: number | null): GoalSettings {
416
- return {
417
- ...structuredClone(settings),
418
- continuationLimits: { ...settings.continuationLimits, [field]: value },
419
- };
389
+ return {
390
+ ...structuredClone(settings),
391
+ continuationLimits: { ...settings.continuationLimits, [field]: value },
392
+ };
420
393
  }
421
394
 
422
395
  function formatAutomaticSettingValue(value: number | null) {
423
- return value === null ? "Unlimited" : `${value} responses`;
396
+ return value === null ? "Unlimited" : `${value} responses`;
424
397
  }
425
398
 
426
399
  function formatNoProgressSettingValue(value: number | null) {
427
- if (value === null) return "Off";
428
- return `${value} ${value === 1 ? "run" : "runs"}`;
400
+ if (value === null) return "Off";
401
+ return `${value} ${value === 1 ? "run" : "runs"}`;
429
402
  }
430
403
 
431
404
  function formatAutomaticWork(value: number | null) {
432
- return value === null ? "Unlimited" : `Up to ${value} responses`;
405
+ return value === null ? "Unlimited" : `Up to ${value} responses`;
433
406
  }
434
407
 
435
408
  function formatNoProgressProtection(value: number | null) {
436
- if (value === null) return "Off";
437
- return `After ${value} repeated ${value === 1 ? "run" : "runs"}`;
409
+ if (value === null) return "Off";
410
+ return `After ${value} repeated ${value === 1 ? "run" : "runs"}`;
438
411
  }
439
412
 
440
413
  function formatLimitSuccess(field: LimitField, value: number | null) {
441
- return field === "automaticTurns"
442
- ? `Automatic-work limit: ${formatAutomaticWork(value)}.`
443
- : `No-progress guard: ${formatNoProgressProtection(value)}.`;
414
+ return field === "automaticTurns"
415
+ ? `Automatic-work limit: ${formatAutomaticWork(value)}.`
416
+ : `No-progress guard: ${formatNoProgressProtection(value)}.`;
444
417
  }
445
418
 
446
419
  function isLimitSelection(value: string): value is LimitSelection {
447
- return value === "unlimited" || value === "default" || value === "custom" || value === "off";
420
+ return value === "unlimited" || value === "default" || value === "custom" || value === "off";
448
421
  }
449
422
 
450
423
  function notifySettingsFailure(ctx: ExtensionCommandContext, settingsPath: string, error: unknown) {
451
- const path = safeTerminalText(settingsPath);
452
- const detail = safeTerminalText(formatError(error));
453
- notifyTerminal(
454
- ctx.ui,
455
- error instanceof AggregateError
456
- ? `Could not apply Goal settings, and rollback was incomplete. Check ${path}, run /reload, and verify the effective settings before retrying: ${detail}`
457
- : `Could not save Goal settings; the previous value remains. Check ${path} and retry: ${detail}`,
458
- "error",
459
- );
424
+ const path = safeTerminalText(settingsPath);
425
+ const detail = safeTerminalText(formatError(error));
426
+ notifyTerminal(
427
+ ctx.ui,
428
+ error instanceof AggregateError
429
+ ? `Could not apply Goal settings, and rollback was incomplete. Check ${path}, run /reload, and verify the effective settings before retrying: ${detail}`
430
+ : `Could not save Goal settings; the previous value remains. Check ${path} and retry: ${detail}`,
431
+ "error",
432
+ );
460
433
  }
461
434
 
462
435
  function formatError(error: unknown) {
463
- return error instanceof Error ? error.message : String(error);
436
+ return error instanceof Error ? error.message : String(error);
464
437
  }