@narumitw/pi-goal 0.15.1 → 0.17.0
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 +62 -11
- package/package.json +3 -2
- package/src/command.ts +99 -24
- package/src/commands.ts +609 -0
- package/src/goal.ts +446 -889
- package/src/persistence.ts +210 -21
- package/src/prompts.ts +11 -4
- package/src/queue.ts +96 -0
- package/src/runtime.ts +860 -0
- package/src/settings.ts +84 -0
package/src/goal.ts
CHANGED
|
@@ -1,44 +1,37 @@
|
|
|
1
|
-
import { randomUUID } from "node:crypto";
|
|
2
|
-
import {
|
|
3
|
-
isContextOverflow,
|
|
4
|
-
type AssistantMessage as PiAssistantMessage,
|
|
5
|
-
type Usage,
|
|
6
|
-
} from "@earendil-works/pi-ai";
|
|
7
1
|
import { defineTool, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
8
2
|
import { Type } from "typebox";
|
|
3
|
+
import { currentTokenTotal } from "./accounting.js";
|
|
4
|
+
import { completeGoalArguments, parseCommand } from "./command.js";
|
|
5
|
+
import { GoalCommandController } from "./commands.js";
|
|
6
|
+
import { type ActiveGoal, loadGoalStateFromSession } from "./persistence.js";
|
|
7
|
+
import { buildGoalPrompt, buildGoalSystemPrompt } from "./prompts.js";
|
|
8
|
+
import { activateQueuedGoal } from "./queue.js";
|
|
9
9
|
import {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
// Per-factory GoalRuntime owns mutable goal/continuation/budget/recovery state
|
|
37
|
-
// so concurrent in-process AgentSessions cannot clobber each other. Pure helpers
|
|
38
|
-
// live at module scope (single source of truth). registerGoalRuntime still keeps
|
|
39
|
-
// the orchestration handlers together so mutable ownership does not fragment
|
|
40
|
-
// across files; a file-size split is deferred until that ownership boundary is
|
|
41
|
-
// stable under isolation tests.
|
|
10
|
+
type AssistantMessageLike,
|
|
11
|
+
abortCurrentTurn,
|
|
12
|
+
blocksStaleGoalToolCalls,
|
|
13
|
+
findFinalAssistantMessage,
|
|
14
|
+
formatError,
|
|
15
|
+
formatStatus,
|
|
16
|
+
GOAL_BLOCKED_TOOL,
|
|
17
|
+
GOAL_COMPLETE_TOOL,
|
|
18
|
+
GoalRuntime,
|
|
19
|
+
goalIdRejectionReason,
|
|
20
|
+
incrementGoal,
|
|
21
|
+
isContradictoryCompletionSummary,
|
|
22
|
+
isGoalContextOverflow,
|
|
23
|
+
isRetryableGoalInterruption,
|
|
24
|
+
isUsageLimitedGoalInterruption,
|
|
25
|
+
STATUS_KEY,
|
|
26
|
+
type StatusContext,
|
|
27
|
+
transitionGoal,
|
|
28
|
+
truncateNotification,
|
|
29
|
+
} from "./runtime.js";
|
|
30
|
+
import { DEFAULT_GOAL_SETTINGS, readGoalSettings } from "./settings.js";
|
|
31
|
+
|
|
32
|
+
// goal.ts is the Pi-facing composition root: it keeps tool contracts and event
|
|
33
|
+
// ordering together. Per-session mechanisms live in runtime.ts, while user command
|
|
34
|
+
// transitions live in commands.ts. Each factory constructs isolated instances.
|
|
42
35
|
|
|
43
36
|
interface GoalCompleteDetails {
|
|
44
37
|
goal: string;
|
|
@@ -54,107 +47,62 @@ interface GoalBlockedDetails {
|
|
|
54
47
|
repeated_turns: number;
|
|
55
48
|
}
|
|
56
49
|
|
|
57
|
-
interface
|
|
58
|
-
|
|
59
|
-
iteration: number;
|
|
60
|
-
marker: string;
|
|
61
|
-
prompt: string;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
interface BudgetWrapUp {
|
|
65
|
-
goalId: string;
|
|
66
|
-
delivered: boolean;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
type GoalRecoveryKind = "provider_retry" | "compaction_retry";
|
|
70
|
-
|
|
71
|
-
interface GoalRecovery {
|
|
72
|
-
goalId: string;
|
|
73
|
-
kind: GoalRecoveryKind;
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
interface AssistantMessageLike {
|
|
77
|
-
role: "assistant";
|
|
78
|
-
stopReason?: AgentStopReason;
|
|
79
|
-
errorMessage?: string;
|
|
80
|
-
content?: PiAssistantMessage["content"];
|
|
81
|
-
api?: PiAssistantMessage["api"];
|
|
82
|
-
provider?: PiAssistantMessage["provider"];
|
|
83
|
-
model?: string;
|
|
84
|
-
usage?: Usage;
|
|
85
|
-
timestamp?: number;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
interface StatusContext {
|
|
89
|
-
cwd: string;
|
|
90
|
-
ui: {
|
|
91
|
-
confirm: (title: string, message: string) => Promise<boolean>;
|
|
92
|
-
notify: (message: string, level?: "info" | "warning" | "error") => void;
|
|
93
|
-
setStatus: (key: string, value: string | undefined) => void;
|
|
94
|
-
};
|
|
95
|
-
isIdle?: () => boolean;
|
|
96
|
-
hasPendingMessages?: () => boolean;
|
|
97
|
-
abort?: () => void;
|
|
98
|
-
sessionManager?: unknown;
|
|
50
|
+
interface GoalOptions {
|
|
51
|
+
settingsPath?: string;
|
|
99
52
|
}
|
|
100
53
|
|
|
101
|
-
const
|
|
102
|
-
|
|
54
|
+
const EXPERIMENTAL_GOALS_WARNING =
|
|
55
|
+
"Experimental ordered goals are enabled for pi-goal. Queue behavior and persisted state may change.";
|
|
103
56
|
const MAX_BLOCKER_REASON_LENGTH = 1_000;
|
|
104
57
|
const MAX_BLOCKER_EVIDENCE_LENGTH = 4_000;
|
|
105
|
-
const MAX_CANCELLED_CONTINUATION_PROMPTS = 20;
|
|
106
|
-
const CONTINUATION_MARKER_PREFIX = "pi-goal-continuation:";
|
|
107
|
-
const BUDGET_WRAP_UP_MESSAGE_TYPE = "goal-budget-wrap-up";
|
|
108
|
-
const BUDGET_WRAP_UP_PROMPT =
|
|
109
|
-
"The active /goal token budget is exhausted. Stop substantive work and do not call substantive tools. Summarize progress, verified results, remaining work, and blockers concisely. Treat completion as unproven. Do not call goal_complete unless authoritative, requirement-by-requirement evidence already proves every requirement is complete. Weak, indirect, or missing evidence is not enough. Budget exhaustion is not completion.";
|
|
110
|
-
const CONTRADICTORY_COMPLETION_PATTERNS = [
|
|
111
|
-
/(?<!could\s)\bnot\s+(?:yet\s+)?(?:complete|completed|done|finished)\b/i,
|
|
112
|
-
/\bstill\s+(?:incomplete|failing|failing\s+tests?|fails?)\b/i,
|
|
113
|
-
/\btests?\s+(?:still\s+)?fail(?:ing)?\b/i,
|
|
114
|
-
] as const;
|
|
115
|
-
const USAGE_LIMIT_GOAL_ERROR_PATTERNS = [
|
|
116
|
-
/usage[_\s-]*(?:limit|cap)|chatgpt.{0,32}usage/i,
|
|
117
|
-
/quota.{0,32}(?:reached|exceeded|exhausted|depleted)|(?:reached|exceeded|exhausted|depleted).{0,32}quota/i,
|
|
118
|
-
/insufficient[_\s-]*(?:quota|credits?)|out of credits|out of budget|available balance|payment required/i,
|
|
119
|
-
/(?:credit|balance).{0,32}(?:low|exhausted|depleted)|billing/i,
|
|
120
|
-
] as const;
|
|
121
|
-
const NON_RETRYABLE_GOAL_ERROR_RE =
|
|
122
|
-
/multi-auth rotation failed|credentials tried|unauthori[sz]ed|invalid api key/i;
|
|
123
|
-
// Pi 0.79 does not export its assistant-error retry classifier. Keep this
|
|
124
|
-
// compatibility mirror aligned with Pi's public retry utility in newer versions.
|
|
125
|
-
const RETRYABLE_GOAL_ERROR_PATTERNS = [
|
|
126
|
-
/overloaded|rate.?limit|too many requests|\b(?:429|500|502|503|504)\b|service.?unavailable|server.?error|internal.?error/i,
|
|
127
|
-
/provider.?returned.?error|you can retry your request|try your request again|please retry your request/i,
|
|
128
|
-
/network.?error|connection.?(?:error|refused|lost)|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up/i,
|
|
129
|
-
/timed? out|timeout|terminated|websocket.?(?:closed|error)|ended without|stream ended before message_stop|http2 request did not get a response|retry delay/i,
|
|
130
|
-
/context[_\s-]*length[_\s-]*exceeded|input exceeds the context window/i,
|
|
131
|
-
] as const;
|
|
132
|
-
|
|
133
|
-
interface GoalRuntime {
|
|
134
|
-
readonly pi: ExtensionAPI;
|
|
135
|
-
activeGoal?: ActiveGoal;
|
|
136
|
-
completionStatusTimer?: NodeJS.Timeout;
|
|
137
|
-
continuationIntent?: ContinuationTicket;
|
|
138
|
-
continuationDelivery?: ContinuationTicket;
|
|
139
|
-
goalRecovery?: GoalRecovery;
|
|
140
|
-
budgetWrapUp?: BudgetWrapUp;
|
|
141
|
-
staleGoalToolCallsBlocked: boolean;
|
|
142
|
-
cancelledContinuationMarkers: Set<string>;
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
function createGoalRuntime(pi: ExtensionAPI): GoalRuntime {
|
|
146
|
-
return {
|
|
147
|
-
pi,
|
|
148
|
-
staleGoalToolCallsBlocked: false,
|
|
149
|
-
cancelledContinuationMarkers: new Set(),
|
|
150
|
-
};
|
|
151
|
-
}
|
|
152
58
|
|
|
153
|
-
function registerGoalRuntime(pi: ExtensionAPI) {
|
|
154
|
-
const runtime =
|
|
59
|
+
function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
|
|
60
|
+
const runtime = new GoalRuntime(pi);
|
|
61
|
+
const commands = new GoalCommandController(runtime);
|
|
62
|
+
|
|
63
|
+
// Bind per-factory runtime operations once so event orchestration stays concise
|
|
64
|
+
// without reintroducing module-global mutable state.
|
|
65
|
+
const clearCompletionStatusTimer = runtime.clearCompletionStatusTimer.bind(runtime);
|
|
66
|
+
const clearContinuationTracking = runtime.clearContinuationTracking.bind(runtime);
|
|
67
|
+
const clearPendingGoalPrompts = runtime.clearPendingGoalPrompts.bind(runtime);
|
|
68
|
+
const clearGoalRecovery = runtime.clearGoalRecovery.bind(runtime);
|
|
69
|
+
const clearBudgetWrapUp = runtime.clearBudgetWrapUp.bind(runtime);
|
|
70
|
+
const clearStaleGoalToolCallBlock = runtime.clearStaleGoalToolCallBlock.bind(runtime);
|
|
71
|
+
const persistGoal = runtime.persistGoal.bind(runtime);
|
|
72
|
+
const updateGoalUsage = runtime.recordGoalUsage.bind(runtime);
|
|
73
|
+
const updateStatus = runtime.updateStatus.bind(runtime);
|
|
74
|
+
const limitActiveGoalForBudget = runtime.limitActiveGoalForBudget.bind(runtime);
|
|
75
|
+
const hideGoalToolsIfLocked = runtime.hideGoalToolsIfLocked.bind(runtime);
|
|
76
|
+
const goalToolsAvailable = runtime.goalToolsAvailable.bind(runtime);
|
|
77
|
+
const pauseGoalForUnavailableTools = runtime.pauseGoalForUnavailableTools.bind(runtime);
|
|
78
|
+
const isPiOwnedCompactionRetry = runtime.isPiOwnedCompactionRetry.bind(runtime);
|
|
79
|
+
const requestContinuation = runtime.requestContinuation.bind(runtime);
|
|
80
|
+
const dispatchContinuationIfSettled = runtime.dispatchContinuationIfSettled.bind(runtime);
|
|
81
|
+
const keepBudgetWrapUpMessage = runtime.keepBudgetWrapUpMessage.bind(runtime);
|
|
82
|
+
const isGoalToolName = runtime.isGoalToolName.bind(runtime);
|
|
83
|
+
const queueBudgetWrapUp = runtime.queueBudgetWrapUp.bind(runtime);
|
|
84
|
+
const clearGoalRecoveryForGoal = runtime.clearGoalRecoveryForGoal.bind(runtime);
|
|
85
|
+
const blockStaleGoalToolCalls = runtime.blockStaleGoalToolCalls.bind(runtime);
|
|
86
|
+
const cancelContinuationWork = runtime.cancelContinuationWork.bind(runtime);
|
|
87
|
+
const consumeCancelledContinuationPrompt =
|
|
88
|
+
runtime.consumeCancelledContinuationPrompt.bind(runtime);
|
|
89
|
+
const consumePendingGoalPrompt = runtime.consumeOwnedGoalPrompt.bind(runtime);
|
|
90
|
+
const markContinuationStarted = runtime.markContinuationStarted.bind(runtime);
|
|
91
|
+
const hasContinuationWorkForGoal = runtime.hasContinuationWorkForGoal.bind(runtime);
|
|
92
|
+
const clearActiveGoal = runtime.clearActiveGoal.bind(runtime);
|
|
93
|
+
const showCompletionStatus = runtime.showCompletionStatus.bind(runtime);
|
|
94
|
+
const restoreGoalToolsHiddenByPolicy = runtime.restoreGoalToolsHiddenByPolicy.bind(runtime);
|
|
95
|
+
const sendOwnedGoalPrompt = (
|
|
96
|
+
_pi: ExtensionAPI,
|
|
97
|
+
ctx: StatusContext,
|
|
98
|
+
goalId: string,
|
|
99
|
+
prompt: string,
|
|
100
|
+
) => runtime.sendOwnedGoalPrompt(ctx, goalId, prompt);
|
|
101
|
+
const dispatchPendingQueueActionIfSettled =
|
|
102
|
+
commands.dispatchPendingQueueActionIfSettled.bind(commands);
|
|
155
103
|
|
|
156
104
|
const goalCompleteTool = defineTool({
|
|
157
|
-
name:
|
|
105
|
+
name: GOAL_COMPLETE_TOOL,
|
|
158
106
|
label: "Goal Complete",
|
|
159
107
|
description:
|
|
160
108
|
"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.",
|
|
@@ -191,11 +139,28 @@ function registerGoalRuntime(pi: ExtensionAPI) {
|
|
|
191
139
|
details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
|
|
192
140
|
};
|
|
193
141
|
}
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
142
|
+
const completingDuringBudgetWrapUp = runtime.hasActiveBudgetWrapUp();
|
|
143
|
+
if (!runtime.canRecordGoalUsage() && !completingDuringBudgetWrapUp) {
|
|
144
|
+
const rejection = "Goal completion rejected: current run does not own the active goal.";
|
|
145
|
+
ctx.ui.notify(rejection, "warning");
|
|
146
|
+
return {
|
|
147
|
+
content: [{ type: "text", text: rejection }],
|
|
148
|
+
details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
if (hasPendingSkipForGoal(completedGoal.id)) {
|
|
152
|
+
updateGoalUsage(completedGoal, ctx);
|
|
153
|
+
persistGoal(completedGoal);
|
|
154
|
+
updateStatus(ctx, completedGoal);
|
|
155
|
+
clearBudgetWrapUp();
|
|
156
|
+
const rejection = "Goal completion rejected: goal is queued to be skipped.";
|
|
157
|
+
ctx.ui.notify(rejection, "warning");
|
|
158
|
+
return {
|
|
159
|
+
content: [{ type: "text", text: rejection }],
|
|
160
|
+
details: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,
|
|
161
|
+
terminate: true,
|
|
162
|
+
};
|
|
163
|
+
}
|
|
199
164
|
const staleGoalRejection = goalIdRejectionReason(completedGoal, requestedGoalId);
|
|
200
165
|
if (staleGoalRejection) {
|
|
201
166
|
const rejection = `Goal completion rejected: ${staleGoalRejection}.`;
|
|
@@ -250,6 +215,48 @@ function registerGoalRuntime(pi: ExtensionAPI) {
|
|
|
250
215
|
|
|
251
216
|
runtime.activeGoal = transitionGoal(completedGoal, "complete");
|
|
252
217
|
updateGoalUsage(runtime.activeGoal, ctx);
|
|
218
|
+
if (runtime.pendingQueueAction?.kind === "prioritize") {
|
|
219
|
+
persistGoal(runtime.activeGoal);
|
|
220
|
+
ctx.ui.setStatus(STATUS_KEY, "complete");
|
|
221
|
+
ctx.ui.notify(`Goal complete: ${goal}. Priority goal waits for Pi to settle.`, "info");
|
|
222
|
+
return {
|
|
223
|
+
content: [{ type: "text", text: `Goal complete: ${summary}` }],
|
|
224
|
+
details: {
|
|
225
|
+
goal,
|
|
226
|
+
goal_id: requestedGoalId,
|
|
227
|
+
summary,
|
|
228
|
+
} satisfies GoalCompleteDetails,
|
|
229
|
+
terminate: true,
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
if (runtime.queuedGoals.length > 0) {
|
|
233
|
+
runtime.pendingQueueAction = {
|
|
234
|
+
kind: "advance",
|
|
235
|
+
goalId: runtime.activeGoal.id,
|
|
236
|
+
reason: "complete",
|
|
237
|
+
completedText: goal,
|
|
238
|
+
};
|
|
239
|
+
persistGoal(runtime.activeGoal);
|
|
240
|
+
ctx.ui.setStatus(STATUS_KEY, "complete");
|
|
241
|
+
ctx.ui.notify(
|
|
242
|
+
`Goal complete: ${goal}. Next goal queued: ${runtime.queuedGoals[0]?.text}`,
|
|
243
|
+
"info",
|
|
244
|
+
);
|
|
245
|
+
return {
|
|
246
|
+
content: [
|
|
247
|
+
{
|
|
248
|
+
type: "text",
|
|
249
|
+
text: `Goal complete: ${summary}\nNext goal queued: ${runtime.queuedGoals[0]?.text}`,
|
|
250
|
+
},
|
|
251
|
+
],
|
|
252
|
+
details: {
|
|
253
|
+
goal,
|
|
254
|
+
goal_id: requestedGoalId,
|
|
255
|
+
summary,
|
|
256
|
+
} satisfies GoalCompleteDetails,
|
|
257
|
+
terminate: true,
|
|
258
|
+
};
|
|
259
|
+
}
|
|
253
260
|
persistGoal(runtime.activeGoal);
|
|
254
261
|
|
|
255
262
|
ctx.ui.setStatus(STATUS_KEY, formatStatus(runtime.activeGoal));
|
|
@@ -266,7 +273,7 @@ function registerGoalRuntime(pi: ExtensionAPI) {
|
|
|
266
273
|
});
|
|
267
274
|
|
|
268
275
|
const goalBlockedTool = defineTool({
|
|
269
|
-
name:
|
|
276
|
+
name: GOAL_BLOCKED_TOOL,
|
|
270
277
|
label: "Goal Blocked",
|
|
271
278
|
description:
|
|
272
279
|
"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.",
|
|
@@ -305,7 +312,7 @@ function registerGoalRuntime(pi: ExtensionAPI) {
|
|
|
305
312
|
const evidence = typeof params.evidence === "string" ? params.evidence.trim() : "";
|
|
306
313
|
const repeatedTurns =
|
|
307
314
|
typeof params.repeated_turns === "number" ? params.repeated_turns : Number.NaN;
|
|
308
|
-
const reject = (rejectionReason: string) => {
|
|
315
|
+
const reject = (rejectionReason: string, terminate = false) => {
|
|
309
316
|
const rejection = `goal_blocked rejected: ${rejectionReason}.`;
|
|
310
317
|
ctx.ui.notify(rejection, "warning");
|
|
311
318
|
return {
|
|
@@ -317,10 +324,21 @@ function registerGoalRuntime(pi: ExtensionAPI) {
|
|
|
317
324
|
evidence: evidence.slice(0, MAX_BLOCKER_EVIDENCE_LENGTH),
|
|
318
325
|
repeated_turns: Number.isFinite(repeatedTurns) ? repeatedTurns : 0,
|
|
319
326
|
} satisfies GoalBlockedDetails,
|
|
327
|
+
...(terminate ? { terminate: true as const } : {}),
|
|
320
328
|
};
|
|
321
329
|
};
|
|
322
330
|
|
|
323
331
|
if (!blockedGoal) return reject("no active goal");
|
|
332
|
+
if (!runtime.canRecordGoalUsage()) {
|
|
333
|
+
return reject("current run does not own the active goal");
|
|
334
|
+
}
|
|
335
|
+
if (hasPendingSkipForGoal(blockedGoal.id)) {
|
|
336
|
+
updateGoalUsage(blockedGoal, ctx);
|
|
337
|
+
persistGoal(blockedGoal);
|
|
338
|
+
updateStatus(ctx, blockedGoal);
|
|
339
|
+
clearBudgetWrapUp();
|
|
340
|
+
return reject("goal is queued to be skipped", true);
|
|
341
|
+
}
|
|
324
342
|
const staleGoalRejection = goalIdRejectionReason(blockedGoal, requestedGoalId);
|
|
325
343
|
if (staleGoalRejection) return reject(staleGoalRejection);
|
|
326
344
|
if (blockedGoal.status !== "active") {
|
|
@@ -359,94 +377,239 @@ function registerGoalRuntime(pi: ExtensionAPI) {
|
|
|
359
377
|
|
|
360
378
|
pi.registerTool(goalCompleteTool);
|
|
361
379
|
pi.registerTool(goalBlockedTool);
|
|
380
|
+
// Do not touch the active tool set during factory registration: ExtensionAPI
|
|
381
|
+
// actions are unbound until the session binds the runtime. session_start applies
|
|
382
|
+
// baseline visibility once actions work; later hooks only enforce goal safety.
|
|
362
383
|
|
|
363
384
|
pi.registerCommand("goal", {
|
|
364
385
|
description: "Run a goal to completion: /goal [--tokens 100k] <goal_to_complete>",
|
|
365
|
-
getArgumentCompletions:
|
|
386
|
+
getArgumentCompletions: (prefix) =>
|
|
387
|
+
completeGoalArguments(prefix, {
|
|
388
|
+
experimentalGoals: runtime.settings.experimental.goals,
|
|
389
|
+
}),
|
|
366
390
|
handler: async (args, ctx) => {
|
|
367
|
-
const result = parseCommand(args
|
|
391
|
+
const result = parseCommand(args, {
|
|
392
|
+
experimentalGoals: runtime.settings.experimental.goals,
|
|
393
|
+
});
|
|
368
394
|
if (typeof result === "string") {
|
|
369
395
|
ctx.ui.notify(result, "warning");
|
|
370
396
|
return;
|
|
371
397
|
}
|
|
398
|
+
if (runtime.queueFrozen) {
|
|
399
|
+
if (result.kind === "show") commands.showGoal(ctx);
|
|
400
|
+
else if (result.kind === "clear") commands.clearGoal(ctx);
|
|
401
|
+
else commands.notifyFrozenQueue(ctx);
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
if (runtime.pendingQueueAction && result.kind !== "show" && result.kind !== "clear") {
|
|
405
|
+
ctx.ui.notify(
|
|
406
|
+
"A queued goal change is waiting for Pi to settle. Retry after it finishes.",
|
|
407
|
+
"warning",
|
|
408
|
+
);
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
372
411
|
|
|
373
412
|
switch (result.kind) {
|
|
374
413
|
case "show":
|
|
375
|
-
showGoal(ctx);
|
|
414
|
+
commands.showGoal(ctx);
|
|
376
415
|
return;
|
|
377
416
|
case "pause":
|
|
378
|
-
pauseGoal(ctx);
|
|
417
|
+
commands.pauseGoal(ctx);
|
|
379
418
|
return;
|
|
380
419
|
case "resume":
|
|
381
|
-
await resumeGoal(
|
|
420
|
+
await commands.resumeGoal(ctx);
|
|
382
421
|
return;
|
|
383
422
|
case "clear":
|
|
384
|
-
clearGoal(ctx);
|
|
423
|
+
commands.clearGoal(ctx);
|
|
385
424
|
return;
|
|
386
425
|
case "edit":
|
|
387
|
-
await editGoal(result.objective ?? "", result.tokenBudget,
|
|
426
|
+
await commands.editGoal(result.objective ?? "", result.tokenBudget, ctx);
|
|
427
|
+
return;
|
|
428
|
+
case "add":
|
|
429
|
+
await commands.addGoal(result.objective ?? "", result.tokenBudget, ctx);
|
|
430
|
+
return;
|
|
431
|
+
case "prioritize":
|
|
432
|
+
await commands.prioritizeGoal(result.objective ?? "", result.tokenBudget, ctx);
|
|
433
|
+
return;
|
|
434
|
+
case "drop-last":
|
|
435
|
+
commands.dropLastGoal(ctx);
|
|
436
|
+
return;
|
|
437
|
+
case "skip":
|
|
438
|
+
await commands.skipGoal(ctx);
|
|
388
439
|
return;
|
|
389
440
|
case "start":
|
|
390
|
-
await startGoal(result.objective ?? "", result.tokenBudget,
|
|
441
|
+
await commands.startGoal(result.objective ?? "", result.tokenBudget, ctx);
|
|
391
442
|
return;
|
|
392
443
|
}
|
|
393
444
|
},
|
|
394
445
|
});
|
|
395
446
|
|
|
396
|
-
pi.on("session_start", (_event, ctx) => {
|
|
447
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
397
448
|
clearCompletionStatusTimer();
|
|
398
449
|
clearContinuationTracking();
|
|
450
|
+
clearPendingGoalPrompts();
|
|
451
|
+
runtime.agentRunGoalId = undefined;
|
|
399
452
|
clearGoalRecovery();
|
|
400
453
|
clearBudgetWrapUp();
|
|
401
454
|
clearStaleGoalToolCallBlock();
|
|
402
|
-
runtime.
|
|
455
|
+
runtime.queuedGoals = [];
|
|
456
|
+
runtime.pendingQueueAction = undefined;
|
|
457
|
+
runtime.queueFrozen = false;
|
|
458
|
+
const previousToolVisibility = runtime.settings.toolVisibility;
|
|
459
|
+
const settingsResult = readGoalSettings(options.settingsPath);
|
|
460
|
+
runtime.settings =
|
|
461
|
+
settingsResult.kind === "loaded" ? settingsResult.settings : DEFAULT_GOAL_SETTINGS;
|
|
462
|
+
if (settingsResult.kind === "invalid") {
|
|
463
|
+
ctx.ui.notify(
|
|
464
|
+
`pi-goal settings ignored: ${settingsResult.reason}. Using default settings.`,
|
|
465
|
+
"warning",
|
|
466
|
+
);
|
|
467
|
+
}
|
|
468
|
+
if (runtime.settings.experimental.goals) {
|
|
469
|
+
ctx.ui.notify(EXPERIMENTAL_GOALS_WARNING, "warning");
|
|
470
|
+
}
|
|
471
|
+
if (
|
|
472
|
+
runtime.settings.toolVisibility === "after-first-goal" &&
|
|
473
|
+
previousToolVisibility === "always"
|
|
474
|
+
) {
|
|
475
|
+
runtime.goalToolsUnlocked = false;
|
|
476
|
+
}
|
|
477
|
+
if (runtime.settings.toolVisibility === "always") {
|
|
478
|
+
if (runtime.goalToolsHiddenByPolicy.size > 0) {
|
|
479
|
+
try {
|
|
480
|
+
restoreGoalToolsHiddenByPolicy();
|
|
481
|
+
} catch (error) {
|
|
482
|
+
ctx.ui.notify(
|
|
483
|
+
`Could not restore always-visible goal tools: ${formatError(error)}`,
|
|
484
|
+
"error",
|
|
485
|
+
);
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
runtime.goalToolsUnlocked = true;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
const loaded = loadGoalStateFromSession(ctx);
|
|
492
|
+
runtime.activeGoal = loaded.goal;
|
|
493
|
+
runtime.queuedGoals = loaded.queue;
|
|
494
|
+
runtime.pendingQueueAction = loaded.pendingAction;
|
|
495
|
+
runtime.queueFrozen = loaded.hasExperimentalQueueState && !runtime.settings.experimental.goals;
|
|
496
|
+
if (runtime.queueFrozen) {
|
|
497
|
+
if (runtime.activeGoal) persistGoal(runtime.activeGoal);
|
|
498
|
+
ctx.ui.setStatus(STATUS_KEY, "queue off");
|
|
499
|
+
ctx.ui.notify(
|
|
500
|
+
"An experimental goal queue is frozen because experimental.goals is disabled. Re-enable it and run /reload to continue, or use /goal clear.",
|
|
501
|
+
"warning",
|
|
502
|
+
);
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
let startRestoredQueuedGoal = false;
|
|
507
|
+
if (runtime.activeGoal?.status === "queued" && !runtime.pendingQueueAction) {
|
|
508
|
+
runtime.activeGoal = activateQueuedGoal(runtime.activeGoal, currentTokenTotal(ctx));
|
|
509
|
+
startRestoredQueuedGoal = runtime.activeGoal.status === "active";
|
|
510
|
+
}
|
|
511
|
+
if (runtime.pendingQueueAction) await dispatchPendingQueueActionIfSettled(ctx);
|
|
403
512
|
if (runtime.activeGoal) {
|
|
404
513
|
if (runtime.activeGoal.status === "active") {
|
|
405
514
|
updateGoalUsage(runtime.activeGoal, ctx);
|
|
406
515
|
if (limitActiveGoalForBudget(ctx, false)) return;
|
|
407
516
|
}
|
|
517
|
+
if (runtime.settings.toolVisibility === "after-first-goal") {
|
|
518
|
+
// Registered tools are already active on an unrestricted fresh runtime.
|
|
519
|
+
// If an earlier session_start handler removed them, that restrictive
|
|
520
|
+
// policy wins: mark lazy visibility unlocked without widening its set.
|
|
521
|
+
runtime.goalToolsUnlocked = true;
|
|
522
|
+
runtime.goalToolsHiddenByPolicy.clear();
|
|
523
|
+
}
|
|
524
|
+
if (runtime.activeGoal.status === "active" && !goalToolsAvailable()) {
|
|
525
|
+
pauseGoalForUnavailableTools(ctx, false);
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
408
528
|
persistGoal(runtime.activeGoal);
|
|
409
529
|
updateStatus(ctx, runtime.activeGoal);
|
|
410
|
-
|
|
530
|
+
if (startRestoredQueuedGoal) {
|
|
531
|
+
const restoredGoal = runtime.activeGoal;
|
|
532
|
+
const sent = await sendOwnedGoalPrompt(
|
|
533
|
+
runtime.pi,
|
|
534
|
+
ctx,
|
|
535
|
+
restoredGoal.id,
|
|
536
|
+
buildGoalPrompt(restoredGoal),
|
|
537
|
+
);
|
|
538
|
+
if (!sent && runtime.activeGoal?.id === restoredGoal.id) {
|
|
539
|
+
runtime.activeGoal = transitionGoal(restoredGoal, "paused");
|
|
540
|
+
blockStaleGoalToolCalls();
|
|
541
|
+
persistGoal(runtime.activeGoal);
|
|
542
|
+
updateStatus(ctx, runtime.activeGoal);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
} else {
|
|
546
|
+
if (runtime.settings.toolVisibility === "after-first-goal" && !runtime.goalToolsUnlocked) {
|
|
547
|
+
hideGoalToolsIfLocked();
|
|
548
|
+
}
|
|
549
|
+
ctx.ui.setStatus(STATUS_KEY, undefined);
|
|
550
|
+
}
|
|
411
551
|
});
|
|
412
552
|
|
|
413
553
|
pi.on("session_shutdown", (_event, ctx) => {
|
|
414
554
|
if (runtime.activeGoal) {
|
|
415
|
-
|
|
555
|
+
if (!runtime.queueFrozen && runtime.activeGoal.status === "active") {
|
|
556
|
+
updateGoalUsage(runtime.activeGoal, ctx, false);
|
|
557
|
+
}
|
|
416
558
|
persistGoal(runtime.activeGoal);
|
|
417
559
|
}
|
|
418
560
|
clearContinuationTracking();
|
|
561
|
+
clearPendingGoalPrompts();
|
|
562
|
+
runtime.agentRunGoalId = undefined;
|
|
419
563
|
clearGoalRecovery();
|
|
420
564
|
clearBudgetWrapUp();
|
|
421
565
|
clearStaleGoalToolCallBlock();
|
|
566
|
+
runtime.activeGoal = undefined;
|
|
567
|
+
runtime.queuedGoals = [];
|
|
568
|
+
runtime.pendingQueueAction = undefined;
|
|
569
|
+
runtime.queueFrozen = false;
|
|
422
570
|
ctx.ui.setStatus(STATUS_KEY, undefined);
|
|
423
571
|
clearCompletionStatusTimer();
|
|
424
572
|
});
|
|
425
573
|
|
|
426
574
|
pi.on("session_before_compact", (event, ctx) => {
|
|
575
|
+
if (runtime.queueFrozen) return;
|
|
427
576
|
if (runtime.activeGoal?.status === "budget_limited") {
|
|
428
577
|
if ((event as { willRetry?: boolean }).willRetry === true) return { cancel: true as const };
|
|
429
578
|
return;
|
|
430
579
|
}
|
|
431
580
|
if (runtime.activeGoal?.status !== "active") return;
|
|
432
|
-
updateGoalUsage(runtime.activeGoal, ctx);
|
|
581
|
+
if (!updateGoalUsage(runtime.activeGoal, ctx)) return;
|
|
433
582
|
cancelContinuationWork();
|
|
434
583
|
persistGoal(runtime.activeGoal);
|
|
435
584
|
updateStatus(ctx, runtime.activeGoal);
|
|
585
|
+
if (runtime.pendingQueueAction) return;
|
|
436
586
|
if (limitActiveGoalForBudget(ctx, false)) return { cancel: true as const };
|
|
437
587
|
});
|
|
438
588
|
|
|
439
|
-
pi.on("session_compact", (event, ctx) => {
|
|
589
|
+
pi.on("session_compact", async (event, ctx) => {
|
|
590
|
+
if (runtime.queueFrozen) return;
|
|
440
591
|
if (runtime.activeGoal?.status !== "active") {
|
|
441
592
|
clearGoalRecovery();
|
|
593
|
+
if (runtime.pendingQueueAction) await dispatchPendingQueueActionIfSettled(ctx);
|
|
442
594
|
return;
|
|
443
595
|
}
|
|
444
596
|
|
|
445
|
-
const
|
|
446
|
-
if (
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
597
|
+
const restoredState = loadGoalStateFromSession(ctx);
|
|
598
|
+
if (restoredState.goal?.id === runtime.activeGoal.id) {
|
|
599
|
+
runtime.activeGoal = restoredState.goal;
|
|
600
|
+
runtime.queuedGoals = restoredState.queue;
|
|
601
|
+
runtime.pendingQueueAction = restoredState.pendingAction;
|
|
602
|
+
}
|
|
603
|
+
const usageRecorded = updateGoalUsage(runtime.activeGoal, ctx);
|
|
604
|
+
if (usageRecorded) {
|
|
605
|
+
persistGoal(runtime.activeGoal);
|
|
606
|
+
updateStatus(ctx, runtime.activeGoal);
|
|
607
|
+
}
|
|
608
|
+
if (runtime.pendingQueueAction) {
|
|
609
|
+
await dispatchPendingQueueActionIfSettled(ctx);
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
if (!usageRecorded) return;
|
|
450
613
|
if (limitActiveGoalForBudget(ctx, false)) return;
|
|
451
614
|
|
|
452
615
|
const wasPiRetry = isPiOwnedCompactionRetry(event, runtime.activeGoal.id);
|
|
@@ -460,8 +623,10 @@ function registerGoalRuntime(pi: ExtensionAPI) {
|
|
|
460
623
|
});
|
|
461
624
|
|
|
462
625
|
pi.on("input", (event) => {
|
|
626
|
+
if (runtime.queueFrozen) return;
|
|
463
627
|
if (event.source === "extension") {
|
|
464
628
|
if (consumeCancelledContinuationPrompt(event.text)) return { action: "handled" as const };
|
|
629
|
+
clearGoalRecovery();
|
|
465
630
|
return;
|
|
466
631
|
}
|
|
467
632
|
if (/^\/goal(?:\s|$)/u.test(event.text.trimStart())) return;
|
|
@@ -476,6 +641,14 @@ function registerGoalRuntime(pi: ExtensionAPI) {
|
|
|
476
641
|
});
|
|
477
642
|
|
|
478
643
|
pi.on("tool_call", (event, ctx) => {
|
|
644
|
+
if (runtime.queueFrozen) {
|
|
645
|
+
if (!isGoalToolName(event.toolName)) return;
|
|
646
|
+
return {
|
|
647
|
+
block: true,
|
|
648
|
+
reason:
|
|
649
|
+
"The experimental goal queue is frozen. Re-enable experimental.goals and run /reload, or use /goal clear.",
|
|
650
|
+
};
|
|
651
|
+
}
|
|
479
652
|
if (
|
|
480
653
|
runtime.activeGoal?.status === "budget_limited" &&
|
|
481
654
|
runtime.budgetWrapUp?.goalId === runtime.activeGoal.id &&
|
|
@@ -501,6 +674,7 @@ function registerGoalRuntime(pi: ExtensionAPI) {
|
|
|
501
674
|
});
|
|
502
675
|
|
|
503
676
|
pi.on("tool_execution_end", (_event, ctx) => {
|
|
677
|
+
if (runtime.queueFrozen) return;
|
|
504
678
|
if (
|
|
505
679
|
runtime.activeGoal?.status === "budget_limited" &&
|
|
506
680
|
runtime.budgetWrapUp?.goalId === runtime.activeGoal.id &&
|
|
@@ -513,15 +687,74 @@ function registerGoalRuntime(pi: ExtensionAPI) {
|
|
|
513
687
|
|
|
514
688
|
// AgentSession persists assistant message_end before tool execution events,
|
|
515
689
|
// so the completed assistant call's usage is authoritative at this boundary.
|
|
516
|
-
updateGoalUsage(runtime.activeGoal, ctx);
|
|
690
|
+
if (!updateGoalUsage(runtime.activeGoal, ctx)) return;
|
|
517
691
|
persistGoal(runtime.activeGoal);
|
|
518
692
|
updateStatus(ctx, runtime.activeGoal);
|
|
519
|
-
limitActiveGoalForBudget(ctx, true);
|
|
693
|
+
if (limitActiveGoalForBudget(ctx, true)) return;
|
|
694
|
+
if (!goalToolsAvailable()) pauseGoalForUnavailableTools(ctx);
|
|
520
695
|
});
|
|
521
696
|
|
|
522
|
-
pi.on("before_agent_start", (event) => {
|
|
523
|
-
|
|
524
|
-
|
|
697
|
+
pi.on("before_agent_start", (event, ctx) => {
|
|
698
|
+
if (runtime.queueFrozen) {
|
|
699
|
+
runtime.agentRunGoalId = undefined;
|
|
700
|
+
return;
|
|
701
|
+
}
|
|
702
|
+
const goalPromptGoalId = consumePendingGoalPrompt(event.prompt);
|
|
703
|
+
const continuationGoalId = goalPromptGoalId ? undefined : markContinuationStarted(event.prompt);
|
|
704
|
+
const ownedPromptGoalId = goalPromptGoalId ?? continuationGoalId;
|
|
705
|
+
const activeBudgetWrapUp = runtime.hasActiveBudgetWrapUp();
|
|
706
|
+
const activeGoalRecovery = runtime.hasActiveGoalRecovery();
|
|
707
|
+
if (
|
|
708
|
+
runtime.pendingQueueAction?.kind === "prioritize" &&
|
|
709
|
+
!activeBudgetWrapUp &&
|
|
710
|
+
!activeGoalRecovery
|
|
711
|
+
) {
|
|
712
|
+
// A turn that starts after priority intent is committed belongs to neither
|
|
713
|
+
// the displaced goal nor the not-yet-activated urgent goal. Persist the
|
|
714
|
+
// displaced goal's final accounting boundary so reload cannot absorb this run.
|
|
715
|
+
if (!runtime.pendingQueueAction.displacedUsageFinalized) {
|
|
716
|
+
if (runtime.activeGoal?.status === "active") {
|
|
717
|
+
updateGoalUsage(runtime.activeGoal, ctx, false);
|
|
718
|
+
}
|
|
719
|
+
runtime.pendingQueueAction.displacedUsageFinalized = true;
|
|
720
|
+
if (runtime.activeGoal) {
|
|
721
|
+
persistGoal(runtime.activeGoal);
|
|
722
|
+
updateStatus(ctx, runtime.activeGoal);
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
runtime.agentRunGoalId = null;
|
|
726
|
+
if (ownedPromptGoalId) abortCurrentTurn(ctx);
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
if (activeBudgetWrapUp && runtime.activeGoal) {
|
|
730
|
+
runtime.agentRunGoalId = runtime.activeGoal.id;
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
if (
|
|
734
|
+
runtime.pendingQueueAction?.kind === "advance" &&
|
|
735
|
+
runtime.pendingQueueAction.goalId === runtime.activeGoal?.id
|
|
736
|
+
) {
|
|
737
|
+
runtime.agentRunGoalId = ownedPromptGoalId ?? runtime.activeGoal.id;
|
|
738
|
+
if (ownedPromptGoalId) abortCurrentTurn(ctx);
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
if (ownedPromptGoalId && ownedPromptGoalId !== runtime.activeGoal?.id) {
|
|
742
|
+
runtime.agentRunGoalId = ownedPromptGoalId;
|
|
743
|
+
if (runtime.activeGoal?.status === "active" && !goalToolsAvailable()) {
|
|
744
|
+
pauseGoalForUnavailableTools(ctx, false);
|
|
745
|
+
}
|
|
746
|
+
abortCurrentTurn(ctx);
|
|
747
|
+
return;
|
|
748
|
+
}
|
|
749
|
+
if (runtime.activeGoal?.status !== "active") {
|
|
750
|
+
runtime.agentRunGoalId = undefined;
|
|
751
|
+
return;
|
|
752
|
+
}
|
|
753
|
+
runtime.agentRunGoalId = runtime.activeGoal.id;
|
|
754
|
+
if (!goalToolsAvailable()) {
|
|
755
|
+
pauseGoalForUnavailableTools(ctx, ownedPromptGoalId !== undefined);
|
|
756
|
+
return;
|
|
757
|
+
}
|
|
525
758
|
|
|
526
759
|
return {
|
|
527
760
|
systemPrompt: `${event.systemPrompt}\n\n${buildGoalSystemPrompt(runtime.activeGoal)}`,
|
|
@@ -529,6 +762,16 @@ function registerGoalRuntime(pi: ExtensionAPI) {
|
|
|
529
762
|
});
|
|
530
763
|
|
|
531
764
|
pi.on("agent_end", (event, ctx) => {
|
|
765
|
+
if (runtime.queueFrozen) return;
|
|
766
|
+
const agentRunGoalId = runtime.agentRunGoalId;
|
|
767
|
+
runtime.agentRunGoalId = undefined;
|
|
768
|
+
if (
|
|
769
|
+
agentRunGoalId === null ||
|
|
770
|
+
(!runtime.canRecordGoalUsage() && !runtime.hasActiveBudgetWrapUp())
|
|
771
|
+
) {
|
|
772
|
+
return;
|
|
773
|
+
}
|
|
774
|
+
if (agentRunGoalId && agentRunGoalId !== runtime.activeGoal?.id) return;
|
|
532
775
|
if (!runtime.activeGoal) return;
|
|
533
776
|
if (
|
|
534
777
|
runtime.activeGoal.status === "budget_limited" &&
|
|
@@ -541,6 +784,15 @@ function registerGoalRuntime(pi: ExtensionAPI) {
|
|
|
541
784
|
return;
|
|
542
785
|
}
|
|
543
786
|
if (runtime.activeGoal.status !== "active") return;
|
|
787
|
+
if (
|
|
788
|
+
runtime.pendingQueueAction?.kind === "advance" &&
|
|
789
|
+
runtime.pendingQueueAction.goalId === runtime.activeGoal.id
|
|
790
|
+
) {
|
|
791
|
+
updateGoalUsage(runtime.activeGoal, ctx);
|
|
792
|
+
persistGoal(runtime.activeGoal);
|
|
793
|
+
updateStatus(ctx, runtime.activeGoal);
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
544
796
|
|
|
545
797
|
const goalId = runtime.activeGoal.id;
|
|
546
798
|
const alreadyAwaitingContinuation = hasContinuationWorkForGoal(goalId);
|
|
@@ -558,6 +810,10 @@ function registerGoalRuntime(pi: ExtensionAPI) {
|
|
|
558
810
|
if (finalAssistant?.stopReason === "error") {
|
|
559
811
|
if (isRetryableGoalInterruption(finalAssistant)) {
|
|
560
812
|
if (limitActiveGoalForBudget(ctx, false)) return;
|
|
813
|
+
if (!goalToolsAvailable()) {
|
|
814
|
+
pauseGoalForUnavailableTools(ctx);
|
|
815
|
+
return;
|
|
816
|
+
}
|
|
561
817
|
runtime.goalRecovery = {
|
|
562
818
|
goalId,
|
|
563
819
|
kind: isGoalContextOverflow(finalAssistant) ? "compaction_retry" : "provider_retry",
|
|
@@ -580,245 +836,37 @@ function registerGoalRuntime(pi: ExtensionAPI) {
|
|
|
580
836
|
clearGoalRecoveryForGoal(goalId);
|
|
581
837
|
|
|
582
838
|
if (limitActiveGoalForBudget(ctx, false)) return;
|
|
839
|
+
if (!goalToolsAvailable()) {
|
|
840
|
+
pauseGoalForUnavailableTools(ctx);
|
|
841
|
+
return;
|
|
842
|
+
}
|
|
583
843
|
|
|
584
844
|
persistGoal(runtime.activeGoal);
|
|
585
845
|
updateStatus(ctx, runtime.activeGoal);
|
|
586
846
|
|
|
587
847
|
const currentGoal = runtime.activeGoal;
|
|
588
848
|
if (!currentGoal || currentGoal.id !== goalId || currentGoal.status !== "active") return;
|
|
849
|
+
if (runtime.pendingQueueAction?.kind === "prioritize") return;
|
|
589
850
|
requestContinuation(currentGoal);
|
|
590
851
|
});
|
|
591
852
|
|
|
592
853
|
pi.on("agent_settled", (_event, ctx) => {
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
async function startGoal(
|
|
597
|
-
objective: string,
|
|
598
|
-
tokenBudget: number | undefined,
|
|
599
|
-
pi: ExtensionAPI,
|
|
600
|
-
ctx: StatusContext,
|
|
601
|
-
) {
|
|
602
|
-
const validationError = validateObjective(objective);
|
|
603
|
-
if (validationError) {
|
|
604
|
-
ctx.ui.notify(validationError, "warning");
|
|
605
|
-
return;
|
|
606
|
-
}
|
|
607
|
-
|
|
608
|
-
const existingGoal = runtime.activeGoal?.status !== "complete" ? runtime.activeGoal : undefined;
|
|
609
|
-
if (existingGoal) {
|
|
610
|
-
const shouldReplace = await ctx.ui.confirm(
|
|
611
|
-
"Replace goal?",
|
|
612
|
-
`Current goal: ${existingGoal.text}\n\nNew goal: ${objective}`,
|
|
613
|
-
);
|
|
614
|
-
if (!shouldReplace) {
|
|
615
|
-
ctx.ui.notify(`Goal kept: ${existingGoal.text}`, "info");
|
|
616
|
-
return;
|
|
617
|
-
}
|
|
618
|
-
}
|
|
619
|
-
|
|
620
|
-
cancelContinuationWork();
|
|
621
|
-
clearGoalRecovery();
|
|
622
|
-
clearBudgetWrapUp();
|
|
623
|
-
clearStaleGoalToolCallBlock();
|
|
624
|
-
runtime.activeGoal = createGoal(objective, tokenBudget, currentTokenTotal(ctx));
|
|
625
|
-
persistGoal(runtime.activeGoal);
|
|
626
|
-
updateStatus(ctx, runtime.activeGoal);
|
|
627
|
-
const startedGoal = runtime.activeGoal;
|
|
628
|
-
const sent = await sendGoalPrompt(pi, ctx, startedGoal);
|
|
629
|
-
if (!sent) {
|
|
630
|
-
if (runtime.activeGoal?.id === startedGoal.id) {
|
|
631
|
-
if (existingGoal) {
|
|
632
|
-
updateGoalUsage(existingGoal, ctx);
|
|
633
|
-
if (existingGoal.status === "active") {
|
|
634
|
-
abortCurrentTurn(ctx);
|
|
635
|
-
runtime.activeGoal = transitionGoal(existingGoal, "paused");
|
|
636
|
-
blockStaleGoalToolCalls();
|
|
637
|
-
} else {
|
|
638
|
-
runtime.activeGoal = existingGoal;
|
|
639
|
-
if (blocksStaleGoalToolCalls(runtime.activeGoal.status)) blockStaleGoalToolCalls();
|
|
640
|
-
else clearStaleGoalToolCallBlock();
|
|
641
|
-
}
|
|
642
|
-
persistGoal(runtime.activeGoal);
|
|
643
|
-
updateStatus(ctx, runtime.activeGoal);
|
|
644
|
-
} else {
|
|
645
|
-
clearActiveGoal(ctx);
|
|
646
|
-
}
|
|
647
|
-
}
|
|
648
|
-
return;
|
|
649
|
-
}
|
|
650
|
-
ctx.ui.notify(
|
|
651
|
-
existingGoal ? `Goal replaced: ${objective}` : `Goal started: ${objective}`,
|
|
652
|
-
"info",
|
|
653
|
-
);
|
|
654
|
-
}
|
|
655
|
-
|
|
656
|
-
function pauseGoal(ctx: StatusContext) {
|
|
657
|
-
if (!runtime.activeGoal) {
|
|
658
|
-
ctx.ui.notify("No active goal.", "info");
|
|
659
|
-
return;
|
|
660
|
-
}
|
|
661
|
-
if (runtime.activeGoal.status !== "active") {
|
|
662
|
-
ctx.ui.notify(
|
|
663
|
-
`Goal is ${runtime.activeGoal.status}; only active goals can be paused.`,
|
|
664
|
-
"warning",
|
|
665
|
-
);
|
|
666
|
-
return;
|
|
667
|
-
}
|
|
668
|
-
updateGoalUsage(runtime.activeGoal, ctx);
|
|
669
|
-
cancelContinuationWork();
|
|
670
|
-
clearBudgetWrapUp();
|
|
671
|
-
blockStaleGoalToolCalls();
|
|
672
|
-
abortCurrentTurn(ctx);
|
|
673
|
-
runtime.activeGoal = transitionGoal(runtime.activeGoal, "paused");
|
|
674
|
-
persistGoal(runtime.activeGoal);
|
|
675
|
-
updateStatus(ctx, runtime.activeGoal);
|
|
676
|
-
ctx.ui.notify(`Goal paused: ${runtime.activeGoal.text}`, "info");
|
|
677
|
-
}
|
|
678
|
-
|
|
679
|
-
async function resumeGoal(pi: ExtensionAPI, ctx: StatusContext) {
|
|
680
|
-
if (!runtime.activeGoal) {
|
|
681
|
-
ctx.ui.notify("No active goal.", "info");
|
|
682
|
-
return;
|
|
683
|
-
}
|
|
684
|
-
if (!isResumableGoalStatus(runtime.activeGoal.status)) {
|
|
685
|
-
ctx.ui.notify(
|
|
686
|
-
`Goal is ${runtime.activeGoal.status}; only paused, blocked, usage-limited, or budget-limited goals can be resumed.`,
|
|
687
|
-
"warning",
|
|
688
|
-
);
|
|
689
|
-
return;
|
|
690
|
-
}
|
|
691
|
-
if (
|
|
692
|
-
runtime.activeGoal.tokenBudget !== undefined &&
|
|
693
|
-
runtime.activeGoal.tokensUsed >= runtime.activeGoal.tokenBudget
|
|
694
|
-
) {
|
|
695
|
-
ctx.ui.notify(
|
|
696
|
-
`Goal token budget is still reached: ${formatBudget(runtime.activeGoal)}`,
|
|
697
|
-
"warning",
|
|
698
|
-
);
|
|
699
|
-
return;
|
|
700
|
-
}
|
|
701
|
-
const stoppedGoal = runtime.activeGoal;
|
|
702
|
-
const stoppedStatus = stoppedGoal.status;
|
|
703
|
-
cancelContinuationWork();
|
|
704
|
-
clearGoalRecovery();
|
|
705
|
-
clearBudgetWrapUp();
|
|
706
|
-
clearStaleGoalToolCallBlock();
|
|
707
|
-
runtime.activeGoal = transitionGoal(nextGoalInstance(runtime.activeGoal), "active");
|
|
708
|
-
persistGoal(runtime.activeGoal);
|
|
709
|
-
updateStatus(ctx, runtime.activeGoal);
|
|
710
|
-
if (runtime.activeGoal.status !== "active") {
|
|
711
|
-
ctx.ui.notify(
|
|
712
|
-
`Goal token budget is still reached: ${formatBudget(runtime.activeGoal)}`,
|
|
713
|
-
"warning",
|
|
714
|
-
);
|
|
715
|
-
return;
|
|
716
|
-
}
|
|
717
|
-
const resumedGoal = runtime.activeGoal;
|
|
718
|
-
const sent = await sendResumePrompt(pi, ctx, resumedGoal, stoppedStatus);
|
|
719
|
-
if (!sent) {
|
|
720
|
-
if (runtime.activeGoal?.id === resumedGoal.id && runtime.activeGoal.status === "active") {
|
|
721
|
-
runtime.activeGoal = stoppedGoal;
|
|
722
|
-
persistGoal(runtime.activeGoal);
|
|
723
|
-
updateStatus(ctx, runtime.activeGoal);
|
|
724
|
-
if (blocksStaleGoalToolCalls(runtime.activeGoal.status)) blockStaleGoalToolCalls();
|
|
725
|
-
}
|
|
726
|
-
return;
|
|
727
|
-
}
|
|
728
|
-
ctx.ui.notify(
|
|
729
|
-
`Goal resumed from ${stoppedStatusLabel(stoppedStatus)}: ${resumedGoal.text}`,
|
|
730
|
-
"info",
|
|
731
|
-
);
|
|
732
|
-
}
|
|
733
|
-
|
|
734
|
-
function clearGoal(ctx: StatusContext) {
|
|
735
|
-
if (!runtime.activeGoal) {
|
|
736
|
-
ctx.ui.notify("No active goal.", "info");
|
|
737
|
-
cancelContinuationWork();
|
|
738
|
-
clearGoalRecovery();
|
|
739
|
-
clearBudgetWrapUp();
|
|
740
|
-
clearStaleGoalToolCallBlock();
|
|
741
|
-
clearPersistedGoal(ctx.cwd);
|
|
742
|
-
ctx.ui.setStatus(STATUS_KEY, undefined);
|
|
743
|
-
return;
|
|
744
|
-
}
|
|
745
|
-
|
|
746
|
-
const stoppedGoal = runtime.activeGoal.text;
|
|
747
|
-
clearActiveGoal(ctx);
|
|
748
|
-
ctx.ui.notify(`Goal cleared: ${stoppedGoal}`, "warning");
|
|
749
|
-
}
|
|
750
|
-
|
|
751
|
-
async function editGoal(
|
|
752
|
-
objective: string,
|
|
753
|
-
tokenBudget: number | undefined,
|
|
754
|
-
pi: ExtensionAPI,
|
|
755
|
-
ctx: StatusContext,
|
|
756
|
-
) {
|
|
757
|
-
const validationError = validateObjective(objective);
|
|
758
|
-
if (validationError) {
|
|
759
|
-
ctx.ui.notify(validationError, "warning");
|
|
760
|
-
return;
|
|
761
|
-
}
|
|
762
|
-
if (!runtime.activeGoal) {
|
|
763
|
-
ctx.ui.notify("No active goal. Use /goal <objective> to start one.", "warning");
|
|
854
|
+
if (runtime.queueFrozen) return;
|
|
855
|
+
if (!runtime.pendingQueueAction) {
|
|
856
|
+
dispatchContinuationIfSettled(ctx);
|
|
764
857
|
return;
|
|
765
858
|
}
|
|
859
|
+
return dispatchPendingQueueActionIfSettled(ctx).then((dispatched) => {
|
|
860
|
+
if (!dispatched) dispatchContinuationIfSettled(ctx);
|
|
861
|
+
});
|
|
862
|
+
});
|
|
766
863
|
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
const previousStatus = runtime.activeGoal.status;
|
|
773
|
-
runtime.activeGoal = transitionGoal(
|
|
774
|
-
{
|
|
775
|
-
...nextGoalInstance(runtime.activeGoal),
|
|
776
|
-
text: objective,
|
|
777
|
-
tokenBudget: tokenBudget ?? runtime.activeGoal.tokenBudget,
|
|
778
|
-
},
|
|
779
|
-
editedGoalStatus(previousStatus),
|
|
864
|
+
function hasPendingSkipForGoal(goalId: string) {
|
|
865
|
+
return (
|
|
866
|
+
runtime.pendingQueueAction?.kind === "advance" &&
|
|
867
|
+
runtime.pendingQueueAction.reason === "skip" &&
|
|
868
|
+
runtime.pendingQueueAction.goalId === goalId
|
|
780
869
|
);
|
|
781
|
-
persistGoal(runtime.activeGoal);
|
|
782
|
-
updateStatus(ctx, runtime.activeGoal);
|
|
783
|
-
const editedGoal = runtime.activeGoal;
|
|
784
|
-
if (!editedGoal) return;
|
|
785
|
-
if (editedGoal.status === "active") {
|
|
786
|
-
clearStaleGoalToolCallBlock();
|
|
787
|
-
const sent = await sendObjectiveUpdatedPrompt(pi, ctx, editedGoal);
|
|
788
|
-
if (!sent) {
|
|
789
|
-
if (runtime.activeGoal?.id === editedGoal.id) {
|
|
790
|
-
if (previousStatus === "active") {
|
|
791
|
-
abortCurrentTurn(ctx);
|
|
792
|
-
runtime.activeGoal = transitionGoal(previousGoal, "paused");
|
|
793
|
-
blockStaleGoalToolCalls();
|
|
794
|
-
} else {
|
|
795
|
-
runtime.activeGoal = previousGoal;
|
|
796
|
-
if (blocksStaleGoalToolCalls(runtime.activeGoal.status)) blockStaleGoalToolCalls();
|
|
797
|
-
else clearStaleGoalToolCallBlock();
|
|
798
|
-
}
|
|
799
|
-
persistGoal(runtime.activeGoal);
|
|
800
|
-
updateStatus(ctx, runtime.activeGoal);
|
|
801
|
-
}
|
|
802
|
-
return;
|
|
803
|
-
}
|
|
804
|
-
} else if (blocksStaleGoalToolCalls(editedGoal.status)) {
|
|
805
|
-
blockStaleGoalToolCalls();
|
|
806
|
-
} else {
|
|
807
|
-
clearStaleGoalToolCallBlock();
|
|
808
|
-
}
|
|
809
|
-
ctx.ui.notify(`Goal updated: ${objective}`, "info");
|
|
810
|
-
}
|
|
811
|
-
|
|
812
|
-
function showGoal(ctx: StatusContext) {
|
|
813
|
-
if (!runtime.activeGoal) {
|
|
814
|
-
ctx.ui.notify("Usage: /goal <objective>\nNo goal is currently set.", "info");
|
|
815
|
-
ctx.ui.setStatus(STATUS_KEY, undefined);
|
|
816
|
-
return;
|
|
817
|
-
}
|
|
818
|
-
updateGoalUsage(runtime.activeGoal, ctx);
|
|
819
|
-
persistGoal(runtime.activeGoal);
|
|
820
|
-
updateStatus(ctx, runtime.activeGoal);
|
|
821
|
-
ctx.ui.notify(goalSummary(runtime.activeGoal), "info");
|
|
822
870
|
}
|
|
823
871
|
|
|
824
872
|
function stopGoalAfterAgentEnd(
|
|
@@ -857,509 +905,10 @@ function registerGoalRuntime(pi: ExtensionAPI) {
|
|
|
857
905
|
"warning",
|
|
858
906
|
);
|
|
859
907
|
}
|
|
860
|
-
|
|
861
|
-
function requestContinuation(goal: ActiveGoal) {
|
|
862
|
-
if (hasContinuationWorkForGoal(goal.id)) return false;
|
|
863
|
-
const marker = continuationMarker(goal);
|
|
864
|
-
runtime.continuationIntent = {
|
|
865
|
-
goalId: goal.id,
|
|
866
|
-
iteration: goal.iteration,
|
|
867
|
-
marker,
|
|
868
|
-
prompt: buildContinuePrompt(goal, marker),
|
|
869
|
-
};
|
|
870
|
-
return true;
|
|
871
|
-
}
|
|
872
|
-
|
|
873
|
-
function dispatchContinuationIfSettled(ctx: StatusContext) {
|
|
874
|
-
const intent = runtime.continuationIntent;
|
|
875
|
-
if (!intent) return false;
|
|
876
|
-
if (
|
|
877
|
-
!runtime.activeGoal ||
|
|
878
|
-
runtime.activeGoal.id !== intent.goalId ||
|
|
879
|
-
runtime.activeGoal.status !== "active"
|
|
880
|
-
) {
|
|
881
|
-
runtime.continuationIntent = undefined;
|
|
882
|
-
return false;
|
|
883
|
-
}
|
|
884
|
-
if (ctx.isIdle?.() !== true || hasPendingMessages(ctx)) return false;
|
|
885
|
-
|
|
886
|
-
runtime.continuationIntent = undefined;
|
|
887
|
-
runtime.continuationDelivery = intent;
|
|
888
|
-
try {
|
|
889
|
-
runtime.pi.sendUserMessage(intent.prompt);
|
|
890
|
-
return true;
|
|
891
|
-
} catch (error) {
|
|
892
|
-
if (runtime.continuationDelivery?.marker === intent.marker)
|
|
893
|
-
runtime.continuationDelivery = undefined;
|
|
894
|
-
if (runtime.activeGoal?.id === intent.goalId && runtime.activeGoal.status === "active") {
|
|
895
|
-
runtime.continuationIntent = intent;
|
|
896
|
-
}
|
|
897
|
-
ctx.ui.notify(`Goal prompt failed: ${formatError(error)}`, "error");
|
|
898
|
-
return false;
|
|
899
|
-
}
|
|
900
|
-
}
|
|
901
|
-
|
|
902
|
-
function hasContinuationWorkForGoal(goalId: string) {
|
|
903
|
-
return (
|
|
904
|
-
runtime.continuationIntent?.goalId === goalId ||
|
|
905
|
-
runtime.continuationDelivery?.goalId === goalId
|
|
906
|
-
);
|
|
907
|
-
}
|
|
908
|
-
|
|
909
|
-
function updateStatus(ctx: StatusContext, goal: ActiveGoal) {
|
|
910
|
-
clearCompletionStatusTimer();
|
|
911
|
-
ctx.ui.setStatus(STATUS_KEY, formatStatus(goal));
|
|
912
|
-
}
|
|
913
|
-
|
|
914
|
-
function blockStaleGoalToolCalls() {
|
|
915
|
-
runtime.staleGoalToolCallsBlocked = true;
|
|
916
|
-
}
|
|
917
|
-
|
|
918
|
-
function clearStaleGoalToolCallBlock() {
|
|
919
|
-
runtime.staleGoalToolCallsBlocked = false;
|
|
920
|
-
}
|
|
921
|
-
|
|
922
|
-
function clearGoalRecovery() {
|
|
923
|
-
runtime.goalRecovery = undefined;
|
|
924
|
-
}
|
|
925
|
-
|
|
926
|
-
function clearBudgetWrapUp() {
|
|
927
|
-
runtime.budgetWrapUp = undefined;
|
|
928
|
-
}
|
|
929
|
-
|
|
930
|
-
function keepBudgetWrapUpMessage(message: unknown) {
|
|
931
|
-
if (!message || typeof message !== "object") return true;
|
|
932
|
-
const candidate = message as {
|
|
933
|
-
role?: unknown;
|
|
934
|
-
customType?: unknown;
|
|
935
|
-
details?: { goalId?: unknown };
|
|
936
|
-
};
|
|
937
|
-
if (candidate.role !== "custom" || candidate.customType !== BUDGET_WRAP_UP_MESSAGE_TYPE) {
|
|
938
|
-
return true;
|
|
939
|
-
}
|
|
940
|
-
return (
|
|
941
|
-
typeof candidate.details?.goalId === "string" &&
|
|
942
|
-
candidate.details.goalId === runtime.budgetWrapUp?.goalId &&
|
|
943
|
-
candidate.details.goalId === runtime.activeGoal?.id
|
|
944
|
-
);
|
|
945
|
-
}
|
|
946
|
-
|
|
947
|
-
function queueBudgetWrapUp(ctx: StatusContext, goal: ActiveGoal) {
|
|
948
|
-
if (!runtime.budgetWrapUp || runtime.budgetWrapUp.goalId !== goal.id) {
|
|
949
|
-
runtime.budgetWrapUp = { goalId: goal.id, delivered: false };
|
|
950
|
-
}
|
|
951
|
-
if (runtime.budgetWrapUp.delivered) return true;
|
|
952
|
-
runtime.budgetWrapUp.delivered = true;
|
|
953
|
-
try {
|
|
954
|
-
runtime.pi.sendMessage(
|
|
955
|
-
{
|
|
956
|
-
customType: BUDGET_WRAP_UP_MESSAGE_TYPE,
|
|
957
|
-
content: BUDGET_WRAP_UP_PROMPT,
|
|
958
|
-
display: true,
|
|
959
|
-
details: { goalId: goal.id },
|
|
960
|
-
},
|
|
961
|
-
{ deliverAs: "steer" },
|
|
962
|
-
);
|
|
963
|
-
return true;
|
|
964
|
-
} catch (error) {
|
|
965
|
-
runtime.budgetWrapUp.delivered = false;
|
|
966
|
-
ctx.ui.notify(`Goal budget wrap-up failed: ${formatError(error)}`, "error");
|
|
967
|
-
return false;
|
|
968
|
-
}
|
|
969
|
-
}
|
|
970
|
-
|
|
971
|
-
function limitActiveGoalForBudget(ctx: StatusContext, sendWrapUp: boolean) {
|
|
972
|
-
const goal = runtime.activeGoal;
|
|
973
|
-
if (
|
|
974
|
-
goal?.status !== "active" ||
|
|
975
|
-
goal.tokenBudget === undefined ||
|
|
976
|
-
goal.tokensUsed < goal.tokenBudget
|
|
977
|
-
) {
|
|
978
|
-
return false;
|
|
979
|
-
}
|
|
980
|
-
|
|
981
|
-
cancelContinuationWork();
|
|
982
|
-
clearGoalRecoveryForGoal(goal.id);
|
|
983
|
-
clearBudgetWrapUp();
|
|
984
|
-
runtime.activeGoal = transitionGoal(goal, "budget_limited");
|
|
985
|
-
persistGoal(runtime.activeGoal);
|
|
986
|
-
updateStatus(ctx, runtime.activeGoal);
|
|
987
|
-
ctx.ui.notify(`Goal token budget reached: ${formatBudget(runtime.activeGoal)}`, "warning");
|
|
988
|
-
if (sendWrapUp) queueBudgetWrapUp(ctx, runtime.activeGoal);
|
|
989
|
-
return true;
|
|
990
|
-
}
|
|
991
|
-
|
|
992
|
-
function clearGoalRecoveryForGoal(goalId: string) {
|
|
993
|
-
if (runtime.goalRecovery?.goalId === goalId) runtime.goalRecovery = undefined;
|
|
994
|
-
}
|
|
995
|
-
|
|
996
|
-
function isPiOwnedCompactionRetry(event: unknown, goalId: string) {
|
|
997
|
-
const compaction = event as { reason?: unknown; willRetry?: unknown };
|
|
998
|
-
if (compaction.willRetry === true) return true;
|
|
999
|
-
return (
|
|
1000
|
-
runtime.goalRecovery?.goalId === goalId &&
|
|
1001
|
-
runtime.goalRecovery.kind === "compaction_retry" &&
|
|
1002
|
-
(compaction.reason === undefined || compaction.reason === "overflow")
|
|
1003
|
-
);
|
|
1004
|
-
}
|
|
1005
|
-
|
|
1006
|
-
function clearContinuationTracking() {
|
|
1007
|
-
runtime.continuationIntent = undefined;
|
|
1008
|
-
runtime.continuationDelivery = undefined;
|
|
1009
|
-
runtime.cancelledContinuationMarkers.clear();
|
|
1010
|
-
}
|
|
1011
|
-
|
|
1012
|
-
function cancelContinuationWork() {
|
|
1013
|
-
if (runtime.continuationDelivery)
|
|
1014
|
-
rememberCancelledContinuationMarker(runtime.continuationDelivery.marker);
|
|
1015
|
-
runtime.continuationIntent = undefined;
|
|
1016
|
-
runtime.continuationDelivery = undefined;
|
|
1017
|
-
}
|
|
1018
|
-
|
|
1019
|
-
function rememberCancelledContinuationMarker(marker: string) {
|
|
1020
|
-
runtime.cancelledContinuationMarkers.add(marker);
|
|
1021
|
-
if (runtime.cancelledContinuationMarkers.size <= MAX_CANCELLED_CONTINUATION_PROMPTS) return;
|
|
1022
|
-
const oldest = runtime.cancelledContinuationMarkers.values().next().value;
|
|
1023
|
-
if (oldest) runtime.cancelledContinuationMarkers.delete(oldest);
|
|
1024
|
-
}
|
|
1025
|
-
|
|
1026
|
-
function consumeCancelledContinuationPrompt(prompt: string) {
|
|
1027
|
-
const marker = extractContinuationMarker(prompt);
|
|
1028
|
-
return marker ? runtime.cancelledContinuationMarkers.delete(marker) : false;
|
|
1029
|
-
}
|
|
1030
|
-
|
|
1031
|
-
function markContinuationStarted(prompt: string) {
|
|
1032
|
-
const marker = extractContinuationMarker(prompt);
|
|
1033
|
-
if (!marker) {
|
|
1034
|
-
// A user, retry, or another extension started newer work. Cancel both an
|
|
1035
|
-
// unsent intent and a delivery that may have lost the non-atomic idle race;
|
|
1036
|
-
// the newer work's agent_end will record a fresh intent.
|
|
1037
|
-
cancelContinuationWork();
|
|
1038
|
-
return;
|
|
1039
|
-
}
|
|
1040
|
-
if (runtime.continuationDelivery?.marker === marker) runtime.continuationDelivery = undefined;
|
|
1041
|
-
}
|
|
1042
|
-
|
|
1043
|
-
function persistGoal(goal: ActiveGoal) {
|
|
1044
|
-
runtime.pi.appendEntry<GoalStateEntryData>(GOAL_STATE_ENTRY_TYPE, { goal });
|
|
1045
|
-
}
|
|
1046
|
-
|
|
1047
|
-
function clearPersistedGoal(cwd: string) {
|
|
1048
|
-
runtime.pi.appendEntry<GoalStateEntryData>(GOAL_STATE_ENTRY_TYPE, { goal: null });
|
|
1049
|
-
clearLegacyPersistedGoal(cwd);
|
|
1050
|
-
}
|
|
1051
|
-
|
|
1052
|
-
function clearActiveGoal(ctx: StatusContext) {
|
|
1053
|
-
cancelContinuationWork();
|
|
1054
|
-
clearGoalRecovery();
|
|
1055
|
-
clearBudgetWrapUp();
|
|
1056
|
-
clearStaleGoalToolCallBlock();
|
|
1057
|
-
runtime.activeGoal = undefined;
|
|
1058
|
-
clearPersistedGoal(ctx.cwd);
|
|
1059
|
-
ctx.ui.setStatus(STATUS_KEY, undefined);
|
|
1060
|
-
}
|
|
1061
|
-
|
|
1062
|
-
function showCompletionStatus(ctx: StatusContext) {
|
|
1063
|
-
clearCompletionStatusTimer();
|
|
1064
|
-
ctx.ui.setStatus(STATUS_KEY, "complete");
|
|
1065
|
-
runtime.completionStatusTimer = setTimeout(() => {
|
|
1066
|
-
runtime.completionStatusTimer = undefined;
|
|
1067
|
-
try {
|
|
1068
|
-
ctx.ui.setStatus(STATUS_KEY, undefined);
|
|
1069
|
-
} catch {
|
|
1070
|
-
// The completion status is best-effort; the captured ctx may be stale after
|
|
1071
|
-
// session replacement or reload before this timer fires.
|
|
1072
|
-
}
|
|
1073
|
-
}, 8_000);
|
|
1074
|
-
}
|
|
1075
|
-
|
|
1076
|
-
function clearCompletionStatusTimer() {
|
|
1077
|
-
if (!runtime.completionStatusTimer) return;
|
|
1078
|
-
clearTimeout(runtime.completionStatusTimer);
|
|
1079
|
-
runtime.completionStatusTimer = undefined;
|
|
1080
|
-
}
|
|
1081
|
-
}
|
|
1082
|
-
|
|
1083
|
-
function createGoal(
|
|
1084
|
-
text: string,
|
|
1085
|
-
tokenBudget: number | undefined,
|
|
1086
|
-
baselineTokens: number,
|
|
1087
|
-
): ActiveGoal {
|
|
1088
|
-
const now = Date.now();
|
|
1089
|
-
return {
|
|
1090
|
-
id: randomUUID(),
|
|
1091
|
-
text,
|
|
1092
|
-
status: "active",
|
|
1093
|
-
startedAt: now,
|
|
1094
|
-
updatedAt: now,
|
|
1095
|
-
iteration: 0,
|
|
1096
|
-
tokenBudget,
|
|
1097
|
-
tokensUsed: 0,
|
|
1098
|
-
timeUsedSeconds: 0,
|
|
1099
|
-
baselineTokens,
|
|
1100
|
-
activeStartedAt: now,
|
|
1101
|
-
};
|
|
1102
|
-
}
|
|
1103
|
-
|
|
1104
|
-
function transitionGoal(goal: ActiveGoal, requestedStatus: GoalStatus): ActiveGoal {
|
|
1105
|
-
const now = Date.now();
|
|
1106
|
-
const status =
|
|
1107
|
-
requestedStatus === "active" &&
|
|
1108
|
-
goal.tokenBudget !== undefined &&
|
|
1109
|
-
goal.tokensUsed >= goal.tokenBudget
|
|
1110
|
-
? "budget_limited"
|
|
1111
|
-
: requestedStatus;
|
|
1112
|
-
const next = { ...goal, status, updatedAt: now };
|
|
1113
|
-
checkpointGoalActiveTime(next, now, status === "active");
|
|
1114
|
-
return next;
|
|
1115
|
-
}
|
|
1116
|
-
|
|
1117
|
-
function nextGoalInstance(goal: ActiveGoal): ActiveGoal {
|
|
1118
|
-
return { ...goal, id: randomUUID(), updatedAt: Date.now() };
|
|
1119
|
-
}
|
|
1120
|
-
|
|
1121
|
-
function editedGoalStatus(status: GoalStatus): GoalStatus {
|
|
1122
|
-
if (status === "paused" || status === "blocked" || status === "usage_limited") return status;
|
|
1123
|
-
return "active";
|
|
1124
|
-
}
|
|
1125
|
-
|
|
1126
|
-
function incrementGoal(goal: ActiveGoal): ActiveGoal {
|
|
1127
|
-
return { ...goal, iteration: goal.iteration + 1, updatedAt: Date.now() };
|
|
1128
|
-
}
|
|
1129
|
-
|
|
1130
|
-
async function sendGoalPrompt(pi: ExtensionAPI, ctx: StatusContext, goal: ActiveGoal) {
|
|
1131
|
-
return sendPrompt(pi, ctx, buildGoalPrompt(goal));
|
|
1132
|
-
}
|
|
1133
|
-
|
|
1134
|
-
async function sendObjectiveUpdatedPrompt(pi: ExtensionAPI, ctx: StatusContext, goal: ActiveGoal) {
|
|
1135
|
-
return sendPrompt(pi, ctx, buildObjectiveUpdatedPrompt(goal));
|
|
1136
|
-
}
|
|
1137
|
-
|
|
1138
|
-
async function sendResumePrompt(
|
|
1139
|
-
pi: ExtensionAPI,
|
|
1140
|
-
ctx: StatusContext,
|
|
1141
|
-
goal: ActiveGoal,
|
|
1142
|
-
stoppedStatus: GoalStatus,
|
|
1143
|
-
) {
|
|
1144
|
-
return sendPrompt(pi, ctx, buildResumePrompt(goal, stoppedStatus));
|
|
1145
|
-
}
|
|
1146
|
-
|
|
1147
|
-
async function sendPrompt(pi: ExtensionAPI, ctx: StatusContext, prompt: string) {
|
|
1148
|
-
try {
|
|
1149
|
-
const sent = ctx.isIdle?.()
|
|
1150
|
-
? (pi.sendUserMessage(prompt) as void | Promise<void>)
|
|
1151
|
-
: (pi.sendUserMessage(prompt, { deliverAs: "followUp" }) as void | Promise<void>);
|
|
1152
|
-
await sent;
|
|
1153
|
-
return true;
|
|
1154
|
-
} catch (error) {
|
|
1155
|
-
ctx.ui.notify(`Goal prompt failed: ${formatError(error)}`, "error");
|
|
1156
|
-
return false;
|
|
1157
|
-
}
|
|
1158
|
-
}
|
|
1159
|
-
|
|
1160
|
-
export function formatStatus(goal: ActiveGoal | undefined) {
|
|
1161
|
-
if (!goal) return undefined;
|
|
1162
|
-
if (goal.status === "complete") return "complete";
|
|
1163
|
-
if (goal.status === "paused") return "paused";
|
|
1164
|
-
if (goal.status === "blocked") return "blocked";
|
|
1165
|
-
if (goal.status === "usage_limited") return "usage";
|
|
1166
|
-
if (goal.status === "budget_limited") return `budget ${formatBudget(goal)}`;
|
|
1167
|
-
if (goal.tokenBudget !== undefined) return `active ${formatBudget(goal)}`;
|
|
1168
|
-
return `active ${formatDuration(goal.timeUsedSeconds)}`;
|
|
1169
|
-
}
|
|
1170
|
-
|
|
1171
|
-
function formatBudget(goal: ActiveGoal) {
|
|
1172
|
-
return `${formatTokenCount(goal.tokensUsed)}/${formatTokenCount(goal.tokenBudget ?? 0)}`;
|
|
1173
|
-
}
|
|
1174
|
-
|
|
1175
|
-
function goalSummary(goal: ActiveGoal) {
|
|
1176
|
-
return [
|
|
1177
|
-
`Goal: ${goal.text}`,
|
|
1178
|
-
`Status: ${goal.status}`,
|
|
1179
|
-
`Iteration: ${goal.iteration}`,
|
|
1180
|
-
`Active elapsed: ${formatDuration(goal.timeUsedSeconds)}`,
|
|
1181
|
-
`Tokens: ${goal.tokenBudget === undefined ? formatTokenCount(goal.tokensUsed) : formatBudget(goal)}`,
|
|
1182
|
-
`Commands: ${goalCommandHint(goal.status)}`,
|
|
1183
|
-
].join("\n");
|
|
1184
|
-
}
|
|
1185
|
-
|
|
1186
|
-
function goalCommandHint(status: GoalStatus) {
|
|
1187
|
-
if (status === "active") return "/goal edit <objective>, /goal pause, /goal clear";
|
|
1188
|
-
if (isResumableGoalStatus(status)) {
|
|
1189
|
-
return "/goal edit <objective>, /goal resume, /goal clear";
|
|
1190
|
-
}
|
|
1191
|
-
return "/goal edit <objective>, /goal clear";
|
|
1192
|
-
}
|
|
1193
|
-
|
|
1194
|
-
function hasPendingMessages(ctx: StatusContext) {
|
|
1195
|
-
return ctx.hasPendingMessages?.() ?? false;
|
|
1196
|
-
}
|
|
1197
|
-
|
|
1198
|
-
function abortCurrentTurn(ctx: StatusContext) {
|
|
1199
|
-
try {
|
|
1200
|
-
ctx.abort?.();
|
|
1201
|
-
} catch {
|
|
1202
|
-
// Best effort: stale goal guards still prevent follow-on tool calls.
|
|
1203
|
-
}
|
|
1204
|
-
}
|
|
1205
|
-
|
|
1206
|
-
function blocksStaleGoalToolCalls(status: GoalStatus) {
|
|
1207
|
-
return status === "paused" || status === "blocked" || status === "usage_limited";
|
|
1208
|
-
}
|
|
1209
|
-
|
|
1210
|
-
function isResumableGoalStatus(status: GoalStatus) {
|
|
1211
|
-
return blocksStaleGoalToolCalls(status) || status === "budget_limited";
|
|
1212
|
-
}
|
|
1213
|
-
|
|
1214
|
-
function stoppedStatusLabel(status: GoalStatus) {
|
|
1215
|
-
if (status === "usage_limited") return "usage-limited";
|
|
1216
|
-
if (status === "budget_limited") return "budget-limited";
|
|
1217
|
-
return status;
|
|
1218
|
-
}
|
|
1219
|
-
|
|
1220
|
-
export function isContradictoryCompletionSummary(summary: string) {
|
|
1221
|
-
return CONTRADICTORY_COMPLETION_PATTERNS.some((pattern) => pattern.test(summary));
|
|
1222
|
-
}
|
|
1223
|
-
|
|
1224
|
-
function goalIdRejectionReason(goal: ActiveGoal, requestedGoalId: string) {
|
|
1225
|
-
if (!requestedGoalId) return "missing goal_id";
|
|
1226
|
-
if (requestedGoalId !== goal.id) return "goal_id does not match the active goal";
|
|
1227
|
-
return undefined;
|
|
1228
|
-
}
|
|
1229
|
-
|
|
1230
|
-
export function isUsageLimitedGoalInterruption(assistant: AssistantMessageLike) {
|
|
1231
|
-
const errorMessage = assistant.errorMessage;
|
|
1232
|
-
return (
|
|
1233
|
-
assistant.stopReason === "error" &&
|
|
1234
|
-
typeof errorMessage === "string" &&
|
|
1235
|
-
USAGE_LIMIT_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(errorMessage))
|
|
1236
|
-
);
|
|
1237
|
-
}
|
|
1238
|
-
|
|
1239
|
-
export function isRetryableGoalInterruption(assistant: AssistantMessageLike) {
|
|
1240
|
-
if (assistant.stopReason !== "error") return false;
|
|
1241
|
-
if (!assistant.errorMessage) return false;
|
|
1242
|
-
if (
|
|
1243
|
-
isUsageLimitedGoalInterruption(assistant) ||
|
|
1244
|
-
NON_RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage)
|
|
1245
|
-
) {
|
|
1246
|
-
return false;
|
|
1247
|
-
}
|
|
1248
|
-
return (
|
|
1249
|
-
isGoalContextOverflow(assistant) ||
|
|
1250
|
-
RETRYABLE_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(assistant.errorMessage ?? ""))
|
|
1251
|
-
);
|
|
1252
|
-
}
|
|
1253
|
-
|
|
1254
|
-
function isGoalContextOverflow(assistant: AssistantMessageLike) {
|
|
1255
|
-
return isContextOverflow(toPiAssistantMessage(assistant));
|
|
1256
908
|
}
|
|
1257
909
|
|
|
1258
|
-
function
|
|
1259
|
-
|
|
1260
|
-
role: "assistant",
|
|
1261
|
-
content: assistant.content ?? [],
|
|
1262
|
-
api: assistant.api ?? "openai-responses",
|
|
1263
|
-
provider: assistant.provider ?? "unknown",
|
|
1264
|
-
model: assistant.model ?? "unknown",
|
|
1265
|
-
usage: assistant.usage ?? zeroUsage(),
|
|
1266
|
-
stopReason: assistant.stopReason ?? "error",
|
|
1267
|
-
errorMessage: assistant.errorMessage,
|
|
1268
|
-
timestamp: assistant.timestamp ?? Date.now(),
|
|
1269
|
-
};
|
|
1270
|
-
}
|
|
1271
|
-
|
|
1272
|
-
function zeroUsage(): Usage {
|
|
1273
|
-
return {
|
|
1274
|
-
input: 0,
|
|
1275
|
-
output: 0,
|
|
1276
|
-
cacheRead: 0,
|
|
1277
|
-
cacheWrite: 0,
|
|
1278
|
-
totalTokens: 0,
|
|
1279
|
-
cost: {
|
|
1280
|
-
input: 0,
|
|
1281
|
-
output: 0,
|
|
1282
|
-
cacheRead: 0,
|
|
1283
|
-
cacheWrite: 0,
|
|
1284
|
-
total: 0,
|
|
1285
|
-
},
|
|
1286
|
-
};
|
|
1287
|
-
}
|
|
1288
|
-
|
|
1289
|
-
function continuationMarker(goal: ActiveGoal) {
|
|
1290
|
-
return `${goal.id}:${goal.iteration}:${randomUUID()}`;
|
|
1291
|
-
}
|
|
1292
|
-
|
|
1293
|
-
function escapeRegExpText(value: string) {
|
|
1294
|
-
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1295
|
-
}
|
|
1296
|
-
|
|
1297
|
-
const CONTINUATION_MARKER_PATTERN = new RegExp(
|
|
1298
|
-
`<!--\\s*${escapeRegExpText(CONTINUATION_MARKER_PREFIX)}([^\\s>]+)\\s*-->`,
|
|
1299
|
-
);
|
|
1300
|
-
|
|
1301
|
-
function extractContinuationMarker(prompt: string) {
|
|
1302
|
-
return CONTINUATION_MARKER_PATTERN.exec(prompt)?.[1];
|
|
1303
|
-
}
|
|
1304
|
-
|
|
1305
|
-
export function findFinalAssistantMessage(messages: unknown[]): AssistantMessageLike | undefined {
|
|
1306
|
-
for (let i = messages.length - 1; i >= 0; i--) {
|
|
1307
|
-
const message = messages[i];
|
|
1308
|
-
if (!message || typeof message !== "object") continue;
|
|
1309
|
-
const candidate = message as Record<string, unknown>;
|
|
1310
|
-
if (candidate.role !== "assistant") continue;
|
|
1311
|
-
const assistant: AssistantMessageLike = {
|
|
1312
|
-
role: "assistant",
|
|
1313
|
-
stopReason: isAgentStopReason(candidate.stopReason) ? candidate.stopReason : undefined,
|
|
1314
|
-
errorMessage: typeof candidate.errorMessage === "string" ? candidate.errorMessage : undefined,
|
|
1315
|
-
};
|
|
1316
|
-
if (Array.isArray(candidate.content))
|
|
1317
|
-
assistant.content = candidate.content as PiAssistantMessage["content"];
|
|
1318
|
-
if (typeof candidate.api === "string") assistant.api = candidate.api;
|
|
1319
|
-
if (typeof candidate.provider === "string") assistant.provider = candidate.provider;
|
|
1320
|
-
if (typeof candidate.model === "string") assistant.model = candidate.model;
|
|
1321
|
-
if (typeof candidate.timestamp === "number") assistant.timestamp = candidate.timestamp;
|
|
1322
|
-
const usage = normalizeUsage(candidate.usage);
|
|
1323
|
-
if (usage) assistant.usage = usage;
|
|
1324
|
-
return assistant;
|
|
1325
|
-
}
|
|
1326
|
-
return undefined;
|
|
1327
|
-
}
|
|
1328
|
-
|
|
1329
|
-
function isAgentStopReason(value: unknown): value is AgentStopReason {
|
|
1330
|
-
return ["stop", "length", "toolUse", "error", "aborted"].includes(String(value));
|
|
1331
|
-
}
|
|
1332
|
-
|
|
1333
|
-
function normalizeUsage(value: unknown): Usage | undefined {
|
|
1334
|
-
if (!value || typeof value !== "object") return undefined;
|
|
1335
|
-
const usage = value as Partial<Usage>;
|
|
1336
|
-
if (typeof usage.input !== "number" || typeof usage.output !== "number") return undefined;
|
|
1337
|
-
return {
|
|
1338
|
-
input: nonNegativeFiniteNumber(usage.input),
|
|
1339
|
-
output: nonNegativeFiniteNumber(usage.output),
|
|
1340
|
-
cacheRead: nonNegativeFiniteNumber(usage.cacheRead),
|
|
1341
|
-
cacheWrite: nonNegativeFiniteNumber(usage.cacheWrite),
|
|
1342
|
-
totalTokens: assistantUsageTokens(usage),
|
|
1343
|
-
cost: {
|
|
1344
|
-
input: usage.cost?.input ?? 0,
|
|
1345
|
-
output: usage.cost?.output ?? 0,
|
|
1346
|
-
cacheRead: usage.cost?.cacheRead ?? 0,
|
|
1347
|
-
cacheWrite: usage.cost?.cacheWrite ?? 0,
|
|
1348
|
-
total: usage.cost?.total ?? 0,
|
|
1349
|
-
},
|
|
1350
|
-
};
|
|
1351
|
-
}
|
|
1352
|
-
|
|
1353
|
-
function formatError(error: unknown) {
|
|
1354
|
-
return truncateNotification(error instanceof Error ? error.message : String(error));
|
|
1355
|
-
}
|
|
1356
|
-
|
|
1357
|
-
function truncateNotification(value: string) {
|
|
1358
|
-
return value.length > 160 ? `${value.slice(0, 157)}...` : value;
|
|
1359
|
-
}
|
|
1360
|
-
|
|
1361
|
-
export default function goal(pi: ExtensionAPI) {
|
|
1362
|
-
registerGoalRuntime(pi);
|
|
910
|
+
export default function goal(pi: ExtensionAPI, options: GoalOptions = {}) {
|
|
911
|
+
registerGoalRuntime(pi, options);
|
|
1363
912
|
}
|
|
1364
913
|
|
|
1365
914
|
export {
|
|
@@ -1377,3 +926,11 @@ export {
|
|
|
1377
926
|
} from "./command.js";
|
|
1378
927
|
|
|
1379
928
|
export { buildGoalSystemPrompt } from "./prompts.js";
|
|
929
|
+
|
|
930
|
+
export {
|
|
931
|
+
findFinalAssistantMessage,
|
|
932
|
+
formatStatus,
|
|
933
|
+
isContradictoryCompletionSummary,
|
|
934
|
+
isRetryableGoalInterruption,
|
|
935
|
+
isUsageLimitedGoalInterruption,
|
|
936
|
+
} from "./runtime.js";
|