AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
feat: add offline sync and agent docs
tianma377b7b9f1daa
diff --git a/README.md b/README.mdindex b70d2a39..3b94ad96 100644--- a/README.md+++ b/README.md@@ -31,8 +31,9 @@ EdgeEver 是一个开源、自托管、Cloudflare-native 的现代笔记工作- 多选合并笔记,原笔记软删除,资源关联迁移到新笔记。- 多选移动笔记,笔记本支持拖拽排序和调整层级。- PWA 可安装,支持静态应用壳离线打开和自动更新。+- 已有笔记支持离线编辑草稿和本地同步队列。- 单用户登录,密码使用 PBKDF2-SHA256 hash。-- REST API-first,支持 API Token、MCP 和 CLI。+- REST API-first,支持 API Token、OpenAPI、MCP 和 CLI。## 技术栈@@ -104,6 +105,16 @@ content_markdown API、Agent、导入导出使用content_text 搜索、摘要和索引使用```+## API 文档++OpenAPI schema:++```text+https://你的域名/api/openapi.json+```++仓库内文件:[docs/openapi.json](docs/openapi.json)。+## MCP / CLI先在 EdgeEver 左侧 **设置** 里创建 API Token。给只读 Agent 使用时建议只勾选 `read:notebooks`、`read:memos`、`read:tags`;需要写入、移动、合并或上传附件时再增加对应 `write:*` scope。@@ -157,6 +168,23 @@ list_notebookslist_tags```+本地 stdio MCP 客户端可通过 bridge 连接远程 EdgeEver:++```sh+EDGEEVER_URL=https://你的域名 \+EDGEEVER_TOKEN=<api-token> \+bun run mcp:stdio+```++也可以复用 CLI profile:++```sh+bun run cli -- profile set prod --url https://你的域名 --token <api-token>+bun run mcp:stdio -- --profile prod+```++Claude Desktop / Cursor / Codex 这类本地客户端可把 command 配成 `bun`,args 配成仓库内 `scripts/edgeever-mcp-stdio.mjs` 的绝对路径,并通过环境变量传入 `EDGEEVER_URL` 和 `EDGEEVER_TOKEN`。+最小调用示例:```shdiff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex 3526f795..48cc8323 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -1,5 +1,6 @@import {createExcerpt,+ DEFAULT_MEMO_TITLE,docToMarkdown,docToText,emptyDoc,@@ -31,6 +32,7 @@ import type { Context } from "hono";import { Hono } from "hono";import { deleteCookie, getCookie, setCookie } from "hono/cookie";import { cors } from "hono/cors";+import openApiSpec from "../../../docs/openapi.json";type Bindings = {DB: D1Database;@@ -235,6 +237,8 @@ app.get("/api/health", (c) =>}));+app.get("/api/openapi.json", (c) => c.json(openApiSpec));+app.get("/api/v1/auth/session", async (c) => {const authRequired = await isAuthRequired(c.env);@@ -655,8 +659,8 @@ app.post("/api/v1/memos", zValidator("json", MemoCreateSchema), async (c) => {const contentMarkdown = input.contentMarkdown ?? "";const contentJson = markdownToDoc(contentMarkdown);const contentText = docToText(contentJson);- const title = input.title || deriveTitle(contentText);- const excerpt = createExcerpt(contentText || title || "");+ const title = normalizeMemoTitle(input.title);+ const excerpt = createExcerpt(contentText);const contentHash = await sha256(contentMarkdown + JSON.stringify(contentJson));const id = createId("memo");const now = isoNow();@@ -787,8 +791,8 @@ app.post("/api/v1/memos/:id/revisions/:revisionId/restore", async (c) => {const contentJson = parseDoc(revision.content_json);const contentMarkdown = revision.content_markdown || docToMarkdown(contentJson);const contentText = revision.content_text || docToText(contentJson);- const title = revision.title ?? deriveTitle(contentText);- const excerpt = createExcerpt(contentText || title || "");+ const title = normalizeMemoTitle(revision.title);+ const excerpt = createExcerpt(contentText);const contentHash = await sha256(contentMarkdown + JSON.stringify(contentJson));const nextRevision = current.revision + 1;const now = isoNow();@@ -1039,9 +1043,10 @@ app.patch("/api/v1/memos/:id", zValidator("json", MemoUpdateSchema), async (c) =const contentMarkdown =input.contentMarkdown !== undefined ? input.contentMarkdown : docToMarkdown(contentJson);const contentText = docToText(contentJson);- const title = input.title ?? current.title ?? deriveTitle(contentText);+ const title =+ input.title !== undefined ? normalizeMemoTitle(input.title) : normalizeMemoTitle(current.title);const tags = input.tags === undefined ? parseJsonArray(current.tags_json) : normalizeTags(input.tags);- const excerpt = createExcerpt(contentText || title || "");+ const excerpt = createExcerpt(contentText);const notebookId = input.notebookId ?? current.notebook_id;const nextRevision = current.revision + 1;const contentHash = await sha256(contentMarkdown + JSON.stringify(contentJson));@@ -2629,8 +2634,8 @@ const createMemoRecord = async (const contentMarkdown = input.contentMarkdown ?? "";const contentJson = markdownToDoc(contentMarkdown);const contentText = docToText(contentJson);- const title = input.title || deriveTitle(contentText);- const excerpt = createExcerpt(contentText || title || "");+ const title = normalizeMemoTitle(input.title);+ const excerpt = createExcerpt(contentText);const contentHash = await sha256(contentMarkdown + JSON.stringify(contentJson));const id = createId("memo");const now = isoNow();@@ -2698,9 +2703,10 @@ const updateMemoRecord = async (const contentMarkdown =input.contentMarkdown !== undefined ? input.contentMarkdown : docToMarkdown(contentJson);const contentText = docToText(contentJson);- const title = input.title ?? current.title ?? deriveTitle(contentText);+ const title =+ input.title !== undefined ? normalizeMemoTitle(input.title) : normalizeMemoTitle(current.title);const tags = input.tags === undefined ? parseJsonArray(current.tags_json) : normalizeTags(input.tags);- const excerpt = createExcerpt(contentText || title || "");+ const excerpt = createExcerpt(contentText);const notebookId = input.notebookId ?? current.notebook_id;const nextRevision = current.revision + 1;const contentHash = await sha256(contentMarkdown + JSON.stringify(contentJson));@@ -2920,9 +2926,9 @@ const slugify = (value: string) =>.replace(/^-+|-+$/g, "").slice(0, 80);-const deriveTitle = (text: string) => {- const title = text.trim().split(/\s+/).slice(0, 10).join(" ");- return title || "Untitled memo";+const normalizeMemoTitle = (value: string | null | undefined) => {+ const title = value?.trim();+ return title || DEFAULT_MEMO_TITLE;};const clampNumber = (value: number, min: number, max: number) => {diff --git a/apps/web/src/app/App.tsx b/apps/web/src/app/App.tsxindex a49c1fec..376aff1a 100644--- a/apps/web/src/app/App.tsx+++ b/apps/web/src/app/App.tsx@@ -1,4 +1,5 @@import {+ DEFAULT_MEMO_TITLE,docToMarkdown,type ApiToken,type AuthSession,@@ -20,7 +21,10 @@ import {CheckSquare,ChevronDown,ChevronRight,+ CheckCircle2,Code2,+ AlertTriangle,+ CloudOff,ExternalLink,File as FileIcon,FilePlus2,@@ -44,6 +48,7 @@ import {Plus,Quote,Redo2,+ RefreshCw,RotateCcw,Save,Search,@@ -69,7 +74,16 @@ import {} from "react";import { api } from "@/lib/api";import { compressImageForUpload } from "@/lib/image-compression";-import { localDb } from "@/lib/local-db";+import { localDb, type MemoUpdateSyncPayload } from "@/lib/local-db";+import {+ emptySyncQueueSummary,+ getMemoUpdateQueueId,+ observeSyncQueue,+ queueMemoUpdate,+ shouldQueueMemoSaveError,+ syncQueuedChanges,+ type SyncQueueSummary,+} from "@/lib/sync-queue";import { buildNotebookTree, cn, formatDateTime, parseTagsText, type NotebookNode } from "@/lib/utils";import { Button } from "@/components/ui/button";@@ -169,6 +183,32 @@ const WorkspaceApp = ({const [tagsOpen, setTagsOpen] = useState(false);const [settingsOpen, setSettingsOpen] = useState(false);const [search, setSearch] = useState("");+ const [syncSummary, setSyncSummary] = useState<SyncQueueSummary>(emptySyncQueueSummary);+ const [isOnline, setIsOnline] = useState(() => (typeof navigator === "undefined" ? true : navigator.onLine));+ const [isSyncingQueuedChanges, setIsSyncingQueuedChanges] = useState(false);++ const runQueuedSync = useCallback(async () => {+ if (typeof navigator !== "undefined" && !navigator.onLine) {+ setIsOnline(false);+ return;+ }++ setIsSyncingQueuedChanges(true);++ try {+ await syncQueuedChanges({+ onSynced: async (memo) => {+ queryClient.setQueryData(["memo", memo.id], { memo });+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: ["memos"] }),+ queryClient.invalidateQueries({ queryKey: ["memo", memo.id] }),+ ]);+ },+ });+ } finally {+ setIsSyncingQueuedChanges(false);+ }+ }, [queryClient]);const notebooksQuery = useQuery({queryKey: ["notebooks"],@@ -211,6 +251,40 @@ const WorkspaceApp = ({writeImageCompressionPreference(imageCompressionEnabled);}, [imageCompressionEnabled]);+ useEffect(() => observeSyncQueue(setSyncSummary), []);++ useEffect(() => {+ const updateOnlineState = () => {+ const online = navigator.onLine;+ setIsOnline(online);++ if (online) {+ void runQueuedSync();+ }+ };++ window.addEventListener("online", updateOnlineState);+ window.addEventListener("offline", updateOnlineState);+ updateOnlineState();++ return () => {+ window.removeEventListener("online", updateOnlineState);+ window.removeEventListener("offline", updateOnlineState);+ };+ }, [runQueuedSync]);++ useEffect(() => {+ if (syncSummary.total === 0) {+ return;+ }++ const timer = window.setInterval(() => {+ void runQueuedSync();+ }, 15_000);++ return () => window.clearInterval(timer);+ }, [runQueuedSync, syncSummary.total]);+const memosQuery = useQuery({queryKey: ["memos", memoView, selectedNotebookId, search],queryFn: () =>@@ -370,7 +444,7 @@ const WorkspaceApp = ({createMemoMutation.mutate({notebookId: selectedNotebookId,- title: "Untitled memo",+ title: DEFAULT_MEMO_TITLE,contentMarkdown: "",tags: [],});@@ -453,6 +527,10 @@ const WorkspaceApp = ({isLoggingOut={isLoggingOut}imageCompressionEnabled={imageCompressionEnabled}onImageCompressionChange={setImageCompressionEnabled}+ syncSummary={syncSummary}+ isOnline={isOnline}+ isSyncingQueuedChanges={isSyncingQueuedChanges}+ onSyncQueuedChanges={() => void runQueuedSync()}onOpenAssets={() => setAssetsOpen(true)}onOpenTags={() => setTagsOpen(true)}onOpenSettings={() => setSettingsOpen(true)}@@ -699,6 +777,10 @@ const NotebookPane = ({isLoggingOut,imageCompressionEnabled,onImageCompressionChange,+ syncSummary,+ isOnline,+ isSyncingQueuedChanges,+ onSyncQueuedChanges,onOpenAssets,onOpenTags,onOpenSettings,@@ -719,6 +801,10 @@ const NotebookPane = ({isLoggingOut: boolean;imageCompressionEnabled: boolean;onImageCompressionChange: (enabled: boolean) => void;+ syncSummary: SyncQueueSummary;+ isOnline: boolean;+ isSyncingQueuedChanges: boolean;+ onSyncQueuedChanges: () => void;onOpenAssets: () => void;onOpenTags: () => void;onOpenSettings: () => void;@@ -772,6 +858,12 @@ const NotebookPane = ({</div><footer className="border-t border-emerald-100 px-4 pb-[max(0.75rem,env(safe-area-inset-bottom))] pt-3">+ <SyncStatusBar+ summary={syncSummary}+ isOnline={isOnline}+ isSyncing={isSyncingQueuedChanges}+ onSyncNow={onSyncQueuedChanges}+ /><label className="mb-3 flex min-h-10 items-center justify-between gap-3 rounded-md border border-emerald-100 bg-emerald-50/70 px-3 py-2"><span className="min-w-0 text-sm font-medium text-slate-700">压缩图片</span><input@@ -806,6 +898,78 @@ const NotebookPane = ({);};+const SyncStatusBar = ({+ summary,+ isOnline,+ isSyncing,+ onSyncNow,+}: {+ summary: SyncQueueSummary;+ isOnline: boolean;+ isSyncing: boolean;+ onSyncNow: () => void;+}) => {+ const hasQueuedWork = summary.total > 0;+ const label = getSyncStatusLabel(summary, isOnline, isSyncing);+ const statusClassName = !isOnline+ ? "border-slate-200 bg-slate-50 text-slate-600"+ : summary.conflict > 0+ ? "border-amber-200 bg-amber-50 text-amber-800"+ : hasQueuedWork+ ? "border-emerald-200 bg-emerald-50 text-emerald-800"+ : "border-emerald-100 bg-white text-slate-500";++ return (+ <div className={cn("mb-3 flex min-h-10 items-center gap-2 rounded-md border px-3 py-2", statusClassName)}>+ {!isOnline ? (+ <CloudOff className="h-4 w-4 shrink-0" />+ ) : summary.conflict > 0 ? (+ <AlertTriangle className="h-4 w-4 shrink-0" />+ ) : hasQueuedWork || isSyncing ? (+ <RefreshCw className={cn("h-4 w-4 shrink-0", isSyncing && "animate-spin")} />+ ) : (+ <CheckCircle2 className="h-4 w-4 shrink-0" />+ )}+ <span className="min-w-0 flex-1 truncate text-xs font-medium">{label}</span>+ {hasQueuedWork ? (+ <button+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md hover:bg-white/70 disabled:opacity-50"+ type="button"+ title="立即同步"+ disabled={!isOnline || isSyncing}+ onClick={onSyncNow}+ >+ <RefreshCw className="h-3.5 w-3.5" />+ </button>+ ) : null}+ </div>+ );+};++const getSyncStatusLabel = (summary: SyncQueueSummary, isOnline: boolean, isSyncing: boolean) => {+ if (!isOnline) {+ return summary.total > 0 ? `离线,${summary.total} 项待同步` : "离线";+ }++ if (isSyncing || summary.syncing > 0) {+ return "同步中";+ }++ if (summary.conflict > 0) {+ return `${summary.conflict} 项同步冲突`;+ }++ if (summary.error > 0) {+ return `${summary.error} 项等待重试`;+ }++ if (summary.pending > 0) {+ return `${summary.pending} 项待同步`;+ }++ return "已同步";+};+const NotebookTreeItem = ({node,depth,@@ -991,6 +1155,7 @@ const MemoListPane = ({onMoveSelectedMemos: (notebookId: string) => void;}) => {const [moveTargetNotebookId, setMoveTargetNotebookId] = useState(notebook?.id ?? notebooks[0]?.id ?? "");+ const memoGroups = useMemo(() => groupMemosByMonth(memos), [memos]);useEffect(() => {if (notebook?.id) {@@ -999,125 +1164,159 @@ const MemoListPane = ({}, [notebook?.id]);return (- <div className="relative flex h-full min-h-0 flex-col">- <header className="border-b border-emerald-100 bg-white px-4 pb-3 pt-[max(0.75rem,env(safe-area-inset-top))] lg:py-3">- <div className="mb-3 flex items-center justify-between gap-3">- <div className="flex min-w-0 items-center gap-2">- <Button className="lg:hidden" size="icon" variant="ghost" title="打开笔记本" onClick={onBackToNotebooks}>- <PanelLeft className="h-4 w-4" />+ <div className="relative flex h-full min-h-0 flex-col">+ <header className="border-b border-emerald-100 bg-white px-4 pb-3 pt-[max(0.75rem,env(safe-area-inset-top))] lg:py-3">+ <div className="mb-3 flex items-center justify-between gap-3">+ <div className="flex min-w-0 items-center gap-2">+ <Button className="lg:hidden" size="icon" variant="ghost" title="打开笔记本" onClick={onBackToNotebooks}>+ <PanelLeft className="h-4 w-4" />+ </Button>+ <div className="min-w-0">+ <div className="truncate text-lg font-semibold text-slate-950 lg:text-sm">+ {view === "trash" ? "回收站" : notebook?.name ?? "全部笔记"}+ </div>+ <div className="text-xs text-slate-500">+ {memos.length} {view === "trash" ? "条已删除" : "条笔记"}+ </div>+ </div>+ </div>+ <Button+ className="hidden lg:inline-flex"+ size="icon"+ variant="solid"+ title="新建笔记"+ onClick={onCreateMemo}+ disabled={!notebook || isCreating || view === "trash"}+ >+ <FilePlus2 className="h-4 w-4" /></Button>- <div className="min-w-0">- <div className="truncate text-lg font-semibold text-slate-950 lg:text-sm">- {view === "trash" ? "回收站" : notebook?.name ?? "全部笔记"}+ </div>+ <label className="flex h-9 items-center gap-2 rounded-md border border-emerald-100 bg-emerald-50/70 px-3 text-sm text-slate-500">+ <Search className="h-4 w-4" />+ <input+ value={search}+ onChange={(event) => onSearch(event.target.value)}+ className="min-w-0 flex-1 bg-transparent text-slate-900 outline-none placeholder:text-slate-400"+ placeholder="搜索笔记"+ />+ </label>+ </header>++ <div className="relative min-h-0 flex-1 overflow-y-auto p-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]">+ {selectedMemoIds.size > 0 ? (+ <div className="sticky top-0 z-10 mb-3 flex flex-wrap items-center justify-between gap-2 rounded-md border border-emerald-100 bg-white px-3 py-2 shadow-panel">+ <div className="flex items-center gap-2 text-sm font-medium">+ <CheckSquare className="h-4 w-4 text-emerald-700" />+ {selectedMemoIds.size} selected</div>- <div className="text-xs text-slate-500">- {memos.length} {view === "trash" ? "trashed" : "memos"}+ <div className="flex min-w-0 flex-wrap items-center gap-2">+ <select+ className="h-8 max-w-40 rounded-md border border-emerald-100 bg-emerald-50/70 px-2 text-xs text-emerald-900 outline-none disabled:opacity-50"+ value={moveTargetNotebookId}+ disabled={view === "trash" || notebooks.length === 0 || isMoving}+ onChange={(event) => setMoveTargetNotebookId(event.target.value)}+ title="移动到笔记本"+ >+ {notebooks.map((item) => (+ <option key={item.id} value={item.id}>+ {item.name}+ </option>+ ))}+ </select>+ <Button+ size="sm"+ variant="soft"+ onClick={() => onMoveSelectedMemos(moveTargetNotebookId)}+ disabled={!moveTargetNotebookId || isMoving || view === "trash"}+ >+ <Folder className="h-4 w-4" />+ 移动+ </Button>+ <Button+ size="sm"+ variant="solid"+ onClick={onMerge}+ disabled={selectedMemoIds.size < 2 || isMerging || view === "trash"}+ >+ <Merge className="h-4 w-4" />+ 合并+ </Button></div></div>- </div>- <Button- className="hidden lg:inline-flex"- size="icon"- variant="solid"+ ) : null}++ {isLoading ? (+ <div className="px-2 py-4 text-sm text-slate-500">加载中</div>+ ) : memos.length === 0 ? (+ <div className="rounded-md border border-dashed border-slate-300 bg-white px-4 py-8 text-center text-sm text-slate-500">+ {view === "trash" ? "回收站为空" : "暂无笔记"}+ </div>+ ) : (+ <div className="overflow-hidden rounded-sm border-y border-slate-200 bg-white">+ {memoGroups.map((group) => (+ <section key={group.key}>+ <div className="sticky top-0 z-[4] flex h-9 items-center justify-between border-b border-slate-200 bg-white/95 px-4 text-sm font-semibold text-slate-500 backdrop-blur">+ <span>{group.label}</span>+ <span>{group.items.length}</span>+ </div>+ <div>+ {group.items.map((memo) => (+ <MemoCard+ key={memo.id}+ memo={memo}+ selected={memo.id === selectedMemoId}+ checked={selectedMemoIds.has(memo.id)}+ multiSelectKeyDown={multiSelectKeyDown}+ onOpen={() => onOpenMemo(memo.id)}+ onToggle={() => onToggleMemo(memo.id)}+ />+ ))}+ </div>+ </section>+ ))}+ </div>+ )}+ </div>+ {selectedMemoIds.size === 0 ? (+ <button+ className="absolute bottom-[max(1rem,env(safe-area-inset-bottom))] right-4 flex h-14 items-center gap-2 rounded-full border border-emerald-200 bg-emerald-100 px-5 text-sm font-semibold text-emerald-950 shadow-panel transition hover:bg-emerald-200 disabled:opacity-50 lg:hidden"title="新建笔记"onClick={onCreateMemo}- disabled={!notebook || isCreating || view === "trash"}+ disabled={!notebook || isCreating}+ hidden={view === "trash"}>- <FilePlus2 className="h-4 w-4" />- </Button>- </div>- <label className="flex h-9 items-center gap-2 rounded-md border border-emerald-100 bg-emerald-50/70 px-3 text-sm text-slate-500">- <Search className="h-4 w-4" />- <input- value={search}- onChange={(event) => onSearch(event.target.value)}- className="min-w-0 flex-1 bg-transparent text-slate-900 outline-none placeholder:text-slate-400"- placeholder="Search memos"- />- </label>- </header>-- <div className="relative min-h-0 flex-1 overflow-y-auto p-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]">- {selectedMemoIds.size > 0 ? (- <div className="sticky top-0 z-10 mb-3 flex flex-wrap items-center justify-between gap-2 rounded-md border border-emerald-100 bg-white px-3 py-2 shadow-panel">- <div className="flex items-center gap-2 text-sm font-medium">- <CheckSquare className="h-4 w-4 text-emerald-700" />- {selectedMemoIds.size} selected- </div>- <div className="flex min-w-0 flex-wrap items-center gap-2">- <select- className="h-8 max-w-40 rounded-md border border-emerald-100 bg-emerald-50/70 px-2 text-xs text-emerald-900 outline-none disabled:opacity-50"- value={moveTargetNotebookId}- disabled={view === "trash" || notebooks.length === 0 || isMoving}- onChange={(event) => setMoveTargetNotebookId(event.target.value)}- title="移动到笔记本"- >- {notebooks.map((item) => (- <option key={item.id} value={item.id}>- {item.name}- </option>- ))}- </select>- <Button- size="sm"- variant="soft"- onClick={() => onMoveSelectedMemos(moveTargetNotebookId)}- disabled={!moveTargetNotebookId || isMoving || view === "trash"}- >- <Folder className="h-4 w-4" />- 移动- </Button>- <Button- size="sm"- variant="solid"- onClick={onMerge}- disabled={selectedMemoIds.size < 2 || isMerging || view === "trash"}- >- <Merge className="h-4 w-4" />- 合并- </Button>- </div>- </div>+ <FilePlus2 className="h-5 w-5" />+ 新建+ </button>) : null}-- {isLoading ? (- <div className="px-2 py-4 text-sm text-slate-500">加载中</div>- ) : memos.length === 0 ? (- <div className="rounded-md border border-dashed border-slate-300 bg-white px-4 py-8 text-center text-sm text-slate-500">- {view === "trash" ? "回收站为空" : "No memos"}- </div>- ) : (- <div className="space-y-2">- {memos.map((memo) => (- <MemoCard- key={memo.id}- memo={memo}- selected={memo.id === selectedMemoId}- checked={selectedMemoIds.has(memo.id)}- multiSelectKeyDown={multiSelectKeyDown}- onOpen={() => onOpenMemo(memo.id)}- onToggle={() => onToggleMemo(memo.id)}- />- ))}- </div>- )}</div>- {selectedMemoIds.size === 0 ? (- <button- className="absolute bottom-[max(1rem,env(safe-area-inset-bottom))] right-4 flex h-14 items-center gap-2 rounded-full border border-emerald-200 bg-emerald-100 px-5 text-sm font-semibold text-emerald-950 shadow-panel transition hover:bg-emerald-200 disabled:opacity-50 lg:hidden"- title="新建笔记"- onClick={onCreateMemo}- disabled={!notebook || isCreating}- hidden={view === "trash"}- >- <FilePlus2 className="h-5 w-5" />- 新建- </button>- ) : null}- </div>);};+const groupMemosByMonth = (memos: MemoSummary[]) => {+ const groups: Array<{ key: string; label: string; items: MemoSummary[] }> = [];++ for (const memo of memos) {+ const date = new Date(memo.updatedAt);+ const key = Number.isNaN(date.getTime())+ ? "unknown"+ : `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}`;+ const label = Number.isNaN(date.getTime())+ ? "未知时间"+ : new Intl.DateTimeFormat("zh-CN", { year: "numeric", month: "long" }).format(date);+ const current = groups[groups.length - 1];++ if (current?.key === key) {+ current.items.push(memo);+ continue;+ }++ groups.push({ key, label, items: [memo] });+ }++ return groups;+};+const MemoCard = ({memo,selected,@@ -1134,6 +1333,8 @@ const MemoCard = ({onToggle: () => void;}) => {const handledModifierPointerRef = useRef(false);+ const memoTitle = getMemoTitle(memo.title);+ const memoExcerpt = memo.excerpt.trim() || "空笔记";const shouldToggleSelection = (event: MouseEvent<HTMLElement>) =>event.ctrlKey || event.metaKey || multiSelectKeyDown;@@ -1191,32 +1392,31 @@ const MemoCard = ({return (<articleclassName={cn(- "rounded-md border bg-white p-3 transition",- selected ? "border-emerald-300 shadow-panel" : "border-emerald-100 hover:border-emerald-200",- checked && "border-emerald-300 bg-emerald-50/70"+ "border-b border-slate-200 transition last:border-b-0",+ selected ? "bg-slate-200" : checked ? "bg-emerald-50/80" : "bg-white hover:bg-slate-50")}>- <div className="flex items-start gap-3">+ <div className="flex min-h-[128px] items-start"><inputtype="checkbox"checked={checked}onChange={onToggle}- className="mt-1 h-5 w-5 shrink-0 rounded border-emerald-300 text-emerald-600"- aria-label={`选择 ${memo.title ?? memo.excerpt}`}+ className="ml-4 mt-5 h-4 w-4 shrink-0 rounded border-slate-300 text-emerald-600"+ aria-label={`选择 ${memoTitle}`}/><button- className={cn("min-w-0 flex-1 text-left", multiSelectKeyDown && "cursor-copy")}+ className={cn("min-w-0 flex-1 px-4 py-4 text-left", multiSelectKeyDown && "cursor-copy")}onMouseDown={handleMouseDown}onClick={handleClick}onContextMenu={handleContextMenu}title="Ctrl/Cmd 点击切换选择">- <div className="mb-1 truncate text-sm font-semibold text-slate-950">{memo.title || "Untitled memo"}</div>- <div className="line-clamp-2 min-h-[40px] text-sm leading-5 text-slate-600">{memo.excerpt || "Empty memo"}</div>- <div className="mt-3 flex flex-wrap items-center gap-2">- <time className="text-xs text-slate-400">{formatDateTime(memo.updatedAt)}</time>+ <div className="mb-2 truncate text-base font-semibold leading-6 text-slate-900">{memoTitle}</div>+ <div className="line-clamp-2 min-h-10 text-[15px] leading-5 text-slate-600">{memoExcerpt}</div>+ <div className="mt-5 flex flex-wrap items-center gap-2">+ <time className="text-sm text-slate-500">{formatMemoPreviewDate(memo.updatedAt)}</time>{memo.tags.slice(0, 3).map((tag) => (- <span key={tag} className="rounded bg-emerald-50 px-1.5 py-0.5 text-xs font-medium text-emerald-700">+ <span key={tag} className="rounded-sm bg-emerald-50 px-1.5 py-0.5 text-xs font-medium text-emerald-700">#{tag}</span>))}@@ -1227,6 +1427,34 @@ const MemoCard = ({);};+const getMemoTitle = (title: string | null | undefined) => title?.trim() || DEFAULT_MEMO_TITLE;++const formatMemoPreviewDate = (value: string) => {+ const date = new Date(value);++ if (Number.isNaN(date.getTime())) {+ return "";+ }++ const now = new Date();+ const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();+ const memoDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();++ if (memoDay === today) {+ return new Intl.DateTimeFormat("zh-CN", { hour: "2-digit", minute: "2-digit" }).format(date);+ }++ if (memoDay === today - 24 * 60 * 60 * 1000) {+ return "昨天";+ }++ return new Intl.DateTimeFormat("zh-CN", {+ year: "numeric",+ month: "numeric",+ day: "numeric",+ }).format(date);+};+const SUPPORTED_PASTE_IMAGE_TYPES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif"]);const getImageFilesFromDataTransfer = (dataTransfer: DataTransfer | null) => {@@ -1662,7 +1890,7 @@ const RevisionHistoryDialog = ({<History className="h-4 w-4 text-emerald-700" />版本历史</div>- <div className="mt-1 truncate text-xs text-slate-500">{memo.title || "Untitled memo"}</div>+ <div className="mt-1 truncate text-xs text-slate-500">{getMemoTitle(memo.title)}</div></div><Button size="icon" variant="ghost" title="关闭" onClick={onClose}><X className="h-4 w-4" />@@ -1740,7 +1968,7 @@ const RevisionPreview = ({ title, markdown }: { title: string; markdown: string<div className="min-h-[260px] border-b border-emerald-100 p-4 sm:border-b-0 sm:border-r"><div className="mb-3 text-xs font-semibold uppercase text-slate-500">{title}</div><pre className="max-h-[54dvh] overflow-auto whitespace-pre-wrap break-words rounded-md border border-emerald-100 bg-emerald-50/30 p-3 text-sm leading-6 text-slate-700">- {markdown || "Empty memo"}+ {markdown || "空笔记"}</pre></div>);@@ -1772,6 +2000,32 @@ const formatRevisionActor = (actor: string) => {return actor || "system";};+const syncStatusToSaveState = (status: "pending" | "syncing" | "conflict" | "error") => {+ if (status === "conflict") {+ return "conflict";+ }++ if (status === "syncing") {+ return "saving";+ }++ return "queued";+};++class MemoSaveRequestError extends Error {+ originalError: unknown;+ payload: MemoUpdateSyncPayload;+ tagsText: string;++ constructor(originalError: unknown, payload: MemoUpdateSyncPayload, tagsText: string) {+ super(originalError instanceof Error ? originalError.message : "Memo save failed");+ this.name = "MemoSaveRequestError";+ this.originalError = originalError;+ this.payload = payload;+ this.tagsText = tagsText;+ }+}+const EditorToolbar = ({ editor, readOnly }: { editor: Editor | null; readOnly: boolean }) => {const disabled = readOnly || !editor;const blockValue = getActiveBlockValue(editor);@@ -2002,7 +2256,7 @@ const EditorPane = ({const queryClient = useQueryClient();const [title, setTitle] = useState("");const [tagsText, setTagsText] = useState("");- const [saveState, setSaveState] = useState<"idle" | "saving" | "saved" | "error" | "conflict">("idle");+ const [saveState, setSaveState] = useState<"idle" | "saving" | "saved" | "queued" | "error" | "conflict">("idle");const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);const [dirtyVersion, setDirtyVersion] = useState(0);const [, setEditorStateVersion] = useState(0);@@ -2181,6 +2435,7 @@ const EditorPane = ({useEffect(() => {const currentEditor = editorRef.current;+ let cancelled = false;if (!memo) {memoRef.current = null;@@ -2202,21 +2457,46 @@ const EditorPane = ({return;}- hydratingRef.current = true;- editingMemoIdRef.current = memo.id;- hasUnsavedChangesRef.current = false;- setHasUnsavedChanges(false);- setSaveState("idle");- setTitle(memo.title ?? "");- setTagsText(memo.tags.join(", "));+ void (async () => {+ const [draft, queuedUpdate] = memo.isDeleted+ ? [null, null]+ : await Promise.all([+ localDb.drafts.get(memo.id),+ localDb.syncQueue.get(getMemoUpdateQueueId(memo.id)),+ ]);++ if (cancelled) {+ return;+ }- if (currentEditor) {- currentEditor.commands.setContent(memo.contentJson);- }+ const draftUpdatedAt = draft ? Date.parse(draft.updatedAt) : 0;+ const remoteUpdatedAt = Date.parse(memo.updatedAt);+ const useDraft = Boolean(draft && (queuedUpdate || draftUpdatedAt >= remoteUpdatedAt));+ const nextTitle = useDraft && draft ? draft.title : memo.title ?? "";+ const nextTagsText = useDraft && draft ? draft.tagsText : memo.tags.join(", ");+ const nextContent = useDraft && draft ? draft.contentJson : memo.contentJson;+ const nextHasUnsavedChanges = Boolean(useDraft && !queuedUpdate);++ hydratingRef.current = true;+ editingMemoIdRef.current = memo.id;+ hasUnsavedChangesRef.current = nextHasUnsavedChanges;+ setHasUnsavedChanges(nextHasUnsavedChanges);+ setSaveState(queuedUpdate ? syncStatusToSaveState(queuedUpdate.status) : "idle");+ setTitle(nextTitle);+ setTagsText(nextTagsText);++ if (currentEditor) {+ currentEditor.commands.setContent(nextContent);+ }- window.setTimeout(() => {- hydratingRef.current = false;- }, 0);+ window.setTimeout(() => {+ hydratingRef.current = false;+ }, 0);+ })();++ return () => {+ cancelled = true;+ };}, [isTrashView, memo, editor]);useEffect(() => {@@ -2258,12 +2538,26 @@ const EditorPane = ({throw new Error("Editor is not ready");}- const data = await api.updateMemo(currentMemo.id, {+ const contentJson = currentEditor.getJSON() as TiptapDoc;+ const payload: MemoUpdateSyncPayload = {+ memoId: currentMemo.id,expectedRevision: currentMemo.revision,title,- contentJson: currentEditor.getJSON() as TiptapDoc,+ contentJson,tags: parseTagsText(tagsText),- });+ };+ let data;++ try {+ data = await api.updateMemo(currentMemo.id, {+ expectedRevision: payload.expectedRevision,+ title: payload.title,+ contentJson: payload.contentJson,+ tags: payload.tags,+ });+ } catch (error) {+ throw new MemoSaveRequestError(error, payload, tagsText);+ }return { memo: data.memo, snapshot };},@@ -2286,9 +2580,35 @@ const EditorPane = ({setHasUnsavedChanges(true);setSaveState("idle");},- onError: (error) => {- const code = error && typeof error === "object" && "code" in error ? String(error.code) : null;- setSaveState(code === "revision_conflict" ? "conflict" : "error");+ onError: async (error) => {+ const sourceError = error instanceof MemoSaveRequestError ? error.originalError : error;+ const code =+ sourceError && typeof sourceError === "object" && "code" in sourceError+ ? String(sourceError.code)+ : null;++ if (code === "revision_conflict") {+ setSaveState("conflict");+ return;+ }++ if (error instanceof MemoSaveRequestError && shouldQueueMemoSaveError(sourceError)) {+ await queueMemoUpdate(error.payload);+ await localDb.drafts.put({+ memoId: error.payload.memoId,+ title: error.payload.title,+ tagsText: error.tagsText,+ contentJson: error.payload.contentJson,+ updatedAt: new Date().toISOString(),+ });++ hasUnsavedChangesRef.current = false;+ setHasUnsavedChanges(false);+ setSaveState("queued");+ return;+ }++ setSaveState("error");},});@@ -2332,13 +2652,15 @@ const EditorPane = ({? "保存中": saveState === "saved"? "已保存"- : saveState === "conflict"- ? "有冲突"- : saveState === "error"- ? "保存失败"- : hasUnsavedChanges- ? "未保存"- : "已保存";+ : saveState === "queued"+ ? "待同步"+ : saveState === "conflict"+ ? "有冲突"+ : saveState === "error"+ ? "保存失败"+ : hasUnsavedChanges+ ? "未保存"+ : "已保存";return (<div className="flex h-full min-w-0 flex-col">@@ -2437,7 +2759,7 @@ const EditorPane = ({markDirty();}}className="block w-full border-0 bg-transparent text-2xl font-semibold leading-tight text-slate-950 outline-none placeholder:text-slate-300 sm:text-3xl"- placeholder="Untitled memo"+ placeholder={DEFAULT_MEMO_TITLE}/><label className="flex h-8 items-center gap-2 text-sm text-slate-500"><Tags className="h-4 w-4" />diff --git a/apps/web/src/lib/local-db.ts b/apps/web/src/lib/local-db.tsindex 150c9b02..8e3d1c33 100644--- a/apps/web/src/lib/local-db.ts+++ b/apps/web/src/lib/local-db.ts@@ -9,14 +9,40 @@ export type LocalDraft = {updatedAt: string;};+export type MemoUpdateSyncPayload = {+ memoId: string;+ expectedRevision: number;+ title: string;+ contentJson: TiptapDoc;+ tags: string[];+};++export type SyncQueueItem = {+ id: string;+ kind: "memo.update";+ memoId: string;+ status: "pending" | "syncing" | "conflict" | "error";+ payload: MemoUpdateSyncPayload;+ attemptCount: number;+ lastError: string | null;+ nextAttemptAt: string | null;+ createdAt: string;+ updatedAt: string;+};+class EdgeEverLocalDb extends Dexie {drafts!: Table<LocalDraft, string>;+ syncQueue!: Table<SyncQueueItem, string>;constructor() {super("edgeever-local");this.version(1).stores({drafts: "memoId, updatedAt",});+ this.version(2).stores({+ drafts: "memoId, updatedAt",+ syncQueue: "id, memoId, status, updatedAt, nextAttemptAt",+ });}}diff --git a/apps/web/src/lib/sync-queue.ts b/apps/web/src/lib/sync-queue.tsnew file mode 100644index 00000000..9b97f9d1--- /dev/null+++ b/apps/web/src/lib/sync-queue.ts@@ -0,0 +1,165 @@+import type { MemoDetail, TiptapDoc } from "@edgeever/shared";+import { liveQuery } from "dexie";+import { ApiRequestError, api } from "@/lib/api";+import { localDb, type MemoUpdateSyncPayload, type SyncQueueItem } from "@/lib/local-db";++export type SyncQueueSummary = {+ total: number;+ pending: number;+ syncing: number;+ conflict: number;+ error: number;+};++export type SyncRunResult = {+ attempted: number;+ synced: number;+ failed: number;+ conflicted: number;+};++export const emptySyncQueueSummary = (): SyncQueueSummary => ({+ total: 0,+ pending: 0,+ syncing: 0,+ conflict: 0,+ error: 0,+});++export const getMemoUpdateQueueId = (memoId: string) => `memo.update:${memoId}`;++export const queueMemoUpdate = async (payload: MemoUpdateSyncPayload) => {+ const id = getMemoUpdateQueueId(payload.memoId);+ const now = new Date().toISOString();+ const existing = await localDb.syncQueue.get(id);++ await localDb.syncQueue.put({+ id,+ kind: "memo.update",+ memoId: payload.memoId,+ status: "pending",+ payload,+ attemptCount: existing?.attemptCount ?? 0,+ lastError: null,+ nextAttemptAt: null,+ createdAt: existing?.createdAt ?? now,+ updatedAt: now,+ });+};++export const observeSyncQueue = (onChange: (summary: SyncQueueSummary) => void) => {+ const subscription = liveQuery(async () => summarizeSyncQueue(await localDb.syncQueue.toArray())).subscribe({+ next: onChange,+ error: () => onChange(emptySyncQueueSummary()),+ });++ return () => subscription.unsubscribe();+};++export const syncQueuedChanges = async (options: {+ onSynced?: (memo: MemoDetail) => void | Promise<void>;+} = {}): Promise<SyncRunResult> => {+ const result: SyncRunResult = {+ attempted: 0,+ synced: 0,+ failed: 0,+ conflicted: 0,+ };++ if (typeof navigator !== "undefined" && !navigator.onLine) {+ return result;+ }++ const now = new Date();+ const items = (await localDb.syncQueue.where("status").anyOf("pending", "error").toArray())+ .filter((item) => !item.nextAttemptAt || new Date(item.nextAttemptAt) <= now)+ .sort((left, right) => left.createdAt.localeCompare(right.createdAt));++ for (const item of items) {+ result.attempted += 1;+ await localDb.syncQueue.update(item.id, {+ status: "syncing",+ updatedAt: new Date().toISOString(),+ });++ try {+ const memo = await syncQueueItem(item);+ await localDb.syncQueue.delete(item.id);+ await localDb.drafts.delete(item.memoId);+ await options.onSynced?.(memo);+ result.synced += 1;+ } catch (error) {+ const status = isRevisionConflict(error) ? "conflict" : "error";+ const attemptCount = item.attemptCount + 1;++ await localDb.syncQueue.update(item.id, {+ status,+ attemptCount,+ lastError: getErrorMessage(error),+ nextAttemptAt: status === "error" ? nextRetryAt(attemptCount) : null,+ updatedAt: new Date().toISOString(),+ });++ if (status === "conflict") {+ result.conflicted += 1;+ } else {+ result.failed += 1;+ }+ }+ }++ return result;+};++export const shouldQueueMemoSaveError = (error: unknown) => {+ if (typeof navigator !== "undefined" && !navigator.onLine) {+ return true;+ }++ if (error instanceof ApiRequestError) {+ return error.status === 408 || error.status === 429 || error.status >= 500;+ }++ return error instanceof TypeError;+};++const syncQueueItem = async (item: SyncQueueItem): Promise<MemoDetail> => {+ if (item.kind !== "memo.update") {+ throw new Error(`Unsupported sync item kind: ${item.kind}`);+ }++ const data = await api.updateMemo(item.memoId, {+ expectedRevision: item.payload.expectedRevision,+ title: item.payload.title,+ contentJson: item.payload.contentJson as TiptapDoc,+ tags: item.payload.tags,+ });++ return data.memo;+};++const summarizeSyncQueue = (items: SyncQueueItem[]): SyncQueueSummary =>+ items.reduce(+ (summary, item) => {+ summary.total += 1;+ summary[item.status] += 1;+ return summary;+ },+ emptySyncQueueSummary()+ );++const isRevisionConflict = (error: unknown) =>+ error instanceof ApiRequestError && error.code === "revision_conflict";++const getErrorMessage = (error: unknown) => {+ if (error instanceof Error) {+ return error.message;+ }++ return "Sync failed";+};++const nextRetryAt = (attemptCount: number) => {+ const delayMs = Math.min(5 * 60_000, 2 ** Math.min(attemptCount, 6) * 1000);+ return new Date(Date.now() + delayMs).toISOString();+};diff --git a/docs/openapi.json b/docs/openapi.jsonnew file mode 100644index 00000000..005bdf18--- /dev/null+++ b/docs/openapi.json@@ -0,0 +1,1463 @@+{+ "openapi": "3.1.0",+ "info": {+ "title": "EdgeEver API",+ "version": "0.1.0",+ "description": "REST API for EdgeEver notebooks, memos, resources, API tokens, and Agent integrations."+ },+ "servers": [+ {+ "url": "/"+ }+ ],+ "security": [+ {+ "bearerAuth": []+ },+ {+ "cookieAuth": []+ }+ ],+ "paths": {+ "/api/health": {+ "get": {+ "summary": "Health check",+ "security": [],+ "responses": {+ "200": {+ "description": "Runtime health",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "ok": {+ "type": "boolean"+ },+ "name": {+ "type": "string"+ },+ "runtime": {+ "type": "string"+ }+ },+ "required": ["ok", "name", "runtime"]+ }+ }+ }+ }+ }+ }+ },+ "/api/openapi.json": {+ "get": {+ "summary": "OpenAPI schema",+ "security": [],+ "responses": {+ "200": {+ "description": "OpenAPI 3.1 schema"+ }+ }+ }+ },+ "/api/v1/auth/session": {+ "get": {+ "summary": "Read interactive session",+ "security": [],+ "responses": {+ "200": {+ "description": "Current session",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AuthSession"+ }+ }+ }+ }+ }+ }+ },+ "/api/v1/auth/login": {+ "post": {+ "summary": "Create interactive session",+ "security": [],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/LoginInput"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Authenticated session",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AuthSession"+ }+ }+ }+ },+ "401": {+ "$ref": "#/components/responses/Error"+ }+ }+ }+ },+ "/api/v1/auth/logout": {+ "post": {+ "summary": "Revoke interactive session",+ "responses": {+ "200": {+ "description": "Logout result",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Ok"+ }+ }+ }+ }+ }+ }+ },+ "/api/v1/notebooks": {+ "get": {+ "summary": "List notebooks",+ "responses": {+ "200": {+ "description": "Notebook list",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "notebooks": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/Notebook"+ }+ }+ },+ "required": ["notebooks"]+ }+ }+ }+ }+ }+ },+ "post": {+ "summary": "Create notebook",+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/NotebookCreateInput"+ }+ }+ }+ },+ "responses": {+ "201": {+ "$ref": "#/components/responses/NotebookResponse"+ }+ }+ }+ },+ "/api/v1/notebooks/{id}": {+ "parameters": [+ {+ "$ref": "#/components/parameters/NotebookId"+ }+ ],+ "patch": {+ "summary": "Update notebook",+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/NotebookUpdateInput"+ }+ }+ }+ },+ "responses": {+ "200": {+ "$ref": "#/components/responses/NotebookResponse"+ },+ "409": {+ "$ref": "#/components/responses/Error"+ }+ }+ },+ "delete": {+ "summary": "Soft-delete empty notebook",+ "responses": {+ "200": {+ "$ref": "#/components/responses/Ok"+ },+ "409": {+ "$ref": "#/components/responses/Error"+ }+ }+ }+ },+ "/api/v1/tags": {+ "get": {+ "summary": "List tag summaries",+ "responses": {+ "200": {+ "description": "Tag summaries",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "tags": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/TagSummary"+ }+ }+ },+ "required": ["tags"]+ }+ }+ }+ }+ }+ }+ },+ "/api/v1/tags/{tag}": {+ "parameters": [+ {+ "name": "tag",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "patch": {+ "summary": "Rename tag across active memos",+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/TagRenameInput"+ }+ }+ }+ },+ "responses": {+ "200": {+ "$ref": "#/components/responses/UpdatedCount"+ }+ }+ },+ "delete": {+ "summary": "Remove tag across active memos",+ "responses": {+ "200": {+ "$ref": "#/components/responses/UpdatedCount"+ }+ }+ }+ },+ "/api/v1/api-tokens": {+ "get": {+ "summary": "List API tokens",+ "responses": {+ "200": {+ "description": "API token list",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "apiTokens": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ApiToken"+ }+ },+ "availableScopes": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": ["apiTokens", "availableScopes"]+ }+ }+ }+ }+ }+ },+ "post": {+ "summary": "Create API token",+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiTokenCreateInput"+ }+ }+ }+ },+ "responses": {+ "201": {+ "description": "Created token; plaintext token is shown once",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreatedApiToken"+ }+ }+ }+ }+ }+ }+ },+ "/api/v1/api-tokens/{id}": {+ "parameters": [+ {+ "$ref": "#/components/parameters/ApiTokenId"+ }+ ],+ "delete": {+ "summary": "Revoke API token",+ "responses": {+ "200": {+ "$ref": "#/components/responses/Ok"+ }+ }+ }+ },+ "/api/v1/memos": {+ "get": {+ "summary": "List or search memos",+ "parameters": [+ {+ "name": "notebookId",+ "in": "query",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "q",+ "in": "query",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "trash",+ "in": "query",+ "schema": {+ "type": "string",+ "enum": ["1"]+ }+ },+ {+ "name": "limit",+ "in": "query",+ "schema": {+ "type": "integer",+ "minimum": 1,+ "maximum": 100,+ "default": 80+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Memo summaries",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "memos": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/MemoSummary"+ }+ }+ },+ "required": ["memos"]+ }+ }+ }+ }+ }+ },+ "post": {+ "summary": "Create memo",+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/MemoCreateInput"+ }+ }+ }+ },+ "responses": {+ "201": {+ "$ref": "#/components/responses/MemoResponse"+ }+ }+ }+ },+ "/api/v1/memos/batch/move": {+ "post": {+ "summary": "Move memos to notebook",+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/MoveMemosInput"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Move result",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "ok": {+ "type": "boolean"+ },+ "moved": {+ "type": "integer"+ }+ },+ "required": ["ok", "moved"]+ }+ }+ }+ }+ }+ }+ },+ "/api/v1/memos/merge": {+ "post": {+ "summary": "Merge memos",+ "description": "Creates a new memo, joins source Markdown with separators, soft-deletes source memos, and re-points resources to the new memo.",+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/MergeMemosInput"+ }+ }+ }+ },+ "responses": {+ "201": {+ "$ref": "#/components/responses/MemoResponse"+ }+ }+ }+ },+ "/api/v1/memos/{id}": {+ "parameters": [+ {+ "$ref": "#/components/parameters/MemoId"+ }+ ],+ "get": {+ "summary": "Get memo detail",+ "parameters": [+ {+ "name": "includeDeleted",+ "in": "query",+ "schema": {+ "type": "string",+ "enum": ["1"]+ }+ }+ ],+ "responses": {+ "200": {+ "$ref": "#/components/responses/MemoResponse"+ }+ }+ },+ "patch": {+ "summary": "Update memo",+ "description": "Use expectedRevision for optimistic concurrency. A mismatch returns revision_conflict.",+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/MemoUpdateInput"+ }+ }+ }+ },+ "responses": {+ "200": {+ "$ref": "#/components/responses/MemoResponse"+ },+ "409": {+ "$ref": "#/components/responses/Error"+ }+ }+ },+ "delete": {+ "summary": "Soft-delete or permanently delete memo",+ "parameters": [+ {+ "name": "permanent",+ "in": "query",+ "schema": {+ "type": "string",+ "enum": ["1"]+ }+ }+ ],+ "responses": {+ "200": {+ "$ref": "#/components/responses/Ok"+ }+ }+ }+ },+ "/api/v1/memos/{id}/restore": {+ "parameters": [+ {+ "$ref": "#/components/parameters/MemoId"+ }+ ],+ "post": {+ "summary": "Restore memo from trash",+ "responses": {+ "200": {+ "$ref": "#/components/responses/MemoResponse"+ }+ }+ }+ },+ "/api/v1/memos/{id}/revisions": {+ "parameters": [+ {+ "$ref": "#/components/parameters/MemoId"+ }+ ],+ "get": {+ "summary": "List memo revisions",+ "parameters": [+ {+ "name": "limit",+ "in": "query",+ "schema": {+ "type": "integer",+ "minimum": 1,+ "maximum": 100,+ "default": 50+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Memo revisions",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "revisions": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/MemoRevision"+ }+ }+ },+ "required": ["revisions"]+ }+ }+ }+ }+ }+ }+ },+ "/api/v1/memos/{id}/revisions/{revisionId}/restore": {+ "parameters": [+ {+ "$ref": "#/components/parameters/MemoId"+ },+ {+ "name": "revisionId",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "post": {+ "summary": "Restore a memo revision",+ "responses": {+ "200": {+ "$ref": "#/components/responses/MemoResponse"+ }+ }+ }+ },+ "/api/v1/memos/{id}/resources": {+ "parameters": [+ {+ "$ref": "#/components/parameters/MemoId"+ }+ ],+ "post": {+ "summary": "Upload image resource for memo",+ "requestBody": {+ "required": true,+ "content": {+ "multipart/form-data": {+ "schema": {+ "type": "object",+ "properties": {+ "file": {+ "type": "string",+ "format": "binary"+ }+ },+ "required": ["file"]+ }+ }+ }+ },+ "responses": {+ "201": {+ "description": "Uploaded resource",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "resource": {+ "$ref": "#/components/schemas/Resource"+ }+ },+ "required": ["resource"]+ }+ }+ }+ }+ }+ }+ },+ "/api/v1/resources": {+ "get": {+ "summary": "List resources and storage summary",+ "parameters": [+ {+ "name": "limit",+ "in": "query",+ "schema": {+ "type": "integer",+ "minimum": 1,+ "maximum": 500,+ "default": 500+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Resource list",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "resources": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ResourceListItem"+ }+ },+ "summary": {+ "$ref": "#/components/schemas/ResourceStorageSummary"+ }+ },+ "required": ["resources", "summary"]+ }+ }+ }+ }+ }+ }+ },+ "/api/v1/resources/{id}/blob": {+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "get": {+ "summary": "Read resource bytes",+ "responses": {+ "200": {+ "description": "Resource blob"+ }+ }+ }+ },+ "/mcp": {+ "get": {+ "summary": "Describe MCP endpoint",+ "security": [],+ "responses": {+ "200": {+ "description": "MCP endpoint metadata"+ }+ }+ },+ "post": {+ "summary": "MCP Streamable HTTP JSON-RPC endpoint",+ "description": "Supports initialize, tools/list, tools/call, notifications/initialized, and batch requests.",+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "oneOf": [+ {+ "$ref": "#/components/schemas/JsonRpcRequest"+ },+ {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/JsonRpcRequest"+ }+ }+ ]+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "JSON-RPC response"+ },+ "204": {+ "description": "Notification accepted"+ }+ }+ }+ }+ },+ "components": {+ "securitySchemes": {+ "bearerAuth": {+ "type": "http",+ "scheme": "bearer"+ },+ "cookieAuth": {+ "type": "apiKey",+ "in": "cookie",+ "name": "edgeever_session"+ }+ },+ "parameters": {+ "NotebookId": {+ "name": "id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ "MemoId": {+ "name": "id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ "ApiTokenId": {+ "name": "id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ },+ "responses": {+ "Ok": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Ok"+ }+ }+ }+ },+ "Error": {+ "description": "API error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "NotebookResponse": {+ "description": "Notebook response",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "notebook": {+ "$ref": "#/components/schemas/Notebook"+ }+ },+ "required": ["notebook"]+ }+ }+ }+ },+ "MemoResponse": {+ "description": "Memo response",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "memo": {+ "$ref": "#/components/schemas/MemoDetail"+ }+ },+ "required": ["memo"]+ }+ }+ }+ },+ "UpdatedCount": {+ "description": "Updated count",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "ok": {+ "type": "boolean"+ },+ "updated": {+ "type": "integer"+ }+ },+ "required": ["ok", "updated"]+ }+ }+ }+ }+ },+ "schemas": {+ "Ok": {+ "type": "object",+ "properties": {+ "ok": {+ "type": "boolean"+ }+ },+ "required": ["ok"]+ },+ "ApiError": {+ "type": "object",+ "properties": {+ "error": {+ "type": "object",+ "properties": {+ "code": {+ "type": "string"+ },+ "message": {+ "type": "string"+ },+ "details": {}+ },+ "required": ["code", "message"]+ }+ },+ "required": ["error"]+ },+ "AuthSession": {+ "type": "object",+ "properties": {+ "authRequired": {+ "type": "boolean"+ },+ "authenticated": {+ "type": "boolean"+ },+ "user": {+ "oneOf": [+ {+ "$ref": "#/components/schemas/AuthUser"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": ["authRequired", "authenticated", "user"]+ },+ "AuthUser": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "username": {+ "type": "string"+ },+ "displayName": {+ "type": ["string", "null"]+ }+ },+ "required": ["id", "username", "displayName"]+ },+ "LoginInput": {+ "type": "object",+ "properties": {+ "username": {+ "type": "string"+ },+ "password": {+ "type": "string"+ }+ },+ "required": ["username", "password"]+ },+ "Notebook": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "parentId": {+ "type": ["string", "null"]+ },+ "name": {+ "type": "string"+ },+ "slug": {+ "type": ["string", "null"]+ },+ "icon": {+ "type": ["string", "null"]+ },+ "color": {+ "type": ["string", "null"]+ },+ "sortOrder": {+ "type": "integer"+ },+ "createdAt": {+ "type": "string",+ "format": "date-time"+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time"+ }+ },+ "required": ["id", "parentId", "name", "slug", "icon", "color", "sortOrder", "createdAt", "updatedAt"]+ },+ "NotebookCreateInput": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "minLength": 1,+ "maxLength": 80+ },+ "parentId": {+ "type": ["string", "null"]+ }+ },+ "required": ["name"]+ },+ "NotebookUpdateInput": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "minLength": 1,+ "maxLength": 80+ },+ "parentId": {+ "type": ["string", "null"]+ },+ "sortOrder": {+ "type": "integer"+ }+ }+ },+ "MemoSummary": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "notebookId": {+ "type": "string"+ },+ "title": {+ "type": ["string", "null"]+ },+ "excerpt": {+ "type": "string"+ },+ "tags": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "isPinned": {+ "type": "boolean"+ },+ "isArchived": {+ "type": "boolean"+ },+ "isDeleted": {+ "type": "boolean"+ },+ "revision": {+ "type": "integer"+ },+ "createdAt": {+ "type": "string",+ "format": "date-time"+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time"+ },+ "deletedAt": {+ "type": ["string", "null"],+ "format": "date-time"+ }+ },+ "required": ["id", "notebookId", "title", "excerpt", "tags", "isPinned", "isArchived", "isDeleted", "revision", "createdAt", "updatedAt", "deletedAt"]+ },+ "MemoDetail": {+ "allOf": [+ {+ "$ref": "#/components/schemas/MemoSummary"+ },+ {+ "type": "object",+ "properties": {+ "contentJson": {+ "$ref": "#/components/schemas/TiptapDoc"+ },+ "contentMarkdown": {+ "type": "string"+ },+ "contentText": {+ "type": "string"+ },+ "sourceMemoIds": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "mergeSourceCount": {+ "type": "integer"+ },+ "mergedIntoMemoId": {+ "type": ["string", "null"]+ }+ },+ "required": ["contentJson", "contentMarkdown", "contentText", "sourceMemoIds", "mergeSourceCount", "mergedIntoMemoId"]+ }+ ]+ },+ "MemoCreateInput": {+ "type": "object",+ "properties": {+ "notebookId": {+ "type": "string"+ },+ "title": {+ "type": "string",+ "maxLength": 160+ },+ "contentMarkdown": {+ "type": "string"+ },+ "tags": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": ["notebookId"]+ },+ "MemoUpdateInput": {+ "type": "object",+ "properties": {+ "expectedRevision": {+ "type": "integer",+ "minimum": 0+ },+ "notebookId": {+ "type": "string"+ },+ "title": {+ "type": "string",+ "maxLength": 160+ },+ "contentJson": {+ "$ref": "#/components/schemas/TiptapDoc"+ },+ "contentMarkdown": {+ "type": "string"+ },+ "tags": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "MoveMemosInput": {+ "type": "object",+ "properties": {+ "memoIds": {+ "type": "array",+ "minItems": 1,+ "maxItems": 100,+ "items": {+ "type": "string"+ }+ },+ "notebookId": {+ "type": "string"+ }+ },+ "required": ["memoIds", "notebookId"]+ },+ "MergeMemosInput": {+ "type": "object",+ "properties": {+ "memoIds": {+ "type": "array",+ "minItems": 2,+ "maxItems": 50,+ "items": {+ "type": "string"+ }+ },+ "notebookId": {+ "type": "string"+ },+ "title": {+ "type": "string",+ "maxLength": 160+ }+ },+ "required": ["memoIds"]+ },+ "MemoRevision": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "memoId": {+ "type": "string"+ },+ "revision": {+ "type": "integer"+ },+ "title": {+ "type": ["string", "null"]+ },+ "tags": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "contentMarkdown": {+ "type": "string"+ },+ "contentText": {+ "type": "string"+ },+ "contentHash": {+ "type": "string"+ },+ "createdBy": {+ "type": "string"+ },+ "createdAt": {+ "type": "string",+ "format": "date-time"+ }+ },+ "required": ["id", "memoId", "revision", "title", "tags", "contentMarkdown", "contentText", "contentHash", "createdBy", "createdAt"]+ },+ "TagSummary": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "memoCount": {+ "type": "integer"+ },+ "updatedAt": {+ "type": ["string", "null"],+ "format": "date-time"+ }+ },+ "required": ["name", "memoCount", "updatedAt"]+ },+ "TagRenameInput": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "minLength": 1,+ "maxLength": 80+ }+ },+ "required": ["name"]+ },+ "ApiToken": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "scopes": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "lastUsedAt": {+ "type": ["string", "null"],+ "format": "date-time"+ },+ "expiresAt": {+ "type": ["string", "null"],+ "format": "date-time"+ },+ "isRevoked": {+ "type": "boolean"+ },+ "createdAt": {+ "type": "string",+ "format": "date-time"+ }+ },+ "required": ["id", "name", "scopes", "lastUsedAt", "expiresAt", "isRevoked", "createdAt"]+ },+ "ApiTokenCreateInput": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "minLength": 1,+ "maxLength": 80+ },+ "scopes": {+ "type": "array",+ "minItems": 1,+ "maxItems": 32,+ "items": {+ "type": "string"+ }+ },+ "expiresAt": {+ "type": ["string", "null"],+ "format": "date-time"+ }+ },+ "required": ["name", "scopes"]+ },+ "CreatedApiToken": {+ "type": "object",+ "properties": {+ "token": {+ "type": "string"+ },+ "apiToken": {+ "$ref": "#/components/schemas/ApiToken"+ }+ },+ "required": ["token", "apiToken"]+ },+ "Resource": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "memoId": {+ "type": "string"+ },+ "originalMemoId": {+ "type": ["string", "null"]+ },+ "kind": {+ "type": "string",+ "enum": ["image", "attachment"]+ },+ "mimeType": {+ "type": ["string", "null"]+ },+ "filename": {+ "type": ["string", "null"]+ },+ "byteSize": {+ "type": "integer"+ },+ "sha256": {+ "type": ["string", "null"]+ },+ "width": {+ "type": ["integer", "null"]+ },+ "height": {+ "type": ["integer", "null"]+ },+ "createdAt": {+ "type": "string",+ "format": "date-time"+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time"+ },+ "url": {+ "type": "string"+ }+ },+ "required": ["id", "memoId", "originalMemoId", "kind", "mimeType", "filename", "byteSize", "sha256", "width", "height", "createdAt", "updatedAt", "url"]+ },+ "ResourceListItem": {+ "allOf": [+ {+ "$ref": "#/components/schemas/Resource"+ },+ {+ "type": "object",+ "properties": {+ "memoTitle": {+ "type": ["string", "null"]+ },+ "memoExcerpt": {+ "type": ["string", "null"]+ },+ "memoDeleted": {+ "type": "boolean"+ }+ },+ "required": ["memoTitle", "memoExcerpt", "memoDeleted"]+ }+ ]+ },+ "ResourceStorageSummary": {+ "type": "object",+ "properties": {+ "totalCount": {+ "type": "integer"+ },+ "totalBytes": {+ "type": "integer"+ },+ "imageCount": {+ "type": "integer"+ },+ "attachmentCount": {+ "type": "integer"+ }+ },+ "required": ["totalCount", "totalBytes", "imageCount", "attachmentCount"]+ },+ "TiptapDoc": {+ "type": "object",+ "additionalProperties": true,+ "properties": {+ "type": {+ "type": "string",+ "const": "doc"+ },+ "content": {+ "type": "array",+ "items": {+ "type": "object",+ "additionalProperties": true+ }+ }+ },+ "required": ["type", "content"]+ },+ "JsonRpcRequest": {+ "type": "object",+ "properties": {+ "jsonrpc": {+ "type": "string",+ "const": "2.0"+ },+ "id": {+ "type": ["string", "number", "null"]+ },+ "method": {+ "type": "string"+ },+ "params": {}+ },+ "required": ["jsonrpc", "method"]+ }+ }+ }+}diff --git a/package.json b/package.jsonindex 15822d57..3f05df7b 100644--- a/package.json+++ b/package.json@@ -19,6 +19,7 @@"db:migrate:remote": "bun scripts/run-wrangler.mjs d1 migrations apply DB --remote","auth:hash": "bun scripts/hash-password.mjs","cli": "bun scripts/edgeever.mjs",+ "mcp:stdio": "bun scripts/edgeever-mcp-stdio.mjs","deploy": "bun run build && bun run db:migrate:remote && bun scripts/run-wrangler.mjs deploy","deploy:tianma": "EDGE_EVER_INSTANCE=tianma bun run deploy","deploy:demo": "EDGE_EVER_INSTANCE=demo bun run deploy",diff --git a/packages/shared/src/content.ts b/packages/shared/src/content.tsindex e2ecfdd5..cc0a5b5e 100644--- a/packages/shared/src/content.ts+++ b/packages/shared/src/content.ts@@ -14,6 +14,8 @@ export type TiptapDoc = {content: TiptapNode[];};+export const DEFAULT_MEMO_TITLE = "无标题笔记";+export const emptyDoc = (): TiptapDoc => ({type: "doc",content: [{ type: "paragraph" }],diff --git a/scripts/edgeever-mcp-stdio.mjs b/scripts/edgeever-mcp-stdio.mjsnew file mode 100644index 00000000..abaca3dc--- /dev/null+++ b/scripts/edgeever-mcp-stdio.mjs@@ -0,0 +1,248 @@+#!/usr/bin/env bun++import { readFile } from "node:fs/promises";+import { join } from "node:path";+import { homedir } from "node:os";++const CONFIG_PATH = process.env.EDGEEVER_CONFIG || join(homedir(), ".edgeever", "config.json");+const DEFAULT_URL = "http://127.0.0.1:8787";+const options = parseOptions(process.argv.slice(2));++const usage = `EdgeEver MCP stdio adapter++Usage:+ EDGEEVER_URL=https://your.edgeever.host EDGEEVER_TOKEN=... bun scripts/edgeever-mcp-stdio.mjs+ bun scripts/edgeever-mcp-stdio.mjs --profile prod++The adapter bridges local stdio MCP clients to the remote EdgeEver /mcp endpoint.+`;++if (options.help || options.h) {+ process.stdout.write(usage);+ process.exit(0);+}++let client;++try {+ client = await createClient(options.profile);+} catch (error) {+ console.error(error instanceof Error ? error.message : error);+ process.exit(1);+}++let inputBuffer = Buffer.alloc(0);+let transportMode = null;++process.stdin.on("data", (chunk) => {+ inputBuffer = Buffer.concat([inputBuffer, chunk]);+ drainInput();+});++process.stdin.on("error", (error) => {+ console.error(error instanceof Error ? error.message : error);+ process.exit(1);+});++process.stdin.resume();++function drainInput() {+ while (inputBuffer.length > 0) {+ const framed = readFramedMessage(inputBuffer);++ if (framed) {+ transportMode = "framed";+ inputBuffer = inputBuffer.subarray(framed.consumedBytes);+ void handleMessage(framed.payload);+ continue;+ }++ if (looksLikeFramedMessage(inputBuffer)) {+ return;+ }++ const newlineIndex = inputBuffer.indexOf(0x0a);++ if (newlineIndex === -1) {+ return;+ }++ const line = inputBuffer.subarray(0, newlineIndex).toString("utf8").trim();+ inputBuffer = inputBuffer.subarray(newlineIndex + 1);++ if (!line) {+ continue;+ }++ transportMode = transportMode || "line";+ void handleMessage(line);+ }+}++async function handleMessage(payload) {+ let request;++ try {+ request = JSON.parse(payload);+ } catch {+ writeMessage(jsonRpcError(null, -32700, "Parse error"));+ return;+ }++ try {+ const response = await forwardToEdgeEver(request);++ if (response !== null) {+ writeMessage(response);+ }+ } catch (error) {+ writeMessage(+ jsonRpcError(getJsonRpcId(request), -32000, error instanceof Error ? error.message : "MCP bridge failed")+ );+ }+}++async function forwardToEdgeEver(request) {+ const response = await fetch(`${client.baseUrl}/mcp`, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${client.token}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify(request),+ });++ if (response.status === 204) {+ return null;+ }++ const body = await response.json().catch(() => null);++ if (!body) {+ throw new Error(`${response.status} ${response.statusText}`);+ }++ return body;+}++async function createClient(profileName) {+ const config = await readConfig();+ const profile = profileName ? config.profiles?.[profileName] : undefined;+ const baseUrl = (process.env.EDGEEVER_URL || profile?.url || DEFAULT_URL).replace(/\/+$/, "");+ const token = process.env.EDGEEVER_TOKEN || profile?.token;++ if (!token) {+ throw new Error("EDGEEVER_TOKEN is required, or configure a profile with `bun run cli -- profile set`.");+ }++ return { baseUrl, token };+}++async function readConfig() {+ try {+ const value = JSON.parse(await readFile(CONFIG_PATH, "utf8"));+ return value && typeof value === "object" ? value : {};+ } catch {+ return {};+ }+}++function readFramedMessage(buffer) {+ const headerEnd = findHeaderEnd(buffer);++ if (!headerEnd) {+ return null;+ }++ const header = buffer.subarray(0, headerEnd.index).toString("utf8");+ const match = /^content-length:\s*(\d+)\s*$/im.exec(header);++ if (!match) {+ return null;+ }++ const contentLength = Number(match[1]);+ const bodyStart = headerEnd.index + headerEnd.length;+ const bodyEnd = bodyStart + contentLength;++ if (!Number.isInteger(contentLength) || contentLength < 0 || buffer.length < bodyEnd) {+ return null;+ }++ return {+ payload: buffer.subarray(bodyStart, bodyEnd).toString("utf8"),+ consumedBytes: bodyEnd,+ };+}++function findHeaderEnd(buffer) {+ const crlf = buffer.indexOf("\r\n\r\n");++ if (crlf !== -1) {+ return { index: crlf, length: 4 };+ }++ const lf = buffer.indexOf("\n\n");+ return lf === -1 ? null : { index: lf, length: 2 };+}++function looksLikeFramedMessage(buffer) {+ return buffer.subarray(0, Math.min(buffer.length, 32)).toString("utf8").toLowerCase().startsWith("content-length:");+}++function writeMessage(message) {+ const payload = `${JSON.stringify(message)}\n`;++ if (transportMode === "framed") {+ const content = payload.trimEnd();+ process.stdout.write(`Content-Length: ${Buffer.byteLength(content, "utf8")}\r\n\r\n${content}`);+ return;+ }++ process.stdout.write(payload);+}++function parseOptions(args) {+ const parsed = {};++ for (let index = 0; index < args.length; index += 1) {+ const arg = args[index];++ if (!arg.startsWith("--")) {+ continue;+ }++ const key = arg.slice(2);+ const next = args[index + 1];++ if (!next || next.startsWith("--")) {+ parsed[key] = "true";+ continue;+ }++ parsed[key] = next;+ index += 1;+ }++ return parsed;+}++function getJsonRpcId(request) {+ if (!request || typeof request !== "object" || !("id" in request)) {+ return null;+ }++ const id = request.id;+ return typeof id === "string" || typeof id === "number" || id === null ? id : null;+}++function jsonRpcError(id, code, message) {+ return {+ jsonrpc: "2.0",+ id,+ error: {+ code,+ message,+ },+ };+}