A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.
TypeScript
feat(daemon): add HTTP and WebSocket gateway with protocol v1, token auth, and conversations
Alan Buscaglia64e25fbbbc16
diff --git a/odd/tasks/gentle-dot.md b/odd/tasks/gentle-dot.mdindex df9831f..300f627 100644--- a/odd/tasks/gentle-dot.md+++ b/odd/tasks/gentle-dot.md@@ -35,9 +35,9 @@ Branch: `feat/gentle-dot` · Delivery strategy: `single-pr` (user choice, L7; fo| ID | Specs | Route | Status | Commit / evidence | Scope ||---|---|---|---|---|---|-| T0 | S8 | inline | done (uncommitted) | readback OK; no commit yet | Design (`docs/design.md`) and this plan |-| T1 | S3, S6 | inline | pending | — | Scaffold the pnpm workspace (`packages/protocol`, `packages/daemon`, `packages/ui`, `apps/desktop` placeholder), TypeScript strict, Vitest, lint, README |-| T2 | S3, S5 | inline | pending | — | Agent supervisor: spawn, strict JSONL framing, id correlation, fake agent for tests, restart with backoff, reopen last session |+| T0 | S8 | inline | done | `5ec596c` readback OK | Design (`docs/design.md`) and this plan |+| T1 | S3, S6 | inline | done | `605b6c2` typecheck, lint, 2 tests green | Scaffold the pnpm workspace (`packages/protocol`, `packages/daemon`, `packages/ui`, `apps/desktop` placeholder), TypeScript strict, Vitest, lint, README |+| T2 | S3, S5 | inline | done | `c199fef` RED (missing modules) → GREEN 14 daemon tests, 3 consecutive runs | Agent supervisor: spawn, strict JSONL framing, id correlation, fake agent for tests, restart with backoff, reopen last session || T3 | S2, S6 | inline | pending | — | Gateway: HTTP static + `/health`, WebSocket protocol v1, token + Origin checks, Pi RPC mapping (design §4) || T4 | S4 | inline | pending | — | White-label: verify `--append-system-prompt` passthrough, `identity.md`, event sanitizer, tool-kind mapping, error neutralization || T5 | S2 | inline (writer only if parallel with T7) | pending | — | Web UI: chat, streaming Markdown, activity rows, conversations, composer with Stop/steer, visual tokens |@@ -57,4 +57,5 @@ Environment notes: Node v24.14.1 and pnpm are present. `cargo` is on PATH but `r- **L5 (2026-10-08, evidence):** `gentle-shell --mode rpc --no-session` returned `get_state` success (model reported) and `get_commands` with 82 commands including `gentle:*`, and emitted `extension_ui_request` `setStatus`/`setWidget`/`notify` at startup, so branding reaches RPC clients and S4 needs the sanitizer. Pi RPC docs: `custom()` returns undefined in RPC mode, while `select`/`confirm`/`input`/`editor`/`notify`/`setStatus`/`setWidget`/`setTitle` are forwarded. `extensions/ask-user-choice.ts` already falls back to `ctx.ui.select` + `ctx.ui.input` for RPC hosts. Pi CLI has `--append-system-prompt` and `--session-dir`.- **L6 (2026-10-08, decision):** Pi Durable deferred. Recovery relies on persisted Pi sessions plus Engram, per L2; it is reconsidered only for unattended or scheduled work.- **L7 (2026-10-08, user):** "Un solo pr, instala lo que necesites y dale nomás" — plan approved, delivery `single-pr` with size exception, installs authorized (Rust stable via rustup).-- **Next step:** T1.+- **L8 (2026-10-08, evidence):** Rust stable 1.99.0 installed via rustup (Homebrew); the nix `cargo` precedes it on PATH, so Tauri commands prepend `/opt/homebrew/opt/rustup/bin`. Toolchain versions: TypeScript 7, Vitest 5, Biome 2, pnpm 11.5. T2 risk tier: medium (process supervision covered by integration tests with a fake agent; the fake delays `crash` exit because macOS pipes are asynchronous).+- **Next step:** T3.diff --git a/packages/daemon/src/bridge.ts b/packages/daemon/src/bridge.tsnew file mode 100644index 0000000..4971ff9--- /dev/null+++ b/packages/daemon/src/bridge.ts@@ -0,0 +1,333 @@+import { join } from "node:path";+import type { AgentState, Ask, ClientMessage, ServerPayload } from "@gentle-dot/protocol";+import {+ conversationIdOf,+ historyFromMessages,+ listConversations,+ resolveConversation,+} from "./conversations.ts";+import { describeTool, textOf } from "./presentation.ts";+import type { AgentRecord, AgentSupervisor, SupervisorEvent } from "./supervisor.ts";++export interface BridgeClient {+ send(payload: ServerPayload): void;+}++export interface BridgeOptions {+ dataDir: string;+ log?: (line: string) => void;+ /** Rewrites or drops UI-bound payloads (white-label layer). Identity by default. */+ filter?: (payload: ServerPayload) => ServerPayload | undefined;+}++const DIALOG_METHODS = new Set(["select", "confirm", "input", "editor"]);+const REMEMBERED_REQUEST_IDS = 500;++/**+ * Translates between protocol v1 clients and the supervised agent: it keeps+ * the derived agent state, the pending asks, and the streaming message ids,+ * and broadcasts every agent event to all connected clients.+ */+export class DotBridge {+ private readonly clients = new Set<BridgeClient>();+ private readonly asks = new Map<string, { ask: Ask; timer?: NodeJS.Timeout }>();+ private readonly runningTools = new Set<string>();+ private readonly seenRequestIds: string[] = [];+ private readonly sessionDir: string;+ private readonly supervisor: AgentSupervisor;+ private readonly options: BridgeOptions;+ private state: AgentState = "starting";+ private interrupted = false;+ private nextMessage = 0;+ private assistantId: string | undefined;++ constructor(supervisor: AgentSupervisor, options: BridgeOptions) {+ this.supervisor = supervisor;+ this.options = options;+ this.sessionDir = join(options.dataDir, "sessions");+ supervisor.onEvent((event) => this.onAgentEvent(event));+ this.state = this.deriveState();+ }++ get agentState(): AgentState {+ return this.state;+ }++ attach(client: BridgeClient): () => void {+ this.clients.add(client);+ this.deliver(client, {+ type: "ready",+ agentState: this.state,+ ...this.conversationRef(),+ ...(this.supervisor.model ? { model: this.supervisor.model } : {}),+ });+ for (const { ask } of this.asks.values()) this.deliver(client, { type: "ask", ask });+ if (this.interrupted) this.deliver(client, { type: "interrupted" });+ return () => this.clients.delete(client);+ }++ async handle(client: BridgeClient, message: ClientMessage): Promise<void> {+ try {+ await this.dispatch(client, message);+ } catch (error) {+ this.log(`command ${message.type} failed: ${(error as Error).message}`);+ const unavailable = this.supervisor.state !== "ready";+ this.deliver(client, {+ type: "error",+ code: unavailable ? "agent_unavailable" : "command_failed",+ message: unavailable+ ? "The assistant is restarting. Try again in a moment."+ : "That did not work. Please try again.",+ });+ }+ }++ private async dispatch(client: BridgeClient, message: ClientMessage): Promise<void> {+ switch (message.type) {+ case "hello":+ return;+ case "send": {+ if (message.requestId && this.alreadySeen(message.requestId)) return;+ this.interrupted = false;+ const busy = this.supervisor.busy;+ await this.supervisor.request(+ busy+ ? { type: "prompt", message: message.text, streamingBehavior: "steer" }+ : { type: "prompt", message: message.text },+ );+ return;+ }+ case "steer":+ await this.supervisor.request({ type: "steer", message: message.text });+ return;+ case "abort":+ await this.supervisor.request({ type: "abort" });+ return;+ case "ui_response": {+ const pending = this.asks.get(message.requestId);+ if (!pending) {+ this.deliver(client, {+ type: "error",+ code: "ask_not_found",+ message: "That question is no longer open.",+ });+ return;+ }+ const { requestId, ...answer } = message;+ const { type: _type, ...fields } = answer;+ this.supervisor.send({ type: "extension_ui_response", id: requestId, ...fields });+ this.resolveAsk(requestId);+ return;+ }+ case "new_conversation":+ await this.supervisor.request({ type: "new_session" });+ this.afterConversationChange([]);+ return;+ case "list_conversations":+ this.deliver(client, this.conversationsPayload());+ return;+ case "open_conversation": {+ const path = resolveConversation(this.sessionDir, message.conversationId);+ if (!path) {+ this.deliver(client, {+ type: "error",+ code: "conversation_not_found",+ message: "That conversation does not exist.",+ });+ return;+ }+ await this.supervisor.request({ type: "switch_session", sessionPath: path });+ this.afterConversationChange(await this.loadHistory());+ return;+ }+ case "get_history":+ this.deliver(client, {+ type: "history",+ ...this.conversationRef(),+ messages: historyFromMessages(await this.loadHistory()),+ });+ return;+ }+ }++ private afterConversationChange(messages: unknown[]): void {+ this.interrupted = false;+ this.assistantId = undefined;+ this.broadcast({ type: "history", ...this.conversationRef(), messages: historyFromMessages(messages) });+ this.broadcast(this.conversationsPayload());+ }++ private async loadHistory(): Promise<unknown[]> {+ const response = await this.supervisor.request({ type: "get_messages" });+ return (response.data as { messages?: unknown[] } | undefined)?.messages ?? [];+ }++ private conversationsPayload(): ServerPayload {+ return { type: "conversations", conversations: listConversations(this.sessionDir), ...this.activeRef() };+ }++ private conversationRef(): { conversationId?: string } {+ const file = this.supervisor.sessionFile;+ return file ? { conversationId: conversationIdOf(this.sessionDir, file) } : {};+ }++ private activeRef(): { activeId?: string } {+ const ref = this.conversationRef();+ return ref.conversationId ? { activeId: ref.conversationId } : {};+ }++ private onAgentEvent(event: SupervisorEvent): void {+ switch (event.type) {+ case "supervisor_state":+ if (event.state !== "ready") this.clearRun();+ break;+ case "interrupted":+ this.interrupted = true;+ this.broadcast({ type: "interrupted" });+ break;+ case "message_start":+ this.onMessageStart(event);+ break;+ case "message_update":+ this.onMessageUpdate(event);+ break;+ case "message_end":+ this.onMessageEnd(event);+ break;+ case "tool_execution_start":+ case "tool_execution_end":+ this.onTool(event);+ break;+ case "agent_settled":+ this.runningTools.clear();+ this.assistantId = undefined;+ break;+ case "extension_ui_request":+ this.onUiRequest(event);+ break;+ }+ this.refreshState();+ }++ private onMessageStart(event: AgentRecord): void {+ const message = event.message as { role?: string } | undefined;+ if (message?.role === "user") {+ this.broadcast({ type: "user_message", messageId: `u${++this.nextMessage}`, text: textOf(message) });+ }+ if (message?.role === "assistant") this.assistantId = `m${++this.nextMessage}`;+ }++ private onMessageUpdate(event: AgentRecord): void {+ const update = event.assistantMessageEvent as { type?: string; delta?: unknown } | undefined;+ if (update?.type !== "text_delta" || typeof update.delta !== "string") return;+ this.assistantId ??= `m${++this.nextMessage}`;+ this.broadcast({ type: "message_delta", messageId: this.assistantId, delta: update.delta });+ }++ private onMessageEnd(event: AgentRecord): void {+ const message = event.message as+ | { role?: string; stopReason?: string; errorMessage?: string }+ | undefined;+ if (message?.role !== "assistant") return;+ const messageId = this.assistantId ?? `m${++this.nextMessage}`;+ this.broadcast({ type: "message_done", messageId, text: textOf(message) });+ if (message.stopReason === "error") {+ this.log(`assistant error: ${message.errorMessage ?? "unknown"}`);+ this.broadcast({ type: "toast", level: "error", message: "Something went wrong while answering." });+ }+ }++ private onTool(event: AgentRecord): void {+ const id = String(event.toolCallId ?? "");+ const started = event.type === "tool_execution_start";+ if (started) this.runningTools.add(id);+ else this.runningTools.delete(id);+ const status = started ? "running" : event.isError ? "failed" : "done";+ this.broadcast({+ type: "activity",+ messageId: this.assistantId ?? `m${++this.nextMessage}`,+ activity: { id, ...describeTool(String(event.toolName ?? ""), event.args), status },+ });+ }++ private onUiRequest(event: AgentRecord): void {+ const method = String(event.method ?? "");+ const requestId = String(event.id ?? "");+ if (method === "notify") {+ const level =+ event.notifyType === "error" ? "error" : event.notifyType === "warning" ? "warning" : "info";+ this.broadcast({ type: "toast", level, message: String(event.message ?? "") });+ return;+ }+ if (!DIALOG_METHODS.has(method) || !requestId) return;+ const ask: Ask = { requestId, method: method as Ask["method"], title: String(event.title ?? "") };+ if (typeof event.message === "string") ask.message = event.message;+ if (Array.isArray(event.options)) ask.options = event.options.map(String);+ if (typeof event.placeholder === "string") ask.placeholder = event.placeholder;+ if (typeof event.prefill === "string") ask.prefill = event.prefill;+ const entry: { ask: Ask; timer?: NodeJS.Timeout } = { ask };+ if (typeof event.timeout === "number" && event.timeout > 0) {+ ask.timeoutMs = event.timeout;+ // Pi resolves the dialog by itself when it times out; drop it here too.+ entry.timer = setTimeout(() => this.resolveAsk(requestId), event.timeout);+ }+ this.asks.set(requestId, entry);+ this.broadcast({ type: "ask", ask });+ }++ private resolveAsk(requestId: string): void {+ const entry = this.asks.get(requestId);+ if (!entry) return;+ clearTimeout(entry.timer);+ this.asks.delete(requestId);+ this.broadcast({ type: "ask_resolved", requestId });+ this.refreshState();+ }++ private clearRun(): void {+ for (const requestId of [...this.asks.keys()]) this.resolveAsk(requestId);+ this.runningTools.clear();+ this.assistantId = undefined;+ }++ private deriveState(): AgentState {+ switch (this.supervisor.state) {+ case "starting":+ return "starting";+ case "restarting":+ return "restarting";+ case "stopped":+ return "error";+ }+ if (this.asks.size > 0) return "needs_you";+ if (!this.supervisor.busy) return "idle";+ return this.runningTools.size > 0 ? "working" : "thinking";+ }++ private refreshState(): void {+ const next = this.deriveState();+ if (next === this.state) return;+ this.state = next;+ this.broadcast({ type: "agent_state", state: next });+ }++ private alreadySeen(requestId: string): boolean {+ if (this.seenRequestIds.includes(requestId)) return true;+ this.seenRequestIds.push(requestId);+ if (this.seenRequestIds.length > REMEMBERED_REQUEST_IDS) this.seenRequestIds.shift();+ return false;+ }++ private broadcast(payload: ServerPayload): void {+ for (const client of this.clients) this.deliver(client, payload);+ }++ private deliver(client: BridgeClient, payload: ServerPayload): void {+ const filtered = this.options.filter ? this.options.filter(payload) : payload;+ if (filtered) client.send(filtered);+ }++ private log(line: string): void {+ this.options.log?.(line);+ }+}diff --git a/packages/daemon/src/cli.ts b/packages/daemon/src/cli.tsindex b85966a..836985a 100644--- a/packages/daemon/src/cli.ts+++ b/packages/daemon/src/cli.ts@@ -1,3 +1,39 @@#!/usr/bin/env node-// Entry point; implemented in T3.-console.log("gentle-dot daemon");+import { loadConfig } from "./config.ts";+import { startDaemon } from "./daemon.ts";++const log = (line: string) => process.stderr.write(`${new Date().toISOString()} ${line}\n`);++async function main(): Promise<void> {+ const config = loadConfig();+ const daemon = await startDaemon({+ port: config.port,+ host: config.host,+ dataDir: config.dataDir,+ workspace: config.workspace,+ uiDir: config.uiDir,+ agentCommand: config.agentCommand,+ agentArgs: config.agentArgs,+ allowedOrigins: config.allowedOrigins,+ log,+ });+ process.stdout.write(`Gentle Dot is running at ${daemon.url}\n`);++ let closing = false;+ const shutdown = (signal: string) => {+ if (closing) return;+ closing = true;+ log(`received ${signal}, shutting down`);+ daemon.close().then(+ () => process.exit(0),+ () => process.exit(1),+ );+ };+ process.on("SIGINT", () => shutdown("SIGINT"));+ process.on("SIGTERM", () => shutdown("SIGTERM"));+}++main().catch((error: Error) => {+ log(`failed to start: ${error.message}`);+ process.exit(1);+});diff --git a/packages/daemon/src/config.ts b/packages/daemon/src/config.tsnew file mode 100644index 0000000..3ca7719--- /dev/null+++ b/packages/daemon/src/config.ts@@ -0,0 +1,67 @@+import { existsSync, readFileSync } from "node:fs";+import { homedir } from "node:os";+import { join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++export interface DotConfig {+ port: number;+ host: string;+ dataDir: string;+ workspace: string;+ uiDir: string;+ agentCommand: string;+ agentArgs: string[];+ allowedOrigins: string[];+}++const DEFAULT_UI_DIR = fileURLToPath(new URL("../../ui/dist/app", import.meta.url));++function expandHome(path: string): string {+ return path === "~" || path.startsWith("~/") ? join(homedir(), path.slice(1)) : path;+}++function readFileConfig(dataDir: string): Record<string, unknown> {+ const file = join(dataDir, "config.json");+ if (!existsSync(file)) return {};+ try {+ return JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown>;+ } catch (error) {+ throw new Error(`Invalid ${file}: ${(error as Error).message}`);+ }+}++function parsePort(value: unknown, source: string): number {+ const port = Number(value);+ if (!Number.isInteger(port) || port < 0 || port > 65535)+ throw new Error(`Invalid port in ${source}: ${String(value)}`);+ return port;+}++function parseList(value: string | undefined, name: string): string[] {+ if (!value) return [];+ const parsed = JSON.parse(value) as unknown;+ if (!Array.isArray(parsed) || !parsed.every((v) => typeof v === "string")) {+ throw new Error(`${name} must be a JSON array of strings`);+ }+ return parsed;+}++/** Resolves configuration from environment variables, then `~/.gentle-dot/config.json`, then defaults. */+export function loadConfig(env: NodeJS.ProcessEnv = process.env): DotConfig {+ const dataDir = resolve(expandHome(env.GENTLE_DOT_DATA_DIR ?? "~/.gentle-dot"));+ const file = readFileConfig(dataDir);+ return {+ port: env.GENTLE_DOT_PORT+ ? parsePort(env.GENTLE_DOT_PORT, "GENTLE_DOT_PORT")+ : parsePort(file.port ?? 4317, "config.json"),+ host: env.GENTLE_DOT_HOST ?? "127.0.0.1",+ dataDir,+ workspace: resolve(+ expandHome(env.GENTLE_DOT_WORKSPACE ?? (typeof file.workspace === "string" ? file.workspace : "~")),+ ),+ uiDir: resolve(env.GENTLE_DOT_UI_DIR ?? DEFAULT_UI_DIR),+ agentCommand: env.GENTLE_DOT_AGENT_BIN ?? "gentle-shell",+ agentArgs: parseList(env.GENTLE_DOT_AGENT_ARGS, "GENTLE_DOT_AGENT_ARGS"),+ allowedOrigins: parseList(env.GENTLE_DOT_ALLOWED_ORIGINS, "GENTLE_DOT_ALLOWED_ORIGINS"),+ };+}diff --git a/packages/daemon/src/conversations.ts b/packages/daemon/src/conversations.tsnew file mode 100644index 0000000..f94b903--- /dev/null+++ b/packages/daemon/src/conversations.ts@@ -0,0 +1,118 @@+import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from "node:fs";+import { join, relative, resolve, sep } from "node:path";+import type { Activity, ConversationSummary, HistoryMessage } from "@gentle-dot/protocol";+import { describeTool, textOf } from "./presentation.ts";++const TITLE_SCAN_BYTES = 256 * 1024;+const TITLE_LENGTH = 60;++/** Session files under `sessionDir` (and one level of subfolders), newest first. */+export function listConversations(sessionDir: string): ConversationSummary[] {+ if (!existsSync(sessionDir)) return [];+ const files: { path: string; mtime: Date }[] = [];+ for (const entry of readdirSync(sessionDir, { withFileTypes: true })) {+ const path = join(sessionDir, entry.name);+ if (entry.isFile() && entry.name.endsWith(".jsonl")) files.push({ path, mtime: statSync(path).mtime });+ if (entry.isDirectory()) {+ for (const nested of readdirSync(path, { withFileTypes: true })) {+ if (nested.isFile() && nested.name.endsWith(".jsonl")) {+ const nestedPath = join(path, nested.name);+ files.push({ path: nestedPath, mtime: statSync(nestedPath).mtime });+ }+ }+ }+ }+ return files+ .sort((a, b) => b.mtime.getTime() - a.mtime.getTime())+ .map(({ path, mtime }) => ({+ id: conversationIdOf(sessionDir, path),+ title: titleOf(path),+ updatedAt: mtime.toISOString(),+ }));+}++export function conversationIdOf(sessionDir: string, sessionFile: string): string {+ return relative(sessionDir, sessionFile).split(sep).join("/");+}++/** Resolves a client-supplied id to a session file inside `sessionDir`, or undefined. */+export function resolveConversation(sessionDir: string, id: string): string | undefined {+ if (!id.endsWith(".jsonl") || id.includes("\0")) return undefined;+ const root = resolve(sessionDir);+ const path = resolve(root, id);+ if (!path.startsWith(root + sep)) return undefined;+ return existsSync(path) && statSync(path).isFile() ? path : undefined;+}++function titleOf(path: string): string {+ let name: string | undefined;+ let firstUser: string | undefined;+ for (const line of readHead(path).split("\n")) {+ if (!line.trim()) continue;+ let record: Record<string, unknown>;+ try {+ record = JSON.parse(line) as Record<string, unknown>;+ } catch {+ continue;+ }+ if (record.type === "session_info") name = typeof record.name === "string" ? record.name : undefined;+ const message = (record.message ?? record) as { role?: unknown };+ if (firstUser === undefined && message.role === "user") firstUser = textOf(message);+ }+ const title = (name ?? firstUser ?? "").replace(/\s+/g, " ").trim();+ if (!title) return "New conversation";+ return title.length > TITLE_LENGTH ? `${title.slice(0, TITLE_LENGTH - 1)}…` : title;+}++function readHead(path: string): string {+ const fd = openSync(path, "r");+ try {+ const buffer = Buffer.alloc(TITLE_SCAN_BYTES);+ const bytes = readSync(fd, buffer, 0, TITLE_SCAN_BYTES, 0);+ return buffer.subarray(0, bytes).toString("utf8");+ } finally {+ closeSync(fd);+ }+}++type AgentMessage = { role?: string; content?: unknown; toolCallId?: string; isError?: boolean };++/** Converts Pi `get_messages` output into display messages; consecutive assistant messages form one turn. */+export function historyFromMessages(messages: unknown[]): HistoryMessage[] {+ const failed = new Set<string>();+ for (const raw of messages) {+ const m = raw as AgentMessage;+ if (m.role === "toolResult" && m.isError && m.toolCallId) failed.add(m.toolCallId);+ }+ const history: HistoryMessage[] = [];+ let index = 0;+ for (const raw of messages) {+ const m = raw as AgentMessage;+ if (m.role === "user") {+ history.push({ id: `h${++index}`, role: "user", text: textOf(m), activities: [] });+ continue;+ }+ if (m.role !== "assistant") continue;+ let turn = history.at(-1);+ if (turn?.role !== "assistant") {+ turn = { id: `h${++index}`, role: "assistant", text: "", activities: [] };+ history.push(turn);+ }+ const text = textOf(m);+ if (text) turn.text = turn.text ? `${turn.text}\n\n${text}` : text;+ turn.activities.push(...activitiesOf(m, failed));+ }+ return history;+}++function activitiesOf(message: AgentMessage, failed: Set<string>): Activity[] {+ if (!Array.isArray(message.content)) return [];+ return message.content.flatMap((block: unknown) => {+ const b = block as { type?: string; id?: string; name?: string; arguments?: unknown };+ if (b?.type !== "toolCall" || typeof b.name !== "string") return [];+ const id = b.id ?? b.name;+ return [+ { id, ...describeTool(b.name, b.arguments), status: failed.has(id) ? "failed" : "done" } as Activity,+ ];+ });+}diff --git a/packages/daemon/src/daemon.ts b/packages/daemon/src/daemon.tsnew file mode 100644index 0000000..556b5b2--- /dev/null+++ b/packages/daemon/src/daemon.ts@@ -0,0 +1,220 @@+import { randomBytes, timingSafeEqual } from "node:crypto";+import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";+import { createServer, type IncomingMessage, type ServerResponse } from "node:http";+import type { AddressInfo } from "node:net";+import { extname, join, resolve, sep } from "node:path";+import {+ type ClientMessage,+ CloseCode,+ PROTOCOL_VERSION,+ parseClientMessage,+ type ServerPayload,+} from "@gentle-dot/protocol";+import { type WebSocket, WebSocketServer } from "ws";+import { type BridgeClient, DotBridge } from "./bridge.ts";+import { AgentSupervisor } from "./supervisor.ts";++export interface DaemonOptions {+ port: number;+ host: string;+ dataDir: string;+ workspace: string;+ /** Directory with the built web UI (`index.html`). */+ uiDir: string;+ agentCommand: string;+ agentArgs?: string[];+ agentExtraArgs?: string[];+ agentEnv?: NodeJS.ProcessEnv;+ /** Origins allowed to open the WebSocket, besides the daemon's own and the desktop app's. */+ allowedOrigins?: string[];+ backoffMs?: number[];+ filter?: (payload: ServerPayload) => ServerPayload | undefined;+ log?: (line: string) => void;+}++export interface DotDaemon {+ port: number;+ token: string;+ url: string;+ bridge: DotBridge;+ supervisor: AgentSupervisor;+ close(): Promise<void>;+}++const HELLO_TIMEOUT_MS = 5000;+const CONTENT_TYPES: Record<string, string> = {+ ".html": "text/html; charset=utf-8",+ ".js": "text/javascript; charset=utf-8",+ ".css": "text/css; charset=utf-8",+ ".svg": "image/svg+xml",+ ".png": "image/png",+ ".ico": "image/x-icon",+ ".json": "application/json",+ ".woff2": "font/woff2",+};++/** Reads the access token from `<dataDir>/token`, creating a random one (mode 0600) when absent. */+export function ensureToken(dataDir: string): string {+ mkdirSync(dataDir, { recursive: true, mode: 0o700 });+ const file = join(dataDir, "token");+ if (existsSync(file)) {+ const existing = readFileSync(file, "utf8").trim();+ if (existing.length >= 32) return existing;+ }+ const token = randomBytes(32).toString("base64url");+ writeFileSync(file, `${token}\n`, { mode: 0o600 });+ return token;+}++export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {+ const log = options.log ?? (() => {});+ const token = ensureToken(options.dataDir);+ const supervisor = new AgentSupervisor({+ command: options.agentCommand,+ args: options.agentArgs ?? [],+ extraArgs: options.agentExtraArgs ?? [],+ cwd: options.workspace,+ dataDir: options.dataDir,+ env: options.agentEnv ?? process.env,+ ...(options.backoffMs ? { backoffMs: options.backoffMs } : {}),+ log: (line) => log(`[agent] ${line}`),+ });+ const bridge = new DotBridge(supervisor, {+ dataDir: options.dataDir,+ log,+ ...(options.filter ? { filter: options.filter } : {}),+ });++ const server = createServer((req, res) => handleHttp(req, res, options.uiDir, bridge));+ const wss = new WebSocketServer({ noServer: true, maxPayload: 1024 * 1024 });+ let port = options.port;++ server.on("upgrade", (req, socket, head) => {+ const url = new URL(req.url ?? "/", "http://localhost");+ const origin = req.headers.origin;+ if (url.pathname !== "/ws" || (origin !== undefined && !allowedOrigins(port, options).has(origin))) {+ socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n");+ return;+ }+ wss.handleUpgrade(req, socket, head, (ws) => acceptClient(ws, token, bridge));+ });++ await new Promise<void>((done, fail) => {+ server.once("error", fail);+ server.listen(options.port, options.host, () => done());+ });+ port = (server.address() as AddressInfo).port;++ await supervisor.start().catch((error: Error) => log(`agent failed to start: ${error.message}; retrying`));++ return {+ port,+ token,+ url: `http://${options.host === "0.0.0.0" ? "127.0.0.1" : options.host}:${port}/#token=${token}`,+ bridge,+ supervisor,+ async close() {+ for (const client of wss.clients) client.terminate();+ wss.close();+ await new Promise<void>((done) => server.close(() => done()));+ await supervisor.stop();+ },+ };+}++function allowedOrigins(port: number, options: DaemonOptions): Set<string> {+ return new Set([+ `http://127.0.0.1:${port}`,+ `http://localhost:${port}`,+ "tauri://localhost",+ "http://tauri.localhost",+ ...(options.allowedOrigins ?? []),+ ]);+}++function acceptClient(ws: WebSocket, token: string, bridge: DotBridge): void {+ let seq = 0;+ let detach: (() => void) | undefined;+ const client: BridgeClient = {+ send(payload) {+ if (ws.readyState === ws.OPEN) ws.send(JSON.stringify({ ...payload, seq: ++seq }));+ },+ };+ const helloTimer = setTimeout(() => ws.close(CloseCode.unauthorized, "hello required"), HELLO_TIMEOUT_MS);++ ws.on("message", (data) => {+ const message = parseClientMessage(String(data));+ if (!detach) {+ clearTimeout(helloTimer);+ if (message?.type !== "hello" || !sameToken(message.token, token)) {+ ws.close(CloseCode.unauthorized, "unauthorized");+ return;+ }+ if (message.protocol !== PROTOCOL_VERSION) {+ ws.close(CloseCode.badProtocol, "unsupported protocol");+ return;+ }+ detach = bridge.attach(client);+ return;+ }+ if (!message) {+ client.send({+ type: "error",+ code: "bad_message",+ message: "The app sent a message the assistant did not understand.",+ });+ return;+ }+ void bridge.handle(client, message as ClientMessage);+ });+ ws.on("close", () => {+ clearTimeout(helloTimer);+ detach?.();+ });+}++function sameToken(given: string, expected: string): boolean {+ const a = Buffer.from(given);+ const b = Buffer.from(expected);+ return a.length === b.length && timingSafeEqual(a, b);+}++function handleHttp(req: IncomingMessage, res: ServerResponse, uiDir: string, bridge: DotBridge): void {+ res.setHeader("X-Content-Type-Options", "nosniff");+ res.setHeader("Referrer-Policy", "no-referrer");+ if (req.method !== "GET" && req.method !== "HEAD") {+ res.writeHead(405).end();+ return;+ }+ const url = new URL(req.url ?? "/", "http://localhost");+ if (url.pathname === "/health") {+ res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });+ res.end(JSON.stringify({ ok: true, agentState: bridge.agentState }));+ return;+ }+ let pathname: string;+ try {+ pathname = decodeURIComponent(url.pathname);+ } catch {+ res.writeHead(400).end();+ return;+ }+ const root = resolve(uiDir);+ const target = resolve(root, `.${pathname}`);+ if (target !== root && !target.startsWith(root + sep)) {+ res.writeHead(403).end();+ return;+ }+ const file = existsSync(target) && statSync(target).isFile() ? target : join(root, "index.html");+ if (!existsSync(file)) {+ res.writeHead(503, { "Content-Type": "text/plain; charset=utf-8" });+ res.end("The interface is not built yet. Run `pnpm build`.");+ return;+ }+ const isIndex = file.endsWith("index.html");+ res.writeHead(200, {+ "Content-Type": CONTENT_TYPES[extname(file)] ?? "application/octet-stream",+ "Cache-Control": isIndex ? "no-store" : "public, max-age=3600",+ });+ res.end(req.method === "HEAD" ? undefined : readFileSync(file));+}diff --git a/packages/daemon/src/presentation.ts b/packages/daemon/src/presentation.tsnew file mode 100644index 0000000..ef98dca--- /dev/null+++ b/packages/daemon/src/presentation.ts@@ -0,0 +1,49 @@+import { basename } from "node:path";+import type { ActivityKind } from "@gentle-dot/protocol";++/**+ * Turns an internal tool call into a neutral activity. Tool names never reach+ * the user; only the kind and a short human title do.+ */+export function describeTool(toolName: string, args: unknown): { kind: ActivityKind; title: string } {+ const name = toolName.toLowerCase();+ const file = fileOf(args);+ if (name === "read") return { kind: "read", title: file ? `Reading ${file}` : "Reading a file" };+ if (name === "write" || name === "edit")+ return { kind: "edit", title: file ? `Editing ${file}` : "Editing a file" };+ if (name === "bash") return { kind: "run", title: "Running a command" };+ if (name.startsWith("mem_save") || name === "mem_update" || name === "mem_session_summary") {+ return { kind: "memory", title: "Saving a note" };+ }+ if (name.startsWith("mem_")) return { kind: "memory", title: "Checking my notes" };+ if (name.startsWith("subagent_")) return { kind: "delegate", title: "Asking a helper" };+ if (["web_search", "fetch_content", "get_search_content", "source_check"].includes(name)) {+ return { kind: "search", title: "Looking things up online" };+ }+ if (["grep", "find", "ls"].includes(name) || name.startsWith("codegraph")) {+ return { kind: "search", title: "Searching files" };+ }+ if (name.startsWith("ask_user")) return { kind: "other", title: "Asking you" };+ return { kind: "other", title: "Working" };+}++function fileOf(args: unknown): string | undefined {+ if (typeof args !== "object" || args === null) return undefined;+ const record = args as Record<string, unknown>;+ const path = record.path ?? record.file_path ?? record.filePath;+ return typeof path === "string" && path !== "" ? basename(path) : undefined;+}++/** Plain text of a user or assistant message whose content is a string or content blocks. */+export function textOf(message: unknown): string {+ if (typeof message !== "object" || message === null) return "";+ const content = (message as { content?: unknown }).content;+ if (typeof content === "string") return content;+ if (!Array.isArray(content)) return "";+ return content+ .flatMap((block: unknown) => {+ const b = block as { type?: string; text?: unknown };+ return b?.type === "text" && typeof b.text === "string" ? [b.text] : [];+ })+ .join("");+}diff --git a/packages/daemon/test/config.test.ts b/packages/daemon/test/config.test.tsnew file mode 100644index 0000000..c7cf83b--- /dev/null+++ b/packages/daemon/test/config.test.ts@@ -0,0 +1,36 @@+import { writeFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import { loadConfig } from "../src/config.ts";+import { tempDir } from "./helpers.ts";++describe("loadConfig", () => {+ it("uses local-only defaults", () => {+ const dataDir = tempDir();+ const config = loadConfig({ GENTLE_DOT_DATA_DIR: dataDir });+ expect(config).toMatchObject({+ port: 4317,+ host: "127.0.0.1",+ dataDir,+ agentCommand: "gentle-shell",+ agentArgs: [],+ });+ });++ it("reads config.json and lets environment variables win", () => {+ const dataDir = tempDir();+ writeFileSync(join(dataDir, "config.json"), JSON.stringify({ port: 5000, workspace: dataDir }));+ expect(loadConfig({ GENTLE_DOT_DATA_DIR: dataDir })).toMatchObject({ port: 5000, workspace: dataDir });+ expect(loadConfig({ GENTLE_DOT_DATA_DIR: dataDir, GENTLE_DOT_PORT: "6000" }).port).toBe(6000);+ });++ it("rejects an invalid port and a malformed argument list", () => {+ const dataDir = tempDir();+ expect(() => loadConfig({ GENTLE_DOT_DATA_DIR: dataDir, GENTLE_DOT_PORT: "abc" })).toThrow(+ "Invalid port",+ );+ expect(() => loadConfig({ GENTLE_DOT_DATA_DIR: dataDir, GENTLE_DOT_AGENT_ARGS: '{"a":1}' })).toThrow(+ "GENTLE_DOT_AGENT_ARGS must be a JSON array of strings",+ );+ });+});diff --git a/packages/daemon/test/gateway.test.ts b/packages/daemon/test/gateway.test.tsnew file mode 100644index 0000000..605c6e7--- /dev/null+++ b/packages/daemon/test/gateway.test.ts@@ -0,0 +1,254 @@+import { mkdirSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import type { ServerMessage } from "@gentle-dot/protocol";+import { afterEach, describe, expect, it } from "vitest";+import WebSocket from "ws";+import { type DotDaemon, startDaemon } from "../src/daemon.ts";+import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";++const daemons: DotDaemon[] = [];+afterEach(async () => {+ await Promise.all(daemons.splice(0).map((d) => d.close()));+});++async function daemon(env: NodeJS.ProcessEnv = process.env) {+ const dataDir = tempDir();+ const uiDir = join(dataDir, "ui");+ mkdirSync(uiDir);+ writeFileSync(join(uiDir, "index.html"), "<!doctype html><title>Gentle Dot</title>");+ writeFileSync(join(uiDir, "app.js"), "console.log('app')");+ const d = await startDaemon({+ port: 0,+ host: "127.0.0.1",+ dataDir,+ workspace: dataDir,+ uiDir,+ agentCommand: process.execPath,+ agentArgs: [FAKE_AGENT],+ agentEnv: env,+ backoffMs: [50],+ });+ daemons.push(d);+ return d;+}++type Client = { ws: WebSocket; messages: ServerMessage[]; closed: Promise<number> };++function connect(d: DotDaemon, origin?: string): Promise<Client> {+ return new Promise((resolve, reject) => {+ const ws = new WebSocket(`ws://127.0.0.1:${d.port}/ws`, origin ? { origin } : {});+ const messages: ServerMessage[] = [];+ const closed = new Promise<number>((done) => ws.on("close", (code) => done(code)));+ ws.on("message", (data) => messages.push(JSON.parse(String(data)) as ServerMessage));+ ws.on("open", () => resolve({ ws, messages, closed }));+ ws.on("error", reject);+ });+}++async function authed(d: DotDaemon): Promise<Client> {+ const client = await connect(d);+ client.ws.send(JSON.stringify({ type: "hello", token: d.token, protocol: 1 }));+ await waitFor(() => client.messages.some((m) => m.type === "ready"));+ return client;+}++function send(client: Client, message: object): void {+ client.ws.send(JSON.stringify(message));+}++function find<T extends ServerMessage["type"]>(+ client: Client,+ type: T,+ where: (m: Extract<ServerMessage, { type: T }>) => boolean = () => true,+) {+ return waitFor(() =>+ client.messages.find(+ (m): m is Extract<ServerMessage, { type: T }> =>+ m.type === type && where(m as Extract<ServerMessage, { type: T }>),+ ),+ );+}++describe("gateway", () => {+ it("closes with 4401 when the token is wrong", async () => {+ const d = await daemon();+ const client = await connect(d);+ send(client, { type: "hello", token: "wrong", protocol: 1 });+ expect(await client.closed).toBe(4401);+ expect(client.messages).toEqual([]);+ });++ it("closes with 4401 when the first message is not hello", async () => {+ const d = await daemon();+ const client = await connect(d);+ send(client, { type: "send", text: "hi" });+ expect(await client.closed).toBe(4401);+ });++ it("closes with 4400 for an unsupported protocol version", async () => {+ const d = await daemon();+ const client = await connect(d);+ send(client, { type: "hello", token: d.token, protocol: 2 });+ expect(await client.closed).toBe(4400);+ });++ it("rejects a WebSocket upgrade from a foreign origin", async () => {+ const d = await daemon();+ await expect(connect(d, "https://evil.example")).rejects.toThrow(/403/);+ });++ it("accepts the desktop app origin", async () => {+ const d = await daemon();+ const client = await connect(d, "tauri://localhost");+ send(client, { type: "hello", token: d.token, protocol: 1 });+ await waitFor(() => client.messages.some((m) => m.type === "ready"));+ });++ it("sends ready with the agent state and numbers every message", async () => {+ const d = await daemon();+ const client = await authed(d);+ const ready = await find(client, "ready");+ expect(ready.agentState).toBe("idle");+ expect(ready.conversationId).toBeTruthy();+ expect(client.messages.map((m) => m.seq)).toEqual(client.messages.map((_, i) => i + 1));+ });++ it("streams an answer: user message, deltas, final text, and state changes", async () => {+ const d = await daemon();+ const client = await authed(d);+ send(client, { type: "send", text: "hello there" });+ const done = await find(client, "message_done");+ expect(done.text).toBe("Echo: hello there");+ const user = await find(client, "user_message");+ expect(user.text).toBe("hello there");+ const deltas = client.messages.filter(+ (m) => m.type === "message_delta" && m.messageId === done.messageId,+ );+ expect(deltas.map((m) => (m.type === "message_delta" ? m.delta : "")).join("")).toBe("Echo: hello there");+ await find(client, "agent_state", (m) => m.state === "idle");+ const states = client.messages.flatMap((m) => (m.type === "agent_state" ? [m.state] : []));+ expect(states).toContain("thinking");+ });++ it("broadcasts to every connected client", async () => {+ const d = await daemon();+ const a = await authed(d);+ const b = await authed(d);+ send(a, { type: "send", text: "shared" });+ const done = await find(b, "message_done");+ expect(done.text).toBe("Echo: shared");+ });++ it("ignores a repeated requestId", async () => {+ const d = await daemon();+ const client = await authed(d);+ send(client, { type: "send", text: "once", requestId: "r1" });+ await find(client, "agent_state", (m) => m.state === "idle");+ await find(client, "message_done");+ send(client, { type: "send", text: "once", requestId: "r1" });+ send(client, { type: "list_conversations" });+ await find(client, "conversations");+ expect(client.messages.filter((m) => m.type === "user_message")).toHaveLength(1);+ });++ it("reports tool activity under the running answer", async () => {+ const d = await daemon();+ const client = await authed(d);+ send(client, { type: "send", text: "tool:read" });+ const done = await find(client, "activity", (m) => m.activity.status === "done");+ expect(done.activity.kind).toBe("read");+ await find(client, "agent_state", (m) => m.state === "working");+ });++ it("relays a select ask and the user's answer", async () => {+ const d = await daemon();+ const client = await authed(d);+ send(client, { type: "send", text: "ask:select" });+ const ask = await find(client, "ask");+ expect(ask.ask).toMatchObject({ method: "select", title: "Pick a color", options: ["Red", "Blue"] });+ await find(client, "agent_state", (m) => m.state === "needs_you");+ send(client, { type: "ui_response", requestId: ask.ask.requestId, value: "Blue" });+ await find(client, "ask_resolved", (m) => m.requestId === ask.ask.requestId);+ const done = await find(client, "message_done");+ expect(done.text).toBe("You chose Blue");+ });++ it("re-sends pending asks to a client that connects later", async () => {+ const d = await daemon();+ const a = await authed(d);+ send(a, { type: "send", text: "ask:confirm" });+ const ask = await find(a, "ask");+ const b = await authed(d);+ const again = await find(b, "ask");+ expect(again.ask.requestId).toBe(ask.ask.requestId);+ send(b, { type: "ui_response", requestId: ask.ask.requestId, confirmed: true });+ expect((await find(a, "message_done")).text).toBe("Confirmed");+ });++ it("creates, lists, and reopens conversations with their history", async () => {+ const d = await daemon();+ const client = await authed(d);+ send(client, { type: "send", text: "first conversation" });+ await find(client, "message_done");+ await find(client, "agent_state", (m) => m.state === "idle");+ const firstId = (await find(client, "ready")).conversationId;++ send(client, { type: "new_conversation" });+ const listed = await find(client, "conversations", (m) => m.activeId !== firstId);+ expect(listed.conversations.map((c) => c.id)).toContain(firstId);+ expect(listed.conversations.find((c) => c.id === firstId)?.title).toBe("first conversation");++ send(client, { type: "open_conversation", conversationId: firstId });+ const history = await find(client, "history", (m) => m.conversationId === firstId);+ expect(history.messages.map((m) => [m.role, m.text])).toEqual([+ ["user", "first conversation"],+ ["assistant", "Echo: first conversation"],+ ]);+ });++ it("refuses a conversation id outside the session directory", async () => {+ const d = await daemon();+ const client = await authed(d);+ send(client, { type: "open_conversation", conversationId: "../../etc/passwd" });+ const error = await find(client, "error");+ expect(error.code).toBe("conversation_not_found");+ });++ it("answers malformed frames with an error and keeps the connection", async () => {+ const d = await daemon();+ const client = await authed(d);+ client.ws.send("{nope");+ expect((await find(client, "error")).code).toBe("bad_message");+ send(client, { type: "get_history" });+ await find(client, "history");+ });++ it("tells clients about an interrupted run after the agent restarts", async () => {+ const d = await daemon();+ const client = await authed(d);+ send(client, { type: "send", text: "crash" });+ await find(client, "agent_state", (m) => m.state === "restarting");+ await find(client, "interrupted");+ await find(client, "agent_state", (m) => m.state === "idle");+ });+});++describe("http", () => {+ it("serves the UI, falls back to index.html, and blocks path traversal", async () => {+ const d = await daemon();+ const base = `http://127.0.0.1:${d.port}`;+ expect(await (await fetch(`${base}/app.js`)).text()).toBe("console.log('app')");+ expect(await (await fetch(`${base}/some/route`)).text()).toContain("<title>Gentle Dot</title>");+ const traversal = await fetch(`${base}/..%2f..%2fpackage.json`);+ expect(await traversal.text()).not.toContain('"name"');+ });++ it("reports health without the token", async () => {+ const d = await daemon();+ const health = (await (await fetch(`http://127.0.0.1:${d.port}/health`)).json()) as Record<+ string,+ unknown+ >;+ expect(health).toEqual({ ok: true, agentState: "idle" });+ });+});diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.tsindex 0d0bdda..5560ee4 100644--- a/packages/protocol/src/index.ts+++ b/packages/protocol/src/index.ts@@ -1,2 +1,126 @@/** Version of the client <-> daemon protocol (docs/design.md §4). */export const PROTOCOL_VERSION = 1;++/** WebSocket close codes used by the daemon. */+export const CloseCode = {+ unauthorized: 4401,+ badProtocol: 4400,+} as const;++export type AgentState = "starting" | "idle" | "thinking" | "working" | "needs_you" | "restarting" | "error";++export type ActivityKind = "read" | "edit" | "run" | "search" | "memory" | "delegate" | "other";++export interface Activity {+ id: string;+ kind: ActivityKind;+ title: string;+ status: "running" | "done" | "failed";+}++export interface Ask {+ requestId: string;+ method: "select" | "confirm" | "input" | "editor";+ title: string;+ message?: string;+ options?: string[];+ placeholder?: string;+ prefill?: string;+ timeoutMs?: number;+}++export interface HistoryMessage {+ id: string;+ role: "user" | "assistant";+ text: string;+ activities: Activity[];+}++export interface ConversationSummary {+ id: string;+ title: string;+ updatedAt: string;+}++export type ClientMessage =+ | { type: "hello"; token: string; protocol: number }+ | { type: "send"; text: string; requestId?: string }+ | { type: "steer"; text: string }+ | { type: "abort" }+ | { type: "ui_response"; requestId: string; value?: string; confirmed?: boolean; cancelled?: boolean }+ | { type: "new_conversation" }+ | { type: "list_conversations" }+ | { type: "open_conversation"; conversationId: string }+ | { type: "get_history" };++export type ServerPayload =+ | { type: "ready"; agentState: AgentState; conversationId?: string; model?: string }+ | { type: "agent_state"; state: AgentState }+ | { type: "user_message"; messageId: string; text: string }+ | { type: "message_delta"; messageId: string; delta: string }+ | { type: "message_done"; messageId: string; text: string }+ | { type: "activity"; messageId: string; activity: Activity }+ | { type: "ask"; ask: Ask }+ | { type: "ask_resolved"; requestId: string }+ | { type: "toast"; level: "info" | "warning" | "error"; message: string }+ | { type: "history"; conversationId?: string; messages: HistoryMessage[] }+ | { type: "conversations"; conversations: ConversationSummary[]; activeId?: string }+ | { type: "interrupted" }+ | { type: "error"; code: string; message: string };++/** Every daemon message carries a per-connection, monotonic `seq`. */+export type ServerMessage = ServerPayload & { seq: number };++const isString = (value: unknown): value is string => typeof value === "string";+const isOptional = (value: unknown, check: (v: unknown) => boolean) => value === undefined || check(value);+const MAX_TEXT = 100_000;++/** Validates one raw client frame; returns undefined when it is not a known, well-formed message. */+export function parseClientMessage(raw: string): ClientMessage | undefined {+ let value: unknown;+ try {+ value = JSON.parse(raw);+ } catch {+ return undefined;+ }+ if (typeof value !== "object" || value === null) return undefined;+ const m = value as Record<string, unknown>;+ switch (m.type) {+ case "hello":+ return isString(m.token) && typeof m.protocol === "number"+ ? { type: "hello", token: m.token, protocol: m.protocol }+ : undefined;+ case "send":+ if (!isString(m.text) || m.text.trim() === "" || m.text.length > MAX_TEXT) return undefined;+ if (!isOptional(m.requestId, isString)) return undefined;+ return m.requestId === undefined+ ? { type: "send", text: m.text }+ : { type: "send", text: m.text, requestId: m.requestId as string };+ case "steer":+ return isString(m.text) && m.text.trim() !== "" && m.text.length <= MAX_TEXT+ ? { type: "steer", text: m.text }+ : undefined;+ case "ui_response": {+ if (!isString(m.requestId)) return undefined;+ if (m.cancelled === true) return { type: "ui_response", requestId: m.requestId, cancelled: true };+ if (typeof m.confirmed === "boolean") {+ return { type: "ui_response", requestId: m.requestId, confirmed: m.confirmed };+ }+ if (isString(m.value) && m.value.length <= MAX_TEXT) {+ return { type: "ui_response", requestId: m.requestId, value: m.value };+ }+ return undefined;+ }+ case "open_conversation":+ return isString(m.conversationId)+ ? { type: "open_conversation", conversationId: m.conversationId }+ : undefined;+ case "abort":+ case "new_conversation":+ case "list_conversations":+ case "get_history":+ return { type: m.type };+ default:+ return undefined;+ }+}diff --git a/packages/protocol/test/protocol.test.ts b/packages/protocol/test/protocol.test.tsindex 8304f4c..d304f7c 100644--- a/packages/protocol/test/protocol.test.ts+++ b/packages/protocol/test/protocol.test.ts@@ -1,8 +1,41 @@import { describe, expect, it } from "vitest";-import { PROTOCOL_VERSION } from "../src/index.ts";+import { PROTOCOL_VERSION, parseClientMessage } from "../src/index.ts";describe("protocol", () => {it("exposes version 1", () => {expect(PROTOCOL_VERSION).toBe(1);});++ it("accepts well-formed client messages", () => {+ expect(parseClientMessage('{"type":"hello","token":"t","protocol":1}')).toEqual({+ type: "hello",+ token: "t",+ protocol: 1,+ });+ expect(parseClientMessage('{"type":"send","text":"hi","requestId":"r"}')).toEqual({+ type: "send",+ text: "hi",+ requestId: "r",+ });+ expect(parseClientMessage('{"type":"ui_response","requestId":"a","confirmed":false}')).toEqual({+ type: "ui_response",+ requestId: "a",+ confirmed: false,+ });+ expect(parseClientMessage('{"type":"abort","extra":1}')).toEqual({ type: "abort" });+ });++ it("rejects malformed or unknown messages", () => {+ for (const raw of [+ "{",+ "null",+ '{"type":"send","text":" "}',+ '{"type":"send","text":1}',+ '{"type":"ui_response","requestId":"a"}',+ '{"type":"open_conversation"}',+ '{"type":"shell","cmd":"rm"}',+ ]) {+ expect(parseClientMessage(raw), raw).toBeUndefined();+ }+ });});