@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,185 @@
1
+ /**
2
+ * Outbound WebSocket client for pi-remote-control.
3
+ * Uses Node 22+ built-in WebSocket (zero runtime npm dependencies).
4
+ */
5
+
6
+ import { PROTOCOL_VERSION, parseServerEnvelope, type AgentState, type ServerInboundMessage, type WireEnvelope } from "../core/protocol.js";
7
+ import type { ConnectionStatus } from "../core/status.js";
8
+
9
+ export interface WebSocketLike {
10
+ readonly readyState: number;
11
+ send(data: string): void;
12
+ close(code?: number, reason?: string): void;
13
+ addEventListener(type: "open", listener: () => void): void;
14
+ addEventListener(type: "message", listener: (event: { data: unknown }) => void): void;
15
+ addEventListener(type: "close", listener: () => void): void;
16
+ addEventListener(type: "error", listener: (event: unknown) => void): void;
17
+ }
18
+
19
+ export type WebSocketFactory = (url: string) => WebSocketLike;
20
+
21
+ export interface AgentHelloInfo {
22
+ readonly serverToken: string;
23
+ readonly sessionId: string;
24
+ readonly sessionName?: string;
25
+ readonly host: string;
26
+ readonly cwd: string;
27
+ readonly branch?: string;
28
+ readonly model?: string;
29
+ readonly state: AgentState;
30
+ readonly requirePairing: boolean;
31
+ }
32
+
33
+ export interface WsClientOptions {
34
+ readonly serverUrl: string;
35
+ readonly reconnectBaseMs: number;
36
+ readonly reconnectMaxMs: number;
37
+ readonly getHello: () => AgentHelloInfo;
38
+ readonly onMessage: (msg: ServerInboundMessage) => void;
39
+ readonly onStatusChange?: (status: ConnectionStatus, detail?: string) => void;
40
+ readonly createWebSocket?: WebSocketFactory;
41
+ }
42
+
43
+ const WS_OPEN = 1;
44
+
45
+ export class WsClient {
46
+ private readonly opts: WsClientOptions;
47
+ private readonly createWS: WebSocketFactory;
48
+ private ws: WebSocketLike | null = null;
49
+ private stopped = true;
50
+ private attempt = 0;
51
+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
52
+ private status: ConnectionStatus = "disconnected";
53
+
54
+ constructor(opts: WsClientOptions) {
55
+ this.opts = opts;
56
+ this.createWS =
57
+ opts.createWebSocket ??
58
+ ((url: string) => {
59
+ const GlobalWS = (globalThis as unknown as { WebSocket?: new (u: string) => WebSocketLike }).WebSocket;
60
+ if (!GlobalWS) {
61
+ throw new Error("Global WebSocket is unavailable; Node >= 22 is required.");
62
+ }
63
+ return new GlobalWS(url);
64
+ });
65
+ }
66
+
67
+ get currentStatus(): ConnectionStatus {
68
+ return this.status;
69
+ }
70
+
71
+ start(): void {
72
+ if (!this.stopped) return;
73
+ this.stopped = false;
74
+ this.attempt = 0;
75
+ this.connect();
76
+ }
77
+
78
+ stop(): void {
79
+ this.stopped = true;
80
+ if (this.reconnectTimer !== null) {
81
+ clearTimeout(this.reconnectTimer);
82
+ this.reconnectTimer = null;
83
+ }
84
+ if (this.ws !== null) {
85
+ const sock = this.ws;
86
+ this.ws = null;
87
+ try {
88
+ sock.close(1000, "session shutdown");
89
+ } catch {
90
+ // Ignore close errors during shutdown.
91
+ }
92
+ }
93
+ this.setStatus("disconnected");
94
+ }
95
+
96
+ send(envelope: WireEnvelope): boolean {
97
+ if (this.ws === null || this.ws.readyState !== WS_OPEN) return false;
98
+ try {
99
+ this.ws.send(JSON.stringify(envelope));
100
+ return true;
101
+ } catch {
102
+ return false;
103
+ }
104
+ }
105
+
106
+ private setStatus(status: ConnectionStatus, detail?: string): void {
107
+ this.status = status;
108
+ this.opts.onStatusChange?.(status, detail);
109
+ }
110
+
111
+ private connect(): void {
112
+ if (this.stopped) return;
113
+ this.setStatus("connecting");
114
+
115
+ let sock: WebSocketLike;
116
+ try {
117
+ sock = this.createWS(this.opts.serverUrl);
118
+ } catch (error) {
119
+ this.setStatus("error", error instanceof Error ? error.message : String(error));
120
+ this.scheduleReconnect();
121
+ return;
122
+ }
123
+ this.ws = sock;
124
+
125
+ sock.addEventListener("open", () => {
126
+ if (this.ws !== sock || this.stopped) return;
127
+ this.attempt = 0;
128
+ const hello = this.opts.getHello();
129
+ this.send({
130
+ type: "agent.hello",
131
+ sessionId: hello.sessionId,
132
+ ts: Date.now(),
133
+ payload: {
134
+ ...hello,
135
+ protocolVersion: PROTOCOL_VERSION,
136
+ },
137
+ });
138
+ this.setStatus("connected");
139
+ });
140
+
141
+ sock.addEventListener("message", (event) => {
142
+ if (this.ws !== sock || this.stopped) return;
143
+ const raw = typeof event.data === "string" ? event.data : String(event.data ?? "");
144
+ const parsed = parseServerEnvelope(raw);
145
+ if (!parsed) return;
146
+ if (parsed.type === "ping") {
147
+ this.send({ type: "pong", sessionId: this.opts.getHello().sessionId, ts: Date.now() });
148
+ return;
149
+ }
150
+ if (parsed.type === "error") {
151
+ this.setStatus("error", parsed.message);
152
+ }
153
+ this.opts.onMessage(parsed);
154
+ });
155
+
156
+ sock.addEventListener("close", () => {
157
+ if (this.ws !== sock) return;
158
+ this.ws = null;
159
+ if (this.stopped) {
160
+ this.setStatus("disconnected");
161
+ return;
162
+ }
163
+ this.setStatus("disconnected");
164
+ this.scheduleReconnect();
165
+ });
166
+
167
+ sock.addEventListener("error", () => {
168
+ if (this.ws !== sock || this.stopped) return;
169
+ this.setStatus("error", "websocket connection error");
170
+ });
171
+ }
172
+
173
+ private scheduleReconnect(): void {
174
+ if (this.stopped || this.reconnectTimer !== null) return;
175
+ const exp = Math.min(this.opts.reconnectMaxMs, this.opts.reconnectBaseMs * 2 ** this.attempt);
176
+ this.attempt += 1;
177
+ this.reconnectTimer = setTimeout(() => {
178
+ this.reconnectTimer = null;
179
+ this.connect();
180
+ }, exp);
181
+ if (typeof this.reconnectTimer === "object" && "unref" in this.reconnectTimer) {
182
+ this.reconnectTimer.unref();
183
+ }
184
+ }
185
+ }
@@ -0,0 +1,18 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { parseRemoteConfig, resolveRemoteConfig } from "./config.js";
3
+
4
+ describe("remote config", () => {
5
+ it("rejects raw tokens and resolves env overrides", () => {
6
+ const parsed = parseRemoteConfig({
7
+ token: "secret",
8
+ serverUrl: "wss://relay.example.com/ws/agent",
9
+ remoteToolPolicy: "read-only",
10
+ remoteToolApproval: "web",
11
+ });
12
+ expect(parsed.warnings).toHaveLength(1);
13
+ const resolved = resolveRemoteConfig(parsed.config, { PI_REMOTE_SERVER_URL: "ws://override:8787/ws/agent" });
14
+ expect(resolved.serverUrl).toBe("ws://override:8787/ws/agent");
15
+ expect(resolved.remoteToolPolicy).toBe("read-only");
16
+ expect(resolved.remoteToolApproval).toBe("web");
17
+ });
18
+ });
package/src/config.ts ADDED
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Configuration loader and validator for pi-remote-control extension.
3
+ * Secrets are never stored in config files — only env var names (`tokenEnv`).
4
+ */
5
+
6
+ import type { RemoteToolApproval, RemoteToolPolicy } from "./core/tool-policy.js";
7
+
8
+ export interface RemoteControlConfig {
9
+ readonly serverUrl: string;
10
+ readonly tokenEnv: string;
11
+ readonly requirePairing: boolean;
12
+ readonly pairingTtlMs: number;
13
+ readonly pairingDigits: number;
14
+ readonly pairingMaxAttempts: number;
15
+ readonly remoteToolPolicy: RemoteToolPolicy;
16
+ readonly remoteToolApproval: RemoteToolApproval;
17
+ readonly approvalTimeoutMs: number;
18
+ readonly maxImageBytes: number;
19
+ readonly maxImages: number;
20
+ readonly reconnectBaseMs: number;
21
+ readonly reconnectMaxMs: number;
22
+ }
23
+
24
+ export const DEFAULT_REMOTE_CONFIG: RemoteControlConfig = {
25
+ serverUrl: "ws://127.0.0.1:8787/ws/agent",
26
+ tokenEnv: "PI_REMOTE_SERVER_TOKEN",
27
+ requirePairing: true,
28
+ pairingTtlMs: 5 * 60 * 1000,
29
+ pairingDigits: 6,
30
+ pairingMaxAttempts: 3,
31
+ remoteToolPolicy: "unrestricted",
32
+ remoteToolApproval: "off",
33
+ approvalTimeoutMs: 60_000,
34
+ maxImageBytes: 8 * 1024 * 1024,
35
+ maxImages: 4,
36
+ reconnectBaseMs: 1_000,
37
+ reconnectMaxMs: 30_000,
38
+ };
39
+
40
+ export interface ParsedConfigResult {
41
+ readonly config: Partial<RemoteControlConfig>;
42
+ readonly warnings: readonly string[];
43
+ }
44
+
45
+ export function parseRemoteConfig(raw: unknown): ParsedConfigResult {
46
+ const warnings: string[] = [];
47
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
48
+ return { config: {}, warnings: ["config must be a JSON object"] };
49
+ }
50
+ const obj = raw as Record<string, unknown>;
51
+ const out: Record<string, unknown> = {};
52
+
53
+ if ("token" in obj || "serverToken" in obj) {
54
+ warnings.push("raw token keys are ignored; use tokenEnv to name an environment variable");
55
+ }
56
+ if (typeof obj.serverUrl === "string" && obj.serverUrl.trim()) {
57
+ out.serverUrl = obj.serverUrl.trim();
58
+ }
59
+ if (typeof obj.tokenEnv === "string" && /^[A-Z0-9_]+$/i.test(obj.tokenEnv.trim())) {
60
+ out.tokenEnv = obj.tokenEnv.trim();
61
+ }
62
+ if (typeof obj.requirePairing === "boolean") {
63
+ out.requirePairing = obj.requirePairing;
64
+ }
65
+ if (obj.remoteToolPolicy === "unrestricted" || obj.remoteToolPolicy === "read-only" || obj.remoteToolPolicy === "no-tools") {
66
+ out.remoteToolPolicy = obj.remoteToolPolicy;
67
+ }
68
+ if (obj.remoteToolApproval === "off" || obj.remoteToolApproval === "local" || obj.remoteToolApproval === "web") {
69
+ out.remoteToolApproval = obj.remoteToolApproval;
70
+ }
71
+ if (typeof obj.approvalTimeoutMs === "number" && obj.approvalTimeoutMs >= 5_000 && obj.approvalTimeoutMs <= 300_000) {
72
+ out.approvalTimeoutMs = obj.approvalTimeoutMs;
73
+ }
74
+ if (typeof obj.pairingTtlMs === "number" && obj.pairingTtlMs >= 10_000 && obj.pairingTtlMs <= 3_600_000) {
75
+ out.pairingTtlMs = obj.pairingTtlMs;
76
+ }
77
+
78
+ return { config: out as Partial<RemoteControlConfig>, warnings };
79
+ }
80
+
81
+ export function resolveRemoteConfig(
82
+ overrides: Partial<RemoteControlConfig>,
83
+ env: Record<string, string | undefined> = process.env,
84
+ ): RemoteControlConfig {
85
+ const envUrl = env.PI_REMOTE_SERVER_URL?.trim();
86
+ return {
87
+ ...DEFAULT_REMOTE_CONFIG,
88
+ ...overrides,
89
+ ...(envUrl ? { serverUrl: envUrl } : {}),
90
+ };
91
+ }
@@ -0,0 +1,22 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { buildWorkDigest, parseGitBranch, parseGitNumstat } from "./digest.js";
3
+
4
+ describe("digest", () => {
5
+ it("parses git numstat and renders redacted digest markdown", () => {
6
+ expect(parseGitBranch("main\n")).toBe("main");
7
+ const changes = parseGitNumstat("10\t2\tsrc/app.ts\n");
8
+ expect(changes).toEqual([{ path: "src/app.ts", added: 10, deleted: 2 }]);
9
+
10
+ const md = buildWorkDigest({
11
+ sessionName: "demo",
12
+ cwd: "/repo",
13
+ branch: "main",
14
+ state: "idle",
15
+ changes,
16
+ lastPrompt: "use sk-ant-api03-1234567890abcdef",
17
+ });
18
+ expect(md).toContain("### Session: demo");
19
+ expect(md).toContain("`src/app.ts` (+10/-2)");
20
+ expect(md).toContain("[redacted:anthropic-key]");
21
+ });
22
+ });
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Pure work digest builder for remote status cards.
3
+ */
4
+
5
+ import { redactSecrets } from "./redact.js";
6
+
7
+ export interface DigestFileChange {
8
+ readonly path: string;
9
+ readonly added: number;
10
+ readonly deleted: number;
11
+ }
12
+
13
+ export interface DigestInput {
14
+ readonly sessionName?: string;
15
+ readonly cwd: string;
16
+ readonly branch?: string;
17
+ readonly state: "idle" | "busy";
18
+ readonly runningTool?: string;
19
+ readonly changes?: readonly DigestFileChange[];
20
+ readonly testSummary?: string;
21
+ readonly lastPrompt?: string;
22
+ readonly lastReply?: string;
23
+ }
24
+
25
+ export function parseGitBranch(stdout: string): string | undefined {
26
+ const trimmed = stdout.trim();
27
+ return trimmed.length > 0 && trimmed !== "HEAD" ? trimmed : undefined;
28
+ }
29
+
30
+ export function parseGitNumstat(stdout: string, max = 20): DigestFileChange[] {
31
+ const out: DigestFileChange[] = [];
32
+ for (const line of stdout.split(/\r?\n/)) {
33
+ if (!line.trim()) continue;
34
+ const parts = line.split("\t");
35
+ if (parts.length < 3) continue;
36
+ const added = parts[0] === "-" ? 0 : Number.parseInt(parts[0] ?? "0", 10);
37
+ const deleted = parts[1] === "-" ? 0 : Number.parseInt(parts[1] ?? "0", 10);
38
+ const path = parts.slice(2).join("\t");
39
+ if (path) {
40
+ out.push({
41
+ path,
42
+ added: Number.isFinite(added) ? added : 0,
43
+ deleted: Number.isFinite(deleted) ? deleted : 0,
44
+ });
45
+ }
46
+ if (out.length >= max) break;
47
+ }
48
+ return out;
49
+ }
50
+
51
+ export function buildWorkDigest(input: DigestInput): string {
52
+ const lines: string[] = [];
53
+ const title = input.sessionName ? `${input.sessionName}` : input.cwd;
54
+ lines.push(`### Session: ${title}`);
55
+ lines.push(`- **cwd:** \`${input.cwd}\``);
56
+ if (input.branch) lines.push(`- **branch:** \`${input.branch}\``);
57
+ lines.push(`- **state:** ${input.state}${input.runningTool ? ` (${input.runningTool})` : ""}`);
58
+ if (input.testSummary) lines.push(`- **last command:** ${redactSecrets(input.testSummary)}`);
59
+
60
+ if (input.changes && input.changes.length > 0) {
61
+ lines.push("");
62
+ lines.push("**Changed files:**");
63
+ for (const c of input.changes.slice(0, 15)) {
64
+ lines.push(`- \`${c.path}\` (+${c.added}/-${c.deleted})`);
65
+ }
66
+ }
67
+
68
+ if (input.lastPrompt) {
69
+ const p = redactSecrets(input.lastPrompt.trim()).slice(0, 200);
70
+ lines.push("");
71
+ lines.push(`**Last prompt:** ${p}`);
72
+ }
73
+ if (input.lastReply) {
74
+ const r = redactSecrets(input.lastReply.trim()).slice(0, 300);
75
+ lines.push("");
76
+ lines.push(`**Last reply:** ${r}`);
77
+ }
78
+
79
+ return lines.join("\n");
80
+ }
@@ -0,0 +1,18 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { buildHistorySnapshot } from "./history.js";
3
+
4
+ describe("buildHistorySnapshot", () => {
5
+ it("extracts user and assistant messages, redacts secrets, and bounds count", () => {
6
+ const entries = [
7
+ { type: "session", id: "h1" },
8
+ { type: "message", timestamp: "2026-11-23T10:00:00Z", message: { role: "user", content: "hi sk-ant-api03-1234567890abcdef" } },
9
+ { type: "message", message: { role: "toolResult", content: "secret output" } },
10
+ { type: "message", message: { role: "assistant", content: [{ type: "text", text: "done" }] } },
11
+ ];
12
+ const out = buildHistorySnapshot(entries, { maxItems: 10 });
13
+ expect(out).toHaveLength(2);
14
+ expect(out[0]?.role).toBe("user");
15
+ expect(out[0]?.text).toContain("[redacted:anthropic-key]");
16
+ expect(out[1]?.text).toBe("done");
17
+ });
18
+ });
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Pure history snapshot extraction from pi session entries.
3
+ * Applies secret redaction and size bounds.
4
+ */
5
+
6
+ import type { HistoryItem } from "./protocol.js";
7
+ import { redactSecrets } from "./redact.js";
8
+
9
+ export interface RawMessageContentPart {
10
+ readonly type?: string;
11
+ readonly text?: string;
12
+ }
13
+
14
+ export interface RawSessionEntry {
15
+ readonly type: string;
16
+ readonly timestamp?: string;
17
+ readonly message?: {
18
+ readonly role?: string;
19
+ readonly content?: unknown;
20
+ };
21
+ }
22
+
23
+ export function extractTextContent(content: unknown): string {
24
+ if (typeof content === "string") return content;
25
+ if (!Array.isArray(content)) return "";
26
+ const parts: string[] = [];
27
+ for (const part of content) {
28
+ if (typeof part === "object" && part !== null) {
29
+ const record = part as RawMessageContentPart;
30
+ if (record.type === "text" && typeof record.text === "string" && record.text.length > 0) {
31
+ parts.push(record.text);
32
+ }
33
+ }
34
+ }
35
+ return parts.join("\n");
36
+ }
37
+
38
+ export function buildHistorySnapshot(
39
+ entries: readonly RawSessionEntry[],
40
+ options: { maxItems?: number; maxItemChars?: number } = {},
41
+ ): HistoryItem[] {
42
+ const maxItems = options.maxItems ?? 40;
43
+ const maxItemChars = options.maxItemChars ?? 4000;
44
+ const items: HistoryItem[] = [];
45
+
46
+ for (const entry of entries) {
47
+ if (entry.type !== "message" || !entry.message) continue;
48
+ const role = entry.message.role;
49
+ if (role !== "user" && role !== "assistant") continue;
50
+ const rawText = extractTextContent(entry.message.content).trim();
51
+ if (!rawText) continue;
52
+
53
+ const redacted = redactSecrets(rawText);
54
+ const text = redacted.length > maxItemChars ? `${redacted.slice(0, maxItemChars - 1)}…` : redacted;
55
+ const parsedTs = entry.timestamp ? Date.parse(entry.timestamp) : Number.NaN;
56
+ items.push({
57
+ role,
58
+ text,
59
+ ...(Number.isFinite(parsedTs) ? { ts: parsedTs } : {}),
60
+ });
61
+ }
62
+
63
+ if (items.length <= maxItems) return items;
64
+ return items.slice(items.length - maxItems);
65
+ }
@@ -0,0 +1,28 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { createChallenge, formatChallengeCode, verifyChallenge } from "./pairing.js";
3
+
4
+ describe("pairing", () => {
5
+ it("creates deterministic 6-digit codes and enforces attempts and TTL", () => {
6
+ let idx = 0;
7
+ const seq = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.0, 0.1, 0.2, 0.3, 0.4, 0.5];
8
+ const ch = createChallenge({
9
+ digits: 6,
10
+ ttlMs: 60_000,
11
+ maxAttempts: 2,
12
+ now: 1000,
13
+ random: () => seq[idx++ % seq.length] ?? 0,
14
+ });
15
+ expect(ch.code).toBe("123456");
16
+ expect(formatChallengeCode(ch.code)).toBe("123-456");
17
+
18
+ const miss = verifyChallenge(ch, "000000", 2000);
19
+ expect(miss.ok).toBe(false);
20
+ if (!miss.ok && miss.reason === "mismatch" && miss.next) {
21
+ expect(miss.next.attemptsLeft).toBe(1);
22
+ const ok = verifyChallenge(miss.next, "123-456", 3000);
23
+ expect(ok).toEqual({ ok: true });
24
+ }
25
+
26
+ expect(verifyChallenge(ch, "123456", 62_000)).toEqual({ ok: false, reason: "expired" });
27
+ });
28
+ });
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Pure 6-digit pairing challenge generator and verifier.
3
+ * Codes are shown only in the local pi terminal, never sent to the relay.
4
+ */
5
+
6
+ export interface PendingChallenge {
7
+ readonly challengeId: string;
8
+ readonly code: string;
9
+ readonly createdAt: number;
10
+ readonly expiresAt: number;
11
+ readonly attemptsLeft: number;
12
+ }
13
+
14
+ export interface CreateChallengeOptions {
15
+ readonly digits: number;
16
+ readonly ttlMs: number;
17
+ readonly maxAttempts: number;
18
+ readonly now: number;
19
+ readonly random: () => number;
20
+ }
21
+
22
+ export function generateNumericCode(digits: number, random: () => number): string {
23
+ let out = "";
24
+ for (let i = 0; i < digits; i++) {
25
+ const n = Math.floor(Math.max(0, Math.min(0.999999999, random())) * 10);
26
+ out += String(n);
27
+ }
28
+ return out;
29
+ }
30
+
31
+ export function createChallenge(options: CreateChallengeOptions): PendingChallenge {
32
+ const code = generateNumericCode(options.digits, options.random);
33
+ const suffix = generateNumericCode(6, options.random);
34
+ return {
35
+ challengeId: `ch_${options.now}_${suffix}`,
36
+ code,
37
+ createdAt: options.now,
38
+ expiresAt: options.now + options.ttlMs,
39
+ attemptsLeft: options.maxAttempts,
40
+ };
41
+ }
42
+
43
+ export type VerifyResult =
44
+ | { readonly ok: true }
45
+ | { readonly ok: false; readonly reason: "expired" | "locked" | "mismatch"; readonly next?: PendingChallenge };
46
+
47
+ export function verifyChallenge(
48
+ challenge: PendingChallenge,
49
+ submitted: string,
50
+ now: number,
51
+ ): VerifyResult {
52
+ if (now > challenge.expiresAt) {
53
+ return { ok: false, reason: "expired" };
54
+ }
55
+ const trimmed = submitted.trim().replace(/[\s-]+/g, "");
56
+ if (trimmed === challenge.code) {
57
+ return { ok: true };
58
+ }
59
+ const remaining = challenge.attemptsLeft - 1;
60
+ if (remaining <= 0) {
61
+ return { ok: false, reason: "locked" };
62
+ }
63
+ return {
64
+ ok: false,
65
+ reason: "mismatch",
66
+ next: { ...challenge, attemptsLeft: remaining },
67
+ };
68
+ }
69
+
70
+ export function formatChallengeCode(code: string): string {
71
+ if (code.length === 6) return `${code.slice(0, 3)}-${code.slice(3)}`;
72
+ return code;
73
+ }
@@ -0,0 +1,44 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { parseServerEnvelope } from "./protocol.js";
3
+
4
+ describe("parseServerEnvelope", () => {
5
+ it("parses prompt.send with images and deliverAs", () => {
6
+ const raw = JSON.stringify({
7
+ type: "prompt.send",
8
+ sessionId: "s1",
9
+ clientId: "web-1",
10
+ payload: {
11
+ text: "check this",
12
+ deliverAs: "steer",
13
+ images: [{ mediaType: "image/png", data: "YWJj" }],
14
+ },
15
+ });
16
+ const msg = parseServerEnvelope(raw);
17
+ expect(msg).toEqual({
18
+ type: "prompt.send",
19
+ clientId: "web-1",
20
+ text: "check this",
21
+ deliverAs: "steer",
22
+ images: [{ mediaType: "image/png", data: "YWJj" }],
23
+ });
24
+ });
25
+
26
+ it("rejects malformed json or missing clientId", () => {
27
+ expect(parseServerEnvelope("{bad")).toBeNull();
28
+ expect(parseServerEnvelope(JSON.stringify({ type: "prompt.send", payload: { text: "hi" } }))).toBeNull();
29
+ });
30
+
31
+ it("parses approval.response", () => {
32
+ const raw = JSON.stringify({
33
+ type: "approval.response",
34
+ clientId: "web-1",
35
+ payload: { requestId: "req-1", approved: true },
36
+ });
37
+ expect(parseServerEnvelope(raw)).toEqual({
38
+ type: "approval.response",
39
+ clientId: "web-1",
40
+ requestId: "req-1",
41
+ approved: true,
42
+ });
43
+ });
44
+ });