@narumitw/pi-goal 0.27.2 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,8 +9,8 @@ Goal mode uses Codex-like persistence instructions and sends guarded continuatio
9
9
  ## ✨ Features
10
10
 
11
11
  - Adds `/goal <goal_to_complete>` to start goal mode, with confirmation before replacing an existing goal.
12
- - Bare `/goal` shows the current goal summary.
13
- - Keeps advanced goal management inside `/goal` subcommands: `pause`, `resume`, `clear`, and `edit`.
12
+ - Bare `/goal` opens a current-state manager in the TUI, with guided start, pause, resume, edit, queue, settings, status, help, and destructive-action confirmation; RPC mode retains observable status notifications.
13
+ - Keeps direct goal management available through `/goal` subcommands: `status`, `pause`, `resume`, `clear`, and `edit`.
14
14
  - Exposes only one top-level command: `/goal`, including when ordered goals are enabled.
15
15
  - Optionally adds ordered-goal operations through `/goal add`, `prioritize`, `drop-last`, and `skip`, while accepting `push`, `unshift`, `pop`, and `shift` as hidden compatibility aliases.
16
16
  - Bounds automatic work by default to 25 normal model responses, including responses inside automatic tool loops and Pi-owned retry/compaction recovery; set `continuationLimits.automaticTurns` explicitly to `null` only when unbounded automatic work is intended.
@@ -70,7 +70,7 @@ with the complete current defaults:
70
70
  }
71
71
  ```
72
72
 
73
- Edit this generated file only when overriding the defaults.
73
+ Use `/goal` → **Settings…** in the TUI to edit these values interactively, or edit the generated file directly. Interactive changes are serialized, written atomically, preserve unknown fields, and apply to the current runtime. Tool-visibility changes that would alter the active tool schema are rejected while Pi is busy; retry after Pi settles. Escape closes the settings screen without reverting changes that were already saved.
74
74
 
75
75
  `toolVisibility` accepts:
76
76
 
@@ -84,9 +84,7 @@ Edit this generated file only when overriding the defaults.
84
84
  - `automaticTurns` is a positive safe integer and defaults to `25`. It counts every completed normal `turn_end` owned by automatically started Goal work, including model responses inside tool loops and matching Pi-owned retries. The user-triggered kickoff, resume, edit, and ordinary user runs are not charged. At the limit, the goal becomes `paused` with cause `continuation_limit`, pending continuation/recovery is cancelled, and the current operation is aborted. Pi may invoke a provider adapter once more with an already-aborted signal to produce its synthetic terminal event; that event is not counted and cannot resume Goal work. Set this field to `null` to remove the authoritative hard bound.
85
85
  - `noProgressTurns` is a positive safe integer and defaults to `3`. At the end of an automatic run, pi-goal compares visible assistant text after Unicode normalization, lowercasing, control-character removal, and whitespace collapse. Thinking and tool blocks are excluded; empty and punctuation-only output are equivalent. Consecutive empty or identical tool-free outputs increment the repeat count. Different non-empty output starts a new run at one, and any attempted tool call resets it. Set this field to `null` to disable only this heuristic.
86
86
 
87
- Settings are reread at Pi startup, session replacement, and `/reload`; the file is not watched live.
88
- A missing file is created during any of those session starts, while an existing file is read without
89
- being rewritten. Initialization publishes the generated file atomically and never overwrites a file
87
+ Settings are reread at Pi startup, session replacement, and `/reload`; direct external file edits are not watched live, while changes made through the Goal menu apply immediately. A missing file is created during any of those session starts, while an existing file is read without being rewritten. Initialization publishes the generated file atomically and never overwrites a file
90
88
  created concurrently by another process.
91
89
 
92
90
  Omitted fields use the defaults above. Invalid or malformed existing settings are never overwritten;
@@ -102,6 +100,7 @@ Tool visibility is a baseline, not ownership of Pi's global active-tool list. Pl
102
100
 
103
101
  ```text
104
102
  /goal
103
+ /goal status
105
104
  /goal implement snake game
106
105
  /goal --tokens 100k fix the failing test and verify it
107
106
  /goal edit ship the smaller fix first
@@ -116,7 +115,9 @@ Tool visibility is a baseline, not ownership of Pi's global active-tool list. Pl
116
115
  /goal skip
117
116
  ```
118
117
 
119
- - `/goal` shows the current goal, status, lifetime iteration count, automatic model-response count, active elapsed time, token usage, any safety-pause reason, and available `/goal` subcommands.
118
+ - In the TUI, `/goal` opens a state-aware manager. Its first action follows the current state: start when empty, pause when active, resume when stopped, or increase the budget when exhausted. Status, Settings, Help, queue management, Clear, and Close remain shallow, labeled routes. Arrow keys navigate, Enter selects, and Escape cancels or closes without changing state.
119
+ - In RPC mode, bare `/goal` and `/goal status` report the current summary through an observable notification without opening terminal UI. Pi exposes no extension-command output channel in print or JSON mode, so those routes reject with an explicit unsupported-mode error instead of misreporting stderr as status output.
120
+ - Menu-driven Replace, Clear, Prioritize, Skip, and Drop last actions preview the exact affected goals and require confirmation. Existing direct routes remain immediate for compatibility and automation.
120
121
  - `/goal <goal_to_complete>` starts goal mode. If another unfinished goal exists, Pi asks for confirmation before replacing it with a new active goal and resetting its usage counters. Failed kickoff delivery clears a new goal or restores the prior goal; a previously active goal is restored as paused.
121
122
  - `/goal --tokens 100k <goal_to_complete>` starts or replaces goal mode with a token budget. `k` and `m` suffixes are accepted, for example `100k` or `1.5m`.
122
123
  - `/goal edit <goal_to_complete>` updates the existing goal objective without resetting usage counters. A successful active edit rotates the stale-turn guard and starts a fresh safety epoch. Paused, blocked, and usage-limited goals stay stopped and retain their safety state until resume. A budget-limited goal reactivates only when `edit --tokens` raises its budget above current usage. Failed prompt delivery restores the exact previous safety counters/cause; it restores a budget-limited goal or restores and pauses a previously active goal.
@@ -143,7 +144,7 @@ Goal state is stored as Pi session state, similar to Codex's thread-owned goals.
143
144
 
144
145
  Ordered queues use the same canonical `goal-state` session entry as single goals. Every item owns independent usage and safety state. Shelving, priority displacement, automatic advancement, and later reactivation preserve that item's epoch rather than granting more automatic work. The legacy `{ goal }` shape remains valid, and missing safety fields normalize to zero/defaults. Queue fields are written only when needed. Sessions created by the former standalone `pi-goals` experiment can migrate their last `goals-state` array and pending `unshift` intent when the branch has never written a canonical `goal-state`; any canonical entry, including an explicit clear, takes precedence so old plural state cannot be resurrected.
145
146
 
146
- If a session still contains multiple goals or a pending queue transition when `experimental.goals` is disabled, pi-goal freezes that queue. It does not inject Goal prompts or continue work, reports `queue off`, preserves every item, and accepts only `/goal` for inspection or `/goal clear` for removal. Re-enable the setting and run `/reload` to resume. A migrated legacy array containing only one goal becomes an ordinary single goal without requiring the experiment.
147
+ If a session still contains multiple goals or a pending queue transition when `experimental.goals` is disabled, pi-goal freezes that queue. It does not inject Goal prompts or continue work, reports `queue off`, preserves every item, and accepts only `/goal` for inspection or `/goal clear` for removal. Re-enabling the setting in the TUI resumes retained work after any aborted Goal-owned run settles; editing the file directly still requires `/reload`. A migrated legacy array containing only one goal becomes an ordinary single goal without requiring the experiment.
147
148
 
148
149
  Older versions wrote unfinished goals to `~/.pi/agent/pi-goal-state.json` keyed by working directory. This version no longer reads that global file, and `/goal clear` removes any legacy entry for the current working directory.
149
150
 
@@ -237,7 +238,8 @@ Whenever pi-goal persists canonical goal state, it emits `pi-goal:state` with `{
237
238
  ```txt
238
239
  extensions/pi-goal/
239
240
  ├── src/
240
- │ ├── goal.ts # Pi entrypoint, tool contracts, and lifecycle orchestration
241
+ │ ├── index.ts # Pi package entrypoint
242
+ │ ├── goal.ts # Tool contracts and lifecycle orchestration
241
243
  │ ├── commands.ts # Per-factory user-command and queue mutation controller
242
244
  │ ├── runtime.ts # Per-factory state, prompt ownership, budgets, and tool policy
243
245
  │ ├── safety.ts # Output normalization and no-progress fingerprint state
@@ -252,12 +254,12 @@ extensions/pi-goal/
252
254
  └── package.json
253
255
  ```
254
256
 
255
- Only `goal.ts` is a Pi entrypoint; the other source modules are internal. The package exposes its Pi extension through `package.json`:
257
+ `index.ts` is the Pi entrypoint and forwards to `goal.ts`; the other source modules are internal. The package exposes its Pi extension through `package.json`:
256
258
 
257
259
  ```json
258
260
  {
259
261
  "pi": {
260
- "extensions": ["./src/goal.ts"]
262
+ "extensions": ["./src/index.ts"]
261
263
  }
262
264
  }
263
265
  ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-goal",
3
- "version": "0.27.2",
3
+ "version": "0.31.0",
4
4
  "description": "Pi extension for autonomous /goal completion with opt-in experimental ordered queues.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -20,7 +20,7 @@
20
20
  ],
21
21
  "pi": {
22
22
  "extensions": [
23
- "./src/goal.ts"
23
+ "./src/index.ts"
24
24
  ]
25
25
  },
26
26
  "scripts": {
@@ -30,12 +30,17 @@
30
30
  "typecheck": "tsc --noEmit"
31
31
  },
32
32
  "dependencies": {
33
- "typebox": "^1.3.3"
33
+ "typebox": "^1.3.8"
34
+ },
35
+ "peerDependencies": {
36
+ "@earendil-works/pi-ai": "*",
37
+ "@earendil-works/pi-coding-agent": "*",
38
+ "@earendil-works/pi-tui": "*"
34
39
  },
35
40
  "devDependencies": {
36
- "@biomejs/biome": "2.5.3",
37
- "@earendil-works/pi-ai": "0.81.1",
38
- "@earendil-works/pi-coding-agent": "0.81.1",
41
+ "@biomejs/biome": "2.5.5",
42
+ "@earendil-works/pi-ai": "0.82.1",
43
+ "@earendil-works/pi-coding-agent": "0.82.1",
39
44
  "typescript": "7.0.2"
40
45
  },
41
46
  "repository": {
package/src/accounting.ts CHANGED
@@ -72,9 +72,7 @@ export function nonNegativeFiniteNumber(value: unknown) {
72
72
  }
73
73
 
74
74
  export function normalizeTokenBudget(value: unknown) {
75
- return typeof value === "number" && Number.isSafeInteger(value) && value > 0
76
- ? value
77
- : undefined;
75
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;
78
76
  }
79
77
 
80
78
  export function assistantUsageTokens(value: unknown) {
package/src/commands.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { currentTokenTotal } from "./accounting.js";
1
+ import { checkpointGoalActiveTime, currentTokenTotal } from "./accounting.js";
2
2
  import { validateObjective } from "./command.js";
3
+ import { safeGoalMenuText } from "./menu.js";
3
4
  import type { ActiveGoal } from "./persistence.js";
4
5
  import { buildGoalPrompt, buildObjectiveUpdatedPrompt, buildResumePrompt } from "./prompts.js";
5
6
  import {
@@ -7,6 +8,7 @@ import {
7
8
  appendGoal,
8
9
  createQueuedGoal,
9
10
  dropLastGoal as dropLastQueuedGoal,
11
+ goalQueueIdentity,
10
12
  prioritizeGoal as prioritizeQueuedGoal,
11
13
  skipGoal as skipQueuedGoal,
12
14
  } from "./queue.js";
@@ -53,15 +55,36 @@ export class GoalCommandController {
53
55
  const existingGoal =
54
56
  this.runtime.activeGoal?.status !== "complete" ? this.runtime.activeGoal : undefined;
55
57
  const existingQueuedGoals = [...this.runtime.queuedGoals];
58
+ const existingQueueIdentity = goalQueueIdentity(
59
+ this.runtime.activeGoal,
60
+ this.runtime.queuedGoals,
61
+ this.runtime.pendingQueueAction,
62
+ );
56
63
  if (existingGoal) {
64
+ const queuedRemovalPreview =
65
+ existingQueuedGoals.length > 0
66
+ ? `\n\nQueued goals also removed:\n${existingQueuedGoals
67
+ .map((goal, index) => `${index + 1}. ${safeGoalMenuText(goal.text, 4_000)}`)
68
+ .join("\n")}`
69
+ : "";
57
70
  const shouldReplace = await ctx.ui.confirm(
58
71
  "Replace goal?",
59
- `Current goal: ${existingGoal.text}\n\nNew goal: ${objective}`,
72
+ `Current goal: ${safeGoalMenuText(existingGoal.text, 4_000)}${queuedRemovalPreview}\n\nNew goal: ${safeGoalMenuText(objective, 4_000)}`,
60
73
  );
61
74
  if (!shouldReplace) {
62
75
  ctx.ui.notify(`Goal kept: ${existingGoal.text}`, "info");
63
76
  return;
64
77
  }
78
+ if (
79
+ goalQueueIdentity(
80
+ this.runtime.activeGoal,
81
+ this.runtime.queuedGoals,
82
+ this.runtime.pendingQueueAction,
83
+ ) !== existingQueueIdentity
84
+ ) {
85
+ ctx.ui.notify("The goal queue changed while confirmation was open. Try again.", "warning");
86
+ return;
87
+ }
65
88
  }
66
89
 
67
90
  // Unlock lazy visibility only for a real activation. In always mode, a
@@ -214,6 +237,35 @@ export class GoalCommandController {
214
237
  }
215
238
  }
216
239
 
240
+ async resumeQueueAfterUnfreeze(ctx: StatusContext) {
241
+ if (this.runtime.queueFreezeAwaitingSettle) return false;
242
+ this.runtime.queueFrozen = false;
243
+ this.runtime.queueFreezeAwaitingSettle = false;
244
+ this.runtime.guardAbortGoalId = undefined;
245
+ this.runtime.clearStaleGoalToolCallBlock();
246
+ if (this.runtime.activeGoal) {
247
+ if (
248
+ this.runtime.activeGoal.status === "active" &&
249
+ this.runtime.activeGoal.activeStartedAt === undefined
250
+ ) {
251
+ const now = Date.now();
252
+ checkpointGoalActiveTime(this.runtime.activeGoal, now, true);
253
+ this.runtime.activeGoal.updatedAt = now;
254
+ }
255
+ this.runtime.persistGoal(this.runtime.activeGoal);
256
+ this.runtime.updateStatus(ctx, this.runtime.activeGoal);
257
+ } else {
258
+ ctx.ui.setStatus(STATUS_KEY, undefined);
259
+ }
260
+ if (this.runtime.pendingQueueAction) {
261
+ return this.dispatchPendingQueueActionIfSettled(ctx);
262
+ }
263
+ const goal = this.runtime.activeGoal;
264
+ if (goal?.status !== "active") return false;
265
+ this.runtime.requestContinuation(goal);
266
+ return this.runtime.dispatchContinuationIfSettled(ctx);
267
+ }
268
+
217
269
  async dispatchPendingQueueActionIfSettled(ctx: StatusContext) {
218
270
  const pending = this.runtime.pendingQueueAction;
219
271
  if (!pending || this.runtime.queueFrozen) return false;
@@ -516,8 +568,9 @@ export class GoalCommandController {
516
568
 
517
569
  showGoal(ctx: StatusContext) {
518
570
  if (!this.runtime.activeGoal) {
519
- ctx.ui.notify("Usage: /goal <objective>\nNo goal is currently set.", "info");
571
+ const message = "Usage: /goal <objective>\nNo goal is currently set.";
520
572
  ctx.ui.setStatus(STATUS_KEY, undefined);
573
+ this.reportGoalStatus(ctx, message);
521
574
  return;
522
575
  }
523
576
  if (!this.runtime.queueFrozen) {
@@ -525,17 +578,27 @@ export class GoalCommandController {
525
578
  this.runtime.persistGoal(this.runtime.activeGoal);
526
579
  this.runtime.updateStatus(ctx, this.runtime.activeGoal);
527
580
  }
528
- ctx.ui.notify(
581
+ this.reportGoalStatus(
582
+ ctx,
529
583
  goalSummary(
530
584
  this.runtime.activeGoal,
531
585
  this.runtime.queuedGoals,
532
586
  this.runtime.settings.experimental.goals,
533
587
  this.runtime.queueFrozen,
588
+ this.runtime.pendingQueueAction,
534
589
  ),
535
- "info",
536
590
  );
537
591
  }
538
592
 
593
+ private reportGoalStatus(ctx: StatusContext, message: string) {
594
+ if (ctx.mode === "print" || ctx.mode === "json") {
595
+ throw new Error(
596
+ `/goal status is unavailable in ${ctx.mode} mode because Pi does not expose an extension-command output channel. Use TUI or RPC mode.`,
597
+ );
598
+ }
599
+ ctx.ui.notify(message, "info");
600
+ }
601
+
539
602
  private async activatePrioritizedGoal(
540
603
  objective: string,
541
604
  tokenBudget: number | undefined,
package/src/goal.ts CHANGED
@@ -3,6 +3,7 @@ import { Type } from "typebox";
3
3
  import { currentTokenTotal } from "./accounting.js";
4
4
  import { completeGoalArguments, parseCommand } from "./command.js";
5
5
  import { GoalCommandController } from "./commands.js";
6
+ import { showGoalManager } from "./menu.js";
6
7
  import { type ActiveGoal, loadGoalStateFromSession } from "./persistence.js";
7
8
  import { buildGoalPrompt, buildGoalSystemPrompt } from "./prompts.js";
8
9
  import { activateQueuedGoal } from "./queue.js";
@@ -31,10 +32,11 @@ import {
31
32
  } from "./runtime.js";
32
33
  import { hasAssistantToolCall } from "./safety.js";
33
34
  import { DEFAULT_GOAL_SETTINGS, loadOrCreateGoalSettings } from "./settings.js";
35
+ import { showGoalSettings } from "./settings-ui.js";
34
36
 
35
- // goal.ts is the Pi-facing composition root: it keeps tool contracts and event
36
- // ordering together. Per-session mechanisms live in runtime.ts, while user command
37
- // transitions live in commands.ts. Each factory constructs isolated instances.
37
+ // goal.ts remains the Pi-facing composition root despite its size because tool contracts and
38
+ // lifecycle-event registration share order-sensitive wiring. Per-session mechanisms live in
39
+ // runtime.ts, while user-command transitions live in commands.ts; each factory stays isolated.
38
40
 
39
41
  interface GoalCompleteDetails {
40
42
  goal: string;
@@ -409,6 +411,17 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
409
411
  ctx.ui.notify(result, "warning");
410
412
  return;
411
413
  }
414
+ if (result.kind === "show" && args.trim() === "") {
415
+ await showGoalManager(runtime, commands, ctx, (menuCtx) =>
416
+ showGoalSettings(runtime, menuCtx, {
417
+ settingsPath: options.settingsPath,
418
+ onQueueUnfrozen: async (settingsCtx) => {
419
+ await commands.resumeQueueAfterUnfreeze(settingsCtx);
420
+ },
421
+ }),
422
+ );
423
+ return;
424
+ }
412
425
  if (runtime.queueFrozen) {
413
426
  if (result.kind === "show") commands.showGoal(ctx);
414
427
  else if (result.kind === "clear") commands.clearGoal(ctx);
@@ -470,6 +483,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
470
483
  runtime.queuedGoals = [];
471
484
  runtime.pendingQueueAction = undefined;
472
485
  runtime.queueFrozen = false;
486
+ runtime.queueFreezeAwaitingSettle = false;
473
487
  runtime.clearTerminalDetails();
474
488
  rpc.bindSession(ctx);
475
489
  const previousToolVisibility = runtime.settings.toolVisibility;
@@ -600,6 +614,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
600
614
  runtime.queuedGoals = [];
601
615
  runtime.pendingQueueAction = undefined;
602
616
  runtime.queueFrozen = false;
617
+ runtime.queueFreezeAwaitingSettle = false;
603
618
  ctx.ui.setStatus(STATUS_KEY, undefined);
604
619
  clearCompletionStatusTimer();
605
620
  runtime.clearTerminalDetails();
@@ -1027,6 +1042,10 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
1027
1042
  pi.on("agent_settled", async (_event, ctx) => {
1028
1043
  if (runtime.queueFrozen) {
1029
1044
  runtime.clearSettledSafetyTracking();
1045
+ runtime.queueFreezeAwaitingSettle = false;
1046
+ if (runtime.settings.experimental.goals) {
1047
+ await commands.resumeQueueAfterUnfreeze(ctx);
1048
+ }
1030
1049
  return;
1031
1050
  }
1032
1051
  runtime.finalizeSettledRecovery(ctx);
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export { default } from "./goal.js";