@narumitw/pi-goal 0.49.5 → 0.49.7

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/src/menu.ts CHANGED
@@ -3,6 +3,10 @@ import type { ActionMenuItem } from "@narumitw/pi-tui-kit";
3
3
  import { formatTokenCount as formatCompactTokenCount, formatDuration } from "./accounting.js";
4
4
  import { parseTokenBudget } from "./command.js";
5
5
  import type { GoalCommandController } from "./commands.js";
6
+ import { notifyTerminal, safeGoalMenuText } from "./errors.js";
7
+
8
+ export { safeGoalMenuText } from "./errors.js";
9
+
6
10
  import type { ActiveGoal, PendingQueueAction } from "./persistence.js";
7
11
  import { goalQueueIdentity } from "./queue.js";
8
12
  import { type GoalRuntime, goalSummary } from "./runtime.js";
@@ -389,7 +393,8 @@ export async function showGoalManager(
389
393
  "start-with-custom-budget": async ({ value, signal }) => {
390
394
  const budget = parseTokenBudget(value ?? "");
391
395
  if (budget === undefined) {
392
- ctx.ui.notify(
396
+ notifyTerminal(
397
+ ctx.ui,
393
398
  "Enter a positive token amount, for example 25k, 300k, or 1.5m.",
394
399
  "warning",
395
400
  );
@@ -411,7 +416,8 @@ export async function showGoalManager(
411
416
  const goal = displayedBudgetGoal;
412
417
  const budget = parseTokenBudget(value ?? "");
413
418
  if (budget === undefined) {
414
- ctx.ui.notify(
419
+ notifyTerminal(
420
+ ctx.ui,
415
421
  "Enter a positive token amount, for example 300k, 1.5m, or 300000.",
416
422
  "warning",
417
423
  );
@@ -431,7 +437,8 @@ export async function showGoalManager(
431
437
  return { kind: "close" };
432
438
  }
433
439
  if (budget <= goal.tokensUsed) {
434
- ctx.ui.notify(
440
+ notifyTerminal(
441
+ ctx.ui,
435
442
  `Enter a new cumulative total greater than current usage (${formatCompactTokenCount(goal.tokensUsed)}).`,
436
443
  "warning",
437
444
  );
@@ -515,7 +522,8 @@ export async function showGoalManager(
515
522
  goalQueueIdentity(runtime.activeGoal, runtime.queuedGoals, runtime.pendingQueueAction) !==
516
523
  previewedQueue
517
524
  ) {
518
- ctx.ui.notify(
525
+ notifyTerminal(
526
+ ctx.ui,
519
527
  "The goal queue changed while the dialog was open. Reopen /goal and try again.",
520
528
  "warning",
521
529
  );
@@ -618,18 +626,6 @@ function refreshGoalMenuState(runtime: GoalMenuRuntimeView, ctx: ExtensionComman
618
626
  runtime.updateStatus?.(ctx, goal);
619
627
  }
620
628
 
621
- export function safeGoalMenuText(value: string, maxCharacters = 120) {
622
- const sanitized = [...value]
623
- .map((character) => (isTerminalControl(character) ? " " : character))
624
- .join("")
625
- .replace(/\s+/gu, " ")
626
- .trim();
627
- const characters = [...sanitized];
628
- return characters.length <= maxCharacters
629
- ? sanitized
630
- : `${characters.slice(0, maxCharacters).join("")}…`;
631
- }
632
-
633
629
  async function startFromMenu(commands: GoalCommandController, ctx: ExtensionCommandContext) {
634
630
  const objective = (await ctx.ui.editor("Goal objective", ""))?.trim();
635
631
  if (!objective) return;
@@ -787,7 +783,8 @@ function requireCurrentStartBudgetQueue(
787
783
  if (currentGoalQueueIdentity(runtime) === expectedIdentity) {
788
784
  return true;
789
785
  }
790
- ctx.ui.notify(
786
+ notifyTerminal(
787
+ ctx.ui,
791
788
  "The goal queue changed while the token budget flow was open. Reopen /goal and try again.",
792
789
  "warning",
793
790
  );
@@ -811,7 +808,8 @@ function requireCurrentBudgetPreview(
811
808
  ) {
812
809
  return true;
813
810
  }
814
- ctx.ui.notify(
811
+ notifyTerminal(
812
+ ctx.ui,
815
813
  "The goal changed or its usage changed while the budget dialog was open. Reopen /goal and try again.",
816
814
  "warning",
817
815
  );
@@ -824,7 +822,8 @@ function requireCurrentQueueHead(
824
822
  ctx: ExtensionCommandContext,
825
823
  ) {
826
824
  if (runtime.activeGoal?.id === expectedGoal.id) return true;
827
- ctx.ui.notify(
825
+ notifyTerminal(
826
+ ctx.ui,
828
827
  "The goal queue changed while the dialog was open. Reopen /goal and try again.",
829
828
  "warning",
830
829
  );
@@ -848,7 +847,8 @@ function requireCurrentQueueSelection(
848
847
  ) {
849
848
  return true;
850
849
  }
851
- ctx.ui.notify(
850
+ notifyTerminal(
851
+ ctx.ui,
852
852
  "The goal queue changed while the dialog was open. Reopen /goal and try again.",
853
853
  "warning",
854
854
  );
@@ -861,7 +861,8 @@ function requireCurrentMenuGoal(
861
861
  ctx: ExtensionCommandContext,
862
862
  ) {
863
863
  if (runtime.activeGoal?.id === expected.id) return true;
864
- ctx.ui.notify(
864
+ notifyTerminal(
865
+ ctx.ui,
865
866
  "The active goal changed while the dialog was open. Reopen /goal and try again.",
866
867
  "warning",
867
868
  );
@@ -893,11 +894,6 @@ function automaticPauseSummary(used: number, limit: number | null) {
893
894
  return `Goal reached its ${used}-of-${limit} safety limit.`;
894
895
  }
895
896
 
896
- function isTerminalControl(character: string) {
897
- const codePoint = character.codePointAt(0) ?? 0;
898
- return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);
899
- }
900
-
901
897
  function goalHelp() {
902
898
  return [
903
899
  "Goal menu",
package/src/runtime.ts CHANGED
@@ -6,7 +6,7 @@ import {
6
6
  formatTokenCount,
7
7
  updateGoalUsage,
8
8
  } from "./accounting.js";
9
- import { formatError, truncateNotification } from "./errors.js";
9
+ import { formatError, notifyTerminal, truncateNotification } from "./errors.js";
10
10
  import {
11
11
  appendGoalPromptMarker,
12
12
  extractContinuationMarker,
@@ -111,6 +111,7 @@ export interface StatusContext {
111
111
 
112
112
  export const STATUS_KEY = "goal";
113
113
  export const GOAL_STATE_ENTRY_TYPE = "goal-state";
114
+ export const MAX_GOAL_ID_LENGTH = 128;
114
115
 
115
116
  /** Canonical Goal state passed to the in-process managed-run publisher. */
116
117
  export type GoalStateSnapshotStatus = GoalStatus | "cleared";
@@ -204,6 +205,7 @@ export class GoalRuntime {
204
205
  queueFrozen = false;
205
206
  queueFreezeAwaitingSettle = false;
206
207
  completionStatusTimer?: NodeJS.Timeout;
208
+ private continuationDispatchTimer?: NodeJS.Timeout;
207
209
  continuationIntent?: ContinuationTicket;
208
210
  continuationDelivery?: ContinuationTicket;
209
211
  goalRecovery?: GoalRecovery;
@@ -361,6 +363,7 @@ export class GoalRuntime {
361
363
  }
362
364
  if (ctx.isIdle?.() !== true || hasPendingMessages(ctx)) return false;
363
365
 
366
+ this.clearContinuationDispatchTimer();
364
367
  this.continuationIntent = undefined;
365
368
  this.continuationDelivery = intent;
366
369
  try {
@@ -373,7 +376,7 @@ export class GoalRuntime {
373
376
  if (this.activeGoal?.id === intent.goalId && this.activeGoal.status === "active") {
374
377
  this.continuationIntent = intent;
375
378
  }
376
- ctx.ui.notify(`Goal prompt failed: ${formatError(error)}`, "error");
379
+ notifyTerminal(ctx.ui, `Goal prompt failed: ${formatError(error)}`, "error");
377
380
  return false;
378
381
  }
379
382
  }
@@ -557,7 +560,7 @@ export class GoalRuntime {
557
560
  return true;
558
561
  } catch (error) {
559
562
  this.budgetWrapUp.delivered = false;
560
- ctx.ui.notify(`Goal budget wrap-up failed: ${formatError(error)}`, "error");
563
+ notifyTerminal(ctx.ui, `Goal budget wrap-up failed: ${formatError(error)}`, "error");
561
564
  return false;
562
565
  }
563
566
  }
@@ -578,7 +581,7 @@ export class GoalRuntime {
578
581
  reason: `token budget reached (${formatBudget(goal)})`,
579
582
  });
580
583
  if (!stoppedGoal) return false;
581
- ctx.ui.notify(`Goal token budget reached: ${formatBudget(stoppedGoal)}`, "warning");
584
+ notifyTerminal(ctx.ui, `Goal token budget reached: ${formatBudget(stoppedGoal)}`, "warning");
582
585
  if (sendWrapUp) this.queueBudgetWrapUp(ctx, stoppedGoal);
583
586
  return true;
584
587
  }
@@ -650,7 +653,8 @@ export class GoalRuntime {
650
653
  reason: `${cause} (${count}; ${formatTokenCount(goal.tokensUsed)} tokens)`,
651
654
  });
652
655
  if (!stoppedGoal) return false;
653
- ctx.ui.notify(
656
+ notifyTerminal(
657
+ ctx.ui,
654
658
  cause === "continuation_limit"
655
659
  ? `Automatic-work limit reached: ${stoppedGoal.automaticModelTurns} of ${automaticLimit} responses. Goal progress is saved with ${formatTokenCount(stoppedGoal.tokensUsed)} cumulative tokens. Open /goal to review and continue.`
656
660
  : `Goal paused: ${count}; ${formatTokenCount(stoppedGoal.tokensUsed)} cumulative tokens. Open /goal to review and continue.`,
@@ -682,7 +686,8 @@ export class GoalRuntime {
682
686
  reason: `agent error after retries${details}`,
683
687
  });
684
688
  if (!stoppedGoal) return false;
685
- ctx.ui.notify(
689
+ notifyTerminal(
690
+ ctx.ui,
686
691
  `Goal blocked after agent error retries were exhausted${details}. Resolve the blocker or run /goal resume to retry.`,
687
692
  "warning",
688
693
  );
@@ -712,6 +717,7 @@ export class GoalRuntime {
712
717
  }
713
718
 
714
719
  clearContinuationTracking() {
720
+ this.clearContinuationDispatchTimer();
715
721
  this.continuationIntent = undefined;
716
722
  this.continuationDelivery = undefined;
717
723
  this.cancelledContinuationMarkers.clear();
@@ -741,6 +747,7 @@ export class GoalRuntime {
741
747
  }
742
748
 
743
749
  cancelContinuationWork() {
750
+ this.clearContinuationDispatchTimer();
744
751
  if (this.continuationDelivery) {
745
752
  this.rememberCancelledContinuationMarker(this.continuationDelivery.marker);
746
753
  }
@@ -748,6 +755,28 @@ export class GoalRuntime {
748
755
  this.continuationDelivery = undefined;
749
756
  }
750
757
 
758
+ scheduleContinuationDispatch(ctx: StatusContext, goalId: string) {
759
+ this.clearContinuationDispatchTimer();
760
+ const generation = this.menuGeneration;
761
+ this.continuationDispatchTimer = setTimeout(() => {
762
+ this.continuationDispatchTimer = undefined;
763
+ if (
764
+ generation !== this.menuGeneration ||
765
+ this.activeGoal?.id !== goalId ||
766
+ this.activeGoal.status !== "active"
767
+ ) {
768
+ return;
769
+ }
770
+ this.dispatchContinuationIfSettled(ctx);
771
+ }, 0);
772
+ }
773
+
774
+ private clearContinuationDispatchTimer() {
775
+ if (!this.continuationDispatchTimer) return;
776
+ clearTimeout(this.continuationDispatchTimer);
777
+ this.continuationDispatchTimer = undefined;
778
+ }
779
+
751
780
  consumeCancelledContinuationPrompt(prompt: string) {
752
781
  const marker = extractContinuationMarker(prompt);
753
782
  return marker ? this.cancelledContinuationMarkers.delete(marker) : false;
@@ -957,7 +986,8 @@ export class GoalRuntime {
957
986
  recordUsage,
958
987
  });
959
988
  if (!stoppedGoal) return false;
960
- ctx.ui.notify(
989
+ notifyTerminal(
990
+ ctx.ui,
961
991
  "Goal tools are unavailable, so the active goal was paused. Restore the tools and run /goal resume.",
962
992
  "warning",
963
993
  );
@@ -1194,6 +1224,7 @@ export function isContradictoryCompletionSummary(summary: string) {
1194
1224
 
1195
1225
  export function goalIdRejectionReason(goal: ActiveGoal, requestedGoalId: string) {
1196
1226
  if (!requestedGoalId) return "missing goal_id";
1227
+ if (requestedGoalId.length > MAX_GOAL_ID_LENGTH) return "goal_id is too long";
1197
1228
  if (requestedGoalId !== goal.id) return "goal_id does not match the active goal";
1198
1229
  return undefined;
1199
1230
  }
@@ -1213,7 +1244,7 @@ async function sendPrompt(
1213
1244
  return true;
1214
1245
  } catch (error) {
1215
1246
  if (!isCurrent || isCurrent()) {
1216
- ctx.ui.notify(`Goal prompt failed: ${formatError(error)}`, "error");
1247
+ notifyTerminal(ctx.ui, `Goal prompt failed: ${formatError(error)}`, "error");
1217
1248
  }
1218
1249
  return false;
1219
1250
  }
@@ -1,6 +1,7 @@
1
1
  import { join } from "node:path";
2
2
  import { type ExtensionCommandContext, getAgentDir } from "@earendil-works/pi-coding-agent";
3
3
  import { checkpointGoalActiveTime } from "./accounting.js";
4
+ import { notifyTerminal, safeTerminalText } from "./errors.js";
4
5
  import { abortCurrentTurn, type GoalRuntime, STATUS_KEY } from "./runtime.js";
5
6
  import {
6
7
  DEFAULT_GOAL_SETTINGS,
@@ -29,7 +30,11 @@ export async function showGoalSettings(
29
30
  ) {
30
31
  const settingsPath = options.settingsPath ?? join(getAgentDir(), GOAL_SETTINGS_FILE);
31
32
  if (ctx.mode !== "tui") {
32
- ctx.ui.notify(`Edit pi-goal settings manually: ${safeTerminalText(settingsPath)}`, "info");
33
+ notifyTerminal(
34
+ ctx.ui,
35
+ `Edit pi-goal settings manually: ${safeTerminalText(settingsPath)}`,
36
+ "info",
37
+ );
33
38
  return;
34
39
  }
35
40
  const generation = runtime.menuGeneration;
@@ -159,7 +164,7 @@ export async function showGoalSettings(
159
164
  applyGoalSettings(runtime, next, ctx, {
160
165
  save: (settings) => (options.save ?? saveGoalSettings)(settings, settingsPath),
161
166
  });
162
- ctx.ui.notify(`Goal tools: ${value}.`, "info");
167
+ notifyTerminal(ctx.ui, `Goal tools: ${value}.`, "info");
163
168
  return { kind: "stay" };
164
169
  } catch (error) {
165
170
  notifySettingsFailure(ctx, settingsPath, error);
@@ -180,13 +185,18 @@ export async function showGoalSettings(
180
185
  try {
181
186
  await options.onQueueUnfrozen?.(ctx);
182
187
  } catch (error) {
183
- ctx.ui.notify(
188
+ notifyTerminal(
189
+ ctx.ui,
184
190
  `Goal queue enabled, but automatic resume failed: ${safeTerminalText(formatError(error))}. Reopen /goal to retry.`,
185
191
  "warning",
186
192
  );
187
193
  }
188
194
  }
189
- ctx.ui.notify(`Ordered goal queue: ${enabled ? "Experimental" : "Off"}.`, "info");
195
+ notifyTerminal(
196
+ ctx.ui,
197
+ `Ordered goal queue: ${enabled ? "Experimental" : "Off"}.`,
198
+ "info",
199
+ );
190
200
  return { kind: "stay" };
191
201
  } catch (error) {
192
202
  notifySettingsFailure(ctx, settingsPath, error);
@@ -204,7 +214,7 @@ export async function showGoalSettings(
204
214
  applyGoalSettings(runtime, next, ctx, {
205
215
  save: (settings) => (options.save ?? saveGoalSettings)(settings, settingsPath),
206
216
  });
207
- ctx.ui.notify(`Managed run RPC: ${enabled ? "On" : "Off"}.`, "info");
217
+ notifyTerminal(ctx.ui, `Managed run RPC: ${enabled ? "On" : "Off"}.`, "info");
208
218
  return { kind: "stay" };
209
219
  } catch (error) {
210
220
  notifySettingsFailure(ctx, settingsPath, error);
@@ -310,7 +320,8 @@ async function applyLimitChoice(
310
320
  ) {
311
321
  if (!isCurrent() || !isLimitSelection(itemId)) return { kind: "rejected" as const };
312
322
  if ((runtime.activeGoal?.id ?? null) !== activeGoalId) {
313
- ctx.ui.notify(
323
+ notifyTerminal(
324
+ ctx.ui,
314
325
  "The active goal changed while the safety setting was open. No settings were changed.",
315
326
  "warning",
316
327
  );
@@ -321,7 +332,8 @@ async function applyLimitChoice(
321
332
  if (!isCurrent()) return { kind: "rejected" as const };
322
333
  if (limit === undefined || limit === previous) return { kind: "back" as const };
323
334
  if ((runtime.activeGoal?.id ?? null) !== activeGoalId) {
324
- ctx.ui.notify(
335
+ notifyTerminal(
336
+ ctx.ui,
325
337
  "The active goal changed while editing the safety setting. No settings were changed.",
326
338
  "warning",
327
339
  );
@@ -330,7 +342,8 @@ async function applyLimitChoice(
330
342
  const confirmation = await confirmLowerActiveLimit(runtime, ctx, field, limit);
331
343
  if (!isCurrent() || !confirmation.apply) return { kind: "rejected" as const };
332
344
  if (confirmation.goalId !== undefined && runtime.activeGoal?.id !== confirmation.goalId) {
333
- ctx.ui.notify(
345
+ notifyTerminal(
346
+ ctx.ui,
334
347
  "The active goal changed while confirming the limit. No settings were changed.",
335
348
  "warning",
336
349
  );
@@ -340,7 +353,7 @@ async function applyLimitChoice(
340
353
  applyGoalSettings(runtime, withLimit(runtime.settings, field, limit), ctx, {
341
354
  save: (settings) => (options.save ?? saveGoalSettings)(settings, settingsPath),
342
355
  });
343
- ctx.ui.notify(formatLimitSuccess(field, limit), "info");
356
+ notifyTerminal(ctx.ui, formatLimitSuccess(field, limit), "info");
344
357
  return { kind: "back" as const };
345
358
  } catch (error) {
346
359
  notifySettingsFailure(ctx, settingsPath, error);
@@ -442,7 +455,8 @@ async function resolveLimitSelection(
442
455
  if (!isCurrent() || raw === undefined) return undefined;
443
456
  const parsed = parseGoalLimit(raw);
444
457
  if (parsed !== undefined) return parsed;
445
- ctx.ui.notify(
458
+ notifyTerminal(
459
+ ctx.ui,
446
460
  `Enter a whole number greater than 0. Choose ${field === "automaticTurns" ? "Unlimited" : "Off"} from the previous screen if you do not want a limit.`,
447
461
  "warning",
448
462
  );
@@ -607,7 +621,8 @@ function retainedGoalCount(runtime: GoalRuntime) {
607
621
  function notifySettingsFailure(ctx: ExtensionCommandContext, settingsPath: string, error: unknown) {
608
622
  const path = safeTerminalText(settingsPath);
609
623
  const detail = safeTerminalText(formatError(error));
610
- ctx.ui.notify(
624
+ notifyTerminal(
625
+ ctx.ui,
611
626
  error instanceof AggregateError
612
627
  ? `Could not apply Goal settings, and rollback was incomplete. Check ${path}, run /reload, and verify the effective settings before retrying: ${detail}`
613
628
  : `Could not save Goal settings; the previous value remains. Check ${path} and retry: ${detail}`,
@@ -615,16 +630,6 @@ function notifySettingsFailure(ctx: ExtensionCommandContext, settingsPath: strin
615
630
  );
616
631
  }
617
632
 
618
- function safeTerminalText(value: string) {
619
- return [...value]
620
- .map((character) => {
621
- const codePoint = character.codePointAt(0) ?? 0;
622
- return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? " " : character;
623
- })
624
- .join("")
625
- .trim();
626
- }
627
-
628
633
  function formatError(error: unknown) {
629
634
  return error instanceof Error ? error.message : String(error);
630
635
  }