@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
package/src/menu.ts CHANGED
@@ -11,675 +11,649 @@ import type { ActiveGoal } from "./persistence.js";
11
11
  import { type GoalRuntime, goalSummary } from "./runtime.js";
12
12
 
13
13
  export const GOAL_MENU_ACTIONS = {
14
- start: "Start a goal…",
15
- startBudget: "Start with token budget…",
16
- pause: "Pause goal",
17
- resume: "Resume goal",
18
- reviewSafety: "Review and continue…",
19
- increaseBudget: "Increase budget and resume…",
20
- edit: "Edit goal…",
21
- replace: "Replace goal…",
22
- status: "View full status",
23
- settings: "Settings…",
24
- help: "Help",
25
- clear: "Clear goal…",
26
- close: "Close",
14
+ start: "Start a goal…",
15
+ startBudget: "Start with token budget…",
16
+ pause: "Pause goal",
17
+ resume: "Resume goal",
18
+ reviewSafety: "Review and continue…",
19
+ increaseBudget: "Increase budget and resume…",
20
+ edit: "Edit goal…",
21
+ replace: "Replace goal…",
22
+ status: "View full status",
23
+ settings: "Settings…",
24
+ help: "Help",
25
+ clear: "Clear goal…",
26
+ close: "Close",
27
27
  } as const;
28
28
 
29
29
  interface GoalMenuRuntimeView {
30
- activeGoal?: ActiveGoal;
31
- settings: GoalRuntime["settings"];
32
- recordGoalUsage?: GoalRuntime["recordGoalUsage"];
33
- persistGoal?: GoalRuntime["persistGoal"];
34
- updateStatus?: GoalRuntime["updateStatus"];
30
+ activeGoal?: ActiveGoal;
31
+ settings: GoalRuntime["settings"];
32
+ recordGoalUsage?: GoalRuntime["recordGoalUsage"];
33
+ persistGoal?: GoalRuntime["persistGoal"];
34
+ updateStatus?: GoalRuntime["updateStatus"];
35
35
  }
36
36
 
37
37
  export interface GoalMenuState {
38
- title: string;
39
- actions: string[];
38
+ title: string;
39
+ actions: string[];
40
40
  }
41
41
 
42
42
  type ShowSettings = (ctx: ExtensionCommandContext, target?: "automatic") => Promise<void>;
43
43
  type GoalMenuScreen =
44
- | "main"
45
- | "start-budget"
46
- | "start-custom-budget"
47
- | "increase-budget"
48
- | "safety"
49
- | "status"
50
- | "help";
44
+ | "main"
45
+ | "start-budget"
46
+ | "start-custom-budget"
47
+ | "increase-budget"
48
+ | "safety"
49
+ | "status"
50
+ | "help";
51
51
  type GoalMenuAction =
52
- | "start"
53
- | "start-with-budget"
54
- | "start-with-custom-budget"
55
- | "submit-increase-budget"
56
- | "pause"
57
- | "resume"
58
- | "safety-resume"
59
- | "safety-settings"
60
- | "edit"
61
- | "replace"
62
- | "settings"
63
- | "clear"
64
- | "back";
52
+ | "start"
53
+ | "start-with-budget"
54
+ | "start-with-custom-budget"
55
+ | "submit-increase-budget"
56
+ | "pause"
57
+ | "resume"
58
+ | "safety-resume"
59
+ | "safety-settings"
60
+ | "edit"
61
+ | "replace"
62
+ | "settings"
63
+ | "clear"
64
+ | "back";
65
65
 
66
66
  export function buildGoalMenuState(runtime: GoalMenuRuntimeView): GoalMenuState {
67
- const goal = runtime.activeGoal;
68
- const pausedByAutomaticLimit =
69
- goal?.status === "paused" && goal.safetyPauseCause === "continuation_limit";
70
- const waitingReason = goal?.waiting ? safeGoalMenuText(goal.waiting.reason) : undefined;
71
- const state = pausedByAutomaticLimit
72
- ? "Paused — automatic-work limit reached"
73
- : waitingReason
74
- ? `Waiting — ${waitingReason}`
75
- : displayStatus(goal?.status);
76
- const automaticTurnLimit = runtime.settings.continuationLimits.automaticTurns;
77
- const used = goal?.automaticModelTurns ?? 0;
78
- const automaticResponses =
79
- automaticTurnLimit === null
80
- ? `Automatic work: ${used} responses · Unlimited`
81
- : `Automatic work: ${used} of ${automaticTurnLimit} responses${
82
- used < automaticTurnLimit ? ` · ${automaticTurnLimit - used} remaining` : ""
83
- }`;
84
- const title = goal
85
- ? [
86
- `Goal · ${state}`,
87
- safeGoalMenuText(goal.text),
88
- `Usage: ${
89
- goal.tokenBudget === undefined
90
- ? formatDuration(goal.timeUsedSeconds)
91
- : `${formatTokenCount(goal.tokensUsed)}/${formatTokenCount(goal.tokenBudget)}`
92
- }`,
93
- automaticResponses,
94
- ...(pausedByAutomaticLimit
95
- ? ["Progress is saved. Review the safety limit before continuing."]
96
- : []),
97
- ].join("\n")
98
- : [
99
- `Goal · ${state}`,
100
- "No goal is currently set",
101
- automaticTurnLimit === null
102
- ? "Automatic work is configured as Unlimited."
103
- : `Automatic work is configured to pause after ${automaticTurnLimit} responses.`,
104
- ].join("\n");
67
+ const goal = runtime.activeGoal;
68
+ const pausedByAutomaticLimit = goal?.status === "paused" && goal.safetyPauseCause === "continuation_limit";
69
+ const waitingReason = goal?.waiting ? safeGoalMenuText(goal.waiting.reason) : undefined;
70
+ const state = pausedByAutomaticLimit
71
+ ? "Paused — automatic-work limit reached"
72
+ : waitingReason
73
+ ? `Waiting — ${waitingReason}`
74
+ : displayStatus(goal?.status);
75
+ const automaticTurnLimit = runtime.settings.continuationLimits.automaticTurns;
76
+ const used = goal?.automaticModelTurns ?? 0;
77
+ const automaticResponses =
78
+ automaticTurnLimit === null
79
+ ? `Automatic work: ${used} responses · Unlimited`
80
+ : `Automatic work: ${used} of ${automaticTurnLimit} responses${
81
+ used < automaticTurnLimit ? ` · ${automaticTurnLimit - used} remaining` : ""
82
+ }`;
83
+ const title = goal
84
+ ? [
85
+ `Goal · ${state}`,
86
+ safeGoalMenuText(goal.text),
87
+ `Usage: ${
88
+ goal.tokenBudget === undefined
89
+ ? formatDuration(goal.timeUsedSeconds)
90
+ : `${formatTokenCount(goal.tokensUsed)}/${formatTokenCount(goal.tokenBudget)}`
91
+ }`,
92
+ automaticResponses,
93
+ ...(pausedByAutomaticLimit ? ["Progress is saved. Review the safety limit before continuing."] : []),
94
+ ].join("\n")
95
+ : [
96
+ `Goal · ${state}`,
97
+ "No goal is currently set",
98
+ automaticTurnLimit === null
99
+ ? "Automatic work is configured as Unlimited."
100
+ : `Automatic work is configured to pause after ${automaticTurnLimit} responses.`,
101
+ ].join("\n");
105
102
 
106
- const actions: string[] = [];
107
- if (!goal || goal.status === "complete") {
108
- actions.push(GOAL_MENU_ACTIONS.start, GOAL_MENU_ACTIONS.startBudget);
109
- } else if (goal.waiting) {
110
- actions.push(GOAL_MENU_ACTIONS.resume);
111
- } else if (goal.status === "active") {
112
- actions.push(GOAL_MENU_ACTIONS.pause);
113
- } else if (goal.status === "budget_limited") {
114
- actions.push(GOAL_MENU_ACTIONS.increaseBudget);
115
- } else if (pausedByAutomaticLimit) {
116
- actions.push(GOAL_MENU_ACTIONS.reviewSafety);
117
- } else {
118
- actions.push(GOAL_MENU_ACTIONS.resume);
119
- }
120
- if (goal && goal.status !== "complete") {
121
- actions.push(GOAL_MENU_ACTIONS.edit, GOAL_MENU_ACTIONS.replace);
122
- }
123
- if (goal) actions.push(GOAL_MENU_ACTIONS.status);
124
- actions.push(GOAL_MENU_ACTIONS.settings, GOAL_MENU_ACTIONS.help);
125
- if (goal) actions.push(GOAL_MENU_ACTIONS.clear);
126
- actions.push(GOAL_MENU_ACTIONS.close);
127
- return { title, actions };
103
+ const actions: string[] = [];
104
+ if (!goal || goal.status === "complete") {
105
+ actions.push(GOAL_MENU_ACTIONS.start, GOAL_MENU_ACTIONS.startBudget);
106
+ } else if (goal.waiting) {
107
+ actions.push(GOAL_MENU_ACTIONS.resume);
108
+ } else if (goal.status === "active") {
109
+ actions.push(GOAL_MENU_ACTIONS.pause);
110
+ } else if (goal.status === "budget_limited") {
111
+ actions.push(GOAL_MENU_ACTIONS.increaseBudget);
112
+ } else if (pausedByAutomaticLimit) {
113
+ actions.push(GOAL_MENU_ACTIONS.reviewSafety);
114
+ } else {
115
+ actions.push(GOAL_MENU_ACTIONS.resume);
116
+ }
117
+ if (goal && goal.status !== "complete") {
118
+ actions.push(GOAL_MENU_ACTIONS.edit, GOAL_MENU_ACTIONS.replace);
119
+ }
120
+ if (goal) actions.push(GOAL_MENU_ACTIONS.status);
121
+ actions.push(GOAL_MENU_ACTIONS.settings, GOAL_MENU_ACTIONS.help);
122
+ if (goal) actions.push(GOAL_MENU_ACTIONS.clear);
123
+ actions.push(GOAL_MENU_ACTIONS.close);
124
+ return { title, actions };
128
125
  }
129
126
 
130
127
  export async function showGoalManager(
131
- runtime: GoalMenuRuntimeView,
132
- commands: GoalCommandController,
133
- ctx: ExtensionCommandContext,
134
- showSettings: ShowSettings,
128
+ runtime: GoalMenuRuntimeView,
129
+ commands: GoalCommandController,
130
+ ctx: ExtensionCommandContext,
131
+ showSettings: ShowSettings,
135
132
  ): Promise<void> {
136
- if (ctx.mode !== "tui") {
137
- commands.showGoal(ctx);
138
- return;
139
- }
140
- const owner = runtime as GoalRuntime;
141
- const generation = owner.menuGeneration;
142
- const ownerSignal = owner.menuController?.signal;
143
- const isMenuCurrent = () =>
144
- owner.menuController === undefined ||
145
- (generation === owner.menuGeneration && !owner.menuController.signal.aborted);
146
- const { defineMenu, runMenu } = await import("@narumitw/pi-tui-kit");
147
- if (!isMenuCurrent()) return;
148
- let displayedGoal: ActiveGoal | undefined;
149
- let displayedBudgetGoal: ActiveGoal | undefined;
150
- let displayedBudgetValue: number | undefined;
151
- let displayedBudgetUsage: number | undefined;
152
- let displayedBudgetStatus: ActiveGoal["status"] | undefined;
153
- const menu = defineMenu<undefined, GoalMenuScreen, GoalMenuAction, ExtensionCommandContext>({
154
- start: "main",
155
- screens: {
156
- main: () => {
157
- refreshGoalMenuState(runtime, ctx);
158
- const state = buildGoalMenuState(runtime);
159
- displayedGoal = runtime.activeGoal;
160
- return {
161
- kind: "actions",
162
- title: "Goal",
163
- lines: state.title.split("\n").slice(1),
164
- items: state.actions.map(goalMainMenuItem),
165
- hint: "close",
166
- };
167
- },
168
- "start-budget": () => {
169
- return {
170
- kind: "actions",
171
- title: "Choose token budget",
172
- lines: tokenBudgetGuidance(runtime.settings.continuationLimits.automaticTurns),
173
- items: [
174
- {
175
- id: "25k",
176
- label: "25k — Lower token ceiling",
177
- description: "Set the cumulative token limit to 25k.",
178
- action: "start-with-budget",
179
- },
180
- {
181
- id: "100k",
182
- label: "100k — Suggested",
183
- description: "Set the cumulative token limit to 100k.",
184
- action: "start-with-budget",
185
- },
186
- {
187
- id: "300k",
188
- label: "300k — Higher token ceiling",
189
- description: "Set the cumulative token limit to 300k.",
190
- action: "start-with-budget",
191
- },
192
- {
193
- id: "custom",
194
- label: "Set a custom budget…",
195
- description: "Enter an exact cumulative token limit.",
196
- to: "start-custom-budget",
197
- },
198
- { id: "back", label: "Back", action: "back" },
199
- ],
200
- hint: "back",
201
- };
202
- },
203
- "start-custom-budget": () => ({
204
- kind: "input",
205
- title: "Custom token budget",
206
- lines: customTokenBudgetGuidance(runtime.settings.continuationLimits.automaticTurns),
207
- placeholder: "100k",
208
- action: "start-with-custom-budget",
209
- hint: "back",
210
- }),
211
- "increase-budget": () => {
212
- const goal = runtime.activeGoal;
213
- displayedBudgetGoal = goal;
214
- displayedBudgetValue = goal?.tokenBudget;
215
- displayedBudgetUsage = goal?.tokensUsed;
216
- displayedBudgetStatus = goal?.status;
217
- if (goal && goal.tokensUsed >= Number.MAX_SAFE_INTEGER) {
218
- return {
219
- kind: "detail",
220
- title: "Increase token budget unavailable",
221
- lines: [
222
- `Current usage: ${formatBudgetDecisionValue(goal.tokensUsed)}`,
223
- "No larger safe whole-number token budget is available. Progress remains saved; choose Back and clear or replace the goal when ready.",
224
- ],
225
- hint: "back",
226
- };
227
- }
228
- return {
229
- kind: "input",
230
- title: "Increase token budget",
231
- lines: goal
232
- ? increaseTokenBudgetGuidance(goal, runtime.settings.continuationLimits.automaticTurns)
233
- : ["The budget-limited goal is no longer available. Return to the Goal menu."],
234
- placeholder: goal ? suggestedIncreasedBudget(goal) : "300k",
235
- action: "submit-increase-budget",
236
- hint: "back",
237
- };
238
- },
239
- safety: () => {
240
- const goal = runtime.activeGoal;
241
- displayedGoal = goal;
242
- const limit = runtime.settings.continuationLimits.automaticTurns;
243
- const used = goal?.automaticModelTurns ?? 0;
244
- return {
245
- kind: "actions",
246
- title: "Automatic work paused",
247
- lines: goal
248
- ? [
249
- automaticPauseSummary(used, limit),
250
- `${safeGoalMenuText(goal.text)} is preserved.`,
251
- `${formatInteger(goal.tokensUsed)} cumulative tokens and ${formatDuration(goal.timeUsedSeconds)} active time are preserved.`,
252
- "The objective and usage are preserved.",
253
- limit === null
254
- ? "Continuing resets the counter to 0 and resumes with Unlimited automatic work."
255
- : `Continuing resets the counter to 0 and allows up to ${limit} more automatic model responses.`,
256
- ]
257
- : ["The paused goal is no longer available. Return to the Goal menu."],
258
- items: goal
259
- ? [
260
- {
261
- id: "continue",
262
- label:
263
- limit === null
264
- ? "Continue — Unlimited"
265
- : `Continue — up to ${limit} more responses`,
266
- action: "safety-resume" as const,
267
- },
268
- {
269
- id: "settings",
270
- label: "Change automatic-work limit…",
271
- action: "safety-settings" as const,
272
- },
273
- { id: "back", label: "Back", action: "back" as const },
274
- ]
275
- : [{ id: "back", label: "Back", action: "back" as const }],
276
- hint: "back",
277
- };
278
- },
279
- status: () => ({
280
- kind: "detail",
281
- title: "Goal status",
282
- lines: runtime.activeGoal
283
- ? goalSummary(
284
- runtime.activeGoal,
285
- runtime.settings.continuationLimits.automaticTurns,
286
- ).split("\n")
287
- : ["No goal is currently set."],
288
- hint: "back",
289
- }),
290
- help: () => ({
291
- kind: "detail",
292
- title: "Goal help",
293
- lines: goalHelp().split("\n").slice(1),
294
- hint: "back",
295
- }),
296
- },
297
- actions: {
298
- start: async () => {
299
- await startFromMenu(commands, ctx);
300
- return { kind: "close" };
301
- },
302
- "start-with-budget": async ({ itemId, signal }) => {
303
- const budget = parseTokenBudget(itemId);
304
- if (budget === undefined) return { kind: "rejected" };
305
- return startBudgetedGoal(
306
- commands,
307
- ctx,
308
- budget,
309
- runtime.settings.continuationLimits.automaticTurns,
310
- signal,
311
- isMenuCurrent,
312
- "stay",
313
- );
314
- },
315
- "start-with-custom-budget": async ({ value, signal }) => {
316
- const budget = parseTokenBudget(value ?? "");
317
- if (budget === undefined) {
318
- notifyTerminal(
319
- ctx.ui,
320
- "Enter a positive token amount, for example 25k, 300k, or 1.5m.",
321
- "warning",
322
- );
323
- return { kind: "rejected" };
324
- }
325
- return startBudgetedGoal(
326
- commands,
327
- ctx,
328
- budget,
329
- runtime.settings.continuationLimits.automaticTurns,
330
- signal,
331
- isMenuCurrent,
332
- "back",
333
- );
334
- },
335
- "submit-increase-budget": async ({ value, signal }) => {
336
- const goal = displayedBudgetGoal;
337
- const budget = parseTokenBudget(value ?? "");
338
- if (budget === undefined) {
339
- notifyTerminal(
340
- ctx.ui,
341
- "Enter a positive token amount, for example 300k, 1.5m, or 300000.",
342
- "warning",
343
- );
344
- return { kind: "rejected" };
345
- }
346
- if (
347
- !goal ||
348
- !requireCurrentBudgetPreview(
349
- runtime,
350
- goal,
351
- displayedBudgetValue,
352
- displayedBudgetUsage,
353
- displayedBudgetStatus,
354
- ctx,
355
- )
356
- ) {
357
- return { kind: "close" };
358
- }
359
- if (budget <= goal.tokensUsed) {
360
- notifyTerminal(
361
- ctx.ui,
362
- `Enter a new cumulative total greater than current usage (${formatCompactTokenCount(goal.tokensUsed)}).`,
363
- "warning",
364
- );
365
- return { kind: "rejected" };
366
- }
367
- const confirmed = await ctx.ui.confirm(
368
- "Increase goal budget?",
369
- increaseBudgetPreview(goal, budget, runtime.settings.continuationLimits.automaticTurns),
370
- );
371
- if (signal.aborted || !isMenuCurrent()) return { kind: "close" };
372
- if (!confirmed) return { kind: "rejected" };
373
- if (
374
- !requireCurrentBudgetPreview(
375
- runtime,
376
- goal,
377
- displayedBudgetValue,
378
- displayedBudgetUsage,
379
- displayedBudgetStatus,
380
- ctx,
381
- )
382
- ) {
383
- return { kind: "close" };
384
- }
385
- await commands.editGoal(goal.text, budget, ctx);
386
- return { kind: "close" };
387
- },
388
- pause: async () => {
389
- if (!displayedGoal || !requireCurrentMenuGoal(runtime, displayedGoal, ctx)) {
390
- return { kind: "stay" };
391
- }
392
- commands.pauseGoal(ctx);
393
- return { kind: "close" };
394
- },
395
- resume: async () => {
396
- if (!displayedGoal || !requireCurrentMenuGoal(runtime, displayedGoal, ctx)) {
397
- return { kind: "stay" };
398
- }
399
- await commands.resumeGoal(ctx);
400
- return { kind: "close" };
401
- },
402
- "safety-resume": async () => {
403
- if (!displayedGoal || !requireCurrentMenuGoal(runtime, displayedGoal, ctx)) {
404
- return { kind: "stay" };
405
- }
406
- await commands.resumeGoal(ctx);
407
- return { kind: "close" };
408
- },
409
- "safety-settings": async () => {
410
- if (!displayedGoal || !requireCurrentMenuGoal(runtime, displayedGoal, ctx)) {
411
- return { kind: "stay" };
412
- }
413
- const expectedGoal = displayedGoal;
414
- await showSettings(ctx, "automatic");
415
- if (!isMenuCurrent()) return { kind: "close" };
416
- if (!requireCurrentMenuGoal(runtime, expectedGoal, ctx)) return { kind: "stay" };
417
- return { kind: "stay" };
418
- },
419
- edit: async () => {
420
- if (!displayedGoal || !requireCurrentMenuGoal(runtime, displayedGoal, ctx)) {
421
- return { kind: "stay" };
422
- }
423
- await editFromMenu(runtime, commands, ctx);
424
- return { kind: "close" };
425
- },
426
- replace: async () => {
427
- await startFromMenu(commands, ctx);
428
- return { kind: "close" };
429
- },
430
- settings: async () => {
431
- await showSettings(ctx);
432
- return { kind: "stay" };
433
- },
434
- clear: async () => {
435
- const previewedGoal = runtime.activeGoal;
436
- if (!(await confirmClear(runtime, ctx))) return { kind: "stay" };
437
- if (previewedGoal && !requireCurrentMenuGoal(runtime, previewedGoal, ctx)) {
438
- return { kind: "stay" };
439
- }
440
- commands.clearGoal(ctx);
441
- return { kind: "close" };
442
- },
443
- back: async () => ({ kind: "back" }),
444
- },
445
- });
446
- await runMenu(ctx, menu, {
447
- getState: () => undefined,
448
- signal: ownerSignal,
449
- isCurrent: isMenuCurrent,
450
- });
133
+ if (ctx.mode !== "tui") {
134
+ commands.showGoal(ctx);
135
+ return;
136
+ }
137
+ const owner = runtime as GoalRuntime;
138
+ const generation = owner.menuGeneration;
139
+ const ownerSignal = owner.menuController?.signal;
140
+ const isMenuCurrent = () =>
141
+ owner.menuController === undefined || (generation === owner.menuGeneration && !owner.menuController.signal.aborted);
142
+ const { defineMenu, runMenu } = await import("@narumitw/pi-tui-kit");
143
+ if (!isMenuCurrent()) return;
144
+ let displayedGoal: ActiveGoal | undefined;
145
+ let displayedBudgetGoal: ActiveGoal | undefined;
146
+ let displayedBudgetValue: number | undefined;
147
+ let displayedBudgetUsage: number | undefined;
148
+ let displayedBudgetStatus: ActiveGoal["status"] | undefined;
149
+ const menu = defineMenu<undefined, GoalMenuScreen, GoalMenuAction, ExtensionCommandContext>({
150
+ start: "main",
151
+ screens: {
152
+ main: () => {
153
+ refreshGoalMenuState(runtime, ctx);
154
+ const state = buildGoalMenuState(runtime);
155
+ displayedGoal = runtime.activeGoal;
156
+ return {
157
+ kind: "actions",
158
+ title: "Goal",
159
+ lines: state.title.split("\n").slice(1),
160
+ items: state.actions.map(goalMainMenuItem),
161
+ hint: "close",
162
+ };
163
+ },
164
+ "start-budget": () => {
165
+ return {
166
+ kind: "actions",
167
+ title: "Choose token budget",
168
+ lines: tokenBudgetGuidance(runtime.settings.continuationLimits.automaticTurns),
169
+ items: [
170
+ {
171
+ id: "25k",
172
+ label: "25k — Lower token ceiling",
173
+ description: "Set the cumulative token limit to 25k.",
174
+ action: "start-with-budget",
175
+ },
176
+ {
177
+ id: "100k",
178
+ label: "100k — Suggested",
179
+ description: "Set the cumulative token limit to 100k.",
180
+ action: "start-with-budget",
181
+ },
182
+ {
183
+ id: "300k",
184
+ label: "300k — Higher token ceiling",
185
+ description: "Set the cumulative token limit to 300k.",
186
+ action: "start-with-budget",
187
+ },
188
+ {
189
+ id: "custom",
190
+ label: "Set a custom budget…",
191
+ description: "Enter an exact cumulative token limit.",
192
+ to: "start-custom-budget",
193
+ },
194
+ { id: "back", label: "Back", action: "back" },
195
+ ],
196
+ hint: "back",
197
+ };
198
+ },
199
+ "start-custom-budget": () => ({
200
+ kind: "input",
201
+ title: "Custom token budget",
202
+ lines: customTokenBudgetGuidance(runtime.settings.continuationLimits.automaticTurns),
203
+ placeholder: "100k",
204
+ action: "start-with-custom-budget",
205
+ hint: "back",
206
+ }),
207
+ "increase-budget": () => {
208
+ const goal = runtime.activeGoal;
209
+ displayedBudgetGoal = goal;
210
+ displayedBudgetValue = goal?.tokenBudget;
211
+ displayedBudgetUsage = goal?.tokensUsed;
212
+ displayedBudgetStatus = goal?.status;
213
+ if (goal && goal.tokensUsed >= Number.MAX_SAFE_INTEGER) {
214
+ return {
215
+ kind: "detail",
216
+ title: "Increase token budget unavailable",
217
+ lines: [
218
+ `Current usage: ${formatBudgetDecisionValue(goal.tokensUsed)}`,
219
+ "No larger safe whole-number token budget is available. Progress remains saved; choose Back and clear or replace the goal when ready.",
220
+ ],
221
+ hint: "back",
222
+ };
223
+ }
224
+ return {
225
+ kind: "input",
226
+ title: "Increase token budget",
227
+ lines: goal
228
+ ? increaseTokenBudgetGuidance(goal, runtime.settings.continuationLimits.automaticTurns)
229
+ : ["The budget-limited goal is no longer available. Return to the Goal menu."],
230
+ placeholder: goal ? suggestedIncreasedBudget(goal) : "300k",
231
+ action: "submit-increase-budget",
232
+ hint: "back",
233
+ };
234
+ },
235
+ safety: () => {
236
+ const goal = runtime.activeGoal;
237
+ displayedGoal = goal;
238
+ const limit = runtime.settings.continuationLimits.automaticTurns;
239
+ const used = goal?.automaticModelTurns ?? 0;
240
+ return {
241
+ kind: "actions",
242
+ title: "Automatic work paused",
243
+ lines: goal
244
+ ? [
245
+ automaticPauseSummary(used, limit),
246
+ `${safeGoalMenuText(goal.text)} is preserved.`,
247
+ `${formatInteger(goal.tokensUsed)} cumulative tokens and ${formatDuration(goal.timeUsedSeconds)} active time are preserved.`,
248
+ "The objective and usage are preserved.",
249
+ limit === null
250
+ ? "Continuing resets the counter to 0 and resumes with Unlimited automatic work."
251
+ : `Continuing resets the counter to 0 and allows up to ${limit} more automatic model responses.`,
252
+ ]
253
+ : ["The paused goal is no longer available. Return to the Goal menu."],
254
+ items: goal
255
+ ? [
256
+ {
257
+ id: "continue",
258
+ label: limit === null ? "Continue — Unlimited" : `Continue — up to ${limit} more responses`,
259
+ action: "safety-resume" as const,
260
+ },
261
+ {
262
+ id: "settings",
263
+ label: "Change automatic-work limit…",
264
+ action: "safety-settings" as const,
265
+ },
266
+ { id: "back", label: "Back", action: "back" as const },
267
+ ]
268
+ : [{ id: "back", label: "Back", action: "back" as const }],
269
+ hint: "back",
270
+ };
271
+ },
272
+ status: () => ({
273
+ kind: "detail",
274
+ title: "Goal status",
275
+ lines: runtime.activeGoal
276
+ ? goalSummary(runtime.activeGoal, runtime.settings.continuationLimits.automaticTurns).split("\n")
277
+ : ["No goal is currently set."],
278
+ hint: "back",
279
+ }),
280
+ help: () => ({
281
+ kind: "detail",
282
+ title: "Goal help",
283
+ lines: goalHelp().split("\n").slice(1),
284
+ hint: "back",
285
+ }),
286
+ },
287
+ actions: {
288
+ start: async () => {
289
+ await startFromMenu(commands, ctx);
290
+ return { kind: "close" };
291
+ },
292
+ "start-with-budget": async ({ itemId, signal }) => {
293
+ const budget = parseTokenBudget(itemId);
294
+ if (budget === undefined) return { kind: "rejected" };
295
+ return startBudgetedGoal(
296
+ commands,
297
+ ctx,
298
+ budget,
299
+ runtime.settings.continuationLimits.automaticTurns,
300
+ signal,
301
+ isMenuCurrent,
302
+ "stay",
303
+ );
304
+ },
305
+ "start-with-custom-budget": async ({ value, signal }) => {
306
+ const budget = parseTokenBudget(value ?? "");
307
+ if (budget === undefined) {
308
+ notifyTerminal(ctx.ui, "Enter a positive token amount, for example 25k, 300k, or 1.5m.", "warning");
309
+ return { kind: "rejected" };
310
+ }
311
+ return startBudgetedGoal(
312
+ commands,
313
+ ctx,
314
+ budget,
315
+ runtime.settings.continuationLimits.automaticTurns,
316
+ signal,
317
+ isMenuCurrent,
318
+ "back",
319
+ );
320
+ },
321
+ "submit-increase-budget": async ({ value, signal }) => {
322
+ const goal = displayedBudgetGoal;
323
+ const budget = parseTokenBudget(value ?? "");
324
+ if (budget === undefined) {
325
+ notifyTerminal(ctx.ui, "Enter a positive token amount, for example 300k, 1.5m, or 300000.", "warning");
326
+ return { kind: "rejected" };
327
+ }
328
+ if (
329
+ !goal ||
330
+ !requireCurrentBudgetPreview(
331
+ runtime,
332
+ goal,
333
+ displayedBudgetValue,
334
+ displayedBudgetUsage,
335
+ displayedBudgetStatus,
336
+ ctx,
337
+ )
338
+ ) {
339
+ return { kind: "close" };
340
+ }
341
+ if (budget <= goal.tokensUsed) {
342
+ notifyTerminal(
343
+ ctx.ui,
344
+ `Enter a new cumulative total greater than current usage (${formatCompactTokenCount(goal.tokensUsed)}).`,
345
+ "warning",
346
+ );
347
+ return { kind: "rejected" };
348
+ }
349
+ const confirmed = await ctx.ui.confirm(
350
+ "Increase goal budget?",
351
+ increaseBudgetPreview(goal, budget, runtime.settings.continuationLimits.automaticTurns),
352
+ );
353
+ if (signal.aborted || !isMenuCurrent()) return { kind: "close" };
354
+ if (!confirmed) return { kind: "rejected" };
355
+ if (
356
+ !requireCurrentBudgetPreview(
357
+ runtime,
358
+ goal,
359
+ displayedBudgetValue,
360
+ displayedBudgetUsage,
361
+ displayedBudgetStatus,
362
+ ctx,
363
+ )
364
+ ) {
365
+ return { kind: "close" };
366
+ }
367
+ await commands.editGoal(goal.text, budget, ctx);
368
+ return { kind: "close" };
369
+ },
370
+ pause: async () => {
371
+ if (!displayedGoal || !requireCurrentMenuGoal(runtime, displayedGoal, ctx)) {
372
+ return { kind: "stay" };
373
+ }
374
+ commands.pauseGoal(ctx);
375
+ return { kind: "close" };
376
+ },
377
+ resume: async () => {
378
+ if (!displayedGoal || !requireCurrentMenuGoal(runtime, displayedGoal, ctx)) {
379
+ return { kind: "stay" };
380
+ }
381
+ await commands.resumeGoal(ctx);
382
+ return { kind: "close" };
383
+ },
384
+ "safety-resume": async () => {
385
+ if (!displayedGoal || !requireCurrentMenuGoal(runtime, displayedGoal, ctx)) {
386
+ return { kind: "stay" };
387
+ }
388
+ await commands.resumeGoal(ctx);
389
+ return { kind: "close" };
390
+ },
391
+ "safety-settings": async () => {
392
+ if (!displayedGoal || !requireCurrentMenuGoal(runtime, displayedGoal, ctx)) {
393
+ return { kind: "stay" };
394
+ }
395
+ const expectedGoal = displayedGoal;
396
+ await showSettings(ctx, "automatic");
397
+ if (!isMenuCurrent()) return { kind: "close" };
398
+ if (!requireCurrentMenuGoal(runtime, expectedGoal, ctx)) return { kind: "stay" };
399
+ return { kind: "stay" };
400
+ },
401
+ edit: async () => {
402
+ if (!displayedGoal || !requireCurrentMenuGoal(runtime, displayedGoal, ctx)) {
403
+ return { kind: "stay" };
404
+ }
405
+ await editFromMenu(runtime, commands, ctx);
406
+ return { kind: "close" };
407
+ },
408
+ replace: async () => {
409
+ await startFromMenu(commands, ctx);
410
+ return { kind: "close" };
411
+ },
412
+ settings: async () => {
413
+ await showSettings(ctx);
414
+ return { kind: "stay" };
415
+ },
416
+ clear: async () => {
417
+ const previewedGoal = runtime.activeGoal;
418
+ if (!(await confirmClear(runtime, ctx))) return { kind: "stay" };
419
+ if (previewedGoal && !requireCurrentMenuGoal(runtime, previewedGoal, ctx)) {
420
+ return { kind: "stay" };
421
+ }
422
+ commands.clearGoal(ctx);
423
+ return { kind: "close" };
424
+ },
425
+ back: async () => ({ kind: "back" }),
426
+ },
427
+ });
428
+ await runMenu(ctx, menu, {
429
+ getState: () => undefined,
430
+ signal: ownerSignal,
431
+ isCurrent: isMenuCurrent,
432
+ });
451
433
  }
452
434
 
453
435
  function goalMainMenuItem(label: string): ActionMenuItem<GoalMenuScreen, GoalMenuAction> {
454
- if (label === GOAL_MENU_ACTIONS.status) return { id: "status", label, to: "status" as const };
455
- if (label === GOAL_MENU_ACTIONS.startBudget) {
456
- return { id: "start-budget", label, to: "start-budget" as const };
457
- }
458
- if (label === GOAL_MENU_ACTIONS.increaseBudget) {
459
- return { id: "increase-budget", label, to: "increase-budget" as const };
460
- }
461
- if (label === GOAL_MENU_ACTIONS.reviewSafety) {
462
- return { id: "review-safety", label, to: "safety" as const };
463
- }
464
- if (label === GOAL_MENU_ACTIONS.help) return { id: "help", label, to: "help" as const };
465
- if (label === GOAL_MENU_ACTIONS.close) return { id: "close", label, close: true as const };
466
- const actions = new Map<string, GoalMenuAction>([
467
- [GOAL_MENU_ACTIONS.start, "start"],
468
- [GOAL_MENU_ACTIONS.pause, "pause"],
469
- [GOAL_MENU_ACTIONS.resume, "resume"],
470
- [GOAL_MENU_ACTIONS.edit, "edit"],
471
- [GOAL_MENU_ACTIONS.replace, "replace"],
472
- [GOAL_MENU_ACTIONS.settings, "settings"],
473
- [GOAL_MENU_ACTIONS.clear, "clear"],
474
- ]);
475
- return { id: actions.get(label) ?? label, label, action: actions.get(label) ?? "settings" };
436
+ if (label === GOAL_MENU_ACTIONS.status) return { id: "status", label, to: "status" as const };
437
+ if (label === GOAL_MENU_ACTIONS.startBudget) {
438
+ return { id: "start-budget", label, to: "start-budget" as const };
439
+ }
440
+ if (label === GOAL_MENU_ACTIONS.increaseBudget) {
441
+ return { id: "increase-budget", label, to: "increase-budget" as const };
442
+ }
443
+ if (label === GOAL_MENU_ACTIONS.reviewSafety) {
444
+ return { id: "review-safety", label, to: "safety" as const };
445
+ }
446
+ if (label === GOAL_MENU_ACTIONS.help) return { id: "help", label, to: "help" as const };
447
+ if (label === GOAL_MENU_ACTIONS.close) return { id: "close", label, close: true as const };
448
+ const actions = new Map<string, GoalMenuAction>([
449
+ [GOAL_MENU_ACTIONS.start, "start"],
450
+ [GOAL_MENU_ACTIONS.pause, "pause"],
451
+ [GOAL_MENU_ACTIONS.resume, "resume"],
452
+ [GOAL_MENU_ACTIONS.edit, "edit"],
453
+ [GOAL_MENU_ACTIONS.replace, "replace"],
454
+ [GOAL_MENU_ACTIONS.settings, "settings"],
455
+ [GOAL_MENU_ACTIONS.clear, "clear"],
456
+ ]);
457
+ return { id: actions.get(label) ?? label, label, action: actions.get(label) ?? "settings" };
476
458
  }
477
459
 
478
460
  function refreshGoalMenuState(runtime: GoalMenuRuntimeView, ctx: ExtensionCommandContext) {
479
- const goal = runtime.activeGoal;
480
- if (!goal) return;
481
- runtime.recordGoalUsage?.(goal, ctx);
482
- runtime.persistGoal?.(goal);
483
- runtime.updateStatus?.(ctx, goal);
461
+ const goal = runtime.activeGoal;
462
+ if (!goal) return;
463
+ runtime.recordGoalUsage?.(goal, ctx);
464
+ runtime.persistGoal?.(goal);
465
+ runtime.updateStatus?.(ctx, goal);
484
466
  }
485
467
 
486
468
  async function startFromMenu(commands: GoalCommandController, ctx: ExtensionCommandContext) {
487
- const objective = (await ctx.ui.editor("Goal objective", ""))?.trim();
488
- if (!objective) return;
489
- await commands.startGoal(objective, undefined, ctx);
469
+ const objective = (await ctx.ui.editor("Goal objective", ""))?.trim();
470
+ if (!objective) return;
471
+ await commands.startGoal(objective, undefined, ctx);
490
472
  }
491
473
 
492
474
  async function startBudgetedGoal(
493
- commands: GoalCommandController,
494
- ctx: ExtensionCommandContext,
495
- budget: number,
496
- automaticLimit: number | null,
497
- signal: AbortSignal,
498
- isMenuCurrent: () => boolean,
499
- cancelTransition: "stay" | "back",
475
+ commands: GoalCommandController,
476
+ ctx: ExtensionCommandContext,
477
+ budget: number,
478
+ automaticLimit: number | null,
479
+ signal: AbortSignal,
480
+ isMenuCurrent: () => boolean,
481
+ cancelTransition: "stay" | "back",
500
482
  ) {
501
- const objective = (
502
- await ctx.ui.editor(
503
- `Goal objective · Token budget ${formatCompactTokenCount(budget)} · ${automaticLimit === null ? "Automatic Unlimited" : `Automatic limit ${automaticLimit}`}`,
504
- "",
505
- )
506
- )?.trim();
507
- if (signal.aborted || !isMenuCurrent()) return { kind: "close" as const };
508
- if (!objective) return { kind: cancelTransition } as const;
509
- await commands.startGoal(
510
- objective,
511
- budget,
512
- ctx,
513
- undefined,
514
- () => !signal.aborted && isMenuCurrent(),
515
- () => !signal.aborted && isMenuCurrent(),
516
- );
517
- return { kind: "close" as const };
483
+ const objective = (
484
+ await ctx.ui.editor(
485
+ `Goal objective · Token budget ${formatCompactTokenCount(budget)} · ${automaticLimit === null ? "Automatic Unlimited" : `Automatic limit ${automaticLimit}`}`,
486
+ "",
487
+ )
488
+ )?.trim();
489
+ if (signal.aborted || !isMenuCurrent()) return { kind: "close" as const };
490
+ if (!objective) return { kind: cancelTransition } as const;
491
+ await commands.startGoal(
492
+ objective,
493
+ budget,
494
+ ctx,
495
+ undefined,
496
+ () => !signal.aborted && isMenuCurrent(),
497
+ () => !signal.aborted && isMenuCurrent(),
498
+ );
499
+ return { kind: "close" as const };
518
500
  }
519
501
 
520
502
  function tokenBudgetGuidance(automaticLimit: number | null) {
521
- return [
522
- "Set the maximum cumulative token usage for this goal.",
523
- "The final model call may exceed the limit; this is not a dollar-cost cap.",
524
- automaticBudgetGuidance(automaticLimit),
525
- ];
503
+ return [
504
+ "Set the maximum cumulative token usage for this goal.",
505
+ "The final model call may exceed the limit; this is not a dollar-cost cap.",
506
+ automaticBudgetGuidance(automaticLimit),
507
+ ];
526
508
  }
527
509
 
528
510
  function customTokenBudgetGuidance(automaticLimit: number | null) {
529
- return [
530
- "Enter the maximum cumulative token usage for this goal.",
531
- "Examples: 25k, 300k, 1.5m, or 300000.",
532
- "The final model call may exceed this value; this is not a dollar-cost cap.",
533
- automaticBudgetGuidance(automaticLimit),
534
- ];
511
+ return [
512
+ "Enter the maximum cumulative token usage for this goal.",
513
+ "Examples: 25k, 300k, 1.5m, or 300000.",
514
+ "The final model call may exceed this value; this is not a dollar-cost cap.",
515
+ automaticBudgetGuidance(automaticLimit),
516
+ ];
535
517
  }
536
518
 
537
519
  function automaticBudgetGuidance(automaticLimit: number | null) {
538
- return automaticLimit === null
539
- ? "Automatic work has no response-count cap."
540
- : `Automatic work will also pause after ${automaticLimit} responses.`;
520
+ return automaticLimit === null
521
+ ? "Automatic work has no response-count cap."
522
+ : `Automatic work will also pause after ${automaticLimit} responses.`;
541
523
  }
542
524
 
543
525
  function increaseTokenBudgetGuidance(goal: ActiveGoal, automaticLimit: number | null) {
544
- return [
545
- `Current budget: ${formatBudgetDecisionValue(goal.tokenBudget ?? 0)}`,
546
- `Current usage: ${formatBudgetDecisionValue(goal.tokensUsed)}`,
547
- `Enter a new cumulative total greater than ${formatBudgetDecisionValue(goal.tokensUsed)}.`,
548
- "Examples: 300k, 1.5m, or 300000.",
549
- "The final model call may exceed the limit; this is not a dollar-cost cap.",
550
- automaticBudgetGuidance(automaticLimit),
551
- ];
526
+ return [
527
+ `Current budget: ${formatBudgetDecisionValue(goal.tokenBudget ?? 0)}`,
528
+ `Current usage: ${formatBudgetDecisionValue(goal.tokensUsed)}`,
529
+ `Enter a new cumulative total greater than ${formatBudgetDecisionValue(goal.tokensUsed)}.`,
530
+ "Examples: 300k, 1.5m, or 300000.",
531
+ "The final model call may exceed the limit; this is not a dollar-cost cap.",
532
+ automaticBudgetGuidance(automaticLimit),
533
+ ];
552
534
  }
553
535
 
554
536
  function suggestedIncreasedBudget(goal: ActiveGoal) {
555
- const floor = Math.max(goal.tokensUsed, goal.tokenBudget ?? 0);
556
- for (const suggestion of [25_000, 100_000, 300_000, 500_000, 1_000_000]) {
557
- if (suggestion > floor) return formatCompactTokenCount(suggestion);
558
- }
559
- return formatCompactTokenCount(
560
- Math.min(Number.MAX_SAFE_INTEGER, Math.max(Math.floor(floor) + 1, Math.ceil(floor * 2))),
561
- );
537
+ const floor = Math.max(goal.tokensUsed, goal.tokenBudget ?? 0);
538
+ for (const suggestion of [25_000, 100_000, 300_000, 500_000, 1_000_000]) {
539
+ if (suggestion > floor) return formatCompactTokenCount(suggestion);
540
+ }
541
+ return formatCompactTokenCount(
542
+ Math.min(Number.MAX_SAFE_INTEGER, Math.max(Math.floor(floor) + 1, Math.ceil(floor * 2))),
543
+ );
562
544
  }
563
545
 
564
546
  function formatBudgetDecisionValue(value: number) {
565
- const compact = formatCompactTokenCount(value);
566
- if (value < 1_000 || value % 1_000 === 0) return compact;
567
- return `${compact} (${formatInteger(value)} tokens)`;
547
+ const compact = formatCompactTokenCount(value);
548
+ if (value < 1_000 || value % 1_000 === 0) return compact;
549
+ return `${compact} (${formatInteger(value)} tokens)`;
568
550
  }
569
551
 
570
552
  function increaseBudgetPreview(goal: ActiveGoal, budget: number, automaticLimit: number | null) {
571
- return [
572
- `Goal: ${safeGoalMenuText(goal.text, 4_000)}`,
573
- `Budget: ${formatCompactTokenCount(goal.tokenBudget ?? 0)} → ${formatCompactTokenCount(budget)}`,
574
- `Current usage: ${formatCompactTokenCount(goal.tokensUsed)}`,
575
- automaticLimit === null
576
- ? "Automatic work: Unlimited after resume"
577
- : `Automatic work: up to ${automaticLimit} more responses after resume`,
578
- "The goal will resume immediately.",
579
- ].join("\n");
553
+ return [
554
+ `Goal: ${safeGoalMenuText(goal.text, 4_000)}`,
555
+ `Budget: ${formatCompactTokenCount(goal.tokenBudget ?? 0)} → ${formatCompactTokenCount(budget)}`,
556
+ `Current usage: ${formatCompactTokenCount(goal.tokensUsed)}`,
557
+ automaticLimit === null
558
+ ? "Automatic work: Unlimited after resume"
559
+ : `Automatic work: up to ${automaticLimit} more responses after resume`,
560
+ "The goal will resume immediately.",
561
+ ].join("\n");
580
562
  }
581
563
 
582
564
  async function editFromMenu(
583
- runtime: GoalMenuRuntimeView,
584
- commands: GoalCommandController,
585
- ctx: ExtensionCommandContext,
565
+ runtime: GoalMenuRuntimeView,
566
+ commands: GoalCommandController,
567
+ ctx: ExtensionCommandContext,
586
568
  ) {
587
- const goal = runtime.activeGoal;
588
- if (!goal) return;
589
- const objective = (await ctx.ui.editor("Edit goal objective", goal.text))?.trim();
590
- if (!objective || objective === goal.text) return;
591
- if (!requireCurrentMenuGoal(runtime, goal, ctx)) return;
592
- if (goal.status === "active") {
593
- const confirmed = await ctx.ui.confirm(
594
- "Apply goal edit?",
595
- `Current goal:\n${safeGoalMenuText(goal.text, 4_000)}\n\nUpdated goal:\n${safeGoalMenuText(objective, 4_000)}\n\nApplying this edit starts a new guarded goal instance.`,
596
- );
597
- if (!confirmed || !requireCurrentMenuGoal(runtime, goal, ctx)) return;
598
- }
599
- await commands.editGoal(objective, undefined, ctx);
569
+ const goal = runtime.activeGoal;
570
+ if (!goal) return;
571
+ const objective = (await ctx.ui.editor("Edit goal objective", goal.text))?.trim();
572
+ if (!objective || objective === goal.text) return;
573
+ if (!requireCurrentMenuGoal(runtime, goal, ctx)) return;
574
+ if (goal.status === "active") {
575
+ const confirmed = await ctx.ui.confirm(
576
+ "Apply goal edit?",
577
+ `Current goal:\n${safeGoalMenuText(goal.text, 4_000)}\n\nUpdated goal:\n${safeGoalMenuText(objective, 4_000)}\n\nApplying this edit starts a new guarded goal instance.`,
578
+ );
579
+ if (!confirmed || !requireCurrentMenuGoal(runtime, goal, ctx)) return;
580
+ }
581
+ await commands.editGoal(objective, undefined, ctx);
600
582
  }
601
583
 
602
584
  async function confirmClear(runtime: GoalMenuRuntimeView, ctx: ExtensionCommandContext) {
603
- const goal = runtime.activeGoal;
604
- if (!goal) return false;
605
- return ctx.ui.confirm(
606
- "Clear goal?",
607
- `Remove this goal:\n\n${safeGoalMenuText(goal.text, 4_000)}\n\nThis cannot be undone.`,
608
- );
585
+ const goal = runtime.activeGoal;
586
+ if (!goal) return false;
587
+ return ctx.ui.confirm(
588
+ "Clear goal?",
589
+ `Remove this goal:\n\n${safeGoalMenuText(goal.text, 4_000)}\n\nThis cannot be undone.`,
590
+ );
609
591
  }
610
592
 
611
593
  function requireCurrentBudgetPreview(
612
- runtime: GoalMenuRuntimeView,
613
- expectedGoal: ActiveGoal,
614
- expectedBudget: number | undefined,
615
- expectedUsage: number | undefined,
616
- expectedStatus: ActiveGoal["status"] | undefined,
617
- ctx: ExtensionCommandContext,
594
+ runtime: GoalMenuRuntimeView,
595
+ expectedGoal: ActiveGoal,
596
+ expectedBudget: number | undefined,
597
+ expectedUsage: number | undefined,
598
+ expectedStatus: ActiveGoal["status"] | undefined,
599
+ ctx: ExtensionCommandContext,
618
600
  ) {
619
- const current = runtime.activeGoal;
620
- if (
621
- current?.id === expectedGoal.id &&
622
- current.tokenBudget === expectedBudget &&
623
- current.tokensUsed === expectedUsage &&
624
- current.status === expectedStatus
625
- ) {
626
- return true;
627
- }
628
- notifyTerminal(
629
- ctx.ui,
630
- "The goal changed or its usage changed while the budget dialog was open. Reopen /goal and try again.",
631
- "warning",
632
- );
633
- return false;
601
+ const current = runtime.activeGoal;
602
+ if (
603
+ current?.id === expectedGoal.id &&
604
+ current.tokenBudget === expectedBudget &&
605
+ current.tokensUsed === expectedUsage &&
606
+ current.status === expectedStatus
607
+ ) {
608
+ return true;
609
+ }
610
+ notifyTerminal(
611
+ ctx.ui,
612
+ "The goal changed or its usage changed while the budget dialog was open. Reopen /goal and try again.",
613
+ "warning",
614
+ );
615
+ return false;
634
616
  }
635
617
 
636
- function requireCurrentMenuGoal(
637
- runtime: GoalMenuRuntimeView,
638
- expected: ActiveGoal,
639
- ctx: ExtensionCommandContext,
640
- ) {
641
- if (runtime.activeGoal?.id === expected.id) return true;
642
- notifyTerminal(
643
- ctx.ui,
644
- "The active goal changed while the dialog was open. Reopen /goal and try again.",
645
- "warning",
646
- );
647
- return false;
618
+ function requireCurrentMenuGoal(runtime: GoalMenuRuntimeView, expected: ActiveGoal, ctx: ExtensionCommandContext) {
619
+ if (runtime.activeGoal?.id === expected.id) return true;
620
+ notifyTerminal(ctx.ui, "The active goal changed while the dialog was open. Reopen /goal and try again.", "warning");
621
+ return false;
648
622
  }
649
623
 
650
624
  function displayStatus(status?: ActiveGoal["status"]) {
651
- if (!status) return "No goal";
652
- if (status === "usage_limited") return "Usage limited";
653
- if (status === "budget_limited") return "Budget limited";
654
- return status[0]?.toUpperCase() + status.slice(1);
625
+ if (!status) return "No goal";
626
+ if (status === "usage_limited") return "Usage limited";
627
+ if (status === "budget_limited") return "Budget limited";
628
+ return status[0]?.toUpperCase() + status.slice(1);
655
629
  }
656
630
 
657
631
  function formatTokenCount(tokens: number) {
658
- return String(tokens);
632
+ return String(tokens);
659
633
  }
660
634
 
661
635
  function formatInteger(value: number) {
662
- return value.toLocaleString("en-US", { maximumFractionDigits: 0 });
636
+ return value.toLocaleString("en-US", { maximumFractionDigits: 0 });
663
637
  }
664
638
 
665
639
  function automaticPauseSummary(used: number, limit: number | null) {
666
- if (limit === null) {
667
- return `Goal paused after ${used} responses at its previous safety limit. Current limit: Unlimited.`;
668
- }
669
- if (used < limit) {
670
- return `Goal paused after ${used} responses at its previous safety limit. Current automatic-work limit: ${limit}.`;
671
- }
672
- return `Goal reached its ${used}-of-${limit} safety limit.`;
640
+ if (limit === null) {
641
+ return `Goal paused after ${used} responses at its previous safety limit. Current limit: Unlimited.`;
642
+ }
643
+ if (used < limit) {
644
+ return `Goal paused after ${used} responses at its previous safety limit. Current automatic-work limit: ${limit}.`;
645
+ }
646
+ return `Goal reached its ${used}-of-${limit} safety limit.`;
673
647
  }
674
648
 
675
649
  function goalHelp() {
676
- return [
677
- "Goal menu",
678
- "Use the menu for guided status, edits, settings, and confirmations.",
679
- "Direct routes remain available for deterministic workflows:",
680
- "/goal <objective>",
681
- "/goal status | pause | resume | edit | clear",
682
- "/goal --tokens 100k <objective>",
683
- "Escape cancels the current menu or input without changing goal state.",
684
- ].join("\n");
650
+ return [
651
+ "Goal menu",
652
+ "Use the menu for guided status, edits, settings, and confirmations.",
653
+ "Direct routes remain available for deterministic workflows:",
654
+ "/goal <objective>",
655
+ "/goal status | pause | resume | edit | clear",
656
+ "/goal --tokens 100k <objective>",
657
+ "Escape cancels the current menu or input without changing goal state.",
658
+ ].join("\n");
685
659
  }