@narumitw/pi-goal 0.20.0 → 0.27.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/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
+ }