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(ai): preserve explicitly requested diagram kind
tianma-if6cf0d4450db8
diff --git a/apps/api/src/companion-agent-tools.ts b/apps/api/src/companion-agent-tools.tsindex c82a0175..962ec7d5 100644--- a/apps/api/src/companion-agent-tools.ts+++ b/apps/api/src/companion-agent-tools.ts@@ -14,6 +14,19 @@ const AUTO_APPLY_WRITES = new Set(COMPANION_MCP_TOOLS.filter(tool => !tool.annotations.readOnlyHint).map(tool => tool.name),);+type ExplicitDiagramKind = "mind-map" | "flowchart" | "architecture";++const EXPLICIT_DIAGRAM_KIND_PATTERNS: Array<[ExplicitDiagramKind, RegExp]> = [+ ["mind-map", /(?:思维导图|思維導圖|心智图|心智圖|腦圖|mind[ -]?map|マインドマップ)/iu],+ ["flowchart", /(?:流程图|流程圖|flow[ -]?chart|フローチャート)/iu],+ ["architecture", /(?:架构图|架構圖|architectur(?:e|al)[ -]?diagram|アーキテクチャ図)/iu],+];++export const explicitDiagramKind = (message: string): ExplicitDiagramKind | undefined => {+ const matches = EXPLICIT_DIAGRAM_KIND_PATTERNS.filter(([, pattern]) => pattern.test(message));+ return matches.length === 1 ? matches[0][0] : undefined;+};+export type CompanionAgentSession = {calls: number;consecutiveErrors: number;@@ -131,12 +144,24 @@ const companionMcpDescription = (definition: (typeof COMPANION_MCP_TOOLS)[numberexport function companionToolDefinitions(input: CompanionTurnInput): CompanionToolDefinition[] {if (!input.allowNotes) return [];+ const requestedDiagramKind = explicitDiagramKind(input.message);return [- ...companionMcpCatalog(input).map(definition => ({- name: definition.name,- description: companionMcpDescription(definition),- inputSchema: definition.inputSchema as Record<string, unknown>,- })),+ ...companionMcpCatalog(input).map(definition => {+ const inputSchema = definition.inputSchema as Record<string, unknown>;+ if (definition.name !== "create_diagram_memo" || !requestedDiagramKind) {+ return { name: definition.name, description: companionMcpDescription(definition), inputSchema };+ }+ const properties = inputSchema.properties as Record<string, unknown>;+ const kind = properties.kind as Record<string, unknown>;+ return {+ name: definition.name,+ description: `${companionMcpDescription(definition)} The user explicitly requested kind=${requestedDiagramKind}; use exactly that kind.`,+ inputSchema: {+ ...inputSchema,+ properties: { ...properties, kind: { ...kind, enum: [requestedDiagramKind] } },+ },+ };+ }),{name: "todo_write",description: "Replace the task list for this run. Use for multi-step work (≥3 steps). Keep at most one item in_progress.",@@ -200,6 +225,11 @@ export function createCompanionTools(args: { db: DatabaseAdapter; scope: Companitry {const { _reason, ...parameters } = input;const { args: parameters_ } = validateCompanionTool(definition.name, parameters);+ const requestedDiagramKind = explicitDiagramKind(args.input.message);+ if (definition.name === "create_diagram_memo" && requestedDiagramKind && parameters_.kind !== requestedDiagramKind) {+ throw new AppError("invalid_params",+ `The user explicitly requested ${requestedDiagramKind}; create_diagram_memo.kind must be ${requestedDiagramKind}.`, 400);+ }const previous = () => new Map([...inspected].map(([id, revision]) => [id, { revision, title: args.sources.find(source => source.id === id)?.title }]));const done = async (payload: unknown) => {if (call.status === "running") {diff --git a/apps/api/src/companion-prepare.ts b/apps/api/src/companion-prepare.tsindex 60506e1e..cc02f5d0 100644--- a/apps/api/src/companion-prepare.ts+++ b/apps/api/src/companion-prepare.ts@@ -40,7 +40,7 @@ When asked what is new, recent, added, created, or updated (最近/新增/本周search_memos matches note titles and bodies, not notebook names. Query is optional. Named tags go through list_tags or search_memos tags.If list_memos or search_memos sets hasMore, say the list is incomplete instead of implying that is everything.When 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. kind is mind-map, flowchart, or architecture. For mind maps, supply a root node and children with parentId; omit node type. If no notebook is named, use the open notebook from Focus DATA. Reply with the new note link.+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 no notebook is named, use the open notebook from Focus DATA. 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.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.diff --git a/apps/api/src/companion-tool-actions.test.mjs b/apps/api/src/companion-tool-actions.test.mjsindex 5f47360b..599dc36d 100644--- a/apps/api/src/companion-tool-actions.test.mjs+++ b/apps/api/src/companion-tool-actions.test.mjs@@ -11,7 +11,7 @@ import { companionWorkspaceCursor, proposeCompanionToolAction } from "./companioimport { getCompanionAction, applyCompanionAction, dismissCompanionAction } from "./companion-actions.ts";import { COMPANION_MCP_TOOLS, validateCompanionTool } from "./companion-tool-catalog.ts";import { MCP_TOOLS } from "./mcp-tools.ts";-import { createCompanionTools } from "./companion-agent-tools.ts";+import { companionToolDefinitions, createCompanionTools, explicitDiagramKind } from "./companion-agent-tools.ts";import { companionExecutionReceipts } from "./companion-runtime.ts";const databases = [];@@ -242,6 +242,31 @@ describe("shared companion MCP adapter", () => {expect(diagram.edges).toMatchObject([{ source: "web", target: "api", kind: "request" }]);expect(diagram.edges[0].id).toBeTruthy();});+ test("an explicit diagram type narrows the Agent schema and rejects a mismatched write", async () => {+ expect(explicitDiagramKind("帮我生成一个架构图笔记作为说明。")).toBe("architecture");+ expect(explicitDiagramKind("Create a flow chart note.")).toBe("flowchart");+ expect(explicitDiagramKind("マインドマップを作成して")).toBe("mind-map");+ expect(explicitDiagramKind("比较思维导图和架构图")).toBeUndefined();++ const f = await setup();+ const agentInput = { ...f.input, message: "帮我生成一个架构图笔记作为说明。" };+ const definition = companionToolDefinitions(agentInput).find(tool => tool.name === "create_diagram_memo");+ expect(definition.inputSchema.properties.kind.enum).toEqual(["architecture"]);+ expect(definition.description).toContain("use exactly that kind");++ const tools = createCompanionTools({ ...f, input: agentInput, scope, signal: new AbortController().signal,+ assertActive: async () => {}, sources: [] });+ const graph = {+ notebookId: "ideas",+ title: "Requested architecture",+ nodes: [{ id: "web", label: "Web", type: "frontend" }],+ };+ await expect(tools.create_diagram_memo.execute({ ...graph, kind: "mind-map" }))+ .rejects.toMatchObject({ code: "invalid_params", message: expect.stringContaining("kind must be architecture") });+ expect(f.sqlite.query("SELECT COUNT(*) AS n FROM memos WHERE title = ?").get(graph.title).n).toBe(0);+ expect(await tools.create_diagram_memo.execute({ ...graph, kind: "architecture" }))+ .toMatchObject({ applied: true, diagramKind: "architecture" });+ });test("note templates and AI instructions execute immediately including deletes", async () => {const f = await setup();const tools = createCompanionTools({ ...f, scope, signal: new AbortController().signal, assertActive: async () => {}, sources: [] });diff --git a/apps/api/src/companion.test.mjs b/apps/api/src/companion.test.mjsindex 61676195..20202837 100644--- a/apps/api/src/companion.test.mjs+++ b/apps/api/src/companion.test.mjs@@ -540,6 +540,7 @@ describe("actual AI SDK companion runtime", () => {expect(COMPANION_INSTRUCTIONS).toContain("after you have already searched");expect(COMPANION_INSTRUCTIONS).toContain("create_diagram_memo");expect(COMPANION_INSTRUCTIONS).toContain("思维导图");+ expect(COMPANION_INSTRUCTIONS).toContain("架构图/architecture diagram means kind=architecture");expect(COMPANION_INSTRUCTIONS).toContain("update_diagram");expect(COMPANION_INSTRUCTIONS).toContain("这篇");expect(COMPANION_INSTRUCTIONS).not.toContain("You cannot create or edit diagrams");