@narumitw/pi-goal 0.28.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 +24 -20
- package/package.json +10 -5
- package/src/accounting.ts +1 -3
- package/src/commands.ts +68 -5
- package/src/goal.ts +25 -14
- package/src/menu.ts +436 -0
- package/src/queue.ts +25 -1
- package/src/runtime.ts +87 -8
- package/src/settings-ui.ts +762 -0
- package/src/settings.ts +51 -42
|
@@ -0,0 +1,762 @@
|
|
|
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";
|
|
19
|
+
import { checkpointGoalActiveTime } from "./accounting.js";
|
|
20
|
+
import { abortCurrentTurn, type GoalRuntime, STATUS_KEY } from "./runtime.js";
|
|
21
|
+
import {
|
|
22
|
+
DEFAULT_GOAL_SETTINGS,
|
|
23
|
+
GOAL_SETTINGS_FILE,
|
|
24
|
+
type GoalSettings,
|
|
25
|
+
saveGoalSettings,
|
|
26
|
+
} from "./settings.js";
|
|
27
|
+
|
|
28
|
+
interface GoalSettingsUiOptions {
|
|
29
|
+
settingsPath?: string;
|
|
30
|
+
save?: (settings: GoalSettings, settingsPath: string) => void;
|
|
31
|
+
onQueueUnfrozen?: (ctx: ExtensionCommandContext) => Promise<void>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
interface GoalSettingsApplyOptions {
|
|
35
|
+
save?: (settings: GoalSettings) => void;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
type LimitField = "automaticTurns" | "noProgressTurns";
|
|
39
|
+
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
|
+
export async function showGoalSettings(
|
|
58
|
+
runtime: GoalRuntime,
|
|
59
|
+
ctx: ExtensionCommandContext,
|
|
60
|
+
options: GoalSettingsUiOptions = {},
|
|
61
|
+
) {
|
|
62
|
+
const settingsPath = options.settingsPath ?? join(getAgentDir(), GOAL_SETTINGS_FILE);
|
|
63
|
+
if (ctx.mode !== "tui") {
|
|
64
|
+
ctx.ui.notify(`Edit pi-goal settings manually: ${safeTerminalText(settingsPath)}`, "info");
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
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
|
+
);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
ctx.ui.notify(`Ordered goal queue: ${result.enabled ? "Experimental" : "Off"}.`, "info");
|
|
90
|
+
} catch (error) {
|
|
91
|
+
notifySettingsFailure(ctx, settingsPath, error);
|
|
92
|
+
}
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
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
|
+
}
|
|
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
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function applyGoalSettings(
|
|
135
|
+
runtime: GoalRuntime,
|
|
136
|
+
next: GoalSettings,
|
|
137
|
+
ctx: ExtensionCommandContext,
|
|
138
|
+
options: GoalSettingsApplyOptions = {},
|
|
139
|
+
) {
|
|
140
|
+
const snapshot = runtime.snapshotSettingsApplicationState();
|
|
141
|
+
let fileSaved = false;
|
|
142
|
+
try {
|
|
143
|
+
runtime.settings = structuredClone(next);
|
|
144
|
+
applyToolVisibility(runtime, snapshot.settings, next, ctx);
|
|
145
|
+
options.save?.(next);
|
|
146
|
+
fileSaved = options.save !== undefined;
|
|
147
|
+
applyQueueSetting(runtime, ctx);
|
|
148
|
+
const activeGoalId = runtime.activeGoal?.id;
|
|
149
|
+
const abortOwnedRun = activeGoalId !== undefined && runtime.agentRunGoalId === activeGoalId;
|
|
150
|
+
const pausedByAutomaticLimit = runtime.enforceAutomaticTurnLimit(ctx, abortOwnedRun);
|
|
151
|
+
if (!pausedByAutomaticLimit) runtime.enforceNoProgressLimit(ctx, abortOwnedRun);
|
|
152
|
+
} catch (error) {
|
|
153
|
+
const rollbackErrors: unknown[] = [];
|
|
154
|
+
try {
|
|
155
|
+
runtime.restoreSettingsApplicationState(snapshot);
|
|
156
|
+
} catch (rollbackError) {
|
|
157
|
+
rollbackErrors.push(rollbackError);
|
|
158
|
+
}
|
|
159
|
+
if (fileSaved) {
|
|
160
|
+
try {
|
|
161
|
+
options.save?.(snapshot.settings);
|
|
162
|
+
} catch (rollbackError) {
|
|
163
|
+
rollbackErrors.push(rollbackError);
|
|
164
|
+
}
|
|
165
|
+
try {
|
|
166
|
+
restorePersistedRuntime(runtime, ctx);
|
|
167
|
+
} catch (rollbackError) {
|
|
168
|
+
rollbackErrors.push(rollbackError);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
if (rollbackErrors.length > 0) {
|
|
172
|
+
throw new AggregateError(
|
|
173
|
+
[error, ...rollbackErrors],
|
|
174
|
+
`pi-goal settings application failed and rollback was incomplete: ${formatError(error)}`,
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
throw error;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export function parseGoalLimit(value: string): number | undefined {
|
|
182
|
+
const normalized = value.trim();
|
|
183
|
+
if (!/^\d+$/u.test(normalized)) return undefined;
|
|
184
|
+
const parsed = Number(normalized);
|
|
185
|
+
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export function formatGoalLimit(value: number | null) {
|
|
189
|
+
return value === null ? "Unlimited" : String(value);
|
|
190
|
+
}
|
|
191
|
+
|
|
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
|
+
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
|
+
|
|
513
|
+
async function nextQueueSettings(
|
|
514
|
+
runtime: GoalRuntime,
|
|
515
|
+
ctx: ExtensionCommandContext,
|
|
516
|
+
enabled: boolean,
|
|
517
|
+
) {
|
|
518
|
+
if (runtime.settings.experimental.goals === enabled) return undefined;
|
|
519
|
+
if (enabled && !runtime.settings.experimental.goals) {
|
|
520
|
+
const confirmed = await ctx.ui.confirm(
|
|
521
|
+
"Enable experimental goal queue?",
|
|
522
|
+
"Queue behavior and persisted state may change between releases. Existing single-goal behavior remains available.",
|
|
523
|
+
);
|
|
524
|
+
if (!confirmed) return undefined;
|
|
525
|
+
}
|
|
526
|
+
if (
|
|
527
|
+
!enabled &&
|
|
528
|
+
(runtime.queuedGoals.length > 0 || runtime.pendingQueueAction !== undefined) &&
|
|
529
|
+
!(await ctx.ui.confirm(
|
|
530
|
+
"Freeze ordered goal queue?",
|
|
531
|
+
`Disabling the experiment preserves ${retainedGoalCount(runtime)} goal(s) but freezes automatic work until the setting is re-enabled. No goal data will be deleted.`,
|
|
532
|
+
))
|
|
533
|
+
) {
|
|
534
|
+
return undefined;
|
|
535
|
+
}
|
|
536
|
+
return {
|
|
537
|
+
...structuredClone(runtime.settings),
|
|
538
|
+
experimental: { goals: enabled },
|
|
539
|
+
} satisfies GoalSettings;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
function applyToolVisibility(
|
|
543
|
+
runtime: GoalRuntime,
|
|
544
|
+
previous: GoalSettings,
|
|
545
|
+
next: GoalSettings,
|
|
546
|
+
ctx: ExtensionCommandContext,
|
|
547
|
+
) {
|
|
548
|
+
if (previous.toolVisibility === next.toolVisibility) return;
|
|
549
|
+
if (next.toolVisibility === "always") {
|
|
550
|
+
if (runtime.goalToolsHiddenByPolicy.size > 0 && ctx.isIdle() !== true) {
|
|
551
|
+
throw new Error("Wait for Pi to become idle before revealing Goal tools.");
|
|
552
|
+
}
|
|
553
|
+
runtime.restoreGoalToolsHiddenByPolicy();
|
|
554
|
+
runtime.goalToolsUnlocked = true;
|
|
555
|
+
return;
|
|
556
|
+
}
|
|
557
|
+
if (runtime.activeGoal) {
|
|
558
|
+
runtime.goalToolsUnlocked = true;
|
|
559
|
+
runtime.goalToolsHiddenByPolicy.clear();
|
|
560
|
+
return;
|
|
561
|
+
}
|
|
562
|
+
if (ctx.isIdle() !== true) {
|
|
563
|
+
throw new Error("Wait for Pi to become idle before hiding Goal tools.");
|
|
564
|
+
}
|
|
565
|
+
runtime.goalToolsUnlocked = false;
|
|
566
|
+
runtime.hideGoalToolsIfLocked();
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
function applyQueueSetting(runtime: GoalRuntime, ctx: ExtensionCommandContext) {
|
|
570
|
+
const hasQueueState = runtime.queuedGoals.length > 0 || runtime.pendingQueueAction !== undefined;
|
|
571
|
+
const shouldFreeze = !runtime.settings.experimental.goals && hasQueueState;
|
|
572
|
+
// Keep the freeze guard until the aborted Goal-owned run reaches agent_settled.
|
|
573
|
+
// Releasing it earlier lets the old agent_end pause newly resumed work.
|
|
574
|
+
if (runtime.queueFrozen && !shouldFreeze && runtime.queueFreezeAwaitingSettle) return;
|
|
575
|
+
if (runtime.queueFrozen === shouldFreeze) return;
|
|
576
|
+
const activeGoal = runtime.activeGoal?.status === "active" ? runtime.activeGoal : undefined;
|
|
577
|
+
const goalOwnedRun = activeGoal && runtime.agentRunGoalId === activeGoal.id;
|
|
578
|
+
if (shouldFreeze && activeGoal) {
|
|
579
|
+
if (goalOwnedRun) runtime.recordGoalUsage(activeGoal, ctx, false);
|
|
580
|
+
else {
|
|
581
|
+
const now = Date.now();
|
|
582
|
+
checkpointGoalActiveTime(activeGoal, now, false);
|
|
583
|
+
activeGoal.updatedAt = now;
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
runtime.queueFrozen = shouldFreeze;
|
|
587
|
+
if (runtime.activeGoal) runtime.persistGoal(runtime.activeGoal);
|
|
588
|
+
if (shouldFreeze) ctx.ui.setStatus(STATUS_KEY, "queue off");
|
|
589
|
+
else if (runtime.activeGoal) runtime.updateStatus(ctx, runtime.activeGoal);
|
|
590
|
+
else ctx.ui.setStatus(STATUS_KEY, undefined);
|
|
591
|
+
if (!shouldFreeze) return;
|
|
592
|
+
|
|
593
|
+
runtime.cancelContinuationWork();
|
|
594
|
+
runtime.clearGoalRecovery();
|
|
595
|
+
runtime.clearBudgetWrapUp();
|
|
596
|
+
if (goalOwnedRun) {
|
|
597
|
+
runtime.blockStaleGoalToolCalls();
|
|
598
|
+
runtime.guardAbortGoalId = activeGoal.id;
|
|
599
|
+
runtime.queueFreezeAwaitingSettle = true;
|
|
600
|
+
runtime.clearAgentRun();
|
|
601
|
+
abortCurrentTurn(ctx);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
function restorePersistedRuntime(runtime: GoalRuntime, ctx: ExtensionCommandContext) {
|
|
606
|
+
if (runtime.activeGoal) {
|
|
607
|
+
runtime.persistGoal(runtime.activeGoal);
|
|
608
|
+
if (runtime.queueFrozen) ctx.ui.setStatus(STATUS_KEY, "queue off");
|
|
609
|
+
else runtime.updateStatus(ctx, runtime.activeGoal);
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
ctx.ui.setStatus(STATUS_KEY, undefined);
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
async function confirmLowerActiveLimit(
|
|
616
|
+
runtime: GoalRuntime,
|
|
617
|
+
ctx: ExtensionCommandContext,
|
|
618
|
+
field: LimitField,
|
|
619
|
+
limit: number | null,
|
|
620
|
+
) {
|
|
621
|
+
const goal = runtime.activeGoal;
|
|
622
|
+
if (goal?.status !== "active" || limit === null) return { apply: true };
|
|
623
|
+
const used = field === "automaticTurns" ? goal.automaticModelTurns : goal.toolFreeRepeatCount;
|
|
624
|
+
if (used < limit) return { apply: true };
|
|
625
|
+
return {
|
|
626
|
+
apply: await ctx.ui.confirm(
|
|
627
|
+
"Apply limit and pause now?",
|
|
628
|
+
`The active goal has already used ${used}. Setting this limit to ${limit} will pause it immediately without deleting progress.`,
|
|
629
|
+
),
|
|
630
|
+
goalId: goal.id,
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
function withLimit(settings: GoalSettings, field: LimitField, value: number | null): GoalSettings {
|
|
635
|
+
return {
|
|
636
|
+
...structuredClone(settings),
|
|
637
|
+
continuationLimits: { ...settings.continuationLimits, [field]: value },
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
|
|
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
|
+
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";
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
function visibilityLabel(value: GoalSettings["toolVisibility"]) {
|
|
701
|
+
return value === "always" ? "Always" : "After first goal";
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
function retainedGoalCount(runtime: GoalRuntime) {
|
|
705
|
+
return (
|
|
706
|
+
(runtime.activeGoal ? 1 : 0) +
|
|
707
|
+
runtime.queuedGoals.length +
|
|
708
|
+
(runtime.pendingQueueAction?.kind === "prioritize" ? 1 : 0)
|
|
709
|
+
);
|
|
710
|
+
}
|
|
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
|
+
|
|
750
|
+
function safeTerminalText(value: string) {
|
|
751
|
+
return [...value]
|
|
752
|
+
.map((character) => {
|
|
753
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
754
|
+
return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? " " : character;
|
|
755
|
+
})
|
|
756
|
+
.join("")
|
|
757
|
+
.trim();
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
function formatError(error: unknown) {
|
|
761
|
+
return error instanceof Error ? error.message : String(error);
|
|
762
|
+
}
|