@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
package/src/tools.ts CHANGED
@@ -1,56 +1,56 @@
1
1
  import {
2
- DEFAULT_MAX_BYTES,
3
- DEFAULT_MAX_LINES,
4
- defineTool,
5
- type ExtensionAPI,
6
- getMarkdownTheme,
7
- truncateHead,
2
+ DEFAULT_MAX_BYTES,
3
+ DEFAULT_MAX_LINES,
4
+ defineTool,
5
+ type ExtensionAPI,
6
+ getMarkdownTheme,
7
+ truncateHead,
8
8
  } from "@earendil-works/pi-coding-agent";
9
9
  import { Markdown } from "@earendil-works/pi-tui";
10
10
  import { Type } from "typebox";
11
11
  import { notifyTerminal, safeTerminalText } from "./errors.js";
12
12
  import {
13
- formatStatus,
14
- GOAL_BLOCKED_TOOL,
15
- GOAL_COMPLETE_TOOL,
16
- GOAL_WAIT_TOOL,
17
- type GoalRuntime,
18
- goalIdRejectionReason,
19
- isContradictoryCompletionSummary,
20
- MAX_GOAL_ID_LENGTH,
21
- STATUS_KEY,
22
- transitionGoal,
23
- truncateNotification,
13
+ formatStatus,
14
+ GOAL_BLOCKED_TOOL,
15
+ GOAL_COMPLETE_TOOL,
16
+ GOAL_WAIT_TOOL,
17
+ type GoalRuntime,
18
+ goalIdRejectionReason,
19
+ isContradictoryCompletionSummary,
20
+ MAX_GOAL_ID_LENGTH,
21
+ STATUS_KEY,
22
+ transitionGoal,
23
+ truncateNotification,
24
24
  } from "./runtime.js";
25
25
  import {
26
- createGoalWait,
27
- MAX_GOAL_WAIT_DELAY_MS,
28
- MAX_GOAL_WAIT_REASON_LENGTH,
29
- MIN_GOAL_WAIT_DELAY_MS,
30
- resolveGoalWaitDelay,
26
+ createGoalWait,
27
+ MAX_GOAL_WAIT_DELAY_MS,
28
+ MAX_GOAL_WAIT_REASON_LENGTH,
29
+ MIN_GOAL_WAIT_DELAY_MS,
30
+ resolveGoalWaitDelay,
31
31
  } from "./wait.js";
32
32
 
33
33
  interface GoalCompleteDetails {
34
- goal: string;
35
- goal_id: string;
36
- summary: string;
34
+ goal: string;
35
+ goal_id: string;
36
+ summary: string;
37
37
  }
38
38
 
39
39
  interface GoalBlockedDetails {
40
- goal: string;
41
- goal_id: string;
42
- reason: string;
43
- evidence: string;
44
- repeated_turns: number;
40
+ goal: string;
41
+ goal_id: string;
42
+ reason: string;
43
+ evidence: string;
44
+ repeated_turns: number;
45
45
  }
46
46
 
47
47
  interface GoalWaitDetails {
48
- goal: string;
49
- goal_id: string;
50
- reason: string;
51
- requested_resume_after_ms?: number;
52
- resume_after_ms?: number;
53
- resume_at?: number;
48
+ goal: string;
49
+ goal_id: string;
50
+ reason: string;
51
+ requested_resume_after_ms?: number;
52
+ resume_after_ms?: number;
53
+ resume_at?: number;
54
54
  }
55
55
 
56
56
  const MAX_GOAL_TEXT_LENGTH = 4_000;
@@ -59,380 +59,369 @@ const MAX_BLOCKER_REASON_LENGTH = 1_000;
59
59
  const MAX_BLOCKER_EVIDENCE_LENGTH = 4_000;
60
60
 
61
61
  export function registerGoalTools(pi: ExtensionAPI, runtime: GoalRuntime) {
62
- const goalCompleteTool = defineTool({
63
- name: GOAL_COMPLETE_TOOL,
64
- label: "Goal Complete",
65
- description:
66
- "Mark an active /goal complete only when the latest effective Goal contract explicitly says Goal mode is active, supplies the matching current goal_id, and every requirement is verified. Tool visibility alone does not activate Goal mode. Never call for ordinary work, partial progress, blockers, failures, or unverified work.",
67
- parameters: Type.Object({
68
- goal_id: Type.String({
69
- minLength: 1,
70
- maxLength: MAX_GOAL_ID_LENGTH,
71
- description:
72
- "The exact goal_id shown in the current active /goal prompt. Used only to reject stale completion calls from older turns.",
73
- }),
74
- summary: Type.String({
75
- minLength: 1,
76
- maxLength: MAX_COMPLETION_SUMMARY_LENGTH,
77
- description:
78
- "State what was completed and what evidence verified it. Do not use this tool to report partial progress, blockers, failures, or remaining work.",
79
- }),
80
- }),
81
- renderResult(result) {
82
- return renderGoalCompletion(result);
83
- },
84
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
85
- const completedGoal = runtime.activeGoal;
86
- const goal = completedGoal?.text ?? "unknown goal";
87
- const requestedGoalId = typeof params.goal_id === "string" ? params.goal_id.trim() : "";
88
- const summary = typeof params.summary === "string" ? params.summary.trim() : "";
62
+ const goalCompleteTool = defineTool({
63
+ name: GOAL_COMPLETE_TOOL,
64
+ label: "Goal Complete",
65
+ description:
66
+ "Mark an active /goal complete only when the latest effective Goal contract explicitly says Goal mode is active, supplies the matching current goal_id, and every requirement is verified. Tool visibility alone does not activate Goal mode. Never call for ordinary work, partial progress, blockers, failures, or unverified work.",
67
+ parameters: Type.Object({
68
+ goal_id: Type.String({
69
+ minLength: 1,
70
+ maxLength: MAX_GOAL_ID_LENGTH,
71
+ description:
72
+ "The exact goal_id shown in the current active /goal prompt. Used only to reject stale completion calls from older turns.",
73
+ }),
74
+ summary: Type.String({
75
+ minLength: 1,
76
+ maxLength: MAX_COMPLETION_SUMMARY_LENGTH,
77
+ description:
78
+ "State what was completed and what evidence verified it. Do not use this tool to report partial progress, blockers, failures, or remaining work.",
79
+ }),
80
+ }),
81
+ renderResult(result) {
82
+ return renderGoalCompletion(result);
83
+ },
84
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
85
+ const completedGoal = runtime.activeGoal;
86
+ const goal = completedGoal?.text ?? "unknown goal";
87
+ const requestedGoalId = typeof params.goal_id === "string" ? params.goal_id.trim() : "";
88
+ const summary = typeof params.summary === "string" ? params.summary.trim() : "";
89
89
 
90
- if (!completedGoal) {
91
- const rejection = "Goal completion rejected: no active goal.";
92
- notifyTerminal(ctx.ui, rejection, "warning");
90
+ if (!completedGoal) {
91
+ const rejection = "Goal completion rejected: no active goal.";
92
+ notifyTerminal(ctx.ui, rejection, "warning");
93
93
 
94
- return {
95
- content: toolContent(rejection),
96
- details: completionDetails(goal, requestedGoalId, summary),
97
- };
98
- }
99
- const completingDuringBudgetWrapUp = runtime.hasActiveBudgetWrapUp();
100
- if (completedGoal.status === "active" && !runtime.ownsWorkflow(completedGoal)) {
101
- const rejection = "Goal completion rejected: active Goal no longer owns its workflow.";
102
- notifyTerminal(ctx.ui, rejection, "warning");
103
- return {
104
- content: toolContent(rejection),
105
- details: completionDetails(goal, requestedGoalId, summary),
106
- };
107
- }
108
- if (!runtime.canRecordGoalUsage() && !completingDuringBudgetWrapUp) {
109
- const rejection = "Goal completion rejected: current run does not own the active goal.";
110
- notifyTerminal(ctx.ui, rejection, "warning");
111
- return {
112
- content: toolContent(rejection),
113
- details: completionDetails(goal, requestedGoalId, summary),
114
- };
115
- }
116
- const staleGoalRejection = goalIdRejectionReason(completedGoal, requestedGoalId);
117
- if (staleGoalRejection) {
118
- const rejection = `Goal completion rejected: ${staleGoalRejection}.`;
119
- notifyTerminal(ctx.ui, rejection, "warning");
120
- if (completingDuringBudgetWrapUp) {
121
- runtime.recordGoalUsage(completedGoal, ctx);
122
- runtime.persistGoal(completedGoal);
123
- runtime.updateStatus(ctx, completedGoal);
124
- runtime.clearBudgetWrapUp();
125
- }
94
+ return {
95
+ content: toolContent(rejection),
96
+ details: completionDetails(goal, requestedGoalId, summary),
97
+ };
98
+ }
99
+ const completingDuringBudgetWrapUp = runtime.hasActiveBudgetWrapUp();
100
+ if (completedGoal.status === "active" && !runtime.ownsWorkflow(completedGoal)) {
101
+ const rejection = "Goal completion rejected: active Goal no longer owns its workflow.";
102
+ notifyTerminal(ctx.ui, rejection, "warning");
103
+ return {
104
+ content: toolContent(rejection),
105
+ details: completionDetails(goal, requestedGoalId, summary),
106
+ };
107
+ }
108
+ if (!runtime.canRecordGoalUsage() && !completingDuringBudgetWrapUp) {
109
+ const rejection = "Goal completion rejected: current run does not own the active goal.";
110
+ notifyTerminal(ctx.ui, rejection, "warning");
111
+ return {
112
+ content: toolContent(rejection),
113
+ details: completionDetails(goal, requestedGoalId, summary),
114
+ };
115
+ }
116
+ const staleGoalRejection = goalIdRejectionReason(completedGoal, requestedGoalId);
117
+ if (staleGoalRejection) {
118
+ const rejection = `Goal completion rejected: ${staleGoalRejection}.`;
119
+ notifyTerminal(ctx.ui, rejection, "warning");
120
+ if (completingDuringBudgetWrapUp) {
121
+ runtime.recordGoalUsage(completedGoal, ctx);
122
+ runtime.persistGoal(completedGoal);
123
+ runtime.updateStatus(ctx, completedGoal);
124
+ runtime.clearBudgetWrapUp();
125
+ }
126
126
 
127
- return {
128
- content: toolContent(rejection),
129
- details: completionDetails(goal, requestedGoalId, summary),
130
- terminate: completingDuringBudgetWrapUp || undefined,
131
- };
132
- }
133
- if (completedGoal.status !== "active" && !completingDuringBudgetWrapUp) {
134
- const rejection = `Goal completion rejected: goal is ${completedGoal.status}, not active.`;
135
- notifyTerminal(ctx.ui, rejection, "warning");
127
+ return {
128
+ content: toolContent(rejection),
129
+ details: completionDetails(goal, requestedGoalId, summary),
130
+ terminate: completingDuringBudgetWrapUp || undefined,
131
+ };
132
+ }
133
+ if (completedGoal.status !== "active" && !completingDuringBudgetWrapUp) {
134
+ const rejection = `Goal completion rejected: goal is ${completedGoal.status}, not active.`;
135
+ notifyTerminal(ctx.ui, rejection, "warning");
136
136
 
137
- return {
138
- content: toolContent(rejection),
139
- details: completionDetails(goal, requestedGoalId, summary),
140
- };
141
- }
137
+ return {
138
+ content: toolContent(rejection),
139
+ details: completionDetails(goal, requestedGoalId, summary),
140
+ };
141
+ }
142
142
 
143
- const rejectionReason = !summary
144
- ? "summary is empty"
145
- : summary.length > MAX_COMPLETION_SUMMARY_LENGTH
146
- ? "summary is too long"
147
- : isContradictoryCompletionSummary(summary)
148
- ? "summary says the goal is not complete"
149
- : undefined;
150
- if (rejectionReason) {
151
- runtime.recordGoalUsage(completedGoal, ctx);
152
- runtime.persistGoal(completedGoal);
153
- runtime.updateStatus(ctx, completedGoal);
154
- const rejection = `Goal completion rejected: ${rejectionReason}.`;
155
- notifyTerminal(ctx.ui, rejection, "warning");
156
- if (completingDuringBudgetWrapUp) runtime.clearBudgetWrapUp();
143
+ const rejectionReason = !summary
144
+ ? "summary is empty"
145
+ : summary.length > MAX_COMPLETION_SUMMARY_LENGTH
146
+ ? "summary is too long"
147
+ : isContradictoryCompletionSummary(summary)
148
+ ? "summary says the goal is not complete"
149
+ : undefined;
150
+ if (rejectionReason) {
151
+ runtime.recordGoalUsage(completedGoal, ctx);
152
+ runtime.persistGoal(completedGoal);
153
+ runtime.updateStatus(ctx, completedGoal);
154
+ const rejection = `Goal completion rejected: ${rejectionReason}.`;
155
+ notifyTerminal(ctx.ui, rejection, "warning");
156
+ if (completingDuringBudgetWrapUp) runtime.clearBudgetWrapUp();
157
157
 
158
- return {
159
- content: toolContent(rejection),
160
- details: completionDetails(goal, requestedGoalId, summary),
161
- terminate: completingDuringBudgetWrapUp || undefined,
162
- };
163
- }
158
+ return {
159
+ content: toolContent(rejection),
160
+ details: completionDetails(goal, requestedGoalId, summary),
161
+ terminate: completingDuringBudgetWrapUp || undefined,
162
+ };
163
+ }
164
164
 
165
- runtime.clearGoalWaitTimer();
166
- runtime.activeGoal = transitionGoal(completedGoal, "complete");
167
- runtime.setCompletionSummary(runtime.activeGoal.id, summary);
168
- runtime.recordGoalUsage(runtime.activeGoal, ctx);
169
- runtime.persistGoal(runtime.activeGoal);
165
+ runtime.clearGoalWaitTimer();
166
+ runtime.activeGoal = transitionGoal(completedGoal, "complete");
167
+ runtime.setCompletionSummary(runtime.activeGoal.id, summary);
168
+ runtime.recordGoalUsage(runtime.activeGoal, ctx);
169
+ runtime.persistGoal(runtime.activeGoal);
170
170
 
171
- ctx.ui.setStatus(STATUS_KEY, formatStatus(runtime.activeGoal));
172
- runtime.clearCompletedGoal(ctx);
173
- runtime.showCompletionStatus(ctx);
174
- notifyTerminal(ctx.ui, `Goal complete: ${goal}`, "info");
171
+ ctx.ui.setStatus(STATUS_KEY, formatStatus(runtime.activeGoal));
172
+ runtime.clearCompletedGoal(ctx);
173
+ runtime.showCompletionStatus(ctx);
174
+ notifyTerminal(ctx.ui, `Goal complete: ${goal}`, "info");
175
175
 
176
- return {
177
- content: toolContent(`Goal complete: ${summary}`),
178
- details: completionDetails(goal, requestedGoalId, summary),
179
- terminate: true,
180
- };
181
- },
182
- });
176
+ return {
177
+ content: toolContent(`Goal complete: ${summary}`),
178
+ details: completionDetails(goal, requestedGoalId, summary),
179
+ terminate: true,
180
+ };
181
+ },
182
+ });
183
183
 
184
- const goalBlockedTool = defineTool({
185
- name: GOAL_BLOCKED_TOOL,
186
- label: "Goal Blocked",
187
- description:
188
- "Stop an active /goal only when the latest effective Goal contract explicitly says Goal mode is active, supplies the matching current goal_id, and the same evidenced external blocker recurred for at least three consecutive Goal turns. Tool visibility alone does not activate Goal mode. Never call for ordinary clarification, uncertainty, incomplete work, or recoverable failures.",
189
- parameters: Type.Object({
190
- goal_id: Type.String({
191
- minLength: 1,
192
- maxLength: MAX_GOAL_ID_LENGTH,
193
- description: "The exact goal_id shown in the current active /goal prompt.",
194
- }),
195
- reason: Type.String({
196
- minLength: 1,
197
- maxLength: MAX_BLOCKER_REASON_LENGTH,
198
- description: "The specific user or external action required to unblock the goal.",
199
- }),
200
- evidence: Type.String({
201
- minLength: 1,
202
- maxLength: MAX_BLOCKER_EVIDENCE_LENGTH,
203
- description: "Concrete evidence from the repeated attempts that proves the impasse.",
204
- }),
205
- repeated_turns: Type.Integer({
206
- minimum: 3,
207
- description: "Number of separate turns spent trying to resolve this same blocker.",
208
- }),
209
- }),
210
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
211
- const blockedGoal = runtime.activeGoal;
212
- const goal = blockedGoal?.text ?? "unknown goal";
213
- const requestedGoalId = typeof params.goal_id === "string" ? params.goal_id.trim() : "";
214
- const reason = typeof params.reason === "string" ? params.reason.trim() : "";
215
- const evidence = typeof params.evidence === "string" ? params.evidence.trim() : "";
216
- const repeatedTurns =
217
- typeof params.repeated_turns === "number" ? params.repeated_turns : Number.NaN;
218
- const reject = (rejectionReason: string, terminate = false) => {
219
- const rejection = `goal_blocked rejected: ${rejectionReason}.`;
220
- notifyTerminal(ctx.ui, rejection, "warning");
221
- return {
222
- content: toolContent(rejection),
223
- details: blockerDetails(goal, requestedGoalId, reason, evidence, repeatedTurns),
224
- ...(terminate ? { terminate: true as const } : {}),
225
- };
226
- };
184
+ const goalBlockedTool = defineTool({
185
+ name: GOAL_BLOCKED_TOOL,
186
+ label: "Goal Blocked",
187
+ description:
188
+ "Stop an active /goal only when the latest effective Goal contract explicitly says Goal mode is active, supplies the matching current goal_id, and the same evidenced external blocker recurred for at least three consecutive Goal turns. Tool visibility alone does not activate Goal mode. Never call for ordinary clarification, uncertainty, incomplete work, or recoverable failures.",
189
+ parameters: Type.Object({
190
+ goal_id: Type.String({
191
+ minLength: 1,
192
+ maxLength: MAX_GOAL_ID_LENGTH,
193
+ description: "The exact goal_id shown in the current active /goal prompt.",
194
+ }),
195
+ reason: Type.String({
196
+ minLength: 1,
197
+ maxLength: MAX_BLOCKER_REASON_LENGTH,
198
+ description: "The specific user or external action required to unblock the goal.",
199
+ }),
200
+ evidence: Type.String({
201
+ minLength: 1,
202
+ maxLength: MAX_BLOCKER_EVIDENCE_LENGTH,
203
+ description: "Concrete evidence from the repeated attempts that proves the impasse.",
204
+ }),
205
+ repeated_turns: Type.Integer({
206
+ minimum: 3,
207
+ description: "Number of separate turns spent trying to resolve this same blocker.",
208
+ }),
209
+ }),
210
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
211
+ const blockedGoal = runtime.activeGoal;
212
+ const goal = blockedGoal?.text ?? "unknown goal";
213
+ const requestedGoalId = typeof params.goal_id === "string" ? params.goal_id.trim() : "";
214
+ const reason = typeof params.reason === "string" ? params.reason.trim() : "";
215
+ const evidence = typeof params.evidence === "string" ? params.evidence.trim() : "";
216
+ const repeatedTurns = typeof params.repeated_turns === "number" ? params.repeated_turns : Number.NaN;
217
+ const reject = (rejectionReason: string, terminate = false) => {
218
+ const rejection = `goal_blocked rejected: ${rejectionReason}.`;
219
+ notifyTerminal(ctx.ui, rejection, "warning");
220
+ return {
221
+ content: toolContent(rejection),
222
+ details: blockerDetails(goal, requestedGoalId, reason, evidence, repeatedTurns),
223
+ ...(terminate ? { terminate: true as const } : {}),
224
+ };
225
+ };
227
226
 
228
- if (!blockedGoal) return reject("no active goal");
229
- if (!runtime.canRecordGoalUsage()) {
230
- return reject("current run does not own the active goal");
231
- }
232
- const staleGoalRejection = goalIdRejectionReason(blockedGoal, requestedGoalId);
233
- if (staleGoalRejection) return reject(staleGoalRejection);
234
- if (blockedGoal.status !== "active") {
235
- return reject(`goal is ${blockedGoal.status}, not active`);
236
- }
237
- if (!runtime.ownsWorkflow(blockedGoal))
238
- return reject("active Goal no longer owns its workflow");
239
- if (!reason) return reject("reason is empty");
240
- if (reason.length > MAX_BLOCKER_REASON_LENGTH) return reject("reason is too long");
241
- if (!evidence) return reject("evidence is empty");
242
- if (evidence.length > MAX_BLOCKER_EVIDENCE_LENGTH) return reject("evidence is too long");
243
- if (!Number.isInteger(repeatedTurns)) return reject("repeated_turns must be a whole number");
244
- if (repeatedTurns < 3) return reject("repeated_turns must be at least 3");
227
+ if (!blockedGoal) return reject("no active goal");
228
+ if (!runtime.canRecordGoalUsage()) {
229
+ return reject("current run does not own the active goal");
230
+ }
231
+ const staleGoalRejection = goalIdRejectionReason(blockedGoal, requestedGoalId);
232
+ if (staleGoalRejection) return reject(staleGoalRejection);
233
+ if (blockedGoal.status !== "active") {
234
+ return reject(`goal is ${blockedGoal.status}, not active`);
235
+ }
236
+ if (!runtime.ownsWorkflow(blockedGoal)) return reject("active Goal no longer owns its workflow");
237
+ if (!reason) return reject("reason is empty");
238
+ if (reason.length > MAX_BLOCKER_REASON_LENGTH) return reject("reason is too long");
239
+ if (!evidence) return reject("evidence is empty");
240
+ if (evidence.length > MAX_BLOCKER_EVIDENCE_LENGTH) return reject("evidence is too long");
241
+ if (!Number.isInteger(repeatedTurns)) return reject("repeated_turns must be a whole number");
242
+ if (repeatedTurns < 3) return reject("repeated_turns must be at least 3");
245
243
 
246
- const stoppedGoal = runtime.stopActiveGoal(ctx, {
247
- kind: "blocker_report",
248
- expectedGoalId: blockedGoal.id,
249
- reason,
250
- });
251
- if (!stoppedGoal) return reject("active goal changed before blocker transition");
252
- notifyTerminal(ctx.ui, `Goal blocked: ${truncateNotification(reason)}`, "warning");
244
+ const stoppedGoal = runtime.stopActiveGoal(ctx, {
245
+ kind: "blocker_report",
246
+ expectedGoalId: blockedGoal.id,
247
+ reason,
248
+ });
249
+ if (!stoppedGoal) return reject("active goal changed before blocker transition");
250
+ notifyTerminal(ctx.ui, `Goal blocked: ${truncateNotification(reason)}`, "warning");
253
251
 
254
- return {
255
- content: toolContent(`Goal blocked: ${reason}`),
256
- details: blockerDetails(goal, requestedGoalId, reason, evidence, repeatedTurns),
257
- terminate: true,
258
- };
259
- },
260
- });
252
+ return {
253
+ content: toolContent(`Goal blocked: ${reason}`),
254
+ details: blockerDetails(goal, requestedGoalId, reason, evidence, repeatedTurns),
255
+ terminate: true,
256
+ };
257
+ },
258
+ });
261
259
 
262
- const goalWaitTool = defineTool({
263
- name: GOAL_WAIT_TOOL,
264
- label: "Goal Wait",
265
- description: `Keep an active /goal quiet only when the latest effective Goal contract explicitly says Goal mode is active, supplies the matching current goal_id, and progress depends on an arranged external wake event or one safety deadline. Tool visibility alone does not activate Goal mode. Call goal_wait alone. Requests below ${MIN_GOAL_WAIT_DELAY_MS}ms are clamped to ${MIN_GOAL_WAIT_DELAY_MS}ms. Never call for ordinary unfinished work.`,
266
- parameters: Type.Object({
267
- goal_id: Type.String({
268
- minLength: 1,
269
- maxLength: MAX_GOAL_ID_LENGTH,
270
- description: "The exact goal_id shown in the current active /goal prompt.",
271
- }),
272
- reason: Type.String({
273
- minLength: 1,
274
- maxLength: MAX_GOAL_WAIT_REASON_LENGTH,
275
- description: "Why the goal is waiting and which external event should wake it.",
276
- }),
277
- resume_after_ms: Type.Optional(
278
- Type.Integer({
279
- minimum: 1,
280
- maximum: MAX_GOAL_WAIT_DELAY_MS,
281
- description: `Optional safety deadline in milliseconds that requests one continuation if no wake message arrives. Values below ${MIN_GOAL_WAIT_DELAY_MS} are accepted but clamped to ${MIN_GOAL_WAIT_DELAY_MS}.`,
282
- }),
283
- ),
284
- }),
285
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
286
- const activeGoal = runtime.activeGoal;
287
- const goal = activeGoal?.text ?? "unknown goal";
288
- const requestedGoalId = typeof params.goal_id === "string" ? params.goal_id.trim() : "";
289
- const reason = typeof params.reason === "string" ? params.reason.trim() : "";
290
- const resumeAfterMs =
291
- typeof params.resume_after_ms === "number" ? params.resume_after_ms : undefined;
292
- const reject = (rejectionReason: string) => {
293
- const rejection = `goal_wait rejected: ${rejectionReason}.`;
294
- notifyTerminal(ctx.ui, rejection, "warning");
295
- return {
296
- content: toolContent(rejection),
297
- details: waitDetails(goal, requestedGoalId, reason, resumeAfterMs),
298
- };
299
- };
260
+ const goalWaitTool = defineTool({
261
+ name: GOAL_WAIT_TOOL,
262
+ label: "Goal Wait",
263
+ description: `Keep an active /goal quiet only when the latest effective Goal contract explicitly says Goal mode is active, supplies the matching current goal_id, and progress depends on an arranged external wake event or one safety deadline. Tool visibility alone does not activate Goal mode. Call goal_wait alone. Requests below ${MIN_GOAL_WAIT_DELAY_MS}ms are clamped to ${MIN_GOAL_WAIT_DELAY_MS}ms. Never call for ordinary unfinished work.`,
264
+ parameters: Type.Object({
265
+ goal_id: Type.String({
266
+ minLength: 1,
267
+ maxLength: MAX_GOAL_ID_LENGTH,
268
+ description: "The exact goal_id shown in the current active /goal prompt.",
269
+ }),
270
+ reason: Type.String({
271
+ minLength: 1,
272
+ maxLength: MAX_GOAL_WAIT_REASON_LENGTH,
273
+ description: "Why the goal is waiting and which external event should wake it.",
274
+ }),
275
+ resume_after_ms: Type.Optional(
276
+ Type.Integer({
277
+ minimum: 1,
278
+ maximum: MAX_GOAL_WAIT_DELAY_MS,
279
+ description: `Optional safety deadline in milliseconds that requests one continuation if no wake message arrives. Values below ${MIN_GOAL_WAIT_DELAY_MS} are accepted but clamped to ${MIN_GOAL_WAIT_DELAY_MS}.`,
280
+ }),
281
+ ),
282
+ }),
283
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
284
+ const activeGoal = runtime.activeGoal;
285
+ const goal = activeGoal?.text ?? "unknown goal";
286
+ const requestedGoalId = typeof params.goal_id === "string" ? params.goal_id.trim() : "";
287
+ const reason = typeof params.reason === "string" ? params.reason.trim() : "";
288
+ const resumeAfterMs = typeof params.resume_after_ms === "number" ? params.resume_after_ms : undefined;
289
+ const reject = (rejectionReason: string) => {
290
+ const rejection = `goal_wait rejected: ${rejectionReason}.`;
291
+ notifyTerminal(ctx.ui, rejection, "warning");
292
+ return {
293
+ content: toolContent(rejection),
294
+ details: waitDetails(goal, requestedGoalId, reason, resumeAfterMs),
295
+ };
296
+ };
300
297
 
301
- if (!activeGoal) return reject("no active goal");
302
- if (!runtime.canRecordGoalUsage()) {
303
- return reject("current run does not own the active goal");
304
- }
305
- const staleGoalRejection = goalIdRejectionReason(activeGoal, requestedGoalId);
306
- if (staleGoalRejection) return reject(staleGoalRejection);
307
- if (activeGoal.status !== "active") {
308
- return reject(`goal is ${activeGoal.status}, not active`);
309
- }
310
- if (!runtime.ownsWorkflow(activeGoal))
311
- return reject("active Goal no longer owns its workflow");
312
- if (activeGoal.waiting) return reject("goal is already waiting");
313
- if (!reason) return reject("reason is empty");
314
- if (reason.length > MAX_GOAL_WAIT_REASON_LENGTH) return reject("reason is too long");
315
- if (
316
- resumeAfterMs !== undefined &&
317
- (!Number.isInteger(resumeAfterMs) ||
318
- resumeAfterMs < 1 ||
319
- resumeAfterMs > MAX_GOAL_WAIT_DELAY_MS)
320
- ) {
321
- return reject(`resume_after_ms must be a whole number from 1 to ${MAX_GOAL_WAIT_DELAY_MS}`);
322
- }
298
+ if (!activeGoal) return reject("no active goal");
299
+ if (!runtime.canRecordGoalUsage()) {
300
+ return reject("current run does not own the active goal");
301
+ }
302
+ const staleGoalRejection = goalIdRejectionReason(activeGoal, requestedGoalId);
303
+ if (staleGoalRejection) return reject(staleGoalRejection);
304
+ if (activeGoal.status !== "active") {
305
+ return reject(`goal is ${activeGoal.status}, not active`);
306
+ }
307
+ if (!runtime.ownsWorkflow(activeGoal)) return reject("active Goal no longer owns its workflow");
308
+ if (activeGoal.waiting) return reject("goal is already waiting");
309
+ if (!reason) return reject("reason is empty");
310
+ if (reason.length > MAX_GOAL_WAIT_REASON_LENGTH) return reject("reason is too long");
311
+ if (
312
+ resumeAfterMs !== undefined &&
313
+ (!Number.isInteger(resumeAfterMs) || resumeAfterMs < 1 || resumeAfterMs > MAX_GOAL_WAIT_DELAY_MS)
314
+ ) {
315
+ return reject(`resume_after_ms must be a whole number from 1 to ${MAX_GOAL_WAIT_DELAY_MS}`);
316
+ }
323
317
 
324
- const { requestedMs, effectiveMs } = resolveGoalWaitDelay(resumeAfterMs);
325
- const waiting = createGoalWait(reason, resumeAfterMs);
326
- const waitingGoal = runtime.enterGoalWait(ctx, activeGoal.id, waiting);
327
- if (!waitingGoal) return reject("active goal changed before waiting transition");
328
- const clamped = requestedMs !== undefined && effectiveMs !== requestedMs;
329
- notifyTerminal(ctx.ui, `Goal waiting: ${truncateNotification(reason)}`, "info");
330
- return {
331
- content: toolContent(
332
- clamped
333
- ? `Goal waiting: ${reason}\nRequested resume_after_ms ${requestedMs} was clamped to ${effectiveMs}.`
334
- : `Goal waiting: ${reason}`,
335
- ),
336
- details: waitDetails(
337
- goal,
338
- requestedGoalId,
339
- reason,
340
- effectiveMs,
341
- waiting.resumeAt,
342
- clamped ? requestedMs : undefined,
343
- ),
344
- terminate: true,
345
- };
346
- },
347
- });
318
+ const { requestedMs, effectiveMs } = resolveGoalWaitDelay(resumeAfterMs);
319
+ const waiting = createGoalWait(reason, resumeAfterMs);
320
+ const waitingGoal = runtime.enterGoalWait(ctx, activeGoal.id, waiting);
321
+ if (!waitingGoal) return reject("active goal changed before waiting transition");
322
+ const clamped = requestedMs !== undefined && effectiveMs !== requestedMs;
323
+ notifyTerminal(ctx.ui, `Goal waiting: ${truncateNotification(reason)}`, "info");
324
+ return {
325
+ content: toolContent(
326
+ clamped
327
+ ? `Goal waiting: ${reason}\nRequested resume_after_ms ${requestedMs} was clamped to ${effectiveMs}.`
328
+ : `Goal waiting: ${reason}`,
329
+ ),
330
+ details: waitDetails(
331
+ goal,
332
+ requestedGoalId,
333
+ reason,
334
+ effectiveMs,
335
+ waiting.resumeAt,
336
+ clamped ? requestedMs : undefined,
337
+ ),
338
+ terminate: true,
339
+ };
340
+ },
341
+ });
348
342
 
349
- pi.registerTool(goalCompleteTool);
350
- pi.registerTool(goalBlockedTool);
351
- pi.registerTool(goalWaitTool);
343
+ pi.registerTool(goalCompleteTool);
344
+ pi.registerTool(goalBlockedTool);
345
+ pi.registerTool(goalWaitTool);
352
346
  }
353
347
 
354
348
  interface GoalCompletionRenderResult {
355
- content: Array<{ type: string; text?: string }>;
356
- details?: unknown;
349
+ content: Array<{ type: string; text?: string }>;
350
+ details?: unknown;
357
351
  }
358
352
 
359
353
  export function goalCompletionMarkdown(result: GoalCompletionRenderResult) {
360
- const content = result.content
361
- .filter((block) => block.type === "text" && typeof block.text === "string")
362
- .map((block) => block.text)
363
- .join("\n")
364
- .trim();
365
- const completionPrefix = "Goal complete:";
366
- if (!content.startsWith(completionPrefix)) return content;
354
+ const content = result.content
355
+ .filter((block) => block.type === "text" && typeof block.text === "string")
356
+ .map((block) => block.text)
357
+ .join("\n")
358
+ .trim();
359
+ const completionPrefix = "Goal complete:";
360
+ if (!content.startsWith(completionPrefix)) return content;
367
361
 
368
- const details = result.details;
369
- const summary =
370
- details &&
371
- typeof details === "object" &&
372
- "summary" in details &&
373
- typeof details.summary === "string"
374
- ? details.summary
375
- : content.slice(completionPrefix.length);
376
- const safeSummary = safeTerminalText(summary);
377
- return safeSummary ? `**Goal complete**\n\n${safeSummary}` : "**Goal complete**";
362
+ const details = result.details;
363
+ const summary =
364
+ details && typeof details === "object" && "summary" in details && typeof details.summary === "string"
365
+ ? details.summary
366
+ : content.slice(completionPrefix.length);
367
+ const safeSummary = safeTerminalText(summary);
368
+ return safeSummary ? `**Goal complete**\n\n${safeSummary}` : "**Goal complete**";
378
369
  }
379
370
 
380
371
  export function renderGoalCompletion(result: GoalCompletionRenderResult) {
381
- return new Markdown(goalCompletionMarkdown(result), 0, 0, getMarkdownTheme());
372
+ return new Markdown(goalCompletionMarkdown(result), 0, 0, getMarkdownTheme());
382
373
  }
383
374
 
384
375
  function toolContent(text: string) {
385
- return [
386
- {
387
- type: "text" as const,
388
- text: truncateHead(safeTerminalText(text), {
389
- maxBytes: DEFAULT_MAX_BYTES,
390
- maxLines: DEFAULT_MAX_LINES,
391
- }).content,
392
- },
393
- ];
376
+ return [
377
+ {
378
+ type: "text" as const,
379
+ text: truncateHead(safeTerminalText(text), {
380
+ maxBytes: DEFAULT_MAX_BYTES,
381
+ maxLines: DEFAULT_MAX_LINES,
382
+ }).content,
383
+ },
384
+ ];
394
385
  }
395
386
 
396
387
  function completionDetails(goal: string, goalId: string, summary: string): GoalCompleteDetails {
397
- return {
398
- goal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),
399
- goal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),
400
- summary: summary.slice(0, MAX_COMPLETION_SUMMARY_LENGTH),
401
- };
388
+ return {
389
+ goal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),
390
+ goal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),
391
+ summary: summary.slice(0, MAX_COMPLETION_SUMMARY_LENGTH),
392
+ };
402
393
  }
403
394
 
404
395
  function blockerDetails(
405
- goal: string,
406
- goalId: string,
407
- reason: string,
408
- evidence: string,
409
- repeatedTurns: number,
396
+ goal: string,
397
+ goalId: string,
398
+ reason: string,
399
+ evidence: string,
400
+ repeatedTurns: number,
410
401
  ): GoalBlockedDetails {
411
- return {
412
- goal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),
413
- goal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),
414
- reason: reason.slice(0, MAX_BLOCKER_REASON_LENGTH),
415
- evidence: evidence.slice(0, MAX_BLOCKER_EVIDENCE_LENGTH),
416
- repeated_turns: Number.isFinite(repeatedTurns) ? repeatedTurns : 0,
417
- };
402
+ return {
403
+ goal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),
404
+ goal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),
405
+ reason: reason.slice(0, MAX_BLOCKER_REASON_LENGTH),
406
+ evidence: evidence.slice(0, MAX_BLOCKER_EVIDENCE_LENGTH),
407
+ repeated_turns: Number.isFinite(repeatedTurns) ? repeatedTurns : 0,
408
+ };
418
409
  }
419
410
 
420
411
  function waitDetails(
421
- goal: string,
422
- goalId: string,
423
- reason: string,
424
- resumeAfterMs: number | undefined,
425
- resumeAt?: number,
426
- requestedResumeAfterMs?: number,
412
+ goal: string,
413
+ goalId: string,
414
+ reason: string,
415
+ resumeAfterMs: number | undefined,
416
+ resumeAt?: number,
417
+ requestedResumeAfterMs?: number,
427
418
  ): GoalWaitDetails {
428
- return {
429
- goal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),
430
- goal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),
431
- reason: reason.slice(0, MAX_GOAL_WAIT_REASON_LENGTH),
432
- ...(requestedResumeAfterMs === undefined
433
- ? {}
434
- : { requested_resume_after_ms: requestedResumeAfterMs }),
435
- ...(resumeAfterMs === undefined ? {} : { resume_after_ms: resumeAfterMs }),
436
- ...(resumeAt === undefined ? {} : { resume_at: resumeAt }),
437
- };
419
+ return {
420
+ goal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),
421
+ goal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),
422
+ reason: reason.slice(0, MAX_GOAL_WAIT_REASON_LENGTH),
423
+ ...(requestedResumeAfterMs === undefined ? {} : { requested_resume_after_ms: requestedResumeAfterMs }),
424
+ ...(resumeAfterMs === undefined ? {} : { resume_after_ms: resumeAfterMs }),
425
+ ...(resumeAt === undefined ? {} : { resume_at: resumeAt }),
426
+ };
438
427
  }