@wkqco33/pi-remote-control 0.1.1 → 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 CHANGED
@@ -6,8 +6,9 @@
6
6
  pi install npm:@wkqco33/pi-remote-control
7
7
  ```
8
8
 
9
- - 런타임 npm 의존성 제로 (Node 22+ 내장 `WebSocket` 사용)
10
- - 로컬 터미널 전용 6자리 페어링 코드
9
+ - 런타임 npm 의존성 제로 (Node 22.19+ 내장 `WebSocket` 사용)
10
+ - `pi` 1.6.0 이상 필요
11
+ - 기본 릴레이 토큰 인증 및 선택 가능한 로컬 터미널 6자리 페어링(`requirePairing: true`)
11
12
  - 실시간 `text` / `thinking` 델타 스트리밍 및 `steer` / `followUp` / `abort`
12
13
  - 원격 턴 도구 정책(`unrestricted` / `read-only` / `no-tools`) 및 웹/로컬 도구 승인
13
14
  - 시크릿 리댁션, 이미지 첨부, 작업 다이제스트(`/remote digest`)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wkqco33/pi-remote-control",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Remote control extension for pi coding agent: stream live sessions, steer/followUp prompts, and approve tool calls from a web relay server.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -13,7 +13,7 @@
13
13
  "relay"
14
14
  ],
15
15
  "engines": {
16
- "node": ">=22.0.0"
16
+ "node": ">=22.19.0"
17
17
  },
18
18
  "repository": {
19
19
  "type": "git",
@@ -43,10 +43,10 @@
43
43
  "prepublishOnly": "npm run check"
44
44
  },
45
45
  "peerDependencies": {
46
- "@earendil-works/pi-coding-agent": "*"
46
+ "@earendil-works/pi-coding-agent": ">=1.6.0"
47
47
  },
48
48
  "devDependencies": {
49
- "@earendil-works/pi-coding-agent": "^0.85.1",
49
+ "@earendil-works/pi-coding-agent": "^1.6.0",
50
50
  "@types/node": "^24.0.0",
51
51
  "typescript": "^5.9.2",
52
52
  "vitest": "^3.2.4"
@@ -0,0 +1,61 @@
1
+ /** Runs the built-in slash commands that have an extension API equivalent. */
2
+
3
+ import { THINKING_LEVELS, type BuiltinCommandName, type ThinkingLevel } from "../core/commands.js";
4
+
5
+ export type SetModelResult = "ok" | "not_found" | "ambiguous" | "no_auth";
6
+
7
+ export interface BuiltinHost {
8
+ readonly model?: string;
9
+ isIdle(): boolean;
10
+ /** Models that have authentication configured, as "provider/id". */
11
+ listModels(): string[];
12
+ setModel(reference: string): Promise<SetModelResult>;
13
+ getThinkingLevel(): ThinkingLevel;
14
+ setThinkingLevel(level: ThinkingLevel): void;
15
+ compact(instructions: string | undefined): Promise<void>;
16
+ }
17
+
18
+ export interface CommandResult {
19
+ readonly ok: boolean;
20
+ readonly message: string;
21
+ }
22
+
23
+ const MAX_LISTED_MODELS = 30;
24
+ const success = (message: string): CommandResult => ({ ok: true, message });
25
+ const failure = (message: string): CommandResult => ({ ok: false, message });
26
+
27
+ async function runModel(host: BuiltinHost, reference: string): Promise<CommandResult> {
28
+ if (!reference) {
29
+ const models = host.listModels();
30
+ const listed = models.slice(0, MAX_LISTED_MODELS).map((model) => `- ${model}`);
31
+ if (models.length > MAX_LISTED_MODELS) listed.push(`- …and ${models.length - MAX_LISTED_MODELS} more`);
32
+ return success([`Current model: ${host.model ?? "unknown"}`, ...listed].join("\n"));
33
+ }
34
+ const result = await host.setModel(reference);
35
+ if (result === "ok") return success(`Model changed to ${reference}.`);
36
+ if (result === "no_auth") return failure(`No authentication is configured for ${reference}.`);
37
+ if (result === "ambiguous") return failure(`Several providers offer ${reference}. Use provider/id.`);
38
+ return failure(`Unknown model: ${reference}. Run /model to list available models.`);
39
+ }
40
+
41
+ function runThinking(host: BuiltinHost, level: string): CommandResult {
42
+ if (!level) return success(`Thinking level: ${host.getThinkingLevel()} (${THINKING_LEVELS.join(", ")})`);
43
+ const next = THINKING_LEVELS.find((item) => item === level);
44
+ if (!next) return failure(`Unknown thinking level: ${level}. Use one of ${THINKING_LEVELS.join(", ")}.`);
45
+ host.setThinkingLevel(next);
46
+ // pi clamps the level to what the current model supports.
47
+ const applied = host.getThinkingLevel();
48
+ return success(applied === next ? `Thinking level set to ${applied}.` : `Thinking level set to ${applied}; this model does not support ${next}.`);
49
+ }
50
+
51
+ export async function runBuiltinCommand(host: BuiltinHost, name: BuiltinCommandName, args: string): Promise<CommandResult> {
52
+ try {
53
+ if (name === "model") return await runModel(host, args);
54
+ if (name === "thinking") return runThinking(host, args);
55
+ if (!host.isIdle()) return failure("Wait for the current work to finish, or abort it, before /compact.");
56
+ await host.compact(args || undefined);
57
+ return success("Session context compacted.");
58
+ } catch (error) {
59
+ return failure(`/${name} failed: ${error instanceof Error ? error.message : String(error)}`);
60
+ }
61
+ }
@@ -0,0 +1,91 @@
1
+ /** Turns web input into agent prompts or slash command runs. */
2
+
3
+ import type { RemoteControlConfig } from "../config.js";
4
+ import { buildCommandCatalog, routeSlashInput, THINKING_LEVELS, type BuiltinCommandName } from "../core/commands.js";
5
+ import type { DeliverMode, PromptImage, WireEnvelope } from "../core/protocol.js";
6
+ import { redactSecrets } from "../core/redact.js";
7
+ import { runBuiltinCommand, type CommandResult } from "./command-handler.js";
8
+ import type { RemoteHost } from "./remote-bridge.js";
9
+
10
+ export interface PromptRouterOptions {
11
+ readonly config: RemoteControlConfig;
12
+ readonly host: RemoteHost;
13
+ readonly send: (envelope: WireEnvelope) => boolean;
14
+ /** Called after a built-in command, which may change the model or busy state. */
15
+ readonly onCommandSettled: () => void;
16
+ }
17
+
18
+ export class PromptRouter {
19
+ private readonly options: PromptRouterOptions;
20
+ private builtinRunning = false;
21
+
22
+ constructor(options: PromptRouterOptions) {
23
+ this.options = options;
24
+ }
25
+
26
+ async submit(text: string, deliverAs?: DeliverMode, images?: readonly PromptImage[]): Promise<void> {
27
+ const { host } = this.options;
28
+ const route = routeSlashInput(text, text.startsWith("/") ? host.listCommands() : []);
29
+ if (route.kind === "reject") {
30
+ this.emitResult(route.name, { ok: false, message: route.reason });
31
+ return;
32
+ }
33
+ if (route.kind === "builtin") {
34
+ await this.runBuiltin(route.name, route.args, Boolean(images?.length));
35
+ return;
36
+ }
37
+ const validImages = this.acceptImages(images);
38
+ host.sendPrompt(route.text, {
39
+ ...(route.kind === "expand" ? { expandPromptTemplates: true } : {}),
40
+ ...(deliverAs ? { deliverAs } : {}),
41
+ ...(validImages.length > 0 ? { images: validImages } : {}),
42
+ });
43
+ }
44
+
45
+ sendCatalog(clientId: string): void {
46
+ const { host } = this.options;
47
+ const commands = buildCommandCatalog(host.listCommands()).map((command) =>
48
+ command.description ? { ...command, description: redactSecrets(command.description) } : command,
49
+ );
50
+ this.options.send({
51
+ type: "commands.snapshot",
52
+ sessionId: host.sessionId,
53
+ clientId,
54
+ ts: host.now(),
55
+ payload: { commands, models: host.listModels(), thinkingLevels: THINKING_LEVELS },
56
+ });
57
+ }
58
+
59
+ private async runBuiltin(name: BuiltinCommandName, args: string, hasImages: boolean): Promise<void> {
60
+ if (hasImages) {
61
+ this.emitResult(name, { ok: false, message: `/${name} does not accept images.` });
62
+ return;
63
+ }
64
+ if (this.builtinRunning) {
65
+ this.emitResult(name, { ok: false, message: "Another command is still running." });
66
+ return;
67
+ }
68
+ this.builtinRunning = true;
69
+ try {
70
+ this.emitResult(name, await runBuiltinCommand(this.options.host, name, args));
71
+ } finally {
72
+ this.builtinRunning = false;
73
+ this.options.onCommandSettled();
74
+ }
75
+ }
76
+
77
+ private acceptImages(images: readonly PromptImage[] = []): PromptImage[] {
78
+ const { maxImages, maxImageBytes } = this.options.config;
79
+ return images.slice(0, maxImages).filter((image) => Math.ceil((image.data.length * 3) / 4) <= maxImageBytes);
80
+ }
81
+
82
+ private emitResult(command: string, result: CommandResult): void {
83
+ const { host } = this.options;
84
+ this.options.send({
85
+ type: "command.result",
86
+ sessionId: host.sessionId,
87
+ ts: host.now(),
88
+ payload: { command, ok: result.ok, message: redactSecrets(result.message) },
89
+ });
90
+ }
91
+ }
@@ -6,7 +6,8 @@ import { RemoteBridge, type RemoteHost, type TransportSink } from "./remote-brid
6
6
  function makeHarness(requirePairing = true) {
7
7
  const sent: WireEnvelope[] = [];
8
8
  const notices: string[] = [];
9
- const prompts: Array<{ text: string; deliverAs?: string }> = [];
9
+ const prompts: Array<{ text: string; deliverAs?: string; expand?: boolean }> = [];
10
+ const calls: string[] = [];
10
11
  let idx = 0;
11
12
  const randSeq = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.9, 0.8, 0.7, 0.0, 0.9, 0.8];
12
13
 
@@ -22,7 +23,20 @@ function makeHarness(requirePairing = true) {
22
23
  host: "box",
23
24
  cwd: "/repo",
24
25
  isIdle: () => true,
25
- sendPrompt: (text, opts) => prompts.push({ text, deliverAs: opts?.deliverAs }),
26
+ sendPrompt: (text, opts) =>
27
+ prompts.push({ text, deliverAs: opts?.deliverAs, ...(opts?.expandPromptTemplates ? { expand: true } : {}) }),
28
+ listCommands: () => [
29
+ { name: "review", source: "prompt", description: "Review sk-ant-api03-1234567890abcdef" },
30
+ { name: "remote", source: "extension" },
31
+ ],
32
+ listModels: () => ["acme/small"],
33
+ setModel: async (reference) => {
34
+ calls.push(`model ${reference}`);
35
+ return reference === "acme/small" ? "ok" : "not_found";
36
+ },
37
+ getThinkingLevel: () => "low",
38
+ setThinkingLevel: (level) => void calls.push(`thinking ${level}`),
39
+ compact: async (instructions) => void calls.push(`compact ${instructions ?? ""}`),
26
40
  abort: vi.fn(),
27
41
  notify: (text) => notices.push(text),
28
42
  getHistory: () => [{ role: "user", text: "hi" }],
@@ -35,7 +49,7 @@ function makeHarness(requirePairing = true) {
35
49
  host,
36
50
  sink,
37
51
  });
38
- return { bridge, sent, notices, prompts, host };
52
+ return { bridge, sent, notices, prompts, calls, host };
39
53
  }
40
54
 
41
55
  describe("RemoteBridge", () => {
@@ -44,6 +58,7 @@ describe("RemoteBridge", () => {
44
58
  await bridge.handleServerMessage({ type: "prompt.send", clientId: "web-1", text: "hack" });
45
59
  expect(prompts).toHaveLength(0);
46
60
  expect(notices[0]).toContain("123-456");
61
+ expect(sent[0]).toMatchObject({ type: "pair.required", clientId: "web-1" });
47
62
  expect(JSON.stringify(sent)).not.toContain("123456");
48
63
 
49
64
  await bridge.handleServerMessage({ type: "pair.submit", clientId: "web-1", code: "123456" });
@@ -54,6 +69,111 @@ describe("RemoteBridge", () => {
54
69
  expect(prompts).toEqual([{ text: "hello", deliverAs: undefined }]);
55
70
  });
56
71
 
72
+ it("refreshes pairing state separately for each subscribed browser", async () => {
73
+ const { bridge, sent } = makeHarness();
74
+ await bridge.handleServerMessage({ type: "history.request", clientId: "web-1" });
75
+ expect(sent[0]).toMatchObject({
76
+ type: "history.snapshot", clientId: "web-1", payload: { paired: false },
77
+ });
78
+ await bridge.handleServerMessage({ type: "pair.submit", clientId: "web-1", code: "123456" });
79
+
80
+ const beforeRefresh = sent.length;
81
+ await bridge.handleServerMessage({ type: "history.request", clientId: "web-2" });
82
+ await bridge.handleServerMessage({ type: "history.request", clientId: "web-1", pairStatusOnly: true });
83
+ expect(sent.slice(beforeRefresh)).toMatchObject([
84
+ { type: "history.snapshot", clientId: "web-2", payload: { paired: false } },
85
+ { type: "pair.required", clientId: "web-2" },
86
+ { type: "pair.status", clientId: "web-1", payload: { paired: true } },
87
+ ]);
88
+
89
+ expect(bridge.disconnectAll()).toBe(1);
90
+ expect(sent.at(-1)).toMatchObject({ type: "pair.required", clientId: "web-1", payload: { reason: "pairing_revoked" } });
91
+ });
92
+
93
+ it("accepts prompts directly when the session disables pairing", async () => {
94
+ const { bridge, sent, notices, prompts } = makeHarness(false);
95
+ await bridge.handleServerMessage({ type: "history.request", clientId: "web-1" });
96
+ await bridge.handleServerMessage({ type: "prompt.send", clientId: "web-1", text: "hello" });
97
+ expect(sent).toMatchObject([
98
+ { type: "history.snapshot", clientId: "web-1", payload: { paired: true } },
99
+ ]);
100
+ expect(notices).toHaveLength(0);
101
+ expect(prompts).toEqual([{ text: "hello", deliverAs: undefined }]);
102
+ });
103
+
104
+ it("expands templates but never dispatches extension or unknown commands", async () => {
105
+ const { bridge, sent, prompts, calls } = makeHarness(false);
106
+ const type = (text: string) => bridge.handleServerMessage({ type: "prompt.send", clientId: "web-1", text });
107
+ await type("/review a.ts");
108
+ await type("//remote auto on");
109
+ await type("/remote auto on");
110
+ await type("/nope");
111
+ expect(prompts).toEqual([
112
+ { text: "/review a.ts", deliverAs: undefined, expand: true },
113
+ { text: "/remote auto on", deliverAs: undefined },
114
+ ]);
115
+ expect(sent.filter((e) => e.type === "command.result").map((e) => e.payload)).toMatchObject([
116
+ { command: "remote", ok: false },
117
+ { command: "nope", ok: false },
118
+ ]);
119
+ expect(calls).toEqual([]);
120
+ });
121
+
122
+ it("runs built-in commands and reports their results", async () => {
123
+ const { bridge, sent, prompts, calls } = makeHarness(false);
124
+ const type = (text: string) => bridge.handleServerMessage({ type: "prompt.send", clientId: "web-1", text });
125
+ for (const text of ["/model acme/small", "/model missing", "/thinking high", "/thinking huge", "/compact keep plan"]) {
126
+ await type(text);
127
+ }
128
+ expect(calls).toEqual(["model acme/small", "model missing", "thinking high", "compact keep plan"]);
129
+ const results = sent.filter((e) => e.type === "command.result").map((e) => e.payload as { ok: boolean; message: string });
130
+ expect(results.map((result) => result.ok)).toEqual([true, false, true, false, true]);
131
+ expect(results[2]?.message).toContain("does not support high");
132
+ expect(prompts).toEqual([]);
133
+ expect(sent.at(-1)?.type).toBe("session.state");
134
+ });
135
+
136
+ it("refuses to compact while the agent is working", async () => {
137
+ const { bridge, sent, calls, host } = makeHarness(false);
138
+ host.isIdle = () => false;
139
+ await bridge.handleServerMessage({ type: "prompt.send", clientId: "web-1", text: "/compact" });
140
+ expect(calls).toEqual([]);
141
+ expect(sent.find((e) => e.type === "command.result")?.payload).toMatchObject({ ok: false });
142
+ });
143
+
144
+ it("sends the command catalog only to paired browsers", async () => {
145
+ const unpaired = makeHarness(true);
146
+ await unpaired.bridge.handleServerMessage({ type: "commands.request", clientId: "web-1" });
147
+ expect(unpaired.sent.map((e) => e.type)).toEqual(["pair.required"]);
148
+
149
+ const { bridge, sent } = makeHarness(false);
150
+ await bridge.handleServerMessage({ type: "commands.request", clientId: "web-1" });
151
+ expect(sent[0]).toMatchObject({ type: "commands.snapshot", clientId: "web-1", payload: { models: ["acme/small"] } });
152
+ expect(JSON.stringify(sent[0])).toContain("[redacted:anthropic-key]");
153
+ expect(JSON.stringify(sent[0])).not.toContain('"remote"');
154
+ });
155
+
156
+ it("coalesces stream deltas and keeps them ahead of later frames", () => {
157
+ vi.useFakeTimers();
158
+ try {
159
+ const { bridge, sent } = makeHarness(false);
160
+ bridge.emitStreamDelta("thinking", "hm");
161
+ bridge.emitStreamDelta("text", "sk-ant-api03-12345678");
162
+ bridge.emitStreamDelta("text", "90abcdef done");
163
+ expect(sent.map((e) => e.payload)).toEqual([{ kind: "thinking", delta: "hm" }]);
164
+ bridge.emitToolStart("tc-1", "bash");
165
+ expect(sent.map((e) => e.type)).toEqual(["stream.delta", "stream.delta", "tool.start"]);
166
+ expect(JSON.stringify(sent[1])).toContain("[redacted:anthropic-key]");
167
+
168
+ bridge.emitStreamDelta("text", "tail");
169
+ vi.advanceTimersByTime(50);
170
+ expect(sent.at(-1)).toMatchObject({ type: "stream.delta", payload: { delta: "tail" } });
171
+ expect(sent).toHaveLength(4);
172
+ } finally {
173
+ vi.useRealTimers();
174
+ }
175
+ });
176
+
57
177
  it("handles web tool approval and resolves false on disconnect", async () => {
58
178
  const { bridge, sent } = makeHarness(false);
59
179
  const promise = bridge.requestWebApproval("tc-1", "bash");
@@ -67,10 +187,47 @@ describe("RemoteBridge", () => {
67
187
  requestId,
68
188
  approved: true,
69
189
  });
70
- await expect(promise).resolves.toBe(true);
190
+ await expect(promise).resolves.toEqual({ approved: true, reason: "user" });
71
191
 
72
192
  const promise2 = bridge.requestWebApproval("tc-2", "bash");
73
193
  bridge.onConnectionStatus("disconnected");
74
- await expect(promise2).resolves.toBe(false);
194
+ await expect(promise2).resolves.toEqual({ approved: false, reason: "cancelled" });
195
+ });
196
+
197
+ it("approves without a browser while auto-approve is on", async () => {
198
+ const { bridge, sent } = makeHarness(false);
199
+ const pending = bridge.requestWebApproval("tc-1", "bash");
200
+ await bridge.handleServerMessage({ type: "approval.mode", clientId: "web-1", autoApprove: true });
201
+ await expect(pending).resolves.toEqual({ approved: true, reason: "auto" });
202
+ expect(sent.at(-1)).toMatchObject({ type: "session.state", payload: { autoApprove: true } });
203
+
204
+ bridge.onConnectionStatus("disconnected");
205
+ const before = sent.length;
206
+ await expect(bridge.requestWebApproval("tc-2", "bash")).resolves.toEqual({ approved: true, reason: "auto" });
207
+ expect(sent.slice(before).map((e) => e.type)).toEqual(["approval.resolved"]);
208
+
209
+ bridge.disconnectAll();
210
+ expect(bridge.autoApprove).toBe(false);
211
+ });
212
+
213
+ it("ignores auto-approve requests from unpaired browsers", async () => {
214
+ const { bridge } = makeHarness(true);
215
+ await bridge.handleServerMessage({ type: "approval.mode", clientId: "web-1", autoApprove: true });
216
+ expect(bridge.autoApprove).toBe(false);
217
+ });
218
+
219
+ it("reports a timeout and repeats pending approvals to a returning browser", async () => {
220
+ vi.useFakeTimers();
221
+ try {
222
+ const { bridge, sent } = makeHarness(false);
223
+ const pending = bridge.requestWebApproval("tc-1", "bash");
224
+ await bridge.handleServerMessage({ type: "history.request", clientId: "web-2" });
225
+ expect(sent.filter((e) => e.type === "approval.request")).toHaveLength(2);
226
+ vi.advanceTimersByTime(5000);
227
+ await expect(pending).resolves.toEqual({ approved: false, reason: "timeout" });
228
+ expect(sent.at(-1)).toMatchObject({ type: "approval.resolved", payload: { reason: "timeout" } });
229
+ } finally {
230
+ vi.useRealTimers();
231
+ }
75
232
  });
76
233
  });