@agent-native/core 0.22.5 → 0.22.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/dist/agent/engine/builder-engine.d.ts.map +1 -1
  2. package/dist/agent/engine/builder-engine.js +4 -2
  3. package/dist/agent/engine/builder-engine.js.map +1 -1
  4. package/dist/agent/engine/builder-gateway-headers.d.ts +10 -0
  5. package/dist/agent/engine/builder-gateway-headers.d.ts.map +1 -0
  6. package/dist/agent/engine/builder-gateway-headers.js +42 -0
  7. package/dist/agent/engine/builder-gateway-headers.js.map +1 -0
  8. package/dist/agent/engine/index.d.ts +1 -1
  9. package/dist/agent/engine/index.d.ts.map +1 -1
  10. package/dist/agent/engine/index.js +1 -1
  11. package/dist/agent/engine/index.js.map +1 -1
  12. package/dist/agent/engine/registry.d.ts +1 -0
  13. package/dist/agent/engine/registry.d.ts.map +1 -1
  14. package/dist/agent/engine/registry.js +51 -0
  15. package/dist/agent/engine/registry.js.map +1 -1
  16. package/dist/agent/engine/translate-ai-sdk.d.ts.map +1 -1
  17. package/dist/agent/engine/translate-ai-sdk.js +3 -2
  18. package/dist/agent/engine/translate-ai-sdk.js.map +1 -1
  19. package/dist/agent/engine/translate-anthropic.d.ts +38 -2
  20. package/dist/agent/engine/translate-anthropic.d.ts.map +1 -1
  21. package/dist/agent/engine/translate-anthropic.js +221 -6
  22. package/dist/agent/engine/translate-anthropic.js.map +1 -1
  23. package/dist/agent/engine/types.d.ts +4 -2
  24. package/dist/agent/engine/types.d.ts.map +1 -1
  25. package/dist/agent/engine/types.js.map +1 -1
  26. package/dist/agent/production-agent.d.ts.map +1 -1
  27. package/dist/agent/production-agent.js +69 -9
  28. package/dist/agent/production-agent.js.map +1 -1
  29. package/dist/agent/types.d.ts +2 -0
  30. package/dist/agent/types.d.ts.map +1 -1
  31. package/dist/agent/types.js.map +1 -1
  32. package/dist/cli/connect.d.ts +1 -1
  33. package/dist/cli/connect.d.ts.map +1 -1
  34. package/dist/cli/connect.js +5 -2
  35. package/dist/cli/connect.js.map +1 -1
  36. package/dist/cli/create.d.ts.map +1 -1
  37. package/dist/cli/create.js +48 -6
  38. package/dist/cli/create.js.map +1 -1
  39. package/dist/client/MultiTabAssistantChat.d.ts.map +1 -1
  40. package/dist/client/MultiTabAssistantChat.js +4 -3
  41. package/dist/client/MultiTabAssistantChat.js.map +1 -1
  42. package/dist/client/NewWorkspaceAppFlow.d.ts.map +1 -1
  43. package/dist/client/NewWorkspaceAppFlow.js +1 -0
  44. package/dist/client/NewWorkspaceAppFlow.js.map +1 -1
  45. package/dist/client/agent-chat-adapter.d.ts.map +1 -1
  46. package/dist/client/agent-chat-adapter.js +11 -5
  47. package/dist/client/agent-chat-adapter.js.map +1 -1
  48. package/dist/client/api-path.d.ts.map +1 -1
  49. package/dist/client/api-path.js +2 -0
  50. package/dist/client/api-path.js.map +1 -1
  51. package/dist/client/embed-auth.d.ts +4 -0
  52. package/dist/client/embed-auth.d.ts.map +1 -0
  53. package/dist/client/embed-auth.js +102 -0
  54. package/dist/client/embed-auth.js.map +1 -0
  55. package/dist/client/index.d.ts +1 -0
  56. package/dist/client/index.d.ts.map +1 -1
  57. package/dist/client/index.js +1 -0
  58. package/dist/client/index.js.map +1 -1
  59. package/dist/client/mcp-apps/McpAppRenderer.js +6 -1
  60. package/dist/client/mcp-apps/McpAppRenderer.js.map +1 -1
  61. package/dist/client/settings/SettingsPanel.d.ts.map +1 -1
  62. package/dist/client/settings/SettingsPanel.js +7 -3
  63. package/dist/client/settings/SettingsPanel.js.map +1 -1
  64. package/dist/client/use-action.d.ts.map +1 -1
  65. package/dist/client/use-action.js +2 -0
  66. package/dist/client/use-action.js.map +1 -1
  67. package/dist/client/use-chat-models.d.ts.map +1 -1
  68. package/dist/client/use-chat-models.js +4 -3
  69. package/dist/client/use-chat-models.js.map +1 -1
  70. package/dist/client/use-db-sync.d.ts.map +1 -1
  71. package/dist/client/use-db-sync.js +4 -0
  72. package/dist/client/use-db-sync.js.map +1 -1
  73. package/dist/deploy/route-discovery.js +1 -1
  74. package/dist/deploy/route-discovery.js.map +1 -1
  75. package/dist/index.browser.d.ts +1 -0
  76. package/dist/index.browser.d.ts.map +1 -1
  77. package/dist/index.browser.js +1 -0
  78. package/dist/index.browser.js.map +1 -1
  79. package/dist/index.d.ts +2 -0
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +2 -0
  82. package/dist/index.js.map +1 -1
  83. package/dist/mcp/build-server.d.ts.map +1 -1
  84. package/dist/mcp/build-server.js +49 -21
  85. package/dist/mcp/build-server.js.map +1 -1
  86. package/dist/mcp/builtin-tools.d.ts +1 -0
  87. package/dist/mcp/builtin-tools.d.ts.map +1 -1
  88. package/dist/mcp/builtin-tools.js +151 -9
  89. package/dist/mcp/builtin-tools.js.map +1 -1
  90. package/dist/mcp/connect-route.d.ts.map +1 -1
  91. package/dist/mcp/connect-route.js +79 -51
  92. package/dist/mcp/connect-route.js.map +1 -1
  93. package/dist/mcp/embed-app.d.ts +14 -0
  94. package/dist/mcp/embed-app.d.ts.map +1 -0
  95. package/dist/mcp/embed-app.js +191 -0
  96. package/dist/mcp/embed-app.js.map +1 -0
  97. package/dist/mcp/index.d.ts +1 -0
  98. package/dist/mcp/index.d.ts.map +1 -1
  99. package/dist/mcp/index.js +1 -0
  100. package/dist/mcp/index.js.map +1 -1
  101. package/dist/scripts/agent-engines/list-agent-engines.d.ts.map +1 -1
  102. package/dist/scripts/agent-engines/list-agent-engines.js +2 -1
  103. package/dist/scripts/agent-engines/list-agent-engines.js.map +1 -1
  104. package/dist/scripts/agent-engines/manage-agent-engine.d.ts.map +1 -1
  105. package/dist/scripts/agent-engines/manage-agent-engine.js +4 -1
  106. package/dist/scripts/agent-engines/manage-agent-engine.js.map +1 -1
  107. package/dist/scripts/agent-engines/set-agent-engine.d.ts.map +1 -1
  108. package/dist/scripts/agent-engines/set-agent-engine.js +4 -1
  109. package/dist/scripts/agent-engines/set-agent-engine.js.map +1 -1
  110. package/dist/server/action-discovery.d.ts.map +1 -1
  111. package/dist/server/action-discovery.js +10 -1
  112. package/dist/server/action-discovery.js.map +1 -1
  113. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  114. package/dist/server/agent-chat-plugin.js +9 -1
  115. package/dist/server/agent-chat-plugin.js.map +1 -1
  116. package/dist/server/auth.d.ts +7 -6
  117. package/dist/server/auth.d.ts.map +1 -1
  118. package/dist/server/auth.js +28 -13
  119. package/dist/server/auth.js.map +1 -1
  120. package/dist/server/core-routes-plugin.d.ts +2 -0
  121. package/dist/server/core-routes-plugin.d.ts.map +1 -1
  122. package/dist/server/core-routes-plugin.js +7 -0
  123. package/dist/server/core-routes-plugin.js.map +1 -1
  124. package/dist/server/embed-route.d.ts +8 -0
  125. package/dist/server/embed-route.d.ts.map +1 -0
  126. package/dist/server/embed-route.js +71 -0
  127. package/dist/server/embed-route.js.map +1 -0
  128. package/dist/server/embed-session.d.ts +65 -0
  129. package/dist/server/embed-session.d.ts.map +1 -0
  130. package/dist/server/embed-session.js +433 -0
  131. package/dist/server/embed-session.js.map +1 -0
  132. package/dist/server/index.d.ts +2 -0
  133. package/dist/server/index.d.ts.map +1 -1
  134. package/dist/server/index.js +2 -0
  135. package/dist/server/index.js.map +1 -1
  136. package/dist/server/open-route.d.ts.map +1 -1
  137. package/dist/server/open-route.js +10 -0
  138. package/dist/server/open-route.js.map +1 -1
  139. package/dist/server/security-headers.d.ts.map +1 -1
  140. package/dist/server/security-headers.js +4 -2
  141. package/dist/server/security-headers.js.map +1 -1
  142. package/dist/shared/embed-auth.d.ts +6 -0
  143. package/dist/shared/embed-auth.d.ts.map +1 -0
  144. package/dist/shared/embed-auth.js +6 -0
  145. package/dist/shared/embed-auth.js.map +1 -0
  146. package/dist/shared/index.d.ts +1 -0
  147. package/dist/shared/index.d.ts.map +1 -1
  148. package/dist/shared/index.js +1 -0
  149. package/dist/shared/index.js.map +1 -1
  150. package/dist/templates/workspace-core/AGENTS.md +14 -5
  151. package/dist/templates/workspace-root/AGENTS.md +5 -0
  152. package/dist/templates/workspace-root/README.md +3 -0
  153. package/dist/vite/action-types-plugin.d.ts.map +1 -1
  154. package/dist/vite/action-types-plugin.js +10 -1
  155. package/dist/vite/action-types-plugin.js.map +1 -1
  156. package/docs/content/a2a-protocol.md +5 -1
  157. package/docs/content/actions.md +25 -10
  158. package/docs/content/cli-adapters.md +5 -0
  159. package/docs/content/client.md +35 -1
  160. package/docs/content/database.md +29 -0
  161. package/docs/content/dispatch.md +7 -1
  162. package/docs/content/external-agents.md +53 -24
  163. package/docs/content/mcp-protocol.md +1 -1
  164. package/docs/content/messaging.md +1 -1
  165. package/docs/content/onboarding.md +26 -0
  166. package/docs/content/template-content.md +1 -1
  167. package/docs/content/template-dispatch.md +9 -0
  168. package/docs/content/template-starter.md +2 -2
  169. package/package.json +1 -1
  170. package/src/templates/workspace-core/AGENTS.md +14 -5
  171. package/src/templates/workspace-root/AGENTS.md +5 -0
  172. package/src/templates/workspace-root/README.md +3 -0
@@ -1 +1 @@
1
- {"version":3,"file":"action-types-plugin.js","sourceRoot":"","sources":["../../src/vite/action-types-plugin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AAGpB,oEAAoE;AACpE,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC;IACzB,SAAS;IACT,KAAK;IACL,YAAY;IACZ,WAAW;IACX,UAAU;CACX,CAAC,CAAC;AAEH;;;;;;;;GAQG;AACH,MAAM,oBAAoB,GAA+C;IACvE;QACE,IAAI,EAAE,gBAAgB;QACtB,SAAS,EAAE,mDAAmD;KAC/D;IACD;QACE,IAAI,EAAE,kBAAkB;QACxB,SAAS,EAAE,qDAAqD;KACjE;IACD;QACE,IAAI,EAAE,sBAAsB;QAC5B,SAAS,EAAE,yDAAyD;KACrE;IACD;QACE,IAAI,EAAE,yBAAyB;QAC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,EAAE,WAAW,CAAC,CAAC;gBACnD,CAAC;YACH,CAAC,CAAC;YACF,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;YACxB,IAAI,mBAAmB;gBAAE,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC,CAAC;YAC1D,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;YAChC,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,YAAY,CAAC,CAAC;YACnC,qEAAqE;YACrE,uEAAuE;YACvE,6CAA6C;QAC/C,CAAC;KACF,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,gCAAgC,CAAC,WAAmB;IAClE,MAAM,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;IACxD,uBAAuB,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;AACnD,CAAC","sourcesContent":["/**\n * Vite plugin that generates end-to-end type-safe action types AND a runtime\n * registry of static imports so bundlers (Nitro on Netlify/Vercel/AWS-Lambda,\n * Rolldown, etc.) include every action file in the server bundle.\n *\n * Watches the `actions/` directory and emits:\n * - `.generated/action-types.d.ts` — type-only module that augments the\n * `ActionRegistry` interface in `@agent-native/core/client`, giving\n * `useActionQuery`/`useActionMutation` full inference.\n * - `.generated/actions-registry.ts` — runtime registry keyed by action\n * name, with static `import` statements for every action. Templates\n * import this file from their `server/plugins/agent-chat.ts` so Nitro\n * bundles the actions into the server function; without it the runtime\n * `fs.readdirSync` inside `autoDiscoverActions` finds nothing in a\n * bundled serverless function and every action route 404s.\n */\nimport path from \"path\";\nimport fs from \"fs\";\nimport type { Plugin } from \"vite\";\n\n/** Files to skip during discovery (matches action-discovery.ts). */\nconst SKIP_FILES = new Set([\n \"helpers\",\n \"run\",\n \"db-connect\",\n \"db-status\",\n \"registry\",\n]);\n\n/**\n * Framework-level sharing actions that must ALWAYS be in the generated\n * registry, even when the template's `actions/` directory doesn't contain\n * them. Each entry maps the action name to the bare-specifier import path so\n * bundlers see a static import and pull the module into the server bundle.\n *\n * Order matters: templates can override by defining a same-named file in\n * their own `actions/` directory — the merge below is skip-existing.\n */\nconst CORE_SHARING_ACTIONS: Array<{ name: string; specifier: string }> = [\n {\n name: \"share-resource\",\n specifier: \"@agent-native/core/sharing/actions/share-resource\",\n },\n {\n name: \"unshare-resource\",\n specifier: \"@agent-native/core/sharing/actions/unshare-resource\",\n },\n {\n name: \"list-resource-shares\",\n specifier: \"@agent-native/core/sharing/actions/list-resource-shares\",\n },\n {\n name: \"set-resource-visibility\",\n specifier: \"@agent-native/core/sharing/actions/set-resource-visibility\",\n },\n {\n name: \"upload-image\",\n specifier: \"@agent-native/core/file-upload/actions/upload-image\",\n },\n];\n\nfunction scanActionFiles(actionsDir: string): string[] {\n let files: string[];\n try {\n files = fs.readdirSync(actionsDir);\n } catch {\n return [];\n }\n return files.filter((f) => {\n if (!f.endsWith(\".ts\") && !f.endsWith(\".js\")) return false;\n const name = f.replace(/\\.(ts|js)$/, \"\");\n if (name.startsWith(\"_\")) return false;\n if (SKIP_FILES.has(name)) return false;\n // Only include files that actually call defineAction or explicitly\n // re-export a package action. CLI scripts or example templates that live\n // in actions/ but don't export an action would otherwise drag their own\n // (often app/, browser-only, or fs-only) imports into the serverless\n // bundle and fail to resolve.\n try {\n const content = fs.readFileSync(path.join(actionsDir, f), \"utf-8\");\n const reexportsDefaultAction =\n /export\\s*\\{\\s*default\\s*\\}\\s*from\\s*[\"'][^\"']+[\"']/.test(content);\n if (!content.includes(\"defineAction\") && !reexportsDefaultAction) {\n return false;\n }\n } catch {\n return false;\n }\n return true;\n });\n}\n\nfunction toIdent(name: string): string {\n return \"a_\" + name.replace(/[^a-zA-Z0-9_]/g, \"_\");\n}\n\nfunction writeIfChanged(outFile: string, content: string): void {\n const existing = fs.existsSync(outFile)\n ? fs.readFileSync(outFile, \"utf-8\")\n : \"\";\n if (existing !== content) {\n fs.mkdirSync(path.dirname(outFile), { recursive: true });\n fs.writeFileSync(outFile, content);\n }\n}\n\nfunction findWorkspaceCoreActionsDir(projectRoot: string): string | null {\n let dir = path.resolve(projectRoot);\n let workspaceRoot: string | null = null;\n let packageName: string | null = null;\n\n for (let i = 0; i < 20; i++) {\n const pkgPath = path.join(dir, \"package.json\");\n if (fs.existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n const declared = pkg?.[\"agent-native\"]?.workspaceCore;\n if (typeof declared === \"string\" && declared.length > 0) {\n workspaceRoot = dir;\n packageName = declared;\n break;\n }\n } catch {\n // Keep walking on malformed package.json.\n }\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n\n if (!workspaceRoot || !packageName) return null;\n\n const nm = path.join(workspaceRoot, \"node_modules\", packageName);\n if (fs.existsSync(path.join(nm, \"package.json\"))) {\n const actionsDir = path.join(fs.realpathSync(nm), \"actions\");\n return fs.existsSync(actionsDir) ? actionsDir : null;\n }\n\n const packagesDir = path.join(workspaceRoot, \"packages\");\n const candidates: string[] = [];\n if (fs.existsSync(packagesDir)) {\n for (const entry of fs.readdirSync(packagesDir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n candidates.push(path.join(packagesDir, entry.name));\n if (entry.name.startsWith(\"@\")) {\n const scopeDir = path.join(packagesDir, entry.name);\n for (const sub of fs.readdirSync(scopeDir, { withFileTypes: true })) {\n if (sub.isDirectory()) candidates.push(path.join(scopeDir, sub.name));\n }\n }\n }\n }\n\n for (const candidate of candidates) {\n const pkgPath = path.join(candidate, \"package.json\");\n if (!fs.existsSync(pkgPath)) continue;\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n if (pkg?.name === packageName) {\n const actionsDir = path.join(candidate, \"actions\");\n return fs.existsSync(actionsDir) ? actionsDir : null;\n }\n } catch {\n // Ignore malformed package.json.\n }\n }\n\n return null;\n}\n\n/**\n * Scan the actions directory and emit the types + runtime registry files.\n * Only writes files whose content has changed, to avoid triggering rebuilds.\n */\nfunction generateActionArtifacts(\n actionsDir: string,\n projectRoot: string,\n): void {\n const outDir = path.resolve(projectRoot, \".generated\");\n const relActionsDir = path.relative(outDir, actionsDir).replace(/\\\\/g, \"/\");\n\n const actionFiles = scanActionFiles(actionsDir);\n const workspaceActionsDir = findWorkspaceCoreActionsDir(projectRoot);\n const workspaceActionFiles = workspaceActionsDir\n ? scanActionFiles(workspaceActionsDir)\n : [];\n\n // Pre-compute template action names — used for skip-existing logic in both\n // the type declarations and the runtime registry below.\n const templateActionNames = new Set<string>(\n actionFiles.map((f) => f.replace(/\\.(ts|js)$/, \"\")),\n );\n const registeredActionNames = new Set(templateActionNames);\n\n const actionSources = actionFiles.map((f) => {\n const name = f.replace(/\\.(ts|js)$/, \"\");\n return {\n name,\n relPath: `${relActionsDir}/${name}`,\n };\n });\n\n if (workspaceActionsDir) {\n for (const f of workspaceActionFiles) {\n const name = f.replace(/\\.(ts|js)$/, \"\");\n if (registeredActionNames.has(name)) continue;\n const relPath = path\n .relative(outDir, path.join(workspaceActionsDir, name))\n .replace(/\\\\/g, \"/\");\n actionSources.push({ name, relPath });\n registeredActionNames.add(name);\n }\n }\n\n // --- types file ---------------------------------------------------------\n const typeEntries = actionSources.map(({ name, relPath }) => {\n return ` \"${name}\": ActionEntry<typeof import(\"${relPath}\")>;`;\n });\n\n // Also declare types for framework-level sharing actions so callers don't\n // need `as any` casts (same skip-existing logic as the runtime registry).\n for (const entry of CORE_SHARING_ACTIONS) {\n if (registeredActionNames.has(entry.name)) continue;\n typeEntries.push(\n ` \"${entry.name}\": ActionEntry<typeof import(\"${entry.specifier}\")>;`,\n );\n registeredActionNames.add(entry.name);\n }\n\n const typesContent = `// AUTO-GENERATED by @agent-native/core — do not edit manually.\n// Regenerated when files in actions/ change.\n// This file augments the ActionRegistry interface so that useActionQuery and\n// useActionMutation infer the correct types from your action definitions.\n\n/** Extract the return type and parameter type from a defineAction module. */\ntype ActionEntry<T> = T extends { default: { run: (...args: infer A) => infer R } }\n ? {\n result: Awaited<R>;\n params: A extends [infer P, ...any[]] ? P : Record<string, any>;\n }\n : { result: any; params: Record<string, any> };\n\ndeclare module \"@agent-native/core/client\" {\n interface ActionRegistry {\n${typeEntries.join(\"\\n\")}\n }\n}\n\nexport {};\n`;\n\n writeIfChanged(path.join(outDir, \"action-types.d.ts\"), typesContent);\n\n // --- runtime registry ---------------------------------------------------\n // Static imports of each action's default export so bundlers see every\n // action and include it in the server bundle. Normalization matches\n // `loadActionsIntoRegistry` in server/action-discovery.ts.\n const imports: string[] = [];\n const entries: string[] = [];\n const runtimeActionNames = new Set<string>();\n for (const { name, relPath } of actionSources) {\n const ident = toIdent(name);\n imports.push(`import * as ${ident} from \"${relPath}\";`);\n entries.push(` ${JSON.stringify(name)}: ${ident},`);\n runtimeActionNames.add(name);\n }\n // Framework-level sharing actions — only added when the template hasn't\n // provided a same-named file (skip-existing merge). Static imports ensure\n // bundlers pull these modules into the server bundle so\n // `/_agent-native/actions/share-resource` (etc.) always resolve.\n for (const entry of CORE_SHARING_ACTIONS) {\n if (runtimeActionNames.has(entry.name)) continue;\n const ident = toIdent(entry.name);\n imports.push(`import * as ${ident} from \"${entry.specifier}\";`);\n entries.push(` ${JSON.stringify(entry.name)}: ${ident},`);\n runtimeActionNames.add(entry.name);\n }\n\n const registryContent = `// AUTO-GENERATED by @agent-native/core — do not edit manually.\n// Static-import registry of every action file. Bundlers (Nitro, Rolldown)\n// see these imports and include the action modules in the server bundle.\n// The agent-chat plugin normalizes each module into an ActionEntry shape.\n${imports.join(\"\\n\")}\n\nconst modules: Record<string, unknown> = {\n${entries.join(\"\\n\")}\n};\n\nexport default modules;\n`;\n\n // Always write the registry — even when the template has no actions/ files\n // we still emit imports for the framework-level sharing actions so they get\n // mounted on every template that consumes the registry.\n writeIfChanged(path.join(outDir, \"actions-registry.ts\"), registryContent);\n\n // Ensure .generated/ is in .gitignore\n const gitignorePath = path.join(projectRoot, \".gitignore\");\n if (fs.existsSync(gitignorePath)) {\n const gitignore = fs.readFileSync(gitignorePath, \"utf-8\");\n if (!gitignore.includes(\".generated\")) {\n fs.appendFileSync(gitignorePath, \"\\n.generated/\\n\");\n }\n }\n}\n\n/**\n * Vite plugin that watches `actions/` and generates type-safe action types.\n *\n * Add to your Vite config (auto-included by `defineConfig` from `@agent-native/core`):\n *\n * ```ts\n * import { actionTypesPlugin } from \"@agent-native/core/vite/action-types-plugin\";\n * plugins: [actionTypesPlugin()]\n * ```\n */\nexport function actionTypesPlugin(): Plugin {\n let projectRoot = \"\";\n let actionsDir = \"\";\n let workspaceActionsDir: string | null = null;\n\n return {\n name: \"agent-native-action-types\",\n configResolved(config) {\n projectRoot = config.root;\n actionsDir = path.resolve(projectRoot, \"actions\");\n workspaceActionsDir = findWorkspaceCoreActionsDir(projectRoot);\n },\n buildStart() {\n generateActionArtifacts(actionsDir, projectRoot);\n },\n configureServer(server) {\n // Generate on startup\n generateActionArtifacts(actionsDir, projectRoot);\n\n // Watch for changes in actions/\n const watcher = server.watcher;\n const handleChange = (file: string) => {\n const inAppActions = file.startsWith(actionsDir);\n const inWorkspaceActions = workspaceActionsDir\n ? file.startsWith(workspaceActionsDir)\n : false;\n if ((inAppActions || inWorkspaceActions) && /\\.(ts|js)$/.test(file)) {\n generateActionArtifacts(actionsDir, projectRoot);\n }\n };\n watcher.add(actionsDir);\n if (workspaceActionsDir) watcher.add(workspaceActionsDir);\n watcher.on(\"add\", handleChange);\n watcher.on(\"unlink\", handleChange);\n // Don't regenerate on content changes — only file additions/removals\n // affect the registry. Return type changes are picked up by TypeScript\n // from the source files via typeof import().\n },\n };\n}\n\n/**\n * Public helper to regenerate the types + registry from a non-Vite context\n * (e.g. the Nitro deploy build, where Vite plugins don't run).\n */\nexport function generateActionRegistryForProject(projectRoot: string): void {\n const actionsDir = path.resolve(projectRoot, \"actions\");\n generateActionArtifacts(actionsDir, projectRoot);\n}\n"]}
1
+ {"version":3,"file":"action-types-plugin.js","sourceRoot":"","sources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G,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;IACxD,uBAAuB,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;AACnD,CAAC","sourcesContent":["/**\n * Vite plugin that generates end-to-end type-safe action types AND a runtime\n * registry of static imports so bundlers (Nitro on Netlify/Vercel/AWS-Lambda,\n * Rolldown, etc.) include every action file in the server bundle.\n *\n * Watches the `actions/` directory and emits:\n * - `.generated/action-types.d.ts` — type-only module that augments the\n * `ActionRegistry` interface in `@agent-native/core/client`, giving\n * `useActionQuery`/`useActionMutation` full inference.\n * - `.generated/actions-registry.ts` — runtime registry keyed by action\n * name, with static `import` statements for every action. Templates\n * import this file from their `server/plugins/agent-chat.ts` so Nitro\n * bundles the actions into the server function; without it the runtime\n * `fs.readdirSync` inside `autoDiscoverActions` finds nothing in a\n * bundled serverless function and every action route 404s.\n */\nimport path from \"path\";\nimport fs from \"fs\";\nimport type { Plugin } from \"vite\";\n\n/** Files to skip during discovery (matches action-discovery.ts). */\nconst SKIP_FILES = new Set([\n \"helpers\",\n \"run\",\n \"db-connect\",\n \"db-status\",\n \"registry\",\n]);\n\n/**\n * Framework-level sharing actions that must ALWAYS be in the generated\n * registry, even when the template's `actions/` directory doesn't contain\n * them. Each entry maps the action name to the bare-specifier import path so\n * bundlers see a static import and pull the module into the server bundle.\n *\n * Order matters: templates can override by defining a same-named file in\n * their own `actions/` directory — the merge below is skip-existing.\n */\nconst CORE_SHARING_ACTIONS: Array<{ name: string; specifier: string }> = [\n {\n name: \"share-resource\",\n specifier: \"@agent-native/core/sharing/actions/share-resource\",\n },\n {\n name: \"unshare-resource\",\n specifier: \"@agent-native/core/sharing/actions/unshare-resource\",\n },\n {\n name: \"list-resource-shares\",\n specifier: \"@agent-native/core/sharing/actions/list-resource-shares\",\n },\n {\n name: \"set-resource-visibility\",\n specifier: \"@agent-native/core/sharing/actions/set-resource-visibility\",\n },\n {\n name: \"upload-image\",\n specifier: \"@agent-native/core/file-upload/actions/upload-image\",\n },\n];\n\nfunction isRuntimeSourceFile(filename: string): boolean {\n if (!/\\.(ts|js)$/.test(filename)) return false;\n if (/\\.d\\.ts$/.test(filename)) return false;\n if (/\\.(test|spec)\\.(ts|js)$/.test(filename)) return false;\n return true;\n}\n\nfunction scanActionFiles(actionsDir: string): string[] {\n let files: string[];\n try {\n files = fs.readdirSync(actionsDir);\n } catch {\n return [];\n }\n return files.filter((f) => {\n if (!isRuntimeSourceFile(f)) return false;\n const name = f.replace(/\\.(ts|js)$/, \"\");\n if (name.startsWith(\"_\")) return false;\n if (SKIP_FILES.has(name)) return false;\n // Only include files that actually call defineAction or explicitly\n // re-export a package action. CLI scripts or example templates that live\n // in actions/ but don't export an action would otherwise drag their own\n // (often app/, browser-only, or fs-only) imports into the serverless\n // bundle and fail to resolve.\n try {\n const content = fs.readFileSync(path.join(actionsDir, f), \"utf-8\");\n const reexportsDefaultAction =\n /export\\s*\\{\\s*default\\s*\\}\\s*from\\s*[\"'][^\"']+[\"']/.test(content);\n if (!content.includes(\"defineAction\") && !reexportsDefaultAction) {\n return false;\n }\n } catch {\n return false;\n }\n return true;\n });\n}\n\nfunction toIdent(name: string): string {\n return \"a_\" + name.replace(/[^a-zA-Z0-9_]/g, \"_\");\n}\n\nfunction writeIfChanged(outFile: string, content: string): void {\n const existing = fs.existsSync(outFile)\n ? fs.readFileSync(outFile, \"utf-8\")\n : \"\";\n if (existing !== content) {\n fs.mkdirSync(path.dirname(outFile), { recursive: true });\n fs.writeFileSync(outFile, content);\n }\n}\n\nfunction findWorkspaceCoreActionsDir(projectRoot: string): string | null {\n let dir = path.resolve(projectRoot);\n let workspaceRoot: string | null = null;\n let packageName: string | null = null;\n\n for (let i = 0; i < 20; i++) {\n const pkgPath = path.join(dir, \"package.json\");\n if (fs.existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n const declared = pkg?.[\"agent-native\"]?.workspaceCore;\n if (typeof declared === \"string\" && declared.length > 0) {\n workspaceRoot = dir;\n packageName = declared;\n break;\n }\n } catch {\n // Keep walking on malformed package.json.\n }\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n\n if (!workspaceRoot || !packageName) return null;\n\n const nm = path.join(workspaceRoot, \"node_modules\", packageName);\n if (fs.existsSync(path.join(nm, \"package.json\"))) {\n const actionsDir = path.join(fs.realpathSync(nm), \"actions\");\n return fs.existsSync(actionsDir) ? actionsDir : null;\n }\n\n const packagesDir = path.join(workspaceRoot, \"packages\");\n const candidates: string[] = [];\n if (fs.existsSync(packagesDir)) {\n for (const entry of fs.readdirSync(packagesDir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n candidates.push(path.join(packagesDir, entry.name));\n if (entry.name.startsWith(\"@\")) {\n const scopeDir = path.join(packagesDir, entry.name);\n for (const sub of fs.readdirSync(scopeDir, { withFileTypes: true })) {\n if (sub.isDirectory()) candidates.push(path.join(scopeDir, sub.name));\n }\n }\n }\n }\n\n for (const candidate of candidates) {\n const pkgPath = path.join(candidate, \"package.json\");\n if (!fs.existsSync(pkgPath)) continue;\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n if (pkg?.name === packageName) {\n const actionsDir = path.join(candidate, \"actions\");\n return fs.existsSync(actionsDir) ? actionsDir : null;\n }\n } catch {\n // Ignore malformed package.json.\n }\n }\n\n return null;\n}\n\n/**\n * Scan the actions directory and emit the types + runtime registry files.\n * Only writes files whose content has changed, to avoid triggering rebuilds.\n */\nfunction generateActionArtifacts(\n actionsDir: string,\n projectRoot: string,\n): void {\n const outDir = path.resolve(projectRoot, \".generated\");\n const relActionsDir = path.relative(outDir, actionsDir).replace(/\\\\/g, \"/\");\n\n const actionFiles = scanActionFiles(actionsDir);\n const workspaceActionsDir = findWorkspaceCoreActionsDir(projectRoot);\n const workspaceActionFiles = workspaceActionsDir\n ? scanActionFiles(workspaceActionsDir)\n : [];\n\n // Pre-compute template action names — used for skip-existing logic in both\n // the type declarations and the runtime registry below.\n const templateActionNames = new Set<string>(\n actionFiles.map((f) => f.replace(/\\.(ts|js)$/, \"\")),\n );\n const registeredActionNames = new Set(templateActionNames);\n\n const actionSources = actionFiles.map((f) => {\n const name = f.replace(/\\.(ts|js)$/, \"\");\n return {\n name,\n relPath: `${relActionsDir}/${name}`,\n };\n });\n\n if (workspaceActionsDir) {\n for (const f of workspaceActionFiles) {\n const name = f.replace(/\\.(ts|js)$/, \"\");\n if (registeredActionNames.has(name)) continue;\n const relPath = path\n .relative(outDir, path.join(workspaceActionsDir, name))\n .replace(/\\\\/g, \"/\");\n actionSources.push({ name, relPath });\n registeredActionNames.add(name);\n }\n }\n\n // --- types file ---------------------------------------------------------\n const typeEntries = actionSources.map(({ name, relPath }) => {\n return ` \"${name}\": ActionEntry<typeof import(\"${relPath}\")>;`;\n });\n\n // Also declare types for framework-level sharing actions so callers don't\n // need `as any` casts (same skip-existing logic as the runtime registry).\n for (const entry of CORE_SHARING_ACTIONS) {\n if (registeredActionNames.has(entry.name)) continue;\n typeEntries.push(\n ` \"${entry.name}\": ActionEntry<typeof import(\"${entry.specifier}\")>;`,\n );\n registeredActionNames.add(entry.name);\n }\n\n const typesContent = `// AUTO-GENERATED by @agent-native/core — do not edit manually.\n// Regenerated when files in actions/ change.\n// This file augments the ActionRegistry interface so that useActionQuery and\n// useActionMutation infer the correct types from your action definitions.\n\n/** Extract the return type and parameter type from a defineAction module. */\ntype ActionEntry<T> = T extends { default: { run: (...args: infer A) => infer R } }\n ? {\n result: Awaited<R>;\n params: A extends [infer P, ...any[]] ? P : Record<string, any>;\n }\n : { result: any; params: Record<string, any> };\n\ndeclare module \"@agent-native/core/client\" {\n interface ActionRegistry {\n${typeEntries.join(\"\\n\")}\n }\n}\n\nexport {};\n`;\n\n writeIfChanged(path.join(outDir, \"action-types.d.ts\"), typesContent);\n\n // --- runtime registry ---------------------------------------------------\n // Static imports of each action's default export so bundlers see every\n // action and include it in the server bundle. Normalization matches\n // `loadActionsIntoRegistry` in server/action-discovery.ts.\n const imports: string[] = [];\n const entries: string[] = [];\n const runtimeActionNames = new Set<string>();\n for (const { name, relPath } of actionSources) {\n const ident = toIdent(name);\n imports.push(`import * as ${ident} from \"${relPath}\";`);\n entries.push(` ${JSON.stringify(name)}: ${ident},`);\n runtimeActionNames.add(name);\n }\n // Framework-level sharing actions — only added when the template hasn't\n // provided a same-named file (skip-existing merge). Static imports ensure\n // bundlers pull these modules into the server bundle so\n // `/_agent-native/actions/share-resource` (etc.) always resolve.\n for (const entry of CORE_SHARING_ACTIONS) {\n if (runtimeActionNames.has(entry.name)) continue;\n const ident = toIdent(entry.name);\n imports.push(`import * as ${ident} from \"${entry.specifier}\";`);\n entries.push(` ${JSON.stringify(entry.name)}: ${ident},`);\n runtimeActionNames.add(entry.name);\n }\n\n const registryContent = `// AUTO-GENERATED by @agent-native/core — do not edit manually.\n// Static-import registry of every action file. Bundlers (Nitro, Rolldown)\n// see these imports and include the action modules in the server bundle.\n// The agent-chat plugin normalizes each module into an ActionEntry shape.\n${imports.join(\"\\n\")}\n\nconst modules: Record<string, unknown> = {\n${entries.join(\"\\n\")}\n};\n\nexport default modules;\n`;\n\n // Always write the registry — even when the template has no actions/ files\n // we still emit imports for the framework-level sharing actions so they get\n // mounted on every template that consumes the registry.\n writeIfChanged(path.join(outDir, \"actions-registry.ts\"), registryContent);\n\n // Ensure .generated/ is in .gitignore\n const gitignorePath = path.join(projectRoot, \".gitignore\");\n if (fs.existsSync(gitignorePath)) {\n const gitignore = fs.readFileSync(gitignorePath, \"utf-8\");\n if (!gitignore.includes(\".generated\")) {\n fs.appendFileSync(gitignorePath, \"\\n.generated/\\n\");\n }\n }\n}\n\n/**\n * Vite plugin that watches `actions/` and generates type-safe action types.\n *\n * Add to your Vite config (auto-included by `defineConfig` from `@agent-native/core`):\n *\n * ```ts\n * import { actionTypesPlugin } from \"@agent-native/core/vite/action-types-plugin\";\n * plugins: [actionTypesPlugin()]\n * ```\n */\nexport function actionTypesPlugin(): Plugin {\n let projectRoot = \"\";\n let actionsDir = \"\";\n let workspaceActionsDir: string | null = null;\n\n return {\n name: \"agent-native-action-types\",\n configResolved(config) {\n projectRoot = config.root;\n actionsDir = path.resolve(projectRoot, \"actions\");\n workspaceActionsDir = findWorkspaceCoreActionsDir(projectRoot);\n },\n buildStart() {\n generateActionArtifacts(actionsDir, projectRoot);\n },\n configureServer(server) {\n // Generate on startup\n generateActionArtifacts(actionsDir, projectRoot);\n\n // Watch for changes in actions/\n const watcher = server.watcher;\n const handleChange = (file: string) => {\n const inAppActions = file.startsWith(actionsDir);\n const inWorkspaceActions = workspaceActionsDir\n ? file.startsWith(workspaceActionsDir)\n : false;\n if ((inAppActions || inWorkspaceActions) && /\\.(ts|js)$/.test(file)) {\n generateActionArtifacts(actionsDir, projectRoot);\n }\n };\n watcher.add(actionsDir);\n if (workspaceActionsDir) watcher.add(workspaceActionsDir);\n watcher.on(\"add\", handleChange);\n watcher.on(\"unlink\", handleChange);\n // Don't regenerate on content changes — only file additions/removals\n // affect the registry. Return type changes are picked up by TypeScript\n // from the source files via typeof import().\n },\n };\n}\n\n/**\n * Public helper to regenerate the types + registry from a non-Vite context\n * (e.g. the Nitro deploy build, where Vite plugins don't run).\n */\nexport function generateActionRegistryForProject(projectRoot: string): void {\n const actionsDir = path.resolve(projectRoot, \"actions\");\n generateActionArtifacts(actionsDir, projectRoot);\n}\n"]}
@@ -29,7 +29,7 @@ Most templates get A2A through the framework agent chat plugin. If you are mount
29
29
  import { mountA2A } from "@agent-native/core/a2a";
30
30
 
31
31
  export default defineNitroPlugin((nitro) => {
32
- mountA2A(nitro.h3App, {
32
+ mountA2A(nitro, {
33
33
  name: "Analytics Agent",
34
34
  description: "Runs analytics queries and returns chart data",
35
35
  skills: [
@@ -106,6 +106,10 @@ All methods are called via `POST /_agent-native/a2a` with JSON-RPC 2.0 format:
106
106
 
107
107
  When `message/send` is called with `async: true`, the JSON-RPC handler enqueues the task and self-fires a POST to an internal `/_agent-native/a2a/_process-task` route so the handler runs in a fresh function execution with its own full timeout. This route is authenticated with an HMAC token bound to the task ID (5-minute lifetime, signed with `A2A_SECRET`). It is mounted before the `/_agent-native/a2a` JSON-RPC route so h3's prefix matching does not swallow it.
108
108
 
109
+ > [!IMPORTANT]
110
+ > **Serverless Webhook & Gateway Timeouts:**
111
+ > Hosted environment gateways (such as Netlify, Vercel, or Cloudflare Pages) impose strict execution limits (often 10 to 30 seconds) on public-facing HTTP routes. Because agent loops can take significant time to run queries, fetch context, and execute tools, you **must use `async: true`** when calling A2A endpoints or handling external webhooks. This immediately returns a `working` status to the API gateway, keeping the connection open only for a few milliseconds, while the self-fired `/process-task` POST executes the agent loop in the background. Do not block the primary HTTP request waiting for the agent loop to finish.
112
+
109
113
  Messages contain typed parts:
110
114
 
111
115
  ```json
@@ -112,7 +112,7 @@ For actions that change state:
112
112
  ```tsx
113
113
  import { useActionMutation } from "@agent-native/core/client";
114
114
 
115
- const { mutate, isPending } = useActionMutation("replyToEmail");
115
+ const { mutate, isPending } = useActionMutation("reply-to-email");
116
116
 
117
117
  <Button
118
118
  disabled={isPending}
@@ -131,17 +131,17 @@ For read-only GET actions:
131
131
  ```ts
132
132
  import { useActionQuery } from "@agent-native/core/client";
133
133
 
134
- const { data, isLoading } = useActionQuery("getLead", { leadId });
134
+ const { data, isLoading } = useActionQuery("get-lead", { leadId });
135
135
  ```
136
136
 
137
- The query is cached under `["action", "getLead", { leadId }]` and auto-invalidated on any mutating action that completes.
137
+ The query is cached under `["action", "get-lead", { leadId }]` and auto-invalidated on any mutating action that completes.
138
138
 
139
139
  ## Calling it from the CLI {#cli}
140
140
 
141
141
  Every action is runnable via `pnpm action`:
142
142
 
143
143
  ```bash
144
- pnpm action replyToEmail --emailId thread-123 --body "Thanks!"
144
+ pnpm action reply-to-email --emailId thread-123 --body "Thanks!"
145
145
  ```
146
146
 
147
147
  Flags are parsed into the shape your schema expects. Useful for agent-dev loops, scripts, and cron.
@@ -154,9 +154,26 @@ If your app is an [A2A](/docs/a2a-protocol) peer, other agent-native apps discov
154
154
 
155
155
  With MCP enabled, your actions show up in the framework's MCP server at `/_agent-native/mcp`. Any MCP client — Claude, ChatGPT custom MCP apps, Claude Desktop/Code, Cursor, Codex, etc. — can connect and see them as tools. See [MCP Protocol](/docs/mcp-protocol).
156
156
 
157
- For UI-capable MCP hosts, actions can also attach an optional MCP Apps resource:
157
+ For UI-capable MCP hosts, actions can also attach an optional MCP Apps resource.
158
+ Use the shared full-app embed helper when the action needs an inline experience.
159
+ MCP Apps should embed the real React route; do not hand-write a separate plain
160
+ HTML product UI.
161
+
162
+ The pattern is the same focused link we already return for external agents:
163
+ the action exposes the operation, `link` points at the route with the right URL
164
+ or deep-link params, and `embedApp()` uses that same target as the inline app.
165
+ This works for draft emails, filtered inboxes, calendar event drafts, full
166
+ dashboards, saved analyses, extension routes, decks, design editors, and any
167
+ other state the app can load from a route.
168
+
169
+ When a whole app surface is too much, embed a narrow route that renders a real
170
+ shared React component instead. For example, Analytics can render `/chart` with
171
+ a compact `SqlPanel` URL payload so the MCP host shows one live chart while the
172
+ implementation still reuses the dashboard chart component.
158
173
 
159
174
  ```ts
175
+ import { embedApp } from "@agent-native/core";
176
+
160
177
  export default defineAction({
161
178
  description: "Create an email draft for review.",
162
179
  schema: z.object({ body: z.string() }),
@@ -166,17 +183,15 @@ export default defineAction({
166
183
  url: "/_agent-native/open?app=mail&view=inbox",
167
184
  }),
168
185
  mcpApp: {
169
- resource: {
170
- title: "Review draft",
171
- html: '<!doctype html><html><body><main id="app"></main></body></html>',
172
- csp: { connectDomains: ["https://mail.agent-native.com"] },
173
- },
186
+ resource: embedApp({ title: "Review draft", openLabel: "Open in Mail" }),
174
187
  },
175
188
  });
176
189
  ```
177
190
 
178
191
  This advertises the MCP Apps extension (`io.modelcontextprotocol/ui`), exposes the HTML via MCP resources, and includes both current and legacy UI resource metadata for compatible hosts. Keep `link` as the fallback for CLI and non-UI MCP clients; see [External Agents](/docs/external-agents#mcp-apps).
179
192
 
193
+ The helper launches the action's `link` target through `/_agent-native/embed/start` with a short-lived browser session, so routes such as full dashboards, filtered inboxes, drafts, and extension pages can reuse the app's React components directly.
194
+
180
195
  ## Standard actions {#standard-actions}
181
196
 
182
197
  Every template should include these two for [context awareness](/docs/context-awareness):
@@ -165,6 +165,11 @@ export class DockerAdapter implements CliAdapter {
165
165
  }
166
166
  ```
167
167
 
168
+ > [!WARNING]
169
+ > **Edge and Serverless Compatibility:**
170
+ > CLI adapters (both `ShellCliAdapter` and custom adapters using `node:child_process`) rely on Node.js-specific system bindings (`child_process.execFile` or `child_process.spawn`).
171
+ > These APIs **do not exist** on edge/worker runtimes (e.g., Cloudflare Workers, Netlify Edge Functions). If you deploy your server routes to these edge presets, executing CLI adapters will throw runtime exceptions. Always ensure CLI adapter endpoints and tasks run in standard Node.js environments (like traditional server containers or serverless Node functions).
172
+
168
173
  ## Server route {#server-route}
169
174
 
170
175
  Expose the registry to the UI via an API route so actions and components can discover and invoke CLIs:
@@ -176,7 +176,41 @@ function App() {
176
176
  | `ignoreSource` | `string?` | Per-tab request source to ignore so a tab does not refetch from its own writes |
177
177
  | `onEvent` | `(data) => void` | Optional callback when SSE/polling receives a change event |
178
178
 
179
- For normal CRUD, prefer `useActionQuery` and `useActionMutation`; mutating actions emit `source: "action"` and those hooks refetch automatically. Raw `useQuery` should include `useChangeVersions(["action", "<domain-source>"])` in the query key when it displays data the agent can mutate.
179
+ For normal CRUD, prefer `useActionQuery` and `useActionMutation`; mutating actions emit `source: "action"` and those hooks refetch automatically.
180
+
181
+ ## useChangeVersion / useChangeVersions {#use-change-version}
182
+
183
+ The framework uses change versions to sync React Query caches with changes made by background agents, cron jobs, or other users.
184
+
185
+ When any server-side database mutation occurs, the server records a change event with a specific `source` key. The client's `useDbSync` listener receives these events and bumps the local change version counter for that source. By folding the version counter into your React Query keys, queries automatically refetch whenever the backend notifies the client of new activity.
186
+
187
+ - **`useChangeVersion(source: string): number`** — returns a counter that increments whenever the specified `source` is mutated.
188
+ - **`useChangeVersions(sources: readonly string[]): number`** — returns the sum of version counters for multiple sources.
189
+
190
+ ### Example: Syncing a raw query with the database
191
+
192
+ ```tsx
193
+ import { useQuery } from "@tanstack/react-query";
194
+ import { useChangeVersion } from "@agent-native/core/client";
195
+
196
+ function DashboardView({ id }) {
197
+ // Get version for dashboards domain source
198
+ const v = useChangeVersion("dashboards");
199
+
200
+ const { data } = useQuery({
201
+ queryKey: ["dashboard", id, v], // Invalidate automatically when version bumps
202
+ queryFn: () => fetchDashboard(id),
203
+ placeholderData: (prev) => prev, // Prevent layout flicker during refetch
204
+ });
205
+
206
+ return <div>{data?.title}</div>;
207
+ }
208
+ ```
209
+
210
+ ### Latency Models & Invalidation Behavior
211
+
212
+ - **UI-Initiated mutations:** When you execute an action from the UI using `useActionMutation`, the mutation immediately fires a local event with `source: "action"` on success. This triggers an **instant, optimistic refetch** of all query keys depending on that action, avoiding visual delay.
213
+ - **Background or Agent Mutations:** When the AI agent, a webhook, or a background worker mutates data, the update is broadcast to the client. The client's `useDbSync` captures this either instantly over SSE (Server-Sent Events) or falls back to the **2-second polling tick**. The query key version then bumps, triggering a background refetch.
180
214
 
181
215
  ## cn(...inputs) {#cn}
182
216
 
@@ -74,6 +74,35 @@ For cases where you need raw SQL outside of Drizzle queries:
74
74
  - `isPostgres()` — runtime dialect check
75
75
  - `intType()` — returns the correct integer type for the current dialect
76
76
 
77
+ ## Migrations and Schema Updates {#migrations}
78
+
79
+ In hosted environments, multiple deployment previews, branches, and the production server share the same underlying database. Therefore, database schema updates must follow strict constraints to avoid data loss and service disruption.
80
+
81
+ ### The "Zero Destructive Changes" Rule
82
+
83
+ All database schema updates must be **strictly additive**.
84
+
85
+ - **Do not drop tables or columns.**
86
+ - **Do not rename tables or columns.** Renaming a column or table looks like a drop + create sequence to Drizzle, which will permanently delete your existing production data.
87
+ - If a column needs to be renamed or replaced, add the new column alongside the old one, update your application code to read from/write to both, migrate the data, and only retire the old column in a later release once no active deployments are referencing it.
88
+
89
+ > [!WARNING]
90
+ > **Never run `drizzle-kit push` against a production database.**
91
+ > Template database schemas only define app-specific domain tables; they do not define central framework tables (`user`, `session`, `application_state`, etc.). If you run `drizzle-kit push` against production, Drizzle will detect these framework tables as "not in schema" and attempt to drop them, causing immediate system-wide failure and data loss.
92
+
93
+ ### Safe Migration Path
94
+
95
+ Instead of pushing directly, schema changes should be applied via SQL migrations executed at application startup. Implement additive migrations within a server plugin (e.g., `server/plugins/db.ts`) by invoking the framework's `runMigrations()` helper:
96
+
97
+ ```ts
98
+ import { runMigrations } from "@agent-native/core/db";
99
+
100
+ export default defineNitroPlugin(async () => {
101
+ // Executes pending SQL migrations safely at startup
102
+ await runMigrations();
103
+ });
104
+ ```
105
+
77
106
  ## Environment Variables {#environment-variables}
78
107
 
79
108
  | Variable | Purpose |
@@ -25,7 +25,7 @@ If you're running a single template standalone, you don't need Dispatch — each
25
25
 
26
26
  ## What Dispatch does {#what-it-does}
27
27
 
28
- Five capabilities, all sitting on top of the same workspace database the other apps use.
28
+ Six capabilities, all sitting on top of the same workspace database the other apps use.
29
29
 
30
30
  ### Central inbox
31
31
 
@@ -45,6 +45,12 @@ Dispatch auto-discovers the other apps in your workspace as A2A peers — no man
45
45
 
46
46
  The behavioral rule lives in the dispatch agent's instructions: domain work belongs to the domain app. Dispatch is the orchestrator, not the specialist.
47
47
 
48
+ ### Unified MCP gateway
49
+
50
+ Dispatch can also be the single MCP URL for external agents. Connect Claude, ChatGPT, Codex, Cursor, or another MCP host to `https://dispatch.agent-native.com/_agent-native/mcp` once, then manage which apps that gateway can reach from Dispatch's **Agents** page. The gateway exposes `list_apps`, `ask_app`, and `open_app`, filtered by the selected app grants, so external agents can route work to Mail, Calendar, Analytics, Brain, and workspace apps without a separate browser authorization for every app.
51
+
52
+ Direct per-app MCP URLs still exist when you intentionally want one isolated app surface. For most workspace use, the Dispatch gateway is the lower-friction path.
53
+
48
54
  ### Workspace resources
49
55
 
50
56
  Skills, guardrail instructions, agent profiles, and reference resources can be authored once in Dispatch and inherited by the rest of the workspace. Resources with **All apps** scope are global: Dispatch stores them once at workspace scope, and every app agent reads them at runtime. They are not copied into each app, and there is no manual workspace-resource sync step. App shared resources and personal resources can override or narrow the workspace defaults locally. Selected resources use explicit per-app grants for app-specific exceptions.
@@ -14,12 +14,21 @@ The external-agent bridge closes the loop. First you connect your own agent to a
14
14
 
15
15
  Add the hosted app as a remote MCP connector in your chat host, sign in, and enable it in a chat.
16
16
 
17
- **Shortcut:** every hosted agent-native app serves a one-page connect helper at `https://<app>/_agent-native/mcp/connect` (for example [mail.agent-native.com/\_agent-native/mcp/connect](https://mail.agent-native.com/_agent-native/mcp/connect), [analytics.agent-native.com/\_agent-native/mcp/connect](https://analytics.agent-native.com/_agent-native/mcp/connect)). It shows the MCP URL with a one-click copy button and a tab strip — Claude · ChatGPT · Cursor · Claude Code · Codex · Other — each with the exact steps or copy-able command for that host. Bookmark it and share with non-developer teammates; everything below is also reachable from that page.
17
+ **Recommended for cross-app work:** connect Dispatch once:
18
+
19
+ ```text
20
+ https://dispatch.agent-native.com/_agent-native/mcp
21
+ ```
22
+
23
+ Dispatch exposes a unified MCP gateway with `list_apps`, `ask_app`, and `open_app`. In Dispatch's **Agents** page, choose whether that gateway can reach all apps or only selected apps. This avoids adding Mail, Calendar, Analytics, Brain, and every workspace app as separate MCP resources.
24
+
25
+ **Shortcut:** every hosted agent-native app serves a one-page connect helper at `https://<app>/_agent-native/mcp/connect` (for example [dispatch.agent-native.com/\_agent-native/mcp/connect](https://dispatch.agent-native.com/_agent-native/mcp/connect), [mail.agent-native.com/\_agent-native/mcp/connect](https://mail.agent-native.com/_agent-native/mcp/connect), [analytics.agent-native.com/\_agent-native/mcp/connect](https://analytics.agent-native.com/_agent-native/mcp/connect), or `https://<your-app>/_agent-native/mcp/connect`). It shows the MCP URL with a one-click copy button and a tab strip — Claude · ChatGPT · Cursor · Claude Code · Codex · Other — each with the exact steps or copy-able command for that host. Bookmark it and share with non-developer teammates; everything below is also reachable from that page.
18
26
 
19
27
  Use the hosted app's MCP URL:
20
28
 
21
29
  | App | Remote MCP URL |
22
30
  | --------- | ------------------------------------------------------ |
31
+ | Dispatch | `https://dispatch.agent-native.com/_agent-native/mcp` |
23
32
  | Mail | `https://mail.agent-native.com/_agent-native/mcp` |
24
33
  | Analytics | `https://analytics.agent-native.com/_agent-native/mcp` |
25
34
  | Any app | `https://<app-host>/_agent-native/mcp` |
@@ -61,6 +70,17 @@ ChatGPT's full MCP connector flow is currently workspace/admin gated. Use ChatGP
61
70
 
62
71
  If the ChatGPT workspace does not expose custom MCP connectors, ask a workspace admin to enable them first.
63
72
 
73
+ #### Recovering "Connector name already exists" {#chatgpt-drafts}
74
+
75
+ ChatGPT creates a **draft** the moment you click **Create app** — even if you closed the OAuth popup before approving the scopes. The draft is not visible under **Enabled apps**, but it still owns the name, so retrying with the same name surfaces a `"Connector name already exists"` toast. Recovery is fully self-service in the ChatGPT UI:
76
+
77
+ 1. Open **Settings → Apps**.
78
+ 2. Scroll past **Enabled apps** and **Advanced settings** to the **Drafts** section (labeled _"Private apps you've created in developer mode"_).
79
+ 3. Click the draft with the conflicting name.
80
+ 4. Either press **Connect** to finish OAuth in place (no rename needed), or open the **⋯** overflow menu and choose **Delete** and re-add via **Advanced settings → Create app**.
81
+
82
+ There is no "Drafts" tab on the **Add more / app directory** dialog, so non-admins sometimes miss the section entirely — it lives further down the same Settings → Apps page that lists enabled apps.
83
+
64
84
  ### Cursor {#cursor}
65
85
 
66
86
  1. Open Cursor → **Settings → MCP**.
@@ -82,7 +102,7 @@ Use Agent-Native Analytics to generate a weekly conversion-rate bar chart and sh
82
102
  Use Agent-Native Mail to draft a short follow-up email to me, but do not send it.
83
103
  ```
84
104
 
85
- In hosts that support MCP Apps, Analytics can render charts and dashboards inline, and Mail can render draft-review UI inline. In hosts that do not render MCP Apps, the same tool call still returns a deep link such as **Open draft in Mail →** or **Open chart in Analytics →**.
105
+ In hosts that support MCP Apps, Analytics can render real dashboard and analysis routes inline, and Mail can render the real compose UI inline for draft review. In hosts that do not render MCP Apps, the same tool call still returns a deep link such as **Open draft in Mail →** or **Open dashboard in Analytics →**.
86
106
 
87
107
  ## Advanced setup: local agents {#connect}
88
108
 
@@ -91,13 +111,13 @@ Use this flow for local agent clients on your machine — Claude Code, Claude Co
91
111
  If you have the Agent-Native CLI installed, run:
92
112
 
93
113
  ```bash
94
- agent-native connect https://mail.agent-native.com
114
+ agent-native connect https://dispatch.agent-native.com
95
115
  ```
96
116
 
97
117
  Or run the same command through npm without installing anything globally:
98
118
 
99
119
  ```bash
100
- npx @agent-native/core connect https://mail.agent-native.com
120
+ npx @agent-native/core connect https://dispatch.agent-native.com
101
121
  ```
102
122
 
103
123
  The command asks which local agent clients should receive MCP config. All clients are preselected the first time; after you choose, the selection is saved to `~/.agent-native/connect.json` so the next run can reuse it with Enter, or you can edit the checked items.
@@ -116,7 +136,7 @@ Restart the agent client after connecting so it picks up the new MCP server; OAu
116
136
 
117
137
  Use `--client codex` (or `--client claude-code`, `--client claude-code-cli`, `--client cowork`, `--client all`) to skip the picker for scripts or one-off installs.
118
138
 
119
- Connect every first-party hosted app at once with:
139
+ When you truly need isolated per-app MCP resources, connect every first-party hosted app at once with:
120
140
 
121
141
  ```bash
122
142
  npx @agent-native/core connect --all
@@ -156,7 +176,7 @@ claude mcp add --transport http agent-native-mail \
156
176
  https://mail.agent-native.com/_agent-native/mcp
157
177
  ```
158
178
 
159
- This is the same URL-only entry that `agent-native connect https://mail.agent-native.com --client claude-code` writes for you. Then run `/mcp` in Claude Code and choose **Authenticate**. The client discovers auth from the MCP server's `401 WWW-Authenticate` challenge, fetches `/.well-known/oauth-protected-resource` and `/.well-known/oauth-authorization-server`, dynamically registers a public OAuth client, opens the app's authorization page, and stores the resulting token securely. ChatGPT developer-mode connectors use the same server URL:
179
+ This is the same URL-only entry that `agent-native connect https://dispatch.agent-native.com --client claude-code` writes for you. Then run `/mcp` in Claude Code and choose **Authenticate**. The client discovers auth from the MCP server's `401 WWW-Authenticate` challenge, fetches `/.well-known/oauth-protected-resource` and `/.well-known/oauth-authorization-server`, dynamically registers a public OAuth client, opens the app's authorization page, and stores the resulting token securely. ChatGPT developer-mode connectors use the same server URL:
160
180
 
161
181
  ```text
162
182
  https://mail.agent-native.com/_agent-native/mcp
@@ -199,13 +219,13 @@ Claude Code and other CLI-first clients still receive the same resources and met
199
219
 
200
220
  On top of the per-action tools the MCP server exposes a stable verb set, so an external agent has a predictable surface without guessing per-app action names:
201
221
 
202
- | Tool | Side effects | Returns |
203
- | ------------------------------------------ | ------------ | ------------------------------------------------------------------------------------ |
204
- | `list_apps` | none | workspace apps + their URLs / running state |
205
- | `open_app({ app, view, params? })` | none | a `buildDeepLink` URL (surfaces as an "Open …" link) |
206
- | `ask_app({ app, message })` | agent loop | routes a natural-language task to that app's in-app agent (delegates to `ask-agent`) |
207
- | `create_workspace_app({ name, template })` | scaffolds | a new app booted via the workspace path, plus its running URL + deep link |
208
- | `list_templates` | none | the allow-listed templates only |
222
+ | Tool | Side effects | Returns |
223
+ | -------------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------- |
224
+ | `list_apps` | none | workspace apps + their URLs / running state |
225
+ | `open_app({ app, view?, path?, params?, embed? })` | none | a deep link or same-origin route; `embed: true` renders the full app inline where supported |
226
+ | `ask_app({ app, message })` | agent loop | routes a natural-language task to that app's in-app agent (delegates to `ask-agent`) |
227
+ | `create_workspace_app({ name, template })` | scaffolds | a new app booted via the workspace path, plus its running URL + deep link |
228
+ | `list_templates` | none | the allow-listed templates only |
209
229
 
210
230
  `create_workspace_app` rejects any non-allow-listed template — the public template allow-list in `packages/shared-app-config/templates.ts` is authoritative and CI-guarded; an external agent cannot widen it. A same-named template action overrides a builtin (template-over-core precedence). Disable the whole set with `MCPConfig.builtinCrossAppTools: false`.
211
231
 
@@ -259,29 +279,36 @@ List/search actions point at a record-focused view the same way — e.g. calenda
259
279
 
260
280
  ## Authoring: optional MCP Apps UI {#mcp-apps}
261
281
 
262
- For hosts that support the MCP Apps extension, an action can also advertise an inline HTML UI resource with `mcpApp`. This is a progressive enhancement for flows where the external agent should hand the user an interactive surface instead of only text — for example reviewing an email draft, editing a calendar invite, or choosing between generated dashboard variants.
282
+ For hosts that support the MCP Apps extension, an action can also advertise an inline UI resource with `mcpApp`. This is a progressive enhancement for flows where the external agent should hand the user an interactive surface instead of only text — for example reviewing an email draft, editing a calendar invite, or choosing between generated dashboard variants.
283
+
284
+ Use the real React app with `embedApp()` whenever the user needs UI. The mental model is simple: the action's `link` target is also the MCP App embed target. Expose the operation as a normal action/tool, return a focused deep link with `link`, and add `mcpApp.resource = embedApp(...)` so capable hosts load that same route inline instead of opening a new tab.
285
+
286
+ That means full-app embeds can do anything the route can do once opened: review or edit an email draft, show a filtered inbox/search, open a calendar event or event draft, load an extension page, inspect a full analytics dashboard or saved analysis, continue a deck in the Slides editor, or open a Design project/editor. Prefer URL/deep-link params and the existing `/_agent-native/open` navigation/app-state bridge over inventing a second state protocol for MCP Apps.
287
+
288
+ On rare occasions the right target is a focused app route that renders one shared React component instead of the whole app shell. Analytics' `/chart` route is the model: it takes a compact `SqlPanel` payload in the URL and renders the same chart component the dashboard uses. This is still an app embed, not a plain HTML MCP App. Expose or call it through a normal action / `open_app({ path, embed: true })`, keep the URL deterministic, and let `embedApp()` render that route inline.
289
+
290
+ Do not hand-write one-off plain HTML MCP Apps for product UI; if the action needs a custom surface, add or reuse a real app route/component first and embed that route.
263
291
 
264
292
  ```ts
293
+ import { embedApp } from "@agent-native/core";
294
+
265
295
  export default defineAction({
266
296
  // ...description, schema, run, link...
267
297
  mcpApp: {
268
- resource: {
298
+ resource: embedApp({
269
299
  title: "Review draft",
270
- description: "Review and send the generated email draft.",
271
- html: ({ actionName, requestOrigin }) => `<!doctype html>
272
- <html><body data-action="${actionName}" data-origin="${requestOrigin}">
273
- <main id="app"></main>
274
- </body></html>`,
275
- csp: { connectDomains: ["https://mail.agent-native.com"] },
276
- prefersBorder: true,
277
- },
300
+ description: "Open the generated draft in the real Mail compose UI.",
301
+ iframeTitle: "Agent-Native Mail",
302
+ openLabel: "Open in Mail",
303
+ frameDomains: ["https:", "http://localhost:*", "http://127.0.0.1:*"],
304
+ }),
278
305
  },
279
306
  });
280
307
  ```
281
308
 
282
309
  The MCP server advertises extension `io.modelcontextprotocol/ui`, adds `_meta.ui.resourceUri` plus `_meta["ui/resourceUri"]` to `tools/list`, and exposes the HTML through `resources/list` + `resources/read` using MIME `text/html;profile=mcp-app`. The stdio proxy forwards those resource handlers from the live app, so desktop and CLI clients see the same resources as HTTP clients.
283
310
 
284
- Keep the existing `link` builder even when adding `mcpApp`. CLI-only clients, older hosts, and any host that does not render MCP Apps will ignore the UI metadata and still need the `"Open in … →"` link. Treat `mcpApp.resource.html` like `link`: synchronous, deterministic, and self-contained; declare external origins in `csp`. Use the full app deep link for heavyweight authenticated workflows that do not fit cleanly in an embedded iframe.
311
+ Keep the existing `link` builder even when adding `mcpApp`. CLI-only clients, older hosts, and any host that does not render MCP Apps will ignore the UI metadata and still need the `"Open in … →"` link. `embedApp()` uses that link as its launch target, calls the app-only `create_embed_session` helper, exchanges a one-time SQL ticket at `/_agent-native/embed/start`, and loads the target route in an iframe with a short-lived browser session plus a bearer fallback for same-origin fetches. `open_app({ app, path, embed: true })` is the generic escape hatch for routes such as full dashboards, filtered inboxes, calendar draft views, analyses, and extension pages, and should be used liberally when the full app is the clearest review/edit surface.
285
312
 
286
313
  ### The `link` contract {#link-contract}
287
314
 
@@ -403,6 +430,8 @@ If `connect dev` cannot infer your local owner identity from an existing connect
403
430
 
404
431
  The standard OAuth path never exposes tokens to MCP Apps: the host stores OAuth access/refresh tokens and mediates tool calls and `resources/read` over the authenticated MCP connection. Embedded iframes receive app data and tool results, not bearer secrets.
405
432
 
433
+ Full-app embeds also avoid handing the MCP bearer token to the browser. The MCP caller mints a one-time embed ticket in SQL; the iframe launch route consumes it and sets a short-lived, iframe-safe browser session cookie. The landing URL carries a temporary `__an_embed_token` query param only long enough for the client to capture it, remove it from the address bar, and attach it to same-origin `fetch` calls when third-party cookies are blocked. Embed sessions are route-scoped; app fetches include the current embedded target, and the server rejects token reuse outside the minted route. Production `X-Frame-Options: DENY` stays in place for normal page loads and is omitted only when that embed session marker is present.
434
+
406
435
  The fallback hosted `connect` flow never copies the deployment's shared secret. Instead:
407
436
 
408
437
  - A logged-in browser session mints a **per-user, scoped, revocable** token — an `A2A_SECRET`-signed JWT carrying the caller's `sub` + `org_domain` and a unique `jti`, so every tool run stays tenant-scoped via `runWithRequestContext`.
@@ -72,7 +72,7 @@ POST https://your-app.example.com/_agent-native/mcp
72
72
 
73
73
  The server supports the standard MCP handshake: `initialize` → `initialized` → `tools/list` → `tools/call`.
74
74
 
75
- If an action declares `mcpApp`, the server also advertises the official MCP Apps extension (`io.modelcontextprotocol/ui`) and supports `resources/list`, `resources/templates/list`, and `resources/read` for the app HTML. Hosts that render MCP Apps can show the UI inline; hosts that do not can still call the tool and use the deep-link fallback. The current official extension matrix includes Claude, Claude Desktop, VS Code GitHub Copilot, Goose, Postman, MCPJam, ChatGPT, and Cursor; host support varies by version and plan, so use the [External Agents MCP Apps notes](/docs/external-agents#mcp-apps-compatibility) for the user-facing guidance.
75
+ If an action declares `mcpApp`, the server also advertises the official MCP Apps extension (`io.modelcontextprotocol/ui`) and supports `resources/list`, `resources/templates/list`, and `resources/read` for the app resource. Hosts that render MCP Apps can show the UI inline; hosts that do not can still call the tool and use the deep-link fallback. Product UIs should use `embedApp()` so the inline surface is the real React app route, or a focused route that renders a shared React component such as an Analytics chart, not a separate plain HTML implementation. The current official extension matrix includes Claude, Claude Desktop, VS Code GitHub Copilot, Goose, Postman, MCPJam, ChatGPT, and Cursor; host support varies by version and plan, so use the [External Agents MCP Apps notes](/docs/external-agents#mcp-apps-compatibility) for the user-facing guidance.
76
76
 
77
77
  ## Tools {#tools}
78
78
 
@@ -349,7 +349,7 @@ This means a multi-app workspace fronted by Dispatch is more resilient than a si
349
349
  ### Common pitfalls {#pitfalls}
350
350
 
351
351
  - **Don't double-read the request body.** h3 v2's body stream is consume-once: if you call `readBody(event)` after the framework has already parsed `event.node.req.body` (or vice versa), the second read hangs the request indefinitely. This shows up most often with Resend and SendGrid — both stream the inbound payload and the dangling read never resolves, the platform times out, and the webhook gets retried until it dedups. If you wrap the framework's webhook handler in your own middleware, pass the already-parsed `IncomingMessage` via the `incoming` option rather than letting the handler re-parse.
352
- - **Don't run agent loops inside the webhook handler.** The handler must enqueue and return — the agent loop runs in the processor's fresh execution. Putting it inline guarantees serverless freeze kills the run.
352
+ - **Don't run agent loops inside the webhook handler.** The handler must enqueue and return — the agent loop runs in the processor's fresh execution. Putting it inline guarantees serverless freeze kills the run. Furthermore, public-facing gateway integrations (such as Netlify or Vercel) enforce strict HTTP timeout limits (e.g., Netlify's 10-second request limit). Because agent runs and tools often take longer than this window, trying to run the loop synchronously within the webhook request will cause the gateway to terminate the connection, resulting in aborted execution and dropped replies. The HMAC-signed self-webhook `/process-task` queue pattern is the only way to satisfy gateway limits while executing the full agent loop safely.
353
353
  - **Don't rely on dedup memory across cold starts.** The dedup key lives in the SQL `(platform, external_event_key)` unique index, not an in-process Map. If you replace the queue, keep the SQL-level dedup or duplicate Slack retries will trigger duplicate agent runs.
354
354
  - **Keep the self-webhook URL reachable.** The processor URL is built from `APP_URL` / `URL` / `DEPLOY_URL` / `BETTER_AUTH_URL`, falling back to the inbound request headers. On preview deploys with rewritten hostnames, set one of these explicitly or the dispatch will hit a 404.
355
355
 
@@ -132,6 +132,32 @@ export default defineNitroPlugin(() => {
132
132
  });
133
133
  ```
134
134
 
135
+ ### Checking Workspace Connections in Onboarding
136
+
137
+ When building templates that interact with external services (like Slack, Google Workspace, GitHub, or HubSpot), you should check if the workspace has already connected and granted that provider connection to your application. This prevents users from having to duplicate credentials (like API keys or refresh tokens) in their local environment variables when a central, managed connection exists.
138
+
139
+ You can check connection readiness in your `isComplete` callback using the connection catalog APIs:
140
+
141
+ ```ts
142
+ import { listWorkspaceConnectionProviderCatalogForApp } from "@agent-native/core/workspace-connections";
143
+
144
+ // Inside registerOnboardingStep:
145
+ isComplete: async () => {
146
+ // Check if a managed workspace connection exists and is ready
147
+ const catalog = await listWorkspaceConnectionProviderCatalogForApp("gmail");
148
+ const connection = catalog.find((p) => p.providerId === "google-gmail");
149
+
150
+ if (connection?.status === "ready" && connection.granted) {
151
+ return true;
152
+ }
153
+
154
+ // Fall back to local environment variable check
155
+ return !!process.env.GMAIL_REFRESH_TOKEN;
156
+ };
157
+ ```
158
+
159
+ Refer to the [Workspace Connections](/docs/workspace-connections) documentation for the full list of connection provider catalog methods.
160
+
135
161
  ### Method kinds
136
162
 
137
163
  | Kind | Payload | Use for |
@@ -155,7 +155,7 @@ The four places to look when changing behavior:
155
155
  - **`app/components/editor/`** — the Tiptap editor. Add a new node type under `extensions/` and register it in `DocumentEditor.tsx`. The bubble toolbar, slash menu, and hover previews are all component files you can edit.
156
156
  - **`.agents/skills/`** — guidance the agent reads before acting. If you add a new capability (say, a CMS publishing pipeline), drop a `SKILL.md` in a new skill folder so the agent uses it correctly. Existing skills: `document-editing`, `notion-integration`, `real-time-sync`, `delegate-to-agent`, `storing-data`, `self-modifying-code`, `security`, `frontend-design`, `create-skill`, `capture-learnings`.
157
157
  - **`AGENTS.md`** — the top-level agent guide with the action cheatsheet and common-tasks table. Update it whenever you add a major feature so the agent discovers it without exploring.
158
- - **`server/db/schema.ts`** — data model. Add a column or table here, run `pnpm db:push`, and it's available to every action.
158
+ - **`server/db/schema.ts`** — data model. Add a column or table here. For local development, you can sync your database schema using `pnpm db:push`. In hosted production environments, **never** run `db:push` (doing so will attempt to drop core framework tables not defined in the template's schema); instead, apply schema updates via strictly additive migration scripts executed at startup (see [Database](/docs/database#migrations) for guidelines).
159
159
  - **`shared/notion-markdown.ts`** — markdown-to-Notion-blocks conversion. Extend this if you add new block types that need to round-trip through Notion.
160
160
 
161
161
  The agent can make all of these changes itself — ask it to "add a tags column to documents and expose it in the sidebar" and it will update the schema, migrate, wire the UI, and write the action.
@@ -83,6 +83,15 @@ When Dispatch approval policy is enabled, applying a shared or team-wide dream p
83
83
 
84
84
  Use Dreams when you want to answer questions like "what did agents keep getting wrong this week?", "what should we remember?", or "which repeated lesson deserves a skill?" Inbound Slack, email, Telegram, WhatsApp, and web-derived evidence is treated as untrusted input, so proposals from those sources require review and provenance before they affect shared memory. Workspace-instruction proposals require durable evidence spanning at least two threads or two source apps; eval-only noise, account setup issues, quota limits, and single-app UI wording corrections stay out of global instructions.
85
85
 
86
+ ### Dream Input Validation Boundaries
87
+
88
+ Because evidence is collected from external, untrusted sources (such as chat transcripts, webhooks, and third-party integrations), the Dream processor enforces strict input validation boundaries to prevent prompt injection and payload-size attacks:
89
+
90
+ - **Byte Size Limits:** Individual thread payloads are capped at a maximum of 10KB of text content per message, and candidate scans are truncated if they exceed 100KB in total to prevent context exhaustion.
91
+ - **Sanitization:** All text inputs are sanitized to strip control characters, binary payloads, and non-printable Unicode ranges.
92
+ - **Schema Validation:** Inbound debug data and thread history are parsed against strict Zod schemas before being compiled into LLM prompts. Any candidate structure that fails schema validation is immediately discarded from the processing batch.
93
+ - **Escaping:** All user-provided text chunks are dynamically escaped when formatted into the prompt templates to prevent prompt injections (e.g., trying to hijack the Dream loop to write arbitrary instructions).
94
+
86
95
  In the Dispatch UI, open **Dreams** to run a manual pass, review candidate threads, inspect the report, and open each proposal's review sheet before applying or rejecting it. Use **Settings** to edit the recurring cron schedule, source scope, timeout/concurrency limits, candidate limit, and minimum candidate threshold; use **Ensure schedule** after saving when you want the `jobs/dispatch-dream.md` recurring job materialized from those settings. The review sheet shows approval behavior, the current target content, proposed content, and source evidence. Agents use the same workflow through actions:
87
96
 
88
97
  - `list-dream-candidates` finds recent threads with grounded signals such as explicit user corrections, failed runs, tool errors, feedback, eval failures, and successful checkpointed workflows. Pass `sourceId: "all"` or `sourceIds` to scan multiple thread-debug sources; `sourceTimeoutMs`, `sourceConcurrency`, `sourceStartStaggerMs`, `threadConcurrency`, and `threadTimeoutMs` keep production scans partial and bounded, and the response includes per-source health.