@wkqco33/pi-remote-control 0.1.2 → 0.2.1
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 +3 -2
- package/package.json +4 -4
- package/src/client/command-handler.ts +61 -0
- package/src/client/prompt-router.ts +91 -0
- package/src/client/remote-bridge.test.ts +162 -5
- package/src/client/remote-bridge.ts +191 -75
- package/src/client/ws-client.ts +1 -0
- package/src/config-loader.test.ts +41 -0
- package/src/config-loader.ts +71 -0
- package/src/config.test.ts +6 -0
- package/src/config.ts +34 -1
- package/src/core/commands.test.ts +42 -0
- package/src/core/commands.ts +80 -0
- package/src/core/history.test.ts +35 -0
- package/src/core/history.ts +81 -30
- package/src/core/protocol.ts +27 -7
- package/src/core/status.test.ts +1 -0
- package/src/core/status.ts +2 -0
- package/src/core/tool-policy.ts +10 -1
- package/src/index.ts +55 -47
- package/src/project-config.test.ts +51 -0
|
@@ -4,20 +4,26 @@
|
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
import type { RemoteControlConfig } from "../config.js";
|
|
7
|
+
import type { CommandInfo } from "../core/commands.js";
|
|
7
8
|
import { createChallenge, formatChallengeCode, verifyChallenge, type PendingChallenge } from "../core/pairing.js";
|
|
8
9
|
import type { DeliverMode, HistoryItem, PromptImage, ServerInboundMessage, WireEnvelope } from "../core/protocol.js";
|
|
9
10
|
import { redactSecrets } from "../core/redact.js";
|
|
11
|
+
import type { ApprovalReason } from "../core/tool-policy.js";
|
|
10
12
|
import type { ConnectionStatus, StatusSnapshot } from "../core/status.js";
|
|
13
|
+
import type { BuiltinHost } from "./command-handler.js";
|
|
14
|
+
import { PromptRouter } from "./prompt-router.js";
|
|
11
15
|
|
|
12
|
-
export interface RemoteHost {
|
|
16
|
+
export interface RemoteHost extends BuiltinHost {
|
|
13
17
|
readonly sessionId: string;
|
|
14
18
|
readonly sessionName?: string;
|
|
15
19
|
readonly host: string;
|
|
16
20
|
readonly cwd: string;
|
|
17
21
|
readonly branch?: string;
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
22
|
+
listCommands(): CommandInfo[];
|
|
23
|
+
sendPrompt(
|
|
24
|
+
text: string,
|
|
25
|
+
options?: { deliverAs?: DeliverMode; images?: readonly PromptImage[]; expandPromptTemplates?: boolean },
|
|
26
|
+
): void;
|
|
21
27
|
abort(): void;
|
|
22
28
|
notify(text: string, level?: "info" | "warning" | "error"): void;
|
|
23
29
|
onStateChanged?(status: ConnectionStatus, trustedClients: number): void;
|
|
@@ -32,8 +38,25 @@ export interface TransportSink {
|
|
|
32
38
|
send(envelope: WireEnvelope): boolean;
|
|
33
39
|
}
|
|
34
40
|
|
|
41
|
+
export interface ApprovalOutcome {
|
|
42
|
+
readonly approved: boolean;
|
|
43
|
+
readonly reason: ApprovalReason;
|
|
44
|
+
}
|
|
45
|
+
|
|
35
46
|
interface PendingApproval {
|
|
36
|
-
readonly
|
|
47
|
+
readonly toolCallId: string;
|
|
48
|
+
readonly toolName: string;
|
|
49
|
+
readonly expiresAt: number;
|
|
50
|
+
readonly resolve: (outcome: ApprovalOutcome) => void;
|
|
51
|
+
readonly timer: ReturnType<typeof setTimeout>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Tokens arriving within this window share one frame, which keeps replays short. */
|
|
55
|
+
export const DELTA_FLUSH_MS = 50;
|
|
56
|
+
|
|
57
|
+
interface PendingDelta {
|
|
58
|
+
readonly kind: "text" | "thinking";
|
|
59
|
+
text: string;
|
|
37
60
|
readonly timer: ReturnType<typeof setTimeout>;
|
|
38
61
|
}
|
|
39
62
|
|
|
@@ -45,12 +68,39 @@ export class RemoteBridge {
|
|
|
45
68
|
private readonly pendingChallenges = new Map<string, PendingChallenge>();
|
|
46
69
|
private readonly pendingApprovals = new Map<string, PendingApproval>();
|
|
47
70
|
private approvalCounter = 0;
|
|
71
|
+
private autoApproveEnabled = false;
|
|
72
|
+
private runningTool?: string;
|
|
73
|
+
private pendingDelta?: PendingDelta;
|
|
74
|
+
private readonly prompts: PromptRouter;
|
|
48
75
|
private lastError?: string;
|
|
49
76
|
|
|
50
77
|
constructor(options: { config: RemoteControlConfig; host: RemoteHost; sink: TransportSink }) {
|
|
51
78
|
this.config = options.config;
|
|
52
79
|
this.host = options.host;
|
|
53
80
|
this.sink = options.sink;
|
|
81
|
+
this.prompts = new PromptRouter({
|
|
82
|
+
config: this.config,
|
|
83
|
+
host: this.host,
|
|
84
|
+
send: (envelope) => this.send(envelope),
|
|
85
|
+
onCommandSettled: () => this.emitSessionState(this.runningTool),
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
get autoApprove(): boolean {
|
|
90
|
+
return this.autoApproveEnabled;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Agent-side mode: stays effective while no browser is connected. */
|
|
94
|
+
setAutoApprove(enabled: boolean, source: string): void {
|
|
95
|
+
if (this.autoApproveEnabled === enabled) return;
|
|
96
|
+
this.autoApproveEnabled = enabled;
|
|
97
|
+
this.host.notify(`[remote] Auto-approve ${enabled ? "on" : "off"} (by ${source}).`, enabled ? "warning" : "info");
|
|
98
|
+
if (enabled) {
|
|
99
|
+
for (const requestId of [...this.pendingApprovals.keys()]) {
|
|
100
|
+
this.settleApproval(requestId, { approved: true, reason: "auto" });
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
this.emitSessionState(this.runningTool);
|
|
54
104
|
}
|
|
55
105
|
|
|
56
106
|
onConnectionStatus(status: ConnectionStatus, detail?: string): void {
|
|
@@ -66,16 +116,23 @@ export class RemoteBridge {
|
|
|
66
116
|
}
|
|
67
117
|
|
|
68
118
|
stop(): void {
|
|
119
|
+
this.flushDeltas();
|
|
69
120
|
this.rejectAllApprovals();
|
|
70
121
|
}
|
|
71
122
|
|
|
72
123
|
disconnectAll(): number {
|
|
73
|
-
const
|
|
124
|
+
const revokedClients = [...this.trustedClients];
|
|
74
125
|
this.trustedClients.clear();
|
|
75
126
|
this.pendingChallenges.clear();
|
|
76
127
|
this.rejectAllApprovals();
|
|
128
|
+
this.setAutoApprove(false, "local disconnect");
|
|
77
129
|
this.host.onStateChanged?.(this.sink.currentStatus, 0);
|
|
78
|
-
|
|
130
|
+
if (this.sink.currentStatus === "connected") {
|
|
131
|
+
for (const clientId of revokedClients) {
|
|
132
|
+
this.issuePairingChallenge(clientId, "pairing_revoked");
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return revokedClients.length;
|
|
79
136
|
}
|
|
80
137
|
|
|
81
138
|
statusSnapshot(): StatusSnapshot {
|
|
@@ -87,6 +144,7 @@ export class RemoteBridge {
|
|
|
87
144
|
pendingPairings: this.pendingChallenges.size,
|
|
88
145
|
remoteToolPolicy: this.config.remoteToolPolicy,
|
|
89
146
|
remoteToolApproval: this.config.remoteToolApproval,
|
|
147
|
+
autoApprove: this.autoApproveEnabled,
|
|
90
148
|
...(this.lastError ? { lastError: this.lastError } : {}),
|
|
91
149
|
};
|
|
92
150
|
}
|
|
@@ -94,16 +152,29 @@ export class RemoteBridge {
|
|
|
94
152
|
async handleServerMessage(msg: ServerInboundMessage): Promise<void> {
|
|
95
153
|
switch (msg.type) {
|
|
96
154
|
case "history.request": {
|
|
97
|
-
const
|
|
98
|
-
this.
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
155
|
+
const { clientId } = msg;
|
|
156
|
+
const paired = !this.config.requirePairing || (clientId !== undefined && this.trustedClients.has(clientId));
|
|
157
|
+
if (msg.pairStatusOnly && clientId) {
|
|
158
|
+
this.send({
|
|
159
|
+
type: "pair.status",
|
|
160
|
+
sessionId: this.host.sessionId,
|
|
161
|
+
clientId,
|
|
162
|
+
ts: this.host.now(),
|
|
163
|
+
payload: { paired },
|
|
164
|
+
});
|
|
165
|
+
} else {
|
|
166
|
+
this.send({
|
|
167
|
+
type: "history.snapshot",
|
|
168
|
+
sessionId: this.host.sessionId,
|
|
169
|
+
...(clientId ? { clientId } : {}),
|
|
170
|
+
ts: this.host.now(),
|
|
171
|
+
payload: { items: this.host.getHistory(), ...(clientId ? { paired } : {}) },
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
if (clientId && !paired) {
|
|
175
|
+
this.issuePairingChallenge(clientId, "pairing_required");
|
|
176
|
+
} else {
|
|
177
|
+
this.resendPendingApprovals();
|
|
107
178
|
}
|
|
108
179
|
return;
|
|
109
180
|
}
|
|
@@ -112,7 +183,11 @@ export class RemoteBridge {
|
|
|
112
183
|
return;
|
|
113
184
|
case "prompt.send":
|
|
114
185
|
if (!this.ensureTrusted(msg.clientId)) return;
|
|
115
|
-
this.
|
|
186
|
+
await this.prompts.submit(msg.text, msg.deliverAs, msg.images);
|
|
187
|
+
return;
|
|
188
|
+
case "commands.request":
|
|
189
|
+
if (!this.ensureTrusted(msg.clientId)) return;
|
|
190
|
+
this.prompts.sendCatalog(msg.clientId);
|
|
116
191
|
return;
|
|
117
192
|
case "turn.abort":
|
|
118
193
|
if (!this.ensureTrusted(msg.clientId)) return;
|
|
@@ -124,7 +199,11 @@ export class RemoteBridge {
|
|
|
124
199
|
return;
|
|
125
200
|
case "approval.response":
|
|
126
201
|
if (!this.ensureTrusted(msg.clientId)) return;
|
|
127
|
-
this.
|
|
202
|
+
this.settleApproval(msg.requestId, { approved: msg.approved, reason: "user" });
|
|
203
|
+
return;
|
|
204
|
+
case "approval.mode":
|
|
205
|
+
if (!this.ensureTrusted(msg.clientId)) return;
|
|
206
|
+
this.setAutoApprove(msg.autoApprove, msg.clientId);
|
|
128
207
|
return;
|
|
129
208
|
default:
|
|
130
209
|
return;
|
|
@@ -132,12 +211,14 @@ export class RemoteBridge {
|
|
|
132
211
|
}
|
|
133
212
|
|
|
134
213
|
emitSessionState(runningTool?: string): void {
|
|
135
|
-
this.
|
|
214
|
+
this.runningTool = runningTool;
|
|
215
|
+
this.send({
|
|
136
216
|
type: "session.state",
|
|
137
217
|
sessionId: this.host.sessionId,
|
|
138
218
|
ts: this.host.now(),
|
|
139
219
|
payload: {
|
|
140
220
|
state: this.host.isIdle() ? "idle" : "busy",
|
|
221
|
+
autoApprove: this.autoApproveEnabled,
|
|
141
222
|
...(this.host.sessionName ? { sessionName: this.host.sessionName } : {}),
|
|
142
223
|
...(this.host.branch ? { branch: this.host.branch } : {}),
|
|
143
224
|
...(this.host.model ? { model: this.host.model } : {}),
|
|
@@ -147,7 +228,7 @@ export class RemoteBridge {
|
|
|
147
228
|
}
|
|
148
229
|
|
|
149
230
|
emitStreamStart(): void {
|
|
150
|
-
this.
|
|
231
|
+
this.send({
|
|
151
232
|
type: "stream.start",
|
|
152
233
|
sessionId: this.host.sessionId,
|
|
153
234
|
ts: this.host.now(),
|
|
@@ -157,16 +238,38 @@ export class RemoteBridge {
|
|
|
157
238
|
|
|
158
239
|
emitStreamDelta(kind: "text" | "thinking", delta: string): void {
|
|
159
240
|
if (!delta) return;
|
|
241
|
+
if (this.pendingDelta && this.pendingDelta.kind !== kind) this.flushDeltas();
|
|
242
|
+
if (this.pendingDelta) {
|
|
243
|
+
this.pendingDelta.text += delta;
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
const timer = setTimeout(() => this.flushDeltas(), DELTA_FLUSH_MS);
|
|
247
|
+
if (typeof timer === "object" && "unref" in timer) timer.unref();
|
|
248
|
+
this.pendingDelta = { kind, text: delta, timer };
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
private flushDeltas(): void {
|
|
252
|
+
const pending = this.pendingDelta;
|
|
253
|
+
if (!pending) return;
|
|
254
|
+
this.pendingDelta = undefined;
|
|
255
|
+
clearTimeout(pending.timer);
|
|
160
256
|
this.sink.send({
|
|
161
257
|
type: "stream.delta",
|
|
162
258
|
sessionId: this.host.sessionId,
|
|
163
259
|
ts: this.host.now(),
|
|
164
|
-
|
|
260
|
+
// Redacting the joined text also catches secrets split across tokens.
|
|
261
|
+
payload: { kind: pending.kind, delta: redactSecrets(pending.text) },
|
|
165
262
|
});
|
|
166
263
|
}
|
|
167
264
|
|
|
265
|
+
/** Every other frame goes out after the buffered text so the order is preserved. */
|
|
266
|
+
private send(envelope: WireEnvelope): boolean {
|
|
267
|
+
this.flushDeltas();
|
|
268
|
+
return this.sink.send(envelope);
|
|
269
|
+
}
|
|
270
|
+
|
|
168
271
|
emitStreamEnd(text: string): void {
|
|
169
|
-
this.
|
|
272
|
+
this.send({
|
|
170
273
|
type: "stream.end",
|
|
171
274
|
sessionId: this.host.sessionId,
|
|
172
275
|
ts: this.host.now(),
|
|
@@ -175,7 +278,7 @@ export class RemoteBridge {
|
|
|
175
278
|
}
|
|
176
279
|
|
|
177
280
|
emitToolStart(toolCallId: string, toolName: string): void {
|
|
178
|
-
this.
|
|
281
|
+
this.send({
|
|
179
282
|
type: "tool.start",
|
|
180
283
|
sessionId: this.host.sessionId,
|
|
181
284
|
ts: this.host.now(),
|
|
@@ -184,7 +287,7 @@ export class RemoteBridge {
|
|
|
184
287
|
}
|
|
185
288
|
|
|
186
289
|
emitToolEnd(toolCallId: string, toolName: string, isError: boolean, durationMs: number): void {
|
|
187
|
-
this.
|
|
290
|
+
this.send({
|
|
188
291
|
type: "tool.end",
|
|
189
292
|
sessionId: this.host.sessionId,
|
|
190
293
|
ts: this.host.now(),
|
|
@@ -194,7 +297,7 @@ export class RemoteBridge {
|
|
|
194
297
|
|
|
195
298
|
async emitDigest(): Promise<void> {
|
|
196
299
|
const markdown = await this.host.getDigest();
|
|
197
|
-
this.
|
|
300
|
+
this.send({
|
|
198
301
|
type: "digest.snapshot",
|
|
199
302
|
sessionId: this.host.sessionId,
|
|
200
303
|
ts: this.host.now(),
|
|
@@ -202,29 +305,56 @@ export class RemoteBridge {
|
|
|
202
305
|
});
|
|
203
306
|
}
|
|
204
307
|
|
|
205
|
-
requestWebApproval(toolCallId: string, toolName: string): Promise<
|
|
308
|
+
requestWebApproval(toolCallId: string, toolName: string): Promise<ApprovalOutcome> {
|
|
206
309
|
const requestId = `apr_${this.host.now()}_${++this.approvalCounter}`;
|
|
207
|
-
|
|
310
|
+
if (this.autoApproveEnabled) {
|
|
311
|
+
const outcome: ApprovalOutcome = { approved: true, reason: "auto" };
|
|
312
|
+
this.emitApprovalResolved(requestId, outcome);
|
|
313
|
+
return Promise.resolve(outcome);
|
|
314
|
+
}
|
|
315
|
+
const timeoutMs = this.config.approvalTimeoutMs;
|
|
316
|
+
const sent = this.sendApprovalRequest(requestId, toolCallId, toolName, timeoutMs);
|
|
317
|
+
if (!sent) {
|
|
318
|
+
return Promise.resolve({ approved: false, reason: "cancelled" });
|
|
319
|
+
}
|
|
320
|
+
return new Promise<ApprovalOutcome>((resolve) => {
|
|
321
|
+
const timer = setTimeout(() => {
|
|
322
|
+
this.settleApproval(requestId, { approved: false, reason: "timeout" });
|
|
323
|
+
}, timeoutMs);
|
|
324
|
+
if (typeof timer === "object" && "unref" in timer) timer.unref();
|
|
325
|
+
this.pendingApprovals.set(requestId, {
|
|
326
|
+
toolCallId,
|
|
327
|
+
toolName,
|
|
328
|
+
expiresAt: this.host.now() + timeoutMs,
|
|
329
|
+
resolve,
|
|
330
|
+
timer,
|
|
331
|
+
});
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
private sendApprovalRequest(requestId: string, toolCallId: string, toolName: string, timeoutMs: number): boolean {
|
|
336
|
+
return this.send({
|
|
208
337
|
type: "approval.request",
|
|
209
338
|
sessionId: this.host.sessionId,
|
|
210
339
|
ts: this.host.now(),
|
|
211
|
-
payload: {
|
|
212
|
-
requestId,
|
|
213
|
-
toolCallId,
|
|
214
|
-
toolName,
|
|
215
|
-
timeoutMs: this.config.approvalTimeoutMs,
|
|
216
|
-
},
|
|
340
|
+
payload: { requestId, toolCallId, toolName, timeoutMs },
|
|
217
341
|
});
|
|
218
|
-
|
|
219
|
-
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** A browser that reloaded has no replay cursor, so repeat what is still waiting. */
|
|
345
|
+
private resendPendingApprovals(): void {
|
|
346
|
+
for (const [requestId, entry] of this.pendingApprovals) {
|
|
347
|
+
const remainingMs = entry.expiresAt - this.host.now();
|
|
348
|
+
if (remainingMs > 0) this.sendApprovalRequest(requestId, entry.toolCallId, entry.toolName, remainingMs);
|
|
220
349
|
}
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
this.
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
private emitApprovalResolved(requestId: string, outcome: ApprovalOutcome): void {
|
|
353
|
+
this.send({
|
|
354
|
+
type: "approval.resolved",
|
|
355
|
+
sessionId: this.host.sessionId,
|
|
356
|
+
ts: this.host.now(),
|
|
357
|
+
payload: { requestId, ...outcome },
|
|
228
358
|
});
|
|
229
359
|
}
|
|
230
360
|
|
|
@@ -252,9 +382,10 @@ export class RemoteBridge {
|
|
|
252
382
|
"info",
|
|
253
383
|
);
|
|
254
384
|
}
|
|
255
|
-
this.
|
|
385
|
+
this.send({
|
|
256
386
|
type: "pair.required",
|
|
257
387
|
sessionId: this.host.sessionId,
|
|
388
|
+
clientId,
|
|
258
389
|
ts: now,
|
|
259
390
|
payload: {
|
|
260
391
|
challengeId: challenge.challengeId,
|
|
@@ -266,6 +397,10 @@ export class RemoteBridge {
|
|
|
266
397
|
}
|
|
267
398
|
|
|
268
399
|
private handlePairSubmit(clientId: string, code: string): void {
|
|
400
|
+
if (!this.config.requirePairing || this.trustedClients.has(clientId)) {
|
|
401
|
+
this.sendPairResult(clientId, { ok: true, clientId });
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
269
404
|
const challenge = this.pendingChallenges.get(clientId);
|
|
270
405
|
if (!challenge) {
|
|
271
406
|
this.issuePairingChallenge(clientId, "no_active_challenge");
|
|
@@ -277,13 +412,7 @@ export class RemoteBridge {
|
|
|
277
412
|
this.trustedClients.add(clientId);
|
|
278
413
|
this.host.notify(`[remote] Paired client ${clientId}.`, "info");
|
|
279
414
|
this.host.onStateChanged?.(this.sink.currentStatus, this.trustedClients.size);
|
|
280
|
-
this.
|
|
281
|
-
type: "pair.result",
|
|
282
|
-
sessionId: this.host.sessionId,
|
|
283
|
-
clientId,
|
|
284
|
-
ts: this.host.now(),
|
|
285
|
-
payload: { ok: true, clientId },
|
|
286
|
-
});
|
|
415
|
+
this.sendPairResult(clientId, { ok: true, clientId });
|
|
287
416
|
return;
|
|
288
417
|
}
|
|
289
418
|
if (result.reason === "mismatch" && result.next) {
|
|
@@ -291,44 +420,31 @@ export class RemoteBridge {
|
|
|
291
420
|
} else {
|
|
292
421
|
this.pendingChallenges.delete(clientId);
|
|
293
422
|
}
|
|
294
|
-
this.
|
|
423
|
+
this.sendPairResult(clientId, { ok: false, clientId, error: result.reason });
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
private sendPairResult(clientId: string, payload: { ok: boolean; clientId: string; error?: string }): void {
|
|
427
|
+
this.send({
|
|
295
428
|
type: "pair.result",
|
|
296
429
|
sessionId: this.host.sessionId,
|
|
297
430
|
clientId,
|
|
298
431
|
ts: this.host.now(),
|
|
299
|
-
payload
|
|
300
|
-
});
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
private handlePromptSend(text: string, deliverAs?: DeliverMode, images?: readonly PromptImage[]): void {
|
|
304
|
-
const validImages: PromptImage[] = [];
|
|
305
|
-
if (images) {
|
|
306
|
-
for (const img of images.slice(0, this.config.maxImages)) {
|
|
307
|
-
const estimatedBytes = Math.ceil((img.data.length * 3) / 4);
|
|
308
|
-
if (estimatedBytes <= this.config.maxImageBytes) {
|
|
309
|
-
validImages.push(img);
|
|
310
|
-
}
|
|
311
|
-
}
|
|
312
|
-
}
|
|
313
|
-
this.host.sendPrompt(text, {
|
|
314
|
-
...(deliverAs ? { deliverAs } : {}),
|
|
315
|
-
...(validImages.length > 0 ? { images: validImages } : {}),
|
|
432
|
+
payload,
|
|
316
433
|
});
|
|
317
434
|
}
|
|
318
435
|
|
|
319
|
-
private
|
|
436
|
+
private settleApproval(requestId: string, outcome: ApprovalOutcome): void {
|
|
320
437
|
const entry = this.pendingApprovals.get(requestId);
|
|
321
438
|
if (!entry) return;
|
|
322
439
|
clearTimeout(entry.timer);
|
|
323
440
|
this.pendingApprovals.delete(requestId);
|
|
324
|
-
|
|
441
|
+
this.emitApprovalResolved(requestId, outcome);
|
|
442
|
+
entry.resolve(outcome);
|
|
325
443
|
}
|
|
326
444
|
|
|
327
445
|
private rejectAllApprovals(): void {
|
|
328
|
-
for (const
|
|
329
|
-
|
|
330
|
-
entry.resolve(false);
|
|
331
|
-
this.pendingApprovals.delete(id);
|
|
446
|
+
for (const requestId of [...this.pendingApprovals.keys()]) {
|
|
447
|
+
this.settleApproval(requestId, { approved: false, reason: "cancelled" });
|
|
332
448
|
}
|
|
333
449
|
}
|
|
334
450
|
}
|
package/src/client/ws-client.ts
CHANGED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
5
|
+
import { loadExtensionConfig } from "./config-loader.js";
|
|
6
|
+
|
|
7
|
+
describe("loadExtensionConfig", () => {
|
|
8
|
+
let root: string;
|
|
9
|
+
const write = async (path: string, body: object) => {
|
|
10
|
+
await mkdir(dirname(path), { recursive: true });
|
|
11
|
+
await writeFile(path, JSON.stringify(body));
|
|
12
|
+
};
|
|
13
|
+
const load = (projectTrusted: boolean, env: Record<string, string> = {}) =>
|
|
14
|
+
loadExtensionConfig({ cwd: join(root, "repo"), homeDir: join(root, "home"), configDirName: ".pi", projectTrusted, env });
|
|
15
|
+
|
|
16
|
+
beforeEach(async () => {
|
|
17
|
+
root = await mkdtemp(join(tmpdir(), "remote-config-"));
|
|
18
|
+
await write(join(root, "home/.pi/agent/remote-control.json"), { serverUrl: "wss://mine/ws/agent" });
|
|
19
|
+
await write(join(root, "repo/.pi/remote-control.json"), { serverUrl: "wss://theirs/ws/agent", requirePairing: true });
|
|
20
|
+
});
|
|
21
|
+
afterEach(() => rm(root, { recursive: true, force: true }));
|
|
22
|
+
|
|
23
|
+
it("does not apply an untrusted project file", async () => {
|
|
24
|
+
const { config, warnings } = await load(false);
|
|
25
|
+
expect(config).toMatchObject({ serverUrl: "wss://mine/ws/agent", requirePairing: false });
|
|
26
|
+
expect(warnings.join()).toContain("not trusted");
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it("applies only the tightening values of a trusted project", async () => {
|
|
30
|
+
const { config, warnings } = await load(true);
|
|
31
|
+
expect(config).toMatchObject({ serverUrl: "wss://mine/ws/agent", requirePairing: true });
|
|
32
|
+
expect(warnings.join()).toContain("serverUrl");
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it("reads only the file named by PI_REMOTE_CONFIG", async () => {
|
|
36
|
+
const path = join(root, "chosen.json");
|
|
37
|
+
await write(path, { serverUrl: "wss://chosen/ws/agent" });
|
|
38
|
+
const { config } = await load(true, { PI_REMOTE_CONFIG: path });
|
|
39
|
+
expect(config).toMatchObject({ serverUrl: "wss://chosen/ws/agent", requirePairing: false });
|
|
40
|
+
});
|
|
41
|
+
});
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/** Reads the extension configuration files. */
|
|
2
|
+
|
|
3
|
+
import { readFile } from "node:fs/promises";
|
|
4
|
+
import { join, resolve } from "node:path";
|
|
5
|
+
import {
|
|
6
|
+
applyProjectConfig,
|
|
7
|
+
parseRemoteConfig,
|
|
8
|
+
resolveRemoteConfig,
|
|
9
|
+
type ParsedConfigResult,
|
|
10
|
+
type RemoteControlConfig,
|
|
11
|
+
} from "./config.js";
|
|
12
|
+
|
|
13
|
+
export interface ConfigLoadOptions {
|
|
14
|
+
readonly cwd: string;
|
|
15
|
+
readonly homeDir: string;
|
|
16
|
+
/** pi's config directory name, ".pi". */
|
|
17
|
+
readonly configDirName: string;
|
|
18
|
+
readonly projectTrusted: boolean;
|
|
19
|
+
readonly env: Record<string, string | undefined>;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface LoadedConfig {
|
|
23
|
+
readonly config: RemoteControlConfig;
|
|
24
|
+
readonly warnings: string[];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Returns null when the file does not exist or cannot be used. */
|
|
28
|
+
async function readConfigFile(path: string, warnings: string[]): Promise<ParsedConfigResult | null> {
|
|
29
|
+
try {
|
|
30
|
+
const parsed = parseRemoteConfig(JSON.parse(await readFile(path, "utf8")) as unknown);
|
|
31
|
+
warnings.push(...parsed.warnings);
|
|
32
|
+
return parsed;
|
|
33
|
+
} catch (error) {
|
|
34
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
|
|
35
|
+
warnings.push(`config error (${path}): ${error instanceof Error ? error.message : String(error)}`);
|
|
36
|
+
}
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export async function loadExtensionConfig(options: ConfigLoadOptions): Promise<LoadedConfig> {
|
|
42
|
+
const warnings: string[] = [];
|
|
43
|
+
// PI_REMOTE_CONFIG is chosen by the user, so it replaces both files.
|
|
44
|
+
const override = options.env.PI_REMOTE_CONFIG?.trim();
|
|
45
|
+
const userPath = override || join(options.homeDir, options.configDirName, "agent", "remote-control.json");
|
|
46
|
+
const userFile = await readConfigFile(userPath, warnings);
|
|
47
|
+
const config = resolveRemoteConfig(userFile?.config ?? {}, options.env);
|
|
48
|
+
if (override) return { config, warnings };
|
|
49
|
+
|
|
50
|
+
const projectPath = join(options.cwd, options.configDirName, "remote-control.json");
|
|
51
|
+
if (resolve(projectPath) === resolve(userPath)) return { config, warnings };
|
|
52
|
+
// The project file comes with the repository, which the user may not control.
|
|
53
|
+
const projectWarnings: string[] = [];
|
|
54
|
+
const projectFile = await readConfigFile(projectPath, projectWarnings);
|
|
55
|
+
if (!options.projectTrusted) {
|
|
56
|
+
if (projectFile || projectWarnings.length > 0) {
|
|
57
|
+
warnings.push(`ignored ${projectPath} because the project is not trusted`);
|
|
58
|
+
}
|
|
59
|
+
return { config, warnings };
|
|
60
|
+
}
|
|
61
|
+
warnings.push(...projectWarnings);
|
|
62
|
+
if (!projectFile) return { config, warnings };
|
|
63
|
+
|
|
64
|
+
const applied = applyProjectConfig(config, projectFile.config);
|
|
65
|
+
if (applied.ignored.length > 0) {
|
|
66
|
+
warnings.push(
|
|
67
|
+
`ignored in ${projectPath}: ${applied.ignored.join(", ")} (project config may only tighten security; set these in ${userPath})`,
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
return { config: applied.config, warnings };
|
|
71
|
+
}
|
package/src/config.test.ts
CHANGED
|
@@ -2,6 +2,12 @@ import { describe, expect, it } from "vitest";
|
|
|
2
2
|
import { expandHomePath, parseRemoteConfig, parseTokenFileContent, resolveRemoteConfig } from "./config.js";
|
|
3
3
|
|
|
4
4
|
describe("remote config", () => {
|
|
5
|
+
it("defaults to token-only control and respects a pairing override", () => {
|
|
6
|
+
expect(resolveRemoteConfig({}, {}).requirePairing).toBe(false);
|
|
7
|
+
const { config } = parseRemoteConfig({ requirePairing: true });
|
|
8
|
+
expect(resolveRemoteConfig(config, {}).requirePairing).toBe(true);
|
|
9
|
+
});
|
|
10
|
+
|
|
5
11
|
it("rejects raw tokens and resolves env overrides", () => {
|
|
6
12
|
const parsed = parseRemoteConfig({
|
|
7
13
|
token: "secret",
|
package/src/config.ts
CHANGED
|
@@ -25,7 +25,7 @@ export interface RemoteControlConfig {
|
|
|
25
25
|
export const DEFAULT_REMOTE_CONFIG: RemoteControlConfig = {
|
|
26
26
|
serverUrl: "ws://127.0.0.1:8787/ws/agent",
|
|
27
27
|
tokenEnv: "PI_REMOTE_SERVER_TOKEN",
|
|
28
|
-
requirePairing:
|
|
28
|
+
requirePairing: false,
|
|
29
29
|
pairingTtlMs: 5 * 60 * 1000,
|
|
30
30
|
pairingDigits: 6,
|
|
31
31
|
pairingMaxAttempts: 3,
|
|
@@ -96,6 +96,39 @@ export function resolveRemoteConfig(
|
|
|
96
96
|
};
|
|
97
97
|
}
|
|
98
98
|
|
|
99
|
+
const POLICY_STRICTNESS: Record<RemoteToolPolicy, number> = { unrestricted: 0, "read-only": 1, "no-tools": 2 };
|
|
100
|
+
// "local" needs someone at the terminal, so it is stricter than "web".
|
|
101
|
+
const APPROVAL_STRICTNESS: Record<RemoteToolApproval, number> = { off: 0, web: 1, local: 2 };
|
|
102
|
+
|
|
103
|
+
type ProjectRule<Key extends keyof RemoteControlConfig> = (
|
|
104
|
+
value: RemoteControlConfig[Key],
|
|
105
|
+
current: RemoteControlConfig[Key],
|
|
106
|
+
) => boolean;
|
|
107
|
+
|
|
108
|
+
/** Keys a project may set, and when its value is at least as strict. All other keys belong to the user. */
|
|
109
|
+
const PROJECT_RULES: { readonly [Key in keyof RemoteControlConfig]?: ProjectRule<Key> } = {
|
|
110
|
+
requirePairing: (value, current) => value || !current,
|
|
111
|
+
remoteToolPolicy: (value, current) => POLICY_STRICTNESS[value] >= POLICY_STRICTNESS[current],
|
|
112
|
+
remoteToolApproval: (value, current) => APPROVAL_STRICTNESS[value] >= APPROVAL_STRICTNESS[current],
|
|
113
|
+
approvalTimeoutMs: (value, current) => value <= current,
|
|
114
|
+
pairingTtlMs: (value, current) => value <= current,
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
/** Layers a repository's config over the user's without letting it weaken or redirect anything. */
|
|
118
|
+
export function applyProjectConfig(
|
|
119
|
+
base: RemoteControlConfig,
|
|
120
|
+
project: Partial<RemoteControlConfig>,
|
|
121
|
+
): { config: RemoteControlConfig; ignored: string[] } {
|
|
122
|
+
const accepted: Record<string, unknown> = {};
|
|
123
|
+
const ignored: string[] = [];
|
|
124
|
+
for (const key of Object.keys(project) as (keyof RemoteControlConfig)[]) {
|
|
125
|
+
const rule = PROJECT_RULES[key] as ((value: unknown, current: unknown) => boolean) | undefined;
|
|
126
|
+
if (rule?.(project[key], base[key])) accepted[key] = project[key];
|
|
127
|
+
else ignored.push(key);
|
|
128
|
+
}
|
|
129
|
+
return { config: { ...base, ...(accepted as Partial<RemoteControlConfig>) }, ignored };
|
|
130
|
+
}
|
|
131
|
+
|
|
99
132
|
export function expandHomePath(filePath: string, homeDir: string): string {
|
|
100
133
|
const trimmed = filePath.trim();
|
|
101
134
|
if (trimmed === "~") return homeDir;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { buildCommandCatalog, routeSlashInput, type CommandInfo } from "./commands.js";
|
|
3
|
+
|
|
4
|
+
const commands: CommandInfo[] = [
|
|
5
|
+
{ name: "review", source: "prompt", description: "Review code" },
|
|
6
|
+
{ name: "skill:verify", source: "skill" },
|
|
7
|
+
{ name: "remote", source: "extension" },
|
|
8
|
+
{ name: "deploy", source: "prompt" },
|
|
9
|
+
{ name: "deploy:1", source: "extension" },
|
|
10
|
+
{ name: "model", source: "prompt" },
|
|
11
|
+
];
|
|
12
|
+
|
|
13
|
+
describe("routeSlashInput", () => {
|
|
14
|
+
it("expands only prompt templates and skills", () => {
|
|
15
|
+
expect(routeSlashInput("/review src/a.ts", commands)).toEqual({ kind: "expand", name: "review", text: "/review src/a.ts" });
|
|
16
|
+
expect(routeSlashInput("/skill:verify", commands).kind).toBe("expand");
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it("rejects extension commands, even when a template shares the name", () => {
|
|
20
|
+
for (const text of ["/remote auto on", "/deploy now", "/deploy:1", "/new", "/unknown"]) {
|
|
21
|
+
expect(routeSlashInput(text, commands).kind, text).toBe("reject");
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it("routes built-ins ahead of templates", () => {
|
|
26
|
+
expect(routeSlashInput("/model a/b ", commands)).toEqual({ kind: "builtin", name: "model", args: "a/b" });
|
|
27
|
+
expect(routeSlashInput("/compact keep\nthe plan", commands)).toMatchObject({ name: "compact", args: "keep\nthe plan" });
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it("keeps ordinary text, paths, and escaped slashes as text", () => {
|
|
31
|
+
expect(routeSlashInput("hello", commands)).toEqual({ kind: "plain", text: "hello" });
|
|
32
|
+
expect(routeSlashInput("/etc/hosts is wrong", commands)).toMatchObject({ kind: "plain", text: "/etc/hosts is wrong" });
|
|
33
|
+
expect(routeSlashInput("//remote auto on", commands)).toEqual({ kind: "plain", text: "/remote auto on" });
|
|
34
|
+
expect(routeSlashInput("/ spaced", commands).kind).toBe("plain");
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it("lists only commands that can run", () => {
|
|
38
|
+
expect(buildCommandCatalog(commands).map((command) => command.name)).toEqual([
|
|
39
|
+
"compact", "model", "thinking", "review", "skill:verify",
|
|
40
|
+
]);
|
|
41
|
+
});
|
|
42
|
+
});
|