@narumitw/pi-goal 0.40.1 → 0.42.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 +66 -21
- package/package.json +2 -2
- package/src/commands.ts +16 -0
- package/src/goal.ts +5 -5
- package/src/run-protocol.ts +380 -0
- package/src/runtime.ts +46 -31
- package/src/settings-ui.ts +30 -1
- package/src/settings.ts +20 -0
- package/src/rpc.ts +0 -188
package/README.md
CHANGED
|
@@ -33,6 +33,7 @@ Goal mode uses Codex-like persistence instructions and sends guarded continuatio
|
|
|
33
33
|
- Rotates the completion guard id when a goal is resumed or edited so delayed old turns cannot complete the newer goal instance.
|
|
34
34
|
- Blocks stale tool calls after in-flight work pauses, blocks, or reaches a usage limit, until fresh non-goal user work, successful reactivation/replacement, or clear.
|
|
35
35
|
- Applies one evidence-based completion audit across kickoff, resume, edit, system, continuation, and budget-wrap-up prompts.
|
|
36
|
+
- Optionally exposes a default-off, run-scoped `pi.events` protocol for trusted sibling extensions to start, observe, and cancel one Goal lifecycle without emulating `/goal` input.
|
|
36
37
|
|
|
37
38
|
## 📦 Install
|
|
38
39
|
|
|
@@ -65,6 +66,9 @@ built-in defaults without creating the file:
|
|
|
65
66
|
"experimental": {
|
|
66
67
|
"goals": false
|
|
67
68
|
},
|
|
69
|
+
"rpc": {
|
|
70
|
+
"enabled": false
|
|
71
|
+
},
|
|
68
72
|
"continuationLimits": {
|
|
69
73
|
"automaticTurns": null,
|
|
70
74
|
"noProgressTurns": 3
|
|
@@ -73,13 +77,14 @@ built-in defaults without creating the file:
|
|
|
73
77
|
```
|
|
74
78
|
|
|
75
79
|
Use `/goal` → **Settings…** in the TUI to create or update the file interactively, or create
|
|
76
|
-
and edit it directly. The standard Settings screen keeps all
|
|
80
|
+
and edit it directly. The standard Settings screen keeps all five controls on one level in task
|
|
77
81
|
order; the two safety limits open standard choice screens:
|
|
78
82
|
|
|
79
83
|
- **Automatic work** shows **Unlimited** or an exact **≤_N_** response cap. Choose **Unlimited** directly, or choose **Set a maximum…** and enter a safe whole number greater than zero.
|
|
80
84
|
- **No-progress guard** shows **_N_ runs** or **Off**. Choose the default threshold, **Off**, or **Set threshold…** and enter a safe whole number greater than zero.
|
|
81
85
|
- **Goal tools** controls whether terminal Goal tools are always visible or appear after the first goal.
|
|
82
86
|
- **Ordered goal queue** controls the experimental ordered-goal workflows.
|
|
87
|
+
- **Managed run RPC** controls whether trusted installed extensions may start and cancel managed Goal runs. It defaults to **Off** and is a cooperation setting, not an extension security sandbox.
|
|
83
88
|
|
|
84
89
|
Custom number inputs reject zero, negative numbers, decimals, text, and unsafe integers without saving; use the explicit **Unlimited** or **Off** choice instead. Interactive changes are serialized, written atomically, preserve unknown fields, and apply to the current runtime. A successful change updates the visible state immediately. A failed save restores the prior value and reports the settings path so it can be retried. Tool-visibility changes that would alter the active tool schema are rejected while Pi is busy; retry after Pi settles. Escape returns to the previous screen without reverting changes that were already saved.
|
|
85
90
|
|
|
@@ -90,6 +95,8 @@ Custom number inputs reject zero, negative numbers, decimals, text, and unsafe i
|
|
|
90
95
|
|
|
91
96
|
`experimental.goals` accepts a boolean and defaults to `false`. Set it to `true` to enable the ordered-goal subcommands and automatic queue advancement described below. Enabled sessions show one warning because command behavior and persisted queue state remain experimental.
|
|
92
97
|
|
|
98
|
+
`rpc.enabled` accepts a boolean and defaults to `false`. When disabled, a valid managed-run start receives `RPC_DISABLED`; manual and restored Goals remain unchanged. A Settings-menu change applies immediately after its atomic save. Disabling rejects new starts but lets an already accepted run continue publishing its exact state and accept its exact cancellation until terminal, avoiding stranded work. Reload, replacement, and shutdown clear that in-memory ownership.
|
|
99
|
+
|
|
93
100
|
`continuationLimits` controls the runaway guards:
|
|
94
101
|
|
|
95
102
|
- `automaticTurns` accepts a positive safe integer or `null` and defaults to `null` (unlimited). When configured, it counts every completed normal `turn_end` owned by automatically started Goal work, including model responses inside tool loops and matching Pi-owned retries. The user-triggered kickoff, resume, edit, and ordinary user runs are not charged. At the limit, the goal becomes `paused` with cause `continuation_limit`, pending continuation/recovery is cancelled, and the current operation is aborted. Pi may invoke a provider adapter once more with an already-aborted signal to produce its synthetic terminal event; that event is not counted and cannot resume Goal work. Set this field to `null` to remove the authoritative hard bound.
|
|
@@ -205,37 +212,75 @@ Do not use `goal_blocked` merely because work is difficult, incomplete, uncertai
|
|
|
205
212
|
|
|
206
213
|
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, and automatic ownership remains charged through retry `agent_start` events. If matching recovery still exists at `agent_settled`, retries are exhausted and the goal becomes `blocked` before any pending queue transition dispatches. Stale recovery cannot block a replacement goal. User and extension work that starts before settlement supersedes the older continuation intent, and pending messages always take priority.
|
|
207
214
|
|
|
208
|
-
## 🤝
|
|
215
|
+
## 🤝 Managed run RPC
|
|
216
|
+
|
|
217
|
+
With `rpc.enabled: true`, pi-goal exposes a session-local, dependency-free protocol over Pi's shared `pi.events` bus. It is intended for trusted sibling extensions that need to start, observe, and cancel one Goal lifecycle without driving the `/goal` command. Installed Pi extensions remain fully privileged: this setting controls only whether pi-goal cooperates with these channels and is not authentication or sandboxing.
|
|
209
218
|
|
|
210
|
-
|
|
219
|
+
The public channels are:
|
|
211
220
|
|
|
212
|
-
|
|
221
|
+
```text
|
|
222
|
+
pi-goal:start
|
|
223
|
+
pi-goal:cancel
|
|
224
|
+
pi-goal:event:${runId}
|
|
225
|
+
```
|
|
213
226
|
|
|
214
|
-
|
|
227
|
+
The protocol intentionally has no separate version field or versioned channel namespace. Before starting, the caller must generate a session-unique `runId`, subscribe to its event channel, and then emit:
|
|
215
228
|
|
|
216
|
-
|
|
229
|
+
```ts
|
|
230
|
+
pi.events.emit("pi-goal:start", {
|
|
231
|
+
runId: "consumer-generated-run-id",
|
|
232
|
+
objective: "Ship and verify the feature",
|
|
233
|
+
tokenBudget: 100000, // optional positive integer
|
|
234
|
+
});
|
|
235
|
+
```
|
|
217
236
|
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
237
|
+
`runId` must match `^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`; UUIDs are recommended. It is a correlation identifier, not a secret or authenticated caller identity. The objective uses the same 4,000-character validation as `/goal`, and `tokenBudget` is an absolute positive integer rather than a `k`/`m` string.
|
|
238
|
+
|
|
239
|
+
A successful start produces canonical state on `pi-goal:event:${runId}`:
|
|
240
|
+
|
|
241
|
+
```json
|
|
242
|
+
{
|
|
243
|
+
"type": "state",
|
|
244
|
+
"runId": "consumer-generated-run-id",
|
|
245
|
+
"goalId": "<pi-goal-instance-id>",
|
|
246
|
+
"status": "active"
|
|
247
|
+
}
|
|
223
248
|
```
|
|
224
249
|
|
|
225
|
-
|
|
250
|
+
Subsequent state events use `active`, `complete`, `blocked`, `paused`, `usage_limited`, `budget_limited`, or `cleared`. `complete` is the only successful terminal outcome. A matching completion may include `summary`; other terminal outcomes may include `reason`. Events come only from canonical Goal persistence and only for the matching managed run. Manual and restored Goals are not adopted or broadcast, unchanged persistence does not duplicate a status, and each run emits at most one terminal event.
|
|
226
251
|
|
|
227
|
-
|
|
228
|
-
- If no session context is bound (before `session_start` or after `session_shutdown`), the reply is a failure rather than starting a goal.
|
|
229
|
-
- 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.
|
|
230
|
-
- 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`.
|
|
252
|
+
Terminal events are dispatched after the underlying Goal transition settles, so a listener can start the next managed run directly after `complete` without re-entering completion cleanup. Other terminal statuses leave a stopped Goal that must be resolved or cleared first. If a manual edit, replacement, skip, or priority transition rotates the Goal id, the prior managed run ends as `cleared` with a superseded reason; the replacement remains outside that run.
|
|
231
253
|
|
|
232
|
-
|
|
254
|
+
To cancel before or after activation, emit the same `runId`:
|
|
255
|
+
|
|
256
|
+
```ts
|
|
257
|
+
pi.events.emit("pi-goal:cancel", {
|
|
258
|
+
runId: "consumer-generated-run-id",
|
|
259
|
+
reason: "Parent work was cancelled", // optional, at most 1,000 characters
|
|
260
|
+
});
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
Cancellation uses the normal Goal pause transition. It cannot affect a manual, restored, stale, or different run. The resulting `paused` state is the cancellation result; there is no separate reply envelope. A caller must not reopen a terminal `runId`, and a later manual `/goal resume` is outside that completed managed run.
|
|
264
|
+
|
|
265
|
+
Rejected operations emit a structured error on the same run event channel:
|
|
266
|
+
|
|
267
|
+
```json
|
|
268
|
+
{
|
|
269
|
+
"type": "error",
|
|
270
|
+
"runId": "consumer-generated-run-id",
|
|
271
|
+
"operation": "start",
|
|
272
|
+
"error": {
|
|
273
|
+
"code": "RPC_DISABLED",
|
|
274
|
+
"message": "Managed run RPC is disabled."
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
```
|
|
233
278
|
|
|
234
|
-
|
|
279
|
+
Stable codes are `RPC_DISABLED`, `INVALID_REQUEST`, `NO_ACTIVE_SESSION`, `RUN_ID_IN_USE`, `RUN_NOT_FOUND`, `GOAL_ALREADY_EXISTS`, `ACTIVATION_FAILED`, and `SUPERSEDED`. Consumers branch on `code`; `message` is diagnostic. An unsafe or missing `runId` is ignored because there is no safe response channel.
|
|
235
280
|
|
|
236
|
-
|
|
281
|
+
Start never prompts for replacement: any pre-existing Goal is rejected. The protocol binds only after current settings and restored Goal state load, and unbinds before session shutdown. A caller must not assume that `emit()` waits for Goal completion; it should wait for a terminal run event and participate in its own session-shutdown cleanup.
|
|
237
282
|
|
|
238
|
-
|
|
283
|
+
This breaking contract replaces and removes `pi-goal:rpc:start`, `pi-goal:rpc:pause`, request-scoped start replies, and the global `pi-goal:state` broadcast. No compatibility aliases are registered.
|
|
239
284
|
|
|
240
285
|
## 🧠 Use cases
|
|
241
286
|
|
|
@@ -257,7 +302,7 @@ extensions/pi-goal/
|
|
|
257
302
|
│ ├── safety.ts # Output normalization and no-progress fingerprint state
|
|
258
303
|
│ ├── errors.ts # Pi-aligned provider error and retry classification
|
|
259
304
|
│ ├── markers.ts # Bounded Goal prompt marker parsing and formatting
|
|
260
|
-
│ ├──
|
|
305
|
+
│ ├── run-protocol.ts # Default-off managed-run protocol and session ownership
|
|
261
306
|
│ ├── queue.ts # Pure ordered-goal transitions
|
|
262
307
|
│ └── *.ts # Package-local parsing, settings, prompts, accounting, and persistence
|
|
263
308
|
├── README.md
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@narumitw/pi-goal",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.42.0",
|
|
4
4
|
"description": "Pi extension for autonomous /goal completion with opt-in experimental ordered queues.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
33
|
"@narumitw/pi-tui-kit": "^0.40.0",
|
|
34
|
-
"typebox": "^1.3.
|
|
34
|
+
"typebox": "^1.3.9"
|
|
35
35
|
},
|
|
36
36
|
"peerDependencies": {
|
|
37
37
|
"@earendil-works/pi-ai": "*",
|
package/src/commands.ts
CHANGED
|
@@ -45,6 +45,7 @@ export class GoalCommandController {
|
|
|
45
45
|
tokenBudget: number | undefined,
|
|
46
46
|
ctx: StatusContext,
|
|
47
47
|
onActivated?: (goal: ActiveGoal) => void,
|
|
48
|
+
isActivationCurrent?: (goal: ActiveGoal) => boolean,
|
|
48
49
|
) {
|
|
49
50
|
const validationError = validateObjective(objective);
|
|
50
51
|
if (validationError) {
|
|
@@ -108,12 +109,21 @@ export class GoalCommandController {
|
|
|
108
109
|
const startedGoal = this.runtime.activeGoal;
|
|
109
110
|
onActivated?.(startedGoal);
|
|
110
111
|
this.runtime.persistGoal(startedGoal);
|
|
112
|
+
if (
|
|
113
|
+
this.runtime.activeGoal?.id !== startedGoal.id ||
|
|
114
|
+
this.runtime.activeGoal.status !== "active"
|
|
115
|
+
) {
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
111
118
|
this.runtime.updateStatus(ctx, startedGoal);
|
|
112
119
|
const sent = await this.runtime.sendOwnedGoalPrompt(
|
|
113
120
|
ctx,
|
|
114
121
|
startedGoal.id,
|
|
115
122
|
buildGoalPrompt(startedGoal),
|
|
123
|
+
true,
|
|
124
|
+
() => isActivationCurrent?.(startedGoal) ?? true,
|
|
116
125
|
);
|
|
126
|
+
if (isActivationCurrent && !isActivationCurrent(startedGoal)) return;
|
|
117
127
|
if (!sent) {
|
|
118
128
|
let rolledBackStartedGoal = false;
|
|
119
129
|
if (this.runtime.activeGoal?.id === startedGoal.id) {
|
|
@@ -144,6 +154,12 @@ export class GoalCommandController {
|
|
|
144
154
|
}
|
|
145
155
|
return;
|
|
146
156
|
}
|
|
157
|
+
if (
|
|
158
|
+
this.runtime.activeGoal?.id !== startedGoal.id ||
|
|
159
|
+
this.runtime.activeGoal.status !== "active"
|
|
160
|
+
) {
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
147
163
|
ctx.ui.notify(
|
|
148
164
|
existingGoal ? `Goal replaced: ${objective}` : `Goal started: ${objective}`,
|
|
149
165
|
"info",
|
package/src/goal.ts
CHANGED
|
@@ -7,7 +7,7 @@ import { showGoalManager } from "./menu.js";
|
|
|
7
7
|
import { type ActiveGoal, loadGoalStateFromSession } from "./persistence.js";
|
|
8
8
|
import { buildGoalPrompt, buildGoalSystemPrompt } from "./prompts.js";
|
|
9
9
|
import { activateQueuedGoal } from "./queue.js";
|
|
10
|
-
import {
|
|
10
|
+
import { GoalRunController } from "./run-protocol.js";
|
|
11
11
|
import {
|
|
12
12
|
type AssistantMessageLike,
|
|
13
13
|
abortCurrentTurn,
|
|
@@ -66,8 +66,8 @@ const MAX_BLOCKER_EVIDENCE_LENGTH = 4_000;
|
|
|
66
66
|
function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
|
|
67
67
|
const runtime = new GoalRuntime(pi);
|
|
68
68
|
const commands = new GoalCommandController(runtime);
|
|
69
|
-
const
|
|
70
|
-
|
|
69
|
+
const runController = new GoalRunController(runtime, commands);
|
|
70
|
+
runController.register(pi);
|
|
71
71
|
|
|
72
72
|
// Bind per-factory runtime operations once so event orchestration stays concise
|
|
73
73
|
// without reintroducing module-global mutable state.
|
|
@@ -487,7 +487,6 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
|
|
|
487
487
|
runtime.queueFrozen = false;
|
|
488
488
|
runtime.queueFreezeAwaitingSettle = false;
|
|
489
489
|
runtime.clearTerminalDetails();
|
|
490
|
-
rpc.bindSession(ctx);
|
|
491
490
|
const previousToolVisibility = runtime.settings.toolVisibility;
|
|
492
491
|
const settingsResult = readGoalSettings(options.settingsPath);
|
|
493
492
|
runtime.settings =
|
|
@@ -527,6 +526,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
|
|
|
527
526
|
runtime.queuedGoals = loaded.queue;
|
|
528
527
|
runtime.pendingQueueAction = loaded.pendingAction;
|
|
529
528
|
runtime.queueFrozen = loaded.hasExperimentalQueueState && !runtime.settings.experimental.goals;
|
|
529
|
+
runController.bindSession(ctx);
|
|
530
530
|
if (runtime.queueFrozen) {
|
|
531
531
|
if (runtime.activeGoal) persistGoal(runtime.activeGoal);
|
|
532
532
|
ctx.ui.setStatus(STATUS_KEY, "queue off");
|
|
@@ -592,6 +592,7 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
|
|
|
592
592
|
});
|
|
593
593
|
|
|
594
594
|
pi.on("session_shutdown", (_event, ctx) => {
|
|
595
|
+
runController.unbindSession();
|
|
595
596
|
runtime.closeMenuSession();
|
|
596
597
|
if (runtime.activeGoal) {
|
|
597
598
|
if (!runtime.queueFrozen && runtime.activeGoal.status === "active") {
|
|
@@ -614,7 +615,6 @@ function registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {
|
|
|
614
615
|
ctx.ui.setStatus(STATUS_KEY, undefined);
|
|
615
616
|
clearCompletionStatusTimer();
|
|
616
617
|
runtime.clearTerminalDetails();
|
|
617
|
-
rpc.unbindSession();
|
|
618
618
|
});
|
|
619
619
|
|
|
620
620
|
pi.on("session_before_compact", (event, ctx) => {
|
|
@@ -0,0 +1,380 @@
|
|
|
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 {
|
|
5
|
+
formatError,
|
|
6
|
+
type GoalRuntime,
|
|
7
|
+
type GoalStateSnapshot,
|
|
8
|
+
isTerminalGoalStatus,
|
|
9
|
+
type StatusContext,
|
|
10
|
+
} from "./runtime.js";
|
|
11
|
+
|
|
12
|
+
export const GOAL_RUN_START_CHANNEL = "pi-goal:start";
|
|
13
|
+
export const GOAL_RUN_CANCEL_CHANNEL = "pi-goal:cancel";
|
|
14
|
+
|
|
15
|
+
const RUN_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
|
|
16
|
+
const MAX_CANCEL_REASON_LENGTH = 1_000;
|
|
17
|
+
|
|
18
|
+
export type GoalRunStatus = Exclude<GoalStateSnapshot["status"], "queued">;
|
|
19
|
+
export type GoalRunErrorCode =
|
|
20
|
+
| "RPC_DISABLED"
|
|
21
|
+
| "INVALID_REQUEST"
|
|
22
|
+
| "NO_ACTIVE_SESSION"
|
|
23
|
+
| "RUN_ID_IN_USE"
|
|
24
|
+
| "RUN_NOT_FOUND"
|
|
25
|
+
| "GOAL_ALREADY_EXISTS"
|
|
26
|
+
| "ACTIVATION_FAILED"
|
|
27
|
+
| "SUPERSEDED";
|
|
28
|
+
|
|
29
|
+
export type GoalRunEvent =
|
|
30
|
+
| {
|
|
31
|
+
type: "state";
|
|
32
|
+
runId: string;
|
|
33
|
+
goalId: string;
|
|
34
|
+
status: GoalRunStatus;
|
|
35
|
+
summary?: string;
|
|
36
|
+
reason?: string;
|
|
37
|
+
}
|
|
38
|
+
| {
|
|
39
|
+
type: "error";
|
|
40
|
+
runId: string;
|
|
41
|
+
operation: "start" | "cancel";
|
|
42
|
+
error: { code: GoalRunErrorCode; message: string };
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
interface GoalRunStartPayload {
|
|
46
|
+
runId: string;
|
|
47
|
+
objective: string;
|
|
48
|
+
tokenBudget?: number;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
interface BoundSession {
|
|
52
|
+
generation: number;
|
|
53
|
+
ctx: StatusContext;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
interface ManagedRun {
|
|
57
|
+
runId: string;
|
|
58
|
+
generation: number;
|
|
59
|
+
goalId?: string;
|
|
60
|
+
lastStatus?: GoalRunStatus;
|
|
61
|
+
closed: boolean;
|
|
62
|
+
cancelRequested: boolean;
|
|
63
|
+
cancelReason?: string;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function goalRunEventChannel(runId: string) {
|
|
67
|
+
return `pi-goal:event:${runId}`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function isPayloadRecord(data: unknown): data is object {
|
|
71
|
+
if (!data || typeof data !== "object") return false;
|
|
72
|
+
try {
|
|
73
|
+
return !Array.isArray(data);
|
|
74
|
+
} catch {
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function readPayloadProperty(
|
|
80
|
+
data: object,
|
|
81
|
+
key: "runId" | "objective" | "tokenBudget" | "reason",
|
|
82
|
+
): { ok: true; value: unknown } | { ok: false } {
|
|
83
|
+
try {
|
|
84
|
+
return { ok: true, value: Reflect.get(data, key) };
|
|
85
|
+
} catch {
|
|
86
|
+
return { ok: false };
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function parseRunId(data: unknown): string | undefined {
|
|
91
|
+
if (!isPayloadRecord(data)) return undefined;
|
|
92
|
+
const runId = readPayloadProperty(data, "runId");
|
|
93
|
+
return runId.ok && typeof runId.value === "string" && RUN_ID_PATTERN.test(runId.value)
|
|
94
|
+
? runId.value
|
|
95
|
+
: undefined;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function currentActiveGoal(runtime: GoalRuntime) {
|
|
99
|
+
return runtime.activeGoal;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function parseStartPayload(data: unknown): string | Omit<GoalRunStartPayload, "runId"> {
|
|
103
|
+
if (!isPayloadRecord(data)) return "start payload must be an object";
|
|
104
|
+
const objectiveValue = readPayloadProperty(data, "objective");
|
|
105
|
+
if (!objectiveValue.ok || typeof objectiveValue.value !== "string") {
|
|
106
|
+
return "objective must be a string";
|
|
107
|
+
}
|
|
108
|
+
const objective = objectiveValue.value.trim();
|
|
109
|
+
const objectiveError = validateObjective(objective);
|
|
110
|
+
if (objectiveError) return objectiveError;
|
|
111
|
+
const tokenBudgetValue = readPayloadProperty(data, "tokenBudget");
|
|
112
|
+
if (
|
|
113
|
+
!tokenBudgetValue.ok ||
|
|
114
|
+
(tokenBudgetValue.value !== undefined &&
|
|
115
|
+
(typeof tokenBudgetValue.value !== "number" ||
|
|
116
|
+
!Number.isFinite(tokenBudgetValue.value) ||
|
|
117
|
+
!Number.isSafeInteger(tokenBudgetValue.value) ||
|
|
118
|
+
tokenBudgetValue.value <= 0))
|
|
119
|
+
) {
|
|
120
|
+
return "tokenBudget must be a positive integer";
|
|
121
|
+
}
|
|
122
|
+
return { objective, tokenBudget: tokenBudgetValue.value as number | undefined };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function parseCancelReason(data: unknown): string | undefined | { error: string } {
|
|
126
|
+
if (!isPayloadRecord(data)) return { error: "cancel payload must be an object" };
|
|
127
|
+
const reasonValue = readPayloadProperty(data, "reason");
|
|
128
|
+
if (
|
|
129
|
+
!reasonValue.ok ||
|
|
130
|
+
(reasonValue.value !== undefined && typeof reasonValue.value !== "string")
|
|
131
|
+
) {
|
|
132
|
+
return { error: "reason must be a string" };
|
|
133
|
+
}
|
|
134
|
+
if (reasonValue.value === undefined) return undefined;
|
|
135
|
+
const reason = reasonValue.value.trim();
|
|
136
|
+
if (reason.length > MAX_CANCEL_REASON_LENGTH) {
|
|
137
|
+
return { error: `reason must be at most ${MAX_CANCEL_REASON_LENGTH} characters` };
|
|
138
|
+
}
|
|
139
|
+
return reason || undefined;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export class GoalRunController {
|
|
143
|
+
private readonly runtime: GoalRuntime;
|
|
144
|
+
private readonly commands: GoalCommandController;
|
|
145
|
+
private generation = 0;
|
|
146
|
+
private session?: BoundSession;
|
|
147
|
+
private run?: ManagedRun;
|
|
148
|
+
private readonly usedRunIds = new Set<string>();
|
|
149
|
+
|
|
150
|
+
constructor(runtime: GoalRuntime, commands: GoalCommandController) {
|
|
151
|
+
this.runtime = runtime;
|
|
152
|
+
this.commands = commands;
|
|
153
|
+
this.runtime.setGoalStateSink((snapshot) => this.handleGoalState(snapshot));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
register(pi: ExtensionAPI) {
|
|
157
|
+
pi.events.on(GOAL_RUN_START_CHANNEL, (data) => this.handleStart(data));
|
|
158
|
+
pi.events.on(GOAL_RUN_CANCEL_CHANNEL, (data) => {
|
|
159
|
+
this.handleCancel(data);
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
bindSession(ctx: StatusContext) {
|
|
164
|
+
this.generation += 1;
|
|
165
|
+
this.session = { generation: this.generation, ctx };
|
|
166
|
+
this.closeCurrentRun();
|
|
167
|
+
this.usedRunIds.clear();
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
unbindSession() {
|
|
171
|
+
this.generation += 1;
|
|
172
|
+
this.session = undefined;
|
|
173
|
+
this.closeCurrentRun();
|
|
174
|
+
this.usedRunIds.clear();
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
private async handleStart(data: unknown) {
|
|
178
|
+
const runId = parseRunId(data);
|
|
179
|
+
if (!runId) return;
|
|
180
|
+
const session = this.session;
|
|
181
|
+
if (!session) {
|
|
182
|
+
this.emitError(runId, "start", "NO_ACTIVE_SESSION", "No active pi-goal session.");
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
if (!this.runtime.settings.rpc.enabled) {
|
|
186
|
+
this.emitError(runId, "start", "RPC_DISABLED", "Managed run RPC is disabled.");
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
if (this.usedRunIds.has(runId)) {
|
|
190
|
+
this.emitError(runId, "start", "RUN_ID_IN_USE", "runId was already used in this session.");
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
const parsed = parseStartPayload(data);
|
|
194
|
+
if (typeof parsed === "string") {
|
|
195
|
+
this.emitError(runId, "start", "INVALID_REQUEST", parsed);
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
if (this.session !== session || this.generation !== session.generation) {
|
|
199
|
+
this.emitError(
|
|
200
|
+
runId,
|
|
201
|
+
"start",
|
|
202
|
+
"SUPERSEDED",
|
|
203
|
+
"The pi-goal session changed while validating the request.",
|
|
204
|
+
);
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
if (this.usedRunIds.has(runId)) {
|
|
208
|
+
this.emitError(runId, "start", "RUN_ID_IN_USE", "runId was already used in this session.");
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
if (this.runtime.activeGoal || (this.run && !this.run.closed)) {
|
|
212
|
+
this.emitError(runId, "start", "GOAL_ALREADY_EXISTS", "A Goal already exists.");
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const run: ManagedRun = {
|
|
217
|
+
runId,
|
|
218
|
+
generation: session.generation,
|
|
219
|
+
closed: false,
|
|
220
|
+
cancelRequested: false,
|
|
221
|
+
};
|
|
222
|
+
this.run = run;
|
|
223
|
+
this.usedRunIds.add(runId);
|
|
224
|
+
|
|
225
|
+
try {
|
|
226
|
+
await this.commands.startGoal(
|
|
227
|
+
parsed.objective,
|
|
228
|
+
parsed.tokenBudget,
|
|
229
|
+
session.ctx,
|
|
230
|
+
(goal) => {
|
|
231
|
+
if (this.ownsRun(run, session.generation)) run.goalId = goal.id;
|
|
232
|
+
},
|
|
233
|
+
() => this.ownsRun(run, session.generation),
|
|
234
|
+
);
|
|
235
|
+
} catch (error) {
|
|
236
|
+
if (this.ownsRun(run, session.generation)) {
|
|
237
|
+
this.closeCurrentRun();
|
|
238
|
+
this.emitError(
|
|
239
|
+
runId,
|
|
240
|
+
"start",
|
|
241
|
+
"ACTIVATION_FAILED",
|
|
242
|
+
`Goal activation failed: ${formatError(error)}`,
|
|
243
|
+
);
|
|
244
|
+
}
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
if (!this.ownsRun(run, session.generation)) return;
|
|
249
|
+
if (!run.goalId) {
|
|
250
|
+
this.closeCurrentRun();
|
|
251
|
+
this.emitError(runId, "start", "ACTIVATION_FAILED", "Goal activation did not create a Goal.");
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
if (currentActiveGoal(this.runtime)?.id !== run.goalId) {
|
|
255
|
+
this.closeCurrentRun();
|
|
256
|
+
this.emitError(runId, "start", "SUPERSEDED", "The managed Goal was superseded.");
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
if (run.cancelRequested) this.cancelActiveRun(run, session, run.cancelReason);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
private handleCancel(data: unknown) {
|
|
263
|
+
const runId = parseRunId(data);
|
|
264
|
+
if (!runId) return;
|
|
265
|
+
const session = this.session;
|
|
266
|
+
if (!session) {
|
|
267
|
+
this.emitError(runId, "cancel", "NO_ACTIVE_SESSION", "No active pi-goal session.");
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
const reason = parseCancelReason(data);
|
|
271
|
+
if (reason && typeof reason === "object") {
|
|
272
|
+
this.emitError(runId, "cancel", "INVALID_REQUEST", reason.error);
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
const run = this.run;
|
|
276
|
+
if (!run || run.closed || run.runId !== runId || run.generation !== session.generation) {
|
|
277
|
+
this.emitError(runId, "cancel", "RUN_NOT_FOUND", "No active managed run matches runId.");
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
if (!run.goalId) {
|
|
281
|
+
run.cancelRequested = true;
|
|
282
|
+
run.cancelReason = reason;
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
this.cancelActiveRun(run, session, reason);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
private cancelActiveRun(run: ManagedRun, session: BoundSession, reason: string | undefined) {
|
|
289
|
+
if (!this.ownsRun(run, session.generation)) return;
|
|
290
|
+
const goal = this.runtime.activeGoal;
|
|
291
|
+
if (!goal || goal.id !== run.goalId) {
|
|
292
|
+
this.closeCurrentRun();
|
|
293
|
+
this.emitError(run.runId, "cancel", "SUPERSEDED", "The managed Goal was superseded.");
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
if (goal.status !== "active") {
|
|
297
|
+
this.closeCurrentRun();
|
|
298
|
+
this.emitError(run.runId, "cancel", "RUN_NOT_FOUND", "The managed run is no longer active.");
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
this.runtime.setTerminalReason(goal.id, reason ?? "goal cancelled by managed run");
|
|
302
|
+
this.commands.pauseGoal(session.ctx);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
private handleGoalState(snapshot: GoalStateSnapshot) {
|
|
306
|
+
const run = this.run;
|
|
307
|
+
if (!run || run.closed || !run.goalId) return;
|
|
308
|
+
if (run.goalId !== snapshot.goalId) {
|
|
309
|
+
if (currentActiveGoal(this.runtime)?.id !== snapshot.goalId) return;
|
|
310
|
+
this.publishStateEvent(run, {
|
|
311
|
+
goalId: run.goalId,
|
|
312
|
+
status: "cleared",
|
|
313
|
+
reason: "managed Goal superseded by another Goal",
|
|
314
|
+
});
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
if (snapshot.status === "queued" || run.lastStatus === snapshot.status) return;
|
|
318
|
+
this.publishStateEvent(run, snapshot);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
private publishStateEvent(
|
|
322
|
+
run: ManagedRun,
|
|
323
|
+
snapshot: Pick<GoalStateSnapshot, "goalId" | "status" | "summary" | "reason">,
|
|
324
|
+
) {
|
|
325
|
+
const status = snapshot.status;
|
|
326
|
+
if (status === "queued") return;
|
|
327
|
+
run.lastStatus = status;
|
|
328
|
+
const event: GoalRunEvent = {
|
|
329
|
+
type: "state",
|
|
330
|
+
runId: run.runId,
|
|
331
|
+
goalId: snapshot.goalId,
|
|
332
|
+
status,
|
|
333
|
+
...(snapshot.summary ? { summary: snapshot.summary } : {}),
|
|
334
|
+
...(snapshot.reason ? { reason: snapshot.reason } : {}),
|
|
335
|
+
};
|
|
336
|
+
if (!isTerminalGoalStatus(status)) {
|
|
337
|
+
this.runtime.pi.events.emit(goalRunEventChannel(run.runId), event);
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
run.closed = true;
|
|
342
|
+
this.run = undefined;
|
|
343
|
+
const generation = run.generation;
|
|
344
|
+
// Active stays synchronous so a listener can cancel before kickoff. Terminal
|
|
345
|
+
// publication waits until the transition finishes, preventing listener work
|
|
346
|
+
// from being overwritten by the old transition's remaining UI or cleanup.
|
|
347
|
+
queueMicrotask(() => {
|
|
348
|
+
if (this.generation !== generation) return;
|
|
349
|
+
this.runtime.pi.events.emit(goalRunEventChannel(run.runId), event);
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
private emitError(
|
|
354
|
+
runId: string,
|
|
355
|
+
operation: "start" | "cancel",
|
|
356
|
+
code: GoalRunErrorCode,
|
|
357
|
+
message: string,
|
|
358
|
+
) {
|
|
359
|
+
this.runtime.pi.events.emit(goalRunEventChannel(runId), {
|
|
360
|
+
type: "error",
|
|
361
|
+
runId,
|
|
362
|
+
operation,
|
|
363
|
+
error: { code, message },
|
|
364
|
+
} satisfies GoalRunEvent);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
private ownsRun(run: ManagedRun, generation: number) {
|
|
368
|
+
return (
|
|
369
|
+
this.session?.generation === generation &&
|
|
370
|
+
this.generation === generation &&
|
|
371
|
+
this.run === run &&
|
|
372
|
+
!run.closed
|
|
373
|
+
);
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
private closeCurrentRun() {
|
|
377
|
+
if (this.run) this.run.closed = true;
|
|
378
|
+
this.run = undefined;
|
|
379
|
+
}
|
|
380
|
+
}
|
package/src/runtime.ts
CHANGED
|
@@ -85,40 +85,32 @@ export const GOAL_COMPLETE_TOOL = "goal_complete";
|
|
|
85
85
|
export const GOAL_BLOCKED_TOOL = "goal_blocked";
|
|
86
86
|
export const GOAL_TOOL_NAMES = [GOAL_COMPLETE_TOOL, GOAL_BLOCKED_TOOL] as const;
|
|
87
87
|
|
|
88
|
-
/**
|
|
89
|
-
export
|
|
88
|
+
/** Canonical Goal state passed to the in-process managed-run publisher. */
|
|
89
|
+
export type GoalStateSnapshotStatus = GoalStatus | "cleared";
|
|
90
90
|
|
|
91
|
-
|
|
92
|
-
export type GoalStateEventStatus = GoalStatus | "cleared";
|
|
93
|
-
|
|
94
|
-
/** Payload emitted on {@link GOAL_STATE_EVENT_CHANNEL} whenever goal state persists. */
|
|
95
|
-
export interface GoalStateEventPayload {
|
|
91
|
+
export interface GoalStateSnapshot {
|
|
96
92
|
goalId: string;
|
|
97
|
-
status:
|
|
93
|
+
status: GoalStateSnapshotStatus;
|
|
98
94
|
summary?: string;
|
|
99
95
|
reason?: string;
|
|
100
96
|
}
|
|
101
97
|
|
|
102
|
-
/** Terminal statuses
|
|
103
|
-
export function isTerminalGoalStatus(status:
|
|
98
|
+
/** Terminal statuses for Goal persistence and managed-run lifecycle publication. */
|
|
99
|
+
export function isTerminalGoalStatus(status: GoalStateSnapshotStatus): boolean {
|
|
104
100
|
return status !== "active" && status !== "queued";
|
|
105
101
|
}
|
|
106
102
|
|
|
107
|
-
|
|
108
|
-
* Build the cross-extension state payload from the canonical goal plus the most
|
|
109
|
-
* recent completion summary or blocked/failure reason, without re-deriving state.
|
|
110
|
-
*/
|
|
111
|
-
export function buildGoalStateEvent(
|
|
103
|
+
function buildGoalStateSnapshot(
|
|
112
104
|
goal: ActiveGoal,
|
|
113
105
|
summary: string | undefined,
|
|
114
106
|
reason: string | undefined,
|
|
115
|
-
):
|
|
116
|
-
const
|
|
117
|
-
if (goal.status === "complete" && summary)
|
|
107
|
+
): GoalStateSnapshot {
|
|
108
|
+
const snapshot: GoalStateSnapshot = { goalId: goal.id, status: goal.status };
|
|
109
|
+
if (goal.status === "complete" && summary) snapshot.summary = summary;
|
|
118
110
|
else if (goal.status !== "complete" && isTerminalGoalStatus(goal.status) && reason) {
|
|
119
|
-
|
|
111
|
+
snapshot.reason = reason;
|
|
120
112
|
}
|
|
121
|
-
return
|
|
113
|
+
return snapshot;
|
|
122
114
|
}
|
|
123
115
|
|
|
124
116
|
interface GoalTerminalDetails {
|
|
@@ -176,8 +168,9 @@ export class GoalRuntime {
|
|
|
176
168
|
settings: GoalSettings = DEFAULT_GOAL_SETTINGS;
|
|
177
169
|
settingsLoadIssue?: GoalSettingsLoadIssue;
|
|
178
170
|
activeGoal?: ActiveGoal;
|
|
179
|
-
/** Terminal details captured for the matching
|
|
171
|
+
/** Terminal details captured for the matching persisted-state snapshot. */
|
|
180
172
|
private terminalDetails?: GoalTerminalDetails;
|
|
173
|
+
private goalStateSink?: (snapshot: GoalStateSnapshot) => void;
|
|
181
174
|
queuedGoals: ActiveGoal[] = [];
|
|
182
175
|
pendingQueueAction?: PendingQueueAction;
|
|
183
176
|
queueFrozen = false;
|
|
@@ -211,6 +204,18 @@ export class GoalRuntime {
|
|
|
211
204
|
this.pi = pi;
|
|
212
205
|
}
|
|
213
206
|
|
|
207
|
+
setGoalStateSink(sink: ((snapshot: GoalStateSnapshot) => void) | undefined) {
|
|
208
|
+
this.goalStateSink = sink;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
private publishGoalState(snapshot: GoalStateSnapshot) {
|
|
212
|
+
try {
|
|
213
|
+
this.goalStateSink?.(snapshot);
|
|
214
|
+
} catch {
|
|
215
|
+
// Protocol publication must not interrupt canonical Goal persistence.
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
214
219
|
replaceMenuSession() {
|
|
215
220
|
this.menuGeneration += 1;
|
|
216
221
|
this.menuController.abort(new DOMException("Goal session replaced", "AbortError"));
|
|
@@ -611,11 +616,15 @@ export class GoalRuntime {
|
|
|
611
616
|
goalId: string,
|
|
612
617
|
prompt: string,
|
|
613
618
|
resetSafetyEpoch = true,
|
|
619
|
+
isCurrent?: () => boolean,
|
|
614
620
|
) {
|
|
615
621
|
const pending = this.rememberPendingGoalPrompt(goalId, prompt, resetSafetyEpoch);
|
|
616
|
-
const sent = await sendPrompt(this.pi, ctx, pending.prompt);
|
|
617
|
-
if (!sent
|
|
618
|
-
|
|
622
|
+
const sent = await sendPrompt(this.pi, ctx, pending.prompt, isCurrent);
|
|
623
|
+
if (!sent || (isCurrent && !isCurrent())) {
|
|
624
|
+
this.pendingGoalPromptMarkers.delete(pending.marker);
|
|
625
|
+
return false;
|
|
626
|
+
}
|
|
627
|
+
return true;
|
|
619
628
|
}
|
|
620
629
|
|
|
621
630
|
cancelContinuationWork() {
|
|
@@ -746,20 +755,19 @@ export class GoalRuntime {
|
|
|
746
755
|
GOAL_STATE_ENTRY_TYPE,
|
|
747
756
|
serializeGoalState(goal, this.queuedGoals, this.pendingQueueAction),
|
|
748
757
|
);
|
|
749
|
-
this.
|
|
750
|
-
|
|
751
|
-
buildGoalStateEvent(goal, this.terminalDetails?.summary, this.terminalDetails?.reason),
|
|
758
|
+
this.publishGoalState(
|
|
759
|
+
buildGoalStateSnapshot(goal, this.terminalDetails?.summary, this.terminalDetails?.reason),
|
|
752
760
|
);
|
|
753
761
|
}
|
|
754
762
|
|
|
755
763
|
clearPersistedGoal(cwd: string, clearedGoal?: ActiveGoal, reason = "goal cleared") {
|
|
756
764
|
this.pi.appendEntry(GOAL_STATE_ENTRY_TYPE, serializeGoalState(undefined, [], undefined));
|
|
757
765
|
if (clearedGoal) {
|
|
758
|
-
this.
|
|
766
|
+
this.publishGoalState({
|
|
759
767
|
goalId: clearedGoal.id,
|
|
760
768
|
status: "cleared",
|
|
761
769
|
reason,
|
|
762
|
-
}
|
|
770
|
+
});
|
|
763
771
|
}
|
|
764
772
|
this.clearTerminalDetails();
|
|
765
773
|
clearLegacyPersistedGoal(cwd);
|
|
@@ -1166,12 +1174,19 @@ function inputFingerprint(prompt: string) {
|
|
|
1166
1174
|
return createHash("sha256").update(prompt, "utf8").digest("hex");
|
|
1167
1175
|
}
|
|
1168
1176
|
|
|
1169
|
-
async function sendPrompt(
|
|
1177
|
+
async function sendPrompt(
|
|
1178
|
+
pi: ExtensionAPI,
|
|
1179
|
+
ctx: StatusContext,
|
|
1180
|
+
prompt: string,
|
|
1181
|
+
isCurrent?: () => boolean,
|
|
1182
|
+
) {
|
|
1170
1183
|
try {
|
|
1171
1184
|
await pi.sendUserMessage(prompt, { deliverAs: "followUp" });
|
|
1172
1185
|
return true;
|
|
1173
1186
|
} catch (error) {
|
|
1174
|
-
|
|
1187
|
+
if (!isCurrent || isCurrent()) {
|
|
1188
|
+
ctx.ui.notify(`Goal prompt failed: ${formatError(error)}`, "error");
|
|
1189
|
+
}
|
|
1175
1190
|
return false;
|
|
1176
1191
|
}
|
|
1177
1192
|
}
|
package/src/settings-ui.ts
CHANGED
|
@@ -42,7 +42,8 @@ export async function showGoalSettings(
|
|
|
42
42
|
| "choose-automatic"
|
|
43
43
|
| "choose-no-progress"
|
|
44
44
|
| "set-visibility"
|
|
45
|
-
| "set-queue"
|
|
45
|
+
| "set-queue"
|
|
46
|
+
| "set-rpc";
|
|
46
47
|
const menu = defineMenu<undefined, Screen, Action, ExtensionCommandContext>({
|
|
47
48
|
start: invalid ? "invalid" : "settings",
|
|
48
49
|
screens: {
|
|
@@ -85,6 +86,15 @@ export async function showGoalSettings(
|
|
|
85
86
|
values: ["Off", "Experimental"],
|
|
86
87
|
action: "set-queue",
|
|
87
88
|
},
|
|
89
|
+
{
|
|
90
|
+
id: "rpcEnabled",
|
|
91
|
+
label: "Managed run RPC",
|
|
92
|
+
description:
|
|
93
|
+
"Allow trusted installed extensions to start and cancel Goal runs; this is not an extension sandbox.",
|
|
94
|
+
currentValue: runtime.settings.rpc.enabled ? "On" : "Off",
|
|
95
|
+
values: ["Off", "On"],
|
|
96
|
+
action: "set-rpc",
|
|
97
|
+
},
|
|
88
98
|
],
|
|
89
99
|
}),
|
|
90
100
|
automatic: () => limitChoiceScreen(runtime, "automaticTurns", "choose-automatic"),
|
|
@@ -98,6 +108,7 @@ export async function showGoalSettings(
|
|
|
98
108
|
`No-progress guard: ${formatNoProgressProtection(runtime.settings.continuationLimits.noProgressTurns)}`,
|
|
99
109
|
`Goal tools: ${visibilityLabel(runtime.settings.toolVisibility)}`,
|
|
100
110
|
`Ordered goal queue: ${runtime.settings.experimental.goals ? "Experimental" : "Off"}`,
|
|
111
|
+
`Managed run RPC: ${runtime.settings.rpc.enabled ? "On" : "Off"}`,
|
|
101
112
|
],
|
|
102
113
|
hint: "back",
|
|
103
114
|
}),
|
|
@@ -176,6 +187,24 @@ export async function showGoalSettings(
|
|
|
176
187
|
return { kind: "rejected" };
|
|
177
188
|
}
|
|
178
189
|
},
|
|
190
|
+
"set-rpc": async ({ value }) => {
|
|
191
|
+
const enabled = value === "On";
|
|
192
|
+
if (enabled === runtime.settings.rpc.enabled) return { kind: "stay" };
|
|
193
|
+
try {
|
|
194
|
+
const next = {
|
|
195
|
+
...structuredClone(runtime.settings),
|
|
196
|
+
rpc: { enabled },
|
|
197
|
+
} satisfies GoalSettings;
|
|
198
|
+
applyGoalSettings(runtime, next, ctx, {
|
|
199
|
+
save: (settings) => (options.save ?? saveGoalSettings)(settings, settingsPath),
|
|
200
|
+
});
|
|
201
|
+
ctx.ui.notify(`Managed run RPC: ${enabled ? "On" : "Off"}.`, "info");
|
|
202
|
+
return { kind: "stay" };
|
|
203
|
+
} catch (error) {
|
|
204
|
+
notifySettingsFailure(ctx, settingsPath, error);
|
|
205
|
+
return { kind: "rejected" };
|
|
206
|
+
}
|
|
207
|
+
},
|
|
179
208
|
},
|
|
180
209
|
});
|
|
181
210
|
await runMenu(ctx, menu, {
|
package/src/settings.ts
CHANGED
|
@@ -14,6 +14,9 @@ export interface GoalSettings {
|
|
|
14
14
|
experimental: {
|
|
15
15
|
goals: boolean;
|
|
16
16
|
};
|
|
17
|
+
rpc: {
|
|
18
|
+
enabled: boolean;
|
|
19
|
+
};
|
|
17
20
|
continuationLimits: {
|
|
18
21
|
automaticTurns: ContinuationLimit;
|
|
19
22
|
noProgressTurns: ContinuationLimit;
|
|
@@ -23,6 +26,7 @@ export interface GoalSettings {
|
|
|
23
26
|
export const DEFAULT_GOAL_SETTINGS: GoalSettings = {
|
|
24
27
|
toolVisibility: "always",
|
|
25
28
|
experimental: { goals: false },
|
|
29
|
+
rpc: { enabled: false },
|
|
26
30
|
continuationLimits: { automaticTurns: null, noProgressTurns: 3 },
|
|
27
31
|
};
|
|
28
32
|
|
|
@@ -64,6 +68,19 @@ export function normalizeGoalSettings(value: unknown): GoalSettings | undefined
|
|
|
64
68
|
: DEFAULT_GOAL_SETTINGS.experimental.goals;
|
|
65
69
|
if (typeof goals !== "boolean") return undefined;
|
|
66
70
|
|
|
71
|
+
const rpcValue = Object.hasOwn(value, "rpc") ? Reflect.get(value, "rpc") : undefined;
|
|
72
|
+
if (
|
|
73
|
+
rpcValue !== undefined &&
|
|
74
|
+
(typeof rpcValue !== "object" || rpcValue === null || Array.isArray(rpcValue))
|
|
75
|
+
) {
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
const rpcEnabled =
|
|
79
|
+
rpcValue && Object.hasOwn(rpcValue, "enabled")
|
|
80
|
+
? Reflect.get(rpcValue, "enabled")
|
|
81
|
+
: DEFAULT_GOAL_SETTINGS.rpc.enabled;
|
|
82
|
+
if (typeof rpcEnabled !== "boolean") return undefined;
|
|
83
|
+
|
|
67
84
|
const continuationLimitsValue = Object.hasOwn(value, "continuationLimits")
|
|
68
85
|
? Reflect.get(value, "continuationLimits")
|
|
69
86
|
: undefined;
|
|
@@ -92,6 +109,7 @@ export function normalizeGoalSettings(value: unknown): GoalSettings | undefined
|
|
|
92
109
|
return {
|
|
93
110
|
toolVisibility: toolVisibility as GoalToolVisibility,
|
|
94
111
|
experimental: { goals },
|
|
112
|
+
rpc: { enabled: rpcEnabled },
|
|
95
113
|
continuationLimits: { automaticTurns, noProgressTurns },
|
|
96
114
|
};
|
|
97
115
|
}
|
|
@@ -128,12 +146,14 @@ export function saveGoalSettings(
|
|
|
128
146
|
}
|
|
129
147
|
|
|
130
148
|
const experimental = ownRecord(raw.experimental) ?? {};
|
|
149
|
+
const rpc = ownRecord(raw.rpc) ?? {};
|
|
131
150
|
const continuationLimits = ownRecord(raw.continuationLimits) ?? {};
|
|
132
151
|
const document = `${JSON.stringify(
|
|
133
152
|
{
|
|
134
153
|
...raw,
|
|
135
154
|
toolVisibility: normalized.toolVisibility,
|
|
136
155
|
experimental: { ...experimental, goals: normalized.experimental.goals },
|
|
156
|
+
rpc: { ...rpc, enabled: normalized.rpc.enabled },
|
|
137
157
|
continuationLimits: {
|
|
138
158
|
...continuationLimits,
|
|
139
159
|
automaticTurns: normalized.continuationLimits.automaticTurns,
|
package/src/rpc.ts
DELETED
|
@@ -1,188 +0,0 @@
|
|
|
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
|
-
}
|