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