@narumitw/pi-goal 0.49.3 → 0.49.6

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 CHANGED
@@ -52,7 +52,7 @@ pi -e npm:@narumitw/pi-goal
52
52
  Try this package locally from the repository root:
53
53
 
54
54
  ```bash
55
- pi -e ./extensions/pi-goal
55
+ pi -e ./packages/pi-goal
56
56
  ```
57
57
 
58
58
  ## ⚙️ Configuration
@@ -310,7 +310,7 @@ This breaking contract replaces and removes `pi-goal:rpc:start`, `pi-goal:rpc:pa
310
310
  ## 🗂️ Package layout
311
311
 
312
312
  ```txt
313
- extensions/pi-goal/
313
+ packages/pi-goal/
314
314
  ├── src/
315
315
  │ ├── index.ts # Pi package entrypoint
316
316
  │ ├── goal.ts # Order-explicit extension composition root
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-goal",
3
- "version": "0.49.3",
3
+ "version": "0.49.6",
4
4
  "description": "Pi extension for autonomous /goal completion with opt-in experimental ordered queues.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -23,6 +23,9 @@
23
23
  "./src/index.ts"
24
24
  ]
25
25
  },
26
+ "piExtension": {
27
+ "lifecycle": "stable"
28
+ },
26
29
  "scripts": {
27
30
  "check": "biome check . && npm run typecheck",
28
31
  "format": "biome check --write .",
@@ -37,9 +40,10 @@
37
40
  },
38
41
  "devDependencies": {
39
42
  "@biomejs/biome": "2.5.7",
40
- "@earendil-works/pi-ai": "0.83.0",
41
- "@earendil-works/pi-coding-agent": "0.83.0",
42
- "typebox": "1.3.10",
43
+ "@earendil-works/pi-ai": "0.84.1",
44
+ "@earendil-works/pi-coding-agent": "0.84.1",
45
+ "@earendil-works/pi-tui": "0.84.1",
46
+ "typebox": "1.3.11",
43
47
  "typescript": "7.0.2"
44
48
  },
45
49
  "dependencies": {
@@ -48,6 +52,6 @@
48
52
  "repository": {
49
53
  "type": "git",
50
54
  "url": "https://github.com/narumiruna/pi-extensions",
51
- "directory": "extensions/pi-goal"
55
+ "directory": "packages/pi-goal"
52
56
  }
53
57
  }
@@ -1,6 +1,7 @@
1
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
1
+ import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
2
  import { completeGoalArguments, parseCommand } from "./command.js";
3
3
  import type { GoalCommandController } from "./commands.js";
4
+ import { notifyTerminal, safeTerminalText } from "./errors.js";
4
5
  import { showGoalManager } from "./menu.js";
5
6
  import type { GoalRuntime } from "./runtime.js";
6
7
  import { showGoalSettings } from "./settings-ui.js";
@@ -26,7 +27,7 @@ export function registerGoalCommand(
26
27
  experimentalGoals: runtime.settings.experimental.goals,
27
28
  });
28
29
  if (typeof result === "string") {
29
- ctx.ui.notify(result, "warning");
30
+ reportCommandError(result, ctx);
30
31
  return;
31
32
  }
32
33
  if (result.kind === "show" && args.trim() === "") {
@@ -48,7 +49,8 @@ export function registerGoalCommand(
48
49
  return;
49
50
  }
50
51
  if (runtime.pendingQueueAction && result.kind !== "show" && result.kind !== "clear") {
51
- ctx.ui.notify(
52
+ notifyTerminal(
53
+ ctx.ui,
52
54
  "A queued goal change is waiting for Pi to settle. Retry after it finishes.",
53
55
  "warning",
54
56
  );
@@ -90,3 +92,9 @@ export function registerGoalCommand(
90
92
  },
91
93
  });
92
94
  }
95
+
96
+ function reportCommandError(message: string, ctx: ExtensionCommandContext) {
97
+ const safeMessage = safeTerminalText(message);
98
+ if (ctx.mode === "print" || ctx.mode === "json") throw new Error(safeMessage);
99
+ notifyTerminal(ctx.ui, safeMessage, "warning");
100
+ }
package/src/commands.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { checkpointGoalActiveTime, currentTokenTotal, formatTokenCount } from "./accounting.js";
2
2
  import { validateObjective } from "./command.js";
3
+ import { notifyTerminal } from "./errors.js";
3
4
  import { safeGoalMenuText } from "./menu.js";
4
5
  import type { ActiveGoal } from "./persistence.js";
5
6
  import { buildGoalPrompt, buildObjectiveUpdatedPrompt, buildResumePrompt } from "./prompts.js";
@@ -50,7 +51,7 @@ export class GoalCommandController {
50
51
  if (isRequestCurrent && !isRequestCurrent()) return;
51
52
  const validationError = validateObjective(objective);
52
53
  if (validationError) {
53
- ctx.ui.notify(validationError, "warning");
54
+ notifyTerminal(ctx.ui, validationError, "warning");
54
55
  return;
55
56
  }
56
57
 
@@ -74,7 +75,7 @@ export class GoalCommandController {
74
75
  `Current goal: ${safeGoalMenuText(existingGoal.text, 4_000)}${queuedRemovalPreview}\n\nNew goal: ${safeGoalMenuText(objective, 4_000)}`,
75
76
  );
76
77
  if (!shouldReplace) {
77
- ctx.ui.notify(`Goal kept: ${existingGoal.text}`, "info");
78
+ notifyTerminal(ctx.ui, `Goal kept: ${existingGoal.text}`, "info");
78
79
  return;
79
80
  }
80
81
  if (isRequestCurrent && !isRequestCurrent()) return;
@@ -85,7 +86,11 @@ export class GoalCommandController {
85
86
  this.runtime.pendingQueueAction,
86
87
  ) !== existingQueueIdentity
87
88
  ) {
88
- ctx.ui.notify("The goal queue changed while confirmation was open. Try again.", "warning");
89
+ notifyTerminal(
90
+ ctx.ui,
91
+ "The goal queue changed while confirmation was open. Try again.",
92
+ "warning",
93
+ );
89
94
  return;
90
95
  }
91
96
  }
@@ -97,7 +102,7 @@ export class GoalCommandController {
97
102
  try {
98
103
  this.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);
99
104
  } catch (error) {
100
- ctx.ui.notify(`Cannot start /goal: ${formatError(error)}`, "error");
105
+ notifyTerminal(ctx.ui, `Cannot start /goal: ${formatError(error)}`, "error");
101
106
  if (existingGoal?.status === "active") this.runtime.pauseGoalForUnavailableTools(ctx);
102
107
  return;
103
108
  }
@@ -167,7 +172,8 @@ export class GoalCommandController {
167
172
  return;
168
173
  }
169
174
  const automaticLimit = this.runtime.settings.continuationLimits.automaticTurns;
170
- ctx.ui.notify(
175
+ notifyTerminal(
176
+ ctx.ui,
171
177
  `${existingGoal ? "Goal replaced" : "Goal started"}: ${objective}. ${
172
178
  startedGoal.tokenBudget === undefined
173
179
  ? ""
@@ -184,7 +190,7 @@ export class GoalCommandController {
184
190
  async addGoal(objective: string, tokenBudget: number | undefined, ctx: StatusContext) {
185
191
  const validationError = validateObjective(objective);
186
192
  if (validationError) {
187
- ctx.ui.notify(validationError, "warning");
193
+ notifyTerminal(ctx.ui, validationError, "warning");
188
194
  return;
189
195
  }
190
196
  if (!this.runtime.activeGoal) {
@@ -196,7 +202,8 @@ export class GoalCommandController {
196
202
  createQueuedGoal(objective, tokenBudget),
197
203
  );
198
204
  this.runtime.persistGoal(this.runtime.activeGoal);
199
- ctx.ui.notify(
205
+ notifyTerminal(
206
+ ctx.ui,
200
207
  `Goal added at position ${this.runtime.queuedGoals.length + 1}: ${objective}`,
201
208
  "info",
202
209
  );
@@ -205,7 +212,7 @@ export class GoalCommandController {
205
212
  async prioritizeGoal(objective: string, tokenBudget: number | undefined, ctx: StatusContext) {
206
213
  const validationError = validateObjective(objective);
207
214
  if (validationError) {
208
- ctx.ui.notify(validationError, "warning");
215
+ notifyTerminal(ctx.ui, validationError, "warning");
209
216
  return;
210
217
  }
211
218
  if (!this.runtime.activeGoal) {
@@ -216,7 +223,7 @@ export class GoalCommandController {
216
223
  this.runtime.pendingQueueAction = { kind: "prioritize", objective, tokenBudget };
217
224
  this.runtime.persistGoal(this.runtime.activeGoal);
218
225
  if (ctx.isIdle?.() !== true || hasPendingMessages(ctx)) {
219
- ctx.ui.notify(`Priority goal queued until Pi settles: ${objective}`, "info");
226
+ notifyTerminal(ctx.ui, `Priority goal queued until Pi settles: ${objective}`, "info");
220
227
  return;
221
228
  }
222
229
  await this.dispatchPendingQueueActionIfSettled(ctx);
@@ -225,29 +232,33 @@ export class GoalCommandController {
225
232
  dropLastGoal(ctx: StatusContext) {
226
233
  const currentGoal = this.runtime.activeGoal;
227
234
  if (!currentGoal) {
228
- ctx.ui.notify("No goals to drop.", "info");
235
+ notifyTerminal(ctx.ui, "No goals to drop.", "info");
229
236
  return;
230
237
  }
231
238
  const result = dropLastQueuedGoal(currentGoal, this.runtime.queuedGoals);
232
239
  if (!result.goal) {
233
240
  this.runtime.clearActiveGoal(ctx);
234
- ctx.ui.notify(`Goal dropped: ${result.removed?.text ?? currentGoal.text}`, "warning");
241
+ notifyTerminal(
242
+ ctx.ui,
243
+ `Goal dropped: ${result.removed?.text ?? currentGoal.text}`,
244
+ "warning",
245
+ );
235
246
  return;
236
247
  }
237
248
  this.runtime.queuedGoals = result.queue;
238
249
  this.runtime.persistGoal(result.goal);
239
- ctx.ui.notify(`Goal dropped: ${result.removed?.text ?? "unknown goal"}`, "warning");
250
+ notifyTerminal(ctx.ui, `Goal dropped: ${result.removed?.text ?? "unknown goal"}`, "warning");
240
251
  }
241
252
 
242
253
  async skipGoal(ctx: StatusContext) {
243
254
  const currentGoal = this.runtime.activeGoal;
244
255
  if (!currentGoal) {
245
- ctx.ui.notify("No goals to skip.", "info");
256
+ notifyTerminal(ctx.ui, "No goals to skip.", "info");
246
257
  return;
247
258
  }
248
259
  if (this.runtime.queuedGoals.length === 0) {
249
260
  this.runtime.clearActiveGoal(ctx);
250
- ctx.ui.notify(`Goal skipped: ${currentGoal.text}. No goals remain.`, "warning");
261
+ notifyTerminal(ctx.ui, `Goal skipped: ${currentGoal.text}. No goals remain.`, "warning");
251
262
  return;
252
263
  }
253
264
  if (currentGoal.status === "active") this.runtime.recordGoalUsage(currentGoal, ctx);
@@ -262,7 +273,7 @@ export class GoalCommandController {
262
273
  completedText: currentGoal.text,
263
274
  };
264
275
  this.runtime.persistGoal(currentGoal);
265
- ctx.ui.notify(`Goal skip queued until Pi settles: ${currentGoal.text}`, "info");
276
+ notifyTerminal(ctx.ui, `Goal skip queued until Pi settles: ${currentGoal.text}`, "info");
266
277
  if (ctx.isIdle?.() === true && !hasPendingMessages(ctx)) {
267
278
  await this.dispatchPendingQueueActionIfSettled(ctx);
268
279
  }
@@ -334,7 +345,8 @@ export class GoalCommandController {
334
345
  : undefined;
335
346
  if (!this.runtime.activeGoal) {
336
347
  this.runtime.clearActiveGoal(ctx);
337
- ctx.ui.notify(
348
+ notifyTerminal(
349
+ ctx.ui,
338
350
  reason === "complete"
339
351
  ? `Goal complete: ${previousText}. No goals remain.`
340
352
  : `Goal skipped: ${previousText}. No goals remain.`,
@@ -349,7 +361,8 @@ export class GoalCommandController {
349
361
  if (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {
350
362
  this.runtime.blockStaleGoalToolCalls();
351
363
  }
352
- ctx.ui.notify(
364
+ notifyTerminal(
365
+ ctx.ui,
353
366
  `${reason === "complete" ? "Goal complete" : "Goal skipped"}: ${previousText}. Next goal remains ${this.runtime.activeGoal.status}: ${this.runtime.activeGoal.text}`,
354
367
  "info",
355
368
  );
@@ -365,7 +378,7 @@ export class GoalCommandController {
365
378
  restoreGoal: this.runtime.activeGoal,
366
379
  abortTurn: false,
367
380
  });
368
- ctx.ui.notify(`Cannot start the next /goal: ${formatError(error)}`, "error");
381
+ notifyTerminal(ctx.ui, `Cannot start the next /goal: ${formatError(error)}`, "error");
369
382
  return false;
370
383
  }
371
384
  const activatedGoal = this.runtime.activeGoal;
@@ -382,13 +395,15 @@ export class GoalCommandController {
382
395
  restoreGoal: activatedGoal,
383
396
  abortTurn: false,
384
397
  });
385
- ctx.ui.notify(
398
+ notifyTerminal(
399
+ ctx.ui,
386
400
  `Next goal paused after prompt delivery failed: ${activatedGoal.text}`,
387
401
  "warning",
388
402
  );
389
403
  return false;
390
404
  }
391
- ctx.ui.notify(
405
+ notifyTerminal(
406
+ ctx.ui,
392
407
  `${reason === "complete" ? "Goal complete" : "Goal skipped"}: ${previousText}. Started next goal: ${activatedGoal.text}`,
393
408
  "info",
394
409
  );
@@ -396,7 +411,8 @@ export class GoalCommandController {
396
411
  }
397
412
 
398
413
  notifyFrozenQueue(ctx: StatusContext) {
399
- ctx.ui.notify(
414
+ notifyTerminal(
415
+ ctx.ui,
400
416
  "The experimental goal queue is frozen. Re-enable experimental.goals in pi-goal.json and run /reload, or use /goal clear.",
401
417
  "warning",
402
418
  );
@@ -404,11 +420,12 @@ export class GoalCommandController {
404
420
 
405
421
  pauseGoal(ctx: StatusContext) {
406
422
  if (!this.runtime.activeGoal) {
407
- ctx.ui.notify("No active goal.", "info");
423
+ notifyTerminal(ctx.ui, "No active goal.", "info");
408
424
  return;
409
425
  }
410
426
  if (this.runtime.activeGoal.status !== "active") {
411
- ctx.ui.notify(
427
+ notifyTerminal(
428
+ ctx.ui,
412
429
  `Goal is ${this.runtime.activeGoal.status}; only active goals can be paused.`,
413
430
  "warning",
414
431
  );
@@ -418,16 +435,17 @@ export class GoalCommandController {
418
435
  kind: "explicit_pause",
419
436
  expectedGoalId: this.runtime.activeGoal.id,
420
437
  });
421
- if (stoppedGoal) ctx.ui.notify(`Goal paused: ${stoppedGoal.text}`, "info");
438
+ if (stoppedGoal) notifyTerminal(ctx.ui, `Goal paused: ${stoppedGoal.text}`, "info");
422
439
  }
423
440
 
424
441
  async resumeGoal(ctx: StatusContext) {
425
442
  if (!this.runtime.activeGoal) {
426
- ctx.ui.notify("No active goal.", "info");
443
+ notifyTerminal(ctx.ui, "No active goal.", "info");
427
444
  return;
428
445
  }
429
446
  if (!isResumableGoalStatus(this.runtime.activeGoal.status)) {
430
- ctx.ui.notify(
447
+ notifyTerminal(
448
+ ctx.ui,
431
449
  `Goal is ${this.runtime.activeGoal.status}; only paused, blocked, usage-limited, or budget-limited goals can be resumed.`,
432
450
  "warning",
433
451
  );
@@ -437,7 +455,8 @@ export class GoalCommandController {
437
455
  this.runtime.activeGoal.tokenBudget !== undefined &&
438
456
  this.runtime.activeGoal.tokensUsed >= this.runtime.activeGoal.tokenBudget
439
457
  ) {
440
- ctx.ui.notify(
458
+ notifyTerminal(
459
+ ctx.ui,
441
460
  `Goal token budget is still reached: ${formatBudget(this.runtime.activeGoal)}`,
442
461
  "warning",
443
462
  );
@@ -447,7 +466,7 @@ export class GoalCommandController {
447
466
  try {
448
467
  this.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);
449
468
  } catch (error) {
450
- ctx.ui.notify(`Cannot resume /goal: ${formatError(error)}`, "error");
469
+ notifyTerminal(ctx.ui, `Cannot resume /goal: ${formatError(error)}`, "error");
451
470
  return;
452
471
  }
453
472
  const stoppedGoal = this.runtime.activeGoal;
@@ -462,7 +481,8 @@ export class GoalCommandController {
462
481
  this.runtime.persistGoal(this.runtime.activeGoal);
463
482
  this.runtime.updateStatus(ctx, this.runtime.activeGoal);
464
483
  if (this.runtime.activeGoal.status !== "active") {
465
- ctx.ui.notify(
484
+ notifyTerminal(
485
+ ctx.ui,
466
486
  `Goal token budget is still reached: ${formatBudget(this.runtime.activeGoal)}`,
467
487
  "warning",
468
488
  );
@@ -490,7 +510,8 @@ export class GoalCommandController {
490
510
  return;
491
511
  }
492
512
  const automaticLimit = this.runtime.settings.continuationLimits.automaticTurns;
493
- ctx.ui.notify(
513
+ notifyTerminal(
514
+ ctx.ui,
494
515
  `Goal resumed from ${stoppedStatusLabel(stoppedStatus)}: ${resumedGoal.text}. ${
495
516
  automaticLimit === null
496
517
  ? "Automatic work remains Unlimited; goal progress and cumulative usage are preserved."
@@ -502,7 +523,7 @@ export class GoalCommandController {
502
523
 
503
524
  clearGoal(ctx: StatusContext) {
504
525
  if (!this.runtime.activeGoal) {
505
- ctx.ui.notify("No active goal.", "info");
526
+ notifyTerminal(ctx.ui, "No active goal.", "info");
506
527
  this.runtime.cancelContinuationWork();
507
528
  this.runtime.clearGoalRecovery();
508
529
  this.runtime.clearBudgetWrapUp();
@@ -514,17 +535,17 @@ export class GoalCommandController {
514
535
 
515
536
  const stoppedGoal = this.runtime.activeGoal.text;
516
537
  this.runtime.clearActiveGoal(ctx);
517
- ctx.ui.notify(`Goal cleared: ${stoppedGoal}`, "warning");
538
+ notifyTerminal(ctx.ui, `Goal cleared: ${stoppedGoal}`, "warning");
518
539
  }
519
540
 
520
541
  async editGoal(objective: string, tokenBudget: number | undefined, ctx: StatusContext) {
521
542
  const validationError = validateObjective(objective);
522
543
  if (validationError) {
523
- ctx.ui.notify(validationError, "warning");
544
+ notifyTerminal(ctx.ui, validationError, "warning");
524
545
  return;
525
546
  }
526
547
  if (!this.runtime.activeGoal) {
527
- ctx.ui.notify("No active goal. Use /goal <objective> to start one.", "warning");
548
+ notifyTerminal(ctx.ui, "No active goal. Use /goal <objective> to start one.", "warning");
528
549
  return;
529
550
  }
530
551
 
@@ -553,7 +574,7 @@ export class GoalCommandController {
553
574
  try {
554
575
  this.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);
555
576
  } catch (error) {
556
- ctx.ui.notify(`Cannot reactivate /goal: ${formatError(error)}`, "error");
577
+ notifyTerminal(ctx.ui, `Cannot reactivate /goal: ${formatError(error)}`, "error");
557
578
  if (this.runtime.activeGoal?.status === "active") {
558
579
  this.runtime.pauseGoalForUnavailableTools(ctx);
559
580
  }
@@ -602,7 +623,7 @@ export class GoalCommandController {
602
623
  } else {
603
624
  this.runtime.clearStaleGoalToolCallBlock();
604
625
  }
605
- ctx.ui.notify(`Goal updated: ${objective}`, "info");
626
+ notifyTerminal(ctx.ui, `Goal updated: ${objective}`, "info");
606
627
  }
607
628
 
608
629
  showGoal(ctx: StatusContext) {
@@ -636,7 +657,7 @@ export class GoalCommandController {
636
657
  `/goal status is unavailable in ${ctx.mode} mode because Pi does not expose an extension-command output channel. Use TUI or RPC mode.`,
637
658
  );
638
659
  }
639
- ctx.ui.notify(message, "info");
660
+ notifyTerminal(ctx.ui, message, "info");
640
661
  }
641
662
 
642
663
  private async activatePrioritizedGoal(
@@ -659,7 +680,7 @@ export class GoalCommandController {
659
680
  try {
660
681
  this.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);
661
682
  } catch (error) {
662
- ctx.ui.notify(`Cannot prioritize /goal: ${formatError(error)}`, "error");
683
+ notifyTerminal(ctx.ui, `Cannot prioritize /goal: ${formatError(error)}`, "error");
663
684
  if (currentGoal.status === "complete") {
664
685
  // Completion already committed, so retain the priority intent for a
665
686
  // later /reload after the tool policy is restored.
@@ -725,7 +746,7 @@ export class GoalCommandController {
725
746
  this.runtime.toolPolicy.restore(visibilityBeforeActivation);
726
747
  return false;
727
748
  }
728
- ctx.ui.notify(`Goal prioritized: ${objective}`, "info");
749
+ notifyTerminal(ctx.ui, `Goal prioritized: ${objective}`, "info");
729
750
  return true;
730
751
  }
731
752
  }
package/src/errors.ts CHANGED
@@ -4,6 +4,7 @@ import {
4
4
  type AssistantMessage as PiAssistantMessage,
5
5
  type Usage,
6
6
  } from "@earendil-works/pi-ai";
7
+ import { stripTerminalSequences } from "@earendil-works/pi-tui";
7
8
  import { assistantUsageTokens, nonNegativeFiniteNumber } from "./accounting.js";
8
9
 
9
10
  export type AgentStopReason = "stop" | "length" | "toolUse" | "error" | "aborted";
@@ -36,12 +37,32 @@ const RETRYABLE_GOAL_ERROR_PATTERNS = [
36
37
  /context[_\s-]*length[_\s-]*exceeded|input exceeds the context window/i,
37
38
  ] as const;
38
39
 
40
+ export function safeTerminalText(value: string) {
41
+ return [...stripTerminalSequences(value)]
42
+ .map((character) => {
43
+ const codePoint = character.codePointAt(0) ?? 0;
44
+ if (character === "\n") return character;
45
+ return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? " " : character;
46
+ })
47
+ .join("")
48
+ .trim();
49
+ }
50
+
51
+ export function notifyTerminal(
52
+ ui: { notify: (message: string, level?: "info" | "warning" | "error") => void },
53
+ message: string,
54
+ level?: "info" | "warning" | "error",
55
+ ) {
56
+ ui.notify(safeTerminalText(message), level);
57
+ }
58
+
39
59
  export function formatError(error: unknown) {
40
60
  return truncateNotification(error instanceof Error ? error.message : String(error));
41
61
  }
42
62
 
43
63
  export function truncateNotification(value: string) {
44
- return value.length > 160 ? `${value.slice(0, 157)}...` : value;
64
+ const safe = [...safeTerminalText(value)];
65
+ return safe.length > 160 ? `${safe.slice(0, 157).join("")}...` : safe.join("");
45
66
  }
46
67
 
47
68
  export function isUsageLimitedGoalInterruption(assistant: AssistantMessageLike) {
package/src/lifecycle.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { currentTokenTotal } from "./accounting.js";
3
3
  import type { GoalCommandController } from "./commands.js";
4
+ import { notifyTerminal } from "./errors.js";
4
5
  import { type ActiveGoal, loadGoalStateFromSession } from "./persistence.js";
5
6
  import { buildGoalPrompt, buildGoalSystemPrompt } from "./prompts.js";
6
7
  import { activateQueuedGoal } from "./queue.js";
@@ -59,13 +60,14 @@ export function registerGoalLifecycle(
59
60
  settingsResult.kind === "loaded" ? settingsResult.settings : DEFAULT_GOAL_SETTINGS;
60
61
  runtime.settingsLoadIssue = settingsResult.kind === "invalid" ? settingsResult : undefined;
61
62
  if (settingsResult.kind === "invalid") {
62
- ctx.ui.notify(
63
+ notifyTerminal(
64
+ ctx.ui,
63
65
  `pi-goal settings ignored: ${settingsResult.reason}. Using default settings.`,
64
66
  "warning",
65
67
  );
66
68
  }
67
69
  if (runtime.settings.experimental.goals) {
68
- ctx.ui.notify(EXPERIMENTAL_GOALS_WARNING, "warning");
70
+ notifyTerminal(ctx.ui, EXPERIMENTAL_GOALS_WARNING, "warning");
69
71
  }
70
72
  try {
71
73
  runtime.toolPolicy.prepareSessionStart(
@@ -73,7 +75,11 @@ export function registerGoalLifecycle(
73
75
  previousToolVisibility,
74
76
  );
75
77
  } catch (error) {
76
- ctx.ui.notify(`Could not restore always-visible goal tools: ${formatError(error)}`, "error");
78
+ notifyTerminal(
79
+ ctx.ui,
80
+ `Could not restore always-visible goal tools: ${formatError(error)}`,
81
+ "error",
82
+ );
77
83
  }
78
84
 
79
85
  const loaded = loadGoalStateFromSession(ctx);
@@ -85,7 +91,8 @@ export function registerGoalLifecycle(
85
91
  if (runtime.queueFrozen) {
86
92
  if (runtime.activeGoal) runtime.persistGoal(runtime.activeGoal);
87
93
  ctx.ui.setStatus(STATUS_KEY, "queue off");
88
- ctx.ui.notify(
94
+ notifyTerminal(
95
+ ctx.ui,
89
96
  "An experimental goal queue is frozen because experimental.goals is disabled. Re-enable it and run /reload to continue, or use /goal clear.",
90
97
  "warning",
91
98
  );
@@ -213,10 +220,11 @@ export function registerGoalLifecycle(
213
220
  if (wasPiRetry) return;
214
221
  runtime.clearGoalRecoveryForGoal(runtime.activeGoal.id);
215
222
  runtime.requestContinuation(runtime.activeGoal);
216
- // Manual compaction does not emit agent_settled. This common dispatcher is
217
- // therefore the narrow fallback; threshold compaction leaves the intent for
218
- // agent_settled when Pi is still busy.
219
- runtime.dispatchContinuationIfSettled(ctx);
223
+ // Pi emits session_compact before it clears its manual-compaction controller,
224
+ // so sendUserMessage still rejects inside this hook even when ctx reports idle.
225
+ // Defer one task; threshold compaction retains the intent for agent_settled
226
+ // when Pi is still busy.
227
+ runtime.scheduleContinuationDispatch(ctx, runtime.activeGoal.id);
220
228
  });
221
229
 
222
230
  pi.on("input", (event, ctx) => {
@@ -641,20 +649,23 @@ export function registerGoalLifecycle(
641
649
  ? ` (${truncateNotification(assistant.errorMessage)})`
642
650
  : "";
643
651
  if (status === "paused") {
644
- ctx.ui.notify(
652
+ notifyTerminal(
653
+ ctx.ui,
645
654
  `Goal paused after interruption${details}. Run /goal resume to continue.`,
646
655
  "warning",
647
656
  );
648
657
  return;
649
658
  }
650
659
  if (status === "usage_limited") {
651
- ctx.ui.notify(
660
+ notifyTerminal(
661
+ ctx.ui,
652
662
  `Goal stopped after provider usage limit${details}. Run /goal resume when usage is available.`,
653
663
  "warning",
654
664
  );
655
665
  return;
656
666
  }
657
- ctx.ui.notify(
667
+ notifyTerminal(
668
+ ctx.ui,
658
669
  `Goal blocked after agent error${details}. Resolve the blocker or run /goal resume to retry.`,
659
670
  "warning",
660
671
  );
package/src/menu.ts CHANGED
@@ -3,6 +3,7 @@ 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, safeTerminalText } from "./errors.js";
6
7
  import type { ActiveGoal, PendingQueueAction } from "./persistence.js";
7
8
  import { goalQueueIdentity } from "./queue.js";
8
9
  import { type GoalRuntime, goalSummary } from "./runtime.js";
@@ -389,7 +390,8 @@ export async function showGoalManager(
389
390
  "start-with-custom-budget": async ({ value, signal }) => {
390
391
  const budget = parseTokenBudget(value ?? "");
391
392
  if (budget === undefined) {
392
- ctx.ui.notify(
393
+ notifyTerminal(
394
+ ctx.ui,
393
395
  "Enter a positive token amount, for example 25k, 300k, or 1.5m.",
394
396
  "warning",
395
397
  );
@@ -411,7 +413,8 @@ export async function showGoalManager(
411
413
  const goal = displayedBudgetGoal;
412
414
  const budget = parseTokenBudget(value ?? "");
413
415
  if (budget === undefined) {
414
- ctx.ui.notify(
416
+ notifyTerminal(
417
+ ctx.ui,
415
418
  "Enter a positive token amount, for example 300k, 1.5m, or 300000.",
416
419
  "warning",
417
420
  );
@@ -431,7 +434,8 @@ export async function showGoalManager(
431
434
  return { kind: "close" };
432
435
  }
433
436
  if (budget <= goal.tokensUsed) {
434
- ctx.ui.notify(
437
+ notifyTerminal(
438
+ ctx.ui,
435
439
  `Enter a new cumulative total greater than current usage (${formatCompactTokenCount(goal.tokensUsed)}).`,
436
440
  "warning",
437
441
  );
@@ -515,7 +519,8 @@ export async function showGoalManager(
515
519
  goalQueueIdentity(runtime.activeGoal, runtime.queuedGoals, runtime.pendingQueueAction) !==
516
520
  previewedQueue
517
521
  ) {
518
- ctx.ui.notify(
522
+ notifyTerminal(
523
+ ctx.ui,
519
524
  "The goal queue changed while the dialog was open. Reopen /goal and try again.",
520
525
  "warning",
521
526
  );
@@ -619,11 +624,7 @@ function refreshGoalMenuState(runtime: GoalMenuRuntimeView, ctx: ExtensionComman
619
624
  }
620
625
 
621
626
  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 sanitized = safeTerminalText(value).replace(/\s+/gu, " ").trim();
627
628
  const characters = [...sanitized];
628
629
  return characters.length <= maxCharacters
629
630
  ? sanitized
@@ -787,7 +788,8 @@ function requireCurrentStartBudgetQueue(
787
788
  if (currentGoalQueueIdentity(runtime) === expectedIdentity) {
788
789
  return true;
789
790
  }
790
- ctx.ui.notify(
791
+ notifyTerminal(
792
+ ctx.ui,
791
793
  "The goal queue changed while the token budget flow was open. Reopen /goal and try again.",
792
794
  "warning",
793
795
  );
@@ -811,7 +813,8 @@ function requireCurrentBudgetPreview(
811
813
  ) {
812
814
  return true;
813
815
  }
814
- ctx.ui.notify(
816
+ notifyTerminal(
817
+ ctx.ui,
815
818
  "The goal changed or its usage changed while the budget dialog was open. Reopen /goal and try again.",
816
819
  "warning",
817
820
  );
@@ -824,7 +827,8 @@ function requireCurrentQueueHead(
824
827
  ctx: ExtensionCommandContext,
825
828
  ) {
826
829
  if (runtime.activeGoal?.id === expectedGoal.id) return true;
827
- ctx.ui.notify(
830
+ notifyTerminal(
831
+ ctx.ui,
828
832
  "The goal queue changed while the dialog was open. Reopen /goal and try again.",
829
833
  "warning",
830
834
  );
@@ -848,7 +852,8 @@ function requireCurrentQueueSelection(
848
852
  ) {
849
853
  return true;
850
854
  }
851
- ctx.ui.notify(
855
+ notifyTerminal(
856
+ ctx.ui,
852
857
  "The goal queue changed while the dialog was open. Reopen /goal and try again.",
853
858
  "warning",
854
859
  );
@@ -861,7 +866,8 @@ function requireCurrentMenuGoal(
861
866
  ctx: ExtensionCommandContext,
862
867
  ) {
863
868
  if (runtime.activeGoal?.id === expected.id) return true;
864
- ctx.ui.notify(
869
+ notifyTerminal(
870
+ ctx.ui,
865
871
  "The active goal changed while the dialog was open. Reopen /goal and try again.",
866
872
  "warning",
867
873
  );
@@ -893,11 +899,6 @@ function automaticPauseSummary(used: number, limit: number | null) {
893
899
  return `Goal reached its ${used}-of-${limit} safety limit.`;
894
900
  }
895
901
 
896
- function isTerminalControl(character: string) {
897
- const codePoint = character.codePointAt(0) ?? 0;
898
- return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);
899
- }
900
-
901
902
  function goalHelp() {
902
903
  return [
903
904
  "Goal menu",
@@ -1,6 +1,6 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
- import process from "node:process";
3
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
4
4
  import {
5
5
  isNonNegativeFiniteNumber,
6
6
  nonNegativeFiniteNumber,
@@ -10,10 +10,7 @@ import type { GoalStatus } from "./prompts.js";
10
10
 
11
11
  const GOAL_STATE_ENTRY_TYPE = "goal-state";
12
12
  const LEGACY_GOALS_STATE_ENTRY_TYPE = "goals-state";
13
- const STATE_FILE = join(
14
- process.env.PI_CODING_AGENT_DIR ?? join(process.env.HOME ?? ".", ".pi", "agent"),
15
- "pi-goal-state.json",
16
- );
13
+ const STATE_FILE = join(getAgentDir(), "pi-goal-state.json");
17
14
 
18
15
  export type SafetyPauseCause = "continuation_limit" | "no_progress";
19
16
 
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
  }
package/src/tools.ts CHANGED
@@ -1,5 +1,12 @@
1
- import { defineTool, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
1
+ import {
2
+ DEFAULT_MAX_BYTES,
3
+ DEFAULT_MAX_LINES,
4
+ defineTool,
5
+ type ExtensionAPI,
6
+ truncateHead,
7
+ } from "@earendil-works/pi-coding-agent";
2
8
  import { Type } from "typebox";
9
+ import { notifyTerminal, safeTerminalText } from "./errors.js";
3
10
  import {
4
11
  formatStatus,
5
12
  GOAL_BLOCKED_TOOL,
@@ -7,6 +14,7 @@ import {
7
14
  type GoalRuntime,
8
15
  goalIdRejectionReason,
9
16
  isContradictoryCompletionSummary,
17
+ MAX_GOAL_ID_LENGTH,
10
18
  STATUS_KEY,
11
19
  transitionGoal,
12
20
  truncateNotification,
@@ -26,6 +34,8 @@ interface GoalBlockedDetails {
26
34
  repeated_turns: number;
27
35
  }
28
36
 
37
+ const MAX_GOAL_TEXT_LENGTH = 4_000;
38
+ const MAX_COMPLETION_SUMMARY_LENGTH = 4_000;
29
39
  const MAX_BLOCKER_REASON_LENGTH = 1_000;
30
40
  const MAX_BLOCKER_EVIDENCE_LENGTH = 4_000;
31
41
 
@@ -45,10 +55,14 @@ export function registerGoalTools(pi: ExtensionAPI, runtime: GoalRuntime) {
45
55
  ],
46
56
  parameters: Type.Object({
47
57
  goal_id: Type.String({
58
+ minLength: 1,
59
+ maxLength: MAX_GOAL_ID_LENGTH,
48
60
  description:
49
61
  "The exact goal_id shown in the current active /goal prompt. Used only to reject stale completion calls from older turns.",
50
62
  }),
51
63
  summary: Type.String({
64
+ minLength: 1,
65
+ maxLength: MAX_COMPLETION_SUMMARY_LENGTH,
52
66
  description:
53
67
  "State what was completed and what evidence verified it. Do not use this tool to report partial progress, blockers, failures, or remaining work.",
54
68
  }),
@@ -61,20 +75,20 @@ export function registerGoalTools(pi: ExtensionAPI, runtime: GoalRuntime) {
61
75
 
62
76
  if (!completedGoal) {
63
77
  const rejection = "Goal completion rejected: no active goal.";
64
- ctx.ui.notify(rejection, "warning");
78
+ notifyTerminal(ctx.ui, rejection, "warning");
65
79
 
66
80
  return {
67
- content: [{ type: "text", text: rejection }],
68
- details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
81
+ content: toolContent(rejection),
82
+ details: completionDetails(goal, requestedGoalId, summary),
69
83
  };
70
84
  }
71
85
  const completingDuringBudgetWrapUp = runtime.hasActiveBudgetWrapUp();
72
86
  if (!runtime.canRecordGoalUsage() && !completingDuringBudgetWrapUp) {
73
87
  const rejection = "Goal completion rejected: current run does not own the active goal.";
74
- ctx.ui.notify(rejection, "warning");
88
+ notifyTerminal(ctx.ui, rejection, "warning");
75
89
  return {
76
- content: [{ type: "text", text: rejection }],
77
- details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
90
+ content: toolContent(rejection),
91
+ details: completionDetails(goal, requestedGoalId, summary),
78
92
  };
79
93
  }
80
94
  if (hasPendingSkipForGoal(runtime, completedGoal.id)) {
@@ -83,17 +97,17 @@ export function registerGoalTools(pi: ExtensionAPI, runtime: GoalRuntime) {
83
97
  runtime.updateStatus(ctx, completedGoal);
84
98
  runtime.clearBudgetWrapUp();
85
99
  const rejection = "Goal completion rejected: goal is queued to be skipped.";
86
- ctx.ui.notify(rejection, "warning");
100
+ notifyTerminal(ctx.ui, rejection, "warning");
87
101
  return {
88
- content: [{ type: "text", text: rejection }],
89
- details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
102
+ content: toolContent(rejection),
103
+ details: completionDetails(goal, requestedGoalId, summary),
90
104
  terminate: true,
91
105
  };
92
106
  }
93
107
  const staleGoalRejection = goalIdRejectionReason(completedGoal, requestedGoalId);
94
108
  if (staleGoalRejection) {
95
109
  const rejection = `Goal completion rejected: ${staleGoalRejection}.`;
96
- ctx.ui.notify(rejection, "warning");
110
+ notifyTerminal(ctx.ui, rejection, "warning");
97
111
  if (completingDuringBudgetWrapUp) {
98
112
  runtime.recordGoalUsage(completedGoal, ctx);
99
113
  runtime.persistGoal(completedGoal);
@@ -102,42 +116,39 @@ export function registerGoalTools(pi: ExtensionAPI, runtime: GoalRuntime) {
102
116
  }
103
117
 
104
118
  return {
105
- content: [{ type: "text", text: rejection }],
106
- details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
119
+ content: toolContent(rejection),
120
+ details: completionDetails(goal, requestedGoalId, summary),
107
121
  terminate: completingDuringBudgetWrapUp || undefined,
108
122
  };
109
123
  }
110
124
  if (completedGoal.status !== "active" && !completingDuringBudgetWrapUp) {
111
125
  const rejection = `Goal completion rejected: goal is ${completedGoal.status}, not active.`;
112
- ctx.ui.notify(rejection, "warning");
126
+ notifyTerminal(ctx.ui, rejection, "warning");
113
127
 
114
128
  return {
115
- content: [{ type: "text", text: rejection }],
116
- details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
129
+ content: toolContent(rejection),
130
+ details: completionDetails(goal, requestedGoalId, summary),
117
131
  };
118
132
  }
119
133
 
120
134
  const rejectionReason = !summary
121
135
  ? "summary is empty"
122
- : isContradictoryCompletionSummary(summary)
123
- ? "summary says the goal is not complete"
124
- : undefined;
136
+ : summary.length > MAX_COMPLETION_SUMMARY_LENGTH
137
+ ? "summary is too long"
138
+ : isContradictoryCompletionSummary(summary)
139
+ ? "summary says the goal is not complete"
140
+ : undefined;
125
141
  if (rejectionReason) {
126
142
  runtime.recordGoalUsage(completedGoal, ctx);
127
143
  runtime.persistGoal(completedGoal);
128
144
  runtime.updateStatus(ctx, completedGoal);
129
145
  const rejection = `Goal completion rejected: ${rejectionReason}.`;
130
- ctx.ui.notify(rejection, "warning");
146
+ notifyTerminal(ctx.ui, rejection, "warning");
131
147
  if (completingDuringBudgetWrapUp) runtime.clearBudgetWrapUp();
132
148
 
133
149
  return {
134
- content: [
135
- {
136
- type: "text",
137
- text: rejection,
138
- },
139
- ],
140
- details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
150
+ content: toolContent(rejection),
151
+ details: completionDetails(goal, requestedGoalId, summary),
141
152
  terminate: completingDuringBudgetWrapUp || undefined,
142
153
  };
143
154
  }
@@ -148,14 +159,14 @@ export function registerGoalTools(pi: ExtensionAPI, runtime: GoalRuntime) {
148
159
  if (runtime.pendingQueueAction?.kind === "prioritize") {
149
160
  runtime.persistGoal(runtime.activeGoal);
150
161
  ctx.ui.setStatus(STATUS_KEY, "complete");
151
- ctx.ui.notify(`Goal complete: ${goal}. Priority goal waits for Pi to settle.`, "info");
162
+ notifyTerminal(
163
+ ctx.ui,
164
+ `Goal complete: ${goal}. Priority goal waits for Pi to settle.`,
165
+ "info",
166
+ );
152
167
  return {
153
- content: [{ type: "text", text: `Goal complete: ${summary}` }],
154
- details: {
155
- goal,
156
- goal_id: requestedGoalId,
157
- summary,
158
- } satisfies GoalCompleteDetails,
168
+ content: toolContent(`Goal complete: ${summary}`),
169
+ details: completionDetails(goal, requestedGoalId, summary),
159
170
  terminate: true,
160
171
  };
161
172
  }
@@ -168,22 +179,16 @@ export function registerGoalTools(pi: ExtensionAPI, runtime: GoalRuntime) {
168
179
  };
169
180
  runtime.persistGoal(runtime.activeGoal);
170
181
  ctx.ui.setStatus(STATUS_KEY, "complete");
171
- ctx.ui.notify(
182
+ notifyTerminal(
183
+ ctx.ui,
172
184
  `Goal complete: ${goal}. Next goal queued: ${runtime.queuedGoals[0]?.text}`,
173
185
  "info",
174
186
  );
175
187
  return {
176
- content: [
177
- {
178
- type: "text",
179
- text: `Goal complete: ${summary}\nNext goal queued: ${runtime.queuedGoals[0]?.text}`,
180
- },
181
- ],
182
- details: {
183
- goal,
184
- goal_id: requestedGoalId,
185
- summary,
186
- } satisfies GoalCompleteDetails,
188
+ content: toolContent(
189
+ `Goal complete: ${summary}\nNext goal queued: ${runtime.queuedGoals[0]?.text}`,
190
+ ),
191
+ details: completionDetails(goal, requestedGoalId, summary),
187
192
  terminate: true,
188
193
  };
189
194
  }
@@ -192,11 +197,11 @@ export function registerGoalTools(pi: ExtensionAPI, runtime: GoalRuntime) {
192
197
  ctx.ui.setStatus(STATUS_KEY, formatStatus(runtime.activeGoal));
193
198
  runtime.clearActiveGoal(ctx);
194
199
  runtime.showCompletionStatus(ctx);
195
- ctx.ui.notify(`Goal complete: ${goal}`, "info");
200
+ notifyTerminal(ctx.ui, `Goal complete: ${goal}`, "info");
196
201
 
197
202
  return {
198
- content: [{ type: "text", text: `Goal complete: ${summary}` }],
199
- details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
203
+ content: toolContent(`Goal complete: ${summary}`),
204
+ details: completionDetails(goal, requestedGoalId, summary),
200
205
  terminate: true,
201
206
  };
202
207
  },
@@ -217,6 +222,8 @@ export function registerGoalTools(pi: ExtensionAPI, runtime: GoalRuntime) {
217
222
  ],
218
223
  parameters: Type.Object({
219
224
  goal_id: Type.String({
225
+ minLength: 1,
226
+ maxLength: MAX_GOAL_ID_LENGTH,
220
227
  description: "The exact goal_id shown in the current active /goal prompt.",
221
228
  }),
222
229
  reason: Type.String({
@@ -244,16 +251,10 @@ export function registerGoalTools(pi: ExtensionAPI, runtime: GoalRuntime) {
244
251
  typeof params.repeated_turns === "number" ? params.repeated_turns : Number.NaN;
245
252
  const reject = (rejectionReason: string, terminate = false) => {
246
253
  const rejection = `goal_blocked rejected: ${rejectionReason}.`;
247
- ctx.ui.notify(rejection, "warning");
254
+ notifyTerminal(ctx.ui, rejection, "warning");
248
255
  return {
249
- content: [{ type: "text" as const, text: rejection }],
250
- details: {
251
- goal,
252
- goal_id: requestedGoalId,
253
- reason: reason.slice(0, MAX_BLOCKER_REASON_LENGTH),
254
- evidence: evidence.slice(0, MAX_BLOCKER_EVIDENCE_LENGTH),
255
- repeated_turns: Number.isFinite(repeatedTurns) ? repeatedTurns : 0,
256
- } satisfies GoalBlockedDetails,
256
+ content: toolContent(rejection),
257
+ details: blockerDetails(goal, requestedGoalId, reason, evidence, repeatedTurns),
257
258
  ...(terminate ? { terminate: true as const } : {}),
258
259
  };
259
260
  };
@@ -287,17 +288,11 @@ export function registerGoalTools(pi: ExtensionAPI, runtime: GoalRuntime) {
287
288
  reason,
288
289
  });
289
290
  if (!stoppedGoal) return reject("active goal changed before blocker transition");
290
- ctx.ui.notify(`Goal blocked: ${truncateNotification(reason)}`, "warning");
291
+ notifyTerminal(ctx.ui, `Goal blocked: ${truncateNotification(reason)}`, "warning");
291
292
 
292
293
  return {
293
- content: [{ type: "text", text: `Goal blocked: ${reason}` }],
294
- details: {
295
- goal,
296
- goal_id: requestedGoalId,
297
- reason,
298
- evidence,
299
- repeated_turns: repeatedTurns,
300
- } satisfies GoalBlockedDetails,
294
+ content: toolContent(`Goal blocked: ${reason}`),
295
+ details: blockerDetails(goal, requestedGoalId, reason, evidence, repeatedTurns),
301
296
  terminate: true,
302
297
  };
303
298
  },
@@ -307,6 +302,42 @@ export function registerGoalTools(pi: ExtensionAPI, runtime: GoalRuntime) {
307
302
  pi.registerTool(goalBlockedTool);
308
303
  }
309
304
 
305
+ function toolContent(text: string) {
306
+ return [
307
+ {
308
+ type: "text" as const,
309
+ text: truncateHead(safeTerminalText(text), {
310
+ maxBytes: DEFAULT_MAX_BYTES,
311
+ maxLines: DEFAULT_MAX_LINES,
312
+ }).content,
313
+ },
314
+ ];
315
+ }
316
+
317
+ function completionDetails(goal: string, goalId: string, summary: string): GoalCompleteDetails {
318
+ return {
319
+ goal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),
320
+ goal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),
321
+ summary: summary.slice(0, MAX_COMPLETION_SUMMARY_LENGTH),
322
+ };
323
+ }
324
+
325
+ function blockerDetails(
326
+ goal: string,
327
+ goalId: string,
328
+ reason: string,
329
+ evidence: string,
330
+ repeatedTurns: number,
331
+ ): GoalBlockedDetails {
332
+ return {
333
+ goal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),
334
+ goal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),
335
+ reason: reason.slice(0, MAX_BLOCKER_REASON_LENGTH),
336
+ evidence: evidence.slice(0, MAX_BLOCKER_EVIDENCE_LENGTH),
337
+ repeated_turns: Number.isFinite(repeatedTurns) ? repeatedTurns : 0,
338
+ };
339
+ }
340
+
310
341
  function hasPendingSkipForGoal(runtime: GoalRuntime, goalId: string) {
311
342
  return (
312
343
  runtime.pendingQueueAction?.kind === "advance" &&