@wkqco33/pi-remote-control 0.1.2 → 0.2.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 +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.test.ts +6 -0
- package/src/config.ts +1 -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 +47 -14
|
@@ -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
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,
|
|
@@ -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
|
+
});
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure routing for slash commands typed in the web UI.
|
|
3
|
+
*
|
|
4
|
+
* Extension commands are never dispatched: pi runs their handlers without the
|
|
5
|
+
* `input` and `tool_call` events, so remote tool policy could not apply to them.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
|
|
9
|
+
|
|
10
|
+
export const THINKING_LEVELS: readonly ThinkingLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
|
|
11
|
+
|
|
12
|
+
export type BuiltinCommandName = "compact" | "model" | "thinking";
|
|
13
|
+
|
|
14
|
+
export interface CommandInfo {
|
|
15
|
+
readonly name: string;
|
|
16
|
+
readonly description?: string;
|
|
17
|
+
readonly source: "extension" | "prompt" | "skill";
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface CatalogCommand {
|
|
21
|
+
readonly name: string;
|
|
22
|
+
readonly description?: string;
|
|
23
|
+
readonly source: "builtin" | "prompt" | "skill";
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export const BUILTIN_COMMANDS: readonly (CatalogCommand & { readonly name: BuiltinCommandName })[] = [
|
|
27
|
+
{ name: "compact", source: "builtin", description: "Compact the session context [instructions]" },
|
|
28
|
+
{ name: "model", source: "builtin", description: "Show or change the model [provider/id]" },
|
|
29
|
+
{ name: "thinking", source: "builtin", description: "Show or change the thinking level [level]" },
|
|
30
|
+
];
|
|
31
|
+
|
|
32
|
+
export type SlashRoute =
|
|
33
|
+
/** Ordinary prompt text, delivered without any expansion. */
|
|
34
|
+
| { readonly kind: "plain"; readonly text: string }
|
|
35
|
+
/** Prompt template or skill that pi expands into a prompt. */
|
|
36
|
+
| { readonly kind: "expand"; readonly name: string; readonly text: string }
|
|
37
|
+
| { readonly kind: "builtin"; readonly name: BuiltinCommandName; readonly args: string }
|
|
38
|
+
| { readonly kind: "reject"; readonly name: string; readonly reason: string };
|
|
39
|
+
|
|
40
|
+
function isExtensionCommand(command: CommandInfo, name: string): boolean {
|
|
41
|
+
if (command.source !== "extension") return false;
|
|
42
|
+
// pi suffixes duplicate names, for example "review:1".
|
|
43
|
+
return command.name === name || (command.name.startsWith(`${name}:`) && /^\d+$/.test(command.name.slice(name.length + 1)));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function routeSlashInput(text: string, commands: readonly CommandInfo[]): SlashRoute {
|
|
47
|
+
if (!text.startsWith("/")) return { kind: "plain", text };
|
|
48
|
+
// "//..." is the escape for text that really starts with a slash.
|
|
49
|
+
if (text.startsWith("//")) return { kind: "plain", text: text.slice(1) };
|
|
50
|
+
|
|
51
|
+
const match = /^\/(\S*)\s*([\s\S]*)$/.exec(text);
|
|
52
|
+
const name = match?.[1] ?? "";
|
|
53
|
+
// A second slash means a file path, not a command.
|
|
54
|
+
if (!name || name.includes("/")) return { kind: "plain", text };
|
|
55
|
+
|
|
56
|
+
const builtin = BUILTIN_COMMANDS.find((command) => command.name === name);
|
|
57
|
+
if (builtin) return { kind: "builtin", name: builtin.name, args: (match?.[2] ?? "").trim() };
|
|
58
|
+
|
|
59
|
+
if (commands.some((command) => isExtensionCommand(command, name))) {
|
|
60
|
+
return { kind: "reject", name, reason: `/${name} is an extension command, which cannot be run from the web.` };
|
|
61
|
+
}
|
|
62
|
+
if (commands.some((command) => command.name === name && command.source !== "extension")) {
|
|
63
|
+
return { kind: "expand", name, text };
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
kind: "reject",
|
|
67
|
+
name,
|
|
68
|
+
reason: `/${name} is not a command available from the web. To send it as text, start with "//".`,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function buildCommandCatalog(commands: readonly CommandInfo[]): CatalogCommand[] {
|
|
73
|
+
const expandable = commands.flatMap((command): CatalogCommand[] => {
|
|
74
|
+
if (command.source === "extension") return [];
|
|
75
|
+
// Hide names that routing would reject or handle as a built-in.
|
|
76
|
+
if (routeSlashInput(`/${command.name}`, commands).kind !== "expand") return [];
|
|
77
|
+
return [{ name: command.name, source: command.source, ...(command.description ? { description: command.description } : {}) }];
|
|
78
|
+
});
|
|
79
|
+
return [...BUILTIN_COMMANDS, ...expandable];
|
|
80
|
+
}
|
package/src/core/history.test.ts
CHANGED
|
@@ -16,3 +16,38 @@ describe("buildHistorySnapshot", () => {
|
|
|
16
16
|
expect(out[1]?.text).toBe("done");
|
|
17
17
|
});
|
|
18
18
|
});
|
|
19
|
+
|
|
20
|
+
describe("buildHistorySnapshot tool calls", () => {
|
|
21
|
+
const call = (id: string, text = "") => ({
|
|
22
|
+
type: "message",
|
|
23
|
+
message: {
|
|
24
|
+
role: "assistant",
|
|
25
|
+
content: [
|
|
26
|
+
...(text ? [{ type: "text", text }] : []),
|
|
27
|
+
{ type: "toolCall", id, name: "bash", arguments: { command: "echo secret-command" } },
|
|
28
|
+
],
|
|
29
|
+
},
|
|
30
|
+
});
|
|
31
|
+
const result = (toolCallId: string, isError = false) => ({
|
|
32
|
+
type: "message",
|
|
33
|
+
message: { role: "toolResult", toolCallId, toolName: "bash", isError, durationMs: 12, content: "secret output" },
|
|
34
|
+
});
|
|
35
|
+
const user = (content: string) => ({ type: "message", message: { role: "user", content } });
|
|
36
|
+
|
|
37
|
+
it("restores call states in order without arguments or output", () => {
|
|
38
|
+
const entries = [user("go"), call("a", "first"), result("a"), call("b"), result("b", true), call("c"), user("next"), call("d")];
|
|
39
|
+
const out = buildHistorySnapshot(entries, { busy: true });
|
|
40
|
+
expect(out.map((item) => (item.role === "tool" ? `${item.toolCallId}:${item.status}` : item.text))).toEqual([
|
|
41
|
+
"go", "first", "a:done", "b:failed", "c:interrupted", "next", "d:running",
|
|
42
|
+
]);
|
|
43
|
+
expect(out[2]).toMatchObject({ role: "tool", text: "bash", durationMs: 12 });
|
|
44
|
+
expect(JSON.stringify(out)).not.toContain("secret");
|
|
45
|
+
expect(buildHistorySnapshot(entries).at(-1)).toMatchObject({ status: "interrupted" });
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it("bounds messages and tool calls separately", () => {
|
|
49
|
+
const entries = [user("old"), user("kept"), call("a"), call("b"), call("c"), user("last")];
|
|
50
|
+
const out = buildHistorySnapshot(entries, { maxItems: 2, maxToolItems: 2 });
|
|
51
|
+
expect(out.map((item) => (item.role === "tool" ? item.toolCallId : item.text))).toEqual(["kept", "b", "c", "last"]);
|
|
52
|
+
});
|
|
53
|
+
});
|