@wkqco33/pi-remote-control 0.0.0-stage → 0.1.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.
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Pure wire protocol types and envelope parser for pi-remote-control.
3
+ * Mirrors `server/internal/protocol/types.go`.
4
+ */
5
+
6
+ export const PROTOCOL_VERSION = 1;
7
+
8
+ export type AgentState = "idle" | "busy";
9
+ export type DeliverMode = "steer" | "followUp";
10
+
11
+ export interface PromptImage {
12
+ readonly mediaType: string;
13
+ readonly data: string;
14
+ }
15
+
16
+ export interface HistoryItem {
17
+ readonly role: "user" | "assistant" | "system";
18
+ readonly text: string;
19
+ readonly ts?: number;
20
+ }
21
+
22
+ export interface WireEnvelope<T = unknown> {
23
+ readonly type: string;
24
+ readonly sessionId?: string;
25
+ readonly seq?: number;
26
+ readonly ts?: number;
27
+ readonly clientId?: string;
28
+ readonly payload?: T;
29
+ }
30
+
31
+ export interface PromptSendPayload {
32
+ readonly sessionId?: string;
33
+ readonly text: string;
34
+ readonly deliverAs?: DeliverMode;
35
+ readonly images?: readonly PromptImage[];
36
+ }
37
+
38
+ export interface PairSubmitPayload {
39
+ readonly sessionId?: string;
40
+ readonly code: string;
41
+ }
42
+
43
+ export interface ApprovalResponsePayload {
44
+ readonly sessionId?: string;
45
+ readonly requestId: string;
46
+ readonly approved: boolean;
47
+ }
48
+
49
+ export interface HistoryRequestPayload {
50
+ readonly clientId?: string;
51
+ }
52
+
53
+ export type ServerInboundMessage =
54
+ | { readonly type: "history.request"; readonly clientId?: string }
55
+ | { readonly type: "pair.submit"; readonly clientId: string; readonly code: string }
56
+ | {
57
+ readonly type: "prompt.send";
58
+ readonly clientId: string;
59
+ readonly text: string;
60
+ readonly deliverAs?: DeliverMode;
61
+ readonly images?: readonly PromptImage[];
62
+ }
63
+ | { readonly type: "turn.abort"; readonly clientId: string }
64
+ | { readonly type: "approval.response"; readonly clientId: string; readonly requestId: string; readonly approved: boolean }
65
+ | { readonly type: "digest.request"; readonly clientId: string }
66
+ | { readonly type: "ping" }
67
+ | { readonly type: "pong" }
68
+ | { readonly type: "error"; readonly code: string; readonly message: string };
69
+
70
+ function isRecord(value: unknown): value is Record<string, unknown> {
71
+ return typeof value === "object" && value !== null && !Array.isArray(value);
72
+ }
73
+
74
+ export function parseServerEnvelope(raw: string): ServerInboundMessage | null {
75
+ let parsed: unknown;
76
+ try {
77
+ parsed = JSON.parse(raw);
78
+ } catch {
79
+ return null;
80
+ }
81
+ if (!isRecord(parsed) || typeof parsed.type !== "string") return null;
82
+
83
+ const clientId = typeof parsed.clientId === "string" ? parsed.clientId : "";
84
+ const payload = isRecord(parsed.payload) ? parsed.payload : {};
85
+
86
+ switch (parsed.type) {
87
+ case "ping":
88
+ return { type: "ping" };
89
+ case "pong":
90
+ return { type: "pong" };
91
+ case "history.request": {
92
+ const reqClient = typeof payload.clientId === "string" ? payload.clientId : clientId || undefined;
93
+ return reqClient === undefined ? { type: "history.request" } : { type: "history.request", clientId: reqClient };
94
+ }
95
+ case "pair.submit":
96
+ if (!clientId || typeof payload.code !== "string") return null;
97
+ return { type: "pair.submit", clientId, code: payload.code };
98
+ case "prompt.send": {
99
+ if (!clientId || typeof payload.text !== "string") return null;
100
+ const deliverAs =
101
+ payload.deliverAs === "steer" || payload.deliverAs === "followUp" ? payload.deliverAs : undefined;
102
+ const images = parseImages(payload.images);
103
+ return {
104
+ type: "prompt.send",
105
+ clientId,
106
+ text: payload.text,
107
+ ...(deliverAs === undefined ? {} : { deliverAs }),
108
+ ...(images === undefined ? {} : { images }),
109
+ };
110
+ }
111
+ case "turn.abort":
112
+ return clientId ? { type: "turn.abort", clientId } : null;
113
+ case "approval.response":
114
+ if (!clientId || typeof payload.requestId !== "string" || typeof payload.approved !== "boolean") return null;
115
+ return { type: "approval.response", clientId, requestId: payload.requestId, approved: payload.approved };
116
+ case "digest.request":
117
+ return clientId ? { type: "digest.request", clientId } : null;
118
+ case "error":
119
+ return {
120
+ type: "error",
121
+ code: typeof payload.code === "string" ? payload.code : "unknown",
122
+ message: typeof payload.message === "string" ? payload.message : "unknown error",
123
+ };
124
+ default:
125
+ return null;
126
+ }
127
+ }
128
+
129
+ function parseImages(raw: unknown): PromptImage[] | undefined {
130
+ if (!Array.isArray(raw) || raw.length === 0) return undefined;
131
+ const out: PromptImage[] = [];
132
+ for (const item of raw) {
133
+ if (!isRecord(item)) continue;
134
+ if (typeof item.mediaType === "string" && typeof item.data === "string" && item.data.length > 0) {
135
+ out.push({ mediaType: item.mediaType, data: item.data });
136
+ }
137
+ }
138
+ return out.length > 0 ? out : undefined;
139
+ }
@@ -0,0 +1,19 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { redactSecrets } from "./redact.js";
3
+
4
+ describe("redactSecrets", () => {
5
+ it("redacts API keys, bearer headers, and env assignments", () => {
6
+ const input = [
7
+ "PI_REMOTE_SERVER_TOKEN=mysecret123",
8
+ "Authorization: Bearer abcdefghijklmnopqrstuvwxyz12345",
9
+ "key sk-ant-api03-1234567890abcdef",
10
+ ].join("\n");
11
+ const out = redactSecrets(input);
12
+ expect(out).not.toContain("mysecret123");
13
+ expect(out).not.toContain("abcdefghijklmnopqrstuvwxyz12345");
14
+ expect(out).not.toContain("1234567890abcdef");
15
+ expect(out).toContain("PI_REMOTE_SERVER_TOKEN=[redacted]");
16
+ expect(out).toContain("Bearer [redacted]");
17
+ expect(out).toContain("[redacted:anthropic-key]");
18
+ });
19
+ });
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Secret redaction for outbound text leaving the local machine.
3
+ */
4
+
5
+ export interface RedactionRule {
6
+ readonly name: string;
7
+ readonly pattern: RegExp;
8
+ readonly replacement: string;
9
+ }
10
+
11
+ export const DEFAULT_REDACTION_RULES: readonly RedactionRule[] = [
12
+ {
13
+ name: "private-key",
14
+ pattern: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g,
15
+ replacement: "[redacted:private-key]",
16
+ },
17
+ { name: "anthropic-key", pattern: /\bsk-ant-[A-Za-z0-9_-]{16,}\b/g, replacement: "[redacted:anthropic-key]" },
18
+ { name: "openai-key", pattern: /\bsk-[A-Za-z0-9]{20,}\b/g, replacement: "[redacted:openai-key]" },
19
+ { name: "github-token", pattern: /\bgh[pousr]_[A-Za-z0-9]{16,}\b/g, replacement: "[redacted:github-token]" },
20
+ { name: "slack-bot-token", pattern: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g, replacement: "[redacted:slack-token]" },
21
+ { name: "npm-token", pattern: /\bnpm_[A-Za-z0-9]{36}\b/g, replacement: "[redacted:npm-token]" },
22
+ {
23
+ name: "jwt",
24
+ pattern: /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,
25
+ replacement: "[redacted:jwt]",
26
+ },
27
+ { name: "aws-access-key", pattern: /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g, replacement: "[redacted:aws-key]" },
28
+ { name: "google-api-key", pattern: /\bAIza[A-Za-z0-9_-]{35}\b/g, replacement: "[redacted:google-key]" },
29
+ {
30
+ name: "auth-header",
31
+ pattern: /\b(Authorization|X-Api-Key|X-Auth-Token|X-Access-Token)\s*:\s*(?!\s*Bearer\b)[^\n]*/gi,
32
+ replacement: "$1: [redacted]",
33
+ },
34
+ {
35
+ name: "bearer-header",
36
+ pattern: /\bBearer\s+[A-Za-z0-9._~+/-]{20,}=*/gi,
37
+ replacement: "Bearer [redacted]",
38
+ },
39
+ {
40
+ name: "env-secret-assignment",
41
+ pattern:
42
+ /\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|APIKEY|PRIVATE_KEY|ACCESS_KEY)[A-Z0-9_]*)\s*=\s*(?:"[^"\n]+"|'[^'\n]+'|[^\s"'\n]+)/g,
43
+ replacement: "$1=[redacted]",
44
+ },
45
+ ];
46
+
47
+ export function redactSecrets(input: string, rules: readonly RedactionRule[] = DEFAULT_REDACTION_RULES): string {
48
+ let text = input;
49
+ for (const rule of rules) {
50
+ rule.pattern.lastIndex = 0;
51
+ if (rule.pattern.test(text)) {
52
+ rule.pattern.lastIndex = 0;
53
+ text = text.replace(rule.pattern, rule.replacement);
54
+ }
55
+ }
56
+ return text;
57
+ }
@@ -0,0 +1,20 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { formatFooterLabel, formatStatusReport } from "./status.js";
3
+
4
+ describe("status", () => {
5
+ it("formats footer and status report without secrets", () => {
6
+ expect(formatFooterLabel("connected", 2)).toBe("remote: on (2)");
7
+ expect(formatFooterLabel("disconnected", 0)).toBe("remote: off");
8
+ const report = formatStatusReport({
9
+ status: "connected",
10
+ serverUrl: "ws://localhost:8787/ws/agent",
11
+ sessionId: "sess-1",
12
+ trustedClients: 1,
13
+ pendingPairings: 0,
14
+ remoteToolPolicy: "unrestricted",
15
+ remoteToolApproval: "web",
16
+ });
17
+ expect(report).toContain("pi-remote-control status: connected");
18
+ expect(report).toContain("toolPolicy: unrestricted (approval: web)");
19
+ });
20
+ });
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Pure status and doctor report renderers.
3
+ */
4
+
5
+ export type ConnectionStatus = "disconnected" | "connecting" | "connected" | "error";
6
+
7
+ export interface StatusSnapshot {
8
+ readonly status: ConnectionStatus;
9
+ readonly serverUrl: string;
10
+ readonly sessionId: string;
11
+ readonly trustedClients: number;
12
+ readonly pendingPairings: number;
13
+ readonly remoteToolPolicy: string;
14
+ readonly remoteToolApproval: string;
15
+ readonly lastError?: string;
16
+ }
17
+
18
+ export function formatFooterLabel(status: ConnectionStatus, trustedClients: number): string {
19
+ if (status === "connected") {
20
+ return trustedClients > 0 ? `remote: on (${trustedClients})` : "remote: on";
21
+ }
22
+ if (status === "connecting") return "remote: connecting";
23
+ if (status === "error") return "remote: error";
24
+ return "remote: off";
25
+ }
26
+
27
+ export function formatStatusReport(s: StatusSnapshot): string {
28
+ const lines = [
29
+ `pi-remote-control status: ${s.status}`,
30
+ `- server: ${s.serverUrl}`,
31
+ `- sessionId: ${s.sessionId}`,
32
+ `- trustedClients: ${s.trustedClients}`,
33
+ `- pendingPairings: ${s.pendingPairings}`,
34
+ `- toolPolicy: ${s.remoteToolPolicy} (approval: ${s.remoteToolApproval})`,
35
+ ];
36
+ if (s.lastError) lines.push(`- lastError: ${s.lastError}`);
37
+ return lines.join("\n");
38
+ }
@@ -0,0 +1,17 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { decideRemoteToolAccess, needsApproval } from "./tool-policy.js";
3
+
4
+ describe("tool-policy", () => {
5
+ it("enforces read-only and no-tools policies", () => {
6
+ expect(decideRemoteToolAccess("read-only", "read")).toBe("allow");
7
+ expect(decideRemoteToolAccess("read-only", "bash")).toBe("block");
8
+ expect(decideRemoteToolAccess("no-tools", "read")).toBe("block");
9
+ expect(decideRemoteToolAccess("unrestricted", "bash")).toBe("allow");
10
+ });
11
+
12
+ it("skips approval for read-only tools even when approval is enabled", () => {
13
+ expect(needsApproval("web", "read")).toBe(false);
14
+ expect(needsApproval("web", "bash")).toBe(true);
15
+ expect(needsApproval("off", "bash")).toBe(false);
16
+ });
17
+ });
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Remote-turn tool policy and approval rules.
3
+ */
4
+
5
+ export type RemoteToolPolicy = "unrestricted" | "read-only" | "no-tools";
6
+ export type RemoteToolApproval = "off" | "local" | "web";
7
+
8
+ export const READ_ONLY_TOOLS: readonly string[] = ["read", "grep", "find", "ls"];
9
+
10
+ export function decideRemoteToolAccess(policy: RemoteToolPolicy, toolName: string): "allow" | "block" {
11
+ if (policy === "unrestricted") return "allow";
12
+ if (policy === "no-tools") return "block";
13
+ return READ_ONLY_TOOLS.includes(toolName) ? "allow" : "block";
14
+ }
15
+
16
+ export function needsApproval(approval: RemoteToolApproval, toolName: string): boolean {
17
+ if (approval === "off") return false;
18
+ return !READ_ONLY_TOOLS.includes(toolName);
19
+ }
20
+
21
+ export function remoteToolBlockReason(policy: RemoteToolPolicy, toolName: string): string {
22
+ if (policy === "no-tools") {
23
+ return `Tool '${toolName}' is blocked for remote turns (no-tools policy).`;
24
+ }
25
+ return `Tool '${toolName}' is blocked for remote turns (read-only policy).`;
26
+ }
27
+
28
+ export function remoteToolDeclinedReason(toolName: string): string {
29
+ return `Remote tool '${toolName}' was declined or timed out.`;
30
+ }
@@ -0,0 +1,29 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
+ import remoteControlExtension from "./index.js";
4
+
5
+ describe("remoteControlExtension wiring", () => {
6
+ it("registers /remote command and lifecycle handlers without opening sockets at load time", async () => {
7
+ const commands: string[] = [];
8
+ const events: string[] = [];
9
+ const fakePi = {
10
+ registerCommand(name: string) {
11
+ commands.push(name);
12
+ },
13
+ on(event: string) {
14
+ events.push(event);
15
+ },
16
+ exec: vi.fn(),
17
+ sendUserMessage: vi.fn(),
18
+ getSessionName: () => "test",
19
+ } as unknown as ExtensionAPI;
20
+
21
+ await remoteControlExtension(fakePi);
22
+ expect(commands).toEqual(["remote"]);
23
+ expect(events).toContain("session_start");
24
+ expect(events).toContain("session_shutdown");
25
+ expect(events).toContain("message_update");
26
+ expect(events).toContain("tool_call");
27
+ expect(events).toContain("agent_settled");
28
+ });
29
+ });
package/src/index.ts ADDED
@@ -0,0 +1,316 @@
1
+ /**
2
+ * pi extension entry point for pi-remote-control.
3
+ * Thin adapter binding pi ExtensionAPI events to WsClient + RemoteBridge.
4
+ */
5
+
6
+ import { readFile } from "node:fs/promises";
7
+ import { homedir, hostname } from "node:os";
8
+ import { join } from "node:path";
9
+ import { CONFIG_DIR_NAME, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
10
+ import { RemoteBridge, type RemoteHost } from "./client/remote-bridge.js";
11
+ import { WsClient } from "./client/ws-client.js";
12
+ import { parseRemoteConfig, resolveRemoteConfig, type RemoteControlConfig } from "./config.js";
13
+ import { buildWorkDigest, parseGitBranch, parseGitNumstat } from "./core/digest.js";
14
+ import { buildHistorySnapshot, type RawSessionEntry } from "./core/history.js";
15
+ import { formatFooterLabel, formatStatusReport } from "./core/status.js";
16
+ import {
17
+ decideRemoteToolAccess,
18
+ needsApproval,
19
+ remoteToolBlockReason,
20
+ remoteToolDeclinedReason,
21
+ } from "./core/tool-policy.js";
22
+
23
+ const EXTENSION_KEY = "remote-control";
24
+
25
+ async function loadExtensionConfig(cwd: string): Promise<{ config: RemoteControlConfig; warnings: string[] }> {
26
+ const warnings: string[] = [];
27
+ let merged: Partial<RemoteControlConfig> = {};
28
+
29
+ const override = process.env.PI_REMOTE_CONFIG?.trim();
30
+ const paths = override
31
+ ? [override]
32
+ : [
33
+ join(homedir(), CONFIG_DIR_NAME, "agent", "remote-control.json"),
34
+ join(cwd, CONFIG_DIR_NAME, "remote-control.json"),
35
+ ];
36
+
37
+ for (const path of paths) {
38
+ try {
39
+ const raw = await readFile(path, "utf8");
40
+ const parsed = parseRemoteConfig(JSON.parse(raw) as unknown);
41
+ warnings.push(...parsed.warnings);
42
+ merged = { ...merged, ...parsed.config };
43
+ } catch (error) {
44
+ const code = (error as NodeJS.ErrnoException).code;
45
+ if (code !== "ENOENT") {
46
+ warnings.push(`config error (${path}): ${error instanceof Error ? error.message : String(error)}`);
47
+ }
48
+ }
49
+ }
50
+
51
+ return { config: resolveRemoteConfig(merged), warnings };
52
+ }
53
+
54
+ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<void> {
55
+ let sessionCtx: ExtensionContext | null = null;
56
+ let wsClient: WsClient | null = null;
57
+ let bridge: RemoteBridge | null = null;
58
+ let remoteTurn = false;
59
+ let lastPrompt = "";
60
+ let lastReply = "";
61
+ let lastShellSummary: string | undefined;
62
+ let currentBranch: string | undefined;
63
+ const toolStartTimes = new Map<string, number>();
64
+
65
+ async function runGit(cwd: string, args: readonly string[]): Promise<string | null> {
66
+ try {
67
+ const res = await pi.exec("git", ["-C", cwd, ...args], { timeout: 5_000 });
68
+ return res.code === 0 ? res.stdout : null;
69
+ } catch {
70
+ return null;
71
+ }
72
+ }
73
+
74
+ async function refreshBranch(cwd: string): Promise<string | undefined> {
75
+ const out = await runGit(cwd, ["rev-parse", "--abbrev-ref", "HEAD"]);
76
+ currentBranch = out ? parseGitBranch(out) : undefined;
77
+ return currentBranch;
78
+ }
79
+
80
+ function getSessionId(ctx: ExtensionContext): string {
81
+ try {
82
+ const id = ctx.sessionManager.getSessionId();
83
+ if (id) return id;
84
+ } catch {
85
+ // Fall back to ephemeral id.
86
+ }
87
+ return `ephemeral-${process.pid}`;
88
+ }
89
+
90
+ pi.registerCommand("remote", {
91
+ description: "Control pi-remote-control relay connection (status, disconnect, digest, help)",
92
+ handler: async (args, ctx) => {
93
+ const sub = args.trim().split(/\s+/)[0] || "status";
94
+ if (sub === "status" || sub === "doctor") {
95
+ if (!bridge) {
96
+ ctx.ui.notify("remote-control: not initialized.", "warning");
97
+ return;
98
+ }
99
+ ctx.ui.notify(formatStatusReport(bridge.statusSnapshot()), "info");
100
+ return;
101
+ }
102
+ if (sub === "disconnect") {
103
+ const count = bridge?.disconnectAll() ?? 0;
104
+ ctx.ui.notify(`remote-control: revoked ${count} paired client(s).`, "info");
105
+ return;
106
+ }
107
+ if (sub === "digest") {
108
+ await bridge?.emitDigest();
109
+ ctx.ui.notify("remote-control: digest pushed.", "info");
110
+ return;
111
+ }
112
+ ctx.ui.notify("Usage: /remote [status|doctor|digest|disconnect]", "info");
113
+ },
114
+ });
115
+
116
+ pi.on("session_start", async (_event, ctx) => {
117
+ sessionCtx = ctx;
118
+ const { config, warnings } = await loadExtensionConfig(ctx.cwd);
119
+ await refreshBranch(ctx.cwd);
120
+ const serverToken = process.env[config.tokenEnv]?.trim() ?? "";
121
+
122
+ const host: RemoteHost = {
123
+ sessionId: getSessionId(ctx),
124
+ get sessionName() {
125
+ return pi.getSessionName();
126
+ },
127
+ host: hostname(),
128
+ cwd: ctx.cwd,
129
+ get branch() {
130
+ return currentBranch;
131
+ },
132
+ get model() {
133
+ return ctx.model?.id;
134
+ },
135
+ isIdle: () => (sessionCtx ? sessionCtx.isIdle() : true),
136
+ sendPrompt(text, options) {
137
+ const content =
138
+ options?.images && options.images.length > 0
139
+ ? [
140
+ { type: "text" as const, text },
141
+ ...options.images.map((img) => ({
142
+ type: "image" as const,
143
+ data: img.data,
144
+ mimeType: img.mediaType,
145
+ })),
146
+ ]
147
+ : text;
148
+ try {
149
+ if (options?.deliverAs) {
150
+ pi.sendUserMessage(content, { deliverAs: options.deliverAs });
151
+ } else if (sessionCtx && !sessionCtx.isIdle()) {
152
+ pi.sendUserMessage(content, { deliverAs: "followUp" });
153
+ } else {
154
+ pi.sendUserMessage(content);
155
+ }
156
+ } catch (error) {
157
+ ctx.ui.notify(
158
+ `[remote] failed to inject prompt: ${error instanceof Error ? error.message : String(error)}`,
159
+ "error",
160
+ );
161
+ }
162
+ },
163
+ abort: () => sessionCtx?.abort(),
164
+ notify: (text, level) => sessionCtx?.ui.notify(text, level ?? "info"),
165
+ onStateChanged: (status, trusted) => {
166
+ sessionCtx?.ui.setStatus(EXTENSION_KEY, formatFooterLabel(status, trusted));
167
+ },
168
+ getHistory: () => {
169
+ try {
170
+ const entries = ctx.sessionManager.getEntries() as unknown as RawSessionEntry[];
171
+ return buildHistorySnapshot(entries);
172
+ } catch {
173
+ return [];
174
+ }
175
+ },
176
+ getDigest: async () => {
177
+ const branch = await refreshBranch(ctx.cwd);
178
+ const numstat = await runGit(ctx.cwd, ["diff", "--numstat", "HEAD"]);
179
+ const changes = numstat ? parseGitNumstat(numstat) : undefined;
180
+ return buildWorkDigest({
181
+ sessionName: pi.getSessionName(),
182
+ cwd: ctx.cwd,
183
+ branch,
184
+ state: ctx.isIdle() ? "idle" : "busy",
185
+ changes,
186
+ testSummary: lastShellSummary,
187
+ lastPrompt,
188
+ lastReply,
189
+ });
190
+ },
191
+ now: () => Date.now(),
192
+ random: () => Math.random(),
193
+ };
194
+
195
+ wsClient = new WsClient({
196
+ serverUrl: config.serverUrl,
197
+ reconnectBaseMs: config.reconnectBaseMs,
198
+ reconnectMaxMs: config.reconnectMaxMs,
199
+ getHello: () => ({
200
+ serverToken,
201
+ sessionId: host.sessionId,
202
+ ...(host.sessionName ? { sessionName: host.sessionName } : {}),
203
+ host: host.host,
204
+ cwd: host.cwd,
205
+ ...(host.branch ? { branch: host.branch } : {}),
206
+ ...(host.model ? { model: host.model } : {}),
207
+ state: host.isIdle() ? "idle" : "busy",
208
+ requirePairing: config.requirePairing,
209
+ }),
210
+ onMessage: (msg) => {
211
+ void bridge?.handleServerMessage(msg);
212
+ },
213
+ onStatusChange: (status, detail) => {
214
+ bridge?.onConnectionStatus(status, detail);
215
+ },
216
+ });
217
+
218
+ bridge = new RemoteBridge({ config, host, sink: wsClient });
219
+ wsClient.start();
220
+ ctx.ui.setStatus(EXTENSION_KEY, formatFooterLabel(wsClient.currentStatus, 0));
221
+
222
+ if (warnings.length > 0) {
223
+ ctx.ui.notify(`[remote] ${warnings.join("; ")}`, "warning");
224
+ }
225
+ });
226
+
227
+ pi.on("session_shutdown", async () => {
228
+ bridge?.stop();
229
+ wsClient?.stop();
230
+ bridge = null;
231
+ wsClient = null;
232
+ sessionCtx = null;
233
+ remoteTurn = false;
234
+ toolStartTimes.clear();
235
+ });
236
+
237
+ pi.on("input", async (event) => {
238
+ remoteTurn = event.source === "extension";
239
+ });
240
+
241
+ pi.on("before_agent_start", async (event, ctx) => {
242
+ sessionCtx = ctx;
243
+ lastPrompt = event.prompt;
244
+ });
245
+
246
+ pi.on("agent_start", async (_event, ctx) => {
247
+ sessionCtx = ctx;
248
+ lastReply = "";
249
+ bridge?.emitSessionState();
250
+ bridge?.emitStreamStart();
251
+ });
252
+
253
+ pi.on("message_update", async (event) => {
254
+ const ev = event.assistantMessageEvent;
255
+ if (ev.type === "text_delta") {
256
+ bridge?.emitStreamDelta("text", ev.delta);
257
+ } else if (ev.type === "thinking_delta") {
258
+ bridge?.emitStreamDelta("thinking", ev.delta);
259
+ }
260
+ });
261
+
262
+ pi.on("message_end", async (event) => {
263
+ if (event.message.role !== "assistant") return;
264
+ const content = event.message.content;
265
+ if (Array.isArray(content)) {
266
+ const text = content
267
+ .filter((p): p is { type: "text"; text: string } => p.type === "text" && typeof p.text === "string")
268
+ .map((p) => p.text)
269
+ .join("\n");
270
+ if (text) lastReply = text;
271
+ }
272
+ });
273
+
274
+ pi.on("tool_execution_start", async (event, ctx) => {
275
+ sessionCtx = ctx;
276
+ toolStartTimes.set(event.toolCallId, Date.now());
277
+ bridge?.emitSessionState(event.toolName);
278
+ bridge?.emitToolStart(event.toolCallId, event.toolName);
279
+ });
280
+
281
+ pi.on("tool_execution_end", async (event, ctx) => {
282
+ sessionCtx = ctx;
283
+ const startedAt = toolStartTimes.get(event.toolCallId) ?? Date.now();
284
+ toolStartTimes.delete(event.toolCallId);
285
+ if (event.toolName === "bash") {
286
+ lastShellSummary = event.isError ? "bash failed" : "bash ok";
287
+ }
288
+ bridge?.emitToolEnd(event.toolCallId, event.toolName, event.isError === true, Date.now() - startedAt);
289
+ bridge?.emitSessionState();
290
+ });
291
+
292
+ pi.on("tool_call", async (event, ctx) => {
293
+ if (!remoteTurn || !bridge) return undefined;
294
+ const { remoteToolPolicy, remoteToolApproval } = bridge.config;
295
+ if (decideRemoteToolAccess(remoteToolPolicy, event.toolName) === "block") {
296
+ return { block: true, reason: remoteToolBlockReason(remoteToolPolicy, event.toolName) };
297
+ }
298
+ if (!needsApproval(remoteToolApproval, event.toolName)) return undefined;
299
+
300
+ let approved = false;
301
+ if (remoteToolApproval === "web") {
302
+ approved = await bridge.requestWebApproval(event.toolCallId, event.toolName);
303
+ } else if (remoteToolApproval === "local") {
304
+ approved = await ctx.ui.confirm("Remote tool call", `Allow '${event.toolName}' on remote turn?`);
305
+ }
306
+ if (approved) return undefined;
307
+ return { block: true, reason: remoteToolDeclinedReason(event.toolName) };
308
+ });
309
+
310
+ pi.on("agent_settled", async (_event, ctx) => {
311
+ sessionCtx = ctx;
312
+ remoteTurn = false;
313
+ bridge?.emitStreamEnd(lastReply);
314
+ bridge?.emitSessionState();
315
+ });
316
+ }