@narumitw/pi-goal 0.48.0 → 0.49.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -20
- package/package.json +7 -6
- package/src/command-registration.ts +92 -0
- package/src/commands.ts +79 -52
- package/src/goal.ts +11 -1108
- package/src/lifecycle.ts +662 -0
- package/src/menu.ts +437 -71
- package/src/runtime.ts +210 -182
- package/src/settings-ui.ts +58 -43
- package/src/settings.ts +1 -1
- package/src/tool-policy.ts +178 -0
- package/src/tools.ts +316 -0
package/src/goal.ts
CHANGED
|
@@ -1,1123 +1,26 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { currentTokenTotal } from "./accounting.js";
|
|
4
|
-
import { completeGoalArguments, parseCommand } from "./command.js";
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { registerGoalCommand } from "./command-registration.js";
|
|
5
3
|
import { GoalCommandController } from "./commands.js";
|
|
6
|
-
import {
|
|
7
|
-
import { type ActiveGoal, loadGoalStateFromSession } from "./persistence.js";
|
|
8
|
-
import { buildGoalPrompt, buildGoalSystemPrompt } from "./prompts.js";
|
|
9
|
-
import { activateQueuedGoal } from "./queue.js";
|
|
4
|
+
import { registerGoalLifecycle } from "./lifecycle.js";
|
|
10
5
|
import { GoalRunController } from "./run-protocol.js";
|
|
11
|
-
import {
|
|
12
|
-
|
|
13
|
-
abortCurrentTurn,
|
|
14
|
-
blocksStaleGoalToolCalls,
|
|
15
|
-
findFinalAssistantMessage,
|
|
16
|
-
formatError,
|
|
17
|
-
formatStatus,
|
|
18
|
-
GOAL_BLOCKED_TOOL,
|
|
19
|
-
GOAL_COMPLETE_TOOL,
|
|
20
|
-
GoalRuntime,
|
|
21
|
-
goalIdRejectionReason,
|
|
22
|
-
incrementGoal,
|
|
23
|
-
isContradictoryCompletionSummary,
|
|
24
|
-
isGoalContextOverflow,
|
|
25
|
-
isRetryableGoalInterruption,
|
|
26
|
-
isUsageLimitedGoalInterruption,
|
|
27
|
-
resetGoalSafetyEpoch,
|
|
28
|
-
STATUS_KEY,
|
|
29
|
-
type StatusContext,
|
|
30
|
-
transitionGoal,
|
|
31
|
-
truncateNotification,
|
|
32
|
-
} from "./runtime.js";
|
|
33
|
-
import { hasAssistantToolCall } from "./safety.js";
|
|
34
|
-
import { DEFAULT_GOAL_SETTINGS, readGoalSettings } from "./settings.js";
|
|
35
|
-
import { showGoalSettings } from "./settings-ui.js";
|
|
36
|
-
|
|
37
|
-
// goal.ts remains the Pi-facing composition root despite its size because tool contracts and
|
|
38
|
-
// lifecycle-event registration share order-sensitive wiring. Per-session mechanisms live in
|
|
39
|
-
// runtime.ts, while user-command transitions live in commands.ts; each factory stays isolated.
|
|
40
|
-
|
|
41
|
-
interface GoalCompleteDetails {
|
|
42
|
-
goal: string;
|
|
43
|
-
goal_id: string;
|
|
44
|
-
summary: string;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
interface GoalBlockedDetails {
|
|
48
|
-
goal: string;
|
|
49
|
-
goal_id: string;
|
|
50
|
-
reason: string;
|
|
51
|
-
evidence: string;
|
|
52
|
-
repeated_turns: number;
|
|
53
|
-
}
|
|
6
|
+
import { GoalRuntime } from "./runtime.js";
|
|
7
|
+
import { registerGoalTools } from "./tools.js";
|
|
54
8
|
|
|
55
9
|
interface GoalOptions {
|
|
56
10
|
settingsPath?: string;
|
|
57
11
|
}
|
|
58
12
|
|
|
59
|
-
const EXPERIMENTAL_GOALS_WARNING =
|
|
60
|
-
"Experimental ordered goals are enabled for pi-goal. Queue behavior and persisted state may change.";
|
|
61
|
-
const MAX_BLOCKER_REASON_LENGTH = 1_000;
|
|
62
|
-
const MAX_BLOCKER_EVIDENCE_LENGTH = 4_000;
|
|
63
|
-
|
|
64
|
-
// Cohesion justification: command, tool, continuation, and lifecycle handlers coordinate one
|
|
65
|
-
// guarded Goal state machine whose ordering and stale-turn invariants share the same closures.
|
|
66
13
|
function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
|
|
67
14
|
const runtime = new GoalRuntime(pi);
|
|
68
15
|
const commands = new GoalCommandController(runtime);
|
|
69
16
|
const runController = new GoalRunController(runtime, commands);
|
|
70
|
-
runController.register(pi);
|
|
71
|
-
|
|
72
|
-
// Bind per-factory runtime operations once so event orchestration stays concise
|
|
73
|
-
// without reintroducing module-global mutable state.
|
|
74
|
-
const clearCompletionStatusTimer = runtime.clearCompletionStatusTimer.bind(runtime);
|
|
75
|
-
const clearContinuationTracking = runtime.clearContinuationTracking.bind(runtime);
|
|
76
|
-
const clearPendingGoalPrompts = runtime.clearPendingGoalPrompts.bind(runtime);
|
|
77
|
-
const clearGoalRecovery = runtime.clearGoalRecovery.bind(runtime);
|
|
78
|
-
const clearBudgetWrapUp = runtime.clearBudgetWrapUp.bind(runtime);
|
|
79
|
-
const clearStaleGoalToolCallBlock = runtime.clearStaleGoalToolCallBlock.bind(runtime);
|
|
80
|
-
const persistGoal = runtime.persistGoal.bind(runtime);
|
|
81
|
-
const updateGoalUsage = runtime.recordGoalUsage.bind(runtime);
|
|
82
|
-
const updateStatus = runtime.updateStatus.bind(runtime);
|
|
83
|
-
const limitActiveGoalForBudget = runtime.limitActiveGoalForBudget.bind(runtime);
|
|
84
|
-
const hideGoalToolsIfLocked = runtime.hideGoalToolsIfLocked.bind(runtime);
|
|
85
|
-
const goalToolsAvailable = runtime.goalToolsAvailable.bind(runtime);
|
|
86
|
-
const pauseGoalForUnavailableTools = runtime.pauseGoalForUnavailableTools.bind(runtime);
|
|
87
|
-
const isPiOwnedCompactionRetry = runtime.isPiOwnedCompactionRetry.bind(runtime);
|
|
88
|
-
const requestContinuation = runtime.requestContinuation.bind(runtime);
|
|
89
|
-
const dispatchContinuationIfSettled = runtime.dispatchContinuationIfSettled.bind(runtime);
|
|
90
|
-
const keepBudgetWrapUpMessage = runtime.keepBudgetWrapUpMessage.bind(runtime);
|
|
91
|
-
const isGoalToolName = runtime.isGoalToolName.bind(runtime);
|
|
92
|
-
const queueBudgetWrapUp = runtime.queueBudgetWrapUp.bind(runtime);
|
|
93
|
-
const clearGoalRecoveryForGoal = runtime.clearGoalRecoveryForGoal.bind(runtime);
|
|
94
|
-
const blockStaleGoalToolCalls = runtime.blockStaleGoalToolCalls.bind(runtime);
|
|
95
|
-
const cancelContinuationWork = runtime.cancelContinuationWork.bind(runtime);
|
|
96
|
-
const consumeCancelledContinuationPrompt =
|
|
97
|
-
runtime.consumeCancelledContinuationPrompt.bind(runtime);
|
|
98
|
-
const consumeStaleOwnedGoalPrompt = runtime.consumeStaleOwnedGoalPrompt.bind(runtime);
|
|
99
|
-
const consumePendingGoalPrompt = runtime.consumeOwnedGoalPrompt.bind(runtime);
|
|
100
|
-
const markContinuationStarted = runtime.markContinuationStarted.bind(runtime);
|
|
101
|
-
const hasContinuationWorkForGoal = runtime.hasContinuationWorkForGoal.bind(runtime);
|
|
102
|
-
const recordAutomaticTurn = runtime.recordAutomaticTurn.bind(runtime);
|
|
103
|
-
const recordAutomaticRunProgress = runtime.recordAutomaticRunProgress.bind(runtime);
|
|
104
|
-
const enforceAutomaticTurnLimit = runtime.enforceAutomaticTurnLimit.bind(runtime);
|
|
105
|
-
const enforceNoProgressLimit = runtime.enforceNoProgressLimit.bind(runtime);
|
|
106
|
-
const clearActiveGoal = runtime.clearActiveGoal.bind(runtime);
|
|
107
|
-
const showCompletionStatus = runtime.showCompletionStatus.bind(runtime);
|
|
108
|
-
const restoreGoalToolsHiddenByPolicy = runtime.restoreGoalToolsHiddenByPolicy.bind(runtime);
|
|
109
|
-
const sendOwnedGoalPrompt = (
|
|
110
|
-
_pi: ExtensionAPI,
|
|
111
|
-
ctx: StatusContext,
|
|
112
|
-
goalId: string,
|
|
113
|
-
prompt: string,
|
|
114
|
-
resetSafetyEpoch = true,
|
|
115
|
-
) => runtime.sendOwnedGoalPrompt(ctx, goalId, prompt, resetSafetyEpoch);
|
|
116
|
-
const dispatchPendingQueueActionIfSettled =
|
|
117
|
-
commands.dispatchPendingQueueActionIfSettled.bind(commands);
|
|
118
|
-
|
|
119
|
-
const goalCompleteTool = defineTool({
|
|
120
|
-
name: GOAL_COMPLETE_TOOL,
|
|
121
|
-
label: "Goal Complete",
|
|
122
|
-
description:
|
|
123
|
-
"Mark the active /goal as complete after all required work is done and verified, using the current goal_id stale-turn guard. Do not use for partial progress, blockers, failing, or unverified work.",
|
|
124
|
-
promptSnippet:
|
|
125
|
-
"Mark the active /goal as complete after fully finishing and verifying it, with the current goal_id",
|
|
126
|
-
promptGuidelines: [
|
|
127
|
-
"When a /goal is active, keep working until the goal is complete; do not stop with only a plan or partial progress.",
|
|
128
|
-
"Before calling goal_complete, audit the active goal requirement by requirement against the current files, command output, tests, or external state.",
|
|
129
|
-
"Pass the exact goal_id shown in the current /goal prompt; never reuse a goal_id from an older, stopped, replaced, or cleared turn.",
|
|
130
|
-
"Call goal_complete only after the requested goal is fully implemented, verified, and no known required work remains; otherwise keep working.",
|
|
131
|
-
],
|
|
132
|
-
parameters: Type.Object({
|
|
133
|
-
goal_id: Type.String({
|
|
134
|
-
description:
|
|
135
|
-
"The exact goal_id shown in the current active /goal prompt. Used only to reject stale completion calls from older turns.",
|
|
136
|
-
}),
|
|
137
|
-
summary: Type.String({
|
|
138
|
-
description:
|
|
139
|
-
"State what was completed and what evidence verified it. Do not use this tool to report partial progress, blockers, failures, or remaining work.",
|
|
140
|
-
}),
|
|
141
|
-
}),
|
|
142
|
-
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
143
|
-
const completedGoal = runtime.activeGoal;
|
|
144
|
-
const goal = completedGoal?.text ?? "unknown goal";
|
|
145
|
-
const requestedGoalId = typeof params.goal_id === "string" ? params.goal_id.trim() : "";
|
|
146
|
-
const summary = typeof params.summary === "string" ? params.summary.trim() : "";
|
|
147
|
-
|
|
148
|
-
if (!completedGoal) {
|
|
149
|
-
const rejection = "Goal completion rejected: no active goal.";
|
|
150
|
-
ctx.ui.notify(rejection, "warning");
|
|
151
|
-
|
|
152
|
-
return {
|
|
153
|
-
content: [{ type: "text", text: rejection }],
|
|
154
|
-
details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
|
|
155
|
-
};
|
|
156
|
-
}
|
|
157
|
-
const completingDuringBudgetWrapUp = runtime.hasActiveBudgetWrapUp();
|
|
158
|
-
if (!runtime.canRecordGoalUsage() && !completingDuringBudgetWrapUp) {
|
|
159
|
-
const rejection = "Goal completion rejected: current run does not own the active goal.";
|
|
160
|
-
ctx.ui.notify(rejection, "warning");
|
|
161
|
-
return {
|
|
162
|
-
content: [{ type: "text", text: rejection }],
|
|
163
|
-
details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
|
|
164
|
-
};
|
|
165
|
-
}
|
|
166
|
-
if (hasPendingSkipForGoal(completedGoal.id)) {
|
|
167
|
-
updateGoalUsage(completedGoal, ctx);
|
|
168
|
-
persistGoal(completedGoal);
|
|
169
|
-
updateStatus(ctx, completedGoal);
|
|
170
|
-
clearBudgetWrapUp();
|
|
171
|
-
const rejection = "Goal completion rejected: goal is queued to be skipped.";
|
|
172
|
-
ctx.ui.notify(rejection, "warning");
|
|
173
|
-
return {
|
|
174
|
-
content: [{ type: "text", text: rejection }],
|
|
175
|
-
details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
|
|
176
|
-
terminate: true,
|
|
177
|
-
};
|
|
178
|
-
}
|
|
179
|
-
const staleGoalRejection = goalIdRejectionReason(completedGoal, requestedGoalId);
|
|
180
|
-
if (staleGoalRejection) {
|
|
181
|
-
const rejection = `Goal completion rejected: ${staleGoalRejection}.`;
|
|
182
|
-
ctx.ui.notify(rejection, "warning");
|
|
183
|
-
if (completingDuringBudgetWrapUp) {
|
|
184
|
-
updateGoalUsage(completedGoal, ctx);
|
|
185
|
-
persistGoal(completedGoal);
|
|
186
|
-
updateStatus(ctx, completedGoal);
|
|
187
|
-
clearBudgetWrapUp();
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
return {
|
|
191
|
-
content: [{ type: "text", text: rejection }],
|
|
192
|
-
details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
|
|
193
|
-
terminate: completingDuringBudgetWrapUp || undefined,
|
|
194
|
-
};
|
|
195
|
-
}
|
|
196
|
-
if (completedGoal.status !== "active" && !completingDuringBudgetWrapUp) {
|
|
197
|
-
const rejection = `Goal completion rejected: goal is ${completedGoal.status}, not active.`;
|
|
198
|
-
ctx.ui.notify(rejection, "warning");
|
|
199
|
-
|
|
200
|
-
return {
|
|
201
|
-
content: [{ type: "text", text: rejection }],
|
|
202
|
-
details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
|
|
203
|
-
};
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
const rejectionReason = !summary
|
|
207
|
-
? "summary is empty"
|
|
208
|
-
: isContradictoryCompletionSummary(summary)
|
|
209
|
-
? "summary says the goal is not complete"
|
|
210
|
-
: undefined;
|
|
211
|
-
if (rejectionReason) {
|
|
212
|
-
updateGoalUsage(completedGoal, ctx);
|
|
213
|
-
persistGoal(completedGoal);
|
|
214
|
-
updateStatus(ctx, completedGoal);
|
|
215
|
-
const rejection = `Goal completion rejected: ${rejectionReason}.`;
|
|
216
|
-
ctx.ui.notify(rejection, "warning");
|
|
217
|
-
if (completingDuringBudgetWrapUp) clearBudgetWrapUp();
|
|
218
|
-
|
|
219
|
-
return {
|
|
220
|
-
content: [
|
|
221
|
-
{
|
|
222
|
-
type: "text",
|
|
223
|
-
text: rejection,
|
|
224
|
-
},
|
|
225
|
-
],
|
|
226
|
-
details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
|
|
227
|
-
terminate: completingDuringBudgetWrapUp || undefined,
|
|
228
|
-
};
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
runtime.activeGoal = transitionGoal(completedGoal, "complete");
|
|
232
|
-
runtime.setCompletionSummary(runtime.activeGoal.id, summary);
|
|
233
|
-
updateGoalUsage(runtime.activeGoal, ctx);
|
|
234
|
-
if (runtime.pendingQueueAction?.kind === "prioritize") {
|
|
235
|
-
persistGoal(runtime.activeGoal);
|
|
236
|
-
ctx.ui.setStatus(STATUS_KEY, "complete");
|
|
237
|
-
ctx.ui.notify(`Goal complete: ${goal}. Priority goal waits for Pi to settle.`, "info");
|
|
238
|
-
return {
|
|
239
|
-
content: [{ type: "text", text: `Goal complete: ${summary}` }],
|
|
240
|
-
details: {
|
|
241
|
-
goal,
|
|
242
|
-
goal_id: requestedGoalId,
|
|
243
|
-
summary,
|
|
244
|
-
} satisfies GoalCompleteDetails,
|
|
245
|
-
terminate: true,
|
|
246
|
-
};
|
|
247
|
-
}
|
|
248
|
-
if (runtime.queuedGoals.length > 0) {
|
|
249
|
-
runtime.pendingQueueAction = {
|
|
250
|
-
kind: "advance",
|
|
251
|
-
goalId: runtime.activeGoal.id,
|
|
252
|
-
reason: "complete",
|
|
253
|
-
completedText: goal,
|
|
254
|
-
};
|
|
255
|
-
persistGoal(runtime.activeGoal);
|
|
256
|
-
ctx.ui.setStatus(STATUS_KEY, "complete");
|
|
257
|
-
ctx.ui.notify(
|
|
258
|
-
`Goal complete: ${goal}. Next goal queued: ${runtime.queuedGoals[0]?.text}`,
|
|
259
|
-
"info",
|
|
260
|
-
);
|
|
261
|
-
return {
|
|
262
|
-
content: [
|
|
263
|
-
{
|
|
264
|
-
type: "text",
|
|
265
|
-
text: `Goal complete: ${summary}\nNext goal queued: ${runtime.queuedGoals[0]?.text}`,
|
|
266
|
-
},
|
|
267
|
-
],
|
|
268
|
-
details: {
|
|
269
|
-
goal,
|
|
270
|
-
goal_id: requestedGoalId,
|
|
271
|
-
summary,
|
|
272
|
-
} satisfies GoalCompleteDetails,
|
|
273
|
-
terminate: true,
|
|
274
|
-
};
|
|
275
|
-
}
|
|
276
|
-
persistGoal(runtime.activeGoal);
|
|
277
|
-
|
|
278
|
-
ctx.ui.setStatus(STATUS_KEY, formatStatus(runtime.activeGoal));
|
|
279
|
-
clearActiveGoal(ctx);
|
|
280
|
-
showCompletionStatus(ctx);
|
|
281
|
-
ctx.ui.notify(`Goal complete: ${goal}`, "info");
|
|
282
|
-
|
|
283
|
-
return {
|
|
284
|
-
content: [{ type: "text", text: `Goal complete: ${summary}` }],
|
|
285
|
-
details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
|
|
286
|
-
terminate: true,
|
|
287
|
-
};
|
|
288
|
-
},
|
|
289
|
-
});
|
|
290
|
-
|
|
291
|
-
const goalBlockedTool = defineTool({
|
|
292
|
-
name: GOAL_BLOCKED_TOOL,
|
|
293
|
-
label: "Goal Blocked",
|
|
294
|
-
description:
|
|
295
|
-
"Stop the active /goal only at a true impasse after the same blocker recurs for at least three consecutive goal turns, with the current goal_id and concrete evidence that user or external action is required. Do not use for ordinary clarification, uncertainty, or recoverable failures.",
|
|
296
|
-
promptSnippet:
|
|
297
|
-
"Mark the active /goal blocked only after the same blocker recurs for three consecutive goal turns",
|
|
298
|
-
promptGuidelines: [
|
|
299
|
-
"Use goal_blocked only for a true impasse after the same blocker recurs for at least three consecutive goal turns and concrete evidence shows user or external action is required.",
|
|
300
|
-
"After a blocked goal is resumed, start a fresh three-turn blocker audit before using goal_blocked again.",
|
|
301
|
-
"Do not use goal_blocked for ordinary clarification, incomplete work, uncertainty, difficult tasks, or recoverable tool/provider failures.",
|
|
302
|
-
"Pass goal_blocked the exact current goal_id; never reuse a goal_id from an older, stopped, replaced, or cleared goal turn.",
|
|
303
|
-
],
|
|
304
|
-
parameters: Type.Object({
|
|
305
|
-
goal_id: Type.String({
|
|
306
|
-
description: "The exact goal_id shown in the current active /goal prompt.",
|
|
307
|
-
}),
|
|
308
|
-
reason: Type.String({
|
|
309
|
-
minLength: 1,
|
|
310
|
-
maxLength: MAX_BLOCKER_REASON_LENGTH,
|
|
311
|
-
description: "The specific user or external action required to unblock the goal.",
|
|
312
|
-
}),
|
|
313
|
-
evidence: Type.String({
|
|
314
|
-
minLength: 1,
|
|
315
|
-
maxLength: MAX_BLOCKER_EVIDENCE_LENGTH,
|
|
316
|
-
description: "Concrete evidence from the repeated attempts that proves the impasse.",
|
|
317
|
-
}),
|
|
318
|
-
repeated_turns: Type.Integer({
|
|
319
|
-
minimum: 3,
|
|
320
|
-
description: "Number of separate turns spent trying to resolve this same blocker.",
|
|
321
|
-
}),
|
|
322
|
-
}),
|
|
323
|
-
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
324
|
-
const blockedGoal = runtime.activeGoal;
|
|
325
|
-
const goal = blockedGoal?.text ?? "unknown goal";
|
|
326
|
-
const requestedGoalId = typeof params.goal_id === "string" ? params.goal_id.trim() : "";
|
|
327
|
-
const reason = typeof params.reason === "string" ? params.reason.trim() : "";
|
|
328
|
-
const evidence = typeof params.evidence === "string" ? params.evidence.trim() : "";
|
|
329
|
-
const repeatedTurns =
|
|
330
|
-
typeof params.repeated_turns === "number" ? params.repeated_turns : Number.NaN;
|
|
331
|
-
const reject = (rejectionReason: string, terminate = false) => {
|
|
332
|
-
const rejection = `goal_blocked rejected: ${rejectionReason}.`;
|
|
333
|
-
ctx.ui.notify(rejection, "warning");
|
|
334
|
-
return {
|
|
335
|
-
content: [{ type: "text" as const, text: rejection }],
|
|
336
|
-
details: {
|
|
337
|
-
goal,
|
|
338
|
-
goal_id: requestedGoalId,
|
|
339
|
-
reason: reason.slice(0, MAX_BLOCKER_REASON_LENGTH),
|
|
340
|
-
evidence: evidence.slice(0, MAX_BLOCKER_EVIDENCE_LENGTH),
|
|
341
|
-
repeated_turns: Number.isFinite(repeatedTurns) ? repeatedTurns : 0,
|
|
342
|
-
} satisfies GoalBlockedDetails,
|
|
343
|
-
...(terminate ? { terminate: true as const } : {}),
|
|
344
|
-
};
|
|
345
|
-
};
|
|
346
|
-
|
|
347
|
-
if (!blockedGoal) return reject("no active goal");
|
|
348
|
-
if (!runtime.canRecordGoalUsage()) {
|
|
349
|
-
return reject("current run does not own the active goal");
|
|
350
|
-
}
|
|
351
|
-
if (hasPendingSkipForGoal(blockedGoal.id)) {
|
|
352
|
-
updateGoalUsage(blockedGoal, ctx);
|
|
353
|
-
persistGoal(blockedGoal);
|
|
354
|
-
updateStatus(ctx, blockedGoal);
|
|
355
|
-
clearBudgetWrapUp();
|
|
356
|
-
return reject("goal is queued to be skipped", true);
|
|
357
|
-
}
|
|
358
|
-
const staleGoalRejection = goalIdRejectionReason(blockedGoal, requestedGoalId);
|
|
359
|
-
if (staleGoalRejection) return reject(staleGoalRejection);
|
|
360
|
-
if (blockedGoal.status !== "active") {
|
|
361
|
-
return reject(`goal is ${blockedGoal.status}, not active`);
|
|
362
|
-
}
|
|
363
|
-
if (!reason) return reject("reason is empty");
|
|
364
|
-
if (reason.length > MAX_BLOCKER_REASON_LENGTH) return reject("reason is too long");
|
|
365
|
-
if (!evidence) return reject("evidence is empty");
|
|
366
|
-
if (evidence.length > MAX_BLOCKER_EVIDENCE_LENGTH) return reject("evidence is too long");
|
|
367
|
-
if (!Number.isInteger(repeatedTurns)) return reject("repeated_turns must be a whole number");
|
|
368
|
-
if (repeatedTurns < 3) return reject("repeated_turns must be at least 3");
|
|
369
|
-
|
|
370
|
-
updateGoalUsage(blockedGoal, ctx);
|
|
371
|
-
cancelContinuationWork();
|
|
372
|
-
clearBudgetWrapUp();
|
|
373
|
-
clearGoalRecoveryForGoal(blockedGoal.id);
|
|
374
|
-
blockStaleGoalToolCalls();
|
|
375
|
-
runtime.activeGoal = transitionGoal(blockedGoal, "blocked");
|
|
376
|
-
runtime.setTerminalReason(runtime.activeGoal.id, reason);
|
|
377
|
-
persistGoal(runtime.activeGoal);
|
|
378
|
-
updateStatus(ctx, runtime.activeGoal);
|
|
379
|
-
ctx.ui.notify(`Goal blocked: ${truncateNotification(reason)}`, "warning");
|
|
380
|
-
|
|
381
|
-
return {
|
|
382
|
-
content: [{ type: "text", text: `Goal blocked: ${reason}` }],
|
|
383
|
-
details: {
|
|
384
|
-
goal,
|
|
385
|
-
goal_id: requestedGoalId,
|
|
386
|
-
reason,
|
|
387
|
-
evidence,
|
|
388
|
-
repeated_turns: repeatedTurns,
|
|
389
|
-
} satisfies GoalBlockedDetails,
|
|
390
|
-
terminate: true,
|
|
391
|
-
};
|
|
392
|
-
},
|
|
393
|
-
});
|
|
394
|
-
|
|
395
|
-
pi.registerTool(goalCompleteTool);
|
|
396
|
-
pi.registerTool(goalBlockedTool);
|
|
397
|
-
// Do not touch the active tool set during factory registration: ExtensionAPI
|
|
398
|
-
// actions are unbound until the session binds the runtime. session_start applies
|
|
399
|
-
// baseline visibility once actions work; later hooks only enforce goal safety.
|
|
400
|
-
|
|
401
|
-
pi.registerCommand("goal", {
|
|
402
|
-
description: "Run a goal to completion: /goal [--tokens 100k] <goal_to_complete>",
|
|
403
|
-
getArgumentCompletions: (prefix) =>
|
|
404
|
-
completeGoalArguments(prefix, {
|
|
405
|
-
experimentalGoals: runtime.settings.experimental.goals,
|
|
406
|
-
}),
|
|
407
|
-
handler: async (args, ctx) => {
|
|
408
|
-
const result = parseCommand(args, {
|
|
409
|
-
experimentalGoals: runtime.settings.experimental.goals,
|
|
410
|
-
});
|
|
411
|
-
if (typeof result === "string") {
|
|
412
|
-
ctx.ui.notify(result, "warning");
|
|
413
|
-
return;
|
|
414
|
-
}
|
|
415
|
-
if (result.kind === "show" && args.trim() === "") {
|
|
416
|
-
await showGoalManager(runtime, commands, ctx, (menuCtx) =>
|
|
417
|
-
showGoalSettings(runtime, menuCtx, {
|
|
418
|
-
settingsPath: options.settingsPath,
|
|
419
|
-
onQueueUnfrozen: async (settingsCtx) => {
|
|
420
|
-
await commands.resumeQueueAfterUnfreeze(settingsCtx);
|
|
421
|
-
},
|
|
422
|
-
}),
|
|
423
|
-
);
|
|
424
|
-
return;
|
|
425
|
-
}
|
|
426
|
-
if (runtime.queueFrozen) {
|
|
427
|
-
if (result.kind === "show") commands.showGoal(ctx);
|
|
428
|
-
else if (result.kind === "clear") commands.clearGoal(ctx);
|
|
429
|
-
else commands.notifyFrozenQueue(ctx);
|
|
430
|
-
return;
|
|
431
|
-
}
|
|
432
|
-
if (runtime.pendingQueueAction && result.kind !== "show" && result.kind !== "clear") {
|
|
433
|
-
ctx.ui.notify(
|
|
434
|
-
"A queued goal change is waiting for Pi to settle. Retry after it finishes.",
|
|
435
|
-
"warning",
|
|
436
|
-
);
|
|
437
|
-
return;
|
|
438
|
-
}
|
|
439
|
-
|
|
440
|
-
switch (result.kind) {
|
|
441
|
-
case "show":
|
|
442
|
-
commands.showGoal(ctx);
|
|
443
|
-
return;
|
|
444
|
-
case "pause":
|
|
445
|
-
commands.pauseGoal(ctx);
|
|
446
|
-
return;
|
|
447
|
-
case "resume":
|
|
448
|
-
await commands.resumeGoal(ctx);
|
|
449
|
-
return;
|
|
450
|
-
case "clear":
|
|
451
|
-
commands.clearGoal(ctx);
|
|
452
|
-
return;
|
|
453
|
-
case "edit":
|
|
454
|
-
await commands.editGoal(result.objective ?? "", result.tokenBudget, ctx);
|
|
455
|
-
return;
|
|
456
|
-
case "add":
|
|
457
|
-
await commands.addGoal(result.objective ?? "", result.tokenBudget, ctx);
|
|
458
|
-
return;
|
|
459
|
-
case "prioritize":
|
|
460
|
-
await commands.prioritizeGoal(result.objective ?? "", result.tokenBudget, ctx);
|
|
461
|
-
return;
|
|
462
|
-
case "drop-last":
|
|
463
|
-
commands.dropLastGoal(ctx);
|
|
464
|
-
return;
|
|
465
|
-
case "skip":
|
|
466
|
-
await commands.skipGoal(ctx);
|
|
467
|
-
return;
|
|
468
|
-
case "start":
|
|
469
|
-
await commands.startGoal(result.objective ?? "", result.tokenBudget, ctx);
|
|
470
|
-
return;
|
|
471
|
-
}
|
|
472
|
-
},
|
|
473
|
-
});
|
|
474
|
-
|
|
475
|
-
pi.on("session_start", async (_event, ctx) => {
|
|
476
|
-
runtime.replaceMenuSession();
|
|
477
|
-
clearCompletionStatusTimer();
|
|
478
|
-
clearContinuationTracking();
|
|
479
|
-
clearPendingGoalPrompts();
|
|
480
|
-
runtime.clearAgentRun();
|
|
481
|
-
runtime.guardAbortGoalId = undefined;
|
|
482
|
-
clearGoalRecovery();
|
|
483
|
-
clearBudgetWrapUp();
|
|
484
|
-
clearStaleGoalToolCallBlock();
|
|
485
|
-
runtime.queuedGoals = [];
|
|
486
|
-
runtime.pendingQueueAction = undefined;
|
|
487
|
-
runtime.queueFrozen = false;
|
|
488
|
-
runtime.queueFreezeAwaitingSettle = false;
|
|
489
|
-
runtime.clearTerminalDetails();
|
|
490
|
-
const previousToolVisibility = runtime.settings.toolVisibility;
|
|
491
|
-
const settingsResult = readGoalSettings(options.settingsPath);
|
|
492
|
-
runtime.settings =
|
|
493
|
-
settingsResult.kind === "loaded" ? settingsResult.settings : DEFAULT_GOAL_SETTINGS;
|
|
494
|
-
runtime.settingsLoadIssue = settingsResult.kind === "invalid" ? settingsResult : undefined;
|
|
495
|
-
if (settingsResult.kind === "invalid") {
|
|
496
|
-
ctx.ui.notify(
|
|
497
|
-
`pi-goal settings ignored: ${settingsResult.reason}. Using default settings.`,
|
|
498
|
-
"warning",
|
|
499
|
-
);
|
|
500
|
-
}
|
|
501
|
-
if (runtime.settings.experimental.goals) {
|
|
502
|
-
ctx.ui.notify(EXPERIMENTAL_GOALS_WARNING, "warning");
|
|
503
|
-
}
|
|
504
|
-
if (
|
|
505
|
-
runtime.settings.toolVisibility === "after-first-goal" &&
|
|
506
|
-
previousToolVisibility === "always"
|
|
507
|
-
) {
|
|
508
|
-
runtime.goalToolsUnlocked = false;
|
|
509
|
-
}
|
|
510
|
-
if (runtime.settings.toolVisibility === "always") {
|
|
511
|
-
if (runtime.goalToolsHiddenByPolicy.size > 0) {
|
|
512
|
-
try {
|
|
513
|
-
restoreGoalToolsHiddenByPolicy();
|
|
514
|
-
} catch (error) {
|
|
515
|
-
ctx.ui.notify(
|
|
516
|
-
`Could not restore always-visible goal tools: ${formatError(error)}`,
|
|
517
|
-
"error",
|
|
518
|
-
);
|
|
519
|
-
}
|
|
520
|
-
}
|
|
521
|
-
runtime.goalToolsUnlocked = true;
|
|
522
|
-
}
|
|
523
17
|
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
if (runtime.queueFrozen) {
|
|
531
|
-
if (runtime.activeGoal) persistGoal(runtime.activeGoal);
|
|
532
|
-
ctx.ui.setStatus(STATUS_KEY, "queue off");
|
|
533
|
-
ctx.ui.notify(
|
|
534
|
-
"An experimental goal queue is frozen because experimental.goals is disabled. Re-enable it and run /reload to continue, or use /goal clear.",
|
|
535
|
-
"warning",
|
|
536
|
-
);
|
|
537
|
-
return;
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
let startRestoredQueuedGoal = false;
|
|
541
|
-
if (runtime.activeGoal?.status === "queued" && !runtime.pendingQueueAction) {
|
|
542
|
-
runtime.activeGoal = activateQueuedGoal(runtime.activeGoal, currentTokenTotal(ctx));
|
|
543
|
-
startRestoredQueuedGoal = runtime.activeGoal.status === "active";
|
|
544
|
-
}
|
|
545
|
-
if (runtime.pendingQueueAction) await dispatchPendingQueueActionIfSettled(ctx);
|
|
546
|
-
if (runtime.activeGoal) {
|
|
547
|
-
if (runtime.activeGoal.status === "active" && runtime.activeGoal.safetyResetPending) {
|
|
548
|
-
// Resume/edit activation is persisted before its queued prompt starts. A
|
|
549
|
-
// reload must commit that promised reset before enforcing the old limits.
|
|
550
|
-
runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
|
|
551
|
-
}
|
|
552
|
-
if (runtime.activeGoal.status === "active") {
|
|
553
|
-
updateGoalUsage(runtime.activeGoal, ctx);
|
|
554
|
-
if (limitActiveGoalForBudget(ctx, false)) return;
|
|
555
|
-
if (enforceAutomaticTurnLimit(ctx, false) || enforceNoProgressLimit(ctx)) return;
|
|
556
|
-
}
|
|
557
|
-
if (runtime.settings.toolVisibility === "after-first-goal") {
|
|
558
|
-
// Registered tools are already active on an unrestricted fresh runtime.
|
|
559
|
-
// If an earlier session_start handler removed them, that restrictive
|
|
560
|
-
// policy wins: mark lazy visibility unlocked without widening its set.
|
|
561
|
-
runtime.goalToolsUnlocked = true;
|
|
562
|
-
runtime.goalToolsHiddenByPolicy.clear();
|
|
563
|
-
}
|
|
564
|
-
if (runtime.activeGoal.status === "active" && !goalToolsAvailable()) {
|
|
565
|
-
pauseGoalForUnavailableTools(ctx, false);
|
|
566
|
-
return;
|
|
567
|
-
}
|
|
568
|
-
persistGoal(runtime.activeGoal);
|
|
569
|
-
updateStatus(ctx, runtime.activeGoal);
|
|
570
|
-
if (startRestoredQueuedGoal) {
|
|
571
|
-
const restoredGoal = runtime.activeGoal;
|
|
572
|
-
const sent = await sendOwnedGoalPrompt(
|
|
573
|
-
runtime.pi,
|
|
574
|
-
ctx,
|
|
575
|
-
restoredGoal.id,
|
|
576
|
-
buildGoalPrompt(restoredGoal),
|
|
577
|
-
false, // Reloaded queue activation preserves its persisted safety epoch.
|
|
578
|
-
);
|
|
579
|
-
if (!sent && runtime.activeGoal?.id === restoredGoal.id) {
|
|
580
|
-
runtime.activeGoal = transitionGoal(restoredGoal, "paused");
|
|
581
|
-
blockStaleGoalToolCalls();
|
|
582
|
-
persistGoal(runtime.activeGoal);
|
|
583
|
-
updateStatus(ctx, runtime.activeGoal);
|
|
584
|
-
}
|
|
585
|
-
}
|
|
586
|
-
} else {
|
|
587
|
-
if (runtime.settings.toolVisibility === "after-first-goal" && !runtime.goalToolsUnlocked) {
|
|
588
|
-
hideGoalToolsIfLocked();
|
|
589
|
-
}
|
|
590
|
-
ctx.ui.setStatus(STATUS_KEY, undefined);
|
|
591
|
-
}
|
|
592
|
-
});
|
|
593
|
-
|
|
594
|
-
pi.on("session_shutdown", (_event, ctx) => {
|
|
595
|
-
runController.unbindSession();
|
|
596
|
-
runtime.closeMenuSession();
|
|
597
|
-
if (runtime.activeGoal) {
|
|
598
|
-
if (!runtime.queueFrozen && runtime.activeGoal.status === "active") {
|
|
599
|
-
updateGoalUsage(runtime.activeGoal, ctx, false);
|
|
600
|
-
}
|
|
601
|
-
persistGoal(runtime.activeGoal);
|
|
602
|
-
}
|
|
603
|
-
clearContinuationTracking();
|
|
604
|
-
clearPendingGoalPrompts();
|
|
605
|
-
runtime.clearAgentRun();
|
|
606
|
-
runtime.guardAbortGoalId = undefined;
|
|
607
|
-
clearGoalRecovery();
|
|
608
|
-
clearBudgetWrapUp();
|
|
609
|
-
clearStaleGoalToolCallBlock();
|
|
610
|
-
runtime.activeGoal = undefined;
|
|
611
|
-
runtime.queuedGoals = [];
|
|
612
|
-
runtime.pendingQueueAction = undefined;
|
|
613
|
-
runtime.queueFrozen = false;
|
|
614
|
-
runtime.queueFreezeAwaitingSettle = false;
|
|
615
|
-
ctx.ui.setStatus(STATUS_KEY, undefined);
|
|
616
|
-
clearCompletionStatusTimer();
|
|
617
|
-
runtime.clearTerminalDetails();
|
|
618
|
-
});
|
|
619
|
-
|
|
620
|
-
pi.on("session_before_compact", (event, ctx) => {
|
|
621
|
-
if (runtime.queueFrozen) return;
|
|
622
|
-
if (runtime.activeGoal?.status === "budget_limited") {
|
|
623
|
-
if ((event as { willRetry?: boolean }).willRetry === true) return { cancel: true as const };
|
|
624
|
-
return;
|
|
625
|
-
}
|
|
626
|
-
if (runtime.activeGoal?.status !== "active") return;
|
|
627
|
-
if (!updateGoalUsage(runtime.activeGoal, ctx)) return;
|
|
628
|
-
cancelContinuationWork();
|
|
629
|
-
persistGoal(runtime.activeGoal);
|
|
630
|
-
updateStatus(ctx, runtime.activeGoal);
|
|
631
|
-
if (runtime.pendingQueueAction) return;
|
|
632
|
-
if (limitActiveGoalForBudget(ctx, false)) return { cancel: true as const };
|
|
633
|
-
});
|
|
634
|
-
|
|
635
|
-
pi.on("session_compact", async (event, ctx) => {
|
|
636
|
-
if (runtime.queueFrozen) return;
|
|
637
|
-
if (runtime.activeGoal?.status !== "active") {
|
|
638
|
-
clearGoalRecovery();
|
|
639
|
-
if (runtime.pendingQueueAction) await dispatchPendingQueueActionIfSettled(ctx);
|
|
640
|
-
return;
|
|
641
|
-
}
|
|
642
|
-
|
|
643
|
-
const restoredState = loadGoalStateFromSession(ctx);
|
|
644
|
-
if (restoredState.goal?.id === runtime.activeGoal.id) {
|
|
645
|
-
runtime.activeGoal = restoredState.goal;
|
|
646
|
-
runtime.queuedGoals = restoredState.queue;
|
|
647
|
-
runtime.pendingQueueAction = restoredState.pendingAction;
|
|
648
|
-
}
|
|
649
|
-
const usageRecorded = updateGoalUsage(runtime.activeGoal, ctx);
|
|
650
|
-
if (usageRecorded) {
|
|
651
|
-
persistGoal(runtime.activeGoal);
|
|
652
|
-
updateStatus(ctx, runtime.activeGoal);
|
|
653
|
-
}
|
|
654
|
-
if (runtime.pendingQueueAction) {
|
|
655
|
-
await dispatchPendingQueueActionIfSettled(ctx);
|
|
656
|
-
return;
|
|
657
|
-
}
|
|
658
|
-
if (!usageRecorded) return;
|
|
659
|
-
if (limitActiveGoalForBudget(ctx, false)) return;
|
|
660
|
-
|
|
661
|
-
const wasPiRetry = isPiOwnedCompactionRetry(event, runtime.activeGoal.id);
|
|
662
|
-
if (wasPiRetry) return;
|
|
663
|
-
clearGoalRecoveryForGoal(runtime.activeGoal.id);
|
|
664
|
-
requestContinuation(runtime.activeGoal);
|
|
665
|
-
// Manual compaction does not emit agent_settled. This common dispatcher is
|
|
666
|
-
// therefore the narrow fallback; threshold compaction leaves the intent for
|
|
667
|
-
// agent_settled when Pi is still busy.
|
|
668
|
-
dispatchContinuationIfSettled(ctx);
|
|
669
|
-
});
|
|
670
|
-
|
|
671
|
-
pi.on("input", (event, ctx) => {
|
|
672
|
-
if (event.source === "extension") {
|
|
673
|
-
if (
|
|
674
|
-
consumeCancelledContinuationPrompt(event.text) ||
|
|
675
|
-
consumeStaleOwnedGoalPrompt(event.text)
|
|
676
|
-
) {
|
|
677
|
-
return { action: "handled" as const };
|
|
678
|
-
}
|
|
679
|
-
if (runtime.queueFrozen) return;
|
|
680
|
-
// Streaming input is queued before its model work starts. Keep owned
|
|
681
|
-
// markers pending for message_start, and track non-goal delivery mode so a
|
|
682
|
-
// steer cannot consume a later follow-up's cleanup protection.
|
|
683
|
-
if (runtime.hasPendingOwnedGoalPrompt(event.text)) return;
|
|
684
|
-
if (event.streamingBehavior === "steer" || event.streamingBehavior === "followUp") {
|
|
685
|
-
runtime.noteQueuedNonGoalInput(event.text, event.streamingBehavior);
|
|
686
|
-
}
|
|
687
|
-
clearGoalRecovery();
|
|
688
|
-
return;
|
|
689
|
-
}
|
|
690
|
-
if (runtime.queueFrozen) return;
|
|
691
|
-
if (/^\/goal(?:\s|$)/u.test(event.text.trimStart())) return;
|
|
692
|
-
if (event.streamingBehavior === "followUp") {
|
|
693
|
-
runtime.noteQueuedNonGoalInput(event.text, "followUp", true);
|
|
694
|
-
return;
|
|
695
|
-
}
|
|
696
|
-
if (event.streamingBehavior === "steer") {
|
|
697
|
-
runtime.noteQueuedNonGoalInput(event.text, "steer");
|
|
698
|
-
}
|
|
699
|
-
clearGoalRecovery();
|
|
700
|
-
clearBudgetWrapUp();
|
|
701
|
-
clearStaleGoalToolCallBlock();
|
|
702
|
-
runtime.resetActiveSafetyEpoch(ctx);
|
|
703
|
-
});
|
|
704
|
-
|
|
705
|
-
pi.on("message_start", (event, ctx) => {
|
|
706
|
-
const message = event.message as { role?: unknown; content?: unknown };
|
|
707
|
-
if (
|
|
708
|
-
message.role === "assistant" &&
|
|
709
|
-
runtime.activeGoal?.status === "paused" &&
|
|
710
|
-
runtime.guardAbortGoalId === runtime.activeGoal.id
|
|
711
|
-
) {
|
|
712
|
-
abortCurrentTurn(ctx);
|
|
713
|
-
return;
|
|
714
|
-
}
|
|
715
|
-
if (message.role === "custom") {
|
|
716
|
-
if (runtime.isActiveBudgetWrapUpMessage(message)) return;
|
|
717
|
-
if (runtime.guardAbortGoalId === runtime.activeGoal?.id) {
|
|
718
|
-
runtime.guardAbortGoalId = undefined;
|
|
719
|
-
}
|
|
720
|
-
beginNonGoalFollowUp(ctx, false);
|
|
721
|
-
return;
|
|
722
|
-
}
|
|
723
|
-
if (message.role !== "user") return;
|
|
724
|
-
const prompt = Array.isArray(message.content)
|
|
725
|
-
? message.content
|
|
726
|
-
.filter(
|
|
727
|
-
(part) => part && typeof part === "object" && Reflect.get(part, "type") === "text",
|
|
728
|
-
)
|
|
729
|
-
.map((part) => Reflect.get(part as object, "text"))
|
|
730
|
-
.filter((text): text is string => typeof text === "string")
|
|
731
|
-
.join("\n")
|
|
732
|
-
: typeof message.content === "string"
|
|
733
|
-
? message.content
|
|
734
|
-
: "";
|
|
735
|
-
const ownedPrompt = consumePendingGoalPrompt(prompt);
|
|
736
|
-
const ownedPromptBoundary = runtime.hasOwnedPromptBoundary(prompt);
|
|
737
|
-
const queuedNonGoalInput = runtime.consumeQueuedNonGoalInput(prompt, !ownedPromptBoundary);
|
|
738
|
-
if (!ownedPrompt) {
|
|
739
|
-
if (queuedNonGoalInput?.behavior === "followUp") {
|
|
740
|
-
beginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);
|
|
741
|
-
}
|
|
742
|
-
return;
|
|
743
|
-
}
|
|
744
|
-
if (runtime.activeGoal?.id !== ownedPrompt.goalId || runtime.activeGoal.status !== "active") {
|
|
745
|
-
return;
|
|
746
|
-
}
|
|
747
|
-
if (runtime.agentRunGoalId !== undefined && runtime.agentRunGoalId !== ownedPrompt.goalId) {
|
|
748
|
-
runtime.activeGoal.baselineTokens = Math.max(
|
|
749
|
-
0,
|
|
750
|
-
currentTokenTotal(ctx) - runtime.activeGoal.tokensUsed,
|
|
751
|
-
);
|
|
752
|
-
}
|
|
753
|
-
runtime.beginAgentRun(ownedPrompt.goalId, "manual");
|
|
754
|
-
if (ownedPrompt.resetSafetyEpoch) {
|
|
755
|
-
runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
|
|
756
|
-
}
|
|
757
|
-
persistGoal(runtime.activeGoal);
|
|
758
|
-
updateStatus(ctx, runtime.activeGoal);
|
|
759
|
-
});
|
|
760
|
-
|
|
761
|
-
pi.on("context", (event, ctx) => {
|
|
762
|
-
const messages = event.messages.filter((message) => keepBudgetWrapUpMessage(message));
|
|
763
|
-
if (
|
|
764
|
-
runtime.activeGoal?.status === "paused" &&
|
|
765
|
-
runtime.guardAbortGoalId === runtime.activeGoal.id
|
|
766
|
-
) {
|
|
767
|
-
// A current custom follow-up clears the guard at message_start. Otherwise,
|
|
768
|
-
// context transformation aborts before the provider adapter receives the signal.
|
|
769
|
-
abortCurrentTurn(ctx);
|
|
770
|
-
}
|
|
771
|
-
if (messages.length !== event.messages.length) return { messages };
|
|
772
|
-
});
|
|
773
|
-
|
|
774
|
-
pi.on("tool_call", (event, ctx) => {
|
|
775
|
-
runtime.markAgentToolAttempted();
|
|
776
|
-
if (runtime.queueFrozen) {
|
|
777
|
-
if (!isGoalToolName(event.toolName)) return;
|
|
778
|
-
// Blocking alone feeds an error tool result back to the model. Abort too so
|
|
779
|
-
// stale Goal calls cannot loop while the experimental queue remains frozen.
|
|
780
|
-
abortCurrentTurn(ctx);
|
|
781
|
-
return {
|
|
782
|
-
block: true,
|
|
783
|
-
reason:
|
|
784
|
-
"The experimental goal queue is frozen. Re-enable experimental.goals and run /reload, or use /goal clear.",
|
|
785
|
-
};
|
|
786
|
-
}
|
|
787
|
-
if (
|
|
788
|
-
runtime.activeGoal?.status === "budget_limited" &&
|
|
789
|
-
runtime.budgetWrapUp?.goalId === runtime.activeGoal.id &&
|
|
790
|
-
event.toolName !== "goal_complete"
|
|
791
|
-
) {
|
|
792
|
-
// A blocked tool result would normally trigger another model call. Abort the
|
|
793
|
-
// wrap-up instead so a tool-seeking model cannot create an unbounded loop.
|
|
794
|
-
abortCurrentTurn(ctx);
|
|
795
|
-
return {
|
|
796
|
-
block: true,
|
|
797
|
-
reason: "Goal token budget is exhausted; only goal_complete is allowed during wrap-up.",
|
|
798
|
-
};
|
|
799
|
-
}
|
|
800
|
-
if (!runtime.staleGoalToolCallsBlocked) return;
|
|
801
|
-
if (!runtime.activeGoal || !blocksStaleGoalToolCalls(runtime.activeGoal.status)) {
|
|
802
|
-
clearStaleGoalToolCallBlock();
|
|
803
|
-
return;
|
|
804
|
-
}
|
|
805
|
-
// A blocked tool result would normally trigger another model call. Abort the
|
|
806
|
-
// current turn so a tool-seeking model cannot create an unbounded loop that
|
|
807
|
-
// burns provider quota while the goal is stopped.
|
|
808
|
-
abortCurrentTurn(ctx);
|
|
809
|
-
return {
|
|
810
|
-
block: true,
|
|
811
|
-
reason: "Blocked stale /goal tool call after the goal stopped or was interrupted.",
|
|
812
|
-
};
|
|
813
|
-
});
|
|
814
|
-
|
|
815
|
-
pi.on("tool_execution_end", (_event, ctx) => {
|
|
816
|
-
if (runtime.queueFrozen) return;
|
|
817
|
-
if (
|
|
818
|
-
runtime.activeGoal?.status === "budget_limited" &&
|
|
819
|
-
runtime.budgetWrapUp?.goalId === runtime.activeGoal.id &&
|
|
820
|
-
!runtime.budgetWrapUp.delivered
|
|
821
|
-
) {
|
|
822
|
-
queueBudgetWrapUp(ctx, runtime.activeGoal);
|
|
823
|
-
return;
|
|
824
|
-
}
|
|
825
|
-
if (runtime.activeGoal?.status !== "active") return;
|
|
826
|
-
|
|
827
|
-
// AgentSession persists assistant message_end before tool execution events,
|
|
828
|
-
// so the completed assistant call's usage is authoritative at this boundary.
|
|
829
|
-
if (!updateGoalUsage(runtime.activeGoal, ctx)) return;
|
|
830
|
-
persistGoal(runtime.activeGoal);
|
|
831
|
-
updateStatus(ctx, runtime.activeGoal);
|
|
832
|
-
if (limitActiveGoalForBudget(ctx, true)) return;
|
|
833
|
-
if (!goalToolsAvailable()) pauseGoalForUnavailableTools(ctx);
|
|
834
|
-
});
|
|
835
|
-
|
|
836
|
-
pi.on("before_agent_start", (event, ctx) => {
|
|
837
|
-
runtime.clearAgentRun();
|
|
838
|
-
if (runtime.queueFrozen) return;
|
|
839
|
-
// Pi-owned retries emit agent_start directly. Reaching a normal prompt
|
|
840
|
-
// boundary means cleanup no longer owns the next run, so the hard-cap guard
|
|
841
|
-
// must not abort it.
|
|
842
|
-
if (runtime.guardAbortGoalId) runtime.guardAbortGoalId = undefined;
|
|
843
|
-
const goalPrompt = consumePendingGoalPrompt(event.prompt);
|
|
844
|
-
const goalPromptGoalId = goalPrompt?.goalId;
|
|
845
|
-
const continuationGoalId = goalPromptGoalId ? undefined : markContinuationStarted(event.prompt);
|
|
846
|
-
const ownedPromptGoalId = goalPromptGoalId ?? continuationGoalId;
|
|
847
|
-
const ownedPromptBoundary = runtime.hasOwnedPromptBoundary(event.prompt);
|
|
848
|
-
const activeBudgetWrapUp = runtime.hasActiveBudgetWrapUp();
|
|
849
|
-
const activeGoalRecovery = runtime.hasActiveGoalRecovery();
|
|
850
|
-
const queuedNonGoalInput = activeBudgetWrapUp
|
|
851
|
-
? undefined
|
|
852
|
-
: runtime.consumeQueuedNonGoalInput(
|
|
853
|
-
event.prompt,
|
|
854
|
-
!activeGoalRecovery && ownedPromptGoalId === undefined && !ownedPromptBoundary,
|
|
855
|
-
);
|
|
856
|
-
if (queuedNonGoalInput?.behavior === "followUp") {
|
|
857
|
-
beginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);
|
|
858
|
-
}
|
|
859
|
-
const runOrigin = continuationGoalId
|
|
860
|
-
? "automatic"
|
|
861
|
-
: activeGoalRecovery && runtime.goalRecovery?.automaticOwner
|
|
862
|
-
? "automatic"
|
|
863
|
-
: "manual";
|
|
864
|
-
if (
|
|
865
|
-
runtime.pendingQueueAction?.kind === "prioritize" &&
|
|
866
|
-
!activeBudgetWrapUp &&
|
|
867
|
-
!activeGoalRecovery
|
|
868
|
-
) {
|
|
869
|
-
// A turn that starts after priority intent is committed belongs to neither
|
|
870
|
-
// the displaced goal nor the not-yet-activated urgent goal. Persist the
|
|
871
|
-
// displaced goal's final accounting boundary so reload cannot absorb this run.
|
|
872
|
-
if (!runtime.pendingQueueAction.displacedUsageFinalized) {
|
|
873
|
-
if (runtime.activeGoal?.status === "active") {
|
|
874
|
-
updateGoalUsage(runtime.activeGoal, ctx, false);
|
|
875
|
-
}
|
|
876
|
-
runtime.pendingQueueAction.displacedUsageFinalized = true;
|
|
877
|
-
if (runtime.activeGoal) {
|
|
878
|
-
persistGoal(runtime.activeGoal);
|
|
879
|
-
updateStatus(ctx, runtime.activeGoal);
|
|
880
|
-
}
|
|
881
|
-
}
|
|
882
|
-
runtime.beginAgentRun(null, undefined);
|
|
883
|
-
if (ownedPromptGoalId) abortCurrentTurn(ctx);
|
|
884
|
-
return;
|
|
885
|
-
}
|
|
886
|
-
if (activeBudgetWrapUp && runtime.activeGoal) {
|
|
887
|
-
runtime.beginAgentRun(runtime.activeGoal.id, "manual");
|
|
888
|
-
return;
|
|
889
|
-
}
|
|
890
|
-
if (
|
|
891
|
-
runtime.pendingQueueAction?.kind === "advance" &&
|
|
892
|
-
runtime.pendingQueueAction.goalId === runtime.activeGoal?.id
|
|
893
|
-
) {
|
|
894
|
-
runtime.beginAgentRun(ownedPromptGoalId ?? runtime.activeGoal.id, runOrigin);
|
|
895
|
-
if (ownedPromptGoalId) abortCurrentTurn(ctx);
|
|
896
|
-
return;
|
|
897
|
-
}
|
|
898
|
-
if (ownedPromptGoalId && ownedPromptGoalId !== runtime.activeGoal?.id) {
|
|
899
|
-
runtime.beginAgentRun(ownedPromptGoalId, runOrigin);
|
|
900
|
-
if (runtime.activeGoal?.status === "active" && !goalToolsAvailable()) {
|
|
901
|
-
pauseGoalForUnavailableTools(ctx, false);
|
|
902
|
-
}
|
|
903
|
-
abortCurrentTurn(ctx);
|
|
904
|
-
return;
|
|
905
|
-
}
|
|
906
|
-
if (runtime.activeGoal?.status !== "active") return;
|
|
907
|
-
runtime.beginAgentRun(runtime.activeGoal.id, runOrigin);
|
|
908
|
-
if (!goalToolsAvailable()) {
|
|
909
|
-
pauseGoalForUnavailableTools(ctx, ownedPromptGoalId !== undefined);
|
|
910
|
-
return;
|
|
911
|
-
}
|
|
912
|
-
if (goalPrompt?.resetSafetyEpoch && goalPromptGoalId === runtime.activeGoal.id) {
|
|
913
|
-
runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
|
|
914
|
-
persistGoal(runtime.activeGoal);
|
|
915
|
-
updateStatus(ctx, runtime.activeGoal);
|
|
916
|
-
}
|
|
917
|
-
|
|
918
|
-
return {
|
|
919
|
-
systemPrompt: `${event.systemPrompt}\n\n${buildGoalSystemPrompt(runtime.activeGoal)}`,
|
|
920
|
-
};
|
|
921
|
-
});
|
|
922
|
-
|
|
923
|
-
pi.on("agent_start", (_event, _ctx) => {
|
|
924
|
-
if (runtime.queueFrozen) return;
|
|
925
|
-
const activeGoal = runtime.activeGoal;
|
|
926
|
-
if (
|
|
927
|
-
activeGoal &&
|
|
928
|
-
runtime.guardAbortGoalId === activeGoal.id &&
|
|
929
|
-
activeGoal.status === "paused"
|
|
930
|
-
) {
|
|
931
|
-
if (runtime.consumeQueuedNonGoalFollowUpForAgentStart()) {
|
|
932
|
-
runtime.guardAbortGoalId = undefined;
|
|
933
|
-
clearStaleGoalToolCallBlock();
|
|
934
|
-
runtime.beginAgentRun(null, undefined);
|
|
935
|
-
}
|
|
936
|
-
// Unknown runs defer cleanup until their message/context boundary: custom
|
|
937
|
-
// follow-ups have no input event, while bare recovery is aborted pre-provider.
|
|
938
|
-
return;
|
|
939
|
-
}
|
|
940
|
-
runtime.beginRecoveryRunIfNeeded();
|
|
941
|
-
});
|
|
942
|
-
|
|
943
|
-
pi.on("turn_end", (event, ctx) => {
|
|
944
|
-
if (runtime.queueFrozen) return;
|
|
945
|
-
recordAutomaticTurn(ctx, event.message);
|
|
946
|
-
});
|
|
947
|
-
|
|
948
|
-
pi.on("agent_end", (event, ctx) => {
|
|
949
|
-
const run = runtime.finishAgentRun();
|
|
950
|
-
if (runtime.queueFrozen || run.goalId === null) return;
|
|
951
|
-
if (!runtime.canRecordGoalUsage() && !runtime.hasActiveBudgetWrapUp()) return;
|
|
952
|
-
if (run.goalId && run.goalId !== runtime.activeGoal?.id) return;
|
|
953
|
-
if (!runtime.activeGoal) return;
|
|
954
|
-
if (
|
|
955
|
-
runtime.activeGoal.status === "budget_limited" &&
|
|
956
|
-
runtime.budgetWrapUp?.goalId === runtime.activeGoal.id
|
|
957
|
-
) {
|
|
958
|
-
updateGoalUsage(runtime.activeGoal, ctx);
|
|
959
|
-
persistGoal(runtime.activeGoal);
|
|
960
|
-
updateStatus(ctx, runtime.activeGoal);
|
|
961
|
-
clearBudgetWrapUp();
|
|
962
|
-
return;
|
|
963
|
-
}
|
|
964
|
-
if (runtime.activeGoal.status !== "active") return;
|
|
965
|
-
if (
|
|
966
|
-
runtime.pendingQueueAction?.kind === "advance" &&
|
|
967
|
-
runtime.pendingQueueAction.goalId === runtime.activeGoal.id
|
|
968
|
-
) {
|
|
969
|
-
updateGoalUsage(runtime.activeGoal, ctx);
|
|
970
|
-
persistGoal(runtime.activeGoal);
|
|
971
|
-
updateStatus(ctx, runtime.activeGoal);
|
|
972
|
-
return;
|
|
973
|
-
}
|
|
974
|
-
|
|
975
|
-
const goalId = runtime.activeGoal.id;
|
|
976
|
-
const alreadyAwaitingContinuation = hasContinuationWorkForGoal(goalId);
|
|
977
|
-
const finalAssistant = findFinalAssistantMessage(event.messages);
|
|
978
|
-
|
|
979
|
-
if (!alreadyAwaitingContinuation) runtime.activeGoal = incrementGoal(runtime.activeGoal);
|
|
980
|
-
updateGoalUsage(runtime.activeGoal, ctx);
|
|
981
|
-
|
|
982
|
-
if (finalAssistant?.stopReason === "aborted") {
|
|
983
|
-
clearGoalRecoveryForGoal(goalId);
|
|
984
|
-
stopGoalAfterAgentEnd(ctx, runtime.activeGoal, finalAssistant, "paused");
|
|
985
|
-
return;
|
|
986
|
-
}
|
|
987
|
-
|
|
988
|
-
if (finalAssistant?.stopReason === "error") {
|
|
989
|
-
if (isRetryableGoalInterruption(finalAssistant)) {
|
|
990
|
-
if (run.origin === "automatic" && enforceAutomaticTurnLimit(ctx, true)) return;
|
|
991
|
-
if (limitActiveGoalForBudget(ctx, false)) return;
|
|
992
|
-
if (!goalToolsAvailable()) {
|
|
993
|
-
pauseGoalForUnavailableTools(ctx);
|
|
994
|
-
return;
|
|
995
|
-
}
|
|
996
|
-
runtime.goalRecovery = {
|
|
997
|
-
goalId,
|
|
998
|
-
kind: isGoalContextOverflow(finalAssistant) ? "compaction_retry" : "provider_retry",
|
|
999
|
-
automaticOwner: run.origin === "automatic",
|
|
1000
|
-
errorMessage: finalAssistant.errorMessage,
|
|
1001
|
-
};
|
|
1002
|
-
cancelContinuationWork();
|
|
1003
|
-
persistGoal(runtime.activeGoal);
|
|
1004
|
-
updateStatus(ctx, runtime.activeGoal);
|
|
1005
|
-
return;
|
|
1006
|
-
}
|
|
1007
|
-
clearGoalRecoveryForGoal(goalId);
|
|
1008
|
-
stopGoalAfterAgentEnd(
|
|
1009
|
-
ctx,
|
|
1010
|
-
runtime.activeGoal,
|
|
1011
|
-
finalAssistant,
|
|
1012
|
-
isUsageLimitedGoalInterruption(finalAssistant) ? "usage_limited" : "blocked",
|
|
1013
|
-
);
|
|
1014
|
-
return;
|
|
1015
|
-
}
|
|
1016
|
-
|
|
1017
|
-
clearGoalRecoveryForGoal(goalId);
|
|
1018
|
-
|
|
1019
|
-
if (limitActiveGoalForBudget(ctx, false)) return;
|
|
1020
|
-
if (!goalToolsAvailable()) {
|
|
1021
|
-
pauseGoalForUnavailableTools(ctx);
|
|
1022
|
-
return;
|
|
1023
|
-
}
|
|
1024
|
-
if (
|
|
1025
|
-
run.origin === "automatic" &&
|
|
1026
|
-
recordAutomaticRunProgress(
|
|
1027
|
-
ctx,
|
|
1028
|
-
goalId,
|
|
1029
|
-
event.messages,
|
|
1030
|
-
run.toolAttempted || hasAssistantToolCall(event.messages),
|
|
1031
|
-
)
|
|
1032
|
-
) {
|
|
1033
|
-
return;
|
|
1034
|
-
}
|
|
1035
|
-
|
|
1036
|
-
persistGoal(runtime.activeGoal);
|
|
1037
|
-
updateStatus(ctx, runtime.activeGoal);
|
|
1038
|
-
|
|
1039
|
-
const currentGoal = runtime.activeGoal;
|
|
1040
|
-
if (!currentGoal || currentGoal.id !== goalId || currentGoal.status !== "active") return;
|
|
1041
|
-
if (runtime.pendingQueueAction?.kind === "prioritize") return;
|
|
1042
|
-
requestContinuation(currentGoal);
|
|
1043
|
-
});
|
|
1044
|
-
|
|
1045
|
-
pi.on("agent_settled", async (_event, ctx) => {
|
|
1046
|
-
if (runtime.queueFrozen) {
|
|
1047
|
-
runtime.clearSettledSafetyTracking();
|
|
1048
|
-
runtime.queueFreezeAwaitingSettle = false;
|
|
1049
|
-
if (runtime.settings.experimental.goals) {
|
|
1050
|
-
await commands.resumeQueueAfterUnfreeze(ctx);
|
|
1051
|
-
}
|
|
1052
|
-
return;
|
|
1053
|
-
}
|
|
1054
|
-
runtime.finalizeSettledRecovery(ctx);
|
|
1055
|
-
let dispatchedQueueAction = false;
|
|
1056
|
-
if (runtime.pendingQueueAction) {
|
|
1057
|
-
dispatchedQueueAction = await dispatchPendingQueueActionIfSettled(ctx);
|
|
1058
|
-
}
|
|
1059
|
-
if (!dispatchedQueueAction) dispatchContinuationIfSettled(ctx);
|
|
1060
|
-
runtime.clearSettledSafetyTracking();
|
|
1061
|
-
});
|
|
1062
|
-
|
|
1063
|
-
function beginNonGoalFollowUp(ctx: StatusContext, resetSafetyEpoch: boolean) {
|
|
1064
|
-
clearGoalRecovery();
|
|
1065
|
-
clearStaleGoalToolCallBlock();
|
|
1066
|
-
if (resetSafetyEpoch) clearBudgetWrapUp();
|
|
1067
|
-
const activeGoalId =
|
|
1068
|
-
runtime.activeGoal?.status === "active" ? runtime.activeGoal.id : undefined;
|
|
1069
|
-
runtime.beginAgentRun(activeGoalId ?? null, activeGoalId ? "manual" : undefined);
|
|
1070
|
-
if (resetSafetyEpoch && activeGoalId) runtime.resetActiveSafetyEpoch(ctx);
|
|
1071
|
-
}
|
|
1072
|
-
|
|
1073
|
-
function hasPendingSkipForGoal(goalId: string) {
|
|
1074
|
-
return (
|
|
1075
|
-
runtime.pendingQueueAction?.kind === "advance" &&
|
|
1076
|
-
runtime.pendingQueueAction.reason === "skip" &&
|
|
1077
|
-
runtime.pendingQueueAction.goalId === goalId
|
|
1078
|
-
);
|
|
1079
|
-
}
|
|
1080
|
-
|
|
1081
|
-
function stopGoalAfterAgentEnd(
|
|
1082
|
-
ctx: StatusContext,
|
|
1083
|
-
goal: ActiveGoal,
|
|
1084
|
-
assistant: AssistantMessageLike,
|
|
1085
|
-
status: "paused" | "blocked" | "usage_limited",
|
|
1086
|
-
) {
|
|
1087
|
-
cancelContinuationWork();
|
|
1088
|
-
clearBudgetWrapUp();
|
|
1089
|
-
blockStaleGoalToolCalls();
|
|
1090
|
-
abortCurrentTurn(ctx);
|
|
1091
|
-
runtime.activeGoal = transitionGoal(goal, status);
|
|
1092
|
-
runtime.setTerminalReason(
|
|
1093
|
-
runtime.activeGoal.id,
|
|
1094
|
-
assistant.errorMessage ?? `goal ${status} after agent interruption`,
|
|
1095
|
-
);
|
|
1096
|
-
persistGoal(runtime.activeGoal);
|
|
1097
|
-
updateStatus(ctx, runtime.activeGoal);
|
|
1098
|
-
|
|
1099
|
-
const details = assistant.errorMessage
|
|
1100
|
-
? ` (${truncateNotification(assistant.errorMessage)})`
|
|
1101
|
-
: "";
|
|
1102
|
-
if (status === "paused") {
|
|
1103
|
-
ctx.ui.notify(
|
|
1104
|
-
`Goal paused after interruption${details}. Run /goal resume to continue.`,
|
|
1105
|
-
"warning",
|
|
1106
|
-
);
|
|
1107
|
-
return;
|
|
1108
|
-
}
|
|
1109
|
-
if (status === "usage_limited") {
|
|
1110
|
-
ctx.ui.notify(
|
|
1111
|
-
`Goal stopped after provider usage limit${details}. Run /goal resume when usage is available.`,
|
|
1112
|
-
"warning",
|
|
1113
|
-
);
|
|
1114
|
-
return;
|
|
1115
|
-
}
|
|
1116
|
-
ctx.ui.notify(
|
|
1117
|
-
`Goal blocked after agent error${details}. Resolve the blocker or run /goal resume to retry.`,
|
|
1118
|
-
"warning",
|
|
1119
|
-
);
|
|
1120
|
-
}
|
|
18
|
+
// Keep registration order explicit: managed-run bus listeners exist before tools,
|
|
19
|
+
// command routing, and session lifecycle bind the per-factory runtime.
|
|
20
|
+
runController.register(pi);
|
|
21
|
+
registerGoalTools(pi, runtime);
|
|
22
|
+
registerGoalCommand(pi, runtime, commands, options);
|
|
23
|
+
registerGoalLifecycle(pi, runtime, commands, runController, options);
|
|
1121
24
|
}
|
|
1122
25
|
|
|
1123
26
|
export default function goal(pi: ExtensionAPI, options: GoalOptions = {}) {
|