@narumitw/pi-goal 0.27.2 → 0.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -11
- package/package.json +11 -6
- package/src/accounting.ts +1 -3
- package/src/commands.ts +68 -5
- package/src/goal.ts +22 -3
- package/src/index.ts +1 -0
- package/src/menu.ts +431 -0
- package/src/queue.ts +25 -1
- package/src/runtime.ts +81 -7
- package/src/settings-ui.ts +430 -0
- package/src/settings.ts +70 -1
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import {
|
|
3
|
+
type ExtensionCommandContext,
|
|
4
|
+
getAgentDir,
|
|
5
|
+
getSettingsListTheme,
|
|
6
|
+
} from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import { Container, type SettingItem, SettingsList, Text } from "@earendil-works/pi-tui";
|
|
8
|
+
import { checkpointGoalActiveTime } from "./accounting.js";
|
|
9
|
+
import { abortCurrentTurn, type GoalRuntime, STATUS_KEY } from "./runtime.js";
|
|
10
|
+
import { GOAL_SETTINGS_FILE, type GoalSettings, saveGoalSettings } from "./settings.js";
|
|
11
|
+
|
|
12
|
+
interface GoalSettingsUiOptions {
|
|
13
|
+
settingsPath?: string;
|
|
14
|
+
save?: (settings: GoalSettings, settingsPath: string) => void;
|
|
15
|
+
onQueueUnfrozen?: (ctx: ExtensionCommandContext) => Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface GoalSettingsApplyOptions {
|
|
19
|
+
save?: (settings: GoalSettings) => void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
type LimitField = "automaticTurns" | "noProgressTurns";
|
|
23
|
+
type SettingsScreenResult =
|
|
24
|
+
| { kind: "limit"; field: LimitField }
|
|
25
|
+
| { kind: "queue"; enabled: boolean }
|
|
26
|
+
| undefined;
|
|
27
|
+
|
|
28
|
+
export async function showGoalSettings(
|
|
29
|
+
runtime: GoalRuntime,
|
|
30
|
+
ctx: ExtensionCommandContext,
|
|
31
|
+
options: GoalSettingsUiOptions = {},
|
|
32
|
+
) {
|
|
33
|
+
const settingsPath = options.settingsPath ?? join(getAgentDir(), GOAL_SETTINGS_FILE);
|
|
34
|
+
if (ctx.mode !== "tui") {
|
|
35
|
+
ctx.ui.notify(`Edit pi-goal settings manually: ${safeTerminalText(settingsPath)}`, "info");
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
while (true) {
|
|
40
|
+
const result = await showSettingsScreen(runtime, ctx, settingsPath, options);
|
|
41
|
+
if (!result) return;
|
|
42
|
+
if (result.kind === "queue") {
|
|
43
|
+
const next = await nextQueueSettings(runtime, ctx, result.enabled);
|
|
44
|
+
if (!next) return;
|
|
45
|
+
const wasFrozen = runtime.queueFrozen;
|
|
46
|
+
try {
|
|
47
|
+
applyGoalSettings(runtime, next, ctx, {
|
|
48
|
+
save: (settings) => (options.save ?? saveGoalSettings)(settings, settingsPath),
|
|
49
|
+
});
|
|
50
|
+
if (wasFrozen && !runtime.queueFrozen) {
|
|
51
|
+
try {
|
|
52
|
+
await options.onQueueUnfrozen?.(ctx);
|
|
53
|
+
} catch (error) {
|
|
54
|
+
ctx.ui.notify(
|
|
55
|
+
`Goal queue enabled, but automatic resume failed: ${formatError(error)}. Reopen /goal to retry.`,
|
|
56
|
+
"warning",
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
ctx.ui.notify(`Ordered goal queue: ${result.enabled ? "Experimental" : "Off"}.`, "info");
|
|
61
|
+
} catch (error) {
|
|
62
|
+
ctx.ui.notify(`pi-goal settings save failed: ${formatError(error)}`, "error");
|
|
63
|
+
}
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const previous = runtime.settings.continuationLimits[result.field];
|
|
68
|
+
const raw = await ctx.ui.input(
|
|
69
|
+
result.field === "automaticTurns" ? "Automatic response limit" : "No-progress run limit",
|
|
70
|
+
formatGoalLimit(previous),
|
|
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");
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
const confirmation = await confirmLowerActiveLimit(runtime, ctx, result.field, limit);
|
|
79
|
+
if (!confirmation.apply) continue;
|
|
80
|
+
if (confirmation.goalId !== undefined && runtime.activeGoal?.id !== confirmation.goalId) {
|
|
81
|
+
ctx.ui.notify(
|
|
82
|
+
"The active goal changed while confirming the limit. No settings were changed.",
|
|
83
|
+
"warning",
|
|
84
|
+
);
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const next = withLimit(runtime.settings, result.field, limit);
|
|
88
|
+
try {
|
|
89
|
+
applyGoalSettings(runtime, next, ctx, {
|
|
90
|
+
save: (settings) => (options.save ?? saveGoalSettings)(settings, settingsPath),
|
|
91
|
+
});
|
|
92
|
+
ctx.ui.notify(
|
|
93
|
+
`${result.field === "automaticTurns" ? "Automatic response" : "No-progress"} limit: ${formatGoalLimit(limit)}.`,
|
|
94
|
+
"info",
|
|
95
|
+
);
|
|
96
|
+
} catch (error) {
|
|
97
|
+
ctx.ui.notify(`pi-goal settings save failed: ${formatError(error)}`, "error");
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function applyGoalSettings(
|
|
103
|
+
runtime: GoalRuntime,
|
|
104
|
+
next: GoalSettings,
|
|
105
|
+
ctx: ExtensionCommandContext,
|
|
106
|
+
options: GoalSettingsApplyOptions = {},
|
|
107
|
+
) {
|
|
108
|
+
const snapshot = runtime.snapshotSettingsApplicationState();
|
|
109
|
+
let fileSaved = false;
|
|
110
|
+
try {
|
|
111
|
+
runtime.settings = structuredClone(next);
|
|
112
|
+
applyToolVisibility(runtime, snapshot.settings, next, ctx);
|
|
113
|
+
options.save?.(next);
|
|
114
|
+
fileSaved = options.save !== undefined;
|
|
115
|
+
applyQueueSetting(runtime, ctx);
|
|
116
|
+
const activeGoalId = runtime.activeGoal?.id;
|
|
117
|
+
const abortOwnedRun = activeGoalId !== undefined && runtime.agentRunGoalId === activeGoalId;
|
|
118
|
+
const pausedByAutomaticLimit = runtime.enforceAutomaticTurnLimit(ctx, abortOwnedRun);
|
|
119
|
+
if (!pausedByAutomaticLimit) runtime.enforceNoProgressLimit(ctx, abortOwnedRun);
|
|
120
|
+
} catch (error) {
|
|
121
|
+
const rollbackErrors: unknown[] = [];
|
|
122
|
+
try {
|
|
123
|
+
runtime.restoreSettingsApplicationState(snapshot);
|
|
124
|
+
} catch (rollbackError) {
|
|
125
|
+
rollbackErrors.push(rollbackError);
|
|
126
|
+
}
|
|
127
|
+
if (fileSaved) {
|
|
128
|
+
try {
|
|
129
|
+
options.save?.(snapshot.settings);
|
|
130
|
+
} catch (rollbackError) {
|
|
131
|
+
rollbackErrors.push(rollbackError);
|
|
132
|
+
}
|
|
133
|
+
try {
|
|
134
|
+
restorePersistedRuntime(runtime, ctx);
|
|
135
|
+
} catch (rollbackError) {
|
|
136
|
+
rollbackErrors.push(rollbackError);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
if (rollbackErrors.length > 0) {
|
|
140
|
+
throw new AggregateError(
|
|
141
|
+
[error, ...rollbackErrors],
|
|
142
|
+
`pi-goal settings application failed and rollback was incomplete: ${formatError(error)}`,
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
throw error;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function parseGoalLimit(value: string): number | null | undefined {
|
|
150
|
+
const normalized = value.trim().toLowerCase();
|
|
151
|
+
if (normalized === "unlimited" || normalized === "off") return null;
|
|
152
|
+
if (!/^\d+$/u.test(normalized)) return undefined;
|
|
153
|
+
const parsed = Number(normalized);
|
|
154
|
+
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function formatGoalLimit(value: number | null) {
|
|
158
|
+
return value === null ? "Unlimited" : String(value);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function showSettingsScreen(
|
|
162
|
+
runtime: GoalRuntime,
|
|
163
|
+
ctx: ExtensionCommandContext,
|
|
164
|
+
settingsPath: string,
|
|
165
|
+
options: GoalSettingsUiOptions,
|
|
166
|
+
): Promise<SettingsScreenResult> {
|
|
167
|
+
let saveQueue = Promise.resolve();
|
|
168
|
+
const latestRequested = new Map<string, string>();
|
|
169
|
+
return ctx.ui.custom<SettingsScreenResult>((tui, theme, _keybindings, done) => {
|
|
170
|
+
const settings = runtime.settings;
|
|
171
|
+
const items: SettingItem[] = [
|
|
172
|
+
{
|
|
173
|
+
id: "toolVisibility",
|
|
174
|
+
label: "Goal tools",
|
|
175
|
+
description: "Keep terminal Goal tools visible, or reveal them after the first goal.",
|
|
176
|
+
currentValue: visibilityLabel(settings.toolVisibility),
|
|
177
|
+
values: ["Always", "After first goal"],
|
|
178
|
+
},
|
|
179
|
+
{
|
|
180
|
+
id: "experimentalGoals",
|
|
181
|
+
label: "Ordered goal queue",
|
|
182
|
+
description: "Enable experimental add, prioritize, skip, and drop-last workflows.",
|
|
183
|
+
currentValue: settings.experimental.goals ? "Experimental" : "Off",
|
|
184
|
+
values: ["Off", "Experimental"],
|
|
185
|
+
},
|
|
186
|
+
limitItem(
|
|
187
|
+
"automaticTurns",
|
|
188
|
+
"Automatic response limit",
|
|
189
|
+
"Pause after this many Goal-owned automatic model responses.",
|
|
190
|
+
settings.continuationLimits.automaticTurns,
|
|
191
|
+
),
|
|
192
|
+
limitItem(
|
|
193
|
+
"noProgressTurns",
|
|
194
|
+
"No-progress limit",
|
|
195
|
+
"Pause after this many repeated or empty tool-free automatic runs.",
|
|
196
|
+
settings.continuationLimits.noProgressTurns,
|
|
197
|
+
),
|
|
198
|
+
];
|
|
199
|
+
const container = new Container();
|
|
200
|
+
container.addChild(new Text(theme.fg("accent", theme.bold("Pi Goal Settings")), 1, 0));
|
|
201
|
+
container.addChild(
|
|
202
|
+
new Text(theme.fg("muted", `User settings · ${safeTerminalText(settingsPath)}`), 1, 0),
|
|
203
|
+
);
|
|
204
|
+
let settingsList: SettingsList;
|
|
205
|
+
let closing = false;
|
|
206
|
+
const closeAfterSaves = (result: SettingsScreenResult) => {
|
|
207
|
+
if (closing) return;
|
|
208
|
+
closing = true;
|
|
209
|
+
void saveQueue.then(() => done(result));
|
|
210
|
+
};
|
|
211
|
+
settingsList = new SettingsList(
|
|
212
|
+
items,
|
|
213
|
+
Math.min(items.length + 2, 15),
|
|
214
|
+
getSettingsListTheme(),
|
|
215
|
+
(id, newValue) => {
|
|
216
|
+
if (closing) return;
|
|
217
|
+
if ((id === "automaticTurns" || id === "noProgressTurns") && newValue === "Edit…") {
|
|
218
|
+
closeAfterSaves({ kind: "limit", field: id });
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
if (id === "experimentalGoals") {
|
|
222
|
+
closeAfterSaves({ kind: "queue", enabled: newValue === "Experimental" });
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
if (id !== "toolVisibility") return;
|
|
226
|
+
latestRequested.set(id, newValue);
|
|
227
|
+
const operation = saveQueue.then(async () => {
|
|
228
|
+
const previousValue = visibilityLabel(runtime.settings.toolVisibility);
|
|
229
|
+
try {
|
|
230
|
+
const next = {
|
|
231
|
+
...structuredClone(runtime.settings),
|
|
232
|
+
toolVisibility: newValue === "Always" ? "always" : "after-first-goal",
|
|
233
|
+
} satisfies GoalSettings;
|
|
234
|
+
applyGoalSettings(runtime, next, ctx, {
|
|
235
|
+
save: (value) => (options.save ?? saveGoalSettings)(value, settingsPath),
|
|
236
|
+
});
|
|
237
|
+
ctx.ui.notify(`Goal tools: ${newValue}.`, "info");
|
|
238
|
+
} catch (error) {
|
|
239
|
+
if (latestRequested.get(id) === newValue) {
|
|
240
|
+
settingsList.updateValue(id, previousValue);
|
|
241
|
+
}
|
|
242
|
+
ctx.ui.notify(`pi-goal settings save failed: ${formatError(error)}`, "error");
|
|
243
|
+
tui.requestRender();
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
saveQueue = operation.catch(() => undefined);
|
|
247
|
+
},
|
|
248
|
+
() => closeAfterSaves(undefined),
|
|
249
|
+
{ enableSearch: false },
|
|
250
|
+
);
|
|
251
|
+
container.addChild(settingsList);
|
|
252
|
+
container.addChild(
|
|
253
|
+
new Text(theme.fg("dim", "↑↓ navigate · enter/space change · esc close"), 1, 0),
|
|
254
|
+
);
|
|
255
|
+
return {
|
|
256
|
+
render: (width: number) => container.render(width),
|
|
257
|
+
invalidate: () => container.invalidate(),
|
|
258
|
+
handleInput(data: string) {
|
|
259
|
+
if (closing) return;
|
|
260
|
+
settingsList.handleInput?.(data);
|
|
261
|
+
tui.requestRender();
|
|
262
|
+
},
|
|
263
|
+
};
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
async function nextQueueSettings(
|
|
268
|
+
runtime: GoalRuntime,
|
|
269
|
+
ctx: ExtensionCommandContext,
|
|
270
|
+
enabled: boolean,
|
|
271
|
+
) {
|
|
272
|
+
if (runtime.settings.experimental.goals === enabled) return undefined;
|
|
273
|
+
if (enabled && !runtime.settings.experimental.goals) {
|
|
274
|
+
const confirmed = await ctx.ui.confirm(
|
|
275
|
+
"Enable experimental goal queue?",
|
|
276
|
+
"Queue behavior and persisted state may change between releases. Existing single-goal behavior remains available.",
|
|
277
|
+
);
|
|
278
|
+
if (!confirmed) return undefined;
|
|
279
|
+
}
|
|
280
|
+
if (
|
|
281
|
+
!enabled &&
|
|
282
|
+
(runtime.queuedGoals.length > 0 || runtime.pendingQueueAction !== undefined) &&
|
|
283
|
+
!(await ctx.ui.confirm(
|
|
284
|
+
"Freeze ordered goal queue?",
|
|
285
|
+
`Disabling the experiment preserves ${retainedGoalCount(runtime)} goal(s) but freezes automatic work until the setting is re-enabled. No goal data will be deleted.`,
|
|
286
|
+
))
|
|
287
|
+
) {
|
|
288
|
+
return undefined;
|
|
289
|
+
}
|
|
290
|
+
return {
|
|
291
|
+
...structuredClone(runtime.settings),
|
|
292
|
+
experimental: { goals: enabled },
|
|
293
|
+
} satisfies GoalSettings;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function applyToolVisibility(
|
|
297
|
+
runtime: GoalRuntime,
|
|
298
|
+
previous: GoalSettings,
|
|
299
|
+
next: GoalSettings,
|
|
300
|
+
ctx: ExtensionCommandContext,
|
|
301
|
+
) {
|
|
302
|
+
if (previous.toolVisibility === next.toolVisibility) return;
|
|
303
|
+
if (next.toolVisibility === "always") {
|
|
304
|
+
if (runtime.goalToolsHiddenByPolicy.size > 0 && ctx.isIdle() !== true) {
|
|
305
|
+
throw new Error("Wait for Pi to become idle before revealing Goal tools.");
|
|
306
|
+
}
|
|
307
|
+
runtime.restoreGoalToolsHiddenByPolicy();
|
|
308
|
+
runtime.goalToolsUnlocked = true;
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
if (runtime.activeGoal) {
|
|
312
|
+
runtime.goalToolsUnlocked = true;
|
|
313
|
+
runtime.goalToolsHiddenByPolicy.clear();
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
if (ctx.isIdle() !== true) {
|
|
317
|
+
throw new Error("Wait for Pi to become idle before hiding Goal tools.");
|
|
318
|
+
}
|
|
319
|
+
runtime.goalToolsUnlocked = false;
|
|
320
|
+
runtime.hideGoalToolsIfLocked();
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function applyQueueSetting(runtime: GoalRuntime, ctx: ExtensionCommandContext) {
|
|
324
|
+
const hasQueueState = runtime.queuedGoals.length > 0 || runtime.pendingQueueAction !== undefined;
|
|
325
|
+
const shouldFreeze = !runtime.settings.experimental.goals && hasQueueState;
|
|
326
|
+
// Keep the freeze guard until the aborted Goal-owned run reaches agent_settled.
|
|
327
|
+
// Releasing it earlier lets the old agent_end pause newly resumed work.
|
|
328
|
+
if (runtime.queueFrozen && !shouldFreeze && runtime.queueFreezeAwaitingSettle) return;
|
|
329
|
+
if (runtime.queueFrozen === shouldFreeze) return;
|
|
330
|
+
const activeGoal = runtime.activeGoal?.status === "active" ? runtime.activeGoal : undefined;
|
|
331
|
+
const goalOwnedRun = activeGoal && runtime.agentRunGoalId === activeGoal.id;
|
|
332
|
+
if (shouldFreeze && activeGoal) {
|
|
333
|
+
if (goalOwnedRun) runtime.recordGoalUsage(activeGoal, ctx, false);
|
|
334
|
+
else {
|
|
335
|
+
const now = Date.now();
|
|
336
|
+
checkpointGoalActiveTime(activeGoal, now, false);
|
|
337
|
+
activeGoal.updatedAt = now;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
runtime.queueFrozen = shouldFreeze;
|
|
341
|
+
if (runtime.activeGoal) runtime.persistGoal(runtime.activeGoal);
|
|
342
|
+
if (shouldFreeze) ctx.ui.setStatus(STATUS_KEY, "queue off");
|
|
343
|
+
else if (runtime.activeGoal) runtime.updateStatus(ctx, runtime.activeGoal);
|
|
344
|
+
else ctx.ui.setStatus(STATUS_KEY, undefined);
|
|
345
|
+
if (!shouldFreeze) return;
|
|
346
|
+
|
|
347
|
+
runtime.cancelContinuationWork();
|
|
348
|
+
runtime.clearGoalRecovery();
|
|
349
|
+
runtime.clearBudgetWrapUp();
|
|
350
|
+
if (goalOwnedRun) {
|
|
351
|
+
runtime.blockStaleGoalToolCalls();
|
|
352
|
+
runtime.guardAbortGoalId = activeGoal.id;
|
|
353
|
+
runtime.queueFreezeAwaitingSettle = true;
|
|
354
|
+
runtime.clearAgentRun();
|
|
355
|
+
abortCurrentTurn(ctx);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function restorePersistedRuntime(runtime: GoalRuntime, ctx: ExtensionCommandContext) {
|
|
360
|
+
if (runtime.activeGoal) {
|
|
361
|
+
runtime.persistGoal(runtime.activeGoal);
|
|
362
|
+
if (runtime.queueFrozen) ctx.ui.setStatus(STATUS_KEY, "queue off");
|
|
363
|
+
else runtime.updateStatus(ctx, runtime.activeGoal);
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
ctx.ui.setStatus(STATUS_KEY, undefined);
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
async function confirmLowerActiveLimit(
|
|
370
|
+
runtime: GoalRuntime,
|
|
371
|
+
ctx: ExtensionCommandContext,
|
|
372
|
+
field: LimitField,
|
|
373
|
+
limit: number | null,
|
|
374
|
+
) {
|
|
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 reached safety limit?",
|
|
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
|
+
};
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function withLimit(settings: GoalSettings, field: LimitField, value: number | null): GoalSettings {
|
|
389
|
+
return {
|
|
390
|
+
...structuredClone(settings),
|
|
391
|
+
continuationLimits: { ...settings.continuationLimits, [field]: value },
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
function limitItem(id: LimitField, label: string, description: string, value: number | null) {
|
|
396
|
+
const currentValue = formatGoalLimit(value);
|
|
397
|
+
return {
|
|
398
|
+
id,
|
|
399
|
+
label,
|
|
400
|
+
description,
|
|
401
|
+
currentValue,
|
|
402
|
+
values: [currentValue, "Edit…"],
|
|
403
|
+
} satisfies SettingItem;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
function visibilityLabel(value: GoalSettings["toolVisibility"]) {
|
|
407
|
+
return value === "always" ? "Always" : "After first goal";
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
function retainedGoalCount(runtime: GoalRuntime) {
|
|
411
|
+
return (
|
|
412
|
+
(runtime.activeGoal ? 1 : 0) +
|
|
413
|
+
runtime.queuedGoals.length +
|
|
414
|
+
(runtime.pendingQueueAction?.kind === "prioritize" ? 1 : 0)
|
|
415
|
+
);
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
function safeTerminalText(value: string) {
|
|
419
|
+
return [...value]
|
|
420
|
+
.map((character) => {
|
|
421
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
422
|
+
return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? " " : character;
|
|
423
|
+
})
|
|
424
|
+
.join("")
|
|
425
|
+
.trim();
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
function formatError(error: unknown) {
|
|
429
|
+
return error instanceof Error ? error.message : String(error);
|
|
430
|
+
}
|
package/src/settings.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import { linkSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { linkSync, 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
|
|
|
@@ -44,6 +44,13 @@ interface GoalSettingsInitializationFileSystem {
|
|
|
44
44
|
rmSync: typeof rmSync;
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
+
interface GoalSettingsSaveFileSystem {
|
|
48
|
+
mkdirSync: typeof mkdirSync;
|
|
49
|
+
writeFileSync: typeof writeFileSync;
|
|
50
|
+
renameSync: typeof renameSync;
|
|
51
|
+
rmSync: typeof rmSync;
|
|
52
|
+
}
|
|
53
|
+
|
|
47
54
|
export function normalizeGoalSettings(value: unknown): GoalSettings | undefined {
|
|
48
55
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined;
|
|
49
56
|
const toolVisibility = Object.hasOwn(value, "toolVisibility")
|
|
@@ -154,6 +161,62 @@ export function loadOrCreateGoalSettings(
|
|
|
154
161
|
}
|
|
155
162
|
}
|
|
156
163
|
|
|
164
|
+
export function saveGoalSettings(
|
|
165
|
+
settings: GoalSettings,
|
|
166
|
+
settingsPath = join(getAgentDir(), GOAL_SETTINGS_FILE),
|
|
167
|
+
overrides: Partial<GoalSettingsSaveFileSystem> = {},
|
|
168
|
+
) {
|
|
169
|
+
const normalized = normalizeGoalSettings(settings);
|
|
170
|
+
if (!normalized) throw new Error("Refusing to save invalid pi-goal settings.");
|
|
171
|
+
|
|
172
|
+
let raw: Record<string, unknown> = {};
|
|
173
|
+
try {
|
|
174
|
+
const contents = readFileSync(settingsPath, "utf8");
|
|
175
|
+
const parsed = JSON.parse(contents) as unknown;
|
|
176
|
+
if (!normalizeGoalSettings(parsed)) {
|
|
177
|
+
throw new Error(`${settingsPath}: invalid settings shape`);
|
|
178
|
+
}
|
|
179
|
+
raw = ownRecord(parsed) ?? {};
|
|
180
|
+
} catch (error) {
|
|
181
|
+
if (!isNodeError(error) || error.code !== "ENOENT") {
|
|
182
|
+
throw new Error(`Cannot save invalid settings file: ${formatError(error)}`);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const experimental = ownRecord(raw.experimental) ?? {};
|
|
187
|
+
const continuationLimits = ownRecord(raw.continuationLimits) ?? {};
|
|
188
|
+
const document = `${JSON.stringify(
|
|
189
|
+
{
|
|
190
|
+
...raw,
|
|
191
|
+
toolVisibility: normalized.toolVisibility,
|
|
192
|
+
experimental: { ...experimental, goals: normalized.experimental.goals },
|
|
193
|
+
continuationLimits: {
|
|
194
|
+
...continuationLimits,
|
|
195
|
+
automaticTurns: normalized.continuationLimits.automaticTurns,
|
|
196
|
+
noProgressTurns: normalized.continuationLimits.noProgressTurns,
|
|
197
|
+
},
|
|
198
|
+
},
|
|
199
|
+
null,
|
|
200
|
+
2,
|
|
201
|
+
)}\n`;
|
|
202
|
+
const fs = { mkdirSync, writeFileSync, renameSync, rmSync, ...overrides };
|
|
203
|
+
const temporaryPath = join(
|
|
204
|
+
dirname(settingsPath),
|
|
205
|
+
`.${basename(settingsPath)}.${randomUUID()}.tmp`,
|
|
206
|
+
);
|
|
207
|
+
try {
|
|
208
|
+
fs.mkdirSync(dirname(settingsPath), { recursive: true });
|
|
209
|
+
fs.writeFileSync(temporaryPath, document, { encoding: "utf8", flag: "wx" });
|
|
210
|
+
fs.renameSync(temporaryPath, settingsPath);
|
|
211
|
+
} finally {
|
|
212
|
+
try {
|
|
213
|
+
fs.rmSync(temporaryPath, { force: true });
|
|
214
|
+
} catch {
|
|
215
|
+
// Best-effort cleanup must not replace the save result.
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
157
220
|
export function readGoalSettings(
|
|
158
221
|
settingsPath = join(getAgentDir(), GOAL_SETTINGS_FILE),
|
|
159
222
|
): GoalSettingsLoadResult {
|
|
@@ -175,6 +238,12 @@ export function readGoalSettings(
|
|
|
175
238
|
}
|
|
176
239
|
}
|
|
177
240
|
|
|
241
|
+
function ownRecord(value: unknown): Record<string, unknown> | undefined {
|
|
242
|
+
return value && typeof value === "object" && !Array.isArray(value)
|
|
243
|
+
? (value as Record<string, unknown>)
|
|
244
|
+
: undefined;
|
|
245
|
+
}
|
|
246
|
+
|
|
178
247
|
function isNodeError(error: unknown): error is NodeJS.ErrnoException {
|
|
179
248
|
return error instanceof Error && "code" in error;
|
|
180
249
|
}
|