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
fix: enable structured table creation in companion agent
tianma-if36f60ca429f9
diff --git a/apps/api/src/companion-agent-tools.ts b/apps/api/src/companion-agent-tools.tsindex a6b8f078..901df5bd 100644--- a/apps/api/src/companion-agent-tools.ts+++ b/apps/api/src/companion-agent-tools.ts@@ -15,7 +15,7 @@ import { AppError } from "./app-error";const AUTO_APPLY_WRITES = new Set(COMPANION_MCP_TOOLS.filter(tool => !tool.annotations.readOnlyHint).map(tool => tool.name),);-const INBOX_DEFAULT_NOTEBOOK_TOOLS = new Set(["create_memo", "create_diagram_memo", "create_infographic_memo", "use_note_template"]);+const INBOX_DEFAULT_NOTEBOOK_TOOLS = new Set(["create_memo", "create_table_memo", "create_diagram_memo", "create_infographic_memo", "use_note_template"]);export async function resolveWorkspaceInboxId(db: DatabaseAdapter, workspaceId: string) {const preferred = workspaceInboxId(workspaceId);@@ -118,7 +118,10 @@ const TOOL_HINTS: Record<string, string> = {list_memos: " To list a named notebook, call find_notebooks first and pass that id. Without notebookId this lists the whole workspace, newest updated first. For newly created notes in a time range, use search_memos with createdAfter. If hasMore is true, say the list is incomplete.",search_memos: " Searches note titles and bodies, not notebook names. query is optional. For recently created or added notes, pass createdAfter (YYYY-MM-DD or ISO date-time) and omit query; never put this week/最近/新增 in query. For recently edited notes, use updatedAfter. Do not pass notebookId unless find_notebooks or list_notebooks returned it. For notes in a named notebook, find_notebooks then list_memos. If hasMore is true, say the list is incomplete.",list_tags: " Use this when the user names a tag.",- create_memo: " For prose Markdown notes only. Never use this for 思维导图/mind maps, 流程图/flowcharts, 架构图, or 信息图/infographics. Use create_diagram_memo for diagrams and create_infographic_memo for infographics. If the user did not name a notebook, omit notebookId. The note is saved in the inbox (等待分类). Do not ask which notebook.",+ create_memo: " For prose Markdown notes only. Never use this for structured tables/多维表格, 思维导图/mind maps, 流程图/flowcharts, 架构图, or 信息图/infographics. Use create_table_memo for tables, create_diagram_memo for diagrams, and create_infographic_memo for infographics. If the user did not name a notebook, omit notebookId. The note is saved in the inbox (等待分类). Do not ask which notebook.",+ create_table_memo: " Create an editable structured table/多维表格 from the user's requested field plan. Infer useful field names and types when unspecified. Select fields need explicit options. This creates an empty table; only add records if the user requested example or supplied records. If the user did not name a notebook, omit notebookId so it is saved in the inbox (等待分类). Do not ask which notebook, and do not use the open notebook unless the user named it.",+ get_table_records: " Read an existing structured table's fields, record IDs, and revision. Use this before adding a record so cell keys are actual field IDs. Do not infer field IDs from names.",+ add_table_record: " Add one requested record to a structured table. First call get_table_records, then use its field IDs and latest revision. Do not invent factual records to fill a new table.",create_diagram_memo: " Create an editable visual diagram note. kind=mind-map for 思维导图/mind map, flowchart for 流程图, architecture for 架构图. Never use this for 信息图/infographic; call create_infographic_memo. Omit edge ids; EdgeEver generates them. For mind maps, give a root and children with parentId; omit node type. If the user did not name a notebook, omit notebookId. The diagram is saved in the inbox (等待分类). Do not ask which notebook, and do not use the open notebook unless the user named it. Build nodes from the open note body in Focus DATA when the user refers to this note.",create_infographic_memo: " Create an AntV infographic note (信息图). A share, proportion, or 占比 uses template chart-pie-donut-plain-text and numeric data.values, not a mind map. If the user did not supply the figures, say in data.desc that they are illustrative and are not an official disclosure. If the user did not name a notebook, omit notebookId. The infographic is saved in the inbox (等待分类). Do not ask which notebook, and do not use the open notebook unless the user named it.",get_diagram: " Read an existing editable diagram as a semantic graph. Call this before update_diagram. Do not use get_memo when you only need the diagram structure.",@@ -419,6 +422,19 @@ export function createCompanionTools(args: { db: DatabaseAdapter; scope: Companiinfographic: true,});}+ if (definition.name === "create_table_memo") {+ const created = result as { memo: MemoDetail; fields?: unknown[] };+ remember(created.memo);+ return done({+ applied: true,+ id: created.memo.id,+ title: created.memo.title,+ notebookId: created.memo.notebookId,+ notebookName: await notebookName(created.memo.notebookId),+ revision: created.memo.revision,+ fieldCount: Array.isArray(created.fields) ? created.fields.length : undefined,+ });+ }if (definition.name === "update_diagram") {const updated = result as { memo: { id: string; title: string | null; revision: number }; diagram?: { nodes?: unknown[] }; changes?: unknown };inspected.set(updated.memo.id, updated.memo.revision);diff --git a/apps/api/src/companion-prepare.ts b/apps/api/src/companion-prepare.tsindex ee8c094b..c1b659c0 100644--- a/apps/api/src/companion-prepare.ts+++ b/apps/api/src/companion-prepare.ts@@ -12,7 +12,7 @@ import { listCompanionMemories, listCompanionTurns, mapCompanionTurn, type Compaimport { companionToolDefinitions } from "./companion-agent-tools";import { parseJsonArray } from "./companion-tool-receipts";-export const COMPANION_IDENTITY_VERSION = 15;+export const COMPANION_IDENTITY_VERSION = 16;export const COMPANION_MAX_STEPS = 8;export const COMPANION_MAX_OUTPUT_TOKENS = 2048;export const COMPANION_INSTRUCTIONS = `You are EdgeEver, a thoughtful personal knowledge companion.@@ -22,13 +22,13 @@ Only claim to remember information present in supplied context. Distinguish explThe user controls long-term memory through the UI. You cannot save, edit, or forget memories yourself.Only report a note operation as completed when the tool result says applied, or a persisted receipt says applied. A proposal is not completion.Never claim a reminder was scheduled or an external action completed.-You can use EdgeEver's shared tools to read, create, update, import, merge, move, tag, trash and restore notes, restore revisions, organize notebooks, create editable diagrams and infographics, and manage note templates and AI instructions.+You can use EdgeEver's shared tools to read, create, update, import, merge, move, tag, trash and restore notes, restore revisions, organize notebooks, create editable structured tables, diagrams and infographics, and manage note templates and AI instructions.Note tools, including update_memo with contentMarkdown, execute immediately when allowed. Read the complete current note before replacing its body. Trashed notes go to the recycle bin; content edits keep revision history. Read tools and explicit dry runs execute immediately.Read every source note completely before merging or replacing its body. Do not merge merely because notes share a broad topic: look for one coherent idea or the user's explicit selection.Merging preserves source bodies/attachments and existing tags, moves sources to trash and revokes their public shares. A destination notebook may be specified.Content changes use update_memo with the exact replacement Markdown. Prefer existing tags; remove tags only when requested.Never operate on hypothetical IDs: confirm the prerequisite first, then use its real result.-For multi-step organization (≥3 steps), call todo_write first and keep it current. If you cannot choose among existing notes or strategies, call ask_user_question once and stop. Never ask which notebook should receive a new note, diagram, infographic, or template. Omit notebookId and it is saved in the inbox notebook (等待分类).+For multi-step organization (≥3 steps), call todo_write first and keep it current. If you cannot choose among existing notes or strategies, call ask_user_question once and stop. Never ask which notebook should receive a new note, table, diagram, infographic, or template. Omit notebookId and it is saved in the inbox notebook (等待分类).Resolve follow-up references such as "the translated content" from the most recent relevant exchange in this thread before asking a question. If you just translated the open note and the user asks to replace its original with the translation, use that exact translated text as the replacement; do not translate it again or ask for a target language. An older translation of different text does not override the latest relevant translation. Read the current note before calling update_memo to change its contentMarkdown. Ask only if the referenced result is missing or genuinely ambiguous.Do not repeat writes already listed as applied in Historical operation receipts.The user already sees each tool in a timeline. Do not narrate that you will search, read, or create, and do not write status updates such as "I will now" or "I have obtained". After tools finish, write only the user-facing answer: what you did, with note links.@@ -47,8 +47,9 @@ If list_memos or search_memos sets hasMore, say the list is incomplete instead oWhen the user refers to this note, 这篇, 当前, or the open note, use the Open note body in Focus DATA. If that body is truncated, call get_memo. If Focus DATA says the open note is a diagram, call get_diagram. Do not invent structure from the title alone.When the user asks for a mind map, 思维导图, flowchart, 流程图, architecture diagram, or 架构图 of the open note, build it from that body (or get_memo/get_diagram first). To create a new diagram note, call create_diagram_memo. Do not use create_memo, Markdown outlines, or Mermaid. Preserve an explicitly requested type exactly: 思维导图/mind map means kind=mind-map, 流程图/flowchart means kind=flowchart, and 架构图/architecture diagram means kind=architecture. For mind maps, supply a root node and children with parentId; omit node type. If the user did not name a notebook, omit notebookId so it is saved in the inbox notebook (等待分类). Do not ask which notebook, and do not use the open notebook unless the user named it. Reply with the new note link.When the user asks for an infographic, 信息图, 資訊圖, or インフォグラフィック, call create_infographic_memo. Do not use create_diagram_memo, create_memo, Markdown, or Mermaid for that request. A share, proportion, or 占比 is a pie infographic: template chart-pie-donut-plain-text and numeric data.values, not a mind map. If the user did not supply the figures, say in data.desc that they are illustrative and are not an official disclosure. If the user did not name a notebook, omit notebookId. Reply with the new note link.+When the user asks for a 多维表格, 多維表格, or structured table, call create_table_memo with explicit fields. Do not use create_memo or a Markdown table. If no records were supplied or requested, leave it empty. If records were requested, call get_table_records for the new table's field IDs and revision before add_table_record. Omit notebookId when no notebook was named. Reply with the new note link.To change an existing diagram, call get_diagram then update_diagram. Do not create a second diagram unless the user asked for a new note. Do not use update_memo or Mermaid for diagrams.-A structured table cannot be replaced with update_memo. Answer from the open note body or get_memo, and do not rewrite its Markdown.+A structured table cannot be replaced with update_memo. Use get_table_records to read its structure and records. Do not rewrite its Markdown.You can list, create, update, use, and delete note templates, and list, create, update, and delete AI instructions. use_note_template creates a memo immediately. You cannot empty the trash, share notes, or upload files. Do not claim those tools exist.Call get_memo only when you must quote, summarize, or edit one specific note; even then quote at most a short phrase and always include the link.Say when evidence is missing or truncated.diff --git a/apps/api/src/companion-tool-actions.test.mjs b/apps/api/src/companion-tool-actions.test.mjsindex 7bd33352..0fb7e64a 100644--- a/apps/api/src/companion-tool-actions.test.mjs+++ b/apps/api/src/companion-tool-actions.test.mjs@@ -5,7 +5,7 @@ import { Hono } from "hono";import { createSelfHostedStorageAdapter } from "./self-hosted-storage-adapter.ts";import { registerCompanionRoutes } from "./companion-routes.ts";import { beginCompanionTurn, checkpointCompanionTurn, clearCompanionHistory, saveCompanionMemory } from "./companion-service.ts";-import { createDefaultTableDocument, parseDiagramDocument, parseInfographicDocument, serializeTableDocument } from "@edgeever/shared";+import { createDefaultTableDocument, parseDiagramDocument, parseInfographicDocument, parseTableDocument, serializeTableDocument } from "@edgeever/shared";import { createMemoRecord, getMemoDetail, normalizeSearchTimeBound, updateMemoRecord } from "./memo-service.ts";import { companionWorkspaceCursor, proposeCompanionToolAction } from "./companion-tool-actions.ts";import { getCompanionAction, applyCompanionAction, dismissCompanionAction } from "./companion-actions.ts";@@ -49,7 +49,7 @@ async function setup() {describe("shared companion MCP adapter", () => {test("reuses the exact reviewed MCP definitions, with no administration or upload tools", () => {- expect(COMPANION_MCP_TOOLS).toHaveLength(44);+ expect(COMPANION_MCP_TOOLS).toHaveLength(47);for (const definition of COMPANION_MCP_TOOLS) expect(MCP_TOOLS.includes(definition)).toBe(true);for (const name of ["upload_memo_image", "upload_memo_attachment", "empty_trash", "share_memo"]) {expect(() => validateCompanionTool(name, {})).toThrow();@@ -115,7 +115,7 @@ describe("shared companion MCP adapter", () => {test("read and dry-run tools reuse MCP without writing or requiring a proposal", async () => {const f = await setup();const tools = createCompanionTools({ ...f, scope, signal: new AbortController().signal, assertActive: async () => {}, sources: [] });- expect(Object.keys(tools)).toHaveLength(46);+ expect(Object.keys(tools)).toHaveLength(49);expect(await tools.get_memo.execute({ memoId: f.notes[0].id })).toMatchObject({ content: "One original content" });expect(await tools.trash_memos.execute({ memoIds: [f.notes[0].id], dryRun: true })).toMatchObject({ dryRun: true });expect(await getMemoDetail(f.db, scope.workspaceId, f.notes[0].id)).not.toBeNull();@@ -243,6 +243,43 @@ describe("shared companion MCP adapter", () => {.toContain("eval");expect(f.sqlite.query("SELECT COUNT(*) AS n FROM companion_actions").get().n).toBe(0);});+ test("creates a structured table in the inbox and adds a record using real field IDs", async () => {+ const f = await setup();+ const inboxId = `${scope.workspaceId}_inbox`;+ f.sqlite.query("INSERT INTO notebooks(id, workspace_id, name, slug) VALUES (?, ?, '等待分类', 'inbox')").run(inboxId, scope.workspaceId);+ const input = { ...f.input, message: "帮我生成一个自媒体选题库的多维表格" };+ const definition = companionToolDefinitions(input).find(tool => tool.name === "create_table_memo");+ expect(definition).toBeTruthy();+ expect(definition.inputSchema.required).not.toContain("notebookId");+ expect(definition.description).toContain("editable structured table");+ const sources = [];+ const tools = createCompanionTools({ ...f, input, scope, signal: new AbortController().signal, assertActive: async () => {}, sources });+ const created = await tools.create_table_memo.execute({+ title: "自媒体选题库",+ fields: [+ { name: "选题标题", type: "text" },+ { name: "平台", type: "select", options: ["小红书", "抖音", "公众号"] },+ { name: "计划发布时间", type: "date" },+ ],+ });+ expect(created).toMatchObject({ applied: true, title: "自媒体选题库", notebookId: inboxId, fieldCount: 3 });+ expect(created).not.toHaveProperty("memo");+ expect(sources.map(source => source.id)).toContain(created.id);+ const memo = await getMemoDetail(f.db, scope.workspaceId, created.id);+ expect(parseTableDocument(memo.contentMarkdown)).toMatchObject({ records: [], fields: [+ { name: "选题标题", type: "text" },+ { name: "平台", type: "select", options: ["小红书", "抖音", "公众号"] },+ { name: "计划发布时间", type: "date" },+ ] });+ const table = await tools.get_table_records.execute({ memoId: created.id });+ expect(table).toMatchObject({ memoId: created.id, totalRecords: 0 });+ const cells = Object.fromEntries(table.fields.slice(0, 2).map((field, index) => [field.id, ["秋季选题", "小红书"][index]]));+ const added = await tools.add_table_record.execute({ memoId: created.id, expectedRevision: table.revision, cells });+ expect(added).toMatchObject({ applied: true });+ expect((await tools.get_table_records.execute({ memoId: created.id })).totalRecords).toBe(1);+ expect(parseTableDocument((await getMemoDetail(f.db, scope.workspaceId, created.id)).contentMarkdown).records).toHaveLength(1);+ expect(f.sqlite.query("SELECT COUNT(*) AS n FROM companion_actions").get().n).toBe(0);+ });test("refuses to replace a structured table with update_memo", async () => {const f = await setup();const table = await createMemoRecord(f.db, scope.workspaceId, {diff --git a/apps/api/src/companion-tool-catalog.ts b/apps/api/src/companion-tool-catalog.tsindex 91f151e0..194fe1d4 100644--- a/apps/api/src/companion-tool-catalog.ts+++ b/apps/api/src/companion-tool-catalog.ts@@ -5,7 +5,7 @@ import { AppError } from "./app-error";// Exposure policy, not a second tool implementation/schema registry. New MCP// capabilities must be reviewed rather than silently acquiring user authority.const allowed = new Set([- "get_current_user", "search_memos", "list_memos", "get_memo", "create_memo", "create_diagram_memo", "create_infographic_memo", "get_diagram",+ "get_current_user", "search_memos", "list_memos", "get_memo", "create_memo", "create_table_memo", "get_table_records", "add_table_record", "create_diagram_memo", "create_infographic_memo", "get_diagram","update_diagram","import_memos", "update_memo","trash_memos", "restore_memos", "move_memos", "add_tags_to_memos", "remove_tags_from_memos",diff --git a/apps/api/src/companion-tool-receipts.ts b/apps/api/src/companion-tool-receipts.tsindex e16f5437..25aab91e 100644--- a/apps/api/src/companion-tool-receipts.ts+++ b/apps/api/src/companion-tool-receipts.ts@@ -33,8 +33,10 @@ export function describeCompanionTool(const memos = Array.isArray(record?.memos) ? record.memos : [];return memos.slice(0, 5).map(item => effect("listed", asMemo(item)));}- if (name === "get_memo" || name === "get_diagram") return [effect("read", memo ?? { id: String(args.memoId ?? record?.id ?? "") })];- if (name === "create_memo" || name === "create_diagram_memo" || name === "create_infographic_memo" || name === "use_note_template") {+ if (name === "get_memo" || name === "get_diagram" || name === "get_table_records") {+ return [effect("read", memo ?? { id: String(args.memoId ?? record?.memoId ?? record?.id ?? "") })];+ }+ if (name === "create_memo" || name === "create_table_memo" || name === "create_diagram_memo" || name === "create_infographic_memo" || name === "use_note_template") {return [effect("created", memo)];}if (name === "update_memo" || name === "update_diagram" || name === "restore_memo_revision") {@@ -42,6 +44,11 @@ export function describeCompanionTool(const before = prior(id);return [effect("updated", memo ?? { id, title: before?.title }, { previousRevision: before?.revision })];}+ if (name === "add_table_record") {+ const id = String(record?.memoId ?? args.memoId ?? "");+ return [effect("updated", { id, revision: typeof record?.revision === "number" ? record.revision : undefined },+ { previousRevision: prior(id)?.revision })];+ }if (name === "merge_memos") {const created = effect("merged", memo);const sources = ids(args.memoIds).filter(id => id !== memo?.id).map(id => effect("trashed", { id, title: prior(id)?.title }));