Skip to content

Self-hosted MCP server + dashboard giving Claude Code, Cursor & Hermes agents shared long-term memory over a git-backed markdown vault. Agent-native, Obsidian-compatible second brain — markdown RAG, no vector DB.

feat(curator): named chat agent grounded in your brain

Ronalds Palacis610e2afa8d02
diff --git a/app/(app)/page.tsx b/app/(app)/page.tsx
index c44bb4b..93e2304 100644
--- a/app/(app)/page.tsx
+++ b/app/(app)/page.tsx
@@ -2,8 +2,9 @@
import Link from "next/link";
import useSWR from "swr";
-import { ArrowRight, Check, GitBranch, Plug, Zap } from "lucide-react";
+import { ArrowRight, Brain, Check, GitBranch, Plug } from "lucide-react";
import { fetcher } from "@/lib/client";
+import { CuratorChat } from "@/components/curator-chat";
interface Repo {
id: string;
@@ -89,6 +90,9 @@ export default function Home() {
? `${sync?.dirty || 0} local · ↑${sync?.ahead || 0} ↓${sync?.behind || 0}`
: "synced";
+ // Curator on → the home is a chat window over your brain.
+ if (feat?.harness) return <CuratorChat />;
+
return (
<div className="scrollbar-none h-full overflow-y-auto">
<div className="mx-auto flex min-h-full max-w-2xl flex-col justify-center gap-6 px-8 py-12">
@@ -122,11 +126,11 @@ export default function Home() {
cta={tokenCount > 0 ? "Manage" : "Connect an agent"}
/>
<Pillar
- icon={<Zap size={16} />}
- title="AI capture"
+ icon={<Brain size={16} />}
+ title="Curator"
ok={!!feat?.harness}
state={feat?.harness ? "on" : "off"}
- desc="Dump a rough note and the brain files it into the right place, with clean frontmatter."
+ desc="A chat agent that reads your notes to answer, and files rough dumps into the right place. Runs on your Anthropic key."
href="/settings"
cta={feat?.harness ? "Configure" : "Enable"}
/>
diff --git a/app/(app)/settings/page.tsx b/app/(app)/settings/page.tsx
index 5b49866..fe42e96 100644
--- a/app/(app)/settings/page.tsx
+++ b/app/(app)/settings/page.tsx
@@ -169,9 +169,10 @@ export default function SettingsPage() {
<section className="mt-6 space-y-4 border-t border-border pt-6">
<div className="flex items-center justify-between">
<div>
- <h2 className="text-sm font-medium">AI capture (brain_capture)</h2>
+ <h2 className="text-sm font-medium">Curator</h2>
<p className="text-xs text-muted-foreground">
- Server-side auto-filing of rough dumps. Off by default — costs Anthropic tokens.
+ The in-app chat agent that reads your notes to answer, plus auto-filing of rough dumps
+ (brain_capture). Off by default — runs on your Anthropic key.
</p>
</div>
<Toggle on={harness} onChange={setHarness} />
diff --git a/app/api/curator/chat/route.ts b/app/api/curator/chat/route.ts
new file mode 100644
index 0000000..7b94991
--- /dev/null
+++ b/app/api/curator/chat/route.ts
@@ -0,0 +1,36 @@
+import { curatorStream, type ChatMessage } from "@/lib/curator";
+
+export const dynamic = "force-dynamic";
+export const maxDuration = 300;
+
+/** SSE stream of the Curator's reply, grounded in the vault via a server-side tool loop. */
+export async function POST(req: Request) {
+ let body: { messages?: ChatMessage[]; model?: string; thinking?: boolean };
+ try {
+ body = await req.json();
+ } catch {
+ return new Response("invalid JSON", { status: 400 });
+ }
+ const messages = Array.isArray(body.messages) ? body.messages : [];
+
+ const encoder = new TextEncoder();
+ const stream = new ReadableStream({
+ async start(controller) {
+ const send = (ev: unknown) => controller.enqueue(encoder.encode(`data: ${JSON.stringify(ev)}\n\n`));
+ try {
+ for await (const ev of curatorStream({ messages, model: body.model, thinking: body.thinking })) {
+ send(ev);
+ if (ev.type === "done" || ev.type === "error") break;
+ }
+ } catch (e) {
+ send({ type: "error", message: e instanceof Error ? e.message : String(e) });
+ } finally {
+ controller.close();
+ }
+ },
+ });
+
+ return new Response(stream, {
+ headers: { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-store", connection: "keep-alive" },
+ });
+}
diff --git a/bun.lock b/bun.lock
index 2440755..26b3e91 100644
--- a/bun.lock
+++ b/bun.lock
@@ -5,6 +5,7 @@
"": {
"name": "engram",
"dependencies": {
+ "@anthropic-ai/sdk": "^0.110.0",
"@base-ui/react": "^1.5.0",
"@modelcontextprotocol/sdk": "^1.13.0",
"chokidar": "^5.0.0",
@@ -50,6 +51,8 @@
"packages": {
"@alloc/quick-lru": ["@alloc/[email protected]", "", {}, "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw=="],
+ "@anthropic-ai/sdk": ["@anthropic-ai/[email protected]", "", { "dependencies": { "json-schema-to-ts": "^3.1.1", "standardwebhooks": "^1.0.0" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-hOP4bNYXDFHDxxiEgzlILXrxZIYCDnhe8sry0RDRKD/QnsEpvZcQpablCdm9X/WuD/YgOiSIkkqsL1mLLlTqJw=="],
+
"@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="],
"@babel/compat-data": ["@babel/[email protected]", "", {}, "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg=="],
@@ -350,6 +353,8 @@
"@sindresorhus/merge-streams": ["@sindresorhus/[email protected]", "", {}, "sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ=="],
+ "@stablelib/base64": ["@stablelib/[email protected]", "", {}, "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ=="],
+
"@swc/helpers": ["@swc/[email protected]", "", { "dependencies": { "tslib": "^2.8.0" } }, "sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g=="],
"@tailwindcss/node": ["@tailwindcss/[email protected]", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "enhanced-resolve": "5.21.6", "jiti": "^2.7.0", "lightningcss": "1.32.0", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.3.2" } }, "sha512-yWP/sqEcBLaD8JuA6zNwxoYKr75qxTioYwlRwekj5Jr/I5GXnoJfjetH/psLUIv74cYTH2lBUEzBkinthoYcBg=="],
@@ -784,6 +789,8 @@
"fast-levenshtein": ["[email protected]", "", {}, "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw=="],
+ "fast-sha256": ["[email protected]", "", {}, "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ=="],
+
"fast-uri": ["[email protected]", "", {}, "sha512-i70LwGWUduXqzicKXWshooq+sWL1K3WUU5rKZNG/0i3a1OSoX3HqhH5WbWwTmqWfor4urUakGPiRQcleRZTwOg=="],
"fastq": ["[email protected]", "", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw=="],
@@ -1022,6 +1029,8 @@
"json-parse-even-better-errors": ["[email protected]", "", {}, "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w=="],
+ "json-schema-to-ts": ["[email protected]", "", { "dependencies": { "@babel/runtime": "^7.18.3", "ts-algebra": "^2.0.0" } }, "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g=="],
+
"json-schema-traverse": ["[email protected]", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="],
"json-schema-typed": ["[email protected]", "", {}, "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA=="],
@@ -1432,6 +1441,8 @@
"stable-hash": ["[email protected]", "", {}, "sha512-+L3ccpzibovGXFK+Ap/f8LOS0ahMrHTf3xu7mMLSpEGU0EO9ucaysSylKo9eRDFNhWve/y275iPmIZ4z39a9iA=="],
+ "standardwebhooks": ["[email protected]", "", { "dependencies": { "@stablelib/base64": "^1.0.0", "fast-sha256": "^1.3.0" } }, "sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg=="],
+
"statuses": ["[email protected]", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
"stdin-discarder": ["[email protected]", "", {}, "sha512-UhDfHmA92YAlNnCfhmq0VeNL5bDbiZGg7sZ2IvPsXubGkiNa9EC+tUTsjBRsYUAz87btI6/1wf4XoVvQ3uRnmQ=="],
@@ -1498,6 +1509,8 @@
"trough": ["[email protected]", "", {}, "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw=="],
+ "ts-algebra": ["[email protected]", "", {}, "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw=="],
+
"ts-api-utils": ["[email protected]", "", { "peerDependencies": { "typescript": ">=4.8.4" } }, "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA=="],
"ts-morph": ["[email protected]", "", { "dependencies": { "@ts-morph/common": "~0.27.0", "code-block-writer": "^13.0.3" } }, "sha512-ztMO++owQnz8c/gIENcM9XfCEzgoGphTv+nKpYNM1bgsdOVC/jRZuEBf6N+mLLDNg68Kl+GgUZfOySaRiG1/Ug=="],
diff --git a/components/curator-chat.tsx b/components/curator-chat.tsx
new file mode 100644
index 0000000..222b28d
--- /dev/null
+++ b/components/curator-chat.tsx
@@ -0,0 +1,216 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { ArrowUp, Brain, Paperclip, Square } from "lucide-react";
+import { Markdown } from "@/components/markdown";
+
+const MODELS = [
+ { id: "claude-opus-4-8", label: "Opus 4.8" },
+ { id: "claude-sonnet-5", label: "Sonnet 5" },
+ { id: "claude-haiku-4-5", label: "Haiku 4.5" },
+];
+
+interface Msg {
+ role: "user" | "assistant";
+ content: string;
+}
+
+export function CuratorChat() {
+ const [messages, setMessages] = useState<Msg[]>([]);
+ const [input, setInput] = useState("");
+ const [model, setModel] = useState(MODELS[0].id);
+ const [thinking, setThinking] = useState(false);
+ const [streaming, setStreaming] = useState(false);
+ const [streamText, setStreamText] = useState("");
+ const [activity, setActivity] = useState<string>(""); // "thinking" | "reading …"
+ const [error, setError] = useState("");
+ const abortRef = useRef<AbortController | null>(null);
+ const scrollRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" });
+ }, [messages, streamText, activity]);
+
+ async function send() {
+ const text = input.trim();
+ if (!text || streaming) return;
+ setError("");
+ const next: Msg[] = [...messages, { role: "user", content: text }];
+ setMessages(next);
+ setInput("");
+ setStreaming(true);
+ setStreamText("");
+ setActivity("");
+
+ const ctrl = new AbortController();
+ abortRef.current = ctrl;
+ let acc = "";
+ try {
+ const res = await fetch("/api/curator/chat", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ messages: next, model, thinking }),
+ signal: ctrl.signal,
+ });
+ if (!res.ok || !res.body) throw new Error(`request failed (${res.status})`);
+ const reader = res.body.getReader();
+ const decoder = new TextDecoder();
+ let buf = "";
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ buf += decoder.decode(value, { stream: true });
+ const parts = buf.split("\n\n");
+ buf = parts.pop() || "";
+ for (const part of parts) {
+ const line = part.trim();
+ if (!line.startsWith("data:")) continue;
+ const ev = JSON.parse(line.slice(5).trim());
+ if (ev.type === "text") {
+ acc += ev.text;
+ setActivity("");
+ setStreamText(acc);
+ } else if (ev.type === "thinking") {
+ setActivity("thinking…");
+ } else if (ev.type === "tool") {
+ const verb = ev.name === "brain_search" ? "searching the vault…" : ev.name === "brain_read" ? "reading a note…" : "checking the vault…";
+ setActivity(verb);
+ } else if (ev.type === "error") {
+ setError(ev.message || "error");
+ }
+ }
+ }
+ } catch (e) {
+ if ((e as Error).name !== "AbortError") setError(e instanceof Error ? e.message : "stream failed");
+ } finally {
+ if (acc.trim()) setMessages((m) => [...m, { role: "assistant", content: acc }]);
+ setStreamText("");
+ setActivity("");
+ setStreaming(false);
+ abortRef.current = null;
+ }
+ }
+
+ function stop() {
+ abortRef.current?.abort();
+ }
+
+ async function attach(e: React.ChangeEvent<HTMLInputElement>) {
+ const file = e.target.files?.[0];
+ e.target.value = "";
+ if (!file) return;
+ if (file.size > 200_000) {
+ setError("File too large (max 200KB text).");
+ return;
+ }
+ const content = await file.text();
+ setInput((v) => `Attached file \`${file.name}\`:\n\n\`\`\`\n${content}\n\`\`\`\n\n${v}`);
+ }
+
+ return (
+ <div className="flex h-full flex-col">
+ {/* Controls */}
+ <div className="flex shrink-0 items-center gap-2 border-b border-border px-4 py-2">
+ <Brain size={15} className="text-muted-foreground" />
+ <span className="text-sm font-medium">Curator</span>
+ <div className="ml-auto flex items-center gap-2">
+ <select
+ value={model}
+ onChange={(e) => setModel(e.target.value)}
+ className="rounded-md border border-border bg-background px-2 py-1 text-xs outline-none"
+ >
+ {MODELS.map((m) => (
+ <option key={m.id} value={m.id}>{m.label}</option>
+ ))}
+ </select>
+ <button
+ onClick={() => setThinking((t) => !t)}
+ title="Extended thinking"
+ className={`inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs transition-colors ${thinking ? "border-primary/40 text-foreground" : "border-border text-muted-foreground hover:text-foreground"}`}
+ >
+ <span className={`size-1.5 rounded-full ${thinking ? "bg-emerald-500" : "bg-muted-foreground/40"}`} /> thinking
+ </button>
+ {messages.length > 0 && (
+ <button onClick={() => { setMessages([]); setError(""); }} className="rounded-md border border-border px-2 py-1 text-xs text-muted-foreground hover:text-foreground">
+ Clear
+ </button>
+ )}
+ </div>
+ </div>
+
+ {/* Messages */}
+ <div ref={scrollRef} className="scrollbar-none flex-1 overflow-y-auto px-4 py-4">
+ <div className="mx-auto max-w-2xl space-y-4">
+ {messages.length === 0 && !streaming && (
+ <div className="py-10 text-center text-sm text-muted-foreground">
+ Ask the Curator about your brain. It reads your notes to answer — try
+ <span className="text-foreground"> “what did we decide about pricing?”</span> or
+ <span className="text-foreground"> “summarize the Shroom Shop thread.”</span>
+ </div>
+ )}
+ {messages.map((m, i) =>
+ m.role === "user" ? (
+ <div key={i} className="flex justify-end">
+ <div className="max-w-[85%] whitespace-pre-wrap rounded-2xl bg-secondary px-3.5 py-2 text-sm">{m.content}</div>
+ </div>
+ ) : (
+ <div key={i} className="text-sm">
+ <Markdown content={m.content} resolve={(s) => `/n/${s}`} />
+ </div>
+ ),
+ )}
+ {streaming && (
+ <div className="text-sm">
+ {streamText ? (
+ <Markdown content={streamText} resolve={(s) => `/n/${s}`} />
+ ) : (
+ <div className="flex items-center gap-2 text-muted-foreground">
+ <span className="size-1.5 animate-pulse rounded-full bg-muted-foreground" />
+ {activity || "…"}
+ </div>
+ )}
+ </div>
+ )}
+ {error && <p className="text-xs text-destructive">{error}</p>}
+ </div>
+ </div>
+
+ {/* Composer */}
+ <div className="shrink-0 border-t border-border px-4 py-3">
+ <div className="mx-auto flex max-w-2xl items-end gap-2">
+ <label className="inline-flex size-9 shrink-0 cursor-pointer items-center justify-center rounded-md border border-border text-muted-foreground transition-colors hover:text-foreground" title="Attach a text file">
+ <Paperclip size={15} />
+ <input type="file" accept=".md,.txt,.json,.csv,.ts,.tsx,.js,.py,text/*" className="hidden" onChange={attach} />
+ </label>
+ <textarea
+ value={input}
+ onChange={(e) => setInput(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && !e.shiftKey) {
+ e.preventDefault();
+ send();
+ }
+ }}
+ placeholder="Ask the Curator…"
+ rows={1}
+ className="scrollbar-none max-h-40 min-h-9 flex-1 resize-none rounded-md border border-border bg-background px-3 py-2 text-sm outline-none placeholder:text-muted-foreground focus:border-ring"
+ />
+ {streaming ? (
+ <button onClick={stop} className="inline-flex size-9 shrink-0 items-center justify-center rounded-md bg-primary text-primary-foreground" title="Stop">
+ <Square size={13} className="fill-current" />
+ </button>
+ ) : (
+ <button
+ onClick={send}
+ disabled={!input.trim()}
+ className="inline-flex size-9 shrink-0 items-center justify-center rounded-md bg-primary text-primary-foreground disabled:opacity-40"
+ title="Send"
+ >
+ <ArrowUp size={16} />
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/lib/curator.ts b/lib/curator.ts
new file mode 100644
index 0000000..f12f063
--- /dev/null
+++ b/lib/curator.ts
@@ -0,0 +1,140 @@
+import Anthropic from "@anthropic-ai/sdk";
+import { anthropicApiKey } from "@/lib/settings";
+import { getBacklinks, getNote, listNotes, readVaultFile, searchNotes } from "@/lib/vault/store";
+
+/**
+ * The Curator — the resident chat agent of the brain. It answers questions about the
+ * vault, grounded in the actual notes via read tools (search/read/list), streaming over
+ * SSE with an interleaved tool loop. Read-only: it helps you think, it doesn't write notes.
+ * Uses the official Anthropic SDK so model IDs + adaptive thinking are exact.
+ */
+
+export const CURATOR_MODELS = [
+ { id: "claude-opus-4-8", label: "Opus 4.8" },
+ { id: "claude-sonnet-5", label: "Sonnet 5" },
+ { id: "claude-haiku-4-5", label: "Haiku 4.5" },
+] as const;
+export const DEFAULT_CURATOR_MODEL = "claude-opus-4-8";
+const MODEL_IDS = new Set<string>(CURATOR_MODELS.map((m) => m.id));
+
+function systemPrompt(): string {
+ const schema = readVaultFile("SCHEMA.md");
+ return `You are the Curator — the resident agent of this markdown "second brain". You help the operator recall, connect, and reason over their own notes.
+
+Rules:
+- Ground every factual claim about the vault in the notes. Use brain_search to find notes, brain_read to read their full content, brain_list to see what exists. Never invent facts about the vault — if it isn't in the notes, say so plainly.
+- Cite notes in wikilink form so the user can click through, e.g. [[clients/mks/mks|MKS]] or [[decisions/foo-2026-07-09]].
+- Be direct, specific, and concise. Lead with the answer, then the supporting detail.
+- You are READ-ONLY in this chat. You help the user think; you do not create or edit notes.
+${schema ? `\nThe vault's SCHEMA (folder taxonomy + conventions):\n"""\n${schema.slice(0, 4000)}\n"""` : ""}`;
+}
+
+// Anthropic tool definitions — read-only vault access.
+const TOOLS: Anthropic.Tool[] = [
+ {
+ name: "brain_search",
+ description: "Full-text + fuzzy search across all notes. Returns ranked results (path, title, folder). Use this first to find relevant notes.",
+ input_schema: { type: "object", properties: { query: { type: "string", description: "search query" } }, required: ["query"] },
+ },
+ {
+ name: "brain_read",
+ description: "Read a note's full markdown (frontmatter + body) plus its backlinks. Path is vault-relative, e.g. 'clients/mks/mks.md'.",
+ input_schema: { type: "object", properties: { path: { type: "string", description: "vault-relative path" } }, required: ["path"] },
+ },
+ {
+ name: "brain_list",
+ description: "List all notes with metadata (path, title, folder, type, tags). Use to discover what exists.",
+ input_schema: { type: "object", properties: {} },
+ },
+];
+
+function runTool(name: string, input: Record<string, unknown>): unknown {
+ if (name === "brain_search") return searchNotes(String(input.query ?? ""));
+ if (name === "brain_read") {
+ const p = String(input.path ?? "");
+ const n = getNote(p);
+ return n ? { path: p, frontmatter: n.frontmatter, content: n.raw, backlinks: getBacklinks(p) } : { error: `not found: ${p}` };
+ }
+ if (name === "brain_list") return listNotes();
+ return { error: `unknown tool: ${name}` };
+}
+
+export interface ChatMessage {
+ role: "user" | "assistant";
+ content: string;
+}
+export type CuratorEvent =
+ | { type: "text"; text: string }
+ | { type: "thinking"; text: string }
+ | { type: "tool"; name: string }
+ | { type: "done" }
+ | { type: "error"; message: string };
+
+/** Stream a Curator turn: yields text/thinking/tool events, runs the vault tool loop server-side. */
+export async function* curatorStream(opts: {
+ messages: ChatMessage[];
+ model?: string;
+ thinking?: boolean;
+}): AsyncGenerator<CuratorEvent> {
+ const apiKey = anthropicApiKey();
+ if (!apiKey) {
+ yield { type: "error", message: "No Anthropic API key. Enable the Curator in Settings and add a key." };
+ return;
+ }
+ const model = opts.model && MODEL_IDS.has(opts.model) ? opts.model : DEFAULT_CURATOR_MODEL;
+ const client = new Anthropic({ apiKey });
+
+ const messages: Anthropic.MessageParam[] = opts.messages
+ .filter((m) => (m.role === "user" || m.role === "assistant") && typeof m.content === "string" && m.content.trim() !== "")
+ .map((m) => ({ role: m.role, content: m.content }));
+ if (messages.length === 0) {
+ yield { type: "error", message: "No message to send." };
+ return;
+ }
+
+ try {
+ for (let turn = 0; turn < 8; turn++) {
+ const stream = client.messages.stream({
+ model,
+ max_tokens: 16000,
+ system: systemPrompt(),
+ tools: TOOLS,
+ messages,
+ ...(opts.thinking ? { thinking: { type: "adaptive", display: "summarized" } } : {}),
+ });
+
+ for await (const event of stream) {
+ if (event.type === "content_block_delta") {
+ if (event.delta.type === "text_delta") yield { type: "text", text: event.delta.text };
+ else if (event.delta.type === "thinking_delta") yield { type: "thinking", text: event.delta.thinking };
+ } else if (event.type === "content_block_start" && event.content_block.type === "tool_use") {
+ yield { type: "tool", name: event.content_block.name };
+ }
+ }
+
+ const message = await stream.finalMessage();
+ if (message.stop_reason !== "tool_use") {
+ yield { type: "done" };
+ return;
+ }
+ // Echo the assistant turn back (thinking + tool_use blocks unchanged), then run the tools.
+ messages.push({ role: "assistant", content: message.content });
+ const results: Anthropic.ToolResultBlockParam[] = [];
+ for (const block of message.content) {
+ if (block.type === "tool_use") {
+ let out: unknown;
+ try {
+ out = runTool(block.name, block.input as Record<string, unknown>);
+ } catch (e) {
+ out = { error: e instanceof Error ? e.message : String(e) };
+ }
+ results.push({ type: "tool_result", tool_use_id: block.id, content: JSON.stringify(out).slice(0, 40000) });
+ }
+ }
+ messages.push({ role: "user", content: results });
+ }
+ yield { type: "done" };
+ } catch (e) {
+ yield { type: "error", message: e instanceof Error ? e.message : String(e) };
+ }
+}
diff --git a/package.json b/package.json
index 5bbdd73..7a1ab6a 100644
--- a/package.json
+++ b/package.json
@@ -34,6 +34,7 @@
"gen:secrets": "tsx scripts/gen-secrets.ts"
},
"dependencies": {
+ "@anthropic-ai/sdk": "^0.110.0",
"@base-ui/react": "^1.5.0",
"@modelcontextprotocol/sdk": "^1.13.0",
"chokidar": "^5.0.0",