Merge branch 't3/claude-chat-panel'
# Conflicts: # .agents/mind/gotchas.md # packages/core/src/protocol.ts
This commit is contained in:
@@ -8,6 +8,7 @@ import { terminalPlugin, type TerminalOptions } from "./terminal";
|
||||
import { createNotebookWatcher } from "./watch";
|
||||
import { registerAuth, type AuthOptions } from "./auth";
|
||||
import { registerStatic } from "./static";
|
||||
import { chatPlugin } from "./chat";
|
||||
|
||||
export interface AppOptions {
|
||||
logger?: boolean;
|
||||
@@ -43,6 +44,7 @@ export async function buildApp(options: AppOptions = {}): Promise<FastifyInstanc
|
||||
await app.register(workspacePlugin, { config });
|
||||
await app.register(runsPlugin, { config, hub });
|
||||
await app.register(terminalPlugin, { ...options.terminal, workspaceDir: config.workspaceDir });
|
||||
await app.register(chatPlugin, { config });
|
||||
|
||||
if (options.watchNotebooks) {
|
||||
const watcher = createNotebookWatcher(config.workspaceDir, {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# Chat transport and CLI contract (#8)
|
||||
|
||||
`/api/chat` is a dedicated JSON WebSocket protected by the existing auth and
|
||||
same-origin hook. Run events remain on `/api/events`. The socket owns its turn:
|
||||
disconnect, server shutdown, Stop, a five-minute timeout, malformed CLI output,
|
||||
or resource overflow terminates the child (SIGTERM, then SIGKILL after 1.5s).
|
||||
One turn per conversation, one per socket, at most four processes globally.
|
||||
The lock lasts until process close. Output is capped at 4 MiB per turn, records
|
||||
at 1 MiB, stderr at 8 KiB and outgoing socket buffering at 1 MiB.
|
||||
|
||||
Client frames: `send` with `message` (1–32000 characters), optional
|
||||
`conversationId`, optional workspace-relative `notebookPath`, and required
|
||||
`allowShell` boolean; or `cancel`. Server frames: `history`, `conversation`,
|
||||
`delta`, `tool` (name and optional notebook path only), `finished` (optional
|
||||
cancelled/costUsd/durationMs), and `error` (code and safe message). See core's
|
||||
additive Chat section. Tool activity describes requested operations, not proof
|
||||
that an edit succeeded. The existing watcher reloads actual changed files.
|
||||
|
||||
The data directory stores only a private, atomically replaced index of up to
|
||||
100 conversations: ID, first-message title (120 characters), CLI session ID,
|
||||
creation and update timestamps. Old inactive entries are evicted first.
|
||||
Shell permission is per-turn and never persisted. Messages/tool contents are
|
||||
not stored by ShellBook; Claude retains its own session files for `--resume`.
|
||||
The browser caches messages only while this panel is mounted. Do not enter
|
||||
secrets in chat: conversation titles and the CLI's own transcripts persist.
|
||||
|
||||
Verified against the official CLI reference and headless guide on 2026-11-16:
|
||||
- https://code.claude.com/docs/en/cli-reference
|
||||
- https://code.claude.com/docs/en/headless
|
||||
|
||||
Exact base argv: `-p --output-format stream-json --input-format stream-json
|
||||
--verbose --include-partial-messages --restricted --strict-mcp-config
|
||||
--disallowedTools mcp__* --tools Read,Glob,Grep,Edit,Write,MultiEdit
|
||||
--allowedTools Read,Glob,Grep,Edit,Write,MultiEdit --permission-mode acceptEdits
|
||||
--append-system-prompt <ShellBook context>`. Add `,Bash` to both tool lists only
|
||||
when the toggle is enabled; append `--resume <session_id>` on follow-ups.
|
||||
`--allowedTools` auto-approves; `--tools` actually restricts built-ins.
|
||||
`--restricted` confines file tools to working directories and ignores user/project
|
||||
settings (requires Claude Code **2.1.248+**). MCP is disabled. No bypass mode.
|
||||
Restricted mode still reads workspace CLAUDE.md. Unlike `--bare`, this preserves
|
||||
subscription authentication. The default CLI environment is inherited; no auth
|
||||
files or tokens are read or copied by ShellBook. Unsupported flags fail closed.
|
||||
Optional Bash has service-user authority; this toggle is not an OS sandbox.
|
||||
|
||||
The user prompt is a single newline-delimited user JSON record on stdin; never
|
||||
part of argv or a shell string. Init/result session IDs enable explicit resume.
|
||||
Only text deltas are rendered (assistant snapshots would duplicate them).
|
||||
Result errors and bounded stderr detect missing login without forwarding raw
|
||||
records or environment details. Cost is a CLI estimate and can be cumulative
|
||||
across a resumed session. Terminal recovery says to run `claude`, then `/login`.
|
||||
|
||||
Tests use a synthetic captured-format JSONL fixture and a small Node executable
|
||||
fixture, invoked through Node for portable Windows execution, including a fake
|
||||
`claude` launcher resolved through PATH (no real CLI or credentials).
|
||||
The fixture is representative protocol data, not a live recording.
|
||||
Real installed CLI compatibility, subscription login, Linux process trees and
|
||||
the visual layout still need deployment verification.
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { ChatEvent } from "@shellbook/core";
|
||||
import { isAbsolute, relative, resolve } from "node:path";
|
||||
|
||||
export function notebookPath(value: unknown): value is string {
|
||||
return typeof value === "string" && /^notebooks\/(?:[^/\\\x00-\x1f]+\/)*[^/\\\x00-\x1f]+\.md$/.test(value)
|
||||
&& !value.split("/").some(part => part === "." || part === "..");
|
||||
}
|
||||
|
||||
export function buildClaudeArgs(options: { sessionId?: string; notebookPath?: string; allowShell: boolean }): string[] {
|
||||
const tools = "Read,Glob,Grep,Edit,Write,MultiEdit" + (options.allowShell ? ",Bash" : "");
|
||||
const args = ["-p", "--output-format", "stream-json", "--input-format", "stream-json", "--verbose",
|
||||
"--include-partial-messages", "--restricted", "--strict-mcp-config", "--disallowedTools", "mcp__*",
|
||||
"--tools", tools, "--allowedTools", tools, "--permission-mode", "acceptEdits",
|
||||
"--append-system-prompt", `You are inside ShellBook. Follow the workspace CLAUDE.md notebook format. Write notebooks in notebooks/**/*.md. Never include secrets in notebooks or responses. Open notebook: ${options.notebookPath ?? "none"}.`];
|
||||
if (options.sessionId) args.push("--resume", options.sessionId);
|
||||
return args;
|
||||
}
|
||||
|
||||
export type ParsedEvent = ChatEvent | { type: "session"; sessionId: string };
|
||||
const loginPattern = /not logged in|please (?:run|use).*\/login|authentication[_ ](?:error|required)|invalid.*(?:api key|oauth)|login required|failed to authenticate/i;
|
||||
export const needsLogin = (text: string) => loginPattern.test(text);
|
||||
|
||||
/** Whitelist fields: never forward full CLI records, tool inputs, or stderr. */
|
||||
export function parseClaudeLine(line: string, workspace: string): ParsedEvent[] {
|
||||
const m = JSON.parse(line);
|
||||
if (!m || typeof m !== "object") throw new Error("Invalid CLI record");
|
||||
const result: ParsedEvent[] = [];
|
||||
if (typeof m.session_id === "string" && /^[a-zA-Z0-9-]{1,128}$/.test(m.session_id)) result.push({ type: "session", sessionId: m.session_id });
|
||||
if (m.type === "stream_event" && m.event?.type === "content_block_delta" && m.event.delta?.type === "text_delta" && typeof m.event.delta.text === "string") {
|
||||
result.push({ type: "delta", text: m.event.delta.text });
|
||||
}
|
||||
if (m.type === "assistant" && Array.isArray(m.message?.content)) {
|
||||
for (const block of m.message.content) {
|
||||
if (block.type !== "tool_use" || typeof block.name !== "string") continue;
|
||||
let target: string | undefined;
|
||||
const file = block.input?.file_path ?? block.input?.path;
|
||||
if (typeof file === "string") {
|
||||
const local = relative(workspace, resolve(workspace, file)).replaceAll("\\", "/");
|
||||
if (!isAbsolute(local) && !local.startsWith("../") && notebookPath(local)) target = local;
|
||||
}
|
||||
result.push({ type: "tool", name: block.name.slice(0, 80), ...(target ? { path: target } : {}) });
|
||||
}
|
||||
}
|
||||
if (m.type === "result") {
|
||||
if (m.is_error || m.subtype !== "success") {
|
||||
result.push({ type: "error", code: needsLogin(JSON.stringify(m)) ? "login" : "cli", message: needsLogin(JSON.stringify(m)) ? "Claude needs a login. Open Terminal, run claude, then /login." : "Claude could not complete this turn." });
|
||||
} else result.push({ type: "finished", ...(typeof m.total_cost_usd === "number" ? { costUsd: m.total_cost_usd } : {}), ...(typeof m.duration_ms === "number" ? { durationMs: m.duration_ms } : {}) });
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { FastifyPluginAsync } from "fastify";
|
||||
import type { ChatClientMessage, ChatConversation, ChatEvent } from "@shellbook/core";
|
||||
import type { ServerConfig } from "../config";
|
||||
import { notebookPath } from "./cli";
|
||||
import { startTurn, type TurnOptions } from "./process";
|
||||
|
||||
export function parseChatMessage(text: string): ChatClientMessage | undefined {
|
||||
if (text.length > 70_000) return;
|
||||
let m; try { m = JSON.parse(text); } catch { return; }
|
||||
if (!m || typeof m !== "object") return;
|
||||
if (m.type === "cancel") return { type: "cancel" };
|
||||
if (m.type !== "send" || typeof m.message !== "string" || !m.message.trim() || m.message.length > 32_000
|
||||
|| typeof m.allowShell !== "boolean" || (m.notebookPath !== undefined && !notebookPath(m.notebookPath))
|
||||
|| (m.conversationId !== undefined && (typeof m.conversationId !== "string" || !/^[a-f0-9-]{36}$/.test(m.conversationId)))) return;
|
||||
return { type: "send", message: m.message, allowShell: m.allowShell, notebookPath: m.notebookPath, conversationId: m.conversationId };
|
||||
}
|
||||
|
||||
export const chatPlugin: FastifyPluginAsync<{ config: ServerConfig; processOptions?: Pick<TurnOptions, "executable" | "prefixArgs" | "timeoutMs"> }> = async (app, { config, processOptions }) => {
|
||||
mkdirSync(config.dataDir, { recursive: true, mode: 0o700 });
|
||||
const file = join(config.dataDir, "chat-conversations.json");
|
||||
let conversations: ChatConversation[] = [];
|
||||
try {
|
||||
const raw = readFileSync(file);
|
||||
if (raw.length > 512 * 1024) throw new Error("Conversation index exceeds limit");
|
||||
const saved = JSON.parse(raw.toString());
|
||||
if (!Array.isArray(saved) || saved.length > 100 || saved.some(c => !c || !/^[a-f0-9-]{36}$/.test(c.id)
|
||||
|| typeof c.title !== "string" || c.title.length > 120 || typeof c.createdAt !== "string" || typeof c.updatedAt !== "string"
|
||||
|| (c.sessionId !== undefined && !/^[a-zA-Z0-9-]{1,128}$/.test(c.sessionId)))) throw new Error("Invalid conversation index");
|
||||
conversations = saved;
|
||||
} catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw new Error("Cannot load chat conversation index"); }
|
||||
const save = () => {
|
||||
writeFileSync(file + ".tmp", JSON.stringify(conversations), { mode: 0o600 });
|
||||
renameSync(file + ".tmp", file);
|
||||
};
|
||||
const turns = new Map<string, ReturnType<typeof startTurn>>();
|
||||
app.addHook("onClose", async () => { for (const turn of turns.values()) turn.cancel(); await Promise.all([...turns.values()].map(t => t.done)); });
|
||||
app.get("/api/chat", { websocket: true }, socket => {
|
||||
let active: ReturnType<typeof startTurn> | undefined;
|
||||
const send = (event: ChatEvent) => {
|
||||
if (socket.readyState !== 1) return;
|
||||
if (socket.bufferedAmount > 1024 * 1024) { active?.cancel(); socket.close(1013, "Chat client too slow"); return; }
|
||||
socket.send(JSON.stringify(event), error => { if (error) active?.cancel(); });
|
||||
};
|
||||
send({ type: "history", conversations });
|
||||
socket.on("close", () => active?.cancel());
|
||||
socket.on("error", () => { active?.cancel(); socket.close(); });
|
||||
socket.on("message", (raw, binary) => {
|
||||
const m = binary ? undefined : parseChatMessage(raw.toString());
|
||||
if (!m) { send({ type: "error", code: "invalid", message: "Invalid chat message." }); return; }
|
||||
if (m.type === "cancel") { active?.cancel(); return; }
|
||||
if (active || (m.conversationId && turns.has(m.conversationId))) { send({ type: "error", code: "busy", message: "A turn is already running in this conversation." }); return; }
|
||||
// Bound total concurrent CLI processes, not only per-conversation use.
|
||||
if (turns.size >= 4) { send({ type: "error", code: "busy", message: "Chat is busy. Try again shortly." }); return; }
|
||||
let conversation = conversations.find(c => c.id === m.conversationId);
|
||||
if (m.conversationId && !conversation) { send({ type: "error", code: "invalid", message: "Conversation no longer exists." }); return; }
|
||||
try {
|
||||
if (!conversation) {
|
||||
if (conversations.length >= 100) {
|
||||
const removable = conversations.findIndex(c => !turns.has(c.id));
|
||||
if (removable < 0) throw new Error("No free conversation slots");
|
||||
conversations.splice(removable, 1);
|
||||
}
|
||||
const now = new Date().toISOString();
|
||||
conversation = { id: randomUUID(), title: m.message.replace(/\s+/g, " ").slice(0, 120), createdAt: now, updatedAt: now };
|
||||
conversations.push(conversation);
|
||||
}
|
||||
conversation.updatedAt = new Date().toISOString(); save();
|
||||
const current = conversation;
|
||||
send({ type: "conversation", conversation: current });
|
||||
active = startTurn({ ...processOptions, workspaceDir: config.workspaceDir, message: m.message, allowShell: m.allowShell,
|
||||
notebookPath: m.notebookPath, sessionId: current.sessionId, emit: send,
|
||||
onSession: id => { current.sessionId = id; try { save(); } catch { active?.cancel(); send({ type: "error", code: "cli", message: "Cannot save conversation." }); } },
|
||||
});
|
||||
turns.set(current.id, active);
|
||||
void active.done.finally(() => { turns.delete(current.id); active = undefined; });
|
||||
} catch { send({ type: "error", code: "cli", message: "Cannot start or save conversation." }); }
|
||||
});
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,70 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { StringDecoder } from "node:string_decoder";
|
||||
import type { ChatEvent } from "@shellbook/core";
|
||||
import { buildClaudeArgs, needsLogin, parseClaudeLine } from "./cli";
|
||||
|
||||
export interface TurnOptions {
|
||||
workspaceDir: string; message: string; sessionId?: string; notebookPath?: string; allowShell: boolean;
|
||||
executable?: string; prefixArgs?: string[]; timeoutMs?: number;
|
||||
emit(event: ChatEvent): void; onSession(id: string): void;
|
||||
}
|
||||
/** One process per turn. Resolves only on close, so cancelled turns retain their lock. */
|
||||
export function startTurn(options: TurnOptions): { cancel(): void; done: Promise<void> } {
|
||||
const child = spawn(options.executable ?? "claude", [...(options.prefixArgs ?? []), ...buildClaudeArgs(options)], {
|
||||
cwd: options.workspaceDir, shell: false, stdio: ["pipe", "pipe", "pipe"], windowsHide: true,
|
||||
detached: process.platform !== "win32",
|
||||
});
|
||||
let terminal: ChatEvent | undefined;
|
||||
let stopped = false, bytes = 0, pending = "", stderr = "";
|
||||
const decoder = new StringDecoder("utf8");
|
||||
let force: ReturnType<typeof setTimeout> | undefined;
|
||||
const kill = (signal: NodeJS.Signals) => {
|
||||
// On the Linux service, also stop any shell descendants in the turn's group.
|
||||
try {
|
||||
if (process.platform !== "win32" && child.pid) process.kill(-child.pid, signal);
|
||||
else child.kill(signal);
|
||||
} catch { /* The process may already have exited. */ }
|
||||
};
|
||||
const stop = (event: ChatEvent) => {
|
||||
if (stopped) return;
|
||||
stopped = true; terminal = event;
|
||||
kill("SIGTERM");
|
||||
force = setTimeout(() => kill("SIGKILL"), 1500);
|
||||
force.unref();
|
||||
};
|
||||
const consume = (line: string) => {
|
||||
if (!line.trim()) return;
|
||||
for (const event of parseClaudeLine(line, options.workspaceDir)) {
|
||||
if (event.type === "session") options.onSession(event.sessionId);
|
||||
else if (event.type === "finished" || event.type === "error") terminal = event;
|
||||
else options.emit(event);
|
||||
}
|
||||
};
|
||||
child.stdout.on("data", (chunk: Buffer) => {
|
||||
if (stopped) return;
|
||||
bytes += chunk.length;
|
||||
if (bytes > 4 * 1024 * 1024) { stop({ type: "error", code: "limit", message: "Claude output limit exceeded." }); return; }
|
||||
pending += decoder.write(chunk);
|
||||
if (pending.length > 1024 * 1024) { stop({ type: "error", code: "limit", message: "Claude record limit exceeded." }); return; }
|
||||
const lines = pending.split("\n"); pending = lines.pop()!;
|
||||
try { for (const line of lines) consume(line); }
|
||||
catch { stop({ type: "error", code: "cli", message: "Invalid response from Claude CLI." }); }
|
||||
});
|
||||
child.stderr.on("data", (chunk: Buffer) => { stderr = (stderr + chunk.toString()).slice(-8192); });
|
||||
child.stdin.on("error", () => {});
|
||||
child.stdin.end(JSON.stringify({ type: "user", message: { role: "user", content: options.message } }) + "\n");
|
||||
const timeout = setTimeout(() => stop({ type: "error", code: "timeout", message: "Claude turn timed out." }), options.timeoutMs ?? 5 * 60_000);
|
||||
const done = new Promise<void>(resolve => {
|
||||
child.on("error", (error: NodeJS.ErrnoException) => {
|
||||
terminal = { type: "error", code: error.code === "ENOENT" ? "missing" : "cli", message: error.code === "ENOENT" ? "Claude CLI is missing from the server PATH. Install it, then open Terminal and run claude followed by /login." : "Unable to start Claude CLI." };
|
||||
});
|
||||
child.on("close", code => {
|
||||
clearTimeout(timeout); clearTimeout(force);
|
||||
if (!stopped) { try { consume(pending + decoder.end()); } catch { terminal = undefined; } }
|
||||
if (!stopped && needsLogin(stderr)) terminal = { type: "error", code: "login", message: "Claude needs a login. Open Terminal, run claude, then /login." };
|
||||
if (!terminal || (!stopped && code !== 0 && terminal.type === "finished")) terminal = { type: "error", code: "cli", message: "Claude CLI exited without completing the turn." };
|
||||
options.emit(terminal); resolve();
|
||||
});
|
||||
});
|
||||
return { done, cancel: () => stop({ type: "finished", cancelled: true }) };
|
||||
}
|
||||
Reference in New Issue
Block a user