@narumitw/pi-goal 0.54.3 → 0.54.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +117 -190
  2. package/dist/chunks/{chunk-QWIUWKRW.js → chunk-VJ5LR26S.js} +57 -77
  3. package/dist/chunks/chunk-VJ5LR26S.js.map +7 -0
  4. package/dist/chunks/{chunk-UQRRW4CY.js → chunk-WQIA35U2.js} +6 -5
  5. package/dist/chunks/chunk-WQIA35U2.js.map +7 -0
  6. package/dist/chunks/{menu-WEFDREGC.js → menu-JMGWQZIT.js} +7 -22
  7. package/dist/chunks/menu-JMGWQZIT.js.map +7 -0
  8. package/dist/chunks/{settings-ui-MVYTTBHW.js → settings-ui-JG3PFRB5.js} +6 -18
  9. package/dist/chunks/settings-ui-JG3PFRB5.js.map +7 -0
  10. package/dist/index.ts +111 -126
  11. package/dist/index.ts.map +2 -2
  12. package/docs/managing-goals.md +47 -0
  13. package/docs/settings.md +91 -0
  14. package/package.json +55 -58
  15. package/src/accounting.ts +62 -66
  16. package/src/command-registration.ts +104 -102
  17. package/src/command.ts +101 -112
  18. package/src/commands.ts +465 -501
  19. package/src/errors.ts +127 -122
  20. package/src/goal-contract.ts +64 -64
  21. package/src/goal.ts +25 -25
  22. package/src/lifecycle.ts +615 -628
  23. package/src/markers.ts +6 -6
  24. package/src/menu.ts +565 -591
  25. package/src/persistence.ts +177 -192
  26. package/src/prompts.ts +53 -67
  27. package/src/run-protocol.ts +299 -325
  28. package/src/runtime.ts +1422 -1495
  29. package/src/safety.ts +51 -51
  30. package/src/settings-ui.ts +366 -393
  31. package/src/settings.ts +134 -147
  32. package/src/tool-policy.ts +6 -6
  33. package/src/tools.ts +371 -347
  34. package/src/wait.ts +47 -51
  35. package/src/workflow-mutex.ts +68 -68
  36. package/dist/chunks/chunk-QWIUWKRW.js.map +0 -7
  37. package/dist/chunks/chunk-UQRRW4CY.js.map +0 -7
  38. package/dist/chunks/menu-WEFDREGC.js.map +0 -7
  39. package/dist/chunks/settings-ui-MVYTTBHW.js.map +0 -7
@@ -0,0 +1,47 @@
1
+ # Managing goals
2
+
3
+ [Back to README](../README.md#-commands)
4
+
5
+ ## Start, edit, and replace
6
+
7
+ Starting a goal begins automatic work and resets its usage counters.
8
+ Replacing an unfinished goal requires confirmation; cancelling keeps the previous goal.
9
+ If kickoff delivery fails, a new goal is cleared or the previous Goal and tool policy are restored, including its prior active or waiting state.
10
+
11
+ An edit preserves cumulative usage.
12
+ An active edit starts a fresh safety epoch and invalidates stale turns; stopped goals retain their safety state until resumed.
13
+ A budget-limited goal reactivates only when `edit --tokens` raises its total budget above current usage.
14
+ Failed prompt delivery restores the previous objective, state, safety counters, and tool policy.
15
+
16
+ For budget selection, units, cancellation, and cost limits, see [Token budgets and elapsed time](../README.md#-token-budgets-and-elapsed-time).
17
+ For automatic-work settings, see the [settings reference](./settings.md).
18
+
19
+ ## Pause and resume
20
+
21
+ `/goal pause` stops automatic continuation and aborts the current turn while preserving the goal.
22
+ It applies only to active goals.
23
+
24
+ Resuming a paused, blocked, usage-limited, or eligible budget-limited goal starts another safety epoch: automatic-response and repetition counters reset, while the objective, cumulative usage, and active elapsed time remain intact.
25
+ The command reports the new finite epoch or explicit Unlimited state.
26
+ If resume delivery fails, the original stopped state and counters are restored.
27
+ Resuming an active waiting goal instead clears its wait without resetting the safety epoch; see [External waiting](../README.md#-external-waiting).
28
+
29
+ In the TUI, an automatic-work-limit pause offers **Review and continue…**, which previews and confirms another epoch.
30
+ Changing the automatic-work limit alone leaves the goal paused; Back or Escape makes no change.
31
+ An exhausted token budget must be raised above current usage before work can resume.
32
+
33
+ ## Clear and migrate legacy queues
34
+
35
+ Menu-driven Clear previews the affected goal and requires confirmation.
36
+ Direct `/goal clear` and its `/goal stop` alias clear immediately, including pending continuation and inert legacy queue state, without aborting unrelated in-flight work.
37
+ For session persistence and old working-directory state cleanup, see [Session and reload behavior](../README.md#-session-and-reload-behavior).
38
+
39
+ The experimental ordered-goal queue has been removed.
40
+ Use `/goal edit <objective>` to reprioritize one objective instead, for example:
41
+
42
+ ```text
43
+ /goal edit task b is complete; do task a next; then continue task c and task d; do not redo task b unless verification shows it is incomplete.
44
+ ```
45
+
46
+ Former queue words `add`, `prioritize`, `drop-last`, `skip`, `push`, `unshift`, `pop`, and `shift` are ordinary objective text for unaffected users.
47
+ Sessions with legacy queue settings or persisted queue state show a migration warning for those words instead of replacing the active Goal.
@@ -0,0 +1,91 @@
1
+ # Pi Goal settings reference
2
+
3
+ [Back to README](../README.md)
4
+
5
+ This reference covers safety limits, managed-run access, settings persistence, and compatibility.
6
+ For installation and first use, start with the README.
7
+
8
+ ## Settings and safety limits
9
+
10
+ Settings are optional.
11
+ When `~/.pi/agent/pi-goal.json` is absent, pi-goal uses these built-in defaults without creating the file:
12
+
13
+ ```json
14
+ {
15
+ "rpc": {
16
+ "enabled": false
17
+ },
18
+ "continuationLimits": {
19
+ "automaticTurns": 25,
20
+ "noProgressTurns": 3
21
+ }
22
+ }
23
+ ```
24
+
25
+ Use `/goal` → **Settings…** in the TUI to create or update the file, or edit it directly.
26
+ The Settings screen shows all three controls on one level.
27
+ The two safety limits open separate choice screens:
28
+
29
+ - **Automatic-work limit** shows the exact response limit or **Unlimited**.
30
+ Choose **Set response limit…** to edit the current finite value (or the built-in default of 25 when switching from Unlimited), or choose **Unlimited…**.
31
+ Unlimited requires confirmation that tool loops may continue consuming tokens and provider cost without a response-count cap.
32
+ - **No-progress guard** shows **_N_ runs** or **Off**.
33
+ Choose the default threshold, **Off**, or **Set threshold…** and enter a safe whole number greater than zero.
34
+ - **Managed run RPC** controls whether trusted installed extensions may start and cancel managed Goal runs.
35
+ It defaults to **Off** and controls cooperation, not extension permissions.
36
+
37
+ Custom number inputs accept only positive safe integers.
38
+ Choose **Unlimited** or **Off** explicitly instead of entering zero, a negative number, a decimal, or text.
39
+ Interactive changes run in order, publish atomically, preserve unknown fields, and apply to the current runtime.
40
+ A successful save updates the visible state immediately.
41
+ A failed save restores the prior value and reports the settings path so it can be retried.
42
+ Escape returns to the previous screen without reverting changes that were already saved.
43
+
44
+ Pi-goal registers `goal_complete`, `goal_blocked`, and `goal_wait` once and keeps their schemas stable from startup.
45
+ Visible Goal tools do not mean Goal mode is active, and only the latest effective active Goal contract authorizes their use.
46
+ Pi-goal never widens a restrictive active-tool policy; activation rejects when required terminal tools are missing, and an active Goal pauses if they later disappear.
47
+ The retired `toolVisibility` key is ignored and preserved as unknown data when another setting is saved.
48
+
49
+ `experimental.goals` is a removed legacy setting.
50
+ If it remains `true`, pi-goal accepts the settings file and ignores the old queue feature.
51
+ Affected users see a warning that recommends `/goal edit` for an active objective or `/goal <objectives>` when no goal is active.
52
+ Later settings saves preserve unknown legacy fields instead of deleting them.
53
+
54
+ `rpc.enabled` accepts a boolean and defaults to `false`.
55
+ When disabled, a valid managed-run start receives `RPC_DISABLED`; manual and restored Goals remain unchanged.
56
+ A Settings-menu change applies immediately after its atomic save.
57
+ Disabling rejects new starts but lets an already accepted run continue publishing its exact state and accept its exact cancellation until terminal, avoiding stranded work.
58
+ Reload, replacement, and shutdown clear that in-memory ownership.
59
+
60
+ `continuationLimits` controls the automatic-work safety guards:
61
+
62
+ - `automaticTurns` accepts a positive safe integer or `null` and defaults to `25`.
63
+ It counts every completed normal `turn_end` owned by automatically started Goal work, including model responses inside tool loops and matching Pi-owned retries.
64
+ The user-triggered kickoff, resume, edit, and ordinary user runs are not charged.
65
+ At the limit, the goal becomes `paused` with cause `continuation_limit` and pending continuation or recovery is cancelled.
66
+ The current operation is aborted before a 26th normal response starts.
67
+ 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.
68
+ Set this field explicitly to `null` to opt into Unlimited mode; existing explicit `null` values remain compatible.
69
+ - `noProgressTurns` is a positive safe integer and defaults to `3`.
70
+ At the end of an automatic run, pi-goal compares visible assistant text after Unicode normalization, lowercase conversion, control-character removal, and whitespace collapse.
71
+ Thinking and tool blocks are excluded; empty and punctuation-only output are equivalent.
72
+ Consecutive empty or identical tool-free outputs increment the repeat count.
73
+ Different non-empty output starts a new run at one, and any attempted tool call resets it.
74
+ Set this field to `null` to disable only this heuristic.
75
+
76
+ Settings are reread at Pi startup, session replacement, and `/reload`.
77
+ Direct file edits are not watched, while Goal-menu changes apply immediately.
78
+ A missing file remains absent and uses the built-in defaults.
79
+ The first successful settings change creates the file atomically; later saves preserve unknown fields.
80
+ Omitted fields use the defaults above.
81
+
82
+ Invalid or malformed existing settings are never overwritten; they produce a warning and fall back to all defaults.
83
+ In the TUI, Goal Settings becomes a read-only summary that identifies the invalid file and tells you to fix it and run `/reload`.
84
+
85
+ Plan mode or another restrictive policy may hide Goal tools.
86
+ Pi-goal does not override that policy during restore or later turns.
87
+ Activation fails when required terminal tools are unavailable, and an active goal pauses without automatic continuation if they disappear.
88
+ A restrictive allowlist created before `goal_wait` existed can still run ordinary Goals with `goal_complete` and `goal_blocked`.
89
+ The model cannot enter external waiting until that allowlist also includes `goal_wait`.
90
+ The pause aborts a Goal-owned kickoff, resume, active edit, or automatic-continuation prompt.
91
+ It does not cancel or stale-block unrelated user or extension turns, including startup follow-ups after a restrictive restore.
package/package.json CHANGED
@@ -1,60 +1,57 @@
1
1
  {
2
- "name": "@narumitw/pi-goal",
3
- "version": "0.54.3",
4
- "description": "Pi extension for autonomous single-objective /goal completion.",
5
- "type": "module",
6
- "license": "MIT",
7
- "private": false,
8
- "keywords": [
9
- "pi-package",
10
- "pi-extension",
11
- "pi",
12
- "goal",
13
- "automation"
14
- ],
15
- "files": [
16
- "src",
17
- "dist",
18
- "README.md",
19
- "LICENSE"
20
- ],
21
- "pi": {
22
- "extensions": [
23
- "./dist/index.ts"
24
- ]
25
- },
26
- "piExtension": {
27
- "lifecycle": "stable"
28
- },
29
- "scripts": {
30
- "build": "node scripts/build-runtime.mjs",
31
- "check": "npm run build && biome check . && npm run typecheck",
32
- "format": "biome check --write .",
33
- "test:runtime": "node ./test/goal-runtime-smoke.mjs",
34
- "typecheck": "tsc --noEmit",
35
- "prepack": "npm run build"
36
- },
37
- "peerDependencies": {
38
- "@earendil-works/pi-ai": "*",
39
- "@earendil-works/pi-coding-agent": "*",
40
- "@earendil-works/pi-tui": "*",
41
- "typebox": "*"
42
- },
43
- "devDependencies": {
44
- "@biomejs/biome": "2.5.10",
45
- "@earendil-works/pi-ai": "0.84.3",
46
- "@earendil-works/pi-coding-agent": "0.84.3",
47
- "@earendil-works/pi-tui": "0.84.3",
48
- "esbuild": "0.28.2",
49
- "typebox": "1.3.18",
50
- "typescript": "7.0.2"
51
- },
52
- "dependencies": {
53
- "@narumitw/pi-tui-kit": "^0.59.0"
54
- },
55
- "repository": {
56
- "type": "git",
57
- "url": "https://github.com/narumiruna/pi-extensions",
58
- "directory": "packages/pi-goal"
59
- }
2
+ "name": "@narumitw/pi-goal",
3
+ "version": "0.54.5",
4
+ "description": "Pi extension for autonomous single-objective /goal completion.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "private": false,
8
+ "keywords": [
9
+ "pi-package",
10
+ "pi-extension",
11
+ "pi",
12
+ "goal",
13
+ "automation"
14
+ ],
15
+ "files": [
16
+ "src",
17
+ "dist",
18
+ "docs",
19
+ "README.md",
20
+ "LICENSE"
21
+ ],
22
+ "pi": {
23
+ "extensions": [
24
+ "./dist/index.ts"
25
+ ]
26
+ },
27
+ "scripts": {
28
+ "build": "node scripts/build-runtime.mjs",
29
+ "check": "npm run build && biome check . && npm run typecheck",
30
+ "format": "biome check --write .",
31
+ "test:runtime": "node ./test/goal-runtime-smoke.mjs",
32
+ "typecheck": "tsc --noEmit",
33
+ "prepack": "npm run build"
34
+ },
35
+ "peerDependencies": {
36
+ "@earendil-works/pi-ai": "*",
37
+ "@earendil-works/pi-coding-agent": "*",
38
+ "@earendil-works/pi-tui": "*",
39
+ "typebox": "*"
40
+ },
41
+ "devDependencies": {
42
+ "@earendil-works/pi-ai": "0.85.1",
43
+ "@earendil-works/pi-coding-agent": "0.85.1",
44
+ "@earendil-works/pi-tui": "0.85.1",
45
+ "esbuild": "0.28.2",
46
+ "typebox": "1.3.30",
47
+ "typescript": "7.0.2"
48
+ },
49
+ "dependencies": {
50
+ "@narumitw/pi-tui-kit": "^0.59.0"
51
+ },
52
+ "repository": {
53
+ "type": "git",
54
+ "url": "https://github.com/narumiruna/pi-extensions",
55
+ "directory": "packages/pi-goal"
56
+ }
60
57
  }
package/src/accounting.ts CHANGED
@@ -1,106 +1,102 @@
1
1
  import type { Usage } from "@earendil-works/pi-ai";
2
2
 
3
3
  export interface GoalAccountingState {
4
- status: string;
5
- baselineTokens: number;
6
- tokensUsed: number;
7
- timeUsedSeconds: number;
8
- activeStartedAt?: number;
9
- updatedAt: number;
4
+ status: string;
5
+ baselineTokens: number;
6
+ tokensUsed: number;
7
+ timeUsedSeconds: number;
8
+ activeStartedAt?: number;
9
+ updatedAt: number;
10
10
  }
11
11
 
12
12
  interface AssistantUsageEntryLike {
13
- type?: unknown;
14
- message?: unknown;
13
+ type?: unknown;
14
+ message?: unknown;
15
15
  }
16
16
 
17
17
  interface UsageContext {
18
- sessionManager?: unknown;
18
+ sessionManager?: unknown;
19
19
  }
20
20
 
21
- export function checkpointGoalActiveTime(
22
- goal: GoalAccountingState,
23
- now: number,
24
- continueClock: boolean,
25
- ) {
26
- const accumulated = nonNegativeFiniteNumber(goal.timeUsedSeconds);
27
- const startedAt = goal.activeStartedAt;
28
- if (typeof startedAt === "number" && Number.isFinite(startedAt)) {
29
- goal.timeUsedSeconds = accumulated + Math.max(0, now - startedAt) / 1000;
30
- } else {
31
- goal.timeUsedSeconds = accumulated;
32
- }
33
- goal.activeStartedAt = continueClock ? now : undefined;
21
+ export function checkpointGoalActiveTime(goal: GoalAccountingState, now: number, continueClock: boolean) {
22
+ const accumulated = nonNegativeFiniteNumber(goal.timeUsedSeconds);
23
+ const startedAt = goal.activeStartedAt;
24
+ if (typeof startedAt === "number" && Number.isFinite(startedAt)) {
25
+ goal.timeUsedSeconds = accumulated + Math.max(0, now - startedAt) / 1000;
26
+ } else {
27
+ goal.timeUsedSeconds = accumulated;
28
+ }
29
+ goal.activeStartedAt = continueClock ? now : undefined;
34
30
  }
35
31
 
36
32
  export function updateGoalUsage(
37
- goal: GoalAccountingState,
38
- ctx: UsageContext,
39
- continueClock = goal.status === "active",
33
+ goal: GoalAccountingState,
34
+ ctx: UsageContext,
35
+ continueClock = goal.status === "active",
40
36
  ) {
41
- const now = Date.now();
42
- const baselineTokens = nonNegativeFiniteNumber(goal.baselineTokens);
43
- goal.baselineTokens = baselineTokens;
44
- goal.tokensUsed = Math.max(0, currentTokenTotal(ctx) - baselineTokens);
45
- checkpointGoalActiveTime(goal, now, continueClock);
46
- goal.updatedAt = now;
37
+ const now = Date.now();
38
+ const baselineTokens = nonNegativeFiniteNumber(goal.baselineTokens);
39
+ goal.baselineTokens = baselineTokens;
40
+ goal.tokensUsed = Math.max(0, currentTokenTotal(ctx) - baselineTokens);
41
+ checkpointGoalActiveTime(goal, now, continueClock);
42
+ goal.updatedAt = now;
47
43
  }
48
44
 
49
45
  export function formatDuration(seconds: number) {
50
- const wholeSeconds = Math.max(0, Math.floor(nonNegativeFiniteNumber(seconds)));
51
- if (wholeSeconds < 60) return `${wholeSeconds}s`;
52
- const minutes = Math.floor(wholeSeconds / 60);
53
- if (minutes < 60) return `${minutes}m`;
54
- const hours = Math.floor(minutes / 60);
55
- return `${hours}h${minutes % 60}m`;
46
+ const wholeSeconds = Math.max(0, Math.floor(nonNegativeFiniteNumber(seconds)));
47
+ if (wholeSeconds < 60) return `${wholeSeconds}s`;
48
+ const minutes = Math.floor(wholeSeconds / 60);
49
+ if (minutes < 60) return `${minutes}m`;
50
+ const hours = Math.floor(minutes / 60);
51
+ return `${hours}h${minutes % 60}m`;
56
52
  }
57
53
 
58
54
  export function formatTokenCount(value: number) {
59
- if (value < 1_000) return `${value}`;
60
- if (value < 1_000_000) {
61
- return `${Number.isInteger(value / 1_000) ? value / 1_000 : (value / 1_000).toFixed(1)}k`;
62
- }
63
- return `${Number.isInteger(value / 1_000_000) ? value / 1_000_000 : (value / 1_000_000).toFixed(1)}m`;
55
+ if (value < 1_000) return `${value}`;
56
+ if (value < 1_000_000) {
57
+ return `${Number.isInteger(value / 1_000) ? value / 1_000 : (value / 1_000).toFixed(1)}k`;
58
+ }
59
+ return `${Number.isInteger(value / 1_000_000) ? value / 1_000_000 : (value / 1_000_000).toFixed(1)}m`;
64
60
  }
65
61
 
66
62
  export function isNonNegativeFiniteNumber(value: unknown): value is number {
67
- return typeof value === "number" && Number.isFinite(value) && value >= 0;
63
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
68
64
  }
69
65
 
70
66
  export function nonNegativeFiniteNumber(value: unknown) {
71
- return isNonNegativeFiniteNumber(value) ? value : 0;
67
+ return isNonNegativeFiniteNumber(value) ? value : 0;
72
68
  }
73
69
 
74
70
  export function normalizeTokenBudget(value: unknown) {
75
- return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;
71
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;
76
72
  }
77
73
 
78
74
  export function assistantUsageTokens(value: unknown) {
79
- if (!value || typeof value !== "object") return 0;
80
- const usage = value as Partial<Usage>;
81
- if (isNonNegativeFiniteNumber(usage.totalTokens)) return usage.totalTokens;
82
- return Math.min(
83
- Number.MAX_SAFE_INTEGER,
84
- nonNegativeFiniteNumber(usage.input) +
85
- nonNegativeFiniteNumber(usage.output) +
86
- nonNegativeFiniteNumber(usage.cacheRead) +
87
- nonNegativeFiniteNumber(usage.cacheWrite),
88
- );
75
+ if (!value || typeof value !== "object") return 0;
76
+ const usage = value as Partial<Usage>;
77
+ if (isNonNegativeFiniteNumber(usage.totalTokens)) return usage.totalTokens;
78
+ return Math.min(
79
+ Number.MAX_SAFE_INTEGER,
80
+ nonNegativeFiniteNumber(usage.input) +
81
+ nonNegativeFiniteNumber(usage.output) +
82
+ nonNegativeFiniteNumber(usage.cacheRead) +
83
+ nonNegativeFiniteNumber(usage.cacheWrite),
84
+ );
89
85
  }
90
86
 
91
87
  export function cumulativeAssistantTokens(entries: unknown[]) {
92
- let total = 0;
93
- for (const entry of entries) {
94
- const candidate = entry as AssistantUsageEntryLike;
95
- if (candidate?.type !== "message") continue;
96
- const message = candidate.message as { role?: unknown; usage?: unknown } | undefined;
97
- if (message?.role !== "assistant") continue;
98
- total = Math.min(Number.MAX_SAFE_INTEGER, total + assistantUsageTokens(message.usage));
99
- }
100
- return total;
88
+ let total = 0;
89
+ for (const entry of entries) {
90
+ const candidate = entry as AssistantUsageEntryLike;
91
+ if (candidate?.type !== "message") continue;
92
+ const message = candidate.message as { role?: unknown; usage?: unknown } | undefined;
93
+ if (message?.role !== "assistant") continue;
94
+ total = Math.min(Number.MAX_SAFE_INTEGER, total + assistantUsageTokens(message.usage));
95
+ }
96
+ return total;
101
97
  }
102
98
 
103
99
  export function currentTokenTotal(ctx: UsageContext): number {
104
- const sessionManager = ctx.sessionManager as { getBranch?: () => unknown[] } | undefined;
105
- return cumulativeAssistantTokens(sessionManager?.getBranch?.() ?? []);
100
+ const sessionManager = ctx.sessionManager as { getBranch?: () => unknown[] } | undefined;
101
+ return cumulativeAssistantTokens(sessionManager?.getBranch?.() ?? []);
106
102
  }