@wkqco33/pi-remote-control 0.4.0 → 0.4.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wkqco33/pi-remote-control",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
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",
@@ -37,11 +37,19 @@ export class PromptRouter {
37
37
  await this.runBuiltin(clientId, route.name, route.args, Boolean(images?.length));
38
38
  return;
39
39
  }
40
- const validImages = this.acceptImages(images);
40
+ const { accepted, dropped } = this.acceptImages(images);
41
+ if (dropped > 0) {
42
+ const msg = `Excluded ${dropped} image(s) exceeding limits (max ${this.options.config.maxImages} images, ${Math.round(this.options.config.maxImageBytes / (1024 * 1024))}MB each).`;
43
+ if (!route.text.trim() && accepted.length === 0) {
44
+ this.emitResult("image", { ok: false, message: msg });
45
+ return;
46
+ }
47
+ this.emitResult("image", { ok: true, message: msg });
48
+ }
41
49
  host.sendPrompt(route.text, {
42
50
  ...(route.kind === "expand" ? { expandPromptTemplates: true } : {}),
43
51
  ...(deliverAs ? { deliverAs } : {}),
44
- ...(validImages.length > 0 ? { images: validImages } : {}),
52
+ ...(accepted.length > 0 ? { images: accepted } : {}),
45
53
  });
46
54
  }
47
55
 
@@ -90,9 +98,10 @@ export class PromptRouter {
90
98
  }
91
99
  }
92
100
 
93
- private acceptImages(images: readonly PromptImage[] = []): PromptImage[] {
101
+ private acceptImages(images: readonly PromptImage[] = []): { accepted: PromptImage[]; dropped: number } {
94
102
  const { maxImages, maxImageBytes } = this.options.config;
95
- return images.slice(0, maxImages).filter((image) => Math.ceil((image.data.length * 3) / 4) <= maxImageBytes);
103
+ const accepted = images.slice(0, maxImages).filter((image) => Math.ceil((image.data.length * 3) / 4) <= maxImageBytes);
104
+ return { accepted, dropped: images.length - accepted.length };
96
105
  }
97
106
 
98
107
  private emitResult(command: string, result: CommandResult): void {
@@ -5,6 +5,7 @@
5
5
 
6
6
  import type { RemoteControlConfig } from "../config.js";
7
7
  import type { CommandInfo } from "../core/commands.js";
8
+ import { formatError, type DiagnosticLogger } from "../core/logger.js";
8
9
  import { createChallenge, formatChallengeCode, verifyChallenge, type PendingChallenge } from "../core/pairing.js";
9
10
  import type { DeliverMode, HistoryItem, PromptImage, ServerInboundMessage, WireEnvelope } from "../core/protocol.js";
10
11
  import { redactSecrets } from "../core/redact.js";
@@ -73,12 +74,14 @@ export class RemoteBridge {
73
74
  private runningTool?: string;
74
75
  private pendingDelta?: PendingDelta;
75
76
  private readonly prompts: PromptRouter;
77
+ private readonly logger?: DiagnosticLogger;
76
78
  private lastError?: string;
77
79
 
78
- constructor(options: { config: RemoteControlConfig; host: RemoteHost; sink: TransportSink }) {
80
+ constructor(options: { config: RemoteControlConfig; host: RemoteHost; sink: TransportSink; logger?: DiagnosticLogger }) {
79
81
  this.config = options.config;
80
82
  this.host = options.host;
81
83
  this.sink = options.sink;
84
+ this.logger = options.logger;
82
85
  this.prompts = new PromptRouter({
83
86
  config: this.config,
84
87
  host: this.host,
@@ -105,7 +108,7 @@ export class RemoteBridge {
105
108
  }
106
109
 
107
110
  onConnectionStatus(status: ConnectionStatus, detail?: string): void {
108
- if (status === "error" && detail) {
111
+ if ((status === "error" || status === "disconnected") && detail) {
109
112
  this.lastError = detail;
110
113
  } else if (status === "connected") {
111
114
  this.lastError = undefined;
@@ -151,6 +154,16 @@ export class RemoteBridge {
151
154
  }
152
155
 
153
156
  async handleServerMessage(msg: ServerInboundMessage): Promise<void> {
157
+ try {
158
+ await this.dispatchServerMessage(msg);
159
+ } catch (error) {
160
+ const detail = formatError(error);
161
+ this.logger?.error(`failed to handle ${msg.type}`, detail);
162
+ this.host.notify(`[remote] failed to handle ${msg.type}: ${detail}`, "error");
163
+ }
164
+ }
165
+
166
+ private async dispatchServerMessage(msg: ServerInboundMessage): Promise<void> {
154
167
  switch (msg.type) {
155
168
  case "history.request": {
156
169
  const { clientId } = msg;
@@ -266,7 +279,11 @@ export class RemoteBridge {
266
279
  /** Every other frame goes out after the buffered text so the order is preserved. */
267
280
  private send(envelope: WireEnvelope): boolean {
268
281
  this.flushDeltas();
269
- return this.sink.send(envelope);
282
+ const ok = this.sink.send(envelope);
283
+ if (!ok) {
284
+ this.logger?.warn("dropped outbound frame", envelope.type);
285
+ }
286
+ return ok;
270
287
  }
271
288
 
272
289
  emitStreamEnd(text: string): void {
@@ -297,13 +314,19 @@ export class RemoteBridge {
297
314
  }
298
315
 
299
316
  async emitDigest(): Promise<void> {
300
- const markdown = await this.host.getDigest();
301
- this.send({
302
- type: "digest.snapshot",
303
- sessionId: this.host.sessionId,
304
- ts: this.host.now(),
305
- payload: { markdown: redactSecrets(markdown) },
306
- });
317
+ try {
318
+ const markdown = await this.host.getDigest();
319
+ this.send({
320
+ type: "digest.snapshot",
321
+ sessionId: this.host.sessionId,
322
+ ts: this.host.now(),
323
+ payload: { markdown: redactSecrets(markdown) },
324
+ });
325
+ } catch (error) {
326
+ const detail = formatError(error);
327
+ this.logger?.error("failed to build work digest", detail);
328
+ this.host.notify(`[remote] failed to build digest: ${detail}`, "error");
329
+ }
307
330
  }
308
331
 
309
332
  requestWebApproval(toolCallId: string, toolName: string): Promise<ApprovalOutcome> {
@@ -6,7 +6,7 @@ class FakeWebSocket implements WebSocketLike {
6
6
  sent: string[] = [];
7
7
  private listeners = new Map<string, Array<(ev: unknown) => void>>();
8
8
 
9
- addEventListener(type: string, listener: (ev: { data: unknown }) => void): void {
9
+ addEventListener(type: string, listener: (...args: never[]) => void): void {
10
10
  const list = this.listeners.get(type) ?? [];
11
11
  list.push(listener as (ev: unknown) => void);
12
12
  this.listeners.set(type, list);
@@ -3,6 +3,7 @@
3
3
  * Uses Node 22+ built-in WebSocket (zero runtime npm dependencies).
4
4
  */
5
5
 
6
+ import { formatError, type DiagnosticLogger } from "../core/logger.js";
6
7
  import { PROTOCOL_VERSION, parseServerEnvelope, type AgentState, type ServerInboundMessage, type WireEnvelope } from "../core/protocol.js";
7
8
  import type { ConnectionStatus } from "../core/status.js";
8
9
 
@@ -12,7 +13,7 @@ export interface WebSocketLike {
12
13
  close(code?: number, reason?: string): void;
13
14
  addEventListener(type: "open", listener: () => void): void;
14
15
  addEventListener(type: "message", listener: (event: { data: unknown }) => void): void;
15
- addEventListener(type: "close", listener: () => void): void;
16
+ addEventListener(type: "close", listener: (event?: { code?: number; reason?: string }) => void): void;
16
17
  addEventListener(type: "error", listener: (event: unknown) => void): void;
17
18
  }
18
19
 
@@ -40,6 +41,7 @@ export interface WsClientOptions {
40
41
  readonly onMessage: (msg: ServerInboundMessage) => void;
41
42
  readonly onStatusChange?: (status: ConnectionStatus, detail?: string) => void;
42
43
  readonly createWebSocket?: WebSocketFactory;
44
+ readonly logger?: DiagnosticLogger;
43
45
  }
44
46
 
45
47
  const WS_OPEN = 1;
@@ -96,11 +98,15 @@ export class WsClient {
96
98
  }
97
99
 
98
100
  send(envelope: WireEnvelope): boolean {
99
- if (this.ws === null || this.ws.readyState !== WS_OPEN) return false;
101
+ if (this.ws === null || this.ws.readyState !== WS_OPEN) {
102
+ this.opts.logger?.debug("websocket send skipped: socket not open", envelope.type);
103
+ return false;
104
+ }
100
105
  try {
101
106
  this.ws.send(JSON.stringify(envelope));
102
107
  return true;
103
- } catch {
108
+ } catch (error) {
109
+ this.opts.logger?.warn("websocket send failed", `${envelope.type}: ${formatError(error)}`);
104
110
  return false;
105
111
  }
106
112
  }
@@ -118,7 +124,9 @@ export class WsClient {
118
124
  try {
119
125
  sock = this.createWS(this.opts.serverUrl);
120
126
  } catch (error) {
121
- this.setStatus("error", error instanceof Error ? error.message : String(error));
127
+ const msg = formatError(error);
128
+ this.opts.logger?.error("failed to create websocket", msg);
129
+ this.setStatus("error", msg);
122
130
  this.scheduleReconnect();
123
131
  return;
124
132
  }
@@ -127,6 +135,7 @@ export class WsClient {
127
135
  sock.addEventListener("open", () => {
128
136
  if (this.ws !== sock || this.stopped) return;
129
137
  this.attempt = 0;
138
+ this.opts.logger?.info("websocket connected", this.opts.serverUrl);
130
139
  const hello = this.opts.getHello();
131
140
  this.send({
132
141
  type: "agent.hello",
@@ -144,31 +153,42 @@ export class WsClient {
144
153
  if (this.ws !== sock || this.stopped) return;
145
154
  const raw = typeof event.data === "string" ? event.data : String(event.data ?? "");
146
155
  const parsed = parseServerEnvelope(raw);
147
- if (!parsed) return;
156
+ if (!parsed) {
157
+ this.opts.logger?.warn("ignored malformed server message", raw.slice(0, 120));
158
+ return;
159
+ }
148
160
  if (parsed.type === "ping") {
149
161
  this.send({ type: "pong", sessionId: this.opts.getHello().sessionId, ts: Date.now() });
150
162
  return;
151
163
  }
152
164
  if (parsed.type === "error") {
165
+ this.opts.logger?.warn("relay error frame", `${parsed.code}: ${parsed.message}`);
153
166
  this.setStatus("error", parsed.message);
154
167
  }
155
168
  this.opts.onMessage(parsed);
156
169
  });
157
170
 
158
- sock.addEventListener("close", () => {
171
+ sock.addEventListener("close", (event) => {
159
172
  if (this.ws !== sock) return;
160
173
  this.ws = null;
174
+ const code = typeof event?.code === "number" ? event.code : undefined;
175
+ const reason = typeof event?.reason === "string" && event.reason ? event.reason : undefined;
176
+ const detail = code !== undefined ? `code=${code}${reason ? ` reason=${reason}` : ""}` : undefined;
161
177
  if (this.stopped) {
178
+ this.opts.logger?.info("websocket closed", detail);
162
179
  this.setStatus("disconnected");
163
180
  return;
164
181
  }
165
- this.setStatus("disconnected");
182
+ this.opts.logger?.warn("websocket disconnected unexpectedly", detail);
183
+ this.setStatus("disconnected", detail);
166
184
  this.scheduleReconnect();
167
185
  });
168
186
 
169
- sock.addEventListener("error", () => {
187
+ sock.addEventListener("error", (event) => {
170
188
  if (this.ws !== sock || this.stopped) return;
171
- this.setStatus("error", "websocket connection error");
189
+ const detail = extractWSErrorDetail(event);
190
+ this.opts.logger?.error("websocket error", detail);
191
+ this.setStatus("error", detail);
172
192
  });
173
193
  }
174
194
 
@@ -176,6 +196,7 @@ export class WsClient {
176
196
  if (this.stopped || this.reconnectTimer !== null) return;
177
197
  const exp = Math.min(this.opts.reconnectMaxMs, this.opts.reconnectBaseMs * 2 ** this.attempt);
178
198
  this.attempt += 1;
199
+ this.opts.logger?.debug("scheduling websocket reconnect", `attempt=${this.attempt} delayMs=${exp}`);
179
200
  this.reconnectTimer = setTimeout(() => {
180
201
  this.reconnectTimer = null;
181
202
  this.connect();
@@ -185,3 +206,12 @@ export class WsClient {
185
206
  }
186
207
  }
187
208
  }
209
+
210
+ function extractWSErrorDetail(event: unknown): string {
211
+ if (event && typeof event === "object") {
212
+ const rec = event as { message?: unknown; error?: unknown };
213
+ if (rec.error instanceof Error && rec.error.message) return rec.error.message;
214
+ if (typeof rec.message === "string" && rec.message) return rec.message;
215
+ }
216
+ return "websocket connection error";
217
+ }
@@ -0,0 +1,27 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { RingLogger, formatLogEntries } from "./logger.js";
3
+
4
+ describe("RingLogger", () => {
5
+ it("bounds entries to capacity and redacts secrets", () => {
6
+ let now = 1_700_000_000_000;
7
+ const logger = new RingLogger({ capacity: 2, now: () => now++ });
8
+
9
+ logger.info("first", "sk-1234567890abcdefghijklmnop");
10
+ logger.warn("second");
11
+ logger.error("third", "Bearer secret-token-value-1234567890");
12
+
13
+ expect(logger.size).toBe(2);
14
+ const recent = logger.recent(10);
15
+ expect(recent.map((e) => e.message)).toEqual(["second", "third"]);
16
+ expect(recent[1]?.detail).toBe("Bearer [redacted]");
17
+ });
18
+
19
+ it("formats empty and populated log lists", () => {
20
+ const logger = new RingLogger();
21
+ expect(formatLogEntries(logger.recent())).toContain("no diagnostic logs");
22
+
23
+ logger.info("connected", "ws://127.0.0.1:8787");
24
+ const text = formatLogEntries(logger.recent());
25
+ expect(text).toContain("[INFO] connected (ws://127.0.0.1:8787)");
26
+ });
27
+ });
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Lightweight in-memory ring-buffer diagnostic logger with secret redaction.
3
+ */
4
+
5
+ import { redactSecrets } from "./redact.js";
6
+
7
+ export type LogLevel = "debug" | "info" | "warn" | "error";
8
+
9
+ export interface LogEntry {
10
+ readonly ts: number;
11
+ readonly level: LogLevel;
12
+ readonly message: string;
13
+ readonly detail?: string;
14
+ }
15
+
16
+ export interface DiagnosticLogger {
17
+ debug(message: string, detail?: string): void;
18
+ info(message: string, detail?: string): void;
19
+ warn(message: string, detail?: string): void;
20
+ error(message: string, detail?: string): void;
21
+ }
22
+
23
+ export class RingLogger implements DiagnosticLogger {
24
+ private readonly capacity: number;
25
+ private readonly now: () => number;
26
+ private readonly entries: LogEntry[] = [];
27
+
28
+ constructor(options: { capacity?: number; now?: () => number } = {}) {
29
+ this.capacity = Math.max(1, options.capacity ?? 200);
30
+ this.now = options.now ?? (() => Date.now());
31
+ }
32
+
33
+ log(level: LogLevel, message: string, detail?: string): void {
34
+ const entry: LogEntry = {
35
+ ts: this.now(),
36
+ level,
37
+ message: redactSecrets(message),
38
+ ...(detail !== undefined && detail !== "" ? { detail: redactSecrets(detail) } : {}),
39
+ };
40
+ if (this.entries.length >= this.capacity) {
41
+ this.entries.shift();
42
+ }
43
+ this.entries.push(entry);
44
+ }
45
+
46
+ debug(message: string, detail?: string): void {
47
+ this.log("debug", message, detail);
48
+ }
49
+
50
+ info(message: string, detail?: string): void {
51
+ this.log("info", message, detail);
52
+ }
53
+
54
+ warn(message: string, detail?: string): void {
55
+ this.log("warn", message, detail);
56
+ }
57
+
58
+ error(message: string, detail?: string): void {
59
+ this.log("error", message, detail);
60
+ }
61
+
62
+ recent(limit = 30): LogEntry[] {
63
+ if (limit <= 0) return [];
64
+ return this.entries.slice(-limit);
65
+ }
66
+
67
+ get size(): number {
68
+ return this.entries.length;
69
+ }
70
+ }
71
+
72
+ export function formatError(error: unknown): string {
73
+ return error instanceof Error ? error.message : String(error);
74
+ }
75
+
76
+ export function formatLogEntries(entries: readonly LogEntry[]): string {
77
+ if (entries.length === 0) {
78
+ return "remote-control: no diagnostic logs recorded.";
79
+ }
80
+ return entries
81
+ .map((entry) => {
82
+ const iso = new Date(entry.ts).toISOString().slice(11, 23);
83
+ const base = `${iso} [${entry.level.toUpperCase()}] ${entry.message}`;
84
+ return entry.detail ? `${base} (${entry.detail})` : base;
85
+ })
86
+ .join("\n");
87
+ }
package/src/index.ts CHANGED
@@ -17,6 +17,7 @@ import {
17
17
  import { loadExtensionConfig } from "./config-loader.js";
18
18
  import { buildWorkDigest, parseGitBranch, parseGitNumstat } from "./core/digest.js";
19
19
  import { buildHistorySnapshot, type RawSessionEntry } from "./core/history.js";
20
+ import { formatError, formatLogEntries, RingLogger } from "./core/logger.js";
20
21
  import { formatFooterLabel, formatStatusReport } from "./core/status.js";
21
22
  import {
22
23
  decideRemoteToolAccess,
@@ -72,6 +73,7 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
72
73
  let sessionCtx: ExtensionContext | null = null;
73
74
  let wsClient: WsClient | null = null;
74
75
  let bridge: RemoteBridge | null = null;
76
+ const logger = new RingLogger({ capacity: 200 });
75
77
  let remoteTurn = false;
76
78
  let lastPrompt = "";
77
79
  let lastReply = "";
@@ -105,7 +107,7 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
105
107
  }
106
108
 
107
109
  pi.registerCommand("remote", {
108
- description: "Control pi-remote-control relay connection (status, disconnect, digest, auto, help)",
110
+ description: "Control pi-remote-control relay connection (status, logs, disconnect, digest, auto, help)",
109
111
  handler: async (args, ctx) => {
110
112
  const [sub = "status", value] = args.trim().split(/\s+/).filter(Boolean);
111
113
  if (sub === "status" || sub === "doctor") {
@@ -116,6 +118,12 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
116
118
  ctx.ui.notify(formatStatusReport(bridge.statusSnapshot()), "info");
117
119
  return;
118
120
  }
121
+ if (sub === "logs") {
122
+ const count = value ? Number.parseInt(value, 10) : 25;
123
+ const limit = Number.isFinite(count) && count > 0 ? count : 25;
124
+ ctx.ui.notify(formatLogEntries(logger.recent(limit)), "info");
125
+ return;
126
+ }
119
127
  if (sub === "disconnect") {
120
128
  const count = bridge?.disconnectAll() ?? 0;
121
129
  ctx.ui.notify(`remote-control: revoked ${count} paired client(s).`, "info");
@@ -134,7 +142,7 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
134
142
  bridge.setAutoApprove(value === "on", "local terminal");
135
143
  return;
136
144
  }
137
- ctx.ui.notify("Usage: /remote [status|doctor|digest|disconnect|auto on|auto off]", "info");
145
+ ctx.ui.notify("Usage: /remote [status|doctor|logs [n]|digest|disconnect|auto on|auto off]", "info");
138
146
  },
139
147
  });
140
148
 
@@ -235,7 +243,8 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
235
243
  try {
236
244
  const entries = ctx.sessionManager.getEntries() as unknown as RawSessionEntry[];
237
245
  return buildHistorySnapshot(entries, { busy: !ctx.isIdle() });
238
- } catch {
246
+ } catch (error) {
247
+ logger.warn("failed to read session history", formatError(error));
239
248
  return [];
240
249
  }
241
250
  },
@@ -262,6 +271,7 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
262
271
  serverUrl: config.serverUrl,
263
272
  reconnectBaseMs: config.reconnectBaseMs,
264
273
  reconnectMaxMs: config.reconnectMaxMs,
274
+ logger,
265
275
  getHello: () => ({
266
276
  serverToken,
267
277
  sessionId: host.sessionId,
@@ -276,18 +286,23 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
276
286
  ...(EXTENSION_VERSION ? { extensionVersion: EXTENSION_VERSION } : {}),
277
287
  }),
278
288
  onMessage: (msg) => {
279
- void bridge?.handleServerMessage(msg);
289
+ void bridge?.handleServerMessage(msg).catch((error) => {
290
+ const detail = formatError(error);
291
+ logger.error("unhandled server message error", detail);
292
+ ctx.ui.notify(`[remote] internal error: ${detail}`, "error");
293
+ });
280
294
  },
281
295
  onStatusChange: (status, detail) => {
282
296
  bridge?.onConnectionStatus(status, detail);
283
297
  },
284
298
  });
285
299
 
286
- bridge = new RemoteBridge({ config, host, sink: wsClient });
300
+ bridge = new RemoteBridge({ config, host, sink: wsClient, logger });
287
301
  wsClient.start();
288
302
  ctx.ui.setStatus(EXTENSION_KEY, formatFooterLabel(wsClient.currentStatus, 0));
289
303
 
290
304
  if (warnings.length > 0) {
305
+ for (const w of warnings) logger.warn("config warning", w);
291
306
  ctx.ui.notify(`[remote] ${warnings.join("; ")}`, "warning");
292
307
  }
293
308
  });