@agent-native/core 0.84.20 → 0.84.22

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 (193) hide show
  1. package/corpus/README.md +1 -1
  2. package/corpus/core/CHANGELOG.md +16 -0
  3. package/corpus/core/package.json +1 -1
  4. package/corpus/core/src/a2a/caller-auth.ts +37 -8
  5. package/corpus/core/src/a2a/client.ts +178 -67
  6. package/corpus/core/src/agent/production-agent.ts +19 -3
  7. package/corpus/core/src/agent/types.ts +1 -1
  8. package/corpus/core/src/cli/pr-visual-recap-workflow.ts +1 -1
  9. package/corpus/core/src/cli/recap.ts +43 -34
  10. package/corpus/core/src/client/AssistantChat.tsx +27 -4
  11. package/corpus/core/src/client/PoweredByBadge.tsx +70 -17
  12. package/corpus/core/src/client/agent-chat-adapter.ts +5 -1
  13. package/corpus/core/src/client/guided-questions.tsx +11 -6
  14. package/corpus/core/src/client/i18n.tsx +10 -5
  15. package/corpus/core/src/client/sse-event-processor.ts +147 -5
  16. package/corpus/core/src/client/tool-display.ts +8 -0
  17. package/corpus/core/src/file-upload/builder.ts +40 -14
  18. package/corpus/core/src/file-upload/types.ts +3 -0
  19. package/corpus/core/src/integrations/a2a-continuation-processor.ts +49 -24
  20. package/corpus/core/src/mcp/builtin-tools.ts +3 -0
  21. package/corpus/core/src/mcp/org-directory.ts +66 -20
  22. package/corpus/core/src/notifications/channels.ts +235 -38
  23. package/corpus/core/src/scripts/call-agent.ts +7 -2
  24. package/corpus/core/src/server/analytics.ts +32 -6
  25. package/corpus/core/src/server/ssr-handler.ts +31 -12
  26. package/corpus/templates/analytics/AGENTS.md +21 -0
  27. package/corpus/templates/analytics/README.md +35 -0
  28. package/corpus/templates/analytics/actions/delete-analytics-alert-rule.ts +23 -0
  29. package/corpus/templates/analytics/actions/list-analytics-alert-rules.ts +20 -0
  30. package/corpus/templates/analytics/actions/run-analytics-alerts.ts +23 -0
  31. package/corpus/templates/analytics/actions/save-analytics-alert-rule.ts +69 -0
  32. package/corpus/templates/analytics/app/pages/sessions/SessionDetailPage.tsx +161 -12
  33. package/corpus/templates/analytics/changelog/2026-07-01-analytics-can-alert-when-first-party-events-spike.md +6 -0
  34. package/corpus/templates/analytics/changelog/2026-07-01-session-replays-load-large-production-recordings-from-scoped.md +6 -0
  35. package/corpus/templates/analytics/changelog/2026-07-01-session-replays-play-back-in-production-instead-of-showing.md +6 -0
  36. package/corpus/templates/analytics/netlify.toml +3 -0
  37. package/corpus/templates/analytics/scripts/emit-netlify-dashboard-report-cron.ts +109 -0
  38. package/corpus/templates/analytics/server/db/schema.ts +55 -0
  39. package/corpus/templates/analytics/server/handlers/session-replay.ts +5 -2
  40. package/corpus/templates/analytics/server/jobs/analytics-alerts.ts +71 -0
  41. package/corpus/templates/analytics/server/lib/analytics-alerts.ts +734 -0
  42. package/corpus/templates/analytics/server/lib/session-replay.ts +10 -3
  43. package/corpus/templates/analytics/server/plugins/analytics-alert-jobs.ts +54 -0
  44. package/corpus/templates/analytics/server/plugins/db.ts +100 -0
  45. package/corpus/templates/analytics/server/routes/api/analytics-alerts/run.post.ts +60 -0
  46. package/corpus/templates/assets/README.md +30 -8
  47. package/corpus/templates/brain/README.md +20 -552
  48. package/corpus/templates/calendar/README.md +22 -28
  49. package/corpus/templates/calendar/app/pages/BookingPage.tsx +14 -8
  50. package/corpus/templates/calendar/changelog/2026-07-01-meeting-invite-pages-have-cleaner-branding-a-black-dark-mo.md +6 -0
  51. package/corpus/templates/chat/README.md +32 -0
  52. package/corpus/templates/clips/README.md +37 -0
  53. package/corpus/templates/clips/actions/create-recording.ts +7 -2
  54. package/corpus/templates/clips/actions/finalize-recording.ts +11 -0
  55. package/corpus/templates/clips/actions/get-recording-player-data.ts +4 -2
  56. package/corpus/templates/clips/actions/import-loom-recording.ts +1 -0
  57. package/corpus/templates/clips/actions/lib/loom-video.ts +16 -0
  58. package/corpus/templates/clips/app/components/library/library-grid.tsx +18 -7
  59. package/corpus/templates/clips/app/components/library/recording-card.tsx +42 -5
  60. package/corpus/templates/clips/app/components/player/scrubber.tsx +2 -2
  61. package/corpus/templates/clips/app/components/recorder/countdown-overlay.tsx +4 -3
  62. package/corpus/templates/clips/app/components/recorder/pre-record-panel.tsx +39 -12
  63. package/corpus/templates/clips/app/components/recorder/recorder-engine.ts +106 -2
  64. package/corpus/templates/clips/app/components/recorder/recording-toolbar.tsx +1 -22
  65. package/corpus/templates/clips/app/routes/record.tsx +48 -8
  66. package/corpus/templates/clips/changelog/2026-07-01-clip-uploads-and-loom-imports-finish-sooner-by-skipping-the-.md +6 -0
  67. package/corpus/templates/clips/changelog/2026-07-01-clip-uploads-and-playback-recover-more-reliably-from-storage.md +6 -0
  68. package/corpus/templates/clips/changelog/2026-07-01-desktop-recording-avoids-unsupported-browser-tab-capture.md +6 -0
  69. package/corpus/templates/clips/changelog/2026-07-01-embedded-player-progress-is-easier-to-see-on-dark-videos.md +6 -0
  70. package/corpus/templates/clips/changelog/2026-07-01-loom-imports-show-clear-guidance-when-loom-does-not-provide-a-downloadable-video.md +6 -0
  71. package/corpus/templates/clips/changelog/2026-07-01-move-to-folder-now-opens-folder-choices-directly-instead-of.md +6 -0
  72. package/corpus/templates/clips/changelog/2026-07-01-preserve-in-flight-streaming-uploads-when-the-streaming-kill.md +6 -0
  73. package/corpus/templates/clips/changelog/2026-07-01-recording-controls-are-cleaner-and-the-countdown-uses-shadow.md +6 -0
  74. package/corpus/templates/clips/changelog/2026-07-01-recordings-now-recover-when-final-upload-status-gets-lost.md +6 -0
  75. package/corpus/templates/clips/chrome-extension/public/manifest.json +1 -1
  76. package/corpus/templates/clips/chrome-extension/src/finalize-recovery.ts +7 -224
  77. package/corpus/templates/clips/chrome-extension/src/offscreen.ts +64 -6
  78. package/corpus/templates/clips/desktop/src/lib/recorder.ts +87 -5
  79. package/corpus/templates/clips/server/lib/streaming-upload-mode.ts +7 -0
  80. package/corpus/templates/clips/server/routes/api/uploads/[recordingId]/chunk.post.ts +51 -1
  81. package/corpus/templates/clips/server/routes/api/uploads/[recordingId]/status.get.ts +4 -1
  82. package/corpus/templates/clips/server/routes/api/video/[recordingId].get.ts +96 -1
  83. package/corpus/templates/clips/shared/finalize-recovery.ts +242 -0
  84. package/corpus/templates/content/AGENTS.md +7 -3
  85. package/corpus/templates/content/README.md +22 -34
  86. package/corpus/templates/content/actions/list-trashed-content-databases.ts +4 -0
  87. package/corpus/templates/content/app/components/editor/SlashCommandMenu.tsx +58 -6
  88. package/corpus/templates/content/app/components/sidebar/DocumentSidebar.tsx +257 -24
  89. package/corpus/templates/content/app/components/sidebar/DocumentTreeItem.tsx +41 -15
  90. package/corpus/templates/content/app/i18n/zh-TW.ts +25 -7
  91. package/corpus/templates/content/app/i18n-data.ts +278 -40
  92. package/corpus/templates/content/changelog/2026-06-30-database-once-again-creates-an-inline-database-in-the-curren.md +6 -0
  93. package/corpus/templates/content/shared/api.ts +1 -0
  94. package/corpus/templates/design/AGENTS.md +7 -6
  95. package/corpus/templates/design/README.md +33 -0
  96. package/corpus/templates/design/actions/delete-file.ts +86 -10
  97. package/corpus/templates/design/actions/get-design-snapshot.ts +13 -0
  98. package/corpus/templates/design/actions/present-design-variants.ts +11 -13
  99. package/corpus/templates/design/app/hooks/use-question-flow.ts +2 -2
  100. package/corpus/templates/design/app/pages/DesignEditor.tsx +2 -2
  101. package/corpus/templates/design/changelog/2026-07-01-design-recovers-sooner-when-an-agent-gets-stuck-preparing-a-.md +6 -0
  102. package/corpus/templates/dispatch/README.md +34 -0
  103. package/corpus/templates/forms/README.md +34 -0
  104. package/corpus/templates/macros/README.md +28 -0
  105. package/corpus/templates/mail/README.md +35 -0
  106. package/corpus/templates/plan/README.md +30 -118
  107. package/corpus/templates/plan/app/global.css +1 -1
  108. package/corpus/templates/slides/README.md +34 -0
  109. package/corpus/templates/videos/README.md +22 -201
  110. package/dist/a2a/caller-auth.d.ts +1 -0
  111. package/dist/a2a/caller-auth.d.ts.map +1 -1
  112. package/dist/a2a/caller-auth.js +34 -8
  113. package/dist/a2a/caller-auth.js.map +1 -1
  114. package/dist/a2a/client.d.ts +4 -0
  115. package/dist/a2a/client.d.ts.map +1 -1
  116. package/dist/a2a/client.js +148 -58
  117. package/dist/a2a/client.js.map +1 -1
  118. package/dist/agent/production-agent.d.ts.map +1 -1
  119. package/dist/agent/production-agent.js +19 -4
  120. package/dist/agent/production-agent.js.map +1 -1
  121. package/dist/agent/types.d.ts +1 -0
  122. package/dist/agent/types.d.ts.map +1 -1
  123. package/dist/agent/types.js.map +1 -1
  124. package/dist/cli/pr-visual-recap-workflow.d.ts +1 -1
  125. package/dist/cli/pr-visual-recap-workflow.d.ts.map +1 -1
  126. package/dist/cli/pr-visual-recap-workflow.js +1 -1
  127. package/dist/cli/pr-visual-recap-workflow.js.map +1 -1
  128. package/dist/cli/recap.d.ts +3 -3
  129. package/dist/cli/recap.d.ts.map +1 -1
  130. package/dist/cli/recap.js +41 -34
  131. package/dist/cli/recap.js.map +1 -1
  132. package/dist/client/AssistantChat.d.ts.map +1 -1
  133. package/dist/client/AssistantChat.js +28 -4
  134. package/dist/client/AssistantChat.js.map +1 -1
  135. package/dist/client/PoweredByBadge.d.ts +9 -3
  136. package/dist/client/PoweredByBadge.d.ts.map +1 -1
  137. package/dist/client/PoweredByBadge.js +47 -15
  138. package/dist/client/PoweredByBadge.js.map +1 -1
  139. package/dist/client/agent-chat-adapter.d.ts.map +1 -1
  140. package/dist/client/agent-chat-adapter.js +5 -1
  141. package/dist/client/agent-chat-adapter.js.map +1 -1
  142. package/dist/client/guided-questions.d.ts.map +1 -1
  143. package/dist/client/guided-questions.js +10 -6
  144. package/dist/client/guided-questions.js.map +1 -1
  145. package/dist/client/i18n.d.ts +1 -1
  146. package/dist/client/i18n.d.ts.map +1 -1
  147. package/dist/client/i18n.js +6 -2
  148. package/dist/client/i18n.js.map +1 -1
  149. package/dist/client/sse-event-processor.d.ts +2 -0
  150. package/dist/client/sse-event-processor.d.ts.map +1 -1
  151. package/dist/client/sse-event-processor.js +121 -5
  152. package/dist/client/sse-event-processor.js.map +1 -1
  153. package/dist/client/tool-display.d.ts.map +1 -1
  154. package/dist/client/tool-display.js +8 -0
  155. package/dist/client/tool-display.js.map +1 -1
  156. package/dist/collab/awareness.d.ts +2 -2
  157. package/dist/collab/awareness.d.ts.map +1 -1
  158. package/dist/collab/routes.d.ts +1 -1
  159. package/dist/file-upload/builder.d.ts.map +1 -1
  160. package/dist/file-upload/builder.js +26 -8
  161. package/dist/file-upload/builder.js.map +1 -1
  162. package/dist/file-upload/types.d.ts +5 -1
  163. package/dist/file-upload/types.d.ts.map +1 -1
  164. package/dist/file-upload/types.js.map +1 -1
  165. package/dist/integrations/a2a-continuation-processor.js +43 -18
  166. package/dist/integrations/a2a-continuation-processor.js.map +1 -1
  167. package/dist/mcp/builtin-tools.d.ts.map +1 -1
  168. package/dist/mcp/builtin-tools.js +3 -0
  169. package/dist/mcp/builtin-tools.js.map +1 -1
  170. package/dist/mcp/org-directory.d.ts.map +1 -1
  171. package/dist/mcp/org-directory.js +58 -20
  172. package/dist/mcp/org-directory.js.map +1 -1
  173. package/dist/notifications/channels.d.ts +10 -0
  174. package/dist/notifications/channels.d.ts.map +1 -1
  175. package/dist/notifications/channels.js +172 -20
  176. package/dist/notifications/channels.js.map +1 -1
  177. package/dist/notifications/routes.d.ts +3 -3
  178. package/dist/observability/routes.d.ts +5 -5
  179. package/dist/progress/routes.d.ts +1 -1
  180. package/dist/resources/handlers.d.ts +1 -1
  181. package/dist/scripts/call-agent.d.ts.map +1 -1
  182. package/dist/scripts/call-agent.js +2 -2
  183. package/dist/scripts/call-agent.js.map +1 -1
  184. package/dist/server/agent-engine-api-key-route.d.ts +1 -1
  185. package/dist/server/analytics.d.ts +16 -0
  186. package/dist/server/analytics.d.ts.map +1 -1
  187. package/dist/server/analytics.js +30 -7
  188. package/dist/server/analytics.js.map +1 -1
  189. package/dist/server/ssr-handler.d.ts.map +1 -1
  190. package/dist/server/ssr-handler.js +28 -12
  191. package/dist/server/ssr-handler.js.map +1 -1
  192. package/dist/server/transcribe-voice.d.ts +1 -1
  193. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"builtin-tools.js","sourceRoot":"","sources":["../../src/mcp/builtin-tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAKH,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,+BAA+B,EAAE,MAAM,yBAAyB,CAAC;AAE1E,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAe,MAAM,oBAAoB,CAAC;AAQ/D;;;;GAIG;AACH,SAAS,IAAI,CACX,WAAmB,EACnB,UAAmB,EACnB,QAAmB;IAEnB,IAAI,CAAC,UAAU;QAAE,OAAO,EAAE,WAAW,EAAE,CAAC;IACxC,OAAO;QACL,WAAW;QACX,UAAU,EAAE;YACV,IAAI,EAAE,QAAQ;YACd,UAAU,EAAE,UAAU;YACtB,GAAG,CAAC,QAAQ,IAAI,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACrD;KACF,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,YAAY,CAAC,MAAiB;IACrC,OAAO,CAAC,MAAM,CAAC,KAAK,IAAI,MAAM,CAAC,IAAI,IAAI,KAAK,CAAC,CAAC,WAAW,EAAE,CAAC;AAC9D,CAAC;AAED,MAAM,aAAa,GAAG,IAAI,MAAM,CAAC,0BAA0B,CAAC,CAAC;AAC7D,MAAM,8BAA8B,GAAG,MAAM,CAAC;AAC9C,MAAM,0BAA0B,GAAG,MAAM,CAAC;AAC1C,MAAM,wBAAwB,GAAG,KAAK,CAAC;AACvC,MAAM,8BAA8B,GAAG,MAAM,CAAC;AAC9C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QAC1C,oBAAoB,EAAE,sBAAsB,CAAC,WAAW,CAAC;QACzD,OAAO,EAAE,UAAU,CAAC,MAAM,EAAE,WAAW,CAAC;QACxC,cAAc,EAAE,gBAAgB,CAAC,MAAM,EAAE,WAAW,CAAC;QACrD,oBAAoB,EAAE,sBAAsB,EAAE;QAC9C,cAAc,EAAE,iBAAiB,EAAE;KACpC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Generic cross-app MCP tools — a stable verb set every external agent gets\n * regardless of which template it is talking to.\n *\n * These are merged into the MCP action registry by\n * `createMCPServerForRequest` (see `build-server.ts`). **Precedence: template\n * actions win.** If a template defines an action named `list_apps` /\n * `open_app` / `ask_app` / `create_workspace_app` / `list_templates`, the\n * template's `ActionEntry` overwrites the builtin of the same name. This is\n * the same template-over-framework precedence `autoDiscoverActions` uses.\n *\n * | Tool | Side effects | Returns |\n * | --------------------- | ------------ | ---------------------------------------- |\n * | `list_apps` | none | `{ apps: [{ id, url, running }] }` |\n * | `open_app` | none | `{ url }` (+ deep-link `link`) |\n * | `create_embed_session`| ticket mint | `{ startUrl }` for MCP App iframes |\n * | `ask_app` | agent loop | `{ app, routedVia, response }` or task |\n * | `ask_app_status` | none | poll a durable `ask_app` task |\n * | `create_workspace_app`| scaffolds | `{ name, url, port, deepLink }` (+ link) |\n *\n * `open_app` / `create_workspace_app` return an **absolute** URL on the\n * *target* app's origin when it differs from this app (so a workspace link\n * lands in the right app), and a relative path for the same app / standalone.\n * `ask_app` routes to a *different* workspace app over A2A when possible and\n * reports `routedVia: \"a2a\"`; otherwise it answers locally\n * (`routedVia: \"local\"`) and never falsely claims cross-app delegation.\n * | `list_templates` | none | `{ templates: [...] }` (allow-list only) |\n *\n * Node-only at call time (workspace resolution + scaffolding use `fs`), but\n * the module has no top-level Node imports so it bundles fine alongside\n * `mountMCP` — the Node bits are dynamically imported inside `run()`.\n */\n\nimport type { Task } from \"../a2a/types.js\";\nimport type { ActionEntry } from \"../agent/production-agent.js\";\nimport type { ActionTool } from \"../agent/types.js\";\nimport { getConfiguredAppBasePath } from \"../server/app-base-path.js\";\nimport { buildDeepLink } from \"../server/deep-link.js\";\nimport { MCP_APP_CHAT_BRIDGE_QUERY_PARAM } from \"../shared/embed-auth.js\";\nimport type { MCPConfig } from \"./build-server.js\";\nimport { embedApp } from \"./embed-app.js\";\nimport { fetchOrgApps, type OrgApp } from \"./org-directory.js\";\n\n/** Flat map of param name → JSON-schema property. */\ntype Params = Record<\n string,\n { type: string; description?: string; enum?: string[] }\n>;\n\n/**\n * Build an `ActionTool`. `parameters` is wrapped in the\n * `{ type:\"object\", properties, required }` shape `createMCPServerForRequest`\n * forwards verbatim as the MCP tool `inputSchema`.\n */\nfunction tool(\n description: string,\n parameters?: Params,\n required?: string[],\n): ActionTool {\n if (!parameters) return { description };\n return {\n description,\n parameters: {\n type: \"object\",\n properties: parameters,\n ...(required && required.length ? { required } : {}),\n },\n };\n}\n\n/**\n * The canonical app id this MCP server is mounted for. `MCPConfig.appId` is\n * authoritative; fall back to lowercasing `name` (which is the capitalized\n * app id at every call site) for back-compat with configs that predate the\n * `appId` field.\n */\nfunction currentAppId(config: MCPConfig): string {\n return (config.appId || config.name || \"app\").toLowerCase();\n}\n\nconst CONTROL_CHARS = new RegExp(\"[\\\\u0000-\\\\u001f\\\\u007f]\");\nconst ASK_APP_DEFAULT_INLINE_WAIT_MS = 20_000;\nconst ASK_APP_MAX_INLINE_WAIT_MS = 25_000;\nconst ASK_APP_POLL_INTERVAL_MS = 1_500;\nconst ASK_APP_A2A_REQUEST_TIMEOUT_MS = 10_000;\nconst ASK_APP_TERMINAL_STATES = new Set<string>([\n \"completed\",\n \"failed\",\n \"canceled\",\n]);\n\ntype AskAppRequestMeta = { origin?: string; basePath?: string };\n\ninterface AskAppRoute {\n app: string;\n origin: string;\n routedVia: \"local\" | \"a2a\";\n note?: string;\n}\n\ninterface AskAppTaskResult {\n app: string;\n routedVia: \"local\" | \"a2a\";\n taskId: string;\n status: string;\n response?: string;\n error?: string;\n note?: string;\n poll?: {\n tool: \"ask_app_status\";\n arguments: { app: string; taskId: string };\n };\n message?: string;\n}\n\nfunction safeAppPath(raw: unknown): string | null {\n if (typeof raw !== \"string\" || !raw.trim()) return null;\n const value = raw.trim();\n if (CONTROL_CHARS.test(value)) return null;\n if (!value.startsWith(\"/\")) return null;\n if (value.startsWith(\"//\") || value.startsWith(\"/\\\\\")) return null;\n if (/^\\/[a-z][a-z0-9+.-]*:/i.test(value)) return null;\n return value;\n}\n\nfunction appendParamsToPath(\n path: string,\n params: Record<string, string | number | boolean> | undefined,\n): string {\n if (!params || Object.keys(params).length === 0) return path;\n const url = new URL(path, \"http://agent-native.invalid\");\n for (const [key, value] of Object.entries(params)) {\n url.searchParams.set(key, String(value));\n }\n return `${url.pathname}${url.search}${url.hash}`;\n}\n\nfunction viewToAppPath(view: string): string | null {\n const value = view.trim();\n if (!value) return null;\n return safeAppPath(value.startsWith(\"/\") ? value : `/${value}`);\n}\n\nfunction withConfiguredBasePath(path: string): string {\n const base = getConfiguredAppBasePath();\n if (!base || path === base || path.startsWith(`${base}/`)) return path;\n return `${base}${path}`;\n}\n\nfunction withMcpChatBridgeParam(path: string): string {\n try {\n const url = new URL(path, \"http://agent-native.invalid\");\n url.searchParams.set(MCP_APP_CHAT_BRIDGE_QUERY_PARAM, \"1\");\n return `${url.pathname}${url.search}${url.hash}`;\n } catch {\n return path;\n }\n}\n\nfunction agentNativeA2AEndpoint(urlOrOrigin: string): string {\n const value = urlOrOrigin.replace(/\\/+$/, \"\");\n try {\n const parsed = new URL(value);\n const pathname = parsed.pathname.replace(/\\/+$/, \"\");\n if (pathname.endsWith(\"/_agent-native/a2a\") || pathname.endsWith(\"/a2a\")) {\n return value;\n }\n } catch {\n // Fall through and append the conventional Agent Native endpoint.\n }\n return `${value}/_agent-native/a2a`;\n}\n\nfunction selfA2AEndpointUrl(requestMeta?: AskAppRequestMeta): string | null {\n const origin = requestMeta?.origin?.replace(/\\/+$/, \"\");\n if (!origin) return null;\n const basePath = requestMeta?.basePath || getConfiguredAppBasePath();\n return agentNativeA2AEndpoint(`${origin}${basePath}`);\n}\n\nfunction boundedAskAppWaitMs(raw: unknown): number {\n if (raw == null || raw === \"\") return ASK_APP_DEFAULT_INLINE_WAIT_MS;\n const parsed = Number(raw);\n if (!Number.isFinite(parsed)) return ASK_APP_DEFAULT_INLINE_WAIT_MS;\n return Math.max(0, Math.min(ASK_APP_MAX_INLINE_WAIT_MS, Math.trunc(parsed)));\n}\n\nfunction isExplicitAsyncAsk(raw: unknown): boolean {\n return raw === true || raw === \"true\" || raw === 1 || raw === \"1\";\n}\n\nfunction taskState(task: Task): string {\n return String(task.status?.state ?? \"unknown\");\n}\n\nfunction isTerminalTask(task: Task): boolean {\n return ASK_APP_TERMINAL_STATES.has(taskState(task));\n}\n\nfunction taskText(task: Task): string {\n return (\n task.status.message?.parts\n ?.filter(\n (part): part is { type: \"text\"; text: string } => part.type === \"text\",\n )\n .map((part) => part.text)\n .join(\"\\n\")\n .trim() ?? \"\"\n );\n}\n\nfunction askAppTaskResult(route: AskAppRoute, task: Task): AskAppTaskResult {\n const status = taskState(task);\n const response = taskText(task);\n const base = {\n app: route.app,\n routedVia: route.routedVia,\n taskId: task.id,\n status,\n ...(route.note ? { note: route.note } : {}),\n };\n\n if (status === \"completed\") {\n return {\n ...base,\n response: response || \"(no response)\",\n };\n }\n\n if (status === \"failed\" || status === \"canceled\") {\n return {\n ...base,\n ...(response ? { response } : {}),\n error: response || `ask_app task ${status}.`,\n };\n }\n\n return {\n ...base,\n poll: {\n tool: \"ask_app_status\",\n arguments: { app: route.app, taskId: task.id },\n },\n message:\n `ask_app is still ${status}. Call ask_app_status with ` +\n `taskId \"${task.id}\" to retrieve the final response.`,\n };\n}\n\nasync function createA2AClientForAskApp(origin: string): Promise<{\n client: import(\"../a2a/client.js\").A2AClient;\n metadata: Record<string, unknown>;\n}> {\n const { A2AClient } = await import(\"../a2a/client.js\");\n const { resolveA2ACallerAuth } = await import(\"../a2a/caller-auth.js\");\n const auth = await resolveA2ACallerAuth();\n const metadata: Record<string, unknown> = {};\n if (auth.userEmail) metadata.userEmail = auth.userEmail;\n if (auth.orgDomain) metadata.orgDomain = auth.orgDomain;\n return {\n client: new A2AClient(origin, auth.apiKey, {\n requestTimeoutMs: ASK_APP_A2A_REQUEST_TIMEOUT_MS,\n }),\n metadata,\n };\n}\n\nasync function waitForA2ATask(\n client: import(\"../a2a/client.js\").A2AClient,\n initialTask: Task,\n maxWaitMs: number,\n): Promise<Task> {\n if (maxWaitMs <= 0 || isTerminalTask(initialTask)) return initialTask;\n const deadline = Date.now() + maxWaitMs;\n let current = initialTask;\n\n while (!isTerminalTask(current)) {\n const remaining = deadline - Date.now();\n if (remaining <= 0) return current;\n await new Promise((resolve) =>\n setTimeout(resolve, Math.min(ASK_APP_POLL_INTERVAL_MS, remaining)),\n );\n try {\n current = await client.getTask(initialTask.id);\n } catch {\n // Transient status fetch failures should not turn a successfully\n // submitted durable task into a failed MCP call.\n if (Date.now() >= deadline) return current;\n continue;\n }\n }\n\n return current;\n}\n\nasync function submitAskAppA2ATask(\n route: AskAppRoute,\n message: string,\n maxWaitMs: number,\n): Promise<AskAppTaskResult> {\n const { client, metadata } = await createA2AClientForAskApp(route.origin);\n const task = await client.send(\n {\n role: \"user\",\n parts: [{ type: \"text\", text: message }],\n },\n {\n async: true,\n metadata,\n },\n );\n const finalOrRunning = await waitForA2ATask(client, task, maxWaitMs);\n return askAppTaskResult(route, finalOrRunning);\n}\n\nasync function fetchAskAppA2ATask(\n route: AskAppRoute,\n taskId: string,\n): Promise<AskAppTaskResult> {\n const { client } = await createA2AClientForAskApp(route.origin);\n const task = await client.getTask(taskId);\n return askAppTaskResult(route, task);\n}\n\n/**\n * Resolve the absolute origin of a *target* workspace app (e.g.\n * `http://127.0.0.1:8101`) so cross-app deep links / A2A calls point at the\n * right app instead of the current request's origin. Reuses the same\n * workspace resolution `list_apps` / the stdio proxy use.\n *\n * Returns `null` when:\n * - the target is the current app (caller should keep relative behavior),\n * - there is no workspace info (standalone / single app), or\n * - the target app is unknown.\n */\nasync function resolveTargetAppOrigin(\n config: MCPConfig,\n targetAppId: string,\n): Promise<{ origin: string; id: string } | null> {\n const target = targetAppId.trim().toLowerCase();\n if (!target || target === currentAppId(config)) return null;\n try {\n const { resolveWorkspace } = await import(\"./workspace-resolve.js\");\n const ws = await resolveWorkspace();\n if (!ws.isWorkspace) return null;\n const match = ws.apps.find((a) => a.id.toLowerCase() === target);\n if (!match) return null;\n return { origin: match.url, id: match.id };\n } catch {\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// list_apps\n// ---------------------------------------------------------------------------\n\nfunction listAppsTool(\n config: MCPConfig,\n requestMeta?: { origin?: string },\n): ActionEntry {\n return {\n tool: tool(\n \"List the workspace apps and their URLs. Use this to discover which \" +\n \"apps exist before opening or asking one. In a single-app project \" +\n \"this returns just that app. When an org directory is configured \" +\n \"this also includes the org's deployed sibling apps.\",\n ),\n readOnly: true,\n parallelSafe: true,\n run: async () => {\n const { resolveWorkspace } = await import(\"./workspace-resolve.js\");\n const ws = await resolveWorkspace();\n\n // The MCP request is served BY the current app, so it is provably\n // reachable at the inbound request origin — that beats a guessed\n // `PORT || 5173` probe (which reports the wrong URL + `running:false`\n // whenever the dev server picked a non-default port, e.g. `agent-\n // native dev` on :8080). For the entry that IS this app (the sole\n // entry when single-app, or the id matching `config.appId` in a\n // workspace) prefer the live origin; other workspace apps keep their\n // probed values.\n const liveOrigin = requestMeta?.origin?.replace(/\\/+$/, \"\") || \"\";\n let livePort = 0;\n if (liveOrigin) {\n try {\n const u = new URL(liveOrigin);\n livePort = Number(u.port) || (u.protocol === \"https:\" ? 443 : 80);\n } catch {\n livePort = 0;\n }\n }\n const selfId = (config.appId ?? \"\").toLowerCase();\n const isSelf = (id: string) =>\n !!liveOrigin &&\n (!ws.isWorkspace || (!!selfId && id.toLowerCase() === selfId));\n\n interface AppEntry {\n id: string;\n url: string;\n port: number | undefined;\n running: boolean;\n source: \"workspace\" | \"org-directory\";\n }\n\n const apps: AppEntry[] = ws.apps.map((a) =>\n isSelf(a.id)\n ? {\n id: a.id,\n url: liveOrigin,\n port: (livePort || a.port) as number | undefined,\n running: true,\n source: \"workspace\" as const,\n }\n : {\n id: a.id,\n url: a.url,\n port: a.port as number | undefined,\n running: a.running,\n source: \"workspace\" as const,\n },\n );\n const seenIds = new Set(apps.map((a) => a.id.toLowerCase()));\n const seenOrigins = new Set(apps.map((a) => a.url.replace(/\\/+$/, \"\")));\n\n // Merge the org directory's deployed sibling apps. Inactive (no env)\n // or any failure ⇒ fetchOrgApps() returns [] and this is a no-op, so\n // the existing local/workspace behavior is preserved exactly.\n const orgApps = await fetchOrgApps({\n selfId: currentAppId(config),\n }).catch(() => [] as OrgApp[]);\n for (const oa of orgApps) {\n const idKey = oa.id.toLowerCase();\n const originKey = oa.url.replace(/\\/+$/, \"\");\n // Dedupe by id OR origin — a workspace app already listed wins.\n if (seenIds.has(idKey) || seenOrigins.has(originKey)) continue;\n seenIds.add(idKey);\n seenOrigins.add(originKey);\n apps.push({\n id: oa.id,\n url: oa.url,\n port: undefined,\n running: true,\n source: \"org-directory\",\n });\n }\n\n return {\n workspace: ws.isWorkspace,\n gatewayUrl: ws.gatewayUrl,\n apps,\n };\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// open_app\n// ---------------------------------------------------------------------------\n\nfunction openAppTool(\n config: MCPConfig,\n requestMeta?: { origin?: string },\n): ActionEntry {\n return {\n tool: tool(\n \"Build a deep link that opens an app at a specific view/record or \" +\n \"focused route/component. No side \" +\n \"effects — returns a URL the user can click to land in the running UI. \" +\n \"Set embed:true when a UI-capable MCP host should render the live app \" +\n \"or focused route/component inline. Omit view and path to land on the \" +\n \"app's home page.\",\n {\n app: { type: \"string\", description: \"App id, e.g. 'mail'\" },\n view: {\n type: \"string\",\n description:\n \"Target view, e.g. 'inbox' (maps to navigate command). Optional — omit (along with path) to open the app's home page.\",\n },\n path: {\n type: \"string\",\n description:\n \"Optional app route to open directly, e.g. '/extensions/abc', '/adhoc/q2', or '/chart?panel=...'. Must be same-origin relative. Omit (along with view) to open the app's home page.\",\n },\n params: {\n type: \"object\",\n description:\n \"Optional record-focus / filter params, e.g. { threadId: 'abc' }\",\n },\n embed: {\n type: \"boolean\",\n description:\n \"Render the full app or focused route/component inline in MCP Apps when the host supports it.\",\n },\n chrome: {\n type: \"string\",\n enum: [\"full\", \"minimal\"],\n description:\n \"Embed chrome preference for compatible app routes. Defaults to full.\",\n },\n },\n [\"app\"],\n ),\n readOnly: true,\n parallelSafe: true,\n run: async (args: Record<string, any>) => {\n const app = String(args.app ?? \"\").trim();\n const view = String(args.view ?? \"\").trim();\n // `safeAppPath` rejects anything that isn't a leading-slash same-origin\n // path. When the caller passes nothing, fall back to the app's root so a\n // bare `open_app({app:\"dispatch\"})` lands on the home page instead of\n // throwing. The model self-corrects on the retry today, but the extra\n // round-trip wastes a turn and looks broken to the user.\n const path = safeAppPath(args.path) || (view ? null : \"/\");\n if (!app) {\n throw new Error(\"open_app requires 'app'.\");\n }\n let params: Record<string, string | number | boolean> | undefined;\n const raw = args.params;\n if (raw && typeof raw === \"object\") {\n params = raw as Record<string, string | number | boolean>;\n } else if (typeof raw === \"string\" && raw.trim()) {\n try {\n params = JSON.parse(raw);\n } catch {\n params = undefined;\n }\n }\n const embeddedParam = params?.embed;\n const chromeParam = params?.chrome;\n let embed = args.embed === true || args.embed === \"true\";\n if (\n args.embed == null &&\n (embeddedParam === true || embeddedParam === \"true\")\n ) {\n embed = true;\n } else if (\n args.embed == null &&\n (embeddedParam === false || embeddedParam === \"false\")\n ) {\n embed = false;\n }\n if (\n embeddedParam === true ||\n embeddedParam === false ||\n embeddedParam === \"true\" ||\n embeddedParam === \"false\"\n ) {\n delete params?.embed;\n }\n\n const chrome =\n typeof args.chrome === \"string\"\n ? args.chrome\n : chromeParam === \"full\" || chromeParam === \"minimal\"\n ? chromeParam\n : undefined;\n if (chromeParam === \"full\" || chromeParam === \"minimal\") {\n delete params?.chrome;\n }\n if (params && Object.keys(params).length === 0) params = undefined;\n\n const directViewPath = embed && view ? viewToAppPath(view) : null;\n const relUrl = path\n ? appendParamsToPath(path, params)\n : directViewPath\n ? appendParamsToPath(directViewPath, params)\n : buildDeepLink({ app, view, params });\n const sameAppUrl =\n path || directViewPath ? withConfiguredBasePath(relUrl) : relUrl;\n\n // Cross-app target in a workspace: resolve the TARGET app's origin and\n // return an absolute URL. Otherwise the MCP layer would prefix the\n // relative path with the CURRENT request origin, landing the user in\n // the wrong app (e.g. open_app({app:\"calendar\"}) served from Mail).\n // Same-app / standalone keeps the relative path (current behavior).\n const targetApp = await resolveTargetAppOrigin(config, app);\n const appUrl = targetApp\n ? `${targetApp.origin.replace(/\\/+$/, \"\")}${relUrl}`\n : sameAppUrl;\n const url = appUrl;\n let embedStartUrl: string | undefined;\n let embedTargetPath: string | undefined;\n let embedExpiresAt: number | undefined;\n\n if (embed && !targetApp) {\n const { getRequestContext } =\n await import(\"../server/request-context.js\");\n const ctx = getRequestContext();\n const ownerEmail = ctx?.userEmail?.trim();\n if (ownerEmail) {\n const { normalizeEmbedTargetPath, createEmbedSessionTicket } =\n await import(\"../server/embed-session.js\");\n const { buildEmbedStartPath } =\n await import(\"../server/embed-route.js\");\n const targetPath = normalizeEmbedTargetPath(\n withMcpChatBridgeParam(url),\n requestMeta?.origin,\n );\n if (targetPath) {\n const ticket = await createEmbedSessionTicket({\n ownerEmail,\n orgId: ctx?.orgId,\n targetPath,\n scope: chrome ?? null,\n });\n const startPath = buildEmbedStartPath(ticket.ticket);\n embedStartUrl = requestMeta?.origin\n ? new URL(startPath, requestMeta.origin).toString()\n : startPath;\n embedTargetPath = targetPath;\n embedExpiresAt = ticket.expiresAt;\n }\n }\n }\n\n return {\n app,\n ...(view ? { view } : {}),\n ...(path ? { path } : {}),\n url,\n ...(embedStartUrl ? { embedStartUrl } : {}),\n ...(embedTargetPath ? { embedTargetPath } : {}),\n ...(embedExpiresAt ? { embedExpiresAt } : {}),\n embed,\n };\n },\n link: ({ result }) => {\n if (!result || typeof result !== \"object\") return null;\n const r = result as {\n url?: string;\n app?: string;\n view?: string;\n embed?: boolean;\n };\n if (r.embed) return null;\n if (!r.url) return null;\n return {\n url: r.url,\n label: `Open ${r.app ?? \"app\"}`,\n view: r.view,\n };\n },\n mcpApp: {\n resource: embedApp({\n title: \"Open app\",\n description: \"Render the requested app route inline.\",\n iframeTitle: \"Agent Native app\",\n openLabel: \"Open app\",\n }),\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// create_embed_session\n// ---------------------------------------------------------------------------\n\nfunction createEmbedSessionTool(requestMeta?: {\n origin?: string;\n}): ActionEntry {\n return {\n tool: {\n ...tool(\n \"MCP Apps helper: create a one-time browser embed session for a same-origin app URL. Usually called by an MCP App iframe, not directly by the model.\",\n {\n url: {\n type: \"string\",\n description:\n \"Same-origin absolute URL or app-relative path to embed.\",\n },\n path: {\n type: \"string\",\n description: \"Same-origin app-relative path to embed.\",\n },\n chrome: {\n type: \"string\",\n enum: [\"full\", \"minimal\"],\n description: \"Embed chrome preference. Defaults to full.\",\n },\n },\n ),\n _meta: { ui: { visibility: [\"app\"] } },\n } as ActionTool,\n // App-only bootstrap helper: the ticket becomes a normal browser session,\n // so keep it write-scoped until embed sessions can enforce MCP scopes.\n readOnly: false,\n parallelSafe: true,\n run: async (args: Record<string, any>) => {\n const { getRequestContext } =\n await import(\"../server/request-context.js\");\n const ctx = getRequestContext();\n const ownerEmail = ctx?.userEmail?.trim();\n if (!ownerEmail) {\n throw new Error(\n \"create_embed_session requires an authenticated MCP caller.\",\n );\n }\n\n const { normalizeEmbedTargetPath, createEmbedSessionTicket } =\n await import(\"../server/embed-session.js\");\n const { buildEmbedStartPath } = await import(\"../server/embed-route.js\");\n const rawTarget =\n typeof args.url === \"string\" && args.url.trim()\n ? args.url\n : typeof args.path === \"string\"\n ? args.path\n : \"\";\n const targetPath = normalizeEmbedTargetPath(\n rawTarget,\n requestMeta?.origin,\n );\n if (!targetPath) {\n throw new Error(\n \"create_embed_session can only embed same-origin app-relative URLs.\",\n );\n }\n\n const ticket = await createEmbedSessionTicket({\n ownerEmail,\n orgId: ctx?.orgId,\n targetPath,\n scope: typeof args.chrome === \"string\" ? args.chrome : null,\n });\n const startPath = buildEmbedStartPath(ticket.ticket);\n const startUrl = requestMeta?.origin\n ? new URL(startPath, requestMeta.origin).toString()\n : startPath;\n return {\n startUrl,\n targetPath,\n expiresAt: ticket.expiresAt,\n };\n },\n };\n}\n\n/**\n * Route an `ask_app` message to a *different* app's agent over A2A. Shared by\n * the workspace-resolved path and the org-directory-resolved path so the A2A\n * call logic is not duplicated. `origin` is the target app's A2A base\n * (workspace dev origin or the directory's `a2aUrl`); `id` is reported back.\n *\n * Throws on failure so the caller can be honest — it never falls back to this\n * app's agent and pretends it was the target.\n */\nasync function routeAskOverA2A(\n origin: string,\n id: string,\n message: string,\n options?: { durable?: boolean; maxWaitMs?: number },\n): Promise<\n { app: string; routedVia: \"a2a\"; response: string } | AskAppTaskResult\n> {\n if (options?.durable) {\n return submitAskAppA2ATask(\n { app: id, origin: agentNativeA2AEndpoint(origin), routedVia: \"a2a\" },\n message,\n options.maxWaitMs ?? ASK_APP_DEFAULT_INLINE_WAIT_MS,\n );\n }\n const { callAgent } = await import(\"../a2a/client.js\");\n const { resolveA2ACallerAuth } = await import(\"../a2a/caller-auth.js\");\n // The MCP handler runs inside `runWithRequestContext`, so this is the\n // verified caller identity and org scope. Reuse the same auth resolver as\n // org-directory discovery so the directory lookup and actual A2A call are\n // scoped the same way.\n const auth = await resolveA2ACallerAuth();\n const response = await callAgent(origin, message, {\n apiKey: auth.apiKey,\n userEmail: auth.userEmail,\n orgDomain: auth.orgDomain,\n orgSecret: auth.orgSecret,\n // Bound the wait — cross-app A2A polls async by default.\n timeoutMs: 5 * 60_000,\n });\n return { app: id, routedVia: \"a2a\", response };\n}\n\nasync function resolveAskAppStatusRoute(\n config: MCPConfig,\n requestedApp: string,\n requestMeta?: AskAppRequestMeta,\n): Promise<AskAppRoute> {\n const selfId = currentAppId(config);\n const normalized = requestedApp.trim().toLowerCase();\n const selfEndpointUrl = selfA2AEndpointUrl(requestMeta);\n\n if (!normalized || normalized === selfId) {\n if (!selfEndpointUrl) {\n throw new Error(\n \"ask_app_status requires a running app origin for local tasks.\",\n );\n }\n return { app: selfId, origin: selfEndpointUrl, routedVia: \"local\" };\n }\n\n const targetApp = await resolveTargetAppOrigin(config, requestedApp);\n if (targetApp) {\n return {\n app: targetApp.id,\n origin: agentNativeA2AEndpoint(targetApp.origin),\n routedVia: \"a2a\",\n };\n }\n\n const orgApps = await fetchOrgApps({ selfId }).catch(() => [] as OrgApp[]);\n const dirMatch = orgApps.find((a) => a.id === normalized);\n if (dirMatch) {\n return {\n app: dirMatch.id,\n origin: agentNativeA2AEndpoint(dirMatch.a2aUrl),\n routedVia: \"a2a\",\n };\n }\n\n throw new Error(`No reachable ask_app task route for app \"${requestedApp}\".`);\n}\n\n// ---------------------------------------------------------------------------\n// ask_app\n// ---------------------------------------------------------------------------\n\nfunction askAppTool(\n config: MCPConfig,\n requestMeta?: AskAppRequestMeta,\n): ActionEntry {\n return {\n tool: tool(\n \"Send a natural-language message to an app's AI agent and get its \" +\n \"response. Use for complex, multi-step tasks needing the agent's \" +\n \"reasoning and full app context. In a single-app project the 'app' \" +\n \"param is optional (defaults to this app). When 'app' names a \" +\n \"different workspace app it is routed there over A2A; the result's \" +\n \"'routedVia' field reports whether it ran cross-app or locally. \" +\n \"On hosted MCP, long tasks may return a durable taskId instead of a \" +\n \"final response; call ask_app_status with that taskId until completed.\",\n {\n app: {\n type: \"string\",\n description: \"App id to route to (optional in a single-app project)\",\n },\n message: {\n type: \"string\",\n description: \"The message to send to the app's agent\",\n },\n async: {\n type: \"boolean\",\n description:\n \"When true, start a durable task and return immediately with a taskId.\",\n },\n maxWaitMs: {\n type: \"number\",\n description:\n \"Maximum time to wait inline before returning a taskId. Hosted MCP clamps this to 25000ms.\",\n },\n },\n [\"message\"],\n ),\n run: async (args: Record<string, any>) => {\n const message = String(args.message ?? \"\").trim();\n if (!message) throw new Error(\"ask_app requires a 'message'.\");\n const requestedApp = String(args.app ?? \"\").trim();\n const selfId = currentAppId(config);\n const useDurableA2A = Boolean(requestMeta?.origin);\n const maxWaitMs = isExplicitAsyncAsk(args.async)\n ? 0\n : boundedAskAppWaitMs(args.maxWaitMs);\n\n // Cross-app: the caller named a *different* workspace app. Route the\n // message to THAT app's agent over A2A (its `/_agent-native/a2a`\n // endpoint runs the real agent loop with JWT identity) rather than\n // silently answering from this app's agent and claiming delegation.\n const targetApp = await resolveTargetAppOrigin(config, requestedApp);\n if (targetApp) {\n try {\n return await routeAskOverA2A(\n targetApp.origin,\n targetApp.id,\n message,\n {\n durable: useDurableA2A,\n maxWaitMs,\n },\n );\n } catch (err: any) {\n // Be honest: routing was attempted and failed — do NOT fall back to\n // this app's agent and pretend it was the target.\n throw new Error(\n `Failed to route ask_app to \"${targetApp.id}\" via A2A: ` +\n `${err?.message ?? err}`,\n );\n }\n }\n\n // Not a known local/workspace app — try the org directory. When a\n // directory is configured and the requested app is one of the org's\n // deployed sibling apps, route to it over A2A (same path as above,\n // against its `a2aUrl`). Inactive directory / any failure ⇒ orgApps is\n // [] and this is skipped, preserving the exact local-only behavior.\n if (requestedApp && requestedApp.toLowerCase() !== selfId) {\n const orgApps = await fetchOrgApps({ selfId }).catch(\n () => [] as OrgApp[],\n );\n const dirMatch = orgApps.find(\n (a) => a.id === requestedApp.toLowerCase(),\n );\n if (dirMatch) {\n try {\n return await routeAskOverA2A(\n dirMatch.a2aUrl,\n dirMatch.id,\n message,\n {\n durable: useDurableA2A,\n maxWaitMs,\n },\n );\n } catch (err: any) {\n throw new Error(\n `Failed to route ask_app to \"${dirMatch.id}\" via A2A ` +\n `(org directory): ${err?.message ?? err}`,\n );\n }\n }\n }\n\n // Same app (or no workspace / unknown target): answer locally with this\n // app's own ask-agent handler — the same entry point the HTTP MCP mount\n // + A2A use, so there is no second agent runner.\n if (!config.askAgent) {\n throw new Error(\n \"This app does not expose an agent (no ask-agent handler).\",\n );\n }\n\n // If the caller named an app we couldn't route to (unknown id, or no\n // workspace), say so honestly instead of claiming we reached it.\n const unresolved =\n !!requestedApp && requestedApp.toLowerCase() !== selfId;\n const note = unresolved\n ? `Requested app \"${requestedApp}\" is not a reachable workspace ` +\n `app; answered with this app (\"${selfId}\") instead.`\n : undefined;\n\n // Hosted MCP cannot safely keep a JSON request/response open for a full\n // agent loop: serverless gateways can return an inactivity 504 before\n // the result body exists. When we know the running app origin, submit the\n // local ask through the app's durable A2A task path and only wait a\n // short bounded window for fast completions.\n const localA2AEndpointUrl = selfA2AEndpointUrl(requestMeta);\n if (localA2AEndpointUrl) {\n return submitAskAppA2ATask(\n {\n app: selfId,\n origin: localA2AEndpointUrl,\n routedVia: \"local\",\n ...(note ? { note } : {}),\n },\n message,\n maxWaitMs,\n );\n }\n\n const response = await config.askAgent(message);\n return {\n app: selfId,\n routedVia: \"local\",\n ...(note ? { note } : {}),\n response,\n };\n },\n };\n}\n\nfunction askAppStatusTool(\n config: MCPConfig,\n requestMeta?: AskAppRequestMeta,\n): ActionEntry {\n return {\n tool: tool(\n \"Poll a durable ask_app task and return its current status or final response.\",\n {\n app: {\n type: \"string\",\n description:\n \"App id returned by ask_app. Optional for same-app local tasks.\",\n },\n taskId: {\n type: \"string\",\n description: \"The durable task id returned by ask_app.\",\n },\n },\n [\"taskId\"],\n ),\n readOnly: true,\n parallelSafe: true,\n run: async (args: Record<string, any>) => {\n const taskId = String(args.taskId ?? \"\").trim();\n if (!taskId) throw new Error(\"ask_app_status requires 'taskId'.\");\n const requestedApp = String(args.app ?? \"\").trim();\n const route = await resolveAskAppStatusRoute(\n config,\n requestedApp,\n requestMeta,\n );\n return fetchAskAppA2ATask(route, taskId);\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// list_templates\n// ---------------------------------------------------------------------------\n\nfunction listTemplatesTool(): ActionEntry {\n return {\n tool: tool(\n \"List the first-party templates that can be scaffolded into a workspace \" +\n \"(allow-listed templates only).\",\n ),\n readOnly: true,\n parallelSafe: true,\n run: async () => {\n const { visibleTemplates } = await import(\"../cli/templates-meta.js\");\n return {\n templates: visibleTemplates().map((t) => ({\n name: t.name,\n label: t.label,\n hint: t.hint,\n })),\n };\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// create_workspace_app\n// ---------------------------------------------------------------------------\n\nfunction createWorkspaceAppTool(): ActionEntry {\n return {\n tool: tool(\n \"Scaffold a new app into the current workspace from an allow-listed \" +\n \"template, then return a deep link to open it. Idempotent: if an app \" +\n \"with that name already exists it is reused.\",\n {\n name: {\n type: \"string\",\n description: \"New app id (directory under apps/), e.g. 'mymail'\",\n },\n template: {\n type: \"string\",\n description:\n \"Template to scaffold from — must be allow-listed (see list_templates)\",\n },\n },\n [\"name\", \"template\"],\n ),\n run: async (args: Record<string, any>) => {\n const name = String(args.name ?? \"\").trim();\n const template = String(args.template ?? \"\").trim();\n if (!name || !template) {\n throw new Error(\n \"create_workspace_app requires both 'name' and 'template'.\",\n );\n }\n\n // Enforce the strict public template allow-list. The authoritative,\n // dependency-free source inside @agent-native/core is cli/templates-meta\n // (kept in sync with packages/shared-app-config/templates.ts; CI guard).\n const { visibleTemplates } = await import(\"../cli/templates-meta.js\");\n const allowed = new Set(visibleTemplates().map((t) => t.name));\n if (!allowed.has(template)) {\n throw new Error(\n `Template \"${template}\" is not allow-listed. Allowed: ${[...allowed]\n .sort()\n .join(\", \")}`,\n );\n }\n\n const { findWorkspaceRoot, resolveWorkspace } =\n await import(\"./workspace-resolve.js\");\n const fs = await import(\"node:fs\");\n const path = await import(\"node:path\");\n\n const root = findWorkspaceRoot(process.cwd());\n if (!root) {\n throw new Error(\n \"Not inside a workspace. create_workspace_app only works in a \" +\n \"multi-app workspace (run from the workspace root).\",\n );\n }\n\n const appDir = path.join(root, \"apps\", name);\n const alreadyExisted = fs.existsSync(appDir);\n\n if (!alreadyExisted) {\n // Reuse the CLI scaffolder directly (no second `agent-native`\n // subprocess). `addAppToWorkspace(name, { template })` takes the\n // non-interactive single-template path when name + one template are\n // given. Run it from the workspace root so detectWorkspace resolves.\n const prevCwd = process.cwd();\n try {\n process.chdir(root);\n const { addAppToWorkspace } = await import(\"../cli/create.js\");\n await addAppToWorkspace(name, { template, noInstall: true });\n } finally {\n try {\n process.chdir(prevCwd);\n } catch {\n // best-effort cwd restore\n }\n }\n }\n\n // The workspace gateway auto-detects new apps/* dirs (fs.watch +\n // 2s sync) and lazily boots the dev server on first request, so we\n // don't spawn vite ourselves — opening the deep link warms it. Resolve\n // the port the gateway will use so we can report it.\n const ws = await resolveWorkspace(root);\n const appInfo = ws.apps.find((a) => a.id === name);\n const port = appInfo?.port;\n // The scaffolded app is always a *different* app from the host MCP\n // server, so anchor the deep link to the new app's own origin. A\n // relative path would otherwise be prefixed with the current request\n // origin and land on the wrong app. Fall back to the relative path\n // only if the gateway hasn't reported the new app's URL yet.\n const relDeepLink = buildDeepLink({ app: name, view: \"home\" });\n const deepLink = appInfo?.url\n ? `${appInfo.url.replace(/\\/+$/, \"\")}${relDeepLink}`\n : relDeepLink;\n\n return {\n name,\n template,\n created: !alreadyExisted,\n reused: alreadyExisted,\n port,\n url: appInfo?.url,\n gatewayUrl: ws.gatewayUrl,\n deepLink,\n };\n },\n link: ({ result }) => {\n if (!result || typeof result !== \"object\") return null;\n const r = result as { deepLink?: string; name?: string };\n if (!r.deepLink) return null;\n return {\n url: r.deepLink,\n label: `Open ${r.name ?? \"app\"}`,\n view: \"home\",\n };\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Registry\n// ---------------------------------------------------------------------------\n\n/**\n * Build the generic cross-app builtin tool registry. Called by\n * `createMCPServerForRequest`; the result is merged UNDER the config's\n * actions so template actions of the same name win.\n */\nexport function getBuiltinCrossAppTools(\n config: MCPConfig,\n requestMeta?: AskAppRequestMeta,\n): Record<string, ActionEntry> {\n return {\n list_apps: listAppsTool(config, requestMeta),\n open_app: openAppTool(config, requestMeta),\n create_embed_session: createEmbedSessionTool(requestMeta),\n ask_app: askAppTool(config, requestMeta),\n ask_app_status: askAppStatusTool(config, requestMeta),\n create_workspace_app: createWorkspaceAppTool(),\n list_templates: listTemplatesTool(),\n };\n}\n"]}
1
+ {"version":3,"file":"builtin-tools.js","sourceRoot":"","sources":["../../src/mcp/builtin-tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAKH,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,+BAA+B,EAAE,MAAM,yBAAyB,CAAC;AAE1E,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAe,MAAM,oBAAoB,CAAC;AAQ/D;;;;GAIG;AACH,SAAS,IAAI,CACX,WAAmB,EACnB,UAAmB,EACnB,QAAmB;IAEnB,IAAI,CAAC,UAAU;QAAE,OAAO,EAAE,WAAW,EAAE,CAAC;IACxC,OAAO;QACL,WAAW;QACX,UAAU,EAAE;YACV,IAAI,EAAE,QAAQ;YACd,UAAU,EAAE,UAAU;YACtB,GAAG,CAAC,QAAQ,IAAI,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACrD;KACF,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,YAAY,CAAC,MAAiB;IACrC,OAAO,CAAC,MAAM,CAAC,KAAK,IAAI,MAAM,CAAC,IAAI,IAAI,KAAK,CAAC,CAAC,WAAW,EAAE,CAAC;AAC9D,CAAC;AAED,MAAM,aAAa,GAAG,IAAI,MAAM,CAAC,0BAA0B,CAAC,CAAC;AAC7D,MAAM,8BAA8B,GAAG,MAAM,CAAC;AAC9C,MAAM,0BAA0B,GAAG,M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AA8E;AAC9E,WAAW;AACX,8EAA8E;AAE9E;;;;GAIG;AACH,MAAM,UAAU,uBAAuB,CACrC,MAAiB,EACjB,WAA+B;IAE/B,OAAO;QACL,SAAS,EAAE,YAAY,CAAC,MAAM,EAAE,WAAW,CAAC;QAC5C,QAAQ,EAAE,WAAW,CAAC,MAAM,EAAE,WAAW,CAAC;QAC1C,oBAAoB,EAAE,sBAAsB,CAAC,WAAW,CAAC;QACzD,OAAO,EAAE,UAAU,CAAC,MAAM,EAAE,WAAW,CAAC;QACxC,cAAc,EAAE,gBAAgB,CAAC,MAAM,EAAE,WAAW,CAAC;QACrD,oBAAoB,EAAE,sBAAsB,EAAE;QAC9C,cAAc,EAAE,iBAAiB,EAAE;KACpC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Generic cross-app MCP tools — a stable verb set every external agent gets\n * regardless of which template it is talking to.\n *\n * These are merged into the MCP action registry by\n * `createMCPServerForRequest` (see `build-server.ts`). **Precedence: template\n * actions win.** If a template defines an action named `list_apps` /\n * `open_app` / `ask_app` / `create_workspace_app` / `list_templates`, the\n * template's `ActionEntry` overwrites the builtin of the same name. This is\n * the same template-over-framework precedence `autoDiscoverActions` uses.\n *\n * | Tool | Side effects | Returns |\n * | --------------------- | ------------ | ---------------------------------------- |\n * | `list_apps` | none | `{ apps: [{ id, url, running }] }` |\n * | `open_app` | none | `{ url }` (+ deep-link `link`) |\n * | `create_embed_session`| ticket mint | `{ startUrl }` for MCP App iframes |\n * | `ask_app` | agent loop | `{ app, routedVia, response }` or task |\n * | `ask_app_status` | none | poll a durable `ask_app` task |\n * | `create_workspace_app`| scaffolds | `{ name, url, port, deepLink }` (+ link) |\n *\n * `open_app` / `create_workspace_app` return an **absolute** URL on the\n * *target* app's origin when it differs from this app (so a workspace link\n * lands in the right app), and a relative path for the same app / standalone.\n * `ask_app` routes to a *different* workspace app over A2A when possible and\n * reports `routedVia: \"a2a\"`; otherwise it answers locally\n * (`routedVia: \"local\"`) and never falsely claims cross-app delegation.\n * | `list_templates` | none | `{ templates: [...] }` (allow-list only) |\n *\n * Node-only at call time (workspace resolution + scaffolding use `fs`), but\n * the module has no top-level Node imports so it bundles fine alongside\n * `mountMCP` — the Node bits are dynamically imported inside `run()`.\n */\n\nimport type { Task } from \"../a2a/types.js\";\nimport type { ActionEntry } from \"../agent/production-agent.js\";\nimport type { ActionTool } from \"../agent/types.js\";\nimport { getConfiguredAppBasePath } from \"../server/app-base-path.js\";\nimport { buildDeepLink } from \"../server/deep-link.js\";\nimport { MCP_APP_CHAT_BRIDGE_QUERY_PARAM } from \"../shared/embed-auth.js\";\nimport type { MCPConfig } from \"./build-server.js\";\nimport { embedApp } from \"./embed-app.js\";\nimport { fetchOrgApps, type OrgApp } from \"./org-directory.js\";\n\n/** Flat map of param name → JSON-schema property. */\ntype Params = Record<\n string,\n { type: string; description?: string; enum?: string[] }\n>;\n\n/**\n * Build an `ActionTool`. `parameters` is wrapped in the\n * `{ type:\"object\", properties, required }` shape `createMCPServerForRequest`\n * forwards verbatim as the MCP tool `inputSchema`.\n */\nfunction tool(\n description: string,\n parameters?: Params,\n required?: string[],\n): ActionTool {\n if (!parameters) return { description };\n return {\n description,\n parameters: {\n type: \"object\",\n properties: parameters,\n ...(required && required.length ? { required } : {}),\n },\n };\n}\n\n/**\n * The canonical app id this MCP server is mounted for. `MCPConfig.appId` is\n * authoritative; fall back to lowercasing `name` (which is the capitalized\n * app id at every call site) for back-compat with configs that predate the\n * `appId` field.\n */\nfunction currentAppId(config: MCPConfig): string {\n return (config.appId || config.name || \"app\").toLowerCase();\n}\n\nconst CONTROL_CHARS = new RegExp(\"[\\\\u0000-\\\\u001f\\\\u007f]\");\nconst ASK_APP_DEFAULT_INLINE_WAIT_MS = 20_000;\nconst ASK_APP_MAX_INLINE_WAIT_MS = 25_000;\nconst ASK_APP_POLL_INTERVAL_MS = 1_500;\nconst ASK_APP_A2A_REQUEST_TIMEOUT_MS = 10_000;\nconst ASK_APP_TERMINAL_STATES = new Set<string>([\n \"completed\",\n \"failed\",\n \"canceled\",\n]);\n\ntype AskAppRequestMeta = { origin?: string; basePath?: string };\n\ninterface AskAppRoute {\n app: string;\n origin: string;\n routedVia: \"local\" | \"a2a\";\n note?: string;\n}\n\ninterface AskAppTaskResult {\n app: string;\n routedVia: \"local\" | \"a2a\";\n taskId: string;\n status: string;\n response?: string;\n error?: string;\n note?: string;\n poll?: {\n tool: \"ask_app_status\";\n arguments: { app: string; taskId: string };\n };\n message?: string;\n}\n\nfunction safeAppPath(raw: unknown): string | null {\n if (typeof raw !== \"string\" || !raw.trim()) return null;\n const value = raw.trim();\n if (CONTROL_CHARS.test(value)) return null;\n if (!value.startsWith(\"/\")) return null;\n if (value.startsWith(\"//\") || value.startsWith(\"/\\\\\")) return null;\n if (/^\\/[a-z][a-z0-9+.-]*:/i.test(value)) return null;\n return value;\n}\n\nfunction appendParamsToPath(\n path: string,\n params: Record<string, string | number | boolean> | undefined,\n): string {\n if (!params || Object.keys(params).length === 0) return path;\n const url = new URL(path, \"http://agent-native.invalid\");\n for (const [key, value] of Object.entries(params)) {\n url.searchParams.set(key, String(value));\n }\n return `${url.pathname}${url.search}${url.hash}`;\n}\n\nfunction viewToAppPath(view: string): string | null {\n const value = view.trim();\n if (!value) return null;\n return safeAppPath(value.startsWith(\"/\") ? value : `/${value}`);\n}\n\nfunction withConfiguredBasePath(path: string): string {\n const base = getConfiguredAppBasePath();\n if (!base || path === base || path.startsWith(`${base}/`)) return path;\n return `${base}${path}`;\n}\n\nfunction withMcpChatBridgeParam(path: string): string {\n try {\n const url = new URL(path, \"http://agent-native.invalid\");\n url.searchParams.set(MCP_APP_CHAT_BRIDGE_QUERY_PARAM, \"1\");\n return `${url.pathname}${url.search}${url.hash}`;\n } catch {\n return path;\n }\n}\n\nfunction agentNativeA2AEndpoint(urlOrOrigin: string): string {\n const value = urlOrOrigin.replace(/\\/+$/, \"\");\n try {\n const parsed = new URL(value);\n const pathname = parsed.pathname.replace(/\\/+$/, \"\");\n if (pathname.endsWith(\"/_agent-native/a2a\") || pathname.endsWith(\"/a2a\")) {\n return value;\n }\n } catch {\n // Fall through and append the conventional Agent Native endpoint.\n }\n return `${value}/_agent-native/a2a`;\n}\n\nfunction selfA2AEndpointUrl(requestMeta?: AskAppRequestMeta): string | null {\n const origin = requestMeta?.origin?.replace(/\\/+$/, \"\");\n if (!origin) return null;\n const basePath = requestMeta?.basePath || getConfiguredAppBasePath();\n return agentNativeA2AEndpoint(`${origin}${basePath}`);\n}\n\nfunction boundedAskAppWaitMs(raw: unknown): number {\n if (raw == null || raw === \"\") return ASK_APP_DEFAULT_INLINE_WAIT_MS;\n const parsed = Number(raw);\n if (!Number.isFinite(parsed)) return ASK_APP_DEFAULT_INLINE_WAIT_MS;\n return Math.max(0, Math.min(ASK_APP_MAX_INLINE_WAIT_MS, Math.trunc(parsed)));\n}\n\nfunction isExplicitAsyncAsk(raw: unknown): boolean {\n return raw === true || raw === \"true\" || raw === 1 || raw === \"1\";\n}\n\nfunction taskState(task: Task): string {\n return String(task.status?.state ?? \"unknown\");\n}\n\nfunction isTerminalTask(task: Task): boolean {\n return ASK_APP_TERMINAL_STATES.has(taskState(task));\n}\n\nfunction taskText(task: Task): string {\n return (\n task.status.message?.parts\n ?.filter(\n (part): part is { type: \"text\"; text: string } => part.type === \"text\",\n )\n .map((part) => part.text)\n .join(\"\\n\")\n .trim() ?? \"\"\n );\n}\n\nfunction askAppTaskResult(route: AskAppRoute, task: Task): AskAppTaskResult {\n const status = taskState(task);\n const response = taskText(task);\n const base = {\n app: route.app,\n routedVia: route.routedVia,\n taskId: task.id,\n status,\n ...(route.note ? { note: route.note } : {}),\n };\n\n if (status === \"completed\") {\n return {\n ...base,\n response: response || \"(no response)\",\n };\n }\n\n if (status === \"failed\" || status === \"canceled\") {\n return {\n ...base,\n ...(response ? { response } : {}),\n error: response || `ask_app task ${status}.`,\n };\n }\n\n return {\n ...base,\n poll: {\n tool: \"ask_app_status\",\n arguments: { app: route.app, taskId: task.id },\n },\n message:\n `ask_app is still ${status}. Call ask_app_status with ` +\n `taskId \"${task.id}\" to retrieve the final response.`,\n };\n}\n\nasync function createA2AClientForAskApp(origin: string): Promise<{\n client: import(\"../a2a/client.js\").A2AClient;\n metadata: Record<string, unknown>;\n}> {\n const { A2AClient } = await import(\"../a2a/client.js\");\n const { resolveA2ACallerAuth } = await import(\"../a2a/caller-auth.js\");\n const auth = await resolveA2ACallerAuth();\n const metadata: Record<string, unknown> = {};\n if (auth.userEmail) metadata.userEmail = auth.userEmail;\n if (auth.orgDomain) metadata.orgDomain = auth.orgDomain;\n return {\n client: new A2AClient(origin, auth.apiKey, {\n requestTimeoutMs: ASK_APP_A2A_REQUEST_TIMEOUT_MS,\n ...(auth.apiKeyFallbacks\n ? { fallbackApiKeys: auth.apiKeyFallbacks }\n : {}),\n }),\n metadata,\n };\n}\n\nasync function waitForA2ATask(\n client: import(\"../a2a/client.js\").A2AClient,\n initialTask: Task,\n maxWaitMs: number,\n): Promise<Task> {\n if (maxWaitMs <= 0 || isTerminalTask(initialTask)) return initialTask;\n const deadline = Date.now() + maxWaitMs;\n let current = initialTask;\n\n while (!isTerminalTask(current)) {\n const remaining = deadline - Date.now();\n if (remaining <= 0) return current;\n await new Promise((resolve) =>\n setTimeout(resolve, Math.min(ASK_APP_POLL_INTERVAL_MS, remaining)),\n );\n try {\n current = await client.getTask(initialTask.id);\n } catch {\n // Transient status fetch failures should not turn a successfully\n // submitted durable task into a failed MCP call.\n if (Date.now() >= deadline) return current;\n continue;\n }\n }\n\n return current;\n}\n\nasync function submitAskAppA2ATask(\n route: AskAppRoute,\n message: string,\n maxWaitMs: number,\n): Promise<AskAppTaskResult> {\n const { client, metadata } = await createA2AClientForAskApp(route.origin);\n const task = await client.send(\n {\n role: \"user\",\n parts: [{ type: \"text\", text: message }],\n },\n {\n async: true,\n metadata,\n },\n );\n const finalOrRunning = await waitForA2ATask(client, task, maxWaitMs);\n return askAppTaskResult(route, finalOrRunning);\n}\n\nasync function fetchAskAppA2ATask(\n route: AskAppRoute,\n taskId: string,\n): Promise<AskAppTaskResult> {\n const { client } = await createA2AClientForAskApp(route.origin);\n const task = await client.getTask(taskId);\n return askAppTaskResult(route, task);\n}\n\n/**\n * Resolve the absolute origin of a *target* workspace app (e.g.\n * `http://127.0.0.1:8101`) so cross-app deep links / A2A calls point at the\n * right app instead of the current request's origin. Reuses the same\n * workspace resolution `list_apps` / the stdio proxy use.\n *\n * Returns `null` when:\n * - the target is the current app (caller should keep relative behavior),\n * - there is no workspace info (standalone / single app), or\n * - the target app is unknown.\n */\nasync function resolveTargetAppOrigin(\n config: MCPConfig,\n targetAppId: string,\n): Promise<{ origin: string; id: string } | null> {\n const target = targetAppId.trim().toLowerCase();\n if (!target || target === currentAppId(config)) return null;\n try {\n const { resolveWorkspace } = await import(\"./workspace-resolve.js\");\n const ws = await resolveWorkspace();\n if (!ws.isWorkspace) return null;\n const match = ws.apps.find((a) => a.id.toLowerCase() === target);\n if (!match) return null;\n return { origin: match.url, id: match.id };\n } catch {\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// list_apps\n// ---------------------------------------------------------------------------\n\nfunction listAppsTool(\n config: MCPConfig,\n requestMeta?: { origin?: string },\n): ActionEntry {\n return {\n tool: tool(\n \"List the workspace apps and their URLs. Use this to discover which \" +\n \"apps exist before opening or asking one. In a single-app project \" +\n \"this returns just that app. When an org directory is configured \" +\n \"this also includes the org's deployed sibling apps.\",\n ),\n readOnly: true,\n parallelSafe: true,\n run: async () => {\n const { resolveWorkspace } = await import(\"./workspace-resolve.js\");\n const ws = await resolveWorkspace();\n\n // The MCP request is served BY the current app, so it is provably\n // reachable at the inbound request origin — that beats a guessed\n // `PORT || 5173` probe (which reports the wrong URL + `running:false`\n // whenever the dev server picked a non-default port, e.g. `agent-\n // native dev` on :8080). For the entry that IS this app (the sole\n // entry when single-app, or the id matching `config.appId` in a\n // workspace) prefer the live origin; other workspace apps keep their\n // probed values.\n const liveOrigin = requestMeta?.origin?.replace(/\\/+$/, \"\") || \"\";\n let livePort = 0;\n if (liveOrigin) {\n try {\n const u = new URL(liveOrigin);\n livePort = Number(u.port) || (u.protocol === \"https:\" ? 443 : 80);\n } catch {\n livePort = 0;\n }\n }\n const selfId = (config.appId ?? \"\").toLowerCase();\n const isSelf = (id: string) =>\n !!liveOrigin &&\n (!ws.isWorkspace || (!!selfId && id.toLowerCase() === selfId));\n\n interface AppEntry {\n id: string;\n url: string;\n port: number | undefined;\n running: boolean;\n source: \"workspace\" | \"org-directory\";\n }\n\n const apps: AppEntry[] = ws.apps.map((a) =>\n isSelf(a.id)\n ? {\n id: a.id,\n url: liveOrigin,\n port: (livePort || a.port) as number | undefined,\n running: true,\n source: \"workspace\" as const,\n }\n : {\n id: a.id,\n url: a.url,\n port: a.port as number | undefined,\n running: a.running,\n source: \"workspace\" as const,\n },\n );\n const seenIds = new Set(apps.map((a) => a.id.toLowerCase()));\n const seenOrigins = new Set(apps.map((a) => a.url.replace(/\\/+$/, \"\")));\n\n // Merge the org directory's deployed sibling apps. Inactive (no env)\n // or any failure ⇒ fetchOrgApps() returns [] and this is a no-op, so\n // the existing local/workspace behavior is preserved exactly.\n const orgApps = await fetchOrgApps({\n selfId: currentAppId(config),\n }).catch(() => [] as OrgApp[]);\n for (const oa of orgApps) {\n const idKey = oa.id.toLowerCase();\n const originKey = oa.url.replace(/\\/+$/, \"\");\n // Dedupe by id OR origin — a workspace app already listed wins.\n if (seenIds.has(idKey) || seenOrigins.has(originKey)) continue;\n seenIds.add(idKey);\n seenOrigins.add(originKey);\n apps.push({\n id: oa.id,\n url: oa.url,\n port: undefined,\n running: true,\n source: \"org-directory\",\n });\n }\n\n return {\n workspace: ws.isWorkspace,\n gatewayUrl: ws.gatewayUrl,\n apps,\n };\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// open_app\n// ---------------------------------------------------------------------------\n\nfunction openAppTool(\n config: MCPConfig,\n requestMeta?: { origin?: string },\n): ActionEntry {\n return {\n tool: tool(\n \"Build a deep link that opens an app at a specific view/record or \" +\n \"focused route/component. No side \" +\n \"effects — returns a URL the user can click to land in the running UI. \" +\n \"Set embed:true when a UI-capable MCP host should render the live app \" +\n \"or focused route/component inline. Omit view and path to land on the \" +\n \"app's home page.\",\n {\n app: { type: \"string\", description: \"App id, e.g. 'mail'\" },\n view: {\n type: \"string\",\n description:\n \"Target view, e.g. 'inbox' (maps to navigate command). Optional — omit (along with path) to open the app's home page.\",\n },\n path: {\n type: \"string\",\n description:\n \"Optional app route to open directly, e.g. '/extensions/abc', '/adhoc/q2', or '/chart?panel=...'. Must be same-origin relative. Omit (along with view) to open the app's home page.\",\n },\n params: {\n type: \"object\",\n description:\n \"Optional record-focus / filter params, e.g. { threadId: 'abc' }\",\n },\n embed: {\n type: \"boolean\",\n description:\n \"Render the full app or focused route/component inline in MCP Apps when the host supports it.\",\n },\n chrome: {\n type: \"string\",\n enum: [\"full\", \"minimal\"],\n description:\n \"Embed chrome preference for compatible app routes. Defaults to full.\",\n },\n },\n [\"app\"],\n ),\n readOnly: true,\n parallelSafe: true,\n run: async (args: Record<string, any>) => {\n const app = String(args.app ?? \"\").trim();\n const view = String(args.view ?? \"\").trim();\n // `safeAppPath` rejects anything that isn't a leading-slash same-origin\n // path. When the caller passes nothing, fall back to the app's root so a\n // bare `open_app({app:\"dispatch\"})` lands on the home page instead of\n // throwing. The model self-corrects on the retry today, but the extra\n // round-trip wastes a turn and looks broken to the user.\n const path = safeAppPath(args.path) || (view ? null : \"/\");\n if (!app) {\n throw new Error(\"open_app requires 'app'.\");\n }\n let params: Record<string, string | number | boolean> | undefined;\n const raw = args.params;\n if (raw && typeof raw === \"object\") {\n params = raw as Record<string, string | number | boolean>;\n } else if (typeof raw === \"string\" && raw.trim()) {\n try {\n params = JSON.parse(raw);\n } catch {\n params = undefined;\n }\n }\n const embeddedParam = params?.embed;\n const chromeParam = params?.chrome;\n let embed = args.embed === true || args.embed === \"true\";\n if (\n args.embed == null &&\n (embeddedParam === true || embeddedParam === \"true\")\n ) {\n embed = true;\n } else if (\n args.embed == null &&\n (embeddedParam === false || embeddedParam === \"false\")\n ) {\n embed = false;\n }\n if (\n embeddedParam === true ||\n embeddedParam === false ||\n embeddedParam === \"true\" ||\n embeddedParam === \"false\"\n ) {\n delete params?.embed;\n }\n\n const chrome =\n typeof args.chrome === \"string\"\n ? args.chrome\n : chromeParam === \"full\" || chromeParam === \"minimal\"\n ? chromeParam\n : undefined;\n if (chromeParam === \"full\" || chromeParam === \"minimal\") {\n delete params?.chrome;\n }\n if (params && Object.keys(params).length === 0) params = undefined;\n\n const directViewPath = embed && view ? viewToAppPath(view) : null;\n const relUrl = path\n ? appendParamsToPath(path, params)\n : directViewPath\n ? appendParamsToPath(directViewPath, params)\n : buildDeepLink({ app, view, params });\n const sameAppUrl =\n path || directViewPath ? withConfiguredBasePath(relUrl) : relUrl;\n\n // Cross-app target in a workspace: resolve the TARGET app's origin and\n // return an absolute URL. Otherwise the MCP layer would prefix the\n // relative path with the CURRENT request origin, landing the user in\n // the wrong app (e.g. open_app({app:\"calendar\"}) served from Mail).\n // Same-app / standalone keeps the relative path (current behavior).\n const targetApp = await resolveTargetAppOrigin(config, app);\n const appUrl = targetApp\n ? `${targetApp.origin.replace(/\\/+$/, \"\")}${relUrl}`\n : sameAppUrl;\n const url = appUrl;\n let embedStartUrl: string | undefined;\n let embedTargetPath: string | undefined;\n let embedExpiresAt: number | undefined;\n\n if (embed && !targetApp) {\n const { getRequestContext } =\n await import(\"../server/request-context.js\");\n const ctx = getRequestContext();\n const ownerEmail = ctx?.userEmail?.trim();\n if (ownerEmail) {\n const { normalizeEmbedTargetPath, createEmbedSessionTicket } =\n await import(\"../server/embed-session.js\");\n const { buildEmbedStartPath } =\n await import(\"../server/embed-route.js\");\n const targetPath = normalizeEmbedTargetPath(\n withMcpChatBridgeParam(url),\n requestMeta?.origin,\n );\n if (targetPath) {\n const ticket = await createEmbedSessionTicket({\n ownerEmail,\n orgId: ctx?.orgId,\n targetPath,\n scope: chrome ?? null,\n });\n const startPath = buildEmbedStartPath(ticket.ticket);\n embedStartUrl = requestMeta?.origin\n ? new URL(startPath, requestMeta.origin).toString()\n : startPath;\n embedTargetPath = targetPath;\n embedExpiresAt = ticket.expiresAt;\n }\n }\n }\n\n return {\n app,\n ...(view ? { view } : {}),\n ...(path ? { path } : {}),\n url,\n ...(embedStartUrl ? { embedStartUrl } : {}),\n ...(embedTargetPath ? { embedTargetPath } : {}),\n ...(embedExpiresAt ? { embedExpiresAt } : {}),\n embed,\n };\n },\n link: ({ result }) => {\n if (!result || typeof result !== \"object\") return null;\n const r = result as {\n url?: string;\n app?: string;\n view?: string;\n embed?: boolean;\n };\n if (r.embed) return null;\n if (!r.url) return null;\n return {\n url: r.url,\n label: `Open ${r.app ?? \"app\"}`,\n view: r.view,\n };\n },\n mcpApp: {\n resource: embedApp({\n title: \"Open app\",\n description: \"Render the requested app route inline.\",\n iframeTitle: \"Agent Native app\",\n openLabel: \"Open app\",\n }),\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// create_embed_session\n// ---------------------------------------------------------------------------\n\nfunction createEmbedSessionTool(requestMeta?: {\n origin?: string;\n}): ActionEntry {\n return {\n tool: {\n ...tool(\n \"MCP Apps helper: create a one-time browser embed session for a same-origin app URL. Usually called by an MCP App iframe, not directly by the model.\",\n {\n url: {\n type: \"string\",\n description:\n \"Same-origin absolute URL or app-relative path to embed.\",\n },\n path: {\n type: \"string\",\n description: \"Same-origin app-relative path to embed.\",\n },\n chrome: {\n type: \"string\",\n enum: [\"full\", \"minimal\"],\n description: \"Embed chrome preference. Defaults to full.\",\n },\n },\n ),\n _meta: { ui: { visibility: [\"app\"] } },\n } as ActionTool,\n // App-only bootstrap helper: the ticket becomes a normal browser session,\n // so keep it write-scoped until embed sessions can enforce MCP scopes.\n readOnly: false,\n parallelSafe: true,\n run: async (args: Record<string, any>) => {\n const { getRequestContext } =\n await import(\"../server/request-context.js\");\n const ctx = getRequestContext();\n const ownerEmail = ctx?.userEmail?.trim();\n if (!ownerEmail) {\n throw new Error(\n \"create_embed_session requires an authenticated MCP caller.\",\n );\n }\n\n const { normalizeEmbedTargetPath, createEmbedSessionTicket } =\n await import(\"../server/embed-session.js\");\n const { buildEmbedStartPath } = await import(\"../server/embed-route.js\");\n const rawTarget =\n typeof args.url === \"string\" && args.url.trim()\n ? args.url\n : typeof args.path === \"string\"\n ? args.path\n : \"\";\n const targetPath = normalizeEmbedTargetPath(\n rawTarget,\n requestMeta?.origin,\n );\n if (!targetPath) {\n throw new Error(\n \"create_embed_session can only embed same-origin app-relative URLs.\",\n );\n }\n\n const ticket = await createEmbedSessionTicket({\n ownerEmail,\n orgId: ctx?.orgId,\n targetPath,\n scope: typeof args.chrome === \"string\" ? args.chrome : null,\n });\n const startPath = buildEmbedStartPath(ticket.ticket);\n const startUrl = requestMeta?.origin\n ? new URL(startPath, requestMeta.origin).toString()\n : startPath;\n return {\n startUrl,\n targetPath,\n expiresAt: ticket.expiresAt,\n };\n },\n };\n}\n\n/**\n * Route an `ask_app` message to a *different* app's agent over A2A. Shared by\n * the workspace-resolved path and the org-directory-resolved path so the A2A\n * call logic is not duplicated. `origin` is the target app's A2A base\n * (workspace dev origin or the directory's `a2aUrl`); `id` is reported back.\n *\n * Throws on failure so the caller can be honest — it never falls back to this\n * app's agent and pretends it was the target.\n */\nasync function routeAskOverA2A(\n origin: string,\n id: string,\n message: string,\n options?: { durable?: boolean; maxWaitMs?: number },\n): Promise<\n { app: string; routedVia: \"a2a\"; response: string } | AskAppTaskResult\n> {\n if (options?.durable) {\n return submitAskAppA2ATask(\n { app: id, origin: agentNativeA2AEndpoint(origin), routedVia: \"a2a\" },\n message,\n options.maxWaitMs ?? ASK_APP_DEFAULT_INLINE_WAIT_MS,\n );\n }\n const { callAgent } = await import(\"../a2a/client.js\");\n const { resolveA2ACallerAuth } = await import(\"../a2a/caller-auth.js\");\n // The MCP handler runs inside `runWithRequestContext`, so this is the\n // verified caller identity and org scope. Reuse the same auth resolver as\n // org-directory discovery so the directory lookup and actual A2A call are\n // scoped the same way.\n const auth = await resolveA2ACallerAuth();\n const response = await callAgent(origin, message, {\n apiKey: auth.apiKey,\n userEmail: auth.userEmail,\n orgDomain: auth.orgDomain,\n orgSecret: auth.orgSecret,\n // Bound the wait — cross-app A2A polls async by default.\n timeoutMs: 5 * 60_000,\n });\n return { app: id, routedVia: \"a2a\", response };\n}\n\nasync function resolveAskAppStatusRoute(\n config: MCPConfig,\n requestedApp: string,\n requestMeta?: AskAppRequestMeta,\n): Promise<AskAppRoute> {\n const selfId = currentAppId(config);\n const normalized = requestedApp.trim().toLowerCase();\n const selfEndpointUrl = selfA2AEndpointUrl(requestMeta);\n\n if (!normalized || normalized === selfId) {\n if (!selfEndpointUrl) {\n throw new Error(\n \"ask_app_status requires a running app origin for local tasks.\",\n );\n }\n return { app: selfId, origin: selfEndpointUrl, routedVia: \"local\" };\n }\n\n const targetApp = await resolveTargetAppOrigin(config, requestedApp);\n if (targetApp) {\n return {\n app: targetApp.id,\n origin: agentNativeA2AEndpoint(targetApp.origin),\n routedVia: \"a2a\",\n };\n }\n\n const orgApps = await fetchOrgApps({ selfId }).catch(() => [] as OrgApp[]);\n const dirMatch = orgApps.find((a) => a.id === normalized);\n if (dirMatch) {\n return {\n app: dirMatch.id,\n origin: agentNativeA2AEndpoint(dirMatch.a2aUrl),\n routedVia: \"a2a\",\n };\n }\n\n throw new Error(`No reachable ask_app task route for app \"${requestedApp}\".`);\n}\n\n// ---------------------------------------------------------------------------\n// ask_app\n// ---------------------------------------------------------------------------\n\nfunction askAppTool(\n config: MCPConfig,\n requestMeta?: AskAppRequestMeta,\n): ActionEntry {\n return {\n tool: tool(\n \"Send a natural-language message to an app's AI agent and get its \" +\n \"response. Use for complex, multi-step tasks needing the agent's \" +\n \"reasoning and full app context. In a single-app project the 'app' \" +\n \"param is optional (defaults to this app). When 'app' names a \" +\n \"different workspace app it is routed there over A2A; the result's \" +\n \"'routedVia' field reports whether it ran cross-app or locally. \" +\n \"On hosted MCP, long tasks may return a durable taskId instead of a \" +\n \"final response; call ask_app_status with that taskId until completed.\",\n {\n app: {\n type: \"string\",\n description: \"App id to route to (optional in a single-app project)\",\n },\n message: {\n type: \"string\",\n description: \"The message to send to the app's agent\",\n },\n async: {\n type: \"boolean\",\n description:\n \"When true, start a durable task and return immediately with a taskId.\",\n },\n maxWaitMs: {\n type: \"number\",\n description:\n \"Maximum time to wait inline before returning a taskId. Hosted MCP clamps this to 25000ms.\",\n },\n },\n [\"message\"],\n ),\n run: async (args: Record<string, any>) => {\n const message = String(args.message ?? \"\").trim();\n if (!message) throw new Error(\"ask_app requires a 'message'.\");\n const requestedApp = String(args.app ?? \"\").trim();\n const selfId = currentAppId(config);\n const useDurableA2A = Boolean(requestMeta?.origin);\n const maxWaitMs = isExplicitAsyncAsk(args.async)\n ? 0\n : boundedAskAppWaitMs(args.maxWaitMs);\n\n // Cross-app: the caller named a *different* workspace app. Route the\n // message to THAT app's agent over A2A (its `/_agent-native/a2a`\n // endpoint runs the real agent loop with JWT identity) rather than\n // silently answering from this app's agent and claiming delegation.\n const targetApp = await resolveTargetAppOrigin(config, requestedApp);\n if (targetApp) {\n try {\n return await routeAskOverA2A(\n targetApp.origin,\n targetApp.id,\n message,\n {\n durable: useDurableA2A,\n maxWaitMs,\n },\n );\n } catch (err: any) {\n // Be honest: routing was attempted and failed — do NOT fall back to\n // this app's agent and pretend it was the target.\n throw new Error(\n `Failed to route ask_app to \"${targetApp.id}\" via A2A: ` +\n `${err?.message ?? err}`,\n );\n }\n }\n\n // Not a known local/workspace app — try the org directory. When a\n // directory is configured and the requested app is one of the org's\n // deployed sibling apps, route to it over A2A (same path as above,\n // against its `a2aUrl`). Inactive directory / any failure ⇒ orgApps is\n // [] and this is skipped, preserving the exact local-only behavior.\n if (requestedApp && requestedApp.toLowerCase() !== selfId) {\n const orgApps = await fetchOrgApps({ selfId }).catch(\n () => [] as OrgApp[],\n );\n const dirMatch = orgApps.find(\n (a) => a.id === requestedApp.toLowerCase(),\n );\n if (dirMatch) {\n try {\n return await routeAskOverA2A(\n dirMatch.a2aUrl,\n dirMatch.id,\n message,\n {\n durable: useDurableA2A,\n maxWaitMs,\n },\n );\n } catch (err: any) {\n throw new Error(\n `Failed to route ask_app to \"${dirMatch.id}\" via A2A ` +\n `(org directory): ${err?.message ?? err}`,\n );\n }\n }\n }\n\n // Same app (or no workspace / unknown target): answer locally with this\n // app's own ask-agent handler — the same entry point the HTTP MCP mount\n // + A2A use, so there is no second agent runner.\n if (!config.askAgent) {\n throw new Error(\n \"This app does not expose an agent (no ask-agent handler).\",\n );\n }\n\n // If the caller named an app we couldn't route to (unknown id, or no\n // workspace), say so honestly instead of claiming we reached it.\n const unresolved =\n !!requestedApp && requestedApp.toLowerCase() !== selfId;\n const note = unresolved\n ? `Requested app \"${requestedApp}\" is not a reachable workspace ` +\n `app; answered with this app (\"${selfId}\") instead.`\n : undefined;\n\n // Hosted MCP cannot safely keep a JSON request/response open for a full\n // agent loop: serverless gateways can return an inactivity 504 before\n // the result body exists. When we know the running app origin, submit the\n // local ask through the app's durable A2A task path and only wait a\n // short bounded window for fast completions.\n const localA2AEndpointUrl = selfA2AEndpointUrl(requestMeta);\n if (localA2AEndpointUrl) {\n return submitAskAppA2ATask(\n {\n app: selfId,\n origin: localA2AEndpointUrl,\n routedVia: \"local\",\n ...(note ? { note } : {}),\n },\n message,\n maxWaitMs,\n );\n }\n\n const response = await config.askAgent(message);\n return {\n app: selfId,\n routedVia: \"local\",\n ...(note ? { note } : {}),\n response,\n };\n },\n };\n}\n\nfunction askAppStatusTool(\n config: MCPConfig,\n requestMeta?: AskAppRequestMeta,\n): ActionEntry {\n return {\n tool: tool(\n \"Poll a durable ask_app task and return its current status or final response.\",\n {\n app: {\n type: \"string\",\n description:\n \"App id returned by ask_app. Optional for same-app local tasks.\",\n },\n taskId: {\n type: \"string\",\n description: \"The durable task id returned by ask_app.\",\n },\n },\n [\"taskId\"],\n ),\n readOnly: true,\n parallelSafe: true,\n run: async (args: Record<string, any>) => {\n const taskId = String(args.taskId ?? \"\").trim();\n if (!taskId) throw new Error(\"ask_app_status requires 'taskId'.\");\n const requestedApp = String(args.app ?? \"\").trim();\n const route = await resolveAskAppStatusRoute(\n config,\n requestedApp,\n requestMeta,\n );\n return fetchAskAppA2ATask(route, taskId);\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// list_templates\n// ---------------------------------------------------------------------------\n\nfunction listTemplatesTool(): ActionEntry {\n return {\n tool: tool(\n \"List the first-party templates that can be scaffolded into a workspace \" +\n \"(allow-listed templates only).\",\n ),\n readOnly: true,\n parallelSafe: true,\n run: async () => {\n const { visibleTemplates } = await import(\"../cli/templates-meta.js\");\n return {\n templates: visibleTemplates().map((t) => ({\n name: t.name,\n label: t.label,\n hint: t.hint,\n })),\n };\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// create_workspace_app\n// ---------------------------------------------------------------------------\n\nfunction createWorkspaceAppTool(): ActionEntry {\n return {\n tool: tool(\n \"Scaffold a new app into the current workspace from an allow-listed \" +\n \"template, then return a deep link to open it. Idempotent: if an app \" +\n \"with that name already exists it is reused.\",\n {\n name: {\n type: \"string\",\n description: \"New app id (directory under apps/), e.g. 'mymail'\",\n },\n template: {\n type: \"string\",\n description:\n \"Template to scaffold from — must be allow-listed (see list_templates)\",\n },\n },\n [\"name\", \"template\"],\n ),\n run: async (args: Record<string, any>) => {\n const name = String(args.name ?? \"\").trim();\n const template = String(args.template ?? \"\").trim();\n if (!name || !template) {\n throw new Error(\n \"create_workspace_app requires both 'name' and 'template'.\",\n );\n }\n\n // Enforce the strict public template allow-list. The authoritative,\n // dependency-free source inside @agent-native/core is cli/templates-meta\n // (kept in sync with packages/shared-app-config/templates.ts; CI guard).\n const { visibleTemplates } = await import(\"../cli/templates-meta.js\");\n const allowed = new Set(visibleTemplates().map((t) => t.name));\n if (!allowed.has(template)) {\n throw new Error(\n `Template \"${template}\" is not allow-listed. Allowed: ${[...allowed]\n .sort()\n .join(\", \")}`,\n );\n }\n\n const { findWorkspaceRoot, resolveWorkspace } =\n await import(\"./workspace-resolve.js\");\n const fs = await import(\"node:fs\");\n const path = await import(\"node:path\");\n\n const root = findWorkspaceRoot(process.cwd());\n if (!root) {\n throw new Error(\n \"Not inside a workspace. create_workspace_app only works in a \" +\n \"multi-app workspace (run from the workspace root).\",\n );\n }\n\n const appDir = path.join(root, \"apps\", name);\n const alreadyExisted = fs.existsSync(appDir);\n\n if (!alreadyExisted) {\n // Reuse the CLI scaffolder directly (no second `agent-native`\n // subprocess). `addAppToWorkspace(name, { template })` takes the\n // non-interactive single-template path when name + one template are\n // given. Run it from the workspace root so detectWorkspace resolves.\n const prevCwd = process.cwd();\n try {\n process.chdir(root);\n const { addAppToWorkspace } = await import(\"../cli/create.js\");\n await addAppToWorkspace(name, { template, noInstall: true });\n } finally {\n try {\n process.chdir(prevCwd);\n } catch {\n // best-effort cwd restore\n }\n }\n }\n\n // The workspace gateway auto-detects new apps/* dirs (fs.watch +\n // 2s sync) and lazily boots the dev server on first request, so we\n // don't spawn vite ourselves — opening the deep link warms it. Resolve\n // the port the gateway will use so we can report it.\n const ws = await resolveWorkspace(root);\n const appInfo = ws.apps.find((a) => a.id === name);\n const port = appInfo?.port;\n // The scaffolded app is always a *different* app from the host MCP\n // server, so anchor the deep link to the new app's own origin. A\n // relative path would otherwise be prefixed with the current request\n // origin and land on the wrong app. Fall back to the relative path\n // only if the gateway hasn't reported the new app's URL yet.\n const relDeepLink = buildDeepLink({ app: name, view: \"home\" });\n const deepLink = appInfo?.url\n ? `${appInfo.url.replace(/\\/+$/, \"\")}${relDeepLink}`\n : relDeepLink;\n\n return {\n name,\n template,\n created: !alreadyExisted,\n reused: alreadyExisted,\n port,\n url: appInfo?.url,\n gatewayUrl: ws.gatewayUrl,\n deepLink,\n };\n },\n link: ({ result }) => {\n if (!result || typeof result !== \"object\") return null;\n const r = result as { deepLink?: string; name?: string };\n if (!r.deepLink) return null;\n return {\n url: r.deepLink,\n label: `Open ${r.name ?? \"app\"}`,\n view: \"home\",\n };\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Registry\n// ---------------------------------------------------------------------------\n\n/**\n * Build the generic cross-app builtin tool registry. Called by\n * `createMCPServerForRequest`; the result is merged UNDER the config's\n * actions so template actions of the same name win.\n */\nexport function getBuiltinCrossAppTools(\n config: MCPConfig,\n requestMeta?: AskAppRequestMeta,\n): Record<string, ActionEntry> {\n return {\n list_apps: listAppsTool(config, requestMeta),\n open_app: openAppTool(config, requestMeta),\n create_embed_session: createEmbedSessionTool(requestMeta),\n ask_app: askAppTool(config, requestMeta),\n ask_app_status: askAppStatusTool(config, requestMeta),\n create_workspace_app: createWorkspaceAppTool(),\n list_templates: listTemplatesTool(),\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"org-directory.d.ts","sourceRoot":"","sources":["../../src/mcp/org-directory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAEH,MAAM,WAAW,MAAM;IACrB,yCAAyC;IACzC,EAAE,EAAE,MAAM,CAAC;IACX,4CAA4C;IAC5C,IAAI,EAAE,MAAM,CAAC;IACb,iEAAiE;IACjE,GAAG,EAAE,MAAM,CAAC;IACZ;;;OAGG;IACH,MAAM,EAAE,MAAM,CAAC;IACf,gEAAgE;IAChE,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;CACzB;AAeD;;;;;GAKG;AACH,wBAAgB,yBAAyB,CACvC,GAAG,GAAE,MAAM,CAAC,UAAwB,GACnC,MAAM,GAAG,IAAI,CAcf;AA4DD;;;;;;;;;;;;GAYG;AACH,wBAAsB,YAAY,CAAC,IAAI,CAAC,EAAE;IACxC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;CACzB,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CA2EpB;AAED,0DAA0D;AAC1D,wBAAgB,uBAAuB,IAAI,IAAI,CAE9C"}
1
+ {"version":3,"file":"org-directory.d.ts","sourceRoot":"","sources":["../../src/mcp/org-directory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAEH,MAAM,WAAW,MAAM;IACrB,yCAAyC;IACzC,EAAE,EAAE,MAAM,CAAC;IACX,4CAA4C;IAC5C,IAAI,EAAE,MAAM,CAAC;IACb,iEAAiE;IACjE,GAAG,EAAE,MAAM,CAAC;IACZ;;;OAGG;IACH,MAAM,EAAE,MAAM,CAAC;IACf,gEAAgE;IAChE,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;CACzB;AAeD;;;;;GAKG;AACH,wBAAgB,yBAAyB,CACvC,GAAG,GAAE,MAAM,CAAC,UAAwB,GACnC,MAAM,GAAG,IAAI,CAcf;AAqED;;;;;;;;;;;;GAYG;AACH,wBAAsB,YAAY,CAAC,IAAI,CAAC,EAAE;IACxC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;CACzB,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAgFpB;AAED,0DAA0D;AAC1D,wBAAgB,uBAAuB,IAAI,IAAI,CAE9C"}
@@ -116,6 +116,9 @@ function scopedCacheKey(origin, auth) {
116
116
  `org:${auth.orgId ?? auth.orgDomain ?? ""}`,
117
117
  ].join("|");
118
118
  }
119
+ function authTokenAttempts(auth) {
120
+ return [auth.apiKey, ...(auth.apiKeyFallbacks ?? [])].filter((token) => typeof token === "string" && token.length > 0);
121
+ }
119
122
  function serviceScopedCacheKey(origin, orgId) {
120
123
  return [origin, `service-org:${orgId}`].join("|");
121
124
  }
@@ -163,7 +166,8 @@ export async function fetchOrgApps(opts) {
163
166
  const auth = serviceOrgId
164
167
  ? await resolveOrgDirectoryServiceAuth(serviceOrgId)
165
168
  : await resolveOrgDirectoryCallerAuth();
166
- if (!auth.apiKey) {
169
+ const attempts = authTokenAttempts(auth);
170
+ if (attempts.length === 0) {
167
171
  // No signed token available (no A2A secret / no caller identity) — the
168
172
  // directory requires the org bearer, so degrade silently to local-only.
169
173
  return [];
@@ -176,19 +180,24 @@ export async function fetchOrgApps(opts) {
176
180
  return stripSelf(cached.apps);
177
181
  }
178
182
  }
179
- const res = await fetch(`${origin}/_agent-native/org/apps`, {
180
- method: "GET",
181
- headers: {
182
- Authorization: `Bearer ${auth.apiKey}`,
183
- Accept: "application/json",
184
- },
185
- signal: AbortSignal.timeout(4000),
186
- });
187
- if (res.ok) {
188
- const json = (await res.json());
189
- const list = Array.isArray(json?.apps) ? json.apps : [];
190
- apps = list.map(normalizeApp).filter((a) => a !== null);
191
- ttl = SUCCESS_TTL_MS;
183
+ for (let i = 0; i < attempts.length; i++) {
184
+ const res = await fetch(`${origin}/_agent-native/org/apps`, {
185
+ method: "GET",
186
+ headers: {
187
+ Authorization: `Bearer ${attempts[i]}`,
188
+ Accept: "application/json",
189
+ },
190
+ signal: AbortSignal.timeout(4000),
191
+ });
192
+ if (res.ok) {
193
+ const json = (await res.json());
194
+ const list = Array.isArray(json?.apps) ? json.apps : [];
195
+ apps = list.map(normalizeApp).filter((a) => a !== null);
196
+ ttl = SUCCESS_TTL_MS;
197
+ break;
198
+ }
199
+ if (res.status !== 401 || i >= attempts.length - 1)
200
+ break;
192
201
  }
193
202
  // Non-2xx ⇒ leave apps=[] with the short EMPTY_TTL (silent degrade).
194
203
  }
@@ -235,12 +244,41 @@ async function resolveOrgDirectoryServiceAuth(orgId) {
235
244
  import("./connect-store.js"),
236
245
  ]);
237
246
  const userEmail = serviceIdentityEmail("mcp-client", trimmedOrgId);
238
- const apiKey = await signA2AToken(userEmail, orgDomain, orgSecret, {
239
- expiresIn: "5m",
240
- preferGlobalSecret: !orgSecret,
241
- extraClaims: { org_id: trimmedOrgId },
242
- });
243
- return { apiKey, userEmail, orgId: trimmedOrgId, orgDomain };
247
+ const apiKeyAttempts = [];
248
+ const addApiKeyAttempt = (token) => {
249
+ if (!token || apiKeyAttempts.includes(token))
250
+ return;
251
+ apiKeyAttempts.push(token);
252
+ };
253
+ if (process.env.A2A_SECRET?.trim()) {
254
+ try {
255
+ addApiKeyAttempt(await signA2AToken(userEmail, orgDomain, orgSecret, {
256
+ expiresIn: "5m",
257
+ preferGlobalSecret: true,
258
+ extraClaims: { org_id: trimmedOrgId },
259
+ }));
260
+ }
261
+ catch { }
262
+ }
263
+ if (orgSecret) {
264
+ try {
265
+ addApiKeyAttempt(await signA2AToken(userEmail, orgDomain, orgSecret, {
266
+ expiresIn: "5m",
267
+ preferGlobalSecret: false,
268
+ extraClaims: { org_id: trimmedOrgId },
269
+ }));
270
+ }
271
+ catch { }
272
+ }
273
+ return {
274
+ apiKey: apiKeyAttempts[0],
275
+ ...(apiKeyAttempts.length > 1
276
+ ? { apiKeyFallbacks: apiKeyAttempts.slice(1) }
277
+ : {}),
278
+ userEmail,
279
+ orgId: trimmedOrgId,
280
+ orgDomain,
281
+ };
244
282
  }
245
283
  catch {
246
284
  return { orgId: trimmedOrgId, orgDomain };
@@ -1 +1 @@
1
- {"version":3,"file":"org-directory.js","sourceRoot":"","sources":["../../src/mcp/org-directory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAkBH,0DAA0D;AAC1D,MAAM,cAAc,GAAG,MAAM,CAAC;AAC9B,8EAA8E;AAC9E,MAAM,YAAY,GAAG,MAAM,CAAC;AAO5B,6EAA6E;AAC7E,MAAM,KAAK,GAAG,IAAI,GAAG,EAAsB,CAAC;AAE5C;;;;;GAKG;AACH,MAAM,UAAU,yBAAyB,CACvC,GAAG,GAAsB,OAAO,CAAC,GAAG;IAEpC,MAAM,GAAG,G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AE,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,CAAC;IAC/D,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,CAAC;IAC5C,CAAC;AACH,CAAC","sourcesContent":["/**\n * Org-directory discovery for the generic cross-app MCP verbs\n * (`list_apps` / `ask_app` in `builtin-tools.ts`).\n *\n * Phase 3b of cross-app auto-wiring. Today the cross-app verbs resolve sibling\n * apps from *local workspace* info only (`workspace-resolve.ts`), so the mail\n * agent can only reach the calendar agent in a local dev workspace. When the\n * deployment runs against an org directory (Dispatch is also the identity hub\n * for the org), this module discovers the org's *deployed* sibling apps so the\n * same verbs work cross-app in production with ZERO manual setup.\n *\n * ## The directory request\n *\n * GET <directoryOrigin>/_agent-native/org/apps\n * Auth Authorization: Bearer <org A2A token> (same signed token A2A peers\n * already mint — reuses `resolveA2ACallerAuth()`; the org A2A secret /\n * global `A2A_SECRET` is loaded exactly how outgoing A2A calls load it)\n * ⇒ { org, apps: [ { id, name, url, a2aUrl, capabilities? } ] }\n * (allow-listed first-party apps only, prod URLs — enforced by the\n * authority side, Phase 3a, on Dispatch)\n *\n * ## Resolution + safety model\n *\n * - The directory origin is read from env: `AGENT_NATIVE_ORG_DIRECTORY_URL`\n * (dedicated) or `AGENT_NATIVE_IDENTITY_HUB_URL` (Dispatch is also the\n * identity hub). When *neither* is set the feature is simply inactive —\n * `fetchOrgApps()` returns `[]` and nothing changes anywhere (asserted by\n * a test). This makes the whole feature opt-in and back-compat.\n * - On ANY error (no env, unreachable, 401, non-2xx, bad JSON, no signed\n * token) `fetchOrgApps()` returns `[]` and NEVER throws — the cross-app\n * verbs degrade silently to their exact current local-only behavior.\n * - A short in-memory TTL cache (default 60s) keyed by directory origin and\n * caller identity/org scope so sibling app lists never cross tenants.\n * Empty authenticated results are cached too (with a shorter TTL) so a\n * transient failure doesn't hammer the directory on every call.\n * - No secrets are ever logged.\n *\n * Bundled alongside `mountMCP` (no Node-only top-level imports). The A2A\n * caller-auth + a2a client are dynamically imported inside `fetchOrgApps()`.\n */\n\nexport interface OrgApp {\n /** Canonical app id, e.g. `calendar`. */\n id: string;\n /** Human-readable name, e.g. `Calendar`. */\n name: string;\n /** Deployed app origin/URL, e.g. `https://calendar.acme.com`. */\n url: string;\n /**\n * A2A endpoint to route `ask_app` to. The authority side returns this; we\n * fall back to the app `url` (the A2A client appends `/_agent-native/a2a`).\n */\n a2aUrl: string;\n /** Optional capability hints the authority side may include. */\n capabilities?: string[];\n}\n\n/** Default cache TTL for a successful directory fetch. */\nconst SUCCESS_TTL_MS = 60_000;\n/** Shorter TTL for an empty/failed fetch so transient errors recover fast. */\nconst EMPTY_TTL_MS = 10_000;\n\ninterface CacheEntry {\n apps: OrgApp[];\n expiresAt: number;\n}\n\n/** In-memory cache keyed by resolved directory origin (+ identity scope). */\nconst cache = new Map<string, CacheEntry>();\n\n/**\n * Resolve the org-directory origin from env. Returns `null` when neither env\n * var is set — the caller treats `null` as \"feature inactive\".\n *\n * `env` is injectable for tests; defaults to `process.env`.\n */\nexport function resolveOrgDirectoryOrigin(\n env: NodeJS.ProcessEnv = process.env,\n): string | null {\n const raw =\n env.AGENT_NATIVE_ORG_DIRECTORY_URL || env.AGENT_NATIVE_IDENTITY_HUB_URL;\n if (!raw || typeof raw !== \"string\") return null;\n const trimmed = raw.trim().replace(/\\/+$/, \"\");\n if (!trimmed) return null;\n try {\n // Validate it's an absolute http(s) URL; reject anything else.\n const u = new URL(trimmed);\n if (u.protocol !== \"http:\" && u.protocol !== \"https:\") return null;\n return trimmed;\n } catch {\n return null;\n }\n}\n\nfunction normalizeApp(raw: unknown): OrgApp | null {\n if (!raw || typeof raw !== \"object\") return null;\n const r = raw as Record<string, unknown>;\n const id = typeof r.id === \"string\" ? r.id.trim().toLowerCase() : \"\";\n const url = typeof r.url === \"string\" ? r.url.trim() : \"\";\n if (!id || !url) return null;\n // Only accept absolute http(s) URLs from the directory.\n try {\n const u = new URL(url);\n if (u.protocol !== \"http:\" && u.protocol !== \"https:\") return null;\n } catch {\n return null;\n }\n const name = typeof r.name === \"string\" && r.name.trim() ? r.name.trim() : id;\n const a2aUrl =\n typeof r.a2aUrl === \"string\" && r.a2aUrl.trim() ? r.a2aUrl.trim() : url;\n const capabilities = Array.isArray(r.capabilities)\n ? r.capabilities.filter((c): c is string => typeof c === \"string\")\n : undefined;\n return {\n id,\n name,\n url: url.replace(/\\/+$/, \"\"),\n a2aUrl: a2aUrl.replace(/\\/+$/, \"\"),\n ...(capabilities && capabilities.length ? { capabilities } : {}),\n };\n}\n\n/** Compare two origins by host (ignores trailing slash / protocol noise). */\nfunction sameOrigin(a: string, b: string): boolean {\n try {\n const ua = new URL(a);\n const ub = new URL(b);\n return ua.host === ub.host && ua.protocol === ub.protocol;\n } catch {\n return a.replace(/\\/+$/, \"\") === b.replace(/\\/+$/, \"\");\n }\n}\n\nfunction scopedCacheKey(\n origin: string,\n auth: {\n userEmail?: string;\n orgId?: string;\n orgDomain?: string;\n },\n): string {\n return [\n origin,\n `user:${auth.userEmail ?? \"\"}`,\n `org:${auth.orgId ?? auth.orgDomain ?? \"\"}`,\n ].join(\"|\");\n}\n\nfunction serviceScopedCacheKey(origin: string, orgId: string): string {\n return [origin, `service-org:${orgId}`].join(\"|\");\n}\n\n/**\n * Fetch the org's first-party sibling apps from the org directory.\n *\n * - Returns `[]` (never throws) on ANY failure or when the directory env is\n * unset — the cross-app verbs then keep their exact local-only behavior.\n * - Short in-memory TTL cache so it isn't fetched on every tool call.\n * - Strips the current app from the result (compared by id and by origin) so\n * `list_apps` / `ask_app` never offer to route to themselves.\n *\n * @param opts.selfId Current app id (so it's stripped from the result).\n * @param opts.selfOrigin Current app origin (so it's stripped by origin too).\n * @param opts.env Injectable env (tests). Defaults to `process.env`.\n */\nexport async function fetchOrgApps(opts?: {\n selfId?: string;\n selfOrigin?: string;\n serviceOrgId?: string;\n env?: NodeJS.ProcessEnv;\n}): Promise<OrgApp[]> {\n const env = opts?.env ?? process.env;\n const origin = resolveOrgDirectoryOrigin(env);\n // Feature inactive: no directory configured ⇒ behave exactly as before.\n if (!origin) return [];\n\n const selfId = (opts?.selfId ?? \"\").trim().toLowerCase();\n const selfOrigin = (opts?.selfOrigin ?? \"\").trim();\n\n const stripSelf = (apps: OrgApp[]): OrgApp[] =>\n apps.filter((a) => {\n if (selfId && a.id === selfId) return false;\n if (selfOrigin && sameOrigin(a.url, selfOrigin)) return false;\n return true;\n });\n\n let cacheKey: string | null = null;\n let apps: OrgApp[] = [];\n let ttl = EMPTY_TTL_MS;\n const serviceOrgId = opts?.serviceOrgId?.trim();\n if (serviceOrgId) {\n const serviceCacheKey = serviceScopedCacheKey(origin, serviceOrgId);\n const cached = cache.get(serviceCacheKey);\n if (cached && cached.expiresAt > Date.now()) {\n return stripSelf(cached.apps);\n }\n cacheKey = serviceCacheKey;\n }\n try {\n const auth = serviceOrgId\n ? await resolveOrgDirectoryServiceAuth(serviceOrgId)\n : await resolveOrgDirectoryCallerAuth();\n if (!auth.apiKey) {\n // No signed token available (no A2A secret / no caller identity) — the\n // directory requires the org bearer, so degrade silently to local-only.\n return [];\n }\n\n if (!cacheKey) {\n const now = Date.now();\n cacheKey = scopedCacheKey(origin, auth);\n const cached = cache.get(cacheKey);\n if (cached && cached.expiresAt > now) {\n return stripSelf(cached.apps);\n }\n }\n\n const res = await fetch(`${origin}/_agent-native/org/apps`, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n Accept: \"application/json\",\n },\n signal: AbortSignal.timeout(4000),\n });\n if (res.ok) {\n const json = (await res.json()) as { apps?: unknown };\n const list = Array.isArray(json?.apps) ? json.apps : [];\n apps = list.map(normalizeApp).filter((a): a is OrgApp => a !== null);\n ttl = SUCCESS_TTL_MS;\n }\n // Non-2xx ⇒ leave apps=[] with the short EMPTY_TTL (silent degrade).\n } catch {\n // Unreachable / parse error / abort ⇒ silent degrade to local-only.\n apps = [];\n ttl = EMPTY_TTL_MS;\n }\n\n if (cacheKey) {\n cache.set(cacheKey, {\n apps,\n expiresAt: Date.now() + ttl,\n });\n }\n return stripSelf(apps);\n}\n\n/** Test-only: clear the in-memory cache between cases. */\nexport function _resetOrgDirectoryCache(): void {\n cache.clear();\n}\n\nasync function resolveOrgDirectoryCallerAuth(): Promise<{\n apiKey?: string;\n userEmail?: string;\n orgId?: string;\n orgDomain?: string;\n}> {\n // Reuse the existing A2A caller-auth: it reads userEmail + orgId from the\n // request context, loads the org A2A secret via getOrgA2ASecret (falling\n // back to the global A2A_SECRET env), and signs the same bearer JWT A2A\n // peers already use. No new secret loading is invented for normal callers.\n const { resolveA2ACallerAuth } = await import(\"../a2a/caller-auth.js\");\n return resolveA2ACallerAuth();\n}\n\nasync function resolveOrgDirectoryServiceAuth(orgId: string): Promise<{\n apiKey?: string;\n userEmail?: string;\n orgId?: string;\n orgDomain?: string;\n}> {\n const trimmedOrgId = orgId.trim();\n if (!trimmedOrgId) return {};\n let orgDomain: string | undefined;\n let orgSecret: string | undefined;\n try {\n const { getOrgDomain, getOrgA2ASecret } = await import(\"../org/context.js\");\n orgDomain = (await getOrgDomain(trimmedOrgId)) ?? undefined;\n orgSecret = (await getOrgA2ASecret(trimmedOrgId)) ?? undefined;\n } catch {}\n try {\n const [{ signA2AToken }, { serviceIdentityEmail }] = await Promise.all([\n import(\"../a2a/client.js\"),\n import(\"./connect-store.js\"),\n ]);\n const userEmail = serviceIdentityEmail(\"mcp-client\", trimmedOrgId);\n const apiKey = await signA2AToken(userEmail, orgDomain, orgSecret, {\n expiresIn: \"5m\",\n preferGlobalSecret: !orgSecret,\n extraClaims: { org_id: trimmedOrgId },\n });\n return { apiKey, userEmail, orgId: trimmedOrgId, orgDomain };\n } catch {\n return { orgId: trimmedOrgId, orgDomain };\n }\n}\n"]}
1
+ {"version":3,"file":"org-directory.js","sourceRoot":"","sources":["../../src/mcp/org-directory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;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CAAA,CAAC;QACZ,CAAC;QACD,IAAI,SAAS,EAAE,CAAC;YACd,IAAI,CAAC;gBACH,gBAAgB,CACd,MAAM,YAAY,CAAC,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE;oBAClD,SAAS,EAAE,IAAI;oBACf,kBAAkB,EAAE,KAAK;oBACzB,WAAW,EAAE,EAAE,MAAM,EAAE,YAAY,EAAE;iBACtC,CAAC,CACH,CAAC;YACJ,CAAC;YAAC,MAAM,CAAC,CAAA,CAAC;QACZ,CAAC;QACD,OAAO;YACL,MAAM,EAAE,cAAc,CAAC,CAAC,CAAC;YACzB,GAAG,CAAC,cAAc,CAAC,MAAM,GAAG,CAAC;gBAC3B,CAAC,CAAC,EAAE,eAAe,EAAE,cAAc,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE;gBAC9C,CAAC,CAAC,EAAE,CAAC;YACP,SAAS;YACT,KAAK,EAAE,YAAY;YACnB,SAAS;SACV,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,CAAC;IAC5C,CAAC;AACH,CAAC","sourcesContent":["/**\n * Org-directory discovery for the generic cross-app MCP verbs\n * (`list_apps` / `ask_app` in `builtin-tools.ts`).\n *\n * Phase 3b of cross-app auto-wiring. Today the cross-app verbs resolve sibling\n * apps from *local workspace* info only (`workspace-resolve.ts`), so the mail\n * agent can only reach the calendar agent in a local dev workspace. When the\n * deployment runs against an org directory (Dispatch is also the identity hub\n * for the org), this module discovers the org's *deployed* sibling apps so the\n * same verbs work cross-app in production with ZERO manual setup.\n *\n * ## The directory request\n *\n * GET <directoryOrigin>/_agent-native/org/apps\n * Auth Authorization: Bearer <org A2A token> (same signed token A2A peers\n * already mint — reuses `resolveA2ACallerAuth()`; the org A2A secret /\n * global `A2A_SECRET` is loaded exactly how outgoing A2A calls load it)\n * ⇒ { org, apps: [ { id, name, url, a2aUrl, capabilities? } ] }\n * (allow-listed first-party apps only, prod URLs — enforced by the\n * authority side, Phase 3a, on Dispatch)\n *\n * ## Resolution + safety model\n *\n * - The directory origin is read from env: `AGENT_NATIVE_ORG_DIRECTORY_URL`\n * (dedicated) or `AGENT_NATIVE_IDENTITY_HUB_URL` (Dispatch is also the\n * identity hub). When *neither* is set the feature is simply inactive —\n * `fetchOrgApps()` returns `[]` and nothing changes anywhere (asserted by\n * a test). This makes the whole feature opt-in and back-compat.\n * - On ANY error (no env, unreachable, 401, non-2xx, bad JSON, no signed\n * token) `fetchOrgApps()` returns `[]` and NEVER throws — the cross-app\n * verbs degrade silently to their exact current local-only behavior.\n * - A short in-memory TTL cache (default 60s) keyed by directory origin and\n * caller identity/org scope so sibling app lists never cross tenants.\n * Empty authenticated results are cached too (with a shorter TTL) so a\n * transient failure doesn't hammer the directory on every call.\n * - No secrets are ever logged.\n *\n * Bundled alongside `mountMCP` (no Node-only top-level imports). The A2A\n * caller-auth + a2a client are dynamically imported inside `fetchOrgApps()`.\n */\n\nexport interface OrgApp {\n /** Canonical app id, e.g. `calendar`. */\n id: string;\n /** Human-readable name, e.g. `Calendar`. */\n name: string;\n /** Deployed app origin/URL, e.g. `https://calendar.acme.com`. */\n url: string;\n /**\n * A2A endpoint to route `ask_app` to. The authority side returns this; we\n * fall back to the app `url` (the A2A client appends `/_agent-native/a2a`).\n */\n a2aUrl: string;\n /** Optional capability hints the authority side may include. */\n capabilities?: string[];\n}\n\n/** Default cache TTL for a successful directory fetch. */\nconst SUCCESS_TTL_MS = 60_000;\n/** Shorter TTL for an empty/failed fetch so transient errors recover fast. */\nconst EMPTY_TTL_MS = 10_000;\n\ninterface CacheEntry {\n apps: OrgApp[];\n expiresAt: number;\n}\n\n/** In-memory cache keyed by resolved directory origin (+ identity scope). */\nconst cache = new Map<string, CacheEntry>();\n\n/**\n * Resolve the org-directory origin from env. Returns `null` when neither env\n * var is set — the caller treats `null` as \"feature inactive\".\n *\n * `env` is injectable for tests; defaults to `process.env`.\n */\nexport function resolveOrgDirectoryOrigin(\n env: NodeJS.ProcessEnv = process.env,\n): string | null {\n const raw =\n env.AGENT_NATIVE_ORG_DIRECTORY_URL || env.AGENT_NATIVE_IDENTITY_HUB_URL;\n if (!raw || typeof raw !== \"string\") return null;\n const trimmed = raw.trim().replace(/\\/+$/, \"\");\n if (!trimmed) return null;\n try {\n // Validate it's an absolute http(s) URL; reject anything else.\n const u = new URL(trimmed);\n if (u.protocol !== \"http:\" && u.protocol !== \"https:\") return null;\n return trimmed;\n } catch {\n return null;\n }\n}\n\nfunction normalizeApp(raw: unknown): OrgApp | null {\n if (!raw || typeof raw !== \"object\") return null;\n const r = raw as Record<string, unknown>;\n const id = typeof r.id === \"string\" ? r.id.trim().toLowerCase() : \"\";\n const url = typeof r.url === \"string\" ? r.url.trim() : \"\";\n if (!id || !url) return null;\n // Only accept absolute http(s) URLs from the directory.\n try {\n const u = new URL(url);\n if (u.protocol !== \"http:\" && u.protocol !== \"https:\") return null;\n } catch {\n return null;\n }\n const name = typeof r.name === \"string\" && r.name.trim() ? r.name.trim() : id;\n const a2aUrl =\n typeof r.a2aUrl === \"string\" && r.a2aUrl.trim() ? r.a2aUrl.trim() : url;\n const capabilities = Array.isArray(r.capabilities)\n ? r.capabilities.filter((c): c is string => typeof c === \"string\")\n : undefined;\n return {\n id,\n name,\n url: url.replace(/\\/+$/, \"\"),\n a2aUrl: a2aUrl.replace(/\\/+$/, \"\"),\n ...(capabilities && capabilities.length ? { capabilities } : {}),\n };\n}\n\n/** Compare two origins by host (ignores trailing slash / protocol noise). */\nfunction sameOrigin(a: string, b: string): boolean {\n try {\n const ua = new URL(a);\n const ub = new URL(b);\n return ua.host === ub.host && ua.protocol === ub.protocol;\n } catch {\n return a.replace(/\\/+$/, \"\") === b.replace(/\\/+$/, \"\");\n }\n}\n\nfunction scopedCacheKey(\n origin: string,\n auth: {\n userEmail?: string;\n orgId?: string;\n orgDomain?: string;\n },\n): string {\n return [\n origin,\n `user:${auth.userEmail ?? \"\"}`,\n `org:${auth.orgId ?? auth.orgDomain ?? \"\"}`,\n ].join(\"|\");\n}\n\nfunction authTokenAttempts(auth: {\n apiKey?: string;\n apiKeyFallbacks?: string[];\n}): string[] {\n return [auth.apiKey, ...(auth.apiKeyFallbacks ?? [])].filter(\n (token): token is string => typeof token === \"string\" && token.length > 0,\n );\n}\n\nfunction serviceScopedCacheKey(origin: string, orgId: string): string {\n return [origin, `service-org:${orgId}`].join(\"|\");\n}\n\n/**\n * Fetch the org's first-party sibling apps from the org directory.\n *\n * - Returns `[]` (never throws) on ANY failure or when the directory env is\n * unset — the cross-app verbs then keep their exact local-only behavior.\n * - Short in-memory TTL cache so it isn't fetched on every tool call.\n * - Strips the current app from the result (compared by id and by origin) so\n * `list_apps` / `ask_app` never offer to route to themselves.\n *\n * @param opts.selfId Current app id (so it's stripped from the result).\n * @param opts.selfOrigin Current app origin (so it's stripped by origin too).\n * @param opts.env Injectable env (tests). Defaults to `process.env`.\n */\nexport async function fetchOrgApps(opts?: {\n selfId?: string;\n selfOrigin?: string;\n serviceOrgId?: string;\n env?: NodeJS.ProcessEnv;\n}): Promise<OrgApp[]> {\n const env = opts?.env ?? process.env;\n const origin = resolveOrgDirectoryOrigin(env);\n // Feature inactive: no directory configured ⇒ behave exactly as before.\n if (!origin) return [];\n\n const selfId = (opts?.selfId ?? \"\").trim().toLowerCase();\n const selfOrigin = (opts?.selfOrigin ?? \"\").trim();\n\n const stripSelf = (apps: OrgApp[]): OrgApp[] =>\n apps.filter((a) => {\n if (selfId && a.id === selfId) return false;\n if (selfOrigin && sameOrigin(a.url, selfOrigin)) return false;\n return true;\n });\n\n let cacheKey: string | null = null;\n let apps: OrgApp[] = [];\n let ttl = EMPTY_TTL_MS;\n const serviceOrgId = opts?.serviceOrgId?.trim();\n if (serviceOrgId) {\n const serviceCacheKey = serviceScopedCacheKey(origin, serviceOrgId);\n const cached = cache.get(serviceCacheKey);\n if (cached && cached.expiresAt > Date.now()) {\n return stripSelf(cached.apps);\n }\n cacheKey = serviceCacheKey;\n }\n try {\n const auth = serviceOrgId\n ? await resolveOrgDirectoryServiceAuth(serviceOrgId)\n : await resolveOrgDirectoryCallerAuth();\n const attempts = authTokenAttempts(auth);\n if (attempts.length === 0) {\n // No signed token available (no A2A secret / no caller identity) — the\n // directory requires the org bearer, so degrade silently to local-only.\n return [];\n }\n\n if (!cacheKey) {\n const now = Date.now();\n cacheKey = scopedCacheKey(origin, auth);\n const cached = cache.get(cacheKey);\n if (cached && cached.expiresAt > now) {\n return stripSelf(cached.apps);\n }\n }\n\n for (let i = 0; i < attempts.length; i++) {\n const res = await fetch(`${origin}/_agent-native/org/apps`, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${attempts[i]}`,\n Accept: \"application/json\",\n },\n signal: AbortSignal.timeout(4000),\n });\n if (res.ok) {\n const json = (await res.json()) as { apps?: unknown };\n const list = Array.isArray(json?.apps) ? json.apps : [];\n apps = list.map(normalizeApp).filter((a): a is OrgApp => a !== null);\n ttl = SUCCESS_TTL_MS;\n break;\n }\n if (res.status !== 401 || i >= attempts.length - 1) break;\n }\n // Non-2xx ⇒ leave apps=[] with the short EMPTY_TTL (silent degrade).\n } catch {\n // Unreachable / parse error / abort ⇒ silent degrade to local-only.\n apps = [];\n ttl = EMPTY_TTL_MS;\n }\n\n if (cacheKey) {\n cache.set(cacheKey, {\n apps,\n expiresAt: Date.now() + ttl,\n });\n }\n return stripSelf(apps);\n}\n\n/** Test-only: clear the in-memory cache between cases. */\nexport function _resetOrgDirectoryCache(): void {\n cache.clear();\n}\n\nasync function resolveOrgDirectoryCallerAuth(): Promise<{\n apiKey?: string;\n apiKeyFallbacks?: string[];\n userEmail?: string;\n orgId?: string;\n orgDomain?: string;\n}> {\n // Reuse the existing A2A caller-auth: it reads userEmail + orgId from the\n // request context, loads the org A2A secret via getOrgA2ASecret (falling\n // back to the global A2A_SECRET env), and signs the same bearer JWT A2A\n // peers already use. No new secret loading is invented for normal callers.\n const { resolveA2ACallerAuth } = await import(\"../a2a/caller-auth.js\");\n return resolveA2ACallerAuth();\n}\n\nasync function resolveOrgDirectoryServiceAuth(orgId: string): Promise<{\n apiKey?: string;\n apiKeyFallbacks?: string[];\n userEmail?: string;\n orgId?: string;\n orgDomain?: string;\n}> {\n const trimmedOrgId = orgId.trim();\n if (!trimmedOrgId) return {};\n let orgDomain: string | undefined;\n let orgSecret: string | undefined;\n try {\n const { getOrgDomain, getOrgA2ASecret } = await import(\"../org/context.js\");\n orgDomain = (await getOrgDomain(trimmedOrgId)) ?? undefined;\n orgSecret = (await getOrgA2ASecret(trimmedOrgId)) ?? undefined;\n } catch {}\n try {\n const [{ signA2AToken }, { serviceIdentityEmail }] = await Promise.all([\n import(\"../a2a/client.js\"),\n import(\"./connect-store.js\"),\n ]);\n const userEmail = serviceIdentityEmail(\"mcp-client\", trimmedOrgId);\n const apiKeyAttempts: string[] = [];\n const addApiKeyAttempt = (token: string | undefined) => {\n if (!token || apiKeyAttempts.includes(token)) return;\n apiKeyAttempts.push(token);\n };\n if (process.env.A2A_SECRET?.trim()) {\n try {\n addApiKeyAttempt(\n await signA2AToken(userEmail, orgDomain, orgSecret, {\n expiresIn: \"5m\",\n preferGlobalSecret: true,\n extraClaims: { org_id: trimmedOrgId },\n }),\n );\n } catch {}\n }\n if (orgSecret) {\n try {\n addApiKeyAttempt(\n await signA2AToken(userEmail, orgDomain, orgSecret, {\n expiresIn: \"5m\",\n preferGlobalSecret: false,\n extraClaims: { org_id: trimmedOrgId },\n }),\n );\n } catch {}\n }\n return {\n apiKey: apiKeyAttempts[0],\n ...(apiKeyAttempts.length > 1\n ? { apiKeyFallbacks: apiKeyAttempts.slice(1) }\n : {}),\n userEmail,\n orgId: trimmedOrgId,\n orgDomain,\n };\n } catch {\n return { orgId: trimmedOrgId, orgDomain };\n }\n}\n"]}
@@ -10,6 +10,16 @@
10
10
  * value never enters the agent context.
11
11
  * NOTIFICATIONS_WEBHOOK_AUTH → optional `Authorization` header value (also
12
12
  * supports `${keys.NAME}`).
13
+ * NOTIFICATIONS_SLACK_WEBHOOK_URL
14
+ * → POST notifications to a Slack incoming webhook.
15
+ * Supports `${keys.NAME}` substitution.
16
+ * NOTIFICATIONS_EMAIL_CHANNEL=1
17
+ * → enable the built-in email channel for
18
+ * per-notification recipients.
19
+ * NOTIFICATIONS_EMAIL_RECIPIENTS
20
+ * → comma-separated fallback recipients for email
21
+ * notifications that do not pass
22
+ * `metadata.emailRecipients`.
13
23
  */
14
24
  export declare function registerBuiltinNotificationChannels(): void;
15
25
  //# sourceMappingURL=channels.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"channels.d.ts","sourceRoot":"","sources":["../../src/notifications/channels.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAaH,wBAAgB,mCAAmC,IAAI,IAAI,CAQ1D"}
1
+ {"version":3,"file":"channels.d.ts","sourceRoot":"","sources":["../../src/notifications/channels.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAcH,wBAAgB,mCAAmC,IAAI,IAAI,CAkB1D"}