@narumitw/pi-goal 0.18.0 → 0.24.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 +33 -0
- package/package.json +4 -4
- package/src/commands.ts +10 -3
- package/src/goal.ts +24 -1
- package/src/rpc.ts +188 -0
- package/src/runtime.ts +79 -3
package/README.md
CHANGED
|
@@ -166,6 +166,38 @@ Do not use `goal_blocked` merely because work is difficult, incomplete, uncertai
|
|
|
166
166
|
|
|
167
167
|
A user pause or aborted turn produces `paused`; a terminal provider/account quota error produces `usage_limited`; another non-retryable agent error produces `blocked`. Each stopped transition cancels pending continuation intent or delivery, aborts stale work when applicable, and blocks stale tool calls until the next non-goal user prompt, successful reactivation/replacement, or `/goal clear`. On `/goal clear`, the extension clears goal state, continuation markers, and any stale tool-call block without aborting an unrelated in-flight turn. Retryable provider interruptions and overflow compaction retries stay `active` while Pi retries; no extra continuation is queued. User and extension work that starts before settlement supersedes the older continuation intent, and pending messages always take priority.
|
|
168
168
|
|
|
169
|
+
## 🤝 Cross-extension RPC and events
|
|
170
|
+
|
|
171
|
+
pi-goal exposes a session-local, dependency-free integration contract over Pi's shared `pi.events` bus so sibling extensions (such as `@tintinweb/pi-subagents`) can start, pause, and observe goals programmatically without driving the `/goal` slash command. The contract is bound only while a Pi session is active: it is established on `session_start` and the captured session context is unbound on `session_shutdown`. All channels are plain JSON-shaped payloads; this extension never adds a runtime dependency for them.
|
|
172
|
+
|
|
173
|
+
### Starting a goal: `pi-goal:rpc:start`
|
|
174
|
+
|
|
175
|
+
Emit `pi-goal:rpc:start` with `{ requestId: string, objective: string, tokenBudget?: number }`. `tokenBudget` is an absolute positive integer token count (for example `100000`), not a `k`/`m` string. The request reuses the same `startGoal()` transition as the slash command, so it never implements goal transitions twice.
|
|
176
|
+
|
|
177
|
+
pi-goal replies on `pi-goal:rpc:start:reply:${requestId}` with one of:
|
|
178
|
+
|
|
179
|
+
```jsonc
|
|
180
|
+
// success
|
|
181
|
+
{ "success": true, "data": { "goalId": "<uuid>", "status": "active" } }
|
|
182
|
+
// failure (validation, no session, pre-existing goal, or failed activation)
|
|
183
|
+
{ "success": false, "error": "<human-readable reason>" }
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
Behavior notes:
|
|
187
|
+
|
|
188
|
+
- Malformed payloads (missing/empty/non-string `objective`, or a non-positive-integer `tokenBudget`) fail fast with a descriptive `error`.
|
|
189
|
+
- If no session context is bound (before `session_start` or after `session_shutdown`), the reply is a failure rather than starting a goal.
|
|
190
|
+
- RPC starts run in a fresh child context, so a **pre-existing goal fails** instead of prompting, replacing, or reusing stale state. Clear the existing goal first.
|
|
191
|
+
- The reply `status` is read from the authoritative goal state, so an immediate terminal outcome during start is represented rather than assumed to be `active`.
|
|
192
|
+
|
|
193
|
+
### Pausing a goal: `pi-goal:rpc:pause`
|
|
194
|
+
|
|
195
|
+
Emit `pi-goal:rpc:pause` with `{ goalId?: string, requestId?: string, reason?: string }` to stop an active RPC-owned goal safely. After a successful start reply, pass its `goalId`. To cancel while the start reply is still pending, omit `goalId` and pass the originating start `requestId`. Uncorrelated requests, stale request IDs, mismatched goal IDs, and goals not created through RPC are ignored. A successful pause uses the normal Goal pause transition and emits the authoritative `pi-goal:state` event described below.
|
|
196
|
+
|
|
197
|
+
### Observing goal state: `pi-goal:state`
|
|
198
|
+
|
|
199
|
+
Whenever pi-goal persists canonical goal state, it emits `pi-goal:state` with `{ goalId, status, summary?, reason? }`. `goalId` and `status` are always authoritative. Terminal statuses are `complete`, `blocked`, `paused`, `usage_limited`, `budget_limited`, and `cleared`. Explicit clears and failed activation rollbacks emit `cleared` for the removed goal so observers cannot retain stale active state. `summary` is populated from the matching `goal_complete` summary when available, and `reason` is populated from the same goal instance's blocked/usage/budget/clear state where available; an `active` or `queued` event carries only `goalId` and `status`. Listeners must treat any non-terminal status as in-progress and should key follow-up behavior on `goalId` plus a terminal `status`.
|
|
200
|
+
|
|
169
201
|
## 🧠 Use cases
|
|
170
202
|
|
|
171
203
|
- Finish implementation tasks without stopping at a plan.
|
|
@@ -182,6 +214,7 @@ extensions/pi-goal/
|
|
|
182
214
|
│ ├── goal.ts # Pi entrypoint, tool contracts, and lifecycle orchestration
|
|
183
215
|
│ ├── commands.ts # Per-factory user-command and queue mutation controller
|
|
184
216
|
│ ├── runtime.ts # Per-factory state, prompt ownership, budgets, and tool policy
|
|
217
|
+
│ ├── rpc.ts # Session-local cross-extension request ownership and replies
|
|
185
218
|
│ ├── queue.ts # Pure ordered-goal transitions
|
|
186
219
|
│ └── *.ts # Package-local parsing, settings, prompts, accounting, and persistence
|
|
187
220
|
├── README.md
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@narumitw/pi-goal",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.24.0",
|
|
4
4
|
"description": "Pi extension for autonomous /goal completion with opt-in experimental ordered queues.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -34,9 +34,9 @@
|
|
|
34
34
|
},
|
|
35
35
|
"devDependencies": {
|
|
36
36
|
"@biomejs/biome": "2.5.3",
|
|
37
|
-
"@earendil-works/pi-ai": "0.80.
|
|
38
|
-
"@earendil-works/pi-coding-agent": "0.80.
|
|
39
|
-
"typescript": "
|
|
37
|
+
"@earendil-works/pi-ai": "0.80.10",
|
|
38
|
+
"@earendil-works/pi-coding-agent": "0.80.10",
|
|
39
|
+
"typescript": "7.0.2"
|
|
40
40
|
},
|
|
41
41
|
"repository": {
|
|
42
42
|
"type": "git",
|
package/src/commands.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { currentTokenTotal } from "./accounting.js";
|
|
2
2
|
import { validateObjective } from "./command.js";
|
|
3
|
+
import type { ActiveGoal } from "./persistence.js";
|
|
3
4
|
import { buildGoalPrompt, buildObjectiveUpdatedPrompt, buildResumePrompt } from "./prompts.js";
|
|
4
5
|
import {
|
|
5
6
|
activateQueuedGoal,
|
|
@@ -36,7 +37,12 @@ export class GoalCommandController {
|
|
|
36
37
|
this.runtime = runtime;
|
|
37
38
|
}
|
|
38
39
|
|
|
39
|
-
async startGoal(
|
|
40
|
+
async startGoal(
|
|
41
|
+
objective: string,
|
|
42
|
+
tokenBudget: number | undefined,
|
|
43
|
+
ctx: StatusContext,
|
|
44
|
+
onActivated?: (goal: ActiveGoal) => void,
|
|
45
|
+
) {
|
|
40
46
|
const validationError = validateObjective(objective);
|
|
41
47
|
if (validationError) {
|
|
42
48
|
ctx.ui.notify(validationError, "warning");
|
|
@@ -75,9 +81,10 @@ export class GoalCommandController {
|
|
|
75
81
|
this.runtime.queuedGoals = [];
|
|
76
82
|
this.runtime.pendingQueueAction = undefined;
|
|
77
83
|
this.runtime.activeGoal = createGoal(objective, tokenBudget, currentTokenTotal(ctx));
|
|
78
|
-
this.runtime.persistGoal(this.runtime.activeGoal);
|
|
79
|
-
this.runtime.updateStatus(ctx, this.runtime.activeGoal);
|
|
80
84
|
const startedGoal = this.runtime.activeGoal;
|
|
85
|
+
onActivated?.(startedGoal);
|
|
86
|
+
this.runtime.persistGoal(startedGoal);
|
|
87
|
+
this.runtime.updateStatus(ctx, startedGoal);
|
|
81
88
|
const sent = await this.runtime.sendOwnedGoalPrompt(
|
|
82
89
|
ctx,
|
|
83
90
|
startedGoal.id,
|
package/src/goal.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { GoalCommandController } from "./commands.js";
|
|
|
6
6
|
import { type ActiveGoal, loadGoalStateFromSession } from "./persistence.js";
|
|
7
7
|
import { buildGoalPrompt, buildGoalSystemPrompt } from "./prompts.js";
|
|
8
8
|
import { activateQueuedGoal } from "./queue.js";
|
|
9
|
+
import { GoalRpcController } from "./rpc.js";
|
|
9
10
|
import {
|
|
10
11
|
type AssistantMessageLike,
|
|
11
12
|
abortCurrentTurn,
|
|
@@ -56,9 +57,21 @@ const EXPERIMENTAL_GOALS_WARNING =
|
|
|
56
57
|
const MAX_BLOCKER_REASON_LENGTH = 1_000;
|
|
57
58
|
const MAX_BLOCKER_EVIDENCE_LENGTH = 4_000;
|
|
58
59
|
|
|
60
|
+
type AgentSettledHandler = (event: unknown, ctx: StatusContext) => unknown;
|
|
61
|
+
|
|
62
|
+
function onAgentSettled(pi: ExtensionAPI, handler: AgentSettledHandler) {
|
|
63
|
+
(
|
|
64
|
+
pi as unknown as {
|
|
65
|
+
on(event: "agent_settled", callback: AgentSettledHandler): void;
|
|
66
|
+
}
|
|
67
|
+
).on("agent_settled", handler);
|
|
68
|
+
}
|
|
69
|
+
|
|
59
70
|
function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
|
|
60
71
|
const runtime = new GoalRuntime(pi);
|
|
61
72
|
const commands = new GoalCommandController(runtime);
|
|
73
|
+
const rpc = new GoalRpcController(runtime, commands);
|
|
74
|
+
rpc.register(pi);
|
|
62
75
|
|
|
63
76
|
// Bind per-factory runtime operations once so event orchestration stays concise
|
|
64
77
|
// without reintroducing module-global mutable state.
|
|
@@ -215,6 +228,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
|
|
|
215
228
|
}
|
|
216
229
|
|
|
217
230
|
runtime.activeGoal = transitionGoal(completedGoal, "complete");
|
|
231
|
+
runtime.setCompletionSummary(runtime.activeGoal.id, summary);
|
|
218
232
|
updateGoalUsage(runtime.activeGoal, ctx);
|
|
219
233
|
if (runtime.pendingQueueAction?.kind === "prioritize") {
|
|
220
234
|
persistGoal(runtime.activeGoal);
|
|
@@ -358,6 +372,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
|
|
|
358
372
|
clearGoalRecoveryForGoal(blockedGoal.id);
|
|
359
373
|
blockStaleGoalToolCalls();
|
|
360
374
|
runtime.activeGoal = transitionGoal(blockedGoal, "blocked");
|
|
375
|
+
runtime.setTerminalReason(runtime.activeGoal.id, reason);
|
|
361
376
|
persistGoal(runtime.activeGoal);
|
|
362
377
|
updateStatus(ctx, runtime.activeGoal);
|
|
363
378
|
ctx.ui.notify(`Goal blocked: ${truncateNotification(reason)}`, "warning");
|
|
@@ -456,6 +471,8 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
|
|
|
456
471
|
runtime.queuedGoals = [];
|
|
457
472
|
runtime.pendingQueueAction = undefined;
|
|
458
473
|
runtime.queueFrozen = false;
|
|
474
|
+
runtime.clearTerminalDetails();
|
|
475
|
+
rpc.bindSession(ctx);
|
|
459
476
|
const previousToolVisibility = runtime.settings.toolVisibility;
|
|
460
477
|
const settingsResult = readGoalSettings(options.settingsPath);
|
|
461
478
|
runtime.settings =
|
|
@@ -570,6 +587,8 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
|
|
|
570
587
|
runtime.queueFrozen = false;
|
|
571
588
|
ctx.ui.setStatus(STATUS_KEY, undefined);
|
|
572
589
|
clearCompletionStatusTimer();
|
|
590
|
+
runtime.clearTerminalDetails();
|
|
591
|
+
rpc.unbindSession();
|
|
573
592
|
});
|
|
574
593
|
|
|
575
594
|
pi.on("session_before_compact", (event, ctx) => {
|
|
@@ -857,7 +876,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
|
|
|
857
876
|
requestContinuation(currentGoal);
|
|
858
877
|
});
|
|
859
878
|
|
|
860
|
-
pi
|
|
879
|
+
onAgentSettled(pi, (_event, ctx) => {
|
|
861
880
|
if (runtime.queueFrozen) return;
|
|
862
881
|
if (!runtime.pendingQueueAction) {
|
|
863
882
|
dispatchContinuationIfSettled(ctx);
|
|
@@ -887,6 +906,10 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
|
|
|
887
906
|
blockStaleGoalToolCalls();
|
|
888
907
|
abortCurrentTurn(ctx);
|
|
889
908
|
runtime.activeGoal = transitionGoal(goal, status);
|
|
909
|
+
runtime.setTerminalReason(
|
|
910
|
+
runtime.activeGoal.id,
|
|
911
|
+
assistant.errorMessage ?? `goal ${status} after agent interruption`,
|
|
912
|
+
);
|
|
890
913
|
persistGoal(runtime.activeGoal);
|
|
891
914
|
updateStatus(ctx, runtime.activeGoal);
|
|
892
915
|
|
package/src/rpc.ts
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { validateObjective } from "./command.js";
|
|
3
|
+
import type { GoalCommandController } from "./commands.js";
|
|
4
|
+
import type { GoalStatus } from "./prompts.js";
|
|
5
|
+
import { formatError, type GoalRuntime, type StatusContext } from "./runtime.js";
|
|
6
|
+
|
|
7
|
+
// Cross-extension RPC contract over Pi's session-local events bus. pi-subagents
|
|
8
|
+
// (or any sibling extension) starts or pauses a goal through RPC; pi-goal replies
|
|
9
|
+
// to starts and broadcasts `pi-goal:state` from the runtime persistence boundary.
|
|
10
|
+
const RPC_START_CHANNEL = "pi-goal:rpc:start";
|
|
11
|
+
const RPC_PAUSE_CHANNEL = "pi-goal:rpc:pause";
|
|
12
|
+
|
|
13
|
+
interface GoalRpcStartPayload {
|
|
14
|
+
requestId: string;
|
|
15
|
+
objective: string;
|
|
16
|
+
tokenBudget?: number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
interface GoalRpcPausePayload {
|
|
20
|
+
requestId?: string;
|
|
21
|
+
goalId?: string;
|
|
22
|
+
reason?: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
type GoalRpcReply =
|
|
26
|
+
| { success: true; data: { goalId: string; status: GoalStatus } }
|
|
27
|
+
| { success: false; error: string };
|
|
28
|
+
|
|
29
|
+
interface GoalRpcOwnership {
|
|
30
|
+
requestId: string;
|
|
31
|
+
goalId: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function rpcReplyChannel(requestId: string) {
|
|
35
|
+
return `pi-goal:rpc:start:reply:${requestId}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function parseRpcStartPayload(
|
|
39
|
+
payload: Partial<GoalRpcStartPayload> | null,
|
|
40
|
+
): string | { objective: string; tokenBudget?: number } {
|
|
41
|
+
if (!payload || typeof payload !== "object") return "rpc:start payload is missing";
|
|
42
|
+
if (typeof payload.objective !== "string") return "objective must be a string";
|
|
43
|
+
const objective = payload.objective.trim();
|
|
44
|
+
const objectiveError = validateObjective(objective);
|
|
45
|
+
if (objectiveError) return objectiveError;
|
|
46
|
+
let tokenBudget: number | undefined;
|
|
47
|
+
if (payload.tokenBudget !== undefined) {
|
|
48
|
+
if (
|
|
49
|
+
typeof payload.tokenBudget !== "number" ||
|
|
50
|
+
!Number.isFinite(payload.tokenBudget) ||
|
|
51
|
+
!Number.isSafeInteger(payload.tokenBudget) ||
|
|
52
|
+
payload.tokenBudget <= 0
|
|
53
|
+
) {
|
|
54
|
+
return "tokenBudget must be a positive integer";
|
|
55
|
+
}
|
|
56
|
+
tokenBudget = payload.tokenBudget;
|
|
57
|
+
}
|
|
58
|
+
return { objective, tokenBudget };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export class GoalRpcController {
|
|
62
|
+
private readonly runtime: GoalRuntime;
|
|
63
|
+
private readonly commands: GoalCommandController;
|
|
64
|
+
private sessionContext?: StatusContext;
|
|
65
|
+
private ownership?: GoalRpcOwnership;
|
|
66
|
+
|
|
67
|
+
constructor(runtime: GoalRuntime, commands: GoalCommandController) {
|
|
68
|
+
this.runtime = runtime;
|
|
69
|
+
this.commands = commands;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
register(pi: ExtensionAPI) {
|
|
73
|
+
pi.events.on(RPC_START_CHANNEL, (data) => {
|
|
74
|
+
void this.handleStart(data);
|
|
75
|
+
});
|
|
76
|
+
pi.events.on(RPC_PAUSE_CHANNEL, (data) => {
|
|
77
|
+
this.handlePause(data);
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
bindSession(ctx: StatusContext) {
|
|
82
|
+
this.sessionContext = ctx;
|
|
83
|
+
this.ownership = undefined;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
unbindSession() {
|
|
87
|
+
this.sessionContext = undefined;
|
|
88
|
+
this.ownership = undefined;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
private async handleStart(data: unknown) {
|
|
92
|
+
const payload = data as Partial<GoalRpcStartPayload> | null;
|
|
93
|
+
const requestId = typeof payload?.requestId === "string" ? payload.requestId.trim() : "";
|
|
94
|
+
// Without a usable requestId there is no reply channel to address safely.
|
|
95
|
+
if (!requestId) return;
|
|
96
|
+
const reply = (envelope: GoalRpcReply) =>
|
|
97
|
+
this.runtime.pi.events.emit(rpcReplyChannel(requestId), envelope);
|
|
98
|
+
|
|
99
|
+
const sessionContext = this.sessionContext;
|
|
100
|
+
if (!sessionContext) {
|
|
101
|
+
reply({ success: false, error: "no active pi-goal session context" });
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
const parsed = parseRpcStartPayload(payload);
|
|
105
|
+
if (typeof parsed === "string") {
|
|
106
|
+
reply({ success: false, error: parsed });
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
// RPC starts run in a fresh child: any pre-existing goal must fail rather
|
|
110
|
+
// than trigger interactive replacement confirmation or reuse stale state.
|
|
111
|
+
const existingGoal = this.runtime.activeGoal;
|
|
112
|
+
if (existingGoal) {
|
|
113
|
+
reply({
|
|
114
|
+
success: false,
|
|
115
|
+
error: "a goal already exists; clear it before starting another via RPC",
|
|
116
|
+
});
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
let activatedGoalId: string | undefined;
|
|
121
|
+
try {
|
|
122
|
+
await this.commands.startGoal(
|
|
123
|
+
parsed.objective,
|
|
124
|
+
parsed.tokenBudget,
|
|
125
|
+
sessionContext,
|
|
126
|
+
(goal) => {
|
|
127
|
+
activatedGoalId = goal.id;
|
|
128
|
+
this.ownership = { requestId, goalId: goal.id };
|
|
129
|
+
},
|
|
130
|
+
);
|
|
131
|
+
} catch (error) {
|
|
132
|
+
this.clearOwnership(requestId, activatedGoalId);
|
|
133
|
+
reply({ success: false, error: `goal start failed: ${formatError(error)}` });
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// Read only the goal activated by this request. A replacement or clear that
|
|
138
|
+
// wins while kickoff delivery is pending must not be reported as this start.
|
|
139
|
+
const goal = this.runtime.activeGoal;
|
|
140
|
+
if (!goal || !activatedGoalId || goal.id !== activatedGoalId) {
|
|
141
|
+
this.clearOwnership(requestId, activatedGoalId);
|
|
142
|
+
reply({
|
|
143
|
+
success: false,
|
|
144
|
+
error:
|
|
145
|
+
"goal start failed; the objective could not be activated (goal tools unavailable, kickoff delivery failed, or the goal was superseded)",
|
|
146
|
+
});
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
reply({ success: true, data: { goalId: goal.id, status: goal.status } });
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
private handlePause(data: unknown) {
|
|
153
|
+
const sessionContext = this.sessionContext;
|
|
154
|
+
const goal = this.runtime.activeGoal;
|
|
155
|
+
const ownership = this.ownership;
|
|
156
|
+
if (
|
|
157
|
+
!sessionContext ||
|
|
158
|
+
goal?.status !== "active" ||
|
|
159
|
+
!ownership ||
|
|
160
|
+
ownership.goalId !== goal.id
|
|
161
|
+
) {
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const payload = data as GoalRpcPausePayload | null;
|
|
166
|
+
const goalId = typeof payload?.goalId === "string" ? payload.goalId : undefined;
|
|
167
|
+
if (goalId !== undefined) {
|
|
168
|
+
if (goalId !== goal.id) return;
|
|
169
|
+
} else {
|
|
170
|
+
const requestId =
|
|
171
|
+
typeof payload?.requestId === "string" ? payload.requestId.trim() : undefined;
|
|
172
|
+
if (!requestId || requestId !== ownership.requestId) return;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const reason = typeof payload?.reason === "string" ? payload.reason.trim() : "";
|
|
176
|
+
this.runtime.setTerminalReason(goal.id, reason || "goal paused by RPC");
|
|
177
|
+
this.commands.pauseGoal(sessionContext);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
private clearOwnership(requestId: string, goalId: string | undefined) {
|
|
181
|
+
if (
|
|
182
|
+
this.ownership?.requestId === requestId &&
|
|
183
|
+
(goalId === undefined || this.ownership.goalId === goalId)
|
|
184
|
+
) {
|
|
185
|
+
this.ownership = undefined;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
package/src/runtime.ts
CHANGED
|
@@ -80,6 +80,48 @@ export const GOAL_COMPLETE_TOOL = "goal_complete";
|
|
|
80
80
|
export const GOAL_BLOCKED_TOOL = "goal_blocked";
|
|
81
81
|
export const GOAL_TOOL_NAMES = [GOAL_COMPLETE_TOOL, GOAL_BLOCKED_TOOL] as const;
|
|
82
82
|
|
|
83
|
+
/** Cross-extension event channel carrying the canonical persisted goal state. */
|
|
84
|
+
export const GOAL_STATE_EVENT_CHANNEL = "pi-goal:state";
|
|
85
|
+
|
|
86
|
+
/** State values broadcast to cross-extension listeners. */
|
|
87
|
+
export type GoalStateEventStatus = GoalStatus | "cleared";
|
|
88
|
+
|
|
89
|
+
/** Payload emitted on {@link GOAL_STATE_EVENT_CHANNEL} whenever goal state persists. */
|
|
90
|
+
export interface GoalStateEventPayload {
|
|
91
|
+
goalId: string;
|
|
92
|
+
status: GoalStateEventStatus;
|
|
93
|
+
summary?: string;
|
|
94
|
+
reason?: string;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Terminal statuses broadcast to cross-extension listeners. */
|
|
98
|
+
export function isTerminalGoalStatus(status: GoalStateEventStatus): boolean {
|
|
99
|
+
return status !== "active" && status !== "queued";
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Build the cross-extension state payload from the canonical goal plus the most
|
|
104
|
+
* recent completion summary or blocked/failure reason, without re-deriving state.
|
|
105
|
+
*/
|
|
106
|
+
export function buildGoalStateEvent(
|
|
107
|
+
goal: ActiveGoal,
|
|
108
|
+
summary: string | undefined,
|
|
109
|
+
reason: string | undefined,
|
|
110
|
+
): GoalStateEventPayload {
|
|
111
|
+
const payload: GoalStateEventPayload = { goalId: goal.id, status: goal.status };
|
|
112
|
+
if (goal.status === "complete" && summary) payload.summary = summary;
|
|
113
|
+
else if (goal.status !== "complete" && isTerminalGoalStatus(goal.status) && reason) {
|
|
114
|
+
payload.reason = reason;
|
|
115
|
+
}
|
|
116
|
+
return payload;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
interface GoalTerminalDetails {
|
|
120
|
+
goalId: string;
|
|
121
|
+
summary?: string;
|
|
122
|
+
reason?: string;
|
|
123
|
+
}
|
|
124
|
+
|
|
83
125
|
const MAX_CANCELLED_CONTINUATION_PROMPTS = 20;
|
|
84
126
|
const MAX_PENDING_GOAL_PROMPTS = 20;
|
|
85
127
|
const GOAL_PROMPT_MARKER_PREFIX = "pi-goal-prompt:";
|
|
@@ -115,6 +157,8 @@ const RETRYABLE_GOAL_ERROR_PATTERNS = [
|
|
|
115
157
|
export class GoalRuntime {
|
|
116
158
|
settings: GoalSettings = DEFAULT_GOAL_SETTINGS;
|
|
117
159
|
activeGoal?: ActiveGoal;
|
|
160
|
+
/** Terminal details captured for the matching cross-extension state event. */
|
|
161
|
+
private terminalDetails?: GoalTerminalDetails;
|
|
118
162
|
queuedGoals: ActiveGoal[] = [];
|
|
119
163
|
pendingQueueAction?: PendingQueueAction;
|
|
120
164
|
queueFrozen = false;
|
|
@@ -244,6 +288,18 @@ export class GoalRuntime {
|
|
|
244
288
|
this.budgetWrapUp = undefined;
|
|
245
289
|
}
|
|
246
290
|
|
|
291
|
+
setCompletionSummary(goalId: string, summary: string) {
|
|
292
|
+
this.terminalDetails = { goalId, summary };
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
setTerminalReason(goalId: string, reason: string) {
|
|
296
|
+
this.terminalDetails = { goalId, reason };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
clearTerminalDetails() {
|
|
300
|
+
this.terminalDetails = undefined;
|
|
301
|
+
}
|
|
302
|
+
|
|
247
303
|
keepBudgetWrapUpMessage(message: unknown) {
|
|
248
304
|
if (!message || typeof message !== "object") return true;
|
|
249
305
|
const candidate = message as {
|
|
@@ -299,6 +355,10 @@ export class GoalRuntime {
|
|
|
299
355
|
this.clearGoalRecoveryForGoal(goal.id);
|
|
300
356
|
this.clearBudgetWrapUp();
|
|
301
357
|
this.activeGoal = transitionGoal(goal, "budget_limited");
|
|
358
|
+
this.setTerminalReason(
|
|
359
|
+
this.activeGoal.id,
|
|
360
|
+
`token budget reached (${formatBudget(this.activeGoal)})`,
|
|
361
|
+
);
|
|
302
362
|
this.persistGoal(this.activeGoal);
|
|
303
363
|
this.updateStatus(ctx, this.activeGoal);
|
|
304
364
|
ctx.ui.notify(`Goal token budget reached: ${formatBudget(this.activeGoal)}`, "warning");
|
|
@@ -381,18 +441,34 @@ export class GoalRuntime {
|
|
|
381
441
|
}
|
|
382
442
|
|
|
383
443
|
persistGoal(goal: ActiveGoal) {
|
|
444
|
+
if (!isTerminalGoalStatus(goal.status) || this.terminalDetails?.goalId !== goal.id) {
|
|
445
|
+
this.clearTerminalDetails();
|
|
446
|
+
}
|
|
384
447
|
this.pi.appendEntry(
|
|
385
448
|
GOAL_STATE_ENTRY_TYPE,
|
|
386
449
|
serializeGoalState(goal, this.queuedGoals, this.pendingQueueAction),
|
|
387
450
|
);
|
|
451
|
+
this.pi.events.emit(
|
|
452
|
+
GOAL_STATE_EVENT_CHANNEL,
|
|
453
|
+
buildGoalStateEvent(goal, this.terminalDetails?.summary, this.terminalDetails?.reason),
|
|
454
|
+
);
|
|
388
455
|
}
|
|
389
456
|
|
|
390
|
-
clearPersistedGoal(cwd: string) {
|
|
457
|
+
clearPersistedGoal(cwd: string, clearedGoal?: ActiveGoal, reason = "goal cleared") {
|
|
391
458
|
this.pi.appendEntry(GOAL_STATE_ENTRY_TYPE, serializeGoalState(undefined, [], undefined));
|
|
459
|
+
if (clearedGoal) {
|
|
460
|
+
this.pi.events.emit(GOAL_STATE_EVENT_CHANNEL, {
|
|
461
|
+
goalId: clearedGoal.id,
|
|
462
|
+
status: "cleared",
|
|
463
|
+
reason,
|
|
464
|
+
} satisfies GoalStateEventPayload);
|
|
465
|
+
}
|
|
466
|
+
this.clearTerminalDetails();
|
|
392
467
|
clearLegacyPersistedGoal(cwd);
|
|
393
468
|
}
|
|
394
469
|
|
|
395
|
-
clearActiveGoal(ctx: StatusContext) {
|
|
470
|
+
clearActiveGoal(ctx: StatusContext, reason = "goal cleared") {
|
|
471
|
+
const clearedGoal = this.activeGoal;
|
|
396
472
|
this.cancelContinuationWork();
|
|
397
473
|
this.clearGoalRecovery();
|
|
398
474
|
this.clearBudgetWrapUp();
|
|
@@ -401,7 +477,7 @@ export class GoalRuntime {
|
|
|
401
477
|
this.queuedGoals = [];
|
|
402
478
|
this.pendingQueueAction = undefined;
|
|
403
479
|
this.queueFrozen = false;
|
|
404
|
-
this.clearPersistedGoal(ctx.cwd);
|
|
480
|
+
this.clearPersistedGoal(ctx.cwd, clearedGoal, reason);
|
|
405
481
|
ctx.ui.setStatus(STATUS_KEY, undefined);
|
|
406
482
|
// Do not clear goalToolsUnlocked: after first activation, keep tools visible
|
|
407
483
|
// for the rest of this extension runtime to avoid repeated goal-tool schema
|