@narumitw/pi-goal 0.54.4 → 0.54.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +41 -166
  2. package/dist/chunks/{chunk-QWIUWKRW.js → chunk-VJ5LR26S.js} +57 -77
  3. package/dist/chunks/chunk-VJ5LR26S.js.map +7 -0
  4. package/dist/chunks/{chunk-UQRRW4CY.js → chunk-WQIA35U2.js} +6 -5
  5. package/dist/chunks/chunk-WQIA35U2.js.map +7 -0
  6. package/dist/chunks/{menu-WEFDREGC.js → menu-JMGWQZIT.js} +7 -22
  7. package/dist/chunks/menu-JMGWQZIT.js.map +7 -0
  8. package/dist/chunks/{settings-ui-MVYTTBHW.js → settings-ui-JG3PFRB5.js} +6 -18
  9. package/dist/chunks/settings-ui-JG3PFRB5.js.map +7 -0
  10. package/dist/index.ts +92 -126
  11. package/dist/index.ts.map +2 -2
  12. package/docs/managing-goals.md +47 -0
  13. package/docs/settings.md +91 -0
  14. package/package.json +55 -55
  15. package/src/accounting.ts +62 -66
  16. package/src/command-registration.ts +104 -102
  17. package/src/command.ts +101 -112
  18. package/src/commands.ts +465 -501
  19. package/src/errors.ts +127 -122
  20. package/src/goal-contract.ts +64 -64
  21. package/src/goal.ts +25 -25
  22. package/src/lifecycle.ts +615 -628
  23. package/src/markers.ts +6 -6
  24. package/src/menu.ts +565 -591
  25. package/src/persistence.ts +177 -192
  26. package/src/prompts.ts +53 -67
  27. package/src/run-protocol.ts +299 -325
  28. package/src/runtime.ts +1422 -1495
  29. package/src/safety.ts +51 -51
  30. package/src/settings-ui.ts +366 -393
  31. package/src/settings.ts +134 -147
  32. package/src/tool-policy.ts +6 -6
  33. package/src/tools.ts +360 -371
  34. package/src/wait.ts +47 -51
  35. package/src/workflow-mutex.ts +68 -68
  36. package/dist/chunks/chunk-QWIUWKRW.js.map +0 -7
  37. package/dist/chunks/chunk-UQRRW4CY.js.map +0 -7
  38. package/dist/chunks/menu-WEFDREGC.js.map +0 -7
  39. package/dist/chunks/settings-ui-MVYTTBHW.js.map +0 -7
@@ -1,129 +1,131 @@
1
1
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
2
  import { completeGoalArguments, isRemovedQueueCommand, parseCommand } from "./command.js";
3
3
  import type { GoalCommandController } from "./commands.js";
4
- import { notifyTerminal, safeTerminalText } from "./errors.js";
4
+ import { isStaleContextError, notifyTerminal, safeTerminalText } from "./errors.js";
5
5
  import type { GoalRuntime } from "./runtime.js";
6
6
 
7
7
  type GoalManagerModule = Pick<typeof import("./menu.js"), "showGoalManager">;
8
8
  type GoalSettingsModule = Pick<typeof import("./settings-ui.js"), "showGoalSettings">;
9
9
 
10
10
  export interface GoalCommandRegistrationOptions {
11
- settingsPath?: string;
12
- loadGoalManager?: () => Promise<GoalManagerModule>;
13
- loadGoalSettings?: () => Promise<GoalSettingsModule>;
11
+ settingsPath?: string;
12
+ loadGoalManager?: () => Promise<GoalManagerModule>;
13
+ loadGoalSettings?: () => Promise<GoalSettingsModule>;
14
14
  }
15
15
 
16
16
  export function registerGoalCommand(
17
- pi: ExtensionAPI,
18
- runtime: GoalRuntime,
19
- commands: GoalCommandController,
20
- options: GoalCommandRegistrationOptions = {},
17
+ pi: ExtensionAPI,
18
+ runtime: GoalRuntime,
19
+ commands: GoalCommandController,
20
+ options: GoalCommandRegistrationOptions = {},
21
21
  ) {
22
- const loadGoalManager = cachedModuleLoader(
23
- options.loadGoalManager ?? (() => import("./menu.js")),
24
- );
25
- const loadGoalSettings = cachedModuleLoader(
26
- options.loadGoalSettings ?? (() => import("./settings-ui.js")),
27
- );
22
+ const loadGoalManager = cachedModuleLoader(options.loadGoalManager ?? (() => import("./menu.js")));
23
+ const loadGoalSettings = cachedModuleLoader(options.loadGoalSettings ?? (() => import("./settings-ui.js")));
28
24
 
29
- pi.registerCommand("goal", {
30
- description: "Run a goal to completion: /goal [--tokens 100k] <goal_to_complete>",
31
- getArgumentCompletions: (prefix) => completeGoalArguments(prefix),
32
- handler: async (args, ctx) => {
33
- if (runtime.hasLegacyQueueInterface() && isRemovedQueueCommand(args)) {
34
- reportRemovedQueueCommand(ctx, runtime);
35
- return;
36
- }
37
- const result = parseCommand(args);
38
- if (typeof result === "string") {
39
- reportCommandError(result, ctx);
40
- return;
41
- }
42
- if (result.kind === "show" && args.trim() === "") {
43
- const menuIsCurrent = captureMenuOwnership(runtime);
44
- let managerModule: GoalManagerModule;
45
- try {
46
- managerModule = await loadGoalManager();
47
- } catch (error) {
48
- if (!menuIsCurrent()) return;
49
- throw error;
50
- }
51
- if (!menuIsCurrent()) return;
52
- const { showGoalManager } = managerModule;
53
- await showGoalManager(runtime, commands, ctx, async (menuCtx, target) => {
54
- const settingsAreCurrent = captureMenuOwnership(runtime);
55
- let settingsModule: GoalSettingsModule;
56
- try {
57
- settingsModule = await loadGoalSettings();
58
- } catch (error) {
59
- if (!settingsAreCurrent()) return;
60
- throw error;
61
- }
62
- if (!settingsAreCurrent()) return;
63
- const { showGoalSettings } = settingsModule;
64
- await showGoalSettings(runtime, menuCtx, {
65
- settingsPath: options.settingsPath,
66
- initialScreen: target,
67
- });
68
- });
69
- return;
70
- }
71
- switch (result.kind) {
72
- case "show":
73
- commands.showGoal(ctx);
74
- return;
75
- case "pause":
76
- commands.pauseGoal(ctx);
77
- return;
78
- case "resume":
79
- await commands.resumeGoal(ctx);
80
- return;
81
- case "clear":
82
- commands.clearGoal(ctx);
83
- return;
84
- case "edit":
85
- await commands.editGoal(result.objective ?? "", result.tokenBudget, ctx);
86
- return;
87
- case "start":
88
- await commands.startGoal(result.objective ?? "", result.tokenBudget, ctx);
89
- return;
90
- }
91
- },
92
- });
25
+ pi.registerCommand("goal", {
26
+ description: "Run a goal to completion: /goal [--tokens 100k] <goal_to_complete>",
27
+ getArgumentCompletions: (prefix) => completeGoalArguments(prefix),
28
+ handler: async (args, ctx) => {
29
+ try {
30
+ if (runtime.hasLegacyQueueInterface() && isRemovedQueueCommand(args)) {
31
+ reportRemovedQueueCommand(ctx, runtime);
32
+ return;
33
+ }
34
+ const result = parseCommand(args);
35
+ if (typeof result === "string") {
36
+ reportCommandError(result, ctx);
37
+ return;
38
+ }
39
+ if (result.kind === "show" && args.trim() === "") {
40
+ const menuIsCurrent = captureMenuOwnership(runtime);
41
+ let managerModule: GoalManagerModule;
42
+ try {
43
+ managerModule = await loadGoalManager();
44
+ } catch (error) {
45
+ if (!menuIsCurrent()) return;
46
+ throw error;
47
+ }
48
+ if (!menuIsCurrent()) return;
49
+ const { showGoalManager } = managerModule;
50
+ await showGoalManager(runtime, commands, ctx, async (menuCtx, target) => {
51
+ const settingsAreCurrent = captureMenuOwnership(runtime);
52
+ let settingsModule: GoalSettingsModule;
53
+ try {
54
+ settingsModule = await loadGoalSettings();
55
+ } catch (error) {
56
+ if (!settingsAreCurrent()) return;
57
+ throw error;
58
+ }
59
+ if (!settingsAreCurrent()) return;
60
+ const { showGoalSettings } = settingsModule;
61
+ await showGoalSettings(runtime, menuCtx, {
62
+ settingsPath: options.settingsPath,
63
+ initialScreen: target,
64
+ });
65
+ });
66
+ return;
67
+ }
68
+ switch (result.kind) {
69
+ case "show":
70
+ commands.showGoal(ctx);
71
+ return;
72
+ case "pause":
73
+ commands.pauseGoal(ctx);
74
+ return;
75
+ case "resume":
76
+ await commands.resumeGoal(ctx);
77
+ return;
78
+ case "clear":
79
+ commands.clearGoal(ctx);
80
+ return;
81
+ case "edit":
82
+ await commands.editGoal(result.objective ?? "", result.tokenBudget, ctx);
83
+ return;
84
+ case "start":
85
+ await commands.startGoal(result.objective ?? "", result.tokenBudget, ctx);
86
+ return;
87
+ }
88
+ } catch (error) {
89
+ // Pi invalidates command ctx when the session is replaced while a
90
+ // confirmation or menu await is still in flight. The dead session's
91
+ // command result is discarded, so a stale context is not an error.
92
+ if (isStaleContextError(error)) return;
93
+ throw error;
94
+ }
95
+ },
96
+ });
93
97
  }
94
98
 
95
99
  function reportCommandError(message: string, ctx: ExtensionCommandContext) {
96
- const safeMessage = safeTerminalText(message);
97
- if (ctx.mode === "print" || ctx.mode === "json") throw new Error(safeMessage);
98
- notifyTerminal(ctx.ui, safeMessage, "warning");
100
+ const safeMessage = safeTerminalText(message);
101
+ if (ctx.mode === "print" || ctx.mode === "json") throw new Error(safeMessage);
102
+ notifyTerminal(ctx.ui, safeMessage, "warning");
99
103
  }
100
104
 
101
105
  function reportRemovedQueueCommand(ctx: ExtensionCommandContext, runtime: GoalRuntime) {
102
- const message = runtime.activeGoal
103
- ? "Ordered goal queue has been removed. Use /goal edit to reprioritize the active objective instead."
104
- : "Ordered goal queue has been removed. Start /goal <objectives> to continue with one merged objective, or use /goal clear to discard the old queue state.";
105
- if (ctx.mode === "print" || ctx.mode === "json") throw new Error(message);
106
- notifyTerminal(ctx.ui, message, "warning");
106
+ const message = runtime.activeGoal
107
+ ? "Ordered goal queue has been removed. Use /goal edit to reprioritize the active objective instead."
108
+ : "Ordered goal queue has been removed. Start /goal <objectives> to continue with one merged objective, or use /goal clear to discard the old queue state.";
109
+ if (ctx.mode === "print" || ctx.mode === "json") throw new Error(message);
110
+ notifyTerminal(ctx.ui, message, "warning");
107
111
  }
108
112
 
109
113
  function captureMenuOwnership(runtime: GoalRuntime): () => boolean {
110
- const generation = runtime.menuGeneration;
111
- const controller = runtime.menuController;
112
- return () =>
113
- runtime.menuGeneration === generation &&
114
- runtime.menuController === controller &&
115
- !controller.signal.aborted;
114
+ const generation = runtime.menuGeneration;
115
+ const controller = runtime.menuController;
116
+ return () =>
117
+ runtime.menuGeneration === generation && runtime.menuController === controller && !controller.signal.aborted;
116
118
  }
117
119
 
118
120
  function cachedModuleLoader<Module>(load: () => Promise<Module>): () => Promise<Module> {
119
- let pending: Promise<Module> | undefined;
120
- return () => {
121
- if (!pending) {
122
- pending = load().catch((error) => {
123
- pending = undefined;
124
- throw error;
125
- });
126
- }
127
- return pending;
128
- };
121
+ let pending: Promise<Module> | undefined;
122
+ return () => {
123
+ if (!pending) {
124
+ pending = load().catch((error) => {
125
+ pending = undefined;
126
+ throw error;
127
+ });
128
+ }
129
+ return pending;
130
+ };
129
131
  }
package/src/command.ts CHANGED
@@ -1,151 +1,140 @@
1
1
  const MAX_OBJECTIVE_LENGTH = 4_000;
2
2
 
3
- const REMOVED_QUEUE_COMMANDS = new Set([
4
- "add",
5
- "prioritize",
6
- "drop-last",
7
- "skip",
8
- "push",
9
- "unshift",
10
- "pop",
11
- "shift",
12
- ]);
3
+ const REMOVED_QUEUE_COMMANDS = new Set(["add", "prioritize", "drop-last", "skip", "push", "unshift", "pop", "shift"]);
13
4
 
14
5
  export interface CommandResult {
15
- kind: "start" | "pause" | "resume" | "clear" | "show" | "edit";
16
- objective?: string;
17
- tokenBudget?: number;
6
+ kind: "start" | "pause" | "resume" | "clear" | "show" | "edit";
7
+ objective?: string;
8
+ tokenBudget?: number;
18
9
  }
19
10
 
20
11
  export interface GoalArgumentCompletion {
21
- value: string;
22
- label: string;
23
- description?: string;
12
+ value: string;
13
+ label: string;
14
+ description?: string;
24
15
  }
25
16
 
26
17
  const TOKEN_BUDGET_COMPLETION: GoalArgumentCompletion = {
27
- value: "--tokens ",
28
- label: "--tokens",
29
- description: "Set a token budget before the goal",
18
+ value: "--tokens ",
19
+ label: "--tokens",
20
+ description: "Set a token budget before the goal",
30
21
  };
31
22
  const GOAL_ARGUMENT_COMPLETIONS: readonly GoalArgumentCompletion[] = [
32
- { value: "pause", label: "pause", description: "Pause the active goal" },
33
- { value: "resume", label: "resume", description: "Resume a stopped or budget-limited goal" },
34
- { value: "clear", label: "clear", description: "Clear the current goal" },
35
- { value: "edit", label: "edit", description: "Edit the current goal objective" },
36
- { value: "status", label: "status", description: "Show the current goal" },
37
- TOKEN_BUDGET_COMPLETION,
23
+ { value: "pause", label: "pause", description: "Pause the active goal" },
24
+ { value: "resume", label: "resume", description: "Resume a stopped or budget-limited goal" },
25
+ { value: "clear", label: "clear", description: "Clear the current goal" },
26
+ { value: "edit", label: "edit", description: "Edit the current goal objective" },
27
+ { value: "status", label: "status", description: "Show the current goal" },
28
+ TOKEN_BUDGET_COMPLETION,
38
29
  ];
39
30
 
40
31
  export function completeGoalArguments(argumentPrefix: string): GoalArgumentCompletion[] | null {
41
- const prefix = argumentPrefix.trimStart();
42
- if (prefix === "") return [...GOAL_ARGUMENT_COMPLETIONS];
32
+ const prefix = argumentPrefix.trimStart();
33
+ if (prefix === "") return [...GOAL_ARGUMENT_COMPLETIONS];
43
34
 
44
- const objectiveOption = /^edit\s+(\S*)$/.exec(prefix);
45
- if (objectiveOption) {
46
- const optionPrefix = objectiveOption[1] ?? "";
47
- return optionPrefix === "" || "--tokens".startsWith(optionPrefix)
48
- ? [
49
- {
50
- value: "edit --tokens ",
51
- label: "--tokens",
52
- description: "Set a token budget before the updated goal",
53
- },
54
- ]
55
- : null;
56
- }
57
- if (/\s/.test(prefix)) return null;
58
- const matches = GOAL_ARGUMENT_COMPLETIONS.filter(
59
- (item) => item.value.startsWith(prefix) || item.label.startsWith(prefix),
60
- );
61
- return matches.length > 0 ? matches : null;
35
+ const objectiveOption = /^edit\s+(\S*)$/.exec(prefix);
36
+ if (objectiveOption) {
37
+ const optionPrefix = objectiveOption[1] ?? "";
38
+ return optionPrefix === "" || "--tokens".startsWith(optionPrefix)
39
+ ? [
40
+ {
41
+ value: "edit --tokens ",
42
+ label: "--tokens",
43
+ description: "Set a token budget before the updated goal",
44
+ },
45
+ ]
46
+ : null;
47
+ }
48
+ if (/\s/.test(prefix)) return null;
49
+ const matches = GOAL_ARGUMENT_COMPLETIONS.filter(
50
+ (item) => item.value.startsWith(prefix) || item.label.startsWith(prefix),
51
+ );
52
+ return matches.length > 0 ? matches : null;
62
53
  }
63
54
 
64
55
  export function parseCommand(args: string): CommandResult | string {
65
- const tokens = tokenize(args.trim());
66
- if (tokens.length === 0) return { kind: "show" };
67
- const [first, ...rest] = tokens;
68
- if (first === "pause") return rest.length === 0 ? { kind: "pause" } : "Usage: /goal pause";
69
- if (first === "resume") return rest.length === 0 ? { kind: "resume" } : "Usage: /goal resume";
70
- if (first === "clear" || first === "stop")
71
- return rest.length === 0 ? { kind: "clear" } : "Usage: /goal clear";
72
- if (first === "status") return rest.length === 0 ? { kind: "show" } : "Usage: /goal status";
73
- if (first === "edit") return parseObjective("edit", rest);
56
+ const tokens = tokenize(args.trim());
57
+ if (tokens.length === 0) return { kind: "show" };
58
+ const [first, ...rest] = tokens;
59
+ if (first === "pause") return rest.length === 0 ? { kind: "pause" } : "Usage: /goal pause";
60
+ if (first === "resume") return rest.length === 0 ? { kind: "resume" } : "Usage: /goal resume";
61
+ if (first === "clear" || first === "stop") return rest.length === 0 ? { kind: "clear" } : "Usage: /goal clear";
62
+ if (first === "status") return rest.length === 0 ? { kind: "show" } : "Usage: /goal status";
63
+ if (first === "edit") return parseObjective("edit", rest);
74
64
 
75
- return parseObjective("start", tokens);
65
+ return parseObjective("start", tokens);
76
66
  }
77
67
 
78
68
  export function isRemovedQueueCommand(args: string) {
79
- const [first] = tokenize(args.trim());
80
- return first !== undefined && REMOVED_QUEUE_COMMANDS.has(first);
69
+ const [first] = tokenize(args.trim());
70
+ return first !== undefined && REMOVED_QUEUE_COMMANDS.has(first);
81
71
  }
82
72
 
83
73
  function parseObjective(kind: "start" | "edit", tokens: string[]): CommandResult | string {
84
- let tokenBudget: number | undefined;
85
- const objectiveTokens = [...tokens];
86
- if (objectiveTokens[0] === "--tokens") {
87
- const rawBudget = objectiveTokens[1];
88
- if (!rawBudget) {
89
- return kind === "start"
90
- ? "Usage: /goal --tokens 100k <goal_to_complete>"
91
- : `Usage: /goal ${kind} --tokens 100k <goal_to_complete>`;
92
- }
93
- const parsedBudget = parseTokenBudget(rawBudget);
94
- if (parsedBudget === undefined) return `Invalid token budget: ${rawBudget}`;
95
- tokenBudget = parsedBudget;
96
- objectiveTokens.splice(0, 2);
97
- }
98
- if (objectiveTokens.length === 0) {
99
- if (kind === "start") return "Usage: /goal <goal_to_complete>";
100
- return `Usage: /goal ${kind} <goal_to_complete>`;
101
- }
102
- return { kind, objective: objectiveTokens.join(" "), tokenBudget };
74
+ let tokenBudget: number | undefined;
75
+ const objectiveTokens = [...tokens];
76
+ if (objectiveTokens[0] === "--tokens") {
77
+ const rawBudget = objectiveTokens[1];
78
+ if (!rawBudget) {
79
+ return kind === "start"
80
+ ? "Usage: /goal --tokens 100k <goal_to_complete>"
81
+ : `Usage: /goal ${kind} --tokens 100k <goal_to_complete>`;
82
+ }
83
+ const parsedBudget = parseTokenBudget(rawBudget);
84
+ if (parsedBudget === undefined) return `Invalid token budget: ${rawBudget}`;
85
+ tokenBudget = parsedBudget;
86
+ objectiveTokens.splice(0, 2);
87
+ }
88
+ if (objectiveTokens.length === 0) {
89
+ if (kind === "start") return "Usage: /goal <goal_to_complete>";
90
+ return `Usage: /goal ${kind} <goal_to_complete>`;
91
+ }
92
+ return { kind, objective: objectiveTokens.join(" "), tokenBudget };
103
93
  }
104
94
 
105
95
  function tokenize(input: string): string[] {
106
- const tokens: string[] = [];
107
- let current = "";
108
- let quote: '"' | "'" | undefined;
109
- for (const char of input) {
110
- if (quote) {
111
- if (char === quote) quote = undefined;
112
- else current += char;
113
- continue;
114
- }
115
- if (char === '"' || char === "'") {
116
- quote = char;
117
- continue;
118
- }
119
- if (/\s/.test(char)) {
120
- if (current) tokens.push(current);
121
- current = "";
122
- continue;
123
- }
124
- current += char;
125
- }
126
- if (current) tokens.push(current);
127
- return tokens;
96
+ const tokens: string[] = [];
97
+ let current = "";
98
+ let quote: '"' | "'" | undefined;
99
+ for (const char of input) {
100
+ if (quote) {
101
+ if (char === quote) quote = undefined;
102
+ else current += char;
103
+ continue;
104
+ }
105
+ if (char === '"' || char === "'") {
106
+ quote = char;
107
+ continue;
108
+ }
109
+ if (/\s/.test(char)) {
110
+ if (current) tokens.push(current);
111
+ current = "";
112
+ continue;
113
+ }
114
+ current += char;
115
+ }
116
+ if (current) tokens.push(current);
117
+ return tokens;
128
118
  }
129
119
 
130
120
  export function parseTokenBudget(value: string): number | undefined {
131
- const match = /^(\d+(?:\.\d+)?)([km])?$/iu.exec(value.trim());
132
- if (!match) return undefined;
133
- const amount = Number(match[1]);
134
- if (!Number.isFinite(amount) || amount <= 0) return undefined;
135
- const multiplier =
136
- match[2]?.toLowerCase() === "m" ? 1_000_000 : match[2]?.toLowerCase() === "k" ? 1_000 : 1;
137
- return normalizeTokenBudget(Math.floor(amount * multiplier));
121
+ const match = /^(\d+(?:\.\d+)?)([km])?$/iu.exec(value.trim());
122
+ if (!match) return undefined;
123
+ const amount = Number(match[1]);
124
+ if (!Number.isFinite(amount) || amount <= 0) return undefined;
125
+ const multiplier = match[2]?.toLowerCase() === "m" ? 1_000_000 : match[2]?.toLowerCase() === "k" ? 1_000 : 1;
126
+ return normalizeTokenBudget(Math.floor(amount * multiplier));
138
127
  }
139
128
 
140
129
  export function validateObjective(objective: string): string | undefined {
141
- const trimmed = objective.trim();
142
- if (!trimmed) return "Usage: /goal <goal_to_complete>";
143
- if (trimmed.length > MAX_OBJECTIVE_LENGTH) {
144
- return `Goal objective is too long (${trimmed.length}/${MAX_OBJECTIVE_LENGTH} characters). Put long instructions in a file and reference it from /goal instead.`;
145
- }
146
- return undefined;
130
+ const trimmed = objective.trim();
131
+ if (!trimmed) return "Usage: /goal <goal_to_complete>";
132
+ if (trimmed.length > MAX_OBJECTIVE_LENGTH) {
133
+ return `Goal objective is too long (${trimmed.length}/${MAX_OBJECTIVE_LENGTH} characters). Put long instructions in a file and reference it from /goal instead.`;
134
+ }
135
+ return undefined;
147
136
  }
148
137
 
149
138
  function normalizeTokenBudget(value: unknown) {
150
- return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;
139
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;
151
140
  }