feat(web): add notebook chat panel (#8)

This commit is contained in:
Florian Schmidt
2026-11-16 10:17:20 +01:00
parent 4fe7e4e376
commit 0055001abf
19 changed files with 602 additions and 16 deletions
+2
View File
@@ -7,6 +7,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;
@@ -41,6 +42,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, {
+57
View File
@@ -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.
+50
View File
@@ -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;
}
+82
View File
@@ -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." }); }
});
});
};
+70
View File
@@ -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 }) };
}
+104
View File
@@ -0,0 +1,104 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { copyFileSync, linkSync, mkdtempSync, readFileSync, rmSync, symlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import Fastify from "fastify";
import websocket from "@fastify/websocket";
import { buildClaudeArgs, notebookPath, parseClaudeLine } from "../src/chat/cli";
import { startTurn } from "../src/chat/process";
import { chatPlugin, parseChatMessage } from "../src/chat";
import { buildApp } from "../src/app";
import { loadConfig } from "../src/config";
import { loadSessionSecret, signSession } from "../src/auth/session";
import type { ChatEvent } from "@shellbook/core";
const dirs: string[] = [];
const temp = () => { const dir = mkdtempSync(join(tmpdir(), "shellbook-chat-")); dirs.push(dir); return dir; };
afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
const fixture = resolve("test/fixtures/fake-claude.cjs");
const processOptions = { executable: process.execPath, prefixArgs: [fixture], timeoutMs: 3000 };
const run = (message: string, extra = {}) => {
const events: ChatEvent[] = []; const sessions: string[] = [];
const turn = startTurn({ ...processOptions, workspaceDir: process.cwd(), message, allowShell: false,
emit: e => events.push(e), onSession: id => sessions.push(id), ...extra });
return { ...turn, events, sessions };
};
describe("chat CLI contract", () => {
it("restricts tools, keeps prompts out of argv, resumes explicitly", () => {
const args = buildClaudeArgs({ allowShell: false, sessionId: "abc", notebookPath: "notebooks/a.md" });
expect(args).toEqual(expect.arrayContaining(["-p", "--restricted", "--strict-mcp-config", "mcp__*", "--include-partial-messages", "--resume", "abc", "acceptEdits"]));
expect(args[args.indexOf("--tools") + 1]).toBe("Read,Glob,Grep,Edit,Write,MultiEdit");
expect(args.join(" ")).not.toContain("bypassPermissions");
expect(args[args.indexOf("--append-system-prompt") + 1]).toContain("notebooks/a.md");
const shell = buildClaudeArgs({ allowShell: true });
expect(shell[shell.indexOf("--allowedTools") + 1]).toContain(",Bash");
});
it("parses captured-format fixture records without duplicating text or exposing tool contents", () => {
const events = readFileSync(resolve("test/fixtures/chat.jsonl"), "utf8").trim().split("\n").flatMap(line => parseClaudeLine(line, process.cwd()));
expect(events.filter(e => e.type === "delta")).toEqual([{ type: "delta", text: "Hello notebook" }]);
expect(events).toContainEqual({ type: "tool", name: "Edit", path: "notebooks/setup/nginx.md" });
expect(events).toContainEqual({ type: "finished", costUsd: .002, durationMs: 1234 });
expect(JSON.stringify(events)).not.toContain("private contents");
expect(parseClaudeLine('{"type":"future"}', process.cwd())).toEqual([]);
expect(() => parseClaudeLine("bad", process.cwd())).toThrow();
});
it.each(["../secret", "notebooks/../secret.md", "notebooks/a\\b.md", "/notebooks/a.md", "notebooks/x\n.md"])("rejects invalid notebook %s", path => expect(notebookPath(path)).toBe(false));
it.each(["null", "bad", '{"type":"send","message":"a","allowShell":"yes"}', JSON.stringify({ type: "send", message: "a".repeat(32001), allowShell: false })])("rejects invalid client frame %#", text => expect(parseChatMessage(text)).toBeUndefined());
});
describe("fake CLI lifecycle", () => {
it("streams text, extracts session ID, and waits for exit", async () => {
const turn = run("hello ' ; $(test)"); await turn.done;
expect(turn.sessions).toContain("11111111-1111-4111-8111-111111111111");
expect(turn.events.at(-1)).toEqual({ type: "finished", costUsd: .002, durationMs: 1234 });
});
it.each(["login", "stderr-login"])("detects login failure: %s", async message => {
const turn = run(message); await turn.done; expect(turn.events.at(-1)).toMatchObject({ type: "error", code: "login" });
});
it("detects missing CLI", async () => { const turn = run("a", { executable: join(temp(), "missing-claude"), prefixArgs: [] }); await turn.done; expect(turn.events.at(-1)).toMatchObject({ code: "missing" }); });
it("resolves the fake executable on PATH without a shell", async () => {
const dir = temp(); const launcher = join(dir, process.platform === "win32" ? "claude.exe" : "claude");
if (process.platform === "win32") { try { linkSync(process.execPath, launcher); } catch { copyFileSync(process.execPath, launcher); } }
else symlinkSync(process.execPath, launcher);
const previous = process.env.PATH;
process.env.PATH = dir + (process.platform === "win32" ? ";" : ":") + previous;
try { const turn = run("hello", { executable: "claude" }); await turn.done; expect(turn.events.at(-1)?.type).toBe("finished"); }
finally { process.env.PATH = previous; }
});
it.each(["bad", "failed", "huge"])("fails safely on %s output", async message => { const turn = run(message); await turn.done; expect(turn.events.at(-1)?.type).toBe("error"); });
it("cancels and reaps the process", async () => { const turn = run("hang"); turn.cancel(); await turn.done; expect(turn.events.at(-1)).toEqual({ type: "finished", cancelled: true }); });
it("times out and reaps the process", async () => { const turn = run("hang", { timeoutMs: 100 }); await turn.done; expect(turn.events.at(-1)).toMatchObject({ code: "timeout" }); });
});
describe("chat route", () => {
it("rejects unauthenticated upgrades and foreign origins", async () => {
const dir = temp(); const app = await buildApp({ config: { dataDir: dir } });
try {
expect((await app.inject("/api/chat")).statusCode).toBe(401);
await expect(app.injectWS("/api/chat")).rejects.toThrow("401");
const cookie = `shellbook_session=${signSession(loadSessionSecret(dir), Date.now() + 60000)}`;
expect((await app.inject({ url: "/api/chat", headers: { cookie, origin: "https://evil.example" } })).statusCode).toBe(403);
} finally { await app.close(); }
});
it("persists metadata, prevents concurrent turns, and cancels on disconnect", async () => {
const dir = temp(); const config = loadConfig({ dataDir: dir, workspaceDir: process.cwd() });
const app = Fastify(); await app.register(websocket); await app.register(chatPlugin, { config, processOptions }); await app.ready();
const a = await app.injectWS("/api/chat"); const b = await app.injectWS("/api/chat");
const first: any[] = [], second: any[] = [];
a.on("message", raw => first.push(JSON.parse(raw.toString()))); b.on("message", raw => second.push(JSON.parse(raw.toString())));
try {
a.send(JSON.stringify({ type: "send", message: "hang", allowShell: false }));
await vi.waitFor(() => expect(first.some(e => e.type === "conversation")).toBe(true));
const id = first.find(e => e.type === "conversation").conversation.id;
b.send(JSON.stringify({ type: "send", message: "hello", allowShell: false, conversationId: id }));
await vi.waitFor(() => expect(second.some(e => e.code === "busy")).toBe(true));
[...app.websocketServer.clients][0]!.terminate();
await vi.waitFor(() => expect(a.readyState).toBe(3));
b.send(JSON.stringify({ type: "send", message: "hello", allowShell: false }));
await vi.waitFor(() => expect(second.some(e => e.type === "finished")).toBe(true));
const saved = JSON.parse(readFileSync(join(dir, "chat-conversations.json"), "utf8"));
expect(saved).toHaveLength(2); expect(saved[1].sessionId).toBeTruthy();
expect(Object.keys(saved[1]).sort()).toEqual(["createdAt", "id", "sessionId", "title", "updatedAt"]);
} finally { a.terminate(); b.terminate(); await app.close(); }
const restart = Fastify(); await restart.register(websocket); await restart.register(chatPlugin, { config, processOptions });
try { await restart.ready(); } finally { await restart.close(); }
});
});
+4
View File
@@ -0,0 +1,4 @@
{"type":"system","subtype":"init","session_id":"11111111-1111-4111-8111-111111111111"}
{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello notebook"}}}
{"type":"assistant","message":{"content":[{"type":"text","text":"Hello notebook"},{"type":"tool_use","id":"tool-1","name":"Edit","input":{"file_path":"notebooks/setup/nginx.md","old_string":"private contents","new_string":"other contents"}}]}}
{"type":"result","subtype":"success","is_error":false,"session_id":"11111111-1111-4111-8111-111111111111","total_cost_usd":0.002,"duration_ms":1234,"result":"Hello notebook"}
+15
View File
@@ -0,0 +1,15 @@
// Test-only executable. No external network or real CLI calls.
const fs = require('node:fs');
let input = '';
process.stdin.on('data', chunk => input += chunk);
process.stdin.on('end', () => {
const message = JSON.parse(input).message.content;
if (message === 'hang') { setInterval(() => {}, 1000); return; }
if (message === 'login') { console.log(JSON.stringify({ type: 'result', subtype: 'error_during_execution', is_error: true, result: 'Not logged in · Please run /login' })); process.exitCode = 1; return; }
if (message === 'stderr-login') { process.stderr.write('Authentication required'); process.exitCode = 1; return; }
if (message === 'bad') { console.log('not JSON'); return; }
if (message === 'huge') { process.stdout.write('x'.repeat(1024 * 1024 + 1)); return; }
if (message === 'failed') { process.exitCode = 2; return; }
const lines = fs.readFileSync(__dirname + '/chat.jsonl', 'utf8');
process.stdout.write(lines);
});