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 lazy runtime loading in plugin routes
tianma-if719665e8e15a
diff --git a/apps/api/src/plugin-capability-routes.ts b/apps/api/src/plugin-capability-routes.tsindex 3ec17f7e..29e8d02b 100644--- a/apps/api/src/plugin-capability-routes.ts+++ b/apps/api/src/plugin-capability-routes.ts@@ -4,7 +4,6 @@ import { bodyLimit } from 'hono/body-limit';import type { Hono } from 'hono';import type { AppEnv, Bindings } from './api-context';import { getAiSettings, loadDefaultAiModel, resolvePrimaryAiCredentialEncryptionKey } from './ai-service';-import { generateAiText } from './ai-runtime';import { apiError } from './http-errors';import { getWorkspaceId, requireUser } from './request-auth';import { PUBLIC_NETWORK_TIMEOUT_MS, publicRequestHeaders, publicResponseHeaders, readPublicBody, validatePublicUrl } from './public-network-policy';@@ -41,6 +40,8 @@ export function registerPluginCapabilityRoutes(app: Hono<AppEnv>, dependencies:const signal = AbortSignal.any([c.req.raw.signal, AbortSignal.timeout(120_000)]);if (dependencies.generate) return c.json(await dependencies.generate(input, signal));const model = await loadDefaultAiModel(c.env.storage.db, getWorkspaceId(c), c.env);+ // Keep provider SDKs out of startup and non-AI plugin requests.+ const { generateAiText } = await import('./ai-runtime');const output = await generateAiText({ model, system: input.system, prompt: input.prompt, maxOutputTokens: input.maxOutputTokens ?? 3000, abortSignal: signal });return c.json({ text: output.text });} catch { return apiError(c, 'plugin_ai_failed', 'AI generation failed or timed out. Check the default AI model configuration.', 502); }diff --git a/docs/personality-memory-agent.md b/docs/personality-memory-agent.mdindex 146f17c2..0200ab73 100644--- a/docs/personality-memory-agent.md+++ b/docs/personality-memory-agent.md@@ -6,6 +6,8 @@ Date: 2026-09-03. Status: an interactive preview is implemented in the workspace## Current preview scope (2026-09-03)+Worker lazy-loading fix (2026-09-03): the previously recorded full-suite failure is resolved. The plugin AI endpoint now imports `ai-runtime` only when generating. The build regression follows the entrypoint's complete static dependency graph, including shared chunks, and excludes AI runtimes and SDKs from startup while confirming they remain reachable on demand. Full non-E2E regression: 1,376 passed, zero failed; web/mobile type checks and the web build passed. No new dependency or migration.+- Entry: Settings → AI integration → Agent mode. Off by default; enabling grants access to all notes in the current account, including child notebooks and future notes, without notebook selection. A small bell opens the discovery panel, without a primary navigation tab or system notifications. “Conversation and personal memory” in settings retains the optional `/companion` workspace. No native Android/iOS entry yet.- Requires a signed-in personal account on a non-demo instance with login enabled and reuses the configured default model. Disabling stops discovery and invalidates unconfirmed discovery actions. The optional conversation workspace keeps its independent per-turn note permission. The prompt library only manages note-processing templates.- One stable identity and an on-demand ToolLoopAgent. Users explicitly add memories or save their own words, correct/forget them and reuse them in new conversations. No automatic candidates, background full-library scanning or reminders. Note writes require individual confirmation; notes are not modified automatically.diff --git a/docs/personality-memory-agent.zh-CN.md b/docs/personality-memory-agent.zh-CN.mdindex afc03afd..7e620453 100644--- a/docs/personality-memory-agent.zh-CN.md+++ b/docs/personality-memory-agent.zh-CN.md@@ -6,6 +6,8 @@## 当前预览范围(2026-09-03)+Worker 按需加载修复(2026-09-03):下文历史记录中的全量测试失败现已解决。插件 AI 接口仅在生成时导入 `ai-runtime`。构建回归检查入口完整的静态依赖图(包括共享 chunk),确保 AI runtime 和 SDK 不进入启动依赖,同时验证它们仍可按需加载。全量非 E2E 回归 1,376 通过、0 失败;Web/移动端类型检查及 Web 构建通过。无新增依赖或迁移。+- 入口:设置 → AI 集成 → Agent 模式。默认关闭;开启后默认可访问当前账户全部笔记,包括子笔记本及以后新建的笔记,无需选择笔记本。小铃铛用于打开发现面板,不占主导航,不发系统通知。设置中的「对话与个人记忆」保留可选的 `/companion` 工作区。原生 Android/iOS 暂无入口。- 仅在开启登录的非 Demo 实例中,对登录个人账户开放,复用配置的默认模型。关闭发现会停止生成,并使尚未确认的发现操作失效;可选对话工作区仍保留独立的每轮笔记授权。指令库只负责笔记处理模板。- 单一稳定身份与按需 ToolLoopAgent。记忆由用户手动添加或从自己的原话保存,支持纠正、忘记和跨新会话使用;不自动提取候选、不后台扫描全库、不执行提醒。笔记写操作须逐项确认,不自动修改笔记。diff --git a/scripts/build-cloudflare-worker.mjs b/scripts/build-cloudflare-worker.mjsindex f1fbb236..41fce442 100644--- a/scripts/build-cloudflare-worker.mjs+++ b/scripts/build-cloudflare-worker.mjs@@ -77,7 +77,7 @@ export const buildCloudflareWorker = async () => {...lazyModules.map((module) =>`[worker-build] on-demand module: ${(module.bytes / 1024).toFixed(2)} KiB`),].join("\n"));- return { entry, sharedModules, lazyModules };+ return { entry, sharedModules, lazyModules, metafile: result.metafile };};if (import.meta.main) {diff --git a/scripts/build-cloudflare-worker.test.mjs b/scripts/build-cloudflare-worker.test.mjsindex 6bb4d911..f8fdfc61 100644--- a/scripts/build-cloudflare-worker.test.mjs+++ b/scripts/build-cloudflare-worker.test.mjs@@ -1,22 +1,94 @@import { expect, test } from "bun:test";import { spawnSync } from "node:child_process";-import { readdirSync, readFileSync, rmSync } from "node:fs";+import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";import { resolve } from "node:path";-test("keeps the AI provider runtime out of the Cloudflare Worker entrypoint", () => {- const outputDirectory = resolve(import.meta.dir, "../.wrangler/edgeever-worker");- rmSync(outputDirectory, { force: true, recursive: true });- const result = spawnSync("bun", [resolve(import.meta.dir, "build-cloudflare-worker.mjs")], {- cwd: resolve(import.meta.dir, ".."),- encoding: "utf8",- });- expect(result.status).toBe(0);+// Metafile imports reference output keys, not paths relative to each chunk.+// Follow the entire static graph: checking index.js alone misses eager shared chunks.+function reachableOutputs(outputs, start, includeDynamic = false) {+ const visited = new Set();+ const pending = [start];+ while (pending.length) {+ const path = pending.pop();+ if (visited.has(path)) continue;+ const output = outputs[path];+ if (!output) throw new Error(`Missing build output: ${path}`);+ visited.add(path);+ for (const dependency of output.imports) {+ if (!dependency.external && (includeDynamic || dependency.kind !== "dynamic-import")) {+ pending.push(dependency.path);+ }+ }+ }+ return visited;+}- const moduleNames = readdirSync(resolve(outputDirectory, "modules"));- const aiRuntimeName = moduleNames.find((name) => name.startsWith("ai-runtime-"));- expect(aiRuntimeName).toBeTruthy();- expect(readFileSync(resolve(outputDirectory, "index.js"), "utf8"))- .not.toContain("edgeever-openai-compatible");- expect(readFileSync(resolve(outputDirectory, "modules", aiRuntimeName), "utf8"))- .toContain("edgeever-openai-compatible");+test("startup graph follows transitive shared chunks and cycles, but not dynamic or external imports", () => {+ const outputs = {+ entry: { imports: [{ path: "shared", kind: "import-statement" }, { path: "lazy", kind: "dynamic-import" }] },+ shared: { imports: [{ path: "runtime", kind: "import-statement" }, { path: "external", kind: "import-statement", external: true }] },+ runtime: { imports: [{ path: "shared", kind: "import-statement" }] },+ lazy: { imports: [] },+ };+ expect([...reachableOutputs(outputs, "entry")].sort()).toEqual(["entry", "runtime", "shared"]);+ expect([...reachableOutputs(outputs, "entry", true)].sort()).toEqual(["entry", "lazy", "runtime", "shared"]);+ expect(() => reachableOutputs(outputs, "missing")).toThrow("Missing build output");+});++test("a lazy facade may share its implementation with another lazy entry without loading it at startup", () => {+ const outputs = {+ entry: { imports: [{ path: "ai", kind: "dynamic-import" }, { path: "agent", kind: "dynamic-import" }] },+ ai: { imports: [{ path: "runtime", kind: "import-statement" }] },+ agent: { imports: [{ path: "runtime", kind: "import-statement" }] },+ runtime: { imports: [] },+ };+ expect([...reachableOutputs(outputs, "entry")]).toEqual(["entry"]);+ expect(reachableOutputs(outputs, "ai").has("runtime")).toBe(true);+ expect(reachableOutputs(outputs, "agent").has("runtime")).toBe(true);+});++test("keeps AI runtimes and SDKs out of the entire Cloudflare Worker startup graph", () => {+ // Keep esbuild's service isolated from Bun's test process, as in the CLI build.+ const directory = mkdtempSync(resolve(tmpdir(), "edgeever-worker-graph-"));+ const metadataPath = resolve(directory, "metadata.json");+ let build;+ try {+ const result = spawnSync("bun", ["--eval", `+ import { writeFileSync } from "node:fs";+ import { buildCloudflareWorker } from ${JSON.stringify(new URL("./build-cloudflare-worker.mjs", import.meta.url).href)};+ const { entry, metafile } = await buildCloudflareWorker();+ writeFileSync(${JSON.stringify(metadataPath)}, JSON.stringify({ entry, metafile: { outputs: metafile.outputs } }));+ `], { cwd: resolve(import.meta.dir, ".."), encoding: "utf8" });+ expect(result.error).toBeUndefined();+ expect(result.status, result.stderr).toBe(0);+ build = JSON.parse(readFileSync(metadataPath, "utf8"));+ } finally {+ rmSync(directory, { recursive: true, force: true });+ }+ const { entry, metafile } = build;+ const startup = reachableOutputs(metafile.outputs, entry.path);+ const all = reachableOutputs(metafile.outputs, entry.path, true);+ const inputsFor = paths => [...new Set([...paths].flatMap(path =>+ Object.entries(metafile.outputs[path].inputs)+ .filter(([, input]) => input.bytesInOutput > 0)+ .map(([input]) => input.replaceAll("\\", "/")),+ ))];+ const runtimeSources = ["ai-runtime", "companion-runtime", "companion-discovery-runtime"]+ .map(name => `apps/api/src/${name}.ts`);+ const isAiInput = path => runtimeSources.includes(path)+ || /(?:^|\/)node_modules\/(?:ai|@ai-sdk\/[^/]+)\//.test(path);+ expect(inputsFor(startup).filter(isAiInput)).toEqual([]);+ // Ensure a passing startup check cannot be explained by dropping AI from the build.+ const allInputs = inputsFor(all);+ for (const source of runtimeSources) {+ expect(allInputs).toContain(source);+ const output = Object.entries(metafile.outputs).find(([, metadata]) => metadata.entryPoint === source);+ expect(output).toBeDefined();+ expect(startup.has(output[0])).toBe(false);+ expect(all.has(output[0])).toBe(true);+ }+ for (const sdk of ["ai", "@ai-sdk/anthropic", "@ai-sdk/google", "@ai-sdk/openai-compatible"]) {+ expect(allInputs.some(path => `/${path}`.includes(`/node_modules/${sdk}/`))).toBe(true);+ }});