@agent-native/core 0.97.0 → 0.98.0

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 (844) hide show
  1. package/corpus/README.md +2 -2
  2. package/corpus/core/CHANGELOG.md +32 -0
  3. package/corpus/core/docs/content/authentication.mdx +3 -3
  4. package/corpus/core/docs/content/doctor.mdx +170 -0
  5. package/corpus/core/docs/content/external-agents.mdx +8 -7
  6. package/corpus/core/docs/content/locales/ar-SA/authentication.mdx +2 -2
  7. package/corpus/core/docs/content/locales/ar-SA/external-agents.mdx +8 -7
  8. package/corpus/core/docs/content/locales/ar-SA/mcp-protocol.mdx +1 -1
  9. package/corpus/core/docs/content/locales/ar-SA/security.mdx +2 -0
  10. package/corpus/core/docs/content/locales/de-DE/authentication.mdx +1 -1
  11. package/corpus/core/docs/content/locales/de-DE/external-agents.mdx +8 -7
  12. package/corpus/core/docs/content/locales/de-DE/mcp-protocol.mdx +1 -1
  13. package/corpus/core/docs/content/locales/de-DE/security.mdx +2 -0
  14. package/corpus/core/docs/content/locales/es-ES/authentication.mdx +2 -2
  15. package/corpus/core/docs/content/locales/es-ES/external-agents.mdx +8 -7
  16. package/corpus/core/docs/content/locales/es-ES/mcp-protocol.mdx +1 -1
  17. package/corpus/core/docs/content/locales/es-ES/security.mdx +2 -0
  18. package/corpus/core/docs/content/locales/fr-FR/authentication.mdx +1 -1
  19. package/corpus/core/docs/content/locales/fr-FR/external-agents.mdx +8 -7
  20. package/corpus/core/docs/content/locales/fr-FR/mcp-protocol.mdx +1 -1
  21. package/corpus/core/docs/content/locales/fr-FR/security.mdx +2 -0
  22. package/corpus/core/docs/content/locales/hi-IN/authentication.mdx +2 -2
  23. package/corpus/core/docs/content/locales/hi-IN/external-agents.mdx +8 -7
  24. package/corpus/core/docs/content/locales/hi-IN/mcp-protocol.mdx +1 -1
  25. package/corpus/core/docs/content/locales/hi-IN/security.mdx +2 -0
  26. package/corpus/core/docs/content/locales/ja-JP/authentication.mdx +2 -2
  27. package/corpus/core/docs/content/locales/ja-JP/external-agents.mdx +8 -7
  28. package/corpus/core/docs/content/locales/ja-JP/mcp-protocol.mdx +1 -1
  29. package/corpus/core/docs/content/locales/ja-JP/security.mdx +2 -0
  30. package/corpus/core/docs/content/locales/ko-KR/authentication.mdx +2 -2
  31. package/corpus/core/docs/content/locales/ko-KR/external-agents.mdx +8 -7
  32. package/corpus/core/docs/content/locales/ko-KR/mcp-protocol.mdx +1 -1
  33. package/corpus/core/docs/content/locales/ko-KR/security.mdx +2 -0
  34. package/corpus/core/docs/content/locales/pt-BR/authentication.mdx +2 -2
  35. package/corpus/core/docs/content/locales/pt-BR/external-agents.mdx +8 -7
  36. package/corpus/core/docs/content/locales/pt-BR/mcp-protocol.mdx +1 -1
  37. package/corpus/core/docs/content/locales/pt-BR/security.mdx +2 -0
  38. package/corpus/core/docs/content/locales/zh-CN/authentication.mdx +2 -2
  39. package/corpus/core/docs/content/locales/zh-CN/external-agents.mdx +8 -7
  40. package/corpus/core/docs/content/locales/zh-CN/mcp-protocol.mdx +1 -1
  41. package/corpus/core/docs/content/locales/zh-CN/security.mdx +2 -0
  42. package/corpus/core/docs/content/locales/zh-TW/authentication.mdx +2 -2
  43. package/corpus/core/docs/content/locales/zh-TW/external-agents.mdx +8 -7
  44. package/corpus/core/docs/content/locales/zh-TW/mcp-protocol.mdx +1 -1
  45. package/corpus/core/docs/content/locales/zh-TW/security.mdx +2 -0
  46. package/corpus/core/docs/content/mcp-protocol.mdx +1 -1
  47. package/corpus/core/docs/content/security.mdx +2 -0
  48. package/corpus/core/package.json +5 -1
  49. package/corpus/core/scripts/finalize-build.mjs +63 -3
  50. package/corpus/core/scripts/materialize-source-corpus.mjs +101 -15
  51. package/corpus/core/src/action.ts +42 -0
  52. package/corpus/core/src/agent/engine/builder-engine.ts +3 -0
  53. package/corpus/core/src/agent/engine/context-directives-transform.ts +69 -0
  54. package/corpus/core/src/agent/engine/continuation-dispatch-retry.ts +168 -0
  55. package/corpus/core/src/agent/engine/tool-call-journal-seed.ts +85 -0
  56. package/corpus/core/src/agent/production-agent.ts +129 -244
  57. package/corpus/core/src/cli/doctor.ts +9 -3
  58. package/corpus/core/src/cli/plan-local.ts +10 -2
  59. package/corpus/core/src/cli/skills-content/assets-skill.ts +83 -0
  60. package/corpus/core/src/cli/skills-content/canvas.ts +153 -0
  61. package/corpus/core/src/cli/skills-content/connection.ts +52 -0
  62. package/corpus/core/src/cli/skills-content/content-skill.ts +109 -0
  63. package/corpus/core/src/cli/skills-content/design-exploration-skill.ts +118 -0
  64. package/corpus/core/src/cli/skills-content/design-visual-edit-skill.ts +228 -0
  65. package/corpus/core/src/cli/skills-content/document-quality.ts +196 -0
  66. package/corpus/core/src/cli/skills-content/exemplar.ts +69 -0
  67. package/corpus/core/src/cli/skills-content/help.ts +77 -0
  68. package/corpus/core/src/cli/skills-content/index.ts +22 -0
  69. package/corpus/core/src/cli/skills-content/local-files.ts +95 -0
  70. package/corpus/core/src/cli/skills-content/plan-setup-auth.ts +80 -0
  71. package/corpus/core/src/cli/skills-content/visual-plan-skill.ts +470 -0
  72. package/corpus/core/src/cli/skills-content/visual-recap-skill.ts +547 -0
  73. package/corpus/core/src/cli/skills-content/visualize-repo-skill.ts +93 -0
  74. package/corpus/core/src/cli/skills-content/wireframe.ts +349 -0
  75. package/corpus/core/src/cli/skills.ts +27 -2733
  76. package/corpus/core/src/client/AgentPanel.tsx +6 -5
  77. package/corpus/core/src/client/CommandMenu.tsx +16 -5
  78. package/corpus/core/src/client/FeedbackButton.tsx +2 -2
  79. package/corpus/core/src/client/app-providers.tsx +18 -5
  80. package/corpus/core/src/client/chat/tool-call-display.tsx +3 -3
  81. package/corpus/core/src/client/composer/PastedTextChip.tsx +1 -1
  82. package/corpus/core/src/client/composer/RealtimeVoiceMode.tsx +143 -45
  83. package/corpus/core/src/client/composer/TiptapComposer.tsx +1 -1
  84. package/corpus/core/src/client/composer/VoiceButton.tsx +21 -5
  85. package/corpus/core/src/client/composer/useRealtimeVoiceMode.tsx +107 -10
  86. package/corpus/core/src/client/context-xray/ContextXRayPanel.tsx +5 -2
  87. package/corpus/core/src/client/extensions/ExtensionEditor.tsx +37 -4
  88. package/corpus/core/src/client/extensions/ExtensionQueryErrorState.tsx +47 -0
  89. package/corpus/core/src/client/extensions/ExtensionSlot.tsx +39 -10
  90. package/corpus/core/src/client/extensions/ExtensionViewer.tsx +44 -6
  91. package/corpus/core/src/client/extensions/ExtensionsListPage.tsx +12 -3
  92. package/corpus/core/src/client/extensions/ExtensionsSidebarSection.tsx +49 -11
  93. package/corpus/core/src/client/index.ts +0 -13
  94. package/corpus/core/src/client/progress/RunsTray.tsx +10 -3
  95. package/corpus/core/src/client/settings/SettingsTabsPage.tsx +7 -0
  96. package/corpus/core/src/client/settings/useBuilderStatus.ts +6 -0
  97. package/corpus/core/src/client/tool-cells/EditCell.tsx +19 -16
  98. package/corpus/core/src/client/tool-cells/FilesChangedSummary.tsx +26 -23
  99. package/corpus/core/src/client/tool-cells/WriteCell.tsx +19 -16
  100. package/corpus/core/src/client/visual-style-controls.tsx +1 -1
  101. package/corpus/core/src/deploy/build.ts +36 -14
  102. package/corpus/core/src/integrations/google-docs-poller.ts +23 -2
  103. package/corpus/core/src/integrations/plugin.ts +10 -0
  104. package/corpus/core/src/integrations/webhook-handler.ts +27 -2
  105. package/corpus/core/src/jobs/scheduler.ts +28 -2
  106. package/corpus/core/src/localization/default-messages.ts +8 -1
  107. package/corpus/core/src/mcp/oauth-token.ts +6 -1
  108. package/corpus/core/src/observability/routes.ts +36 -0
  109. package/corpus/core/src/observability/sentiment.ts +261 -0
  110. package/corpus/core/src/observability/store.ts +23 -0
  111. package/corpus/core/src/observability/traces.ts +49 -63
  112. package/corpus/core/src/observability/tracking-identity.ts +55 -0
  113. package/corpus/core/src/observability/types.ts +13 -0
  114. package/corpus/core/src/secrets/storage.ts +67 -3
  115. package/corpus/core/src/server/agent-chat/action-filters-a2a.ts +199 -0
  116. package/corpus/core/src/server/agent-chat/browser-team-tools.ts +510 -0
  117. package/corpus/core/src/server/agent-chat/context-tools.ts +595 -0
  118. package/corpus/core/src/server/agent-chat/framework-prompts.ts +470 -0
  119. package/corpus/core/src/server/agent-chat/lazy-fs.ts +11 -0
  120. package/corpus/core/src/server/agent-chat/mcp-glue.ts +91 -0
  121. package/corpus/core/src/server/agent-chat/plugin-options.ts +350 -0
  122. package/corpus/core/src/server/agent-chat/process-run-failure.ts +62 -0
  123. package/corpus/core/src/server/agent-chat/prompt-resources.ts +688 -0
  124. package/corpus/core/src/server/agent-chat/recurring-jobs-runtime.ts +80 -0
  125. package/corpus/core/src/server/agent-chat/request-surface.ts +71 -0
  126. package/corpus/core/src/server/agent-chat/run-code-tools.ts +67 -0
  127. package/corpus/core/src/server/agent-chat/script-entries.ts +779 -0
  128. package/corpus/core/src/server/agent-chat/shared-thread.ts +301 -0
  129. package/corpus/core/src/server/agent-chat/skill-frontmatter.ts +41 -0
  130. package/corpus/core/src/server/agent-chat-plugin.ts +364 -4182
  131. package/corpus/core/src/server/agent-teams.ts +26 -3
  132. package/corpus/core/src/server/auth.ts +55 -57
  133. package/corpus/core/src/server/credential-provider.ts +22 -25
  134. package/corpus/core/src/server/edge.ts +1 -0
  135. package/corpus/core/src/server/onboarding-html.ts +1 -16
  136. package/corpus/core/src/server/realtime-voice.ts +40 -5
  137. package/corpus/core/src/server/request-origin.ts +6 -2
  138. package/corpus/core/src/server/ssr-handler.ts +55 -2
  139. package/corpus/core/src/sharing/access.ts +155 -11
  140. package/corpus/core/src/sharing/registry.ts +7 -0
  141. package/corpus/core/src/styles/agent-native.css +15 -14
  142. package/corpus/core/src/templates/default/.agents/skills/frontend-design/SKILL.md +1 -1
  143. package/corpus/core/src/templates/default/app/i18n/ar-SA.ts +6 -0
  144. package/corpus/core/src/templates/default/app/i18n/de-DE.ts +6 -0
  145. package/corpus/core/src/templates/default/app/i18n/en-US.ts +6 -0
  146. package/corpus/core/src/templates/default/app/i18n/es-ES.ts +6 -0
  147. package/corpus/core/src/templates/default/app/i18n/fr-FR.ts +6 -0
  148. package/corpus/core/src/templates/default/app/i18n/hi-IN.ts +6 -0
  149. package/corpus/core/src/templates/default/app/i18n/ja-JP.ts +6 -0
  150. package/corpus/core/src/templates/default/app/i18n/ko-KR.ts +6 -0
  151. package/corpus/core/src/templates/default/app/i18n/pt-BR.ts +6 -0
  152. package/corpus/core/src/templates/default/app/i18n/zh-CN.ts +6 -0
  153. package/corpus/core/src/templates/default/app/i18n/zh-TW.ts +6 -0
  154. package/corpus/core/src/templates/workspace-core/.agents/skills/authentication/SKILL.md +27 -29
  155. package/corpus/core/src/templates/workspace-core/.agents/skills/external-agents/SKILL.md +2 -1
  156. package/corpus/core/src/templates/workspace-core/.agents/skills/frontend-design/SKILL.md +1 -1
  157. package/corpus/core/src/templates/workspace-core/.agents/skills/observability/SKILL.md +32 -0
  158. package/corpus/core/src/templates/workspace-core/.agents/skills/writing-agent-instructions/SKILL.md +25 -0
  159. package/corpus/core/src/templates/workspace-core/src/server/index.ts +4 -2
  160. package/corpus/core/src/testing.ts +26 -0
  161. package/corpus/core/src/triggers/dispatcher.ts +23 -2
  162. package/corpus/core/src/vite/client.ts +126 -2
  163. package/corpus/core/tsconfig.cli.json +1 -1
  164. package/corpus/core/tsconfig.json +5 -1
  165. package/corpus/templates/analytics/.agents/skills/bigquery/SKILL.md +2 -2
  166. package/corpus/templates/analytics/.agents/skills/frontend-design/SKILL.md +1 -1
  167. package/corpus/templates/analytics/AGENTS.md +19 -6
  168. package/corpus/templates/analytics/actions/install-dashboard-template.ts +79 -43
  169. package/corpus/templates/analytics/actions/list-explorer-dashboards.ts +3 -3
  170. package/corpus/templates/analytics/actions/list-sql-dashboards.ts +8 -3
  171. package/corpus/templates/analytics/actions/rename-analysis.ts +8 -2
  172. package/corpus/templates/analytics/actions/rename-dashboard.ts +8 -7
  173. package/corpus/templates/analytics/actions/view-screen.ts +4 -23
  174. package/corpus/templates/analytics/app/components/ResourceLoadError.tsx +42 -0
  175. package/corpus/templates/analytics/app/components/layout/CommandPalette.tsx +85 -70
  176. package/corpus/templates/analytics/app/components/layout/Sidebar.tsx +107 -89
  177. package/corpus/templates/analytics/app/components/layout/SidebarLoadError.tsx +24 -0
  178. package/corpus/templates/analytics/app/hooks/use-dashboard-views.ts +15 -5
  179. package/corpus/templates/analytics/app/i18n/zh-TW.ts +4 -0
  180. package/corpus/templates/analytics/app/i18n-data.ts +40 -0
  181. package/corpus/templates/analytics/app/pages/Settings.tsx +6 -2
  182. package/corpus/templates/analytics/app/pages/adhoc/explorer/components/SqlPreview.tsx +36 -20
  183. package/corpus/templates/analytics/app/pages/adhoc/explorer/index.tsx +34 -20
  184. package/corpus/templates/analytics/app/pages/adhoc/explorer/use-explorer-config.ts +42 -41
  185. package/corpus/templates/analytics/app/pages/adhoc/explorer-dashboard/index.tsx +43 -36
  186. package/corpus/templates/analytics/app/pages/adhoc/sql-dashboard/ViewsMenu.tsx +11 -2
  187. package/corpus/templates/analytics/app/root.tsx +13 -1
  188. package/corpus/templates/analytics/app/routes/_index.tsx +14 -2
  189. package/corpus/templates/analytics/changelog/2026-07-03-agent-llm-observability-dashboard.md +1 -1
  190. package/corpus/templates/analytics/changelog/2026-07-11-agent-feedback-sentiment-dashboard.md +6 -0
  191. package/corpus/templates/analytics/changelog/2026-07-11-analytics-chats-now-start-faster-by-loading-metric-definitio.md +6 -0
  192. package/corpus/templates/analytics/changelog/2026-07-11-command-and-sql-previews-now-respond-without-lag.md +6 -0
  193. package/corpus/templates/analytics/changelog/2026-07-11-command-search-now-reports-loading-failures-and-lets-you-ret.md +6 -0
  194. package/corpus/templates/analytics/changelog/2026-07-11-dashboard-navigation-now-loads-faster-and-reports-request-fa.md +6 -0
  195. package/corpus/templates/analytics/changelog/2026-07-11-inferred-message-sentiment-dashboard.md +6 -0
  196. package/corpus/templates/analytics/changelog/2026-07-11-microphone-settings-from-realtime-voice-mode-now-open-the-vo.md +6 -0
  197. package/corpus/templates/analytics/changelog/2026-07-11-more-dashboard-edit-paths-are-now-safe-against-simultaneous-.md +6 -0
  198. package/corpus/templates/analytics/changelog/2026-07-11-renaming-a-dashboard-is-now-safe-against-simultaneous-agent-.md +6 -0
  199. package/corpus/templates/analytics/changelog/2026-07-11-renaming-an-analysis-is-now-safe-against-simultaneous-edits.md +6 -0
  200. package/corpus/templates/analytics/changelog/2026-07-11-workspace-mounted-analytics-now-opens-ask-reliably-and-route.md +6 -0
  201. package/corpus/templates/analytics/docs/schemas/first-party-analytics.md +37 -3
  202. package/corpus/templates/analytics/seeds/dashboards/agent-native-templates-first-party.json +339 -1
  203. package/corpus/templates/analytics/server/lib/dashboard-catalog.ts +1 -24
  204. package/corpus/templates/analytics/server/lib/dashboard-seeds.ts +0 -5
  205. package/corpus/templates/analytics/server/lib/dashboards-store.ts +289 -20
  206. package/corpus/templates/analytics/server/lib/data-dictionary-context.ts +106 -34
  207. package/corpus/templates/analytics/server/lib/demo-dashboards.ts +4 -1
  208. package/corpus/templates/analytics/server/plugins/agent-chat.ts +11 -39
  209. package/corpus/templates/assets/.agents/skills/frontend-design/SKILL.md +1 -1
  210. package/corpus/templates/assets/app/components/create/RecentDraftsSection.tsx +30 -4
  211. package/corpus/templates/assets/app/routes/library.tsx +49 -5
  212. package/corpus/templates/assets/changelog/2026-07-11-library-load-failures-now-show-a-retry-action.md +6 -0
  213. package/corpus/templates/brain/.agents/skills/frontend-design/SKILL.md +1 -1
  214. package/corpus/templates/calendar/.agents/skills/frontend-design/SKILL.md +1 -1
  215. package/corpus/templates/calendar/.env.example +5 -0
  216. package/corpus/templates/calendar/app/components/calendar/EventCard.tsx +2 -2
  217. package/corpus/templates/calendar/app/i18n/zh-TW.ts +2 -0
  218. package/corpus/templates/calendar/app/i18n-data.ts +20 -0
  219. package/corpus/templates/calendar/app/pages/BookingLinksPage.tsx +37 -1
  220. package/corpus/templates/calendar/app/pages/BookingsList.tsx +20 -3
  221. package/corpus/templates/calendar/changelog/2026-07-11-booking-load-failures-now-show-a-retry-action.md +6 -0
  222. package/corpus/templates/calendar/changelog/2026-07-11-event-cards-give-subtle-press-feedback-and-smoother-hover.md +6 -0
  223. package/corpus/templates/chat/.agents/skills/frontend-design/SKILL.md +1 -1
  224. package/corpus/templates/clips/.agents/skills/frontend-design/SKILL.md +1 -1
  225. package/corpus/templates/clips/actions/decline-invite.ts +8 -0
  226. package/corpus/templates/clips/app/components/library/folder-tree.tsx +209 -187
  227. package/corpus/templates/clips/app/components/meetings/meeting-card.tsx +2 -2
  228. package/corpus/templates/clips/app/components/player/reactions-tray.tsx +17 -5
  229. package/corpus/templates/clips/app/components/player/scrubber.tsx +5 -3
  230. package/corpus/templates/clips/app/components/recorder/pre-record-panel.tsx +2 -2
  231. package/corpus/templates/clips/app/components/workspace/insights-hub.tsx +119 -95
  232. package/corpus/templates/clips/app/global.css +45 -0
  233. package/corpus/templates/clips/app/root.tsx +4 -0
  234. package/corpus/templates/clips/app/routes/_app.notifications.tsx +23 -2
  235. package/corpus/templates/clips/app/routes/_app.trash.tsx +24 -2
  236. package/corpus/templates/clips/changelog/2026-07-11-controls-and-folders-now-move-more-smoothly.md +6 -0
  237. package/corpus/templates/clips/changelog/2026-07-11-declining-an-invitation-now-requires-being-its-recipient.md +6 -0
  238. package/corpus/templates/clips/changelog/2026-07-11-recording-overlays-are-lighter-weight-and-no-longer-cause-pa.md +6 -0
  239. package/corpus/templates/clips/changelog/2026-07-11-workspace-load-failures-now-show-a-retry-action.md +6 -0
  240. package/corpus/templates/clips/chrome-extension/src/overlay.css +34 -5
  241. package/corpus/templates/clips/chrome-extension/src/styles.css +2 -2
  242. package/corpus/templates/clips/desktop/src/styles.css +71 -26
  243. package/corpus/templates/content/.agents/skills/frontend-design/SKILL.md +1 -1
  244. package/corpus/templates/content/actions/move-document.ts +34 -18
  245. package/corpus/templates/content/app/components/QueryErrorState.tsx +39 -0
  246. package/corpus/templates/content/app/components/editor/LinkHoverPreview.tsx +1 -1
  247. package/corpus/templates/content/app/components/editor/database/DatabaseView.tsx +225 -1435
  248. package/corpus/templates/content/app/components/editor/database/GalleryView.tsx +368 -0
  249. package/corpus/templates/content/app/components/editor/database/ListView.tsx +353 -0
  250. package/corpus/templates/content/app/components/editor/database/TimelineView.tsx +580 -0
  251. package/corpus/templates/content/app/components/sidebar/DocumentSidebar.tsx +11 -2
  252. package/corpus/templates/content/app/global.css +19 -19
  253. package/corpus/templates/content/app/root.tsx +2 -2
  254. package/corpus/templates/content/app/routes/_app._index.tsx +11 -1
  255. package/corpus/templates/content/changelog/2026-07-11-document-load-failures-now-show-a-retry-action.md +6 -0
  256. package/corpus/templates/content/changelog/2026-07-11-editor-toggle-feedback-now-feels-more-responsive.md +6 -0
  257. package/corpus/templates/content/changelog/2026-07-11-moving-documents-at-the-same-time-no-longer-scrambles-their-.md +6 -0
  258. package/corpus/templates/content/changelog/2026-07-11-public-document-chats-now-start-faster-while-keeping-full-do.md +6 -0
  259. package/corpus/templates/content/changelog/2026-07-11-reopening-a-comment-now-uses-consistent-permissions-everywhe.md +6 -0
  260. package/corpus/templates/content/changelog/2026-07-11-sidebar-resizing-now-tracks-your-cursor-instantly-instead-of.md +6 -0
  261. package/corpus/templates/content/server/lib/public-documents.ts +47 -10
  262. package/corpus/templates/content/server/routes/api/comments/[id].patch.ts +24 -24
  263. package/corpus/templates/design/.agents/skills/frontend-design/SKILL.md +1 -1
  264. package/corpus/templates/design/app/components/QueryErrorState.tsx +24 -0
  265. package/corpus/templates/design/app/components/design/CanvasContextMenu.tsx +1 -1
  266. package/corpus/templates/design/app/components/design/DesignImportPanel.tsx +5 -2
  267. package/corpus/templates/design/app/components/design/EditPanel.tsx +326 -319
  268. package/corpus/templates/design/app/components/design/LayersPanel.tsx +198 -193
  269. package/corpus/templates/design/app/components/design/edit-panel/panel-primitives.tsx +11 -4
  270. package/corpus/templates/design/app/components/design/inspector/DesignColorPicker.tsx +1 -1
  271. package/corpus/templates/design/app/components/layout/Layout.tsx +1 -1
  272. package/corpus/templates/design/app/pages/DesignSystems.tsx +7 -1
  273. package/corpus/templates/design/app/pages/Index.tsx +14 -2
  274. package/corpus/templates/design/app/pages/Present.tsx +16 -3
  275. package/corpus/templates/design/app/pages/Templates.tsx +10 -4
  276. package/corpus/templates/design/app/pages/design-editor/canvas-primitive-insert.ts +484 -0
  277. package/corpus/templates/design/app/pages/design-editor/clone-and-pen-edit.ts +378 -0
  278. package/corpus/templates/design/app/pages/design-editor/design-data-geometry-utils.ts +138 -0
  279. package/corpus/templates/design/app/pages/design-editor/dom-utils.ts +15 -0
  280. package/corpus/templates/design/app/pages/design-editor/generation-prompt-directives.ts +180 -0
  281. package/corpus/templates/design/app/pages/design-editor/html-layer-positioning.ts +226 -0
  282. package/corpus/templates/design/app/pages/design-editor/png-export-render.ts +348 -0
  283. package/corpus/templates/design/app/pages/design-editor/screen-command-utils.ts +160 -0
  284. package/corpus/templates/design/app/pages/design-editor/text-edit-utils.ts +238 -0
  285. package/corpus/templates/design/app/pages/design-editor/tool-state.ts +23 -1
  286. package/corpus/templates/design/app/pages/design-editor/types.ts +25 -0
  287. package/corpus/templates/design/app/root.tsx +10 -1
  288. package/corpus/templates/design/changelog/2026-07-11-canvas-context-menus-now-open-without-motion-jitter.md +6 -0
  289. package/corpus/templates/design/changelog/2026-07-11-design-load-failures-now-show-a-retry-action.md +6 -0
  290. package/corpus/templates/design/changelog/2026-07-11-inspector-tooltips-appear-instantly-as-you-sweep-across-icon.md +6 -0
  291. package/corpus/templates/dispatch/.agents/skills/frontend-design/SKILL.md +1 -1
  292. package/corpus/templates/dispatch/app/i18n/zh-TW.ts +10 -0
  293. package/corpus/templates/dispatch/app/i18n-data.ts +123 -0
  294. package/corpus/templates/dispatch/app/routes/integrations.tsx +163 -144
  295. package/corpus/templates/dispatch/changelog/2026-07-11-dispatch-mcp-connections-now-start-with-safer-app-access-and.md +6 -0
  296. package/corpus/templates/dispatch/changelog/2026-07-11-overview-and-chat-now-share-a-cleaner-more-stable-flow.md +6 -0
  297. package/corpus/templates/dispatch/changelog/2026-07-11-query-errors-now-show-a-retry-option.md +6 -0
  298. package/corpus/templates/forms/.agents/skills/frontend-design/SKILL.md +1 -1
  299. package/corpus/templates/forms/app/components/layout/Sidebar.tsx +3 -3
  300. package/corpus/templates/forms/app/root.tsx +34 -8
  301. package/corpus/templates/macros/.agents/skills/frontend-design/SKILL.md +1 -1
  302. package/corpus/templates/macros/app/components/DailyProgress.tsx +25 -5
  303. package/corpus/templates/macros/app/components/QueryErrorState.tsx +31 -0
  304. package/corpus/templates/macros/app/components/WeightTracker.tsx +5 -1
  305. package/corpus/templates/macros/app/components/ui/button.tsx +1 -1
  306. package/corpus/templates/macros/app/components/ui/progress.tsx +1 -1
  307. package/corpus/templates/macros/app/components/ui/tabs.tsx +1 -1
  308. package/corpus/templates/macros/app/i18n/ar-SA.ts +2 -0
  309. package/corpus/templates/macros/app/i18n/de-DE.ts +2 -0
  310. package/corpus/templates/macros/app/i18n/en-US.ts +2 -0
  311. package/corpus/templates/macros/app/i18n/es-ES.ts +2 -0
  312. package/corpus/templates/macros/app/i18n/fr-FR.ts +2 -0
  313. package/corpus/templates/macros/app/i18n/hi-IN.ts +2 -0
  314. package/corpus/templates/macros/app/i18n/ja-JP.ts +2 -0
  315. package/corpus/templates/macros/app/i18n/ko-KR.ts +2 -0
  316. package/corpus/templates/macros/app/i18n/pt-BR.ts +2 -0
  317. package/corpus/templates/macros/app/i18n/zh-CN.ts +2 -0
  318. package/corpus/templates/macros/app/i18n/zh-TW.ts +2 -0
  319. package/corpus/templates/macros/app/routes/_index.tsx +22 -12
  320. package/corpus/templates/macros/app/routes/analytics.tsx +31 -10
  321. package/corpus/templates/macros/changelog/2026-07-11-daily-tracking-now-loads-and-updates-more-quickly.md +6 -0
  322. package/corpus/templates/macros/changelog/2026-07-11-data-load-failures-now-show-a-clear-error-with-a-retry-actio.md +6 -0
  323. package/corpus/templates/mail/.agents/skills/frontend-design/SKILL.md +1 -1
  324. package/corpus/templates/mail/.env.example +16 -11
  325. package/corpus/templates/mail/actions/list-emails.ts +39 -35
  326. package/corpus/templates/mail/app/components/email/ComposeModal.tsx +58 -6
  327. package/corpus/templates/mail/app/components/email/EmailListItem.tsx +35 -2
  328. package/corpus/templates/mail/app/components/layout/AppLayout.tsx +113 -104
  329. package/corpus/templates/mail/app/root.tsx +8 -10
  330. package/corpus/templates/mail/changelog/2026-07-11-compose-and-navigation-motion-now-feel-faster-and-smoother.md +6 -0
  331. package/corpus/templates/mail/changelog/2026-07-11-swipe-to-archive-or-snooze-now-responds-to-quick-flicks-not-.md +6 -0
  332. package/corpus/templates/mail/changelog/2026-07-11-the-assistant-now-sees-the-same-inbox-you-do-snoozed-mail-st.md +6 -0
  333. package/corpus/templates/mail/server/handlers/emails.ts +25 -69
  334. package/corpus/templates/mail/server/lib/list-inbox-emails.ts +169 -0
  335. package/corpus/templates/plan/.agents/skills/frontend-design/SKILL.md +1 -1
  336. package/corpus/templates/plan/.env.example +4 -0
  337. package/corpus/templates/plan/actions/create-plan-design.ts +89 -81
  338. package/corpus/templates/plan/actions/create-prototype-plan.ts +72 -59
  339. package/corpus/templates/plan/actions/create-ui-plan.ts +70 -55
  340. package/corpus/templates/plan/actions/create-visual-plan.ts +65 -51
  341. package/corpus/templates/plan/actions/update-local-plan-folder.ts +43 -30
  342. package/corpus/templates/plan/actions/update-visual-plan.ts +81 -64
  343. package/corpus/templates/plan/app/components/layout/Sidebar.tsx +17 -0
  344. package/corpus/templates/plan/app/components/ui/tabs.tsx +1 -1
  345. package/corpus/templates/plan/app/i18n/ar-SA.ts +10 -0
  346. package/corpus/templates/plan/app/i18n/de-DE.ts +10 -0
  347. package/corpus/templates/plan/app/i18n/en-US.ts +10 -0
  348. package/corpus/templates/plan/app/i18n/es-ES.ts +10 -0
  349. package/corpus/templates/plan/app/i18n/fr-FR.ts +10 -0
  350. package/corpus/templates/plan/app/i18n/hi-IN.ts +10 -0
  351. package/corpus/templates/plan/app/i18n/ja-JP.ts +10 -0
  352. package/corpus/templates/plan/app/i18n/ko-KR.ts +10 -0
  353. package/corpus/templates/plan/app/i18n/pt-BR.ts +10 -0
  354. package/corpus/templates/plan/app/i18n/zh-CN.ts +10 -0
  355. package/corpus/templates/plan/app/i18n/zh-TW.ts +10 -0
  356. package/corpus/templates/plan/app/lib/plan-local-bridge.ts +80 -1
  357. package/corpus/templates/plan/app/pages/PlansPage.tsx +152 -4
  358. package/corpus/templates/plan/app/root.tsx +11 -0
  359. package/corpus/templates/plan/changelog/2026-07-11-local-plans-now-explain-and-recover-from-browser-permission-.md +6 -0
  360. package/corpus/templates/plan/changelog/2026-07-11-plan-edits-now-save-atomically-and-can-no-longer-partially-a.md +6 -0
  361. package/corpus/templates/plan/changelog/2026-07-11-plan-lists-now-show-a-clear-error-with-a-retry-action-when-t.md +6 -0
  362. package/corpus/templates/plan/shared/plan-content.ts +546 -260
  363. package/corpus/templates/slides/.agents/skills/frontend-design/SKILL.md +1 -1
  364. package/corpus/templates/slides/actions/delete-slide-comment.ts +49 -0
  365. package/corpus/templates/slides/actions/update-slide-comment.ts +93 -0
  366. package/corpus/templates/slides/actions/view-screen.ts +14 -6
  367. package/corpus/templates/slides/app/components/comments/SlideCommentsPanel.tsx +33 -10
  368. package/corpus/templates/slides/app/components/editor/EditorSidebar.tsx +1 -1
  369. package/corpus/templates/slides/app/components/editor/EditorToolbar.tsx +1 -1
  370. package/corpus/templates/slides/app/components/editor/GenerateSlidesDialog.tsx +2 -2
  371. package/corpus/templates/slides/app/components/presentation/PresentationView.tsx +4 -2
  372. package/corpus/templates/slides/app/components/visual-editor/CanvasCommentPins.tsx +4 -3
  373. package/corpus/templates/slides/app/context/DeckContext.tsx +9 -0
  374. package/corpus/templates/slides/app/i18n/ar-SA.ts +6 -0
  375. package/corpus/templates/slides/app/i18n/de-DE.ts +6 -0
  376. package/corpus/templates/slides/app/i18n/en-US.ts +6 -0
  377. package/corpus/templates/slides/app/i18n/es-ES.ts +6 -0
  378. package/corpus/templates/slides/app/i18n/fr-FR.ts +6 -0
  379. package/corpus/templates/slides/app/i18n/hi-IN.ts +6 -0
  380. package/corpus/templates/slides/app/i18n/ja-JP.ts +6 -0
  381. package/corpus/templates/slides/app/i18n/ko-KR.ts +6 -0
  382. package/corpus/templates/slides/app/i18n/pt-BR.ts +6 -0
  383. package/corpus/templates/slides/app/i18n/zh-CN.ts +5 -0
  384. package/corpus/templates/slides/app/i18n/zh-TW.ts +5 -0
  385. package/corpus/templates/slides/app/pages/DesignSystems.tsx +23 -2
  386. package/corpus/templates/slides/app/pages/Index.tsx +29 -1
  387. package/corpus/templates/slides/changelog/2026-07-11-comment-load-failures-now-show-a-retry-action-instead-of-say.md +6 -0
  388. package/corpus/templates/slides/changelog/2026-07-11-comment-pins-now-clear-with-a-faster-smoother-confirmation.md +6 -0
  389. package/corpus/templates/slides/changelog/2026-07-11-deck-and-design-system-load-failures-now-show-a-retry-action.md +6 -0
  390. package/corpus/templates/slides/changelog/2026-07-11-editor-toggles-and-toolbar-menus-now-animate-smoothly.md +6 -0
  391. package/corpus/templates/slides/changelog/2026-07-11-the-assistant-can-now-resolve-reopen-and-delete-slide-commen.md +6 -0
  392. package/corpus/templates/slides/changelog/2026-07-11-viewing-slides-no-longer-loads-every-deck-s-full-contents-in.md +6 -0
  393. package/corpus/templates/slides/server/routes/api/comments/[id].delete.ts +29 -48
  394. package/corpus/templates/slides/server/routes/api/comments/[id].patch.ts +29 -65
  395. package/dist/action.d.ts +23 -0
  396. package/dist/action.d.ts.map +1 -1
  397. package/dist/action.js +13 -0
  398. package/dist/action.js.map +1 -1
  399. package/dist/agent/engine/builder-engine.d.ts.map +1 -1
  400. package/dist/agent/engine/builder-engine.js +3 -0
  401. package/dist/agent/engine/builder-engine.js.map +1 -1
  402. package/dist/agent/engine/context-directives-transform.d.ts +25 -0
  403. package/dist/agent/engine/context-directives-transform.d.ts.map +1 -0
  404. package/dist/agent/engine/context-directives-transform.js +53 -0
  405. package/dist/agent/engine/context-directives-transform.js.map +1 -0
  406. package/dist/agent/engine/continuation-dispatch-retry.d.ts +40 -0
  407. package/dist/agent/engine/continuation-dispatch-retry.d.ts.map +1 -0
  408. package/dist/agent/engine/continuation-dispatch-retry.js +109 -0
  409. package/dist/agent/engine/continuation-dispatch-retry.js.map +1 -0
  410. package/dist/agent/engine/tool-call-journal-seed.d.ts +46 -0
  411. package/dist/agent/engine/tool-call-journal-seed.d.ts.map +1 -0
  412. package/dist/agent/engine/tool-call-journal-seed.js +60 -0
  413. package/dist/agent/engine/tool-call-journal-seed.js.map +1 -0
  414. package/dist/agent/production-agent.d.ts +7 -0
  415. package/dist/agent/production-agent.d.ts.map +1 -1
  416. package/dist/agent/production-agent.js +102 -222
  417. package/dist/agent/production-agent.js.map +1 -1
  418. package/dist/cli/doctor.d.ts.map +1 -1
  419. package/dist/cli/doctor.js +7 -3
  420. package/dist/cli/doctor.js.map +1 -1
  421. package/dist/cli/plan-local.d.ts.map +1 -1
  422. package/dist/cli/plan-local.js +8 -2
  423. package/dist/cli/plan-local.js.map +1 -1
  424. package/dist/cli/skills-content/assets-skill.d.ts +2 -0
  425. package/dist/cli/skills-content/assets-skill.d.ts.map +1 -0
  426. package/dist/cli/skills-content/assets-skill.js +84 -0
  427. package/dist/cli/skills-content/assets-skill.js.map +1 -0
  428. package/dist/cli/skills-content/canvas.d.ts +4 -0
  429. package/dist/cli/skills-content/canvas.d.ts.map +1 -0
  430. package/dist/cli/skills-content/canvas.js +152 -0
  431. package/dist/cli/skills-content/canvas.js.map +1 -0
  432. package/dist/cli/skills-content/connection.d.ts +2 -0
  433. package/dist/cli/skills-content/connection.d.ts.map +1 -0
  434. package/dist/cli/skills-content/connection.js +53 -0
  435. package/dist/cli/skills-content/connection.js.map +1 -0
  436. package/dist/cli/skills-content/content-skill.d.ts +2 -0
  437. package/dist/cli/skills-content/content-skill.d.ts.map +1 -0
  438. package/dist/cli/skills-content/content-skill.js +110 -0
  439. package/dist/cli/skills-content/content-skill.js.map +1 -0
  440. package/dist/cli/skills-content/design-exploration-skill.d.ts +2 -0
  441. package/dist/cli/skills-content/design-exploration-skill.d.ts.map +1 -0
  442. package/dist/cli/skills-content/design-exploration-skill.js +119 -0
  443. package/dist/cli/skills-content/design-exploration-skill.js.map +1 -0
  444. package/dist/cli/skills-content/design-visual-edit-skill.d.ts +2 -0
  445. package/dist/cli/skills-content/design-visual-edit-skill.d.ts.map +1 -0
  446. package/dist/cli/skills-content/design-visual-edit-skill.js +229 -0
  447. package/dist/cli/skills-content/design-visual-edit-skill.js.map +1 -0
  448. package/dist/cli/skills-content/document-quality.d.ts +4 -0
  449. package/dist/cli/skills-content/document-quality.d.ts.map +1 -0
  450. package/dist/cli/skills-content/document-quality.js +195 -0
  451. package/dist/cli/skills-content/document-quality.js.map +1 -0
  452. package/dist/cli/skills-content/exemplar.d.ts +4 -0
  453. package/dist/cli/skills-content/exemplar.d.ts.map +1 -0
  454. package/dist/cli/skills-content/exemplar.js +68 -0
  455. package/dist/cli/skills-content/exemplar.js.map +1 -0
  456. package/dist/cli/skills-content/help.d.ts +2 -0
  457. package/dist/cli/skills-content/help.d.ts.map +1 -0
  458. package/dist/cli/skills-content/help.js +78 -0
  459. package/dist/cli/skills-content/help.js.map +1 -0
  460. package/dist/cli/skills-content/index.d.ts +23 -0
  461. package/dist/cli/skills-content/index.d.ts.map +1 -0
  462. package/dist/cli/skills-content/index.js +23 -0
  463. package/dist/cli/skills-content/index.js.map +1 -0
  464. package/dist/cli/skills-content/local-files.d.ts +2 -0
  465. package/dist/cli/skills-content/local-files.d.ts.map +1 -0
  466. package/dist/cli/skills-content/local-files.js +96 -0
  467. package/dist/cli/skills-content/local-files.js.map +1 -0
  468. package/dist/cli/skills-content/plan-setup-auth.d.ts +9 -0
  469. package/dist/cli/skills-content/plan-setup-auth.d.ts.map +1 -0
  470. package/dist/cli/skills-content/plan-setup-auth.js +81 -0
  471. package/dist/cli/skills-content/plan-setup-auth.js.map +1 -0
  472. package/dist/cli/skills-content/visual-plan-skill.d.ts +2 -0
  473. package/dist/cli/skills-content/visual-plan-skill.d.ts.map +1 -0
  474. package/dist/cli/skills-content/visual-plan-skill.js +471 -0
  475. package/dist/cli/skills-content/visual-plan-skill.js.map +1 -0
  476. package/dist/cli/skills-content/visual-recap-skill.d.ts +2 -0
  477. package/dist/cli/skills-content/visual-recap-skill.d.ts.map +1 -0
  478. package/dist/cli/skills-content/visual-recap-skill.js +548 -0
  479. package/dist/cli/skills-content/visual-recap-skill.js.map +1 -0
  480. package/dist/cli/skills-content/visualize-repo-skill.d.ts +2 -0
  481. package/dist/cli/skills-content/visualize-repo-skill.d.ts.map +1 -0
  482. package/dist/cli/skills-content/visualize-repo-skill.js +94 -0
  483. package/dist/cli/skills-content/visualize-repo-skill.js.map +1 -0
  484. package/dist/cli/skills-content/wireframe.d.ts +4 -0
  485. package/dist/cli/skills-content/wireframe.d.ts.map +1 -0
  486. package/dist/cli/skills-content/wireframe.js +347 -0
  487. package/dist/cli/skills-content/wireframe.js.map +1 -0
  488. package/dist/cli/skills.d.ts +2 -10
  489. package/dist/cli/skills.d.ts.map +1 -1
  490. package/dist/cli/skills.js +2 -2710
  491. package/dist/cli/skills.js.map +1 -1
  492. package/dist/client/AgentPanel.d.ts.map +1 -1
  493. package/dist/client/AgentPanel.js +4 -2
  494. package/dist/client/AgentPanel.js.map +1 -1
  495. package/dist/client/CommandMenu.d.ts.map +1 -1
  496. package/dist/client/CommandMenu.js +15 -3
  497. package/dist/client/CommandMenu.js.map +1 -1
  498. package/dist/client/FeedbackButton.js +2 -2
  499. package/dist/client/FeedbackButton.js.map +1 -1
  500. package/dist/client/app-providers.d.ts +13 -5
  501. package/dist/client/app-providers.d.ts.map +1 -1
  502. package/dist/client/app-providers.js +9 -6
  503. package/dist/client/app-providers.js.map +1 -1
  504. package/dist/client/chat/tool-call-display.d.ts +4 -0
  505. package/dist/client/chat/tool-call-display.d.ts.map +1 -1
  506. package/dist/client/chat/tool-call-display.js +3 -3
  507. package/dist/client/chat/tool-call-display.js.map +1 -1
  508. package/dist/client/composer/PastedTextChip.js +1 -1
  509. package/dist/client/composer/PastedTextChip.js.map +1 -1
  510. package/dist/client/composer/RealtimeVoiceMode.d.ts +3 -1
  511. package/dist/client/composer/RealtimeVoiceMode.d.ts.map +1 -1
  512. package/dist/client/composer/RealtimeVoiceMode.js +35 -14
  513. package/dist/client/composer/RealtimeVoiceMode.js.map +1 -1
  514. package/dist/client/composer/TiptapComposer.js +1 -1
  515. package/dist/client/composer/TiptapComposer.js.map +1 -1
  516. package/dist/client/composer/VoiceButton.d.ts +2 -0
  517. package/dist/client/composer/VoiceButton.d.ts.map +1 -1
  518. package/dist/client/composer/VoiceButton.js +9 -3
  519. package/dist/client/composer/VoiceButton.js.map +1 -1
  520. package/dist/client/composer/useRealtimeVoiceMode.d.ts +5 -0
  521. package/dist/client/composer/useRealtimeVoiceMode.d.ts.map +1 -1
  522. package/dist/client/composer/useRealtimeVoiceMode.js +91 -12
  523. package/dist/client/composer/useRealtimeVoiceMode.js.map +1 -1
  524. package/dist/client/context-xray/ContextXRayPanel.d.ts.map +1 -1
  525. package/dist/client/context-xray/ContextXRayPanel.js +4 -1
  526. package/dist/client/context-xray/ContextXRayPanel.js.map +1 -1
  527. package/dist/client/extensions/ExtensionEditor.d.ts.map +1 -1
  528. package/dist/client/extensions/ExtensionEditor.js +15 -5
  529. package/dist/client/extensions/ExtensionEditor.js.map +1 -1
  530. package/dist/client/extensions/ExtensionQueryErrorState.d.ts +8 -0
  531. package/dist/client/extensions/ExtensionQueryErrorState.d.ts.map +1 -0
  532. package/dist/client/extensions/ExtensionQueryErrorState.js +11 -0
  533. package/dist/client/extensions/ExtensionQueryErrorState.js.map +1 -0
  534. package/dist/client/extensions/ExtensionSlot.d.ts.map +1 -1
  535. package/dist/client/extensions/ExtensionSlot.js +17 -7
  536. package/dist/client/extensions/ExtensionSlot.js.map +1 -1
  537. package/dist/client/extensions/ExtensionViewer.d.ts.map +1 -1
  538. package/dist/client/extensions/ExtensionViewer.js +17 -7
  539. package/dist/client/extensions/ExtensionViewer.js.map +1 -1
  540. package/dist/client/extensions/ExtensionsListPage.d.ts.map +1 -1
  541. package/dist/client/extensions/ExtensionsListPage.js +5 -3
  542. package/dist/client/extensions/ExtensionsListPage.js.map +1 -1
  543. package/dist/client/extensions/ExtensionsSidebarSection.d.ts.map +1 -1
  544. package/dist/client/extensions/ExtensionsSidebarSection.js +21 -8
  545. package/dist/client/extensions/ExtensionsSidebarSection.js.map +1 -1
  546. package/dist/client/index.d.ts +0 -2
  547. package/dist/client/index.d.ts.map +1 -1
  548. package/dist/client/index.js +0 -5
  549. package/dist/client/index.js.map +1 -1
  550. package/dist/client/progress/RunsTray.d.ts.map +1 -1
  551. package/dist/client/progress/RunsTray.js +7 -3
  552. package/dist/client/progress/RunsTray.js.map +1 -1
  553. package/dist/client/settings/SettingsTabsPage.d.ts.map +1 -1
  554. package/dist/client/settings/SettingsTabsPage.js +4 -0
  555. package/dist/client/settings/SettingsTabsPage.js.map +1 -1
  556. package/dist/client/settings/useBuilderStatus.d.ts +2 -0
  557. package/dist/client/settings/useBuilderStatus.d.ts.map +1 -1
  558. package/dist/client/settings/useBuilderStatus.js +4 -0
  559. package/dist/client/settings/useBuilderStatus.js.map +1 -1
  560. package/dist/client/tool-cells/EditCell.d.ts.map +1 -1
  561. package/dist/client/tool-cells/EditCell.js +2 -1
  562. package/dist/client/tool-cells/EditCell.js.map +1 -1
  563. package/dist/client/tool-cells/FilesChangedSummary.d.ts.map +1 -1
  564. package/dist/client/tool-cells/FilesChangedSummary.js +2 -1
  565. package/dist/client/tool-cells/FilesChangedSummary.js.map +1 -1
  566. package/dist/client/tool-cells/WriteCell.d.ts.map +1 -1
  567. package/dist/client/tool-cells/WriteCell.js +2 -1
  568. package/dist/client/tool-cells/WriteCell.js.map +1 -1
  569. package/dist/client/visual-style-controls.js +1 -1
  570. package/dist/client/visual-style-controls.js.map +1 -1
  571. package/dist/collab/routes.d.ts +1 -1
  572. package/dist/deploy/build.d.ts.map +1 -1
  573. package/dist/deploy/build.js +36 -14
  574. package/dist/deploy/build.js.map +1 -1
  575. package/dist/integrations/google-docs-poller.d.ts +7 -0
  576. package/dist/integrations/google-docs-poller.d.ts.map +1 -1
  577. package/dist/integrations/google-docs-poller.js +13 -3
  578. package/dist/integrations/google-docs-poller.js.map +1 -1
  579. package/dist/integrations/plugin.d.ts.map +1 -1
  580. package/dist/integrations/plugin.js +10 -0
  581. package/dist/integrations/plugin.js.map +1 -1
  582. package/dist/integrations/webhook-handler.d.ts +11 -0
  583. package/dist/integrations/webhook-handler.d.ts.map +1 -1
  584. package/dist/integrations/webhook-handler.js +16 -4
  585. package/dist/integrations/webhook-handler.js.map +1 -1
  586. package/dist/jobs/scheduler.d.ts +12 -0
  587. package/dist/jobs/scheduler.d.ts.map +1 -1
  588. package/dist/jobs/scheduler.js +13 -3
  589. package/dist/jobs/scheduler.js.map +1 -1
  590. package/dist/localization/default-messages.d.ts +7 -0
  591. package/dist/localization/default-messages.d.ts.map +1 -1
  592. package/dist/localization/default-messages.js +8 -1
  593. package/dist/localization/default-messages.js.map +1 -1
  594. package/dist/mcp/oauth-token.d.ts +1 -1
  595. package/dist/mcp/oauth-token.d.ts.map +1 -1
  596. package/dist/mcp/oauth-token.js +6 -1
  597. package/dist/mcp/oauth-token.js.map +1 -1
  598. package/dist/notifications/routes.d.ts +2 -2
  599. package/dist/observability/routes.d.ts.map +1 -1
  600. package/dist/observability/routes.js +32 -0
  601. package/dist/observability/routes.js.map +1 -1
  602. package/dist/observability/sentiment.d.ts +42 -0
  603. package/dist/observability/sentiment.d.ts.map +1 -0
  604. package/dist/observability/sentiment.js +196 -0
  605. package/dist/observability/sentiment.js.map +1 -0
  606. package/dist/observability/store.d.ts +5 -0
  607. package/dist/observability/store.d.ts.map +1 -1
  608. package/dist/observability/store.js +17 -0
  609. package/dist/observability/store.js.map +1 -1
  610. package/dist/observability/traces.d.ts +2 -0
  611. package/dist/observability/traces.d.ts.map +1 -1
  612. package/dist/observability/traces.js +42 -57
  613. package/dist/observability/traces.js.map +1 -1
  614. package/dist/observability/tracking-identity.d.ts +3 -0
  615. package/dist/observability/tracking-identity.d.ts.map +1 -0
  616. package/dist/observability/tracking-identity.js +51 -0
  617. package/dist/observability/tracking-identity.js.map +1 -0
  618. package/dist/observability/types.d.ts +10 -0
  619. package/dist/observability/types.d.ts.map +1 -1
  620. package/dist/observability/types.js +3 -0
  621. package/dist/observability/types.js.map +1 -1
  622. package/dist/progress/routes.d.ts +1 -1
  623. package/dist/provider-api/corpus-jobs.d.ts +2 -2
  624. package/dist/resources/handlers.d.ts +1 -1
  625. package/dist/secrets/storage.d.ts +6 -0
  626. package/dist/secrets/storage.d.ts.map +1 -1
  627. package/dist/secrets/storage.js +61 -3
  628. package/dist/secrets/storage.js.map +1 -1
  629. package/dist/server/agent-chat/action-filters-a2a.d.ts +50 -0
  630. package/dist/server/agent-chat/action-filters-a2a.d.ts.map +1 -0
  631. package/dist/server/agent-chat/action-filters-a2a.js +127 -0
  632. package/dist/server/agent-chat/action-filters-a2a.js.map +1 -0
  633. package/dist/server/agent-chat/browser-team-tools.d.ts +21 -0
  634. package/dist/server/agent-chat/browser-team-tools.d.ts.map +1 -0
  635. package/dist/server/agent-chat/browser-team-tools.js +417 -0
  636. package/dist/server/agent-chat/browser-team-tools.js.map +1 -0
  637. package/dist/server/agent-chat/context-tools.d.ts +33 -0
  638. package/dist/server/agent-chat/context-tools.d.ts.map +1 -0
  639. package/dist/server/agent-chat/context-tools.js +520 -0
  640. package/dist/server/agent-chat/context-tools.js.map +1 -0
  641. package/dist/server/agent-chat/framework-prompts.d.ts +65 -0
  642. package/dist/server/agent-chat/framework-prompts.d.ts.map +1 -0
  643. package/dist/server/agent-chat/framework-prompts.js +403 -0
  644. package/dist/server/agent-chat/framework-prompts.js.map +1 -0
  645. package/dist/server/agent-chat/lazy-fs.d.ts +2 -0
  646. package/dist/server/agent-chat/lazy-fs.d.ts.map +1 -0
  647. package/dist/server/agent-chat/lazy-fs.js +11 -0
  648. package/dist/server/agent-chat/lazy-fs.js.map +1 -0
  649. package/dist/server/agent-chat/mcp-glue.d.ts +9 -0
  650. package/dist/server/agent-chat/mcp-glue.d.ts.map +1 -0
  651. package/dist/server/agent-chat/mcp-glue.js +63 -0
  652. package/dist/server/agent-chat/mcp-glue.js.map +1 -0
  653. package/dist/server/agent-chat/plugin-options.d.ts +322 -0
  654. package/dist/server/agent-chat/plugin-options.d.ts.map +1 -0
  655. package/dist/server/agent-chat/plugin-options.js +2 -0
  656. package/dist/server/agent-chat/plugin-options.js.map +1 -0
  657. package/dist/server/agent-chat/process-run-failure.d.ts +12 -0
  658. package/dist/server/agent-chat/process-run-failure.d.ts.map +1 -0
  659. package/dist/server/agent-chat/process-run-failure.js +24 -0
  660. package/dist/server/agent-chat/process-run-failure.js.map +1 -0
  661. package/dist/server/agent-chat/prompt-resources.d.ts +28 -0
  662. package/dist/server/agent-chat/prompt-resources.d.ts.map +1 -0
  663. package/dist/server/agent-chat/prompt-resources.js +514 -0
  664. package/dist/server/agent-chat/prompt-resources.js.map +1 -0
  665. package/dist/server/agent-chat/recurring-jobs-runtime.d.ts +5 -0
  666. package/dist/server/agent-chat/recurring-jobs-runtime.d.ts.map +1 -0
  667. package/dist/server/agent-chat/recurring-jobs-runtime.js +53 -0
  668. package/dist/server/agent-chat/recurring-jobs-runtime.js.map +1 -0
  669. package/dist/server/agent-chat/request-surface.d.ts +8 -0
  670. package/dist/server/agent-chat/request-surface.d.ts.map +1 -0
  671. package/dist/server/agent-chat/request-surface.js +56 -0
  672. package/dist/server/agent-chat/request-surface.js.map +1 -0
  673. package/dist/server/agent-chat/run-code-tools.d.ts +17 -0
  674. package/dist/server/agent-chat/run-code-tools.d.ts.map +1 -0
  675. package/dist/server/agent-chat/run-code-tools.js +55 -0
  676. package/dist/server/agent-chat/run-code-tools.js.map +1 -0
  677. package/dist/server/agent-chat/script-entries.d.ts +47 -0
  678. package/dist/server/agent-chat/script-entries.d.ts.map +1 -0
  679. package/dist/server/agent-chat/script-entries.js +633 -0
  680. package/dist/server/agent-chat/script-entries.js.map +1 -0
  681. package/dist/server/agent-chat/shared-thread.d.ts +33 -0
  682. package/dist/server/agent-chat/shared-thread.d.ts.map +1 -0
  683. package/dist/server/agent-chat/shared-thread.js +242 -0
  684. package/dist/server/agent-chat/shared-thread.js.map +1 -0
  685. package/dist/server/agent-chat/skill-frontmatter.d.ts +7 -0
  686. package/dist/server/agent-chat/skill-frontmatter.d.ts.map +1 -0
  687. package/dist/server/agent-chat/skill-frontmatter.js +26 -0
  688. package/dist/server/agent-chat/skill-frontmatter.js.map +1 -0
  689. package/dist/server/agent-chat-plugin.d.ts +45 -486
  690. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  691. package/dist/server/agent-chat-plugin.js +173 -3005
  692. package/dist/server/agent-chat-plugin.js.map +1 -1
  693. package/dist/server/agent-engine-api-key-route.d.ts +1 -1
  694. package/dist/server/agent-teams.d.ts +10 -0
  695. package/dist/server/agent-teams.d.ts.map +1 -1
  696. package/dist/server/agent-teams.js +13 -3
  697. package/dist/server/agent-teams.js.map +1 -1
  698. package/dist/server/auth.d.ts.map +1 -1
  699. package/dist/server/auth.js +50 -52
  700. package/dist/server/auth.js.map +1 -1
  701. package/dist/server/credential-provider.d.ts.map +1 -1
  702. package/dist/server/credential-provider.js +22 -21
  703. package/dist/server/credential-provider.js.map +1 -1
  704. package/dist/server/edge.d.ts +1 -0
  705. package/dist/server/edge.d.ts.map +1 -1
  706. package/dist/server/edge.js +1 -0
  707. package/dist/server/edge.js.map +1 -1
  708. package/dist/server/onboarding-html.d.ts.map +1 -1
  709. package/dist/server/onboarding-html.js +1 -16
  710. package/dist/server/onboarding-html.js.map +1 -1
  711. package/dist/server/realtime-voice.d.ts +3 -0
  712. package/dist/server/realtime-voice.d.ts.map +1 -1
  713. package/dist/server/realtime-voice.js +29 -5
  714. package/dist/server/realtime-voice.js.map +1 -1
  715. package/dist/server/request-origin.d.ts.map +1 -1
  716. package/dist/server/request-origin.js +6 -3
  717. package/dist/server/request-origin.js.map +1 -1
  718. package/dist/server/ssr-handler.d.ts.map +1 -1
  719. package/dist/server/ssr-handler.js +47 -2
  720. package/dist/server/ssr-handler.js.map +1 -1
  721. package/dist/sharing/access.d.ts +63 -3
  722. package/dist/sharing/access.d.ts.map +1 -1
  723. package/dist/sharing/access.js +53 -15
  724. package/dist/sharing/access.js.map +1 -1
  725. package/dist/sharing/registry.d.ts +7 -0
  726. package/dist/sharing/registry.d.ts.map +1 -1
  727. package/dist/sharing/registry.js.map +1 -1
  728. package/dist/styles/agent-native.css +15 -14
  729. package/dist/templates/default/.agents/skills/frontend-design/SKILL.md +1 -1
  730. package/dist/templates/default/app/i18n/ar-SA.ts +6 -0
  731. package/dist/templates/default/app/i18n/de-DE.ts +6 -0
  732. package/dist/templates/default/app/i18n/en-US.ts +6 -0
  733. package/dist/templates/default/app/i18n/es-ES.ts +6 -0
  734. package/dist/templates/default/app/i18n/fr-FR.ts +6 -0
  735. package/dist/templates/default/app/i18n/hi-IN.ts +6 -0
  736. package/dist/templates/default/app/i18n/ja-JP.ts +6 -0
  737. package/dist/templates/default/app/i18n/ko-KR.ts +6 -0
  738. package/dist/templates/default/app/i18n/pt-BR.ts +6 -0
  739. package/dist/templates/default/app/i18n/zh-CN.ts +6 -0
  740. package/dist/templates/default/app/i18n/zh-TW.ts +6 -0
  741. package/dist/templates/workspace-core/.agents/skills/authentication/SKILL.md +27 -29
  742. package/dist/templates/workspace-core/.agents/skills/external-agents/SKILL.md +2 -1
  743. package/dist/templates/workspace-core/.agents/skills/frontend-design/SKILL.md +1 -1
  744. package/dist/templates/workspace-core/.agents/skills/observability/SKILL.md +32 -0
  745. package/dist/templates/workspace-core/.agents/skills/writing-agent-instructions/SKILL.md +25 -0
  746. package/dist/templates/workspace-core/src/server/index.ts +4 -2
  747. package/dist/testing.d.ts +16 -0
  748. package/dist/testing.d.ts.map +1 -0
  749. package/dist/testing.js +16 -0
  750. package/dist/testing.js.map +1 -0
  751. package/dist/triggers/dispatcher.d.ts +7 -0
  752. package/dist/triggers/dispatcher.d.ts.map +1 -1
  753. package/dist/triggers/dispatcher.js +13 -3
  754. package/dist/triggers/dispatcher.js.map +1 -1
  755. package/dist/vite/client.d.ts +16 -1
  756. package/dist/vite/client.d.ts.map +1 -1
  757. package/dist/vite/client.js +105 -2
  758. package/dist/vite/client.js.map +1 -1
  759. package/docs/content/authentication.mdx +3 -3
  760. package/docs/content/doctor.mdx +170 -0
  761. package/docs/content/external-agents.mdx +8 -7
  762. package/docs/content/locales/ar-SA/authentication.mdx +2 -2
  763. package/docs/content/locales/ar-SA/external-agents.mdx +8 -7
  764. package/docs/content/locales/ar-SA/mcp-protocol.mdx +1 -1
  765. package/docs/content/locales/ar-SA/security.mdx +2 -0
  766. package/docs/content/locales/de-DE/authentication.mdx +1 -1
  767. package/docs/content/locales/de-DE/external-agents.mdx +8 -7
  768. package/docs/content/locales/de-DE/mcp-protocol.mdx +1 -1
  769. package/docs/content/locales/de-DE/security.mdx +2 -0
  770. package/docs/content/locales/es-ES/authentication.mdx +2 -2
  771. package/docs/content/locales/es-ES/external-agents.mdx +8 -7
  772. package/docs/content/locales/es-ES/mcp-protocol.mdx +1 -1
  773. package/docs/content/locales/es-ES/security.mdx +2 -0
  774. package/docs/content/locales/fr-FR/authentication.mdx +1 -1
  775. package/docs/content/locales/fr-FR/external-agents.mdx +8 -7
  776. package/docs/content/locales/fr-FR/mcp-protocol.mdx +1 -1
  777. package/docs/content/locales/fr-FR/security.mdx +2 -0
  778. package/docs/content/locales/hi-IN/authentication.mdx +2 -2
  779. package/docs/content/locales/hi-IN/external-agents.mdx +8 -7
  780. package/docs/content/locales/hi-IN/mcp-protocol.mdx +1 -1
  781. package/docs/content/locales/hi-IN/security.mdx +2 -0
  782. package/docs/content/locales/ja-JP/authentication.mdx +2 -2
  783. package/docs/content/locales/ja-JP/external-agents.mdx +8 -7
  784. package/docs/content/locales/ja-JP/mcp-protocol.mdx +1 -1
  785. package/docs/content/locales/ja-JP/security.mdx +2 -0
  786. package/docs/content/locales/ko-KR/authentication.mdx +2 -2
  787. package/docs/content/locales/ko-KR/external-agents.mdx +8 -7
  788. package/docs/content/locales/ko-KR/mcp-protocol.mdx +1 -1
  789. package/docs/content/locales/ko-KR/security.mdx +2 -0
  790. package/docs/content/locales/pt-BR/authentication.mdx +2 -2
  791. package/docs/content/locales/pt-BR/external-agents.mdx +8 -7
  792. package/docs/content/locales/pt-BR/mcp-protocol.mdx +1 -1
  793. package/docs/content/locales/pt-BR/security.mdx +2 -0
  794. package/docs/content/locales/zh-CN/authentication.mdx +2 -2
  795. package/docs/content/locales/zh-CN/external-agents.mdx +8 -7
  796. package/docs/content/locales/zh-CN/mcp-protocol.mdx +1 -1
  797. package/docs/content/locales/zh-CN/security.mdx +2 -0
  798. package/docs/content/locales/zh-TW/authentication.mdx +2 -2
  799. package/docs/content/locales/zh-TW/external-agents.mdx +8 -7
  800. package/docs/content/locales/zh-TW/mcp-protocol.mdx +1 -1
  801. package/docs/content/locales/zh-TW/security.mdx +2 -0
  802. package/docs/content/mcp-protocol.mdx +1 -1
  803. package/docs/content/security.mdx +2 -0
  804. package/package.json +6 -2
  805. package/src/templates/default/.agents/skills/frontend-design/SKILL.md +1 -1
  806. package/src/templates/default/app/i18n/ar-SA.ts +6 -0
  807. package/src/templates/default/app/i18n/de-DE.ts +6 -0
  808. package/src/templates/default/app/i18n/en-US.ts +6 -0
  809. package/src/templates/default/app/i18n/es-ES.ts +6 -0
  810. package/src/templates/default/app/i18n/fr-FR.ts +6 -0
  811. package/src/templates/default/app/i18n/hi-IN.ts +6 -0
  812. package/src/templates/default/app/i18n/ja-JP.ts +6 -0
  813. package/src/templates/default/app/i18n/ko-KR.ts +6 -0
  814. package/src/templates/default/app/i18n/pt-BR.ts +6 -0
  815. package/src/templates/default/app/i18n/zh-CN.ts +6 -0
  816. package/src/templates/default/app/i18n/zh-TW.ts +6 -0
  817. package/src/templates/workspace-core/.agents/skills/authentication/SKILL.md +27 -29
  818. package/src/templates/workspace-core/.agents/skills/external-agents/SKILL.md +2 -1
  819. package/src/templates/workspace-core/.agents/skills/frontend-design/SKILL.md +1 -1
  820. package/src/templates/workspace-core/.agents/skills/observability/SKILL.md +32 -0
  821. package/src/templates/workspace-core/.agents/skills/writing-agent-instructions/SKILL.md +25 -0
  822. package/src/templates/workspace-core/src/server/index.ts +4 -2
  823. package/corpus/core/src/client/ProductionAgentPanel.tsx +0 -9
  824. package/corpus/core/src/client/auth-redirect-url.ts +0 -23
  825. package/corpus/core/src/client/useProductionAgent.ts +0 -253
  826. package/corpus/core/src/shared/auth-redirect-url.ts +0 -1
  827. package/corpus/templates/analytics/app/pages/Index.tsx +0 -16
  828. package/corpus/templates/analytics/seeds/dashboards/agent-observability-llm.json +0 -173
  829. package/dist/client/ProductionAgentPanel.d.ts +0 -6
  830. package/dist/client/ProductionAgentPanel.d.ts.map +0 -1
  831. package/dist/client/ProductionAgentPanel.js +0 -6
  832. package/dist/client/ProductionAgentPanel.js.map +0 -1
  833. package/dist/client/auth-redirect-url.d.ts +0 -2
  834. package/dist/client/auth-redirect-url.d.ts.map +0 -1
  835. package/dist/client/auth-redirect-url.js +0 -19
  836. package/dist/client/auth-redirect-url.js.map +0 -1
  837. package/dist/client/useProductionAgent.d.ts +0 -24
  838. package/dist/client/useProductionAgent.d.ts.map +0 -1
  839. package/dist/client/useProductionAgent.js +0 -179
  840. package/dist/client/useProductionAgent.js.map +0 -1
  841. package/dist/shared/auth-redirect-url.d.ts +0 -2
  842. package/dist/shared/auth-redirect-url.d.ts.map +0 -1
  843. package/dist/shared/auth-redirect-url.js +0 -2
  844. package/dist/shared/auth-redirect-url.js.map +0 -1
@@ -1,48 +1,44 @@
1
1
  import nodePath from "node:path";
2
2
  import { createError, defineEventHandler, setResponseStatus, setResponseHeader, getMethod, getQuery, getHeader, getRequestIP, } from "h3";
3
- import { appendA2AArtifactLinks, buildA2ARecoverableArtifactMessage, } from "../a2a/artifact-response.js";
3
+ import { buildA2ARecoverableArtifactMessage } from "../a2a/artifact-response.js";
4
4
  import { hasConfiguredA2ASecret, isLoopbackAddress, isTrustedLocalRuntime, } from "../a2a/auth-policy.js";
5
- import { applyAgentTextEventToBuffer, collectFinalResponseTextFromAgentEvents, } from "../a2a/response-text.js";
5
+ import { applyAgentTextEventToBuffer } from "../a2a/response-text.js";
6
6
  import { updateTaskStatusMessage } from "../a2a/task-store.js";
7
- import { ACTION_CHAT_UI_DATA_WIDGET_RENDERER } from "../action-ui.js";
8
7
  import { canUpdateAgentAppModelDefaultSettings, normalizeAgentAppModelDefaultAppId, readAgentAppModelDefaultSettings, resetAgentAppModelDefaultSettings, writeAgentAppModelDefaultSettings, } from "../agent/app-model-defaults.js";
9
8
  import { DEFAULT_ANTHROPIC_MODEL } from "../agent/default-model.js";
10
9
  import { AGENT_CHAT_BACKGROUND_RUN_FIELD, AGENT_CHAT_PROCESS_RUN_PATH, backgroundRunMarkerExpectsBackgroundRuntime, isInBackgroundFunctionRuntime, prepareProcessRunRequest, } from "../agent/durable-background.js";
11
10
  import { resolveEngine, createAnthropicEngine, getStoredModelForEngine, normalizeModelForEngine, getAgentEngineEntry, isAgentEnginePackageInstalled, isStoredEngineUsableForRequest, listAgentEngines, registerBuiltinEngines, } from "../agent/engine/index.js";
12
- import { createProductionAgentHandler, actionsToEngineTools, executeAgentToolCall, filterInitialEngineTools, getActiveRunForThreadAsync, abortRunDurably, subscribeToRun, } from "../agent/production-agent.js";
11
+ import { createProductionAgentHandler, actionsToEngineTools, executeAgentToolCall, getActiveRunForThreadAsync, abortRunDurably, subscribeToRun, } from "../agent/production-agent.js";
13
12
  import { runAgentLoopDirectWithSoftTimeout } from "../agent/run-loop-with-resume.js";
14
13
  import { callerHasRunAccess, callerHasThreadAccess, } from "../agent/run-ownership.js";
15
- import { CLAIMED_BACKGROUND_WORKER_FAILED_ERROR_EVENT, ensureTerminalRunEvent, readBackgroundRunClaim, recordRunDiagnostic, RUN_DIAG_STAGE, setRunError, setRunTerminalReason, updateRunStatusIfRunning, } from "../agent/run-store.js";
14
+ import { readBackgroundRunClaim } from "../agent/run-store.js";
16
15
  import { buildCurrentTimeUserContext, buildRuntimeContextPrompt, } from "../agent/runtime-context.js";
17
- import { buildAssistantMessage, buildUserMessage, extractThreadMeta, foldAssistantTurn, mergeThreadDataForClientSave, normalizeThreadRepository, upsertUserMessage, } from "../agent/thread-data-builder.js";
16
+ import { buildAssistantMessage, buildUserMessage, extractThreadMeta, foldAssistantTurn, mergeThreadDataForClientSave, upsertUserMessage, } from "../agent/thread-data-builder.js";
18
17
  import { attachToolSearch } from "../agent/tool-search.js";
19
18
  import { readAppStateForCurrentTab } from "../application-state/script-helpers.js";
19
+ import { appStateGet } from "../application-state/store.js";
20
20
  import { createThread, forkThread, getThread, registerChatThreadsShareable, resolveThreadAccess, listThreads, searchThreads, renameThread, createThreadShareLink, getThreadByShareToken, getThreadShareState, revokeThreadShareLink, setThreadArchived, setThreadPinned, setThreadScope, updateThreadData, withThreadDataLock, deleteThread, setThreadQueuedMessages, } from "../chat-threads/store.js";
21
- import { dataWidgetResultSchema } from "../data-widgets/index.js";
22
21
  import { createDbAdminAgentTools } from "../db-admin/agent-tools.js";
23
22
  import { verifyInternalToken, extractBearerToken, } from "../integrations/internal-token.js";
24
- import { McpClientManager, loadMcpConfig, autoDetectMcpConfig, mcpToolsToActionEntries, syncMcpActionEntries, mountMcpServersRoutes, mountMcpHubRoutes, buildMergedConfig, startMcpConfigRefresh, areBuiltinMcpCapabilitiesSupported, setBuiltinMcpCapabilityEnabled, getHubStatus, isHubServeEnabled, } from "../mcp-client/index.js";
23
+ import { McpClientManager, loadMcpConfig, autoDetectMcpConfig, mcpToolsToActionEntries, syncMcpActionEntries, mountMcpServersRoutes, mountMcpHubRoutes, buildMergedConfig, startMcpConfigRefresh, getHubStatus, isHubServeEnabled, } from "../mcp-client/index.js";
25
24
  import { setProgressPreListHook } from "../progress/store.js";
26
- import { getFrontmatterValue, getSkillNameFromPath, parseFrontmatter, } from "../resources/metadata.js";
27
- import { resourceList, resourceListAccessible, resourceGet, resourceGetByPath, ensurePersonalDefaults, organizationIdFromResourceOwner, sharedResourceOwner, SHARED_OWNER, WORKSPACE_OWNER, } from "../resources/store.js";
28
- import { normalizeDatabaseToolsMode, } from "../scripts/db/tool-mode.js";
29
- import { dbExecToolParameters } from "../scripts/db/tool-schemas.js";
25
+ import { getSkillNameFromPath } from "../resources/metadata.js";
26
+ import { resourceList, resourceListAccessible, resourceGet, ensurePersonalDefaults, SHARED_OWNER, WORKSPACE_OWNER, } from "../resources/store.js";
27
+ import { normalizeDatabaseToolsMode } from "../scripts/db/tool-mode.js";
30
28
  import { getSetting, putSetting } from "../settings/store.js";
29
+ import { handleSharedThreadRequest, } from "./agent-chat/shared-thread.js";
31
30
  import { discoverAgents } from "./agent-discovery.js";
32
31
  import { resolveAgentRunOwnerContext, runWithAgentRunContext, seedBackgroundAgentRunOwnerContext, } from "./agent-run-context.js";
33
32
  import { AGENT_TEAM_PROCESS_RUN_PATH, getCurrentDelegationDepth, processAgentTeamRun, reconcileAgentTeamRunsForOwner, } from "./agent-teams.js";
34
- import { withConfiguredAppBasePath } from "./app-base-path.js";
35
33
  import { getSession } from "./auth.js";
36
- import { getBuilderBrowserConnectUrlForOwner, resolveBuilderBranchProjectId, } from "./builder-browser.js";
37
34
  import { captureError } from "./capture-error.js";
38
- import { captureCliOutput } from "./cli-capture.js";
39
35
  import { getH3App, markDefaultPluginProvided, trackPluginInit, } from "./framework-request-handler.js";
40
36
  import { getOrigin } from "./google-oauth.js";
41
37
  import { readBody } from "./h3-helpers.js";
42
- import { buildFrameworkCore, buildFrameworkCoreCompact, FIRST_SESSION_PERSONALIZATION, getModelFamilyOverlay, } from "./prompts/index.js";
38
+ import { FIRST_SESSION_PERSONALIZATION, getModelFamilyOverlay, } from "./prompts/index.js";
43
39
  import { mountRealtimeVoiceRoutes } from "./realtime-voice.js";
44
40
  import { runWithRequestContext, getRequestOrgId, getRequestUserEmail, getRequestRunContext, ensureRequestRunContext, } from "./request-context.js";
45
- import { loadSchemaPromptBlock } from "./schema-prompt.js";
41
+ export { handleSharedThreadRequest };
46
42
  // Lazy fs — loaded via dynamic import() on first use.
47
43
  // This avoids require() which bundlers convert to createRequire(import.meta.url)
48
44
  // that crashes on CF Workers where import.meta.url is undefined.
@@ -53,2898 +49,75 @@ async function lazyFs() {
53
49
  }
54
50
  return _fs;
55
51
  }
56
- const SHARED_PROMPT_RESOURCE_MAX_CHARS = 30_000;
57
- const COMPACT_PROMPT_RESOURCE_MAX_CHARS = 12_000;
58
- const MAX_ACTION_SUMMARY_DESCRIPTION_CHARS = 140;
59
- function sanitizeSharedThread(thread) {
60
- let repo = {};
61
- try {
62
- repo = normalizeThreadRepository(JSON.parse(thread.threadData));
63
- }
64
- catch {
65
- repo = {};
66
- }
67
- const messages = Array.isArray(repo.messages)
68
- ? repo.messages
69
- .map((entry) => sanitizeSharedMessage(entry))
70
- .filter((entry) => entry != null)
71
- : [];
72
- return {
73
- id: thread.id,
74
- title: thread.title,
75
- preview: thread.preview,
76
- messageCount: thread.messageCount,
77
- createdAt: thread.createdAt,
78
- updatedAt: thread.updatedAt,
79
- scope: thread.scope
80
- ? {
81
- type: thread.scope.type,
82
- ...(thread.scope.label ? { label: thread.scope.label } : {}),
83
- }
84
- : null,
85
- messages,
86
- };
87
- }
88
- function escapeSharedThreadHtml(value) {
89
- return String(value ?? "")
90
- .replace(/&/g, "&")
91
- .replace(/</g, "&lt;")
92
- .replace(/>/g, "&gt;")
93
- .replace(/"/g, "&quot;")
94
- .replace(/'/g, "&#39;");
95
- }
96
- function wantsSharedThreadHtml(event) {
97
- const accept = getHeader(event, "accept")?.toLowerCase() ?? "";
98
- return accept.includes("text/html") && !accept.includes("application/json");
99
- }
100
- function formatSharedThreadTime(value) {
101
- if (value == null)
102
- return "";
103
- const date = typeof value === "number"
104
- ? new Date(value)
105
- : Number.isFinite(Number(value))
106
- ? new Date(Number(value))
107
- : new Date(value);
108
- return Number.isNaN(date.getTime()) ? String(value) : date.toLocaleString();
109
- }
110
- function renderSharedThreadHtml(thread, runs) {
111
- const title = thread.title || "Shared agent session";
112
- const messages = thread.messages
113
- .map((message) => {
114
- const time = formatSharedThreadTime(message.createdAt);
115
- return `<article class="message ${escapeSharedThreadHtml(message.role)}">
116
- <div class="meta">
117
- <span>${escapeSharedThreadHtml(message.role)}</span>
118
- ${time ? `<time>${escapeSharedThreadHtml(time)}</time>` : ""}
119
- </div>
120
- <pre>${escapeSharedThreadHtml(message.text)}</pre>
121
- </article>`;
122
- })
123
- .join("");
124
- const runsHtml = runs.length
125
- ? `<section class="runs" aria-label="Recent runs">
126
- <h2>Recent runs</h2>
127
- <ol>${runs
128
- .map((run) => {
129
- const started = formatSharedThreadTime(run.startedAt);
130
- const completed = formatSharedThreadTime(run.completedAt);
131
- const detail = [
132
- started ? `started ${started}` : "",
133
- completed ? `completed ${completed}` : "",
134
- run.errorCode ? `error ${run.errorCode}` : "",
135
- run.abortReason ? `aborted ${run.abortReason}` : "",
136
- ]
137
- .filter(Boolean)
138
- .join(" · ");
139
- return `<li><strong>${escapeSharedThreadHtml(run.status)}</strong>${detail ? `<span>${escapeSharedThreadHtml(detail)}</span>` : ""}</li>`;
140
- })
141
- .join("")}</ol>
142
- </section>`
143
- : "";
144
- return `<!doctype html>
145
- <html lang="en">
146
- <head>
147
- <meta charset="utf-8" />
148
- <meta name="viewport" content="width=device-width, initial-scale=1" />
149
- <meta name="robots" content="noindex, nofollow" />
150
- <meta name="referrer" content="no-referrer" />
151
- <title>${escapeSharedThreadHtml(title)}</title>
152
- <style>
153
- :root { color-scheme: light dark; font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: #f7f7f5; color: #1d1d1b; }
154
- * { box-sizing: border-box; }
155
- body { margin: 0; }
156
- main { width: min(920px, calc(100vw - 32px)); margin: 0 auto; padding: 44px 0 64px; }
157
- header { border-bottom: 1px solid rgba(0,0,0,.12); padding-bottom: 24px; margin-bottom: 28px; }
158
- .eyebrow { margin: 0 0 10px; font-size: 12px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; color: #676760; }
159
- h1 { margin: 0; font-size: 42px; line-height: 1.08; letter-spacing: 0; }
160
- .summary { margin: 14px 0 0; color: #5c5c55; line-height: 1.6; max-width: 760px; }
161
- .message { border: 1px solid rgba(0,0,0,.12); border-radius: 8px; background: rgba(255,255,255,.72); margin: 14px 0; padding: 16px; }
162
- .message.assistant { border-left: 4px solid #2563eb; }
163
- .message.user { border-left: 4px solid #0f766e; }
164
- .message.system { border-left: 4px solid #737373; }
165
- .meta { display: flex; gap: 12px; justify-content: space-between; color: #676760; font-size: 12px; font-weight: 700; text-transform: uppercase; }
166
- pre { margin: 12px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; line-height: 1.6; }
167
- .empty, .runs { margin-top: 28px; color: #676760; }
168
- .runs h2 { font-size: 16px; margin: 0 0 12px; }
169
- .runs ol { margin: 0; padding-left: 20px; }
170
- .runs li { margin: 8px 0; }
171
- .runs span { color: #676760; margin-left: 8px; }
172
- @media (prefers-color-scheme: dark) {
173
- :root { background: #11110f; color: #f5f5ef; }
174
- header, .message { border-color: rgba(255,255,255,.15); }
175
- .message { background: rgba(255,255,255,.06); }
176
- .summary, .eyebrow, .meta, .empty, .runs, .runs span { color: #b9b9ad; }
177
- }
178
- @media (max-width: 640px) {
179
- h1 { font-size: 32px; }
180
- main { width: min(100vw - 24px, 920px); padding-top: 32px; }
181
- }
182
- </style>
183
- </head>
184
- <body>
185
- <main>
186
- <header>
187
- <p class="eyebrow">Read-only shared agent session</p>
188
- <h1>${escapeSharedThreadHtml(title)}</h1>
189
- <p class="summary">${escapeSharedThreadHtml(thread.preview || `${thread.messageCount} message${thread.messageCount === 1 ? "" : "s"}`)}</p>
190
- </header>
191
- ${messages || '<p class="empty">No transcript messages were shared.</p>'}
192
- ${runsHtml}
193
- </main>
194
- </body>
195
- </html>`;
196
- }
197
- function renderSharedThreadErrorHtml(status, message) {
198
- return `<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="robots" content="noindex, nofollow" /><title>${status} ${escapeSharedThreadHtml(message)}</title><style>body{margin:0;font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;background:#f7f7f5;color:#1d1d1b}main{max-width:720px;margin:0 auto;padding:64px 24px}p{color:#676760;line-height:1.6}@media(prefers-color-scheme:dark){body{background:#11110f;color:#f5f5ef}p{color:#b9b9ad}}</style></head><body><main><h1>${status}</h1><p>${escapeSharedThreadHtml(message)}</p></main></body></html>`;
199
- }
200
- function sharedThreadError(event, status, message) {
201
- setResponseStatus(event, status);
202
- setResponseHeader(event, "Cache-Control", "private, no-store");
203
- setResponseHeader(event, "X-Robots-Tag", "noindex, nofollow");
204
- if (wantsSharedThreadHtml(event)) {
205
- setResponseHeader(event, "Content-Type", "text/html; charset=utf-8");
206
- return renderSharedThreadErrorHtml(status, message);
207
- }
208
- return { error: message };
209
- }
210
- export async function handleSharedThreadRequest(event, deps) {
211
- const method = getMethod(event);
212
- if (method !== "GET") {
213
- return sharedThreadError(event, 405, "Method not allowed");
214
- }
215
- const token = parseSharedThreadToken(event);
216
- if (!token) {
217
- return sharedThreadError(event, 400, "Share token is required");
218
- }
219
- const thread = await deps.getThreadByShareToken(token);
220
- if (!thread) {
221
- return sharedThreadError(event, 404, "Shared thread not found");
222
- }
223
- const runs = await deps.listRunsForThread(thread.id, { limit: 10 });
224
- const payload = {
225
- thread: sanitizeSharedThread(thread),
226
- runs,
227
- };
228
- setResponseHeader(event, "Cache-Control", "private, no-store");
229
- setResponseHeader(event, "X-Robots-Tag", "noindex, nofollow");
230
- if (wantsSharedThreadHtml(event)) {
231
- setResponseHeader(event, "Content-Type", "text/html; charset=utf-8");
232
- return renderSharedThreadHtml(payload.thread, runs);
233
- }
234
- setResponseHeader(event, "Content-Type", "application/json");
235
- return payload;
236
- }
237
- function sanitizeSharedMessage(entry) {
238
- if (!entry || typeof entry !== "object")
239
- return null;
240
- const raw = entry;
241
- const message = raw.message && typeof raw.message === "object"
242
- ? raw.message
243
- : raw;
244
- const role = message.role;
245
- if (role !== "user" && role !== "assistant" && role !== "system") {
246
- return null;
247
- }
248
- const text = sharedTextFromContent(message.content).trim();
249
- if (!text)
250
- return null;
251
- const id = typeof message.id === "string" ? message.id : undefined;
252
- const createdAt = typeof message.createdAt === "string" ||
253
- typeof message.createdAt === "number"
254
- ? message.createdAt
255
- : undefined;
256
- return {
257
- ...(id ? { id } : {}),
258
- role,
259
- text,
260
- ...(createdAt !== undefined ? { createdAt } : {}),
261
- };
262
- }
263
- function sharedTextFromContent(content) {
264
- if (typeof content === "string")
265
- return content;
266
- if (!Array.isArray(content))
267
- return "";
268
- const parts = [];
269
- for (const part of content) {
270
- if (!part || typeof part !== "object")
271
- continue;
272
- const r = part;
273
- if (r.type !== "text")
274
- continue;
275
- if (typeof r.text === "string")
276
- parts.push(r.text);
277
- }
278
- return parts.join("");
279
- }
280
- function parseSharedThreadToken(event) {
281
- const candidates = [event.path, event.node?.req?.url].filter((value) => typeof value === "string" && value.length > 0);
282
- for (const candidate of candidates) {
283
- const path = candidate.split("?")[0];
284
- const parts = path.replace(/^\/+/, "").split("/").filter(Boolean);
285
- const sharedIndex = parts.lastIndexOf("shared");
286
- if (sharedIndex >= 0 && parts[sharedIndex + 1]) {
287
- return decodeURIComponent(parts[sharedIndex + 1]);
288
- }
289
- if (parts[0])
290
- return decodeURIComponent(parts[0]);
291
- }
292
- return null;
293
- }
294
- function compactPromptLine(value, maxChars) {
295
- const line = value.replace(/\s+/g, " ").trim();
296
- if (line.length <= maxChars)
297
- return line;
298
- return `${line.slice(0, maxChars - 1)}…`;
299
- }
300
- const SHARED_RESOURCE_INDEX_LIMIT = 40;
301
- function normalizeResourcePathForPrompt(path) {
302
- return path.replace(/^\/+/, "").trim();
303
- }
304
- function resourceToolHint(action, extra) {
305
- return `Use the \`resources\` tool with \`action: "${action}"\`${extra ? `, ${extra}` : ""}.`;
306
- }
307
- function skillDocsSlug(name) {
308
- return `skill-${name
309
- .trim()
310
- .toLowerCase()
311
- .replace(/[^a-z0-9]+/g, "-")
312
- .replace(/^-+|-+$/g, "")}`;
313
- }
314
- function ensureSentence(value) {
315
- const trimmed = value.trim();
316
- if (!trimmed)
317
- return "";
318
- return /[.!?]$/.test(trimmed) ? trimmed : `${trimmed}.`;
319
- }
320
- function escapeXmlAttribute(value) {
321
- return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;");
322
- }
323
- function truncatePromptResourceContent(content, path, maxChars = SHARED_PROMPT_RESOURCE_MAX_CHARS, readHint) {
324
- const trimmed = content.trim();
325
- if (trimmed.length <= maxChars)
326
- return trimmed;
327
- const omitted = trimmed.length - maxChars;
328
- const hint = readHint ??
329
- resourceToolHint("read", `\`path: "${path}"\` and the resource's \`scope\` for the full content`);
330
- return `${trimmed.slice(0, maxChars)}\n\n[Resource ${path} truncated after ${maxChars.toLocaleString()} characters; ${omitted.toLocaleString()} characters omitted. ${hint}]`;
331
- }
332
- function promptResourceBlock(input) {
333
- const normalizedPath = input.path
334
- ? normalizeResourcePathForPrompt(input.path)
335
- : undefined;
336
- const content = truncatePromptResourceContent(input.content, normalizedPath ?? input.name, input.maxChars, input.readHint);
337
- if (!content)
338
- return null;
339
- const pathAttr = normalizedPath
340
- ? ` path="${escapeXmlAttribute(normalizedPath)}"`
341
- : "";
342
- return `<resource name="${escapeXmlAttribute(input.name)}" scope="${escapeXmlAttribute(input.scope)}"${pathAttr}>\n${content}\n</resource>`;
343
- }
344
- function isAutoLoadedInstructionPath(path) {
345
- const normalized = normalizeResourcePathForPrompt(path);
346
- return normalized.startsWith("instructions/") && normalized.endsWith(".md");
347
- }
348
- function isSpecialPromptResourcePath(path) {
349
- const normalized = normalizeResourcePathForPrompt(path);
350
- return (normalized === "AGENTS.md" ||
351
- normalized === "LEARNINGS.md" ||
352
- normalized.startsWith("instructions/") ||
353
- normalized.startsWith("skills/") ||
354
- normalized.startsWith("agents/") ||
355
- normalized.startsWith("remote-agents/") ||
356
- normalized.startsWith("jobs/") ||
357
- normalized.startsWith("memory/"));
358
- }
359
- function isTextLikeResource(mimeType) {
360
- return (mimeType.startsWith("text/") ||
361
- mimeType === "application/json" ||
362
- mimeType === "application/yaml" ||
363
- mimeType === "application/x-yaml");
364
- }
365
- function getResourceSummaryFromContent(content) {
366
- const frontmatter = parseFrontmatter(content);
367
- const title = getFrontmatterValue(frontmatter, "title") ||
368
- getFrontmatterValue(frontmatter, "name");
369
- const description = getFrontmatterValue(frontmatter, "description");
370
- if (title && description)
371
- return `${title}: ${description}`;
372
- if (title)
373
- return title;
374
- if (description)
375
- return description;
376
- const heading = content
377
- .split(/\r?\n/)
378
- .map((line) => line.trim())
379
- .find((line) => /^#{1,3}\s+\S/.test(line));
380
- if (heading)
381
- return heading.replace(/^#{1,3}\s+/, "").trim();
382
- return null;
383
- }
384
- function resourceScopeForOwner(owner, currentOwner) {
385
- if (owner === WORKSPACE_OWNER)
386
- return "workspace";
387
- if (owner === SHARED_OWNER || organizationIdFromResourceOwner(owner)) {
388
- return "shared";
389
- }
390
- if (currentOwner && owner === currentOwner)
391
- return "personal";
392
- return "resource";
393
- }
394
- async function loadAgentsResourceForPrompt(owner, scope, maxChars = SHARED_PROMPT_RESOURCE_MAX_CHARS) {
395
- try {
396
- const agents = await resourceGetByPath(owner, "AGENTS.md");
397
- if (!agents?.content?.trim())
398
- return null;
399
- return promptResourceBlock({
400
- name: "AGENTS.md",
401
- scope,
402
- path: "AGENTS.md",
403
- content: agents.content,
404
- maxChars,
405
- });
406
- }
407
- catch {
408
- return null;
409
- }
410
- }
411
- async function loadInstructionResourcesForPrompt(owner, scope, maxChars = SHARED_PROMPT_RESOURCE_MAX_CHARS) {
412
- try {
413
- const resources = await resourceList(owner, "instructions/");
414
- const blocks = [];
415
- const sorted = resources
416
- .filter((resource) => isAutoLoadedInstructionPath(resource.path))
417
- .sort((a, b) => a.path.localeCompare(b.path));
418
- for (const resource of sorted) {
419
- const full = await resourceGet(resource.id).catch(() => null);
420
- if (!full?.content?.trim())
421
- continue;
422
- const block = promptResourceBlock({
423
- name: resource.path,
424
- scope,
425
- path: resource.path,
426
- content: full.content,
427
- maxChars,
428
- });
429
- if (block)
430
- blocks.push(block);
431
- }
432
- return blocks;
433
- }
434
- catch {
435
- return [];
436
- }
437
- }
438
- async function loadResourceSkillsPromptBlock(owner, orgId) {
439
- try {
440
- const organizationOwner = sharedResourceOwner(orgId);
441
- const resources = owner === SHARED_OWNER
442
- ? [
443
- ...(await resourceList(SHARED_OWNER, "skills/")),
444
- ...(await resourceList(WORKSPACE_OWNER, "skills/")),
445
- ]
446
- : await resourceListAccessible(owner, "skills/", { orgId });
447
- const sorted = resources.sort((a, b) => {
448
- const ownerOrder = (a.owner === owner
449
- ? 0
450
- : a.owner === organizationOwner
451
- ? 1
452
- : a.owner === SHARED_OWNER
453
- ? 2
454
- : a.owner === WORKSPACE_OWNER
455
- ? 3
456
- : 4) -
457
- (b.owner === owner
458
- ? 0
459
- : b.owner === organizationOwner
460
- ? 1
461
- : b.owner === SHARED_OWNER
462
- ? 2
463
- : b.owner === WORKSPACE_OWNER
464
- ? 3
465
- : 4);
466
- if (ownerOrder !== 0)
467
- return ownerOrder;
468
- return a.path.localeCompare(b.path);
469
- });
470
- const seen = new Set();
471
- const lines = [];
472
- for (const resource of sorted) {
473
- const full = await resourceGet(resource.id).catch(() => null);
474
- if (!full?.content)
475
- continue;
476
- const meta = parseSkillFrontmatter(full.content);
477
- if (meta.userInvocable === false)
478
- continue;
479
- if (meta.scope === "dev")
480
- continue;
481
- const name = meta.name || getSkillNameFromPath(resource.path);
482
- if (!name || seen.has(name))
483
- continue;
484
- seen.add(name);
485
- const scope = resourceScopeForOwner(resource.owner, owner);
486
- const description = meta.description || "(no description)";
487
- lines.push(`- \`${name}\` at resource \`${resource.path}\` (${scope}) - ${ensureSentence(description)} ${resourceToolHint("read", `\`path: "${resource.path}"\` and \`scope: "${scope}"\` before starting a task it applies to`)}`);
488
- }
489
- if (lines.length === 0)
490
- return null;
491
- return `<resource-skills>\nThe following workspace skills are available in addition to codebase skills. They may come from SQL resources, Dispatch workspace resources, or local file mode. Read a matching skill before starting a task it applies to.\n\n${lines.join("\n")}\n</resource-skills>`;
492
- }
493
- catch {
494
- return null;
495
- }
496
- }
497
- async function loadResourceIndexForPrompt(owner, scope) {
498
- try {
499
- const resources = (await resourceList(owner))
500
- .filter((resource) => !isSpecialPromptResourcePath(resource.path) &&
501
- isTextLikeResource(resource.mimeType))
502
- .sort((a, b) => a.path.localeCompare(b.path));
503
- if (resources.length === 0)
504
- return null;
505
- const listed = resources.slice(0, SHARED_RESOURCE_INDEX_LIMIT);
506
- const lines = [];
507
- for (const resource of listed) {
508
- const full = await resourceGet(resource.id).catch(() => null);
509
- const summary = full?.content
510
- ? getResourceSummaryFromContent(full.content)
511
- : null;
512
- lines.push(`- \`${resource.path}\`${summary ? ` - ${summary}` : ""}`);
513
- }
514
- if (resources.length > listed.length) {
515
- lines.push(`- ...${resources.length - listed.length} more ${scope} resources. ${resourceToolHint("list", `\`scope: "${scope}"\` to inspect them`)}`);
516
- }
517
- const label = scope === "workspace"
518
- ? "Workspace reference resources are inherited by every app and are available for company, brand, positioning, persona, product, or domain context."
519
- : "Shared app/organization reference resources are available for app-specific or team context.";
520
- return `<workspace-resources scope="${scope}">\n${label} ${resourceToolHint("read", `\`path: <path>\` and \`scope: "${scope}"\` when a task may depend on them`)} Do not assume their contents without reading the relevant file.\n\n${lines.join("\n")}\n</workspace-resources>`;
521
- }
522
- catch {
523
- return null;
524
- }
525
- }
526
- /**
527
- * Wraps a core CLI script (that writes to console.log) as a ActionEntry
528
- * by capturing stdout. Uses an AsyncLocalStorage-backed capture so
529
- * concurrent tool calls do not corrupt the global console/stdout pointers
530
- * (see `cli-capture.ts`).
531
- */
532
- function wrapCliScript(tool, cliDefault, opts) {
533
- return {
534
- tool,
535
- ...(opts?.readOnly ? { readOnly: true } : {}),
536
- run: async (args) => {
537
- const cliArgs = [];
538
- for (const [k, v] of Object.entries(args)) {
539
- const raw = v;
540
- const value = raw != null && typeof raw === "object"
541
- ? JSON.stringify(raw)
542
- : String(raw);
543
- cliArgs.push(`--${k}`, value);
544
- }
545
- return captureCliOutput(() => cliDefault(cliArgs));
546
- },
547
- };
548
- }
549
- function filterReadOnlyActions(actions) {
550
- return Object.fromEntries(Object.entries(actions).filter(([, entry]) => entry.readOnly === true));
551
- }
552
- /** Drop actions that opted out of agent exposure via `agentTool: false`. They
553
- * remain callable from the frontend / HTTP (mounted separately from this
554
- * agent tool surface — see `httpActions`) but never appear in any agent tool
555
- * list (in-app assistant, MCP, A2A, job/trigger runners) or actions prompt.
556
- * Default-allow: only an explicit `false` is excluded. */
557
- function filterAgentTools(actions) {
558
- return Object.fromEntries(Object.entries(actions).filter(([, entry]) => entry.agentTool !== false));
559
- }
560
- function filterPublicAgentActions(actions) {
561
- return Object.fromEntries(Object.entries(actions).filter(([, entry]) => {
562
- const config = entry.publicAgent;
563
- return (config?.expose === true &&
564
- config.readOnly === true &&
565
- config.requiresAuth !== true &&
566
- config.isConsequential !== true);
567
- }));
568
- }
569
- export function buildPublicAgentA2ASkills(actions) {
570
- return Object.entries(filterPublicAgentActions(actions)).map(([name, entry]) => ({
571
- id: name,
572
- name,
573
- description: entry.tool.description,
574
- publicAgent: entry.publicAgent,
575
- }));
576
- }
577
- function resolveArtifactBaseUrl(event) {
578
- const fromEnv = process.env.APP_URL ||
579
- process.env.URL ||
580
- process.env.DEPLOY_URL ||
581
- process.env.BETTER_AUTH_URL;
582
- if (fromEnv)
583
- return withConfiguredAppBasePath(String(fromEnv));
584
- try {
585
- const proto = getHeader(event, "x-forwarded-proto") || "https";
586
- const host = getHeader(event, "host");
587
- if (host)
588
- return withConfiguredAppBasePath(`${proto}://${host}`);
589
- }
590
- catch { }
591
- return undefined;
592
- }
593
- export function assembleA2AFinalResponse(events, toolResults, options = {}) {
594
- const terminalError = getA2ATerminalErrorEvent(events);
595
- const responseText = collectFinalResponseTextFromAgentEvents(events, {
596
- fallbackToPreToolText: !terminalError,
597
- });
598
- const finalText = appendA2AArtifactLinks(responseText, [...toolResults], {
599
- baseUrl: options.baseUrl ?? resolveArtifactBaseUrl(options.event),
600
- includeReferencedArtifacts: true,
601
- });
602
- if (terminalError && !finalText.trim()) {
603
- throw new Error(formatA2ATerminalError(terminalError));
604
- }
605
- return { responseText, finalText };
606
- }
607
- function getA2ATerminalErrorEvent(events) {
608
- for (let i = events.length - 1; i >= 0; i--) {
609
- const event = events[i];
610
- if (event.type === "clear")
611
- continue;
612
- if (event.type === "done")
613
- return null;
614
- if (event.type === "error")
615
- return event;
616
- if (event.type === "auto_continue") {
617
- return {
618
- type: "error",
619
- error: `Agent stopped before finishing (${event.reason}).`,
620
- errorCode: event.reason,
621
- recoverable: true,
622
- };
623
- }
624
- }
625
- return null;
626
- }
627
- function formatA2ATerminalError(event) {
628
- const parts = [
629
- event.error || "Agent failed before producing a final response.",
630
- event.errorCode ? `code: ${event.errorCode}` : "",
631
- event.details ? `details: ${event.details}` : "",
632
- ].filter(Boolean);
633
- return parts.join("\n");
634
- }
635
- /**
636
- * Creates the `get-framework-context` tool. Returns detailed instructions
637
- * for framework capabilities that are summarized in the compact prompt.
638
- * The agent calls this on-demand when it needs specifics about embeds,
639
- * agent teams, recurring jobs, etc.
640
- */
641
- function createFrameworkContextEntry() {
642
- const topicList = Object.keys(FRAMEWORK_CONTEXT_SECTIONS).join(", ");
643
- return {
644
- "get-framework-context": {
645
- tool: {
646
- description: `Read detailed framework instructions for a specific capability. Available topics: ${topicList}. Call with topic="all" to get everything.`,
647
- parameters: {
648
- type: "object",
649
- properties: {
650
- topic: {
651
- type: "string",
652
- description: `Topic to read. One of: ${topicList}, or "all" for everything.`,
653
- },
654
- },
655
- required: ["topic"],
656
- },
657
- },
658
- run: async (args) => {
659
- const topic = String(args.topic ?? "all").toLowerCase();
660
- if (topic === "all") {
661
- return Object.values(FRAMEWORK_CONTEXT_SECTIONS).join("\n\n");
662
- }
663
- const section = FRAMEWORK_CONTEXT_SECTIONS[topic];
664
- if (!section) {
665
- return `Unknown topic "${topic}". Available: ${topicList}`;
666
- }
667
- return section;
668
- },
669
- readOnly: true,
670
- },
671
- };
672
- }
673
- /**
674
- * Creates the `refresh-screen` tool. Writes a bump to `application_state`
675
- * under a well-known key; the client's `useDbSync` watches for this and
676
- * invalidates react-query caches so the on-screen UI re-fetches its data
677
- * without a full page reload.
678
- *
679
- * This is the standard way for the agent to say "the data on the screen
680
- * just changed, please refresh it" — e.g. after editing a dashboard config,
681
- * updating a form schema, or mutating a row that the current view renders.
682
- */
683
- function createRefreshScreenEntry() {
684
- return {
685
- "refresh-screen": {
686
- // Writes __screen_refresh__ to application_state, which emits its own
687
- // distinct `screen-refresh` poll event. Don't double-emit a generic
688
- // `action` event on top of that.
689
- readOnly: true,
690
- tool: {
691
- description: "Manually refresh the user's current screen. The framework ALREADY auto-refreshes after any successful mutating action tool call (template actions and any enabled raw DB write tools) — you do NOT need to call this after a normal action. Use it only when (a) you mutated data via a path the framework can't detect (e.g. a direct write to an external system the app mirrors), or (b) you want to pass a `scope` hint so the UI narrows which queries to refetch. The UI re-fetches its queries without a full page reload.",
692
- parameters: {
693
- type: "object",
694
- properties: {
695
- scope: {
696
- type: "string",
697
- description: "Optional hint describing what changed (e.g. 'dashboard', 'form', 'settings'). Templates may use it to narrow which queries to invalidate; if omitted, all queries are invalidated.",
698
- },
699
- },
700
- },
701
- },
702
- run: async (args) => {
703
- const { writeAppState } = await import("../application-state/script-helpers.js");
704
- const nonce = Date.now();
705
- const scope = typeof args?.scope === "string" ? args.scope : undefined;
706
- await writeAppState(SCREEN_REFRESH_KEY, {
707
- nonce,
708
- ...(scope ? { scope } : {}),
709
- });
710
- return `refreshed${scope ? ` (scope: ${scope})` : ""}`;
711
- },
712
- },
713
- };
714
- }
715
- /** Well-known application-state key used by the refresh-screen tool. */
716
- const SCREEN_REFRESH_KEY = "__screen_refresh__";
717
- const SAFE_BROWSER_TAB_ID_RE = /^[A-Za-z0-9_-]{1,96}$/;
718
- function appStateKeyForBrowserTab(key, browserTabId) {
719
- if (typeof browserTabId !== "string")
720
- return key;
721
- const trimmed = browserTabId.trim();
722
- return SAFE_BROWSER_TAB_ID_RE.test(trimmed) ? `${key}:${trimmed}` : key;
723
- }
724
- /**
725
- * In-memory rate-limit tracker for `/generate-title`. Keyed by user email,
726
- * value is recent invocation timestamps within the rolling window. Stale
727
- * entries are pruned on read.
728
- */
729
- const generateTitleRateLimit = new Map();
730
- /** Only sweep drained rate-limit entries once the map grows past this size,
731
- * so the common small-map case stays O(1). */
732
- const RATE_LIMIT_SWEEP_THRESHOLD = 1000;
733
- /**
734
- * Creates the `set-search-params` / `set-url-path` tools. Writes a one-shot
735
- * URL command to application_state; the client's URLSync component applies
736
- * it via react-router (no full page reload) and then deletes the command.
737
- *
738
- * This is how the agent edits URL state — filter query params, route
739
- * changes, hash — without needing a per-template navigate action. The
740
- * current URL is visible to the agent via the auto-injected `<current-url>`
741
- * block, which includes parsed search params.
742
- */
743
- function createUrlTools() {
744
- return {
745
- "set-search-params": {
746
- // Writes __set_url__ to application_state, which the app-state watcher
747
- // already surfaces as a poll event. No need to double-emit.
748
- readOnly: true,
749
- tool: {
750
- description: "Update the URL query string on the user's current page. Use this to change dashboard/list filters, search terms, or any other state the app stores in `?foo=bar` style query params. One-shot — the UI applies it in ~1s without a page reload. See the current URL + parsed search params in the auto-injected `<current-url>` block. Keys are the exact query param names as they appear in the URL (e.g. `f_pubDateStart`, not just `pubDateStart`). Set a value to null or empty string to clear that param. By default merges over existing params — pass `merge: false` to replace them all.",
751
- parameters: {
752
- type: "object",
753
- properties: {
754
- params: {
755
- type: "object",
756
- description: 'Map of query param → value. Each value is a string, or null/"" to clear. Example: {"f_pubDateStart": null, "f_cadence": "MONTH"}.',
757
- },
758
- merge: {
759
- type: "string",
760
- description: '"true" (default) merges over existing params; "false" replaces them entirely.',
761
- enum: ["true", "false"],
762
- },
763
- },
764
- required: ["params"],
765
- },
766
- },
767
- run: async (args) => {
768
- const params = (args?.params ?? {});
769
- const merge = args?.merge !== "false";
770
- const { writeAppState } = await import("../application-state/script-helpers.js");
771
- await writeAppState(appStateKeyForBrowserTab("__set_url__", getRequestRunContext()?.browserTabId), {
772
- searchParams: params,
773
- mergeSearchParams: merge,
774
- // Unique-per-write token. The client's URLSync hook dedups by this
775
- // so a fire-and-forget DELETE that loses its race against the next
776
- // polling refetch can't cause the same URL command to be applied
777
- // repeatedly (which caused the editor to bounce between slides
778
- // when an agent turn errored partway through).
779
- _writeId: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
780
- });
781
- const keys = Object.keys(params);
782
- return `set-search-params: ${keys.length} key${keys.length === 1 ? "" : "s"}${merge ? "" : " (replace)"}`;
783
- },
784
- },
785
- "set-url-path": {
786
- // Same as set-search-params — writes application_state, already emits
787
- // via the app-state watcher.
788
- readOnly: true,
789
- tool: {
790
- description: "Navigate the user to a different pathname, optionally also setting search params. For most template-specific routing prefer the template's `navigate` action if it exists — this is the generic fallback. One-shot, applied by the client without a page reload.",
791
- parameters: {
792
- type: "object",
793
- properties: {
794
- pathname: {
795
- type: "string",
796
- description: "New URL pathname (e.g. '/adhoc/weekly').",
797
- },
798
- params: {
799
- type: "object",
800
- description: 'Optional query params to set alongside the path change. String values set, null/"" clears.',
801
- },
802
- merge: {
803
- type: "string",
804
- description: '"true" (default) merges over existing params; "false" starts fresh.',
805
- enum: ["true", "false"],
806
- },
807
- },
808
- required: ["pathname"],
809
- },
810
- },
811
- run: async (args) => {
812
- const pathname = String(args?.pathname ?? "");
813
- if (!pathname.startsWith("/")) {
814
- return "Error: pathname must start with '/'.";
815
- }
816
- const params = (args?.params ?? {});
817
- const merge = args?.merge !== "false";
818
- const { writeAppState } = await import("../application-state/script-helpers.js");
819
- await writeAppState(appStateKeyForBrowserTab("__set_url__", getRequestRunContext()?.browserTabId), {
820
- pathname,
821
- searchParams: params,
822
- mergeSearchParams: merge,
823
- // See note in set-search-params: unique-per-write dedup token so a
824
- // race between GET and consume-DELETE in URLSync can't re-apply
825
- // this command.
826
- _writeId: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
827
- });
828
- return `set-url-path: ${pathname}`;
829
- },
830
- },
831
- "ask-question": {
832
- tool: {
833
- description: "Ask the user a multiple-choice clarifying question and render it inline in the chat. Use this ONLY when you are genuinely blocked on a decision you cannot resolve from context and a wrong guess would be costly — an ambiguous metric, date range, or grain; a real fork in approach. Present 2-5 concrete options and mark the most likely one recommended. Do NOT use it for confirmations, for things the user already specified, or to dodge easy work you could just do. Ask at most once per turn. Calling this yields the turn: stop and wait for the user's answer.",
834
- parameters: {
835
- type: "object",
836
- properties: {
837
- question: {
838
- type: "string",
839
- description: "The complete question to ask the user. Clear, specific, ends with a question mark.",
840
- },
841
- header: {
842
- type: "string",
843
- description: 'Optional very short label (max ~12 chars) shown as a chip/heading above the question, e.g. "Date range", "Approach", "Library".',
844
- },
845
- options: {
846
- type: "string",
847
- description: 'A JSON array of 2-4 distinct, mutually-exclusive options (unless `allowMultiple` is true), each `{ "label": string, "value"?: string, "description"?: string, "preview"?: string, "recommended"?: boolean }`. `label` is 1-5 words; `description` explains the trade-off; `preview` is optional content (mockup, code snippet, short comparison) rendered under the option. `value` defaults to `label` when omitted. Mark the most likely option `"recommended": true`. Do NOT add an "Other" option — free text is provided automatically when `allowFreeText` is on.',
848
- },
849
- allowFreeText: {
850
- type: "string",
851
- description: 'Whether the user may also type a free-text "Other" answer. "true" (default) or "false".',
852
- enum: ["true", "false"],
853
- },
854
- allowMultiple: {
855
- type: "string",
856
- description: 'Whether the user may select more than one option (multi-select). "true" or "false" (default).',
857
- enum: ["true", "false"],
858
- },
859
- },
860
- required: ["question", "options"],
861
- },
862
- },
863
- run: async (args) => {
864
- const question = String(args?.question ?? "").trim();
865
- if (!question)
866
- return "Error: 'question' is required.";
867
- const header = String(args?.header ?? "").trim();
868
- const allowMultiple = String(args?.allowMultiple ?? "") === "true";
869
- const allowFreeText = String(args?.allowFreeText ?? "true") !== "false";
870
- let parsedOptions;
871
- try {
872
- parsedOptions = JSON.parse(String(args?.options ?? "[]"));
873
- }
874
- catch {
875
- return "Error: 'options' must be a JSON array of { label, value?, description?, recommended? }.";
876
- }
877
- if (!Array.isArray(parsedOptions) || parsedOptions.length === 0) {
878
- return "Error: 'options' must be a non-empty JSON array of { label, value?, description?, recommended? }.";
879
- }
880
- const options = parsedOptions
881
- .map((raw) => {
882
- const opt = (raw ?? {});
883
- const label = typeof opt.label === "string" && opt.label.trim()
884
- ? opt.label.trim()
885
- : typeof opt.value === "string"
886
- ? String(opt.value).trim()
887
- : "";
888
- if (!label)
889
- return null;
890
- const value = typeof opt.value === "string" && opt.value.trim()
891
- ? opt.value.trim()
892
- : label;
893
- const option = { label, value };
894
- if (typeof opt.description === "string" && opt.description.trim()) {
895
- option.description = opt.description.trim();
896
- }
897
- if (typeof opt.preview === "string" && opt.preview.trim()) {
898
- option.preview = opt.preview;
899
- }
900
- if (opt.recommended === true)
901
- option.recommended = true;
902
- return option;
903
- })
904
- .filter((opt) => opt !== null);
905
- if (options.length === 0) {
906
- return "Error: 'options' must contain at least one option with a label.";
907
- }
908
- // Shape must match the GuidedQuestionFlow renderer in
909
- // client/guided-questions.tsx: a `text-options` question whose options
910
- // carry `value`, with `multiSelect` for multi-pick and `allowOther` for
911
- // free text. The renderer otherwise injects "Explore"/"Decide" options,
912
- // which would be noise for a focused clarifying question, so disable them.
913
- const payload = {
914
- questions: [
915
- {
916
- id: "q1",
917
- type: "text-options",
918
- question,
919
- ...(header ? { header } : {}),
920
- required: !allowFreeText,
921
- multiSelect: allowMultiple,
922
- allowOther: allowFreeText,
923
- includeExplore: false,
924
- includeDecide: false,
925
- options,
926
- },
927
- ],
928
- };
929
- const { writeAppState } = await import("../application-state/script-helpers.js");
930
- await writeAppState(appStateKeyForBrowserTab("guided-questions", getRequestRunContext()?.browserTabId), payload);
931
- return "Asked the user a clarifying question and rendered it in the chat. Stop here and wait for their answer — do not proceed or assume an answer.";
932
- },
933
- },
934
- };
935
- }
936
- function createDataWidgetActionEntries() {
937
- return {
938
- "render-data-widget": {
939
- readOnly: true,
940
- parallelSafe: true,
941
- chatUI: {
942
- renderer: ACTION_CHAT_UI_DATA_WIDGET_RENDERER,
943
- title: "Data widget",
944
- description: "Render a validated native data table or chart in chat.",
945
- },
946
- tool: {
947
- description: "Render a native Agent-Native chat data widget from compact, real data you already retrieved or the user provided. Use this for in-chat tables, charts, graphs, trends, and compact reports when no domain-specific action already returns a native widget. Never fabricate rows or metrics just to make a chart.",
948
- parameters: {
949
- type: "object",
950
- properties: {
951
- widget: {
952
- type: "string",
953
- enum: ["data-table", "data-chart", "data-insights"],
954
- description: "Widget kind. Use data-chart for a chart, data-table for a table, or data-insights for a combined summary/chart/table card.",
955
- },
956
- widgetId: {
957
- type: "string",
958
- description: "Optional stable widget identifier.",
959
- },
960
- title: {
961
- type: "string",
962
- description: "Optional widget title.",
963
- },
964
- summary: {
965
- type: "object",
966
- description: "Optional scalar summary values for data-insights cards.",
967
- },
968
- display: {
969
- type: "object",
970
- description: "Optional display metadata: title, description, primaryAction.",
971
- },
972
- table: {
973
- type: "object",
974
- description: "For data-table/data-insights: { title?, columns: [{ key, label, align? }], rows, totalRows?, sampledRows?, truncated? }.",
975
- },
976
- chartSeries: {
977
- type: "object",
978
- description: "For data-chart/data-insights: { type: 'bar'|'line'|'area', title?, xKey, series: [{ key, label, color? }], data, sampled? }.",
979
- },
980
- },
981
- required: ["widget"],
982
- },
983
- },
984
- run: async (args) => dataWidgetResultSchema.parse(args),
985
- },
986
- };
987
- }
988
- /**
989
- * Creates db-* tools (db-query, db-exec, db-patch, db-schema) as native tools.
990
- * By default these let the agent inspect the app's own SQL database; raw SQL
991
- * writes are only exposed when the app explicitly opts into write mode.
992
- * Scoping to the current user/org is enforced automatically in production via
993
- * temp views.
994
- *
995
- * In dev mode template actions are invoked via bash and the agent can call
996
- * `pnpm action db-query ...` — but in production there is no bash, so these
997
- * must be registered as native tools for the agent to reach the app DB at all.
998
- */
999
- async function createDbScriptEntries(mode = "read", options = {}) {
1000
- try {
1001
- if (mode === "off")
1002
- return {};
1003
- const extensionQueryGuidance = options.extensionTools === false
1004
- ? "Extension management tools are disabled for this app; do not query or mutate the legacy tools table as a workaround."
1005
- : "For extension management, use list-extensions, update-extension, hide-extension, or delete-extension instead of querying the legacy tools table.";
1006
- const [schemaMod, queryMod] = await Promise.all([
1007
- import("../scripts/db/schema.js"),
1008
- import("../scripts/db/query.js"),
1009
- ]);
1010
- const [execMod, patchMod] = mode === "write"
1011
- ? await Promise.all([
1012
- import("../scripts/db/exec.js"),
1013
- import("../scripts/db/patch.js"),
1014
- ])
1015
- : [null, null];
1016
- const entries = {
1017
- "db-schema": wrapCliScript({
1018
- description: "Show the app's SQL schema — all tables, columns, types, indexes, and foreign keys. Use this to understand the data model before querying.",
1019
- parameters: {
1020
- type: "object",
1021
- properties: {
1022
- format: {
1023
- type: "string",
1024
- description: 'Output format: "json" or "text" (default: text)',
1025
- enum: ["json", "text"],
1026
- },
1027
- },
1028
- },
1029
- }, schemaMod.default, { readOnly: true }),
1030
- "db-query": wrapCliScript({
1031
- description: `Read from the app's own SQL database ONLY. Runs a SELECT against the app's internal tables (settings, application_state, template tables). Results are auto-scoped to the current user/org. IMPORTANT: This tool CANNOT access external data sources like data warehouses, CRMs, issue trackers, analytics platforms, calendars, mail, docs, or other third-party services. For those, use the relevant template/provider action, MCP connector, or provider-api-catalog/provider-api-docs/provider-api-request when available. If the user names a provider, that named provider wins; do not substitute a warehouse or app database copy unless they explicitly ask for it. If a table isn't in the app schema, don't try db-query — use the data-source-specific action. ${extensionQueryGuidance}`,
1032
- parameters: {
1033
- type: "object",
1034
- properties: {
1035
- sql: {
1036
- type: "string",
1037
- description: "SELECT query to run, e.g. \"SELECT key, value FROM settings WHERE key LIKE 'sql-dashboard-%'\"",
1038
- },
1039
- args: {
1040
- type: "string",
1041
- description: 'Optional JSON array of positional bind args for parameterized placeholders. Example: \'["draft","form-123"]\'',
1042
- },
1043
- format: {
1044
- type: "string",
1045
- description: 'Output format: "json" or "text" (default: text)',
1046
- enum: ["json", "text"],
1047
- },
1048
- limit: {
1049
- type: "string",
1050
- description: "Append LIMIT N if the query doesn't already have one",
1051
- },
1052
- },
1053
- required: ["sql"],
1054
- },
1055
- }, queryMod.default, { readOnly: true }),
1056
- };
1057
- if (execMod && patchMod) {
1058
- entries["db-exec"] = wrapCliScript({
1059
- description: "Write to the app's own SQL database ONLY. Runs INSERT / UPDATE / DELETE / REPLACE against the app's internal tables. For multiple related writes, pass `statements` so they run sequentially in one transaction instead of issuing several db-exec calls. Writes are auto-scoped to the current user/org, and `owner_email` / `org_id` are auto-injected on INSERT. Schema changes (CREATE/ALTER/DROP) are blocked. Never use this to backfill missing data for a read/analysis request or to create/modify users, members, roles, permissions, admin flags, or ownership; use a dedicated app action or reviewed code. IMPORTANT: This tool CANNOT write to external data sources like BigQuery, HubSpot, etc. For external services, use the appropriate template action.",
1060
- parameters: dbExecToolParameters(),
1061
- }, execMod.default);
1062
- entries["db-patch"] = wrapCliScript({
1063
- description: "Surgical patch on a large text/JSON column in the app's SQL database. Two modes: (1) text find/replace via `find`/`replace`/`edits` — best for small edits to documents, slide HTML, etc. (2) structural JSON ops via `json-ops` — STRONGLY PREFERRED when the column is JSON (dashboard configs, form schemas, slide decks) because it avoids all the brace/quote/comma surgery that text find/replace requires. Use `json-ops` to set/remove values at a JSON Pointer path, or to move/insert array items — e.g. reorder dashboard panels, add a filter, rename a field. Targets exactly one row (narrow `where` by primary key). Same per-user/org scoping as db-exec.",
1064
- parameters: {
1065
- type: "object",
1066
- properties: {
1067
- table: {
1068
- type: "string",
1069
- description: "Table name (e.g. 'settings')",
1070
- },
1071
- column: {
1072
- type: "string",
1073
- description: "Text/JSON column to patch (e.g. 'value' for settings)",
1074
- },
1075
- where: {
1076
- type: "string",
1077
- description: "WHERE clause that matches exactly one row (e.g. \"key = 'o:org1:sql-dashboard-foo'\")",
1078
- },
1079
- find: {
1080
- type: "string",
1081
- description: "Text mode: substring to find. Must match EXACTLY ONE occurrence by default (like Claude Code's Edit tool). If 0 matches, you get 'NOT FOUND'. If >1 matches, you get surrounding context for each match — widen `find` with unique context and retry. Use `all: \"true\"` to replace every occurrence.",
1082
- },
1083
- replace: {
1084
- type: "string",
1085
- description: "Text mode: replacement substring",
1086
- },
1087
- edits: {
1088
- type: "string",
1089
- description: 'Text mode batch: JSON array of {find, replace} pairs. Same uniqueness rule applies to each `find`. Example: \'[{"find":"a","replace":"b"}]\'',
1090
- },
1091
- "json-ops": {
1092
- type: "string",
1093
- description: 'JSON mode: JSON array of structural ops. Each op is {op, path, value?, from?}. `op` is one of "set", "remove", "insert", "move", "move-before". `path` / `from` use JSON Pointer ("/panels/3/title"). Examples — reorder: \'[{"op":"move","from":"/panels/7","path":"/panels/1"}]\'; edit field: \'[{"op":"set","path":"/panels/0/title","value":"New"}]\'; delete filter: \'[{"op":"remove","path":"/filters/2"}]\'; add panel: \'[{"op":"insert","path":"/panels/0","value":{"id":"p","title":"..."}}]\'. Much safer than text find/replace for JSON columns.',
1094
- },
1095
- all: {
1096
- type: "string",
1097
- description: 'Text mode: set to "true" to replace every occurrence of each `find` (default requires exactly one match)',
1098
- enum: ["true"],
1099
- },
1100
- },
1101
- required: ["table", "column", "where"],
1102
- },
1103
- }, patchMod.default);
1104
- }
1105
- return entries;
1106
- }
1107
- catch {
1108
- return {};
1109
- }
1110
- }
1111
- /**
1112
- * Creates read-only package lookup tools so agents can inspect version-matched
1113
- * framework docs and source bundled in @agent-native/core at runtime.
1114
- */
1115
- async function createDocsScriptEntries() {
1116
- const entries = {};
1117
- try {
1118
- const mod = await import("../scripts/docs/search.js");
1119
- entries["docs-search"] = wrapCliScript({
1120
- description: "Search and read agent-native framework documentation, bundled AGENTS.md, and codebase skills. Use --list to see all pages, --query to search, --slug to read a specific page. Codebase skill pages use slugs like skill-<name>.",
1121
- parameters: {
1122
- type: "object",
1123
- properties: {
1124
- query: {
1125
- type: "string",
1126
- description: "Search term to find relevant docs (e.g. 'actions', 'authentication', 'database')",
1127
- },
1128
- slug: {
1129
- type: "string",
1130
- description: "Read a specific doc page by slug (e.g. 'actions', 'authentication', 'database')",
1131
- },
1132
- list: {
1133
- type: "string",
1134
- description: 'Set to "true" to list all available doc pages',
1135
- enum: ["true"],
1136
- },
1137
- },
1138
- },
1139
- }, mod.default, { readOnly: true });
1140
- }
1141
- catch {
1142
- // Keep source-search available if docs-search fails during a partial build.
1143
- }
1144
- try {
1145
- const mod = await import("../scripts/docs/source-search.js");
1146
- entries["source-search"] = wrapCliScript({
1147
- description: "Search and read the packaged Agent Native source corpus under node_modules/@agent-native/core/corpus. Use --list for sections, --query to search core/template source, and --path to read a file.",
1148
- parameters: {
1149
- type: "object",
1150
- properties: {
1151
- query: {
1152
- type: "string",
1153
- description: "Search term to find relevant core or template source (e.g. 'defineAction', 'useActionQuery', 'view-screen').",
1154
- },
1155
- path: {
1156
- type: "string",
1157
- description: "Read a specific corpus file or list a directory (e.g. 'templates/plan/AGENTS.md' or 'core/src/action.ts').",
1158
- },
1159
- list: {
1160
- type: "string",
1161
- description: 'Set to "true" to list corpus sections',
1162
- enum: ["true"],
1163
- },
1164
- },
1165
- },
1166
- }, mod.default, { readOnly: true });
1167
- }
1168
- catch {
1169
- // Older package installs may not have the corpus/search script yet.
1170
- }
1171
- return entries;
1172
- }
1173
- /**
1174
- * Creates resource ScriptEntries available in both prod and dev modes.
1175
- */
1176
- function shouldDefaultResourceWriteToWorkspace(path) {
1177
- const normalized = path.replace(/^\/+/, "");
1178
- return (normalized === "AGENTS.md" ||
1179
- normalized === "LEARNINGS.md" ||
1180
- normalized.startsWith("memory/") ||
1181
- normalized.startsWith("skills/") ||
1182
- normalized.startsWith("jobs/") ||
1183
- normalized.startsWith("agents/") ||
1184
- normalized.startsWith("remote-agents/"));
1185
- }
1186
- async function createResourceScriptEntries() {
1187
- try {
1188
- const [list, read, effective, write, del, saveMem, delMem, store] = await Promise.all([
1189
- import("../scripts/resources/list.js"),
1190
- import("../scripts/resources/read.js"),
1191
- import("../scripts/resources/effective.js"),
1192
- import("../scripts/resources/write.js"),
1193
- import("../scripts/resources/delete.js"),
1194
- import("../scripts/resources/save-memory.js"),
1195
- import("../scripts/resources/delete-memory.js"),
1196
- import("../resources/store.js"),
1197
- ]);
1198
- // Wrap each CLI runner so it captures stdout and converts args properly
1199
- const listEntry = wrapCliScript({
1200
- description: "",
1201
- parameters: { type: "object", properties: {} },
1202
- }, list.default, { readOnly: true });
1203
- const readEntry = wrapCliScript({
1204
- description: "",
1205
- parameters: { type: "object", properties: {} },
1206
- }, read.default, { readOnly: true });
1207
- const writeEntry = wrapCliScript({
1208
- description: "",
1209
- parameters: { type: "object", properties: {} },
1210
- }, write.default);
1211
- const effectiveEntry = wrapCliScript({
1212
- description: "",
1213
- parameters: { type: "object", properties: {} },
1214
- }, effective.default, { readOnly: true });
1215
- const deleteEntry = wrapCliScript({
1216
- description: "",
1217
- parameters: { type: "object", properties: {} },
1218
- }, del.default);
1219
- return {
1220
- resources: {
1221
- tool: {
1222
- description: 'Manage workspace resources. Actions: "list" (browse visible files), "read" (get contents), "effective" (show workspace -> organization/app -> personal inheritance for a path), "write" (create/update personal or shared; workspace only for local file mode control files), "promote" (make agent scratch visible), "delete" (remove personal or shared; workspace only for local file mode control files). Agent scratch writes are hidden from the Workspace view by default; use visibility="workspace" only for files the user explicitly wants to keep/manage.',
1223
- parameters: {
1224
- type: "object",
1225
- properties: {
1226
- action: {
1227
- type: "string",
1228
- description: "The operation to perform",
1229
- enum: [
1230
- "list",
1231
- "read",
1232
- "effective",
1233
- "write",
1234
- "promote",
1235
- "delete",
1236
- ],
1237
- },
1238
- path: {
1239
- type: "string",
1240
- description: "Resource path (e.g. 'LEARNINGS.md', 'notes/ideas.md'). Required for read/write/delete.",
1241
- },
1242
- content: {
1243
- type: "string",
1244
- description: "Content to write. Required for write.",
1245
- },
1246
- scope: {
1247
- type: "string",
1248
- description: "personal, shared, workspace, or all (default varies by action). Workspace is read-only when inherited from Dispatch; in local file mode AGENTS.md, agent-native.json, mcp.config.json, .mcp.json, and skills/ are writable.",
1249
- enum: ["personal", "shared", "workspace", "all"],
1250
- },
1251
- prefix: {
1252
- type: "string",
1253
- description: "Filter by path prefix when listing (e.g. 'notes/')",
1254
- },
1255
- mime: {
1256
- type: "string",
1257
- description: "MIME type for write (default: inferred from extension)",
1258
- },
1259
- format: {
1260
- type: "string",
1261
- description: 'Output format for list: "json" or "text" (default: text)',
1262
- enum: ["json", "text"],
1263
- },
1264
- visibility: {
1265
- type: "string",
1266
- description: 'Visibility for write: "agent_scratch" for internal working files, "workspace" for user-requested files. Defaults to agent_scratch except durable instruction/skill/job/memory paths.',
1267
- enum: ["workspace", "agent_scratch"],
1268
- },
1269
- includeAgentScratch: {
1270
- type: "boolean",
1271
- description: "Include hidden agent scratch files when listing.",
1272
- },
1273
- },
1274
- required: ["action"],
1275
- },
1276
- },
1277
- run: async (args) => {
1278
- const { action: a, ...rest } = args;
1279
- if (a === "list")
1280
- return listEntry.run(rest);
1281
- if (a === "read") {
1282
- if (!rest.path)
1283
- return "Error: path is required for read";
1284
- return readEntry.run(rest);
1285
- }
1286
- if (a === "effective") {
1287
- if (!rest.path)
1288
- return "Error: path is required for effective";
1289
- return effectiveEntry.run(rest);
1290
- }
1291
- if (a === "write") {
1292
- if (!rest.path ||
1293
- rest.content === undefined ||
1294
- rest.content === null)
1295
- return "Error: path and content are required for write";
1296
- rest.createdBy = "agent";
1297
- rest.visibility =
1298
- rest.visibility ??
1299
- (shouldDefaultResourceWriteToWorkspace(String(rest.path))
1300
- ? "workspace"
1301
- : "agent_scratch");
1302
- const runCtx = getRequestRunContext();
1303
- if (runCtx?.threadId)
1304
- rest.threadId = runCtx.threadId;
1305
- return writeEntry.run(rest);
1306
- }
1307
- if (a === "promote") {
1308
- if (!rest.path)
1309
- return "Error: path is required for promote";
1310
- const scope = rest.scope ?? "personal";
1311
- if (scope === "workspace" || scope === "all") {
1312
- return "Error: promote supports personal or shared scope only";
1313
- }
1314
- const owner = scope === "shared"
1315
- ? store.sharedResourceOwner(getRequestOrgId())
1316
- : (getRequestRunContext()?.owner ??
1317
- getRequestUserEmail() ??
1318
- process.env.AGENT_USER_EMAIL);
1319
- if (!owner) {
1320
- return "Error: promote requires an authenticated user";
1321
- }
1322
- const resource = await store.resourceGetByPath(owner, String(rest.path));
1323
- if (!resource) {
1324
- return `Resource not found: ${rest.path}`;
1325
- }
1326
- const promoted = await store.resourcePut(owner, resource.path, resource.content, resource.mimeType, {
1327
- createdBy: resource.createdBy,
1328
- visibility: "workspace",
1329
- threadId: resource.threadId,
1330
- runId: resource.runId,
1331
- expiresAt: null,
1332
- metadata: resource.metadata,
1333
- });
1334
- return `Promoted resource: ${promoted.path}`;
1335
- }
1336
- if (a === "delete") {
1337
- if (!rest.path)
1338
- return "Error: path is required for delete";
1339
- return deleteEntry.run(rest);
1340
- }
1341
- return `Error: unknown action "${a}". Use: list, read, write, promote, delete`;
1342
- },
1343
- },
1344
- "save-memory": wrapCliScript({
1345
- description: "Save a memory for future conversations. Creates or updates a memory file and its index entry. Use proactively when you learn preferences, corrections, project context, or references.",
1346
- parameters: {
1347
- type: "object",
1348
- properties: {
1349
- name: {
1350
- type: "string",
1351
- description: "Short kebab-case identifier (e.g. 'coding-style', 'deploy-process'). Used as the filename.",
1352
- },
1353
- type: {
1354
- type: "string",
1355
- description: "Memory category",
1356
- enum: ["user", "feedback", "project", "reference"],
1357
- },
1358
- description: {
1359
- type: "string",
1360
- description: "One-line summary shown in the memory index (keep under 80 chars)",
1361
- },
1362
- content: {
1363
- type: "string",
1364
- description: "The memory content in markdown. For updates, read first and provide full updated content.",
1365
- },
1366
- },
1367
- required: ["name", "type", "description", "content"],
1368
- },
1369
- }, saveMem.default),
1370
- "delete-memory": wrapCliScript({
1371
- description: "Delete a memory entry and remove it from the memory index.",
1372
- parameters: {
1373
- type: "object",
1374
- properties: {
1375
- name: {
1376
- type: "string",
1377
- description: "The memory name to delete (e.g. 'coding-style')",
1378
- },
1379
- },
1380
- required: ["name"],
1381
- },
1382
- }, delMem.default),
1383
- };
1384
- }
1385
- catch {
1386
- // Resources not available — skip silently
1387
- return {};
1388
- }
1389
- }
1390
- /**
1391
- * Creates a unified chat-history ActionEntry that dispatches to search, open,
1392
- * rename, or lightweight organization actions.
1393
- */
1394
- async function createChatScriptEntries() {
1395
- try {
1396
- const [searchMod, openMod] = await Promise.all([
1397
- import("../scripts/chat/search-chats.js"),
1398
- import("../scripts/chat/open-chat.js"),
1399
- ]);
1400
- const searchEntry = wrapCliScript({
1401
- description: "Search or list past agent chat threads.",
1402
- parameters: {
1403
- type: "object",
1404
- properties: {
1405
- query: {
1406
- type: "string",
1407
- description: "Search term to find chats by title, preview, or content",
1408
- },
1409
- limit: {
1410
- type: "string",
1411
- description: "Max number of results (default: 20)",
1412
- },
1413
- format: {
1414
- type: "string",
1415
- description: "Output format",
1416
- enum: ["json", "text"],
1417
- },
1418
- includeArchived: {
1419
- type: "boolean",
1420
- description: "Also include archived chats in the results. Archived chats are excluded by default.",
1421
- },
1422
- },
1423
- },
1424
- }, searchMod.default);
1425
- const openEntry = wrapCliScript({
1426
- description: "Open a chat thread in the UI.",
1427
- parameters: {
1428
- type: "object",
1429
- properties: {
1430
- id: {
1431
- type: "string",
1432
- description: "The chat thread ID to open",
1433
- },
1434
- },
1435
- required: ["id"],
1436
- },
1437
- }, openMod.default);
1438
- return {
1439
- "chat-history": {
1440
- tool: {
1441
- description: "Manage past agent chat threads. Use action 'search' to find previous conversations by keyword, 'open' to open a thread in the UI, or 'rename'/'pin'/'unpin'/'archive' to organize history.",
1442
- parameters: {
1443
- type: "object",
1444
- properties: {
1445
- action: {
1446
- type: "string",
1447
- description: "The operation to perform",
1448
- enum: ["search", "open", "rename", "pin", "unpin", "archive"],
1449
- },
1450
- query: {
1451
- type: "string",
1452
- description: "(search) Search term to find chats by title, preview, or content",
1453
- },
1454
- limit: {
1455
- type: "string",
1456
- description: "(search) Max number of results (default: 20)",
1457
- },
1458
- format: {
1459
- type: "string",
1460
- description: "(search) Output format",
1461
- enum: ["json", "text"],
1462
- },
1463
- includeArchived: {
1464
- type: "boolean",
1465
- description: "(search) Also include archived chats in the results. Archived chats are excluded by default, matching the 'archive' action's effect on the chat list.",
1466
- },
1467
- id: {
1468
- type: "string",
1469
- description: "(open, rename, pin, unpin, archive) The chat thread ID to manage",
1470
- },
1471
- title: {
1472
- type: "string",
1473
- description: "(rename) New chat title",
1474
- },
1475
- },
1476
- required: ["action"],
1477
- },
1478
- },
1479
- run: async (args) => {
1480
- if (args?.action === "open") {
1481
- return openEntry.run(args);
1482
- }
1483
- if (args?.action === "rename" ||
1484
- args?.action === "pin" ||
1485
- args?.action === "unpin" ||
1486
- args?.action === "archive") {
1487
- const id = typeof args?.id === "string" ? args.id : "";
1488
- if (!id)
1489
- return "Missing required id.";
1490
- const owner = getRequestRunContext()?.owner ?? getRequestUserEmail() ?? "";
1491
- if (!owner)
1492
- return "No authenticated user is available.";
1493
- const thread = await resolveThreadAccess(owner, id, "editor", {
1494
- orgId: getRequestOrgId(),
1495
- });
1496
- if (!thread) {
1497
- return `Chat thread "${id}" not found.`;
1498
- }
1499
- const title = thread.title || thread.preview || "(untitled)";
1500
- if (args.action === "rename") {
1501
- const nextTitle = typeof args?.title === "string"
1502
- ? args.title.replace(/\s+/g, " ").trim().slice(0, 160)
1503
- : "";
1504
- if (!nextTitle)
1505
- return "Missing required title.";
1506
- const renamed = await renameThread(id, nextTitle);
1507
- if (!renamed)
1508
- return `Chat thread "${id}" could not be renamed.`;
1509
- return `Renamed chat "${title}" to "${nextTitle}".`;
1510
- }
1511
- if (args.action === "archive") {
1512
- const archived = await setThreadArchived(id, true);
1513
- if (!archived)
1514
- return `Chat thread "${id}" could not be archived.`;
1515
- return `Archived chat: ${title}`;
1516
- }
1517
- const pinned = await setThreadPinned(id, args.action === "pin");
1518
- if (!pinned)
1519
- return `Chat thread "${id}" could not be updated.`;
1520
- return `${args.action === "pin" ? "Pinned" : "Unpinned"} chat: ${title}`;
1521
- }
1522
- return searchEntry.run(args);
1523
- },
1524
- },
1525
- };
1526
- }
1527
- catch {
1528
- return {};
1529
- }
1530
- }
1531
- /**
1532
- * Creates the consolidated manage-agent-engine tool (list / set / test).
1533
- * Let the agent inspect and configure the active LLM engine.
1534
- */
1535
- async function createAgentEngineScriptEntries(appId) {
1536
- try {
1537
- const mod = await import("../scripts/agent-engines/manage-agent-engine.js");
1538
- return {
1539
- "manage-agent-engine": {
1540
- tool: mod.tool,
1541
- run: (args) => mod.run({
1542
- ...args,
1543
- appId: typeof args.appId === "string" && args.appId.trim()
1544
- ? args.appId
1545
- : (appId ?? ""),
1546
- }),
1547
- },
1548
- };
1549
- }
1550
- catch {
1551
- return {};
1552
- }
1553
- }
1554
- /**
1555
- * Creates the manage-agent-loop-settings tool. Lets the agent inspect and
1556
- * configure the loop step limit it may hit on long-running work.
1557
- */
1558
- async function createAgentLoopSettingsScriptEntries() {
1559
- try {
1560
- const mod = await import("../scripts/manage-agent-loop-settings.js");
1561
- return {
1562
- "manage-agent-loop-settings": { tool: mod.tool, run: mod.run },
1563
- };
1564
- }
1565
- catch {
1566
- return {};
1567
- }
1568
- }
1569
- /**
1570
- * Creates the call-agent ActionEntry for cross-agent A2A communication.
1571
- * Binds selfAppId so the agent cannot call itself via call-agent.
1572
- */
1573
- async function createCallAgentScriptEntry(selfAppId) {
1574
- try {
1575
- const mod = await import("../scripts/call-agent.js");
1576
- return {
1577
- "call-agent": {
1578
- tool: mod.tool,
1579
- run: (args, context) => mod.run(args, context, selfAppId),
1580
- },
1581
- };
1582
- }
1583
- catch {
1584
- return {};
1585
- }
1586
- }
1587
- function createBuilderBrowserTool(deps) {
1588
- const extensionRequestGuidance = deps.extensionTools === false
1589
- ? "Do NOT call this for requests to create or edit user-authored extensions/widgets/dashboards/calculators/mini-apps; extension tools are disabled for this app, and Builder is only for source-code changes to the host app. "
1590
- : "Do NOT call this for a self-contained extension/widget/dashboard/calculator/mini-app or an extension that fits an existing named slot; those use create-extension/update-extension instead. If the requested result requires changing the host UI or placing UI where no named slot exists, it IS a source-code change: call this through the normal flow even when the user describes it as an extension. Never stop at saying an extension cannot do it. ";
1591
- const setBuiltinForCurrentUser = async (id, enabled) => {
1592
- const email = getRequestUserEmail();
1593
- if (!email) {
1594
- return {
1595
- ok: false,
1596
- error: "not-signed-in",
1597
- message: "You must be signed in to change built-in MCP tools.",
1598
- };
1599
- }
1600
- const enabledIds = await setBuiltinMcpCapabilityEnabled("user", email, id, enabled);
1601
- const manager = getGlobalMcpManager();
1602
- if (manager) {
1603
- await manager.reconfigure(await buildMergedConfig());
1604
- }
1605
- return { ok: true, enabledIds: enabledIds ?? [] };
1606
- };
1607
- const entries = {
1608
- "connect-builder": {
1609
- tool: {
1610
- description: `Render a Builder.io card inline in the chat. Call this as the first step (no code exploration or planning needed) when the user asks to modify the APP'S OWN SOURCE CODE: add a feature, change the UI chrome, edit a React component, add a route, add an integration, fix a bug in the app itself, or anything else that requires source-file edits while in hosted/production mode. ${extensionRequestGuidance}Do NOT call this for content the app is meant to produce — creating a video, generating a design, drafting an email, building a slide deck, making a dashboard, etc. — those run through the app's own domain actions, not Builder. Do NOT mention 'click Send to Builder' in your response unless this card is already in the conversation. The tool result includes \`builderEnabled\`; treat \`true\` as "Builder Cloud Agents can take the code-change handoff" and \`false\` as "this still needs a code change, but no Builder Cloud Agent can run here." If Builder is connected and Builder Cloud Agents are available, the card shows a 'Send to Builder' button that hands the work off to Builder's cloud agent and returns a branch URL. If \`builderEnabled\` is false, the card still renders but shows the code-change fallback: "This requires a code change. Edit locally or use Builder.io to edit this code in the cloud and continue customizing the app any way you like." Never tell the user to enable Builder Cloud Agents in Builder org settings or beta settings, and do not claim the Builder card has everything, is pre-loaded for handoff, or can run the cloud agent when \`builderEnabled\` is false. When you call this for a code-change request, pass the user's request verbatim as the \`prompt\` arg so the card can forward it to Builder unchanged when cloud agents are available.`,
1611
- parameters: {
1612
- type: "object",
1613
- properties: {
1614
- prompt: {
1615
- type: "string",
1616
- description: "The user's feature / change request, verbatim. Forwarded to Builder's cloud agent when the user clicks Send. Omit only for generic 'connect Builder' requests that aren't tied to a specific code change.",
1617
- },
1618
- },
1619
- },
1620
- },
1621
- run: async (args) => {
1622
- const { getBuilderCredentialAuthFailure, resolveBuilderCredentials } = await import("./credential-provider.js");
1623
- const creds = await resolveBuilderCredentials();
1624
- const authFailure = await getBuilderCredentialAuthFailure(creds);
1625
- const configured = !!(creds.privateKey &&
1626
- creds.publicKey &&
1627
- !authFailure);
1628
- const branchProjectId = await resolveBuilderBranchProjectId();
1629
- const prompt = typeof args?.prompt === "string" ? args.prompt : "";
1630
- const origin = deps.getOrigin();
1631
- const ownerEmail = deps.getOwner?.() ?? getRequestUserEmail();
1632
- return JSON.stringify({
1633
- kind: "connect-builder-card",
1634
- configured,
1635
- builderEnabled: !!branchProjectId,
1636
- connectUrl: getBuilderBrowserConnectUrlForOwner(origin, ownerEmail),
1637
- orgName: creds.orgName || null,
1638
- prompt,
1639
- });
1640
- },
1641
- },
1642
- "set-browser-control": {
1643
- tool: {
1644
- description: "Enable or disable built-in browser-control MCP tools for the current user. Call this when the user asks to test, screenshot, inspect, or interact with a web page and browser tools are not available; confirm once before enabling. Prefer the chrome-devtools backend for live logged-in Chrome, and use playwright when an isolated browser is better.",
1645
- parameters: {
1646
- type: "object",
1647
- properties: {
1648
- enabled: {
1649
- type: "boolean",
1650
- description: "Whether browser-control tools should be enabled.",
1651
- },
1652
- backend: {
1653
- type: "string",
1654
- enum: ["chrome-devtools", "playwright"],
1655
- description: "Browser backend to enable. Defaults to chrome-devtools.",
1656
- },
1657
- },
1658
- required: ["enabled"],
1659
- },
1660
- },
1661
- run: async (args) => {
1662
- const parsed = args && typeof args === "object"
1663
- ? args
1664
- : {};
1665
- const enabled = parsed.enabled !== false;
1666
- const requestedBackend = typeof parsed.backend === "string" ? parsed.backend : undefined;
1667
- const backend = requestedBackend === "playwright" ? "playwright" : "chrome-devtools";
1668
- const targetId = backend === "playwright"
1669
- ? "browser-playwright"
1670
- : "browser-chrome-devtools";
1671
- if (!enabled) {
1672
- const chrome = await setBuiltinForCurrentUser("browser-chrome-devtools", false);
1673
- if (!chrome.ok)
1674
- return JSON.stringify(chrome);
1675
- const playwright = await setBuiltinForCurrentUser("browser-playwright", false);
1676
- return JSON.stringify({
1677
- ...playwright,
1678
- enabled: false,
1679
- message: "Browser-control MCP tools are disabled.",
1680
- });
1681
- }
1682
- const result = await setBuiltinForCurrentUser(targetId, true);
1683
- return JSON.stringify({
1684
- ...result,
1685
- enabled: true,
1686
- backend,
1687
- message: backend === "chrome-devtools"
1688
- ? "Chrome DevTools MCP is enabled. Browser tools will be available on the next action when Chrome remote debugging is available."
1689
- : "Playwright MCP is enabled. Browser tools will be available on the next action in an isolated Playwright browser.",
1690
- });
1691
- },
1692
- },
1693
- "set-computer-use": {
1694
- tool: {
1695
- description: "Enable or disable built-in Computer Use MCP tools for the current user. Call only after the user explicitly asks to let the agent control local desktop apps. macOS may require Screen Recording and Accessibility permissions.",
1696
- parameters: {
1697
- type: "object",
1698
- properties: {
1699
- enabled: {
1700
- type: "boolean",
1701
- description: "Whether Computer Use tools should be enabled.",
1702
- },
1703
- },
1704
- required: ["enabled"],
1705
- },
1706
- },
1707
- run: async (args) => {
1708
- const parsed = args && typeof args === "object"
1709
- ? args
1710
- : {};
1711
- const enabled = parsed.enabled !== false;
1712
- if (enabled && process.platform !== "darwin") {
1713
- return JSON.stringify({
1714
- ok: false,
1715
- error: "unsupported-platform",
1716
- message: "Computer Use is currently available only on macOS.",
1717
- });
1718
- }
1719
- const result = await setBuiltinForCurrentUser("computer-use", enabled);
1720
- return JSON.stringify({
1721
- ...result,
1722
- enabled,
1723
- message: enabled
1724
- ? "Computer Use MCP is enabled. If macOS prompts, grant Screen Recording and Accessibility permission in System Settings > Privacy & Security."
1725
- : "Computer Use MCP is disabled.",
1726
- });
1727
- },
1728
- },
1729
- "activate-browser": {
1730
- tool: {
1731
- description: "Activate browser automation tools. Call this when you need to interact with a real browser — e.g. to extract design tokens from a rendered page, take screenshots, read computed styles from JS-heavy sites, or test a live URL. After activation, chrome-devtools MCP tools (navigate, click, evaluate_script, take_screenshot, etc.) become available on your next action. Requires Builder.io connection.",
1732
- parameters: {
1733
- type: "object",
1734
- properties: {
1735
- sessionId: {
1736
- type: "string",
1737
- description: "Optional session identifier for the browser connection. Auto-generated if omitted.",
1738
- },
1739
- },
1740
- },
1741
- },
1742
- run: async (args) => {
1743
- const { resolveBuilderCredentials } = await import("./credential-provider.js");
1744
- const creds = await resolveBuilderCredentials();
1745
- if (!creds.privateKey || !creds.publicKey) {
1746
- return JSON.stringify({
1747
- error: "builder-not-connected",
1748
- message: "Builder.io is not connected. Call `connect-builder` first to enable browser automation.",
1749
- });
1750
- }
1751
- const { requestBuilderBrowserConnection } = await import("./builder-browser.js");
1752
- const sessionId = (typeof args?.sessionId === "string" && args.sessionId) ||
1753
- `an-browser-${Date.now()}`;
1754
- let connection;
1755
- try {
1756
- connection = await requestBuilderBrowserConnection({ sessionId });
1757
- }
1758
- catch (err) {
1759
- return JSON.stringify({
1760
- error: "browser-connection-failed",
1761
- message: `Failed to get browser connection: ${err?.message ?? err}`,
1762
- });
1763
- }
1764
- const wsUrl = connection.wsUrl;
1765
- if (!wsUrl) {
1766
- return JSON.stringify({
1767
- error: "no-ws-url",
1768
- message: "Browser connection did not return a WebSocket URL.",
1769
- });
1770
- }
1771
- const manager = getGlobalMcpManager();
1772
- if (!manager) {
1773
- return JSON.stringify({
1774
- error: "no-mcp-manager",
1775
- message: "MCP manager is not available.",
1776
- });
1777
- }
1778
- // Add chrome-devtools-mcp server pointing at the provisioned browser
1779
- const currentConfig = manager.getConfig();
1780
- const servers = { ...(currentConfig?.servers ?? {}) };
1781
- servers["chrome-devtools"] = {
1782
- command: "npx",
1783
- args: [
1784
- "-y",
1785
- "chrome-devtools-mcp@0.26.0",
1786
- "--wsEndpoint",
1787
- wsUrl,
1788
- "--categoryEmulation=false",
1789
- ],
1790
- type: "stdio",
1791
- };
1792
- await manager.reconfigure({
1793
- servers,
1794
- source: currentConfig?.source ?? "runtime",
1795
- });
1796
- return JSON.stringify({
1797
- success: true,
1798
- message: "Browser activated. Chrome DevTools MCP tools (mcp__chrome-devtools__*) are now available. Use them on your next action to navigate pages, read DOM, take screenshots, evaluate JavaScript, etc.",
1799
- wsUrl,
1800
- sessionId,
1801
- });
1802
- },
1803
- },
1804
- };
1805
- if (!areBuiltinMcpCapabilitiesSupported()) {
1806
- delete entries["set-browser-control"];
1807
- delete entries["set-computer-use"];
1808
- }
1809
- return entries;
1810
- }
1811
- /**
1812
- * Creates the unified `agent-teams` tool that consolidates all sub-agent
1813
- * orchestration behind a single tool with an `action` parameter.
1814
- */
1815
- function createTeamTools(deps) {
1816
- return {
1817
- "agent-teams": {
1818
- tool: {
1819
- description: "Manage background sub-agent tasks. Use action 'spawn' to start a new sub-agent, 'status' to check progress, 'read-result' to get a finished task's output, 'send' to message a running sub-agent, or 'list' to see all tasks. A successful spawn only means the task started and is running; do not report it as finished until status/read-result shows a terminal status.",
1820
- parameters: {
1821
- type: "object",
1822
- properties: {
1823
- action: {
1824
- type: "string",
1825
- enum: ["spawn", "status", "read-result", "send", "list"],
1826
- description: "The operation to perform",
1827
- },
1828
- task: {
1829
- type: "string",
1830
- description: "(spawn) Clear description of what the sub-agent should accomplish",
1831
- },
1832
- instructions: {
1833
- type: "string",
1834
- description: "(spawn) Optional additional instructions or context for the sub-agent",
1835
- },
1836
- name: {
1837
- type: "string",
1838
- description: "(spawn) Short name for the sub-agent tab (e.g. 'Research', 'Draft email'). If omitted, derived from the task.",
1839
- },
1840
- agent: {
1841
- type: "string",
1842
- description: "(spawn) Optional custom agent profile from agents/*.md to use for this task.",
1843
- },
1844
- taskId: {
1845
- type: "string",
1846
- description: "(status, read-result, send) The task ID returned by a previous spawn",
1847
- },
1848
- message: {
1849
- type: "string",
1850
- description: "(send) Message to send to the sub-agent",
1851
- },
1852
- },
1853
- required: ["action"],
1854
- },
1855
- },
1856
- run: async (args) => {
1857
- const action = args.action;
1858
- // ── spawn ──────────────────────────────────────────────
1859
- if (action === "spawn") {
1860
- if (!args.task)
1861
- throw new Error("'task' is required for spawn");
1862
- // Capture the send function NOW (at spawn time) so that
1863
- // concurrent runs don't clobber each other's send reference.
1864
- const capturedSend = deps.getSend();
1865
- const { spawnTask } = await import("./agent-teams.js");
1866
- // Filter out the team tool so sub-agents can't spawn sub-agents
1867
- const subAgentActions = Object.fromEntries(Object.entries(deps.getActions()).filter(([name]) => name !== "agent-teams"));
1868
- let instructions = args.instructions;
1869
- let selectedModel = deps.getModel();
1870
- let selectedName = args.name || "";
1871
- if (args.agent) {
1872
- const { findAccessibleCustomAgent } = await import("../resources/agents.js");
1873
- const profile = await findAccessibleCustomAgent(deps.getOwner(), args.agent);
1874
- if (!profile) {
1875
- throw new Error(`Custom agent not found: ${args.agent}`);
1876
- }
1877
- const profileInstructions = `## Custom Agent Profile: ${profile.name}\n\n` +
1878
- (profile.description ? `${profile.description}\n\n` : "") +
1879
- profile.instructions;
1880
- instructions = instructions
1881
- ? `${profileInstructions}\n\n## Extra Task Context\n\n${instructions}`
1882
- : profileInstructions;
1883
- selectedModel = profile.model ?? selectedModel;
1884
- selectedName = selectedName || profile.name;
1885
- }
1886
- const task = await spawnTask({
1887
- description: args.task,
1888
- instructions,
1889
- ownerEmail: deps.getOwner(),
1890
- systemPrompt: deps.getSystemPrompt(),
1891
- actions: subAgentActions,
1892
- engine: deps.getEngine(),
1893
- model: selectedModel,
1894
- name: selectedName || undefined,
1895
- parentThreadId: deps.getParentThreadId(),
1896
- parentSend: (event) => {
1897
- if (capturedSend)
1898
- capturedSend(event);
1899
- },
1900
- });
1901
- return JSON.stringify({
1902
- taskId: task.taskId,
1903
- threadId: task.threadId,
1904
- runId: task.runId,
1905
- status: task.status,
1906
- parentThreadId: task.parentThreadId,
1907
- state: "launched_pending_completion",
1908
- message: "Sub-agent launched and is still running. Use status or read-result later; do not describe this task as completed from the spawn response alone.",
1909
- description: task.description,
1910
- name: task.name ?? selectedName,
1911
- });
1912
- }
1913
- // ── status ─────────────────────────────────────────────
1914
- if (action === "status") {
1915
- if (!args.taskId)
1916
- throw new Error("'taskId' is required for status");
1917
- const { getTask } = await import("./agent-teams.js");
1918
- const task = await getTask(args.taskId);
1919
- if (!task)
1920
- return JSON.stringify({ error: "Task not found" });
1921
- return JSON.stringify({
1922
- taskId: task.taskId,
1923
- threadId: task.threadId,
1924
- parentThreadId: task.parentThreadId,
1925
- status: task.status,
1926
- description: task.description,
1927
- name: task.name,
1928
- preview: task.preview,
1929
- currentStep: task.currentStep,
1930
- summary: task.summary,
1931
- });
1932
- }
1933
- // ── read-result ────────────────────────────────────────
1934
- if (action === "read-result") {
1935
- if (!args.taskId)
1936
- throw new Error("'taskId' is required for read-result");
1937
- const { getTask } = await import("./agent-teams.js");
1938
- const task = await getTask(args.taskId);
1939
- if (!task)
1940
- return JSON.stringify({ error: "Task not found" });
1941
- if (task.status === "running") {
1942
- return JSON.stringify({
1943
- status: "running",
1944
- taskId: task.taskId,
1945
- threadId: task.threadId,
1946
- parentThreadId: task.parentThreadId,
1947
- name: task.name,
1948
- preview: task.preview,
1949
- message: "Task is still running. Do not report it as complete; use status/read-result later.",
1950
- });
1951
- }
1952
- return JSON.stringify({
1953
- taskId: task.taskId,
1954
- threadId: task.threadId,
1955
- parentThreadId: task.parentThreadId,
1956
- name: task.name,
1957
- status: task.status,
1958
- summary: task.summary,
1959
- preview: task.preview,
1960
- });
1961
- }
1962
- // ── send ───────────────────────────────────────────────
1963
- if (action === "send") {
1964
- if (!args.taskId)
1965
- throw new Error("'taskId' is required for send");
1966
- if (!args.message)
1967
- throw new Error("'message' is required for send");
1968
- const { sendToTask } = await import("./agent-teams.js");
1969
- const result = await sendToTask(args.taskId, args.message);
1970
- return JSON.stringify(result);
1971
- }
1972
- // ── list ───────────────────────────────────────────────
1973
- if (action === "list") {
1974
- const { listTasks } = await import("./agent-teams.js");
1975
- const tasks = await listTasks();
1976
- if (tasks.length === 0) {
1977
- return "No sub-agent tasks.";
1978
- }
1979
- return JSON.stringify(tasks.map((t) => ({
1980
- taskId: t.taskId,
1981
- threadId: t.threadId,
1982
- parentThreadId: t.parentThreadId,
1983
- name: t.name,
1984
- description: t.description,
1985
- status: t.status,
1986
- currentStep: t.currentStep,
1987
- hasResult: t.summary.length > 0,
1988
- })), null, 2);
1989
- }
1990
- throw new Error(`Unknown action '${action}'. Use one of: spawn, status, read-result, send, list`);
1991
- },
1992
- },
1993
- };
1994
- }
1995
- /**
1996
- * Run an A2A-delegated agent turn with the same final-response guard used by
1997
- * the app's interactive chat surface.
1998
- *
1999
- * Keeping this in one helper prevents delegated calls from silently bypassing
2000
- * template guarantees such as Analytics' requirement to query real data
2001
- * before presenting metrics or exhaustive provider conclusions.
2002
- */
2003
- export function runA2AAgentLoop(runOptions, pluginOptions, timeoutOptions, runner = runAgentLoopDirectWithSoftTimeout) {
2004
- return runner({
2005
- ...runOptions,
2006
- finalResponseGuard: pluginOptions.finalResponseGuard,
2007
- }, pluginOptions.runSoftTimeoutMs, timeoutOptions);
2008
- }
2009
- /**
2010
- * Keep delegated A2A turns on the same compact initial tool surface as
2011
- * interactive chat. `tool-search` remains in the initial set, while the
2012
- * complete registry is supplied separately so the run loop can load a matched
2013
- * schema after a tool-search result.
2014
- */
2015
- export function createA2AEngineToolSurface(availableTools, initialToolNames) {
2016
- return {
2017
- tools: filterInitialEngineTools(availableTools, initialToolNames),
2018
- availableTools,
2019
- };
2020
- }
2021
- /**
2022
- * Verbose framework sections returned by the `get-framework-context` tool.
2023
- * Keyed by topic so the agent can request specific sections.
2024
- * Not template-specific — lives outside buildFrameworkPrompts().
2025
- */
2026
- const FRAMEWORK_CONTEXT_SECTIONS = {
2027
- embeds: `### Inline Embeds
2028
-
2029
- You can embed an interactive view inline in your chat reply by writing an \`embed\` fenced code block. The chat renderer swaps the fence for a sandboxed iframe pointing at a route inside this app.
2030
-
2031
- Syntax:
2032
-
2033
- \`\`\`\`
2034
- \`\`\`embed
2035
- src: /some/path?param=value
2036
- aspect: 16/9
2037
- title: Optional label
2038
- \`\`\`
2039
- \`\`\`\`
2040
-
2041
- Keys:
2042
- - \`src\` (required) — **must be a same-origin path starting with \`/\`**. Cross-origin URLs are blocked. No \`javascript:\` or \`data:\` URLs.
2043
- - \`aspect\` (optional) — one of \`16/9\` (default), \`4/3\`, \`3/2\`, \`2/1\`, \`21/9\`, \`1/1\`.
2044
- - \`title\` (optional) — accessible label / hover tooltip.
2045
- - \`height\` (optional) — fixed pixel height when aspect ratio isn't a good fit.
2046
-
2047
- Use for charts, visualizations, previews. Don't use for simple text/tables or external sites.`,
2048
- "chat-history": `### Chat History
2049
-
2050
- You can search and restore previous chat conversations using \`chat-history\`:
2051
- - \`chat-history\` (action: "search") — Search or list past chat threads by keyword. Archived threads are excluded by default; pass \`includeArchived: true\` to also see them.
2052
- - \`chat-history\` (action: "open") — Open a chat thread in the UI as a new tab and focus it
2053
- - \`chat-history\` (actions: "rename", "pin", "unpin", "archive") — Organize a known chat thread by ID. Archiving a thread hides it from the default chat list and search.
2054
-
2055
- When the user asks to find a previous conversation, use \`chat-history\` with action "search" first to find matching threads, then action "open" to restore the one they want.`,
2056
- "agent-teams": `### Agent Teams — Orchestration
2057
-
2058
- You can delegate to background sub-agents with the \`agent-teams\` tool:
2059
- - \`agent-teams\` (action: "spawn") — Launch a sub-agent on a task. It runs in its own thread with a clean context while you stay available; a live preview card appears in the chat. The spawn result confirms launch only, not completion. Optionally pass a custom agent profile from \`agents/*.md\` via the \`agent\` parameter.
2060
- - \`agent-teams\` (action: "status") — Check a running sub-agent's progress.
2061
- - \`agent-teams\` (action: "read-result") — Read a finished sub-agent's output.
2062
- - \`agent-teams\` (action: "send") — Message a running sub-agent.
2063
- - \`agent-teams\` (action: "list") — List sub-agent tasks.
2064
-
2065
- Sub-agents inherit all of your template tools but **cannot spawn sub-agents themselves** — only you orchestrate.
2066
-
2067
- **User intent phrases.** If the user asks you to use a "sub-agent" or "background agent", that is explicit delegation intent. Also treat phrases like "run these in the background", "kick off the rest", "run the queued items", "batch run these jobs", "parallelize this", or "start the next batch" as delegation intent when the context is a set of independent work items.
2068
-
2069
- **Spawn is not completion.** A successful \`spawn\` call means the sub-agent started and is running. Tell the user it started, show the task id if useful, and then use \`status\`/\`list\`/\`read-result\` to monitor it. Never say the delegated task "completed", "ran successfully", or "finished" until \`status\` or \`read-result\` reports \`completed\` or \`errored\`. If a task is still running, say that plainly.
2070
-
2071
- **Default to doing the work yourself in this thread.** A sub-agent costs real tokens and adds a merge step, so reach for one only when delegation clearly pays for that overhead.
2072
-
2073
- **Delegate ONE sub-agent** when a task is self-contained and heavy: deep research, long multi-step content generation, or a noisy scan whose intermediate steps would clutter this thread. The sub-agent gets its own clean context and hands you back a distilled result.
2074
-
2075
- **Fan out to MULTIPLE sub-agents ONLY** for units of work that are genuinely independent and don't depend on each other's decisions — e.g. research three unrelated competitors, summarize five separate threads, draft sections that don't reference one another. Each gets a distinct slice.
2076
-
2077
- **Do NOT parallelize tightly-coupled work** — one cohesive artifact, edits that must agree with each other, or anything needing a single consistent voice or style. Parallel sub-agents can't see each other's choices and their outputs will clash. For coupled work, do it yourself, or chain sub-agents one at a time, feeding each result into the next.
2078
-
2079
- **Cap fan-out:** aim for 1, use up to ~3, and go beyond that only for clearly independent bulk work. More sub-agents means more tokens and a harder merge.
2080
-
2081
- **Briefing contract.** A sub-agent starts in a fresh thread and can only see the brief you give it — it cannot see this conversation or ask you to clarify before it runs. Make every brief self-contained:
2082
- 1. **Objective** — what "done" looks like, in a sentence or two.
2083
- 2. **Context** — the specific facts it needs from this conversation: IDs, names, the user's actual goal, constraints, prior decisions. Paste the specifics; don't assume it knows them.
2084
- 3. **Output format** — what to return and how (e.g. "a 3-bullet summary with source links", "the drafted email body only") so the result drops cleanly into your synthesis.
2085
- 4. **Boundaries** — what NOT to do, and for parallel sub-agents, which slice is theirs so they don't overlap.
2086
-
2087
- Put the objective and output format in \`task\`; put longer context in \`instructions\`.
2088
-
2089
- **Synthesis discipline.** After the sub-agents you depend on finish, poll \`status\`/\`list\` until they're complete, then pull each one's output with \`read-result\`. Do NOT paste their outputs back to back. Read all results, reconcile any disagreements, de-duplicate, and write ONE integrated answer in your own voice. If two sub-agents conflict, resolve it or flag the discrepancy explicitly rather than presenting both. When findings came from distinct investigations, briefly note which finding came from where so the user can trust the merge.`,
2090
- "recurring-jobs": `### Recurring Jobs
2091
-
2092
- You can create recurring jobs that run on a cron schedule. Jobs are resource files under \`jobs/\`.
2093
-
2094
- - \`manage-jobs\` (action: "create") — Create a new recurring job with a cron schedule and instructions
2095
- - \`manage-jobs\` (action: "list") — List all recurring jobs and their status
2096
- - \`manage-jobs\` (action: "update") — Update a job's schedule, instructions, or toggle enabled/disabled
2097
- - Delete a job with the \`resources\` tool: \`action: "delete"\`, \`path: "jobs/<name>.md"\`
2098
-
2099
- Convert natural language to 5-field cron format:
2100
- - "every morning" / "daily at 9am" → \`0 9 * * *\`
2101
- - "every weekday at 9am" → \`0 9 * * 1-5\`
2102
- - "every hour" → \`0 * * * *\`
2103
- - "every monday at 9am" → \`0 9 * * 1\`
2104
-
2105
- #### Suggesting "Save as automation"
2106
-
2107
- When you finish a task that has obvious recurring value — daily inbox triage, weekly metrics summaries, archive sweeps, status digests, anything the user would plausibly want re-run on a fresh cadence — close the response with ONE short line offering to save it. Examples:
2108
-
2109
- - After "Summarize my unread emails": _"Want me to run this every morning?"_
2110
- - After "What's our top traffic source this week": _"Want a weekly digest on Mondays?"_
2111
- - After "Archive emails older than 30 days": _"Should I run this every Sunday?"_
2112
-
2113
- If the user says yes, call \`manage-jobs\` (action: "create") with the original prompt as the job's instructions and the cadence they confirmed.
2114
-
2115
- Do NOT add this offer for one-shot work: lookups (find Alice, what's the schema, who reported X), single drafts/replies, navigation requests, or any task whose value is in the moment. Skip it when the prompt is already explicitly recurring (the user said "every morning…" — you'd be asking what they already told you). One short sentence at most; do not turn it into a list of cadence options.`,
2116
- builder: `### Connecting Builder.io
2117
-
2118
- When the user asks to connect Builder.io or you hit a "Builder not configured" error, call the \`connect-builder\` tool. It renders a Connect/code-change card inline — do NOT write out multi-step setup instructions yourself. Inspect the returned \`builderEnabled\` flag: \`true\` means Builder Cloud Agents can take the code-change handoff, while \`false\` means this requires a code change and the user should edit locally or use Builder.io to edit this code in the cloud and continue customizing the app any way they like. If Builder Cloud Agents are not available for this workspace, never send the user to Builder org settings or beta settings.`,
2119
- browser: `### Browser Automation
2120
-
2121
- You can activate a real Chrome browser via Builder.io for tasks that need full page rendering:
2122
- - Extracting design tokens from JS-heavy or SPA websites (computed styles, rendered colors/fonts)
2123
- - Taking screenshots of live pages
2124
- - Testing interactive flows on deployed URLs
2125
- - Reading content from pages that require JavaScript execution
2126
-
2127
- **How to use:**
2128
- 1. In local development, call \`set-browser-control\` with \`{"enabled":true,"backend":"chrome-devtools"}\` after confirming once with the user. In production, use \`activate-browser\` for Builder-provisioned Chrome.
2129
- 2. On your next action, use \`mcp__chrome-devtools__navigate_page\`, \`mcp__chrome-devtools__evaluate_script\`, \`mcp__chrome-devtools__take_screenshot\`, etc.
2130
- 3. If Builder is not connected, call \`connect-builder\` first
2131
-
2132
- **When to recommend browser automation:**
2133
- - User wants to import a design system from a URL (JS-rendered sites give almost no useful data from plain HTML fetch)
2134
- - User asks you to check how a deployed site looks or behaves
2135
- - Any task involving reading computed/rendered page state
2136
- - When \`web-request\` returns minimal/skeleton HTML from a modern SPA
2137
-
2138
- Prefer \`web-request\` for simple API calls and static pages. Use browser automation when you need the real rendered page.`,
2139
- "call-agent": `### call-agent — External Apps Only
2140
-
2141
- The \`call-agent\` tool sends a message to a DIFFERENT, separately-deployed app's agent (A2A protocol). It is **not** for calling actions within the current app.
2142
-
2143
- **NEVER use \`call-agent\` to:**
2144
- - Call your own app by name
2145
- - Perform tasks you can accomplish with your own registered tools
2146
-
2147
- **ONLY use \`call-agent\` when:**
2148
- - The user explicitly asks you to communicate with a different app
2149
- - You need data that only another deployed app can provide
2150
- - You need brand-consistent generated media and this app does not have a native generation action; call agent "assets" and keep returned asset IDs and URLs verbatim
2151
-
2152
- If \`call-agent\` says a downstream agent accepted the subtask and will post its result separately, do not call that same agent again for the same subtask. Continue any remaining work and answer with the completed results you have.`,
2153
- memory: `### Structured Memory
2154
-
2155
- Your memory index (\`memory/MEMORY.md\`) is loaded at the start of every conversation.
2156
-
2157
- **Tools:**
2158
- - \`save-memory\` — Create or update a memory (name, type, description, content)
2159
- - \`delete-memory\` — Remove a memory and its index entry
2160
- - \`resources\` with \`action: "read"\` and \`path: "memory/<name>.md"\` — Read the full content of a specific memory
2161
-
2162
- **Memory types:** user, feedback, project, reference
2163
-
2164
- **When to save (proactively):**
2165
- - User corrects your approach → \`feedback\`
2166
- - User shares preferences → \`user\`
2167
- - Non-obvious pattern or gotcha → \`feedback\`
2168
- - Personal context (contacts, team) → \`user\`
2169
- - Project context to track → \`project\`
2170
-
2171
- **Rules:**
2172
- - Don't save things obvious from code or standard framework behavior
2173
- - When updating, read first and merge — don't overwrite
2174
- - Keep descriptions concise
2175
- - One memory per logical topic`,
2176
- "sql-tools": `### SQL Tools
2177
-
2178
- When database tools are enabled, \`db-schema\` refreshes the schema and \`db-query\` runs read-only SELECT queries with current user/org scoping. Raw SQL write tools are only available when the app explicitly opts into database write tools; by default, writes go through typed app actions. Some apps configure database tools as read-only or off; only use tools that are actually present in your tool list.
2179
-
2180
- - \`db-schema\` — refresh the full schema with indexes and foreign keys
2181
- - \`db-query\` — run a SELECT (read-only; results already filtered to the current user/org)
2182
- - \`db-exec\` — only when present: run INSERT / UPDATE / DELETE / REPLACE for scoped maintenance. For normal product data writes, use a typed app action instead.
2183
- - \`db-patch\` — only when present: surgical search-and-replace on a large text column. If a typed app action exists for the resource, use that action.
2184
-
2185
- ### When to pick which SQL tool
2186
- - A template-specific action exists for the table → use that action (it encodes business rules and pushes live Yjs updates)
2187
- - Read data → \`db-query\`. Never re-add \`WHERE owner_email = ...\` — scoping already applies it.
2188
- - Raw write tools are present and no app action exists → use \`db-exec\` or \`db-patch\` only for deliberate maintenance, not normal product workflows.
2189
-
2190
- ### External data sources vs the app database
2191
- The \`db-*\` tools ONLY query the app's own SQL database. They do NOT reach external data warehouses. If the user asks about tables NOT in the schema, use the appropriate template action instead.`,
2192
- };
2193
- /**
2194
- * Framework-level instructions injected into every agent's system prompt.
2195
- * Prompt text lives in packages/core/src/server/prompts/ so this file stays
2196
- * focused on routing and assembly logic.
2197
- *
2198
- * buildFrameworkPrompts() is called once per plugin instantiation (not per
2199
- * request) with the template's promptExamples, producing the four assembled
2200
- * prompt strings used at request time.
2201
- */
2202
- function buildFrameworkPrompts(examples, options) {
2203
- // Note: FIRST_SESSION_PERSONALIZATION is NOT appended here — it is injected
2204
- // at per-request prompt-assembly time only for new threads (no prior messages).
2205
- // This prevents the ~1.5KB block from appearing on every request forever.
2206
- const FRAMEWORK_CORE = buildFrameworkCore(examples, options);
2207
- const FRAMEWORK_CORE_COMPACT = buildFrameworkCoreCompact(examples, options);
2208
- const extensionToolsEnabled = options?.extensionTools !== false;
2209
- const planModeArtifactList = extensionToolsEnabled
2210
- ? "source-code handoffs and app-created artifacts such as extensions, widgets, dashboards, calculators, mini-apps, documents, designs, slides, or videos"
2211
- : "source-code handoffs and app-created artifacts such as documents, designs, slides, or videos";
2212
- const planModeBlockedTools = extensionToolsEnabled
2213
- ? "`render-inline-extension`, `create-extension`, `update-extension`, `connect-builder`, or any action that creates, updates, deletes, sends, publishes, or persists data"
2214
- : "`connect-builder`, or any action that creates, updates, deletes, sends, publishes, or persists data";
2215
- const extensionConnectBuilderGuard = extensionToolsEnabled
2216
- ? "If the complete request can be satisfied by a self-contained extension or an existing named slot, use `render-inline-extension`, `create-extension`, `show-extension-inline`, or `update-extension` instead. If the exact placement or behavior requires changing the host UI or no suitable slot exists, continue with the normal `connect-builder` source-change flow even if the user called it an extension; never stop at saying extensions cannot do it."
2217
- : "Because extension tools are disabled, do NOT invent an extension workflow. Only use `connect-builder` when the request genuinely requires changing the host app's source code.";
2218
- const extensionInstructionsFull = extensionToolsEnabled
2219
- ? `### Generative UI and Extensions (Mini-Apps)
2220
-
2221
- In Act mode, if the user asks for generated interactive UI in chat, choose the smallest extension action that matches the lifetime:
2222
-
2223
- - For a **one-time inline UI** that answers the current chat turn (knobs, controls, pickers, calculators, temporary dashboards, visualizers), call \`render-inline-extension\` immediately with a self-contained Alpine.js HTML body. It renders inside the transcript and is not saved.
2224
- - For a **reusable or saved UI** (an extension/widget/dashboard/calculator/mini-app the user can reopen from Extensions), call \`create-extension\` with a self-contained Alpine.js HTML body. It saves to the Extensions view and also renders inline in chat.
2225
- - To **reuse an existing saved extension inline**, call \`show-extension-inline\` with its id, or a search string when the id is unknown.
2226
-
2227
- These are **NOT** source-code changes and do **NOT** go through \`connect-builder\`. Extensions are sandboxed mini-apps — no source files are touched, no PR is opened, no build is required. Saved extensions can be edited later via \`update-extension\`.
2228
-
2229
- If the app exposes native actions or instructions for dashboards, reports, analyses, charts, documents, decks, or other domain artifacts, use those app-native actions first. Choose an extension only when the user explicitly asks for an extension/custom mini-app, or when the app's native artifact format cannot faithfully express the requested interaction.
2230
-
2231
- Keep \`create-extension\` payloads compact enough to finish quickly. For complex extensions, create a useful working v1 first, then call \`update-extension\` with focused edits for refinements instead of trying to assemble one enormous initial tool input.
2232
-
2233
- Generated UI content can use appAction(), appFetch(), dbQuery(), extensionFetch(), extensionData, agentNative.ui.output(value, opts?), and agentNative.chat.send(...)/sendToAgentChat(...). Use appAction() for app data writes, and dbQuery() only for read-only inspection of known app SQL tables. It can receive chat inputs through slotContext/window.onSlotContext. Use agentNative.ui.output for passive current values from knobs, sliders, selections, and controls; it writes application state at \`inline-ui:<extensionId>:output\` scoped to the inline extension id returned by \`render-inline-extension\` or \`show-extension-inline\`. When the user later says "use that value", "apply the current setting", or similar, read it with \`readAppState("inline-ui:<id>:output")\` instead of asking them to send it again. Use agentNative.chat.send for visible submit/apply actions that should put a message into chat. Transient extensionData is browser-local and not agent-readable, synced, promoted, or garbage-collected; use application_state/appFetch, appAction, ui.output, or chat.send for anything the agent or app must observe. Use semantic Tailwind classes like bg-background, text-foreground, bg-primary, border-border, and text-muted-foreground so the UI inherits the parent app theme.
2234
-
2235
- If the user asks to change, edit, fix, style, rename, or add behavior to an existing extension/widget/dashboard/calculator/mini-app, use the current extension id from \`<current-screen>\` or \`<current-url>\` when present. Call \`get-extension\` only if you need to inspect its content, then \`update-extension\` with that id. After one content read, keep the body in working memory and move to focused \`update-extension\` \`edits\`/\`patches\`; do not loop on repeated \`get-extension\` + \`run-code\` string scans before writing. Use \`list-extensions\` only when no current id/name is available. Existing extension edits are SQL data updates, not source-code changes, even when the request says "change the UI" or "fix this". Do **NOT** call \`connect-builder\` for existing extension edits.
2236
-
2237
- In Act mode, when in doubt — if the request asks for a new small interactive utility and does not need reuse, choose \`render-inline-extension\`; if it mentions saving/reuse or asks for an extension/widget/dashboard/calculator/mini-app, choose \`create-extension\`. If it references an existing one or the current extension page, choose \`update-extension\`. Do **not** preface the call with planning text like "let me build the dashboard…" — just call the right extension action directly.
2238
-
2239
- Note: "extension" is the user-facing primitive (the sandboxed Alpine.js mini-app). Don't confuse it with the LLM concept of "tools" (function calls) — those are how you invoke ANY action, including \`create-extension\` itself.
2240
-
2241
- For existing extensions, use \`get-extension\` or \`update-extension\` directly when \`<current-screen>\` or \`<current-url>\` provides an \`extensionId\`. Use \`list-extensions\` only to browse or resolve an unknown name. If the user wants a shared extension removed only from their view, use \`hide-extension\` — do not query or mutate the legacy \`tools\` table directly.
2242
-
2243
- ### Extensions vs. Code Changes — Pick the Right Path
2244
-
2245
- Route by the exact outcome, not by whether the user calls it an extension. Extensions render in their own sandboxed iframe, either on their own page or inside an existing named slot. They CANNOT change the host app's nav, restyle or inject elements into existing native components, replace built-in views, or render at an arbitrary location that has no slot.
2246
-
2247
- <routing>
2248
- | The request is for… | Path |
2249
- | ---------------------------------------------------------------- | ----------------------------- |
2250
- | A one-off interactive answer inside chat (controls, picker, calculator, temporary visualizer) | \`render-inline-extension\` — inline only |
2251
- | A new self-contained surface (widget, dashboard, calculator, viewer, list, tracker) | \`create-extension\` — ships instantly, no PR |
2252
- | Loading a saved extension inside chat | \`show-extension-inline\` |
2253
- | Editing an existing extension (fix, restyle, rename, add behavior) | \`update-extension\` |
2254
- | The host app's own chrome (nav bar, sidebar, layout, routes, shipped components, existing styles, business logic) | \`connect-builder\` — a real source-code change |
2255
- | UI inside or beside a native component where no named slot exists | \`connect-builder\` — add the native UI or a suitable slot in source |
2256
- | Ambiguous, satisfiable either way (e.g. "give me an unread view") | \`render-inline-extension\` for chat-only, \`create-extension\` for reusable |
2257
- </routing>
2258
-
2259
- If an extension could only approximate the request in a different location, do not silently downgrade the requirement and do not end with "extensions cannot do that." Briefly explain the boundary, then follow the normal source-code handoff so the app can still be customized fully.
2260
-
2261
- Worked examples: "a widget showing unread emails grouped by sender", "a tracker for my newsletter subscriptions", "a custom kanban board with drag-and-drop rules the app does not have" → \`create-extension\`. "Add an Unread tab to the left navigation", "show local time beside every native Calendar attendee row", "make the subject lines wrap", "change the inbox grouping logic", "add a field to the compose form" → \`connect-builder\`.`
2262
- : `### Extensions Disabled
2263
-
2264
- Extension creation and management tools are disabled for this app. Do not claim you can create, edit, hide, or delete Agent-Native extensions unless the template exposes its own typed action for that workflow. For requests that would otherwise be handled as an extension/widget/dashboard/calculator mini-app, explain that this app has disabled extension tools and use the app's available actions instead.`;
2265
- const extensionInstructionsCompact = extensionToolsEnabled
2266
- ? `### Generative UI and Extensions (Mini-Apps)
2267
-
2268
- In Act mode, if the user asks for generated interactive UI in chat, call \`render-inline-extension\` for one-time inline controls/knobs/calculators/visualizers that do not need saving. If the user asks for an **extension**, **widget**, **dashboard**, **calculator**, or **mini-app** that should be reusable or saved, call \`create-extension\` with a self-contained Alpine.js HTML body. To load a saved extension inline, call \`show-extension-inline\`. These are NOT code changes — extensions are sandboxed mini-apps. Do not preface with "let me build…" — just call the right extension action.
2269
-
2270
- Use app-native artifact actions first when they exist for dashboards, reports, analyses, charts, documents, decks, or similar domain artifacts. Pick \`create-extension\` only for explicit extension/custom mini-app requests or for behavior the native artifact format cannot support.
2271
-
2272
- Keep the first \`create-extension\` call compact and working. If the request is complex, create the v1 first and then refine with focused \`update-extension\` edits.
2273
-
2274
- Generated UI can read chat inputs from slotContext/window.onSlotContext, see/update app state through appFetch/appAction, use extensionData, record passive current values through agentNative.ui.output(value, opts?), and send visible results through agentNative.chat.send(...) or sendToAgentChat(...). ui.output writes \`inline-ui:<extensionId>:output\` in application state; when the user asks to use the current slider/selection/value, read \`readAppState("inline-ui:<id>:output")\`. Transient extensionData is browser-local only, so do not rely on it for values the agent or app must observe. Use semantic Tailwind theme classes.
2275
-
2276
- If the user asks to change, edit, fix, style, rename, or add behavior to an existing extension/widget/dashboard/calculator/mini-app, use the current extension id from \`<current-screen>\` or \`<current-url>\` when present. Call \`get-extension\` only if you need to inspect its content, then \`update-extension\` with that id. After one content read, use focused \`update-extension\` \`edits\`/\`patches\`; do not repeatedly re-read and scan the same HTML with \`run-code\` before writing. Use \`list-extensions\` only when no current id/name is available. Existing extension edits are SQL data updates, not source-code changes. Do NOT call \`connect-builder\` for them.
2277
-
2278
- For existing extensions, use \`get-extension\` or \`update-extension\` directly when \`<current-screen>\` or \`<current-url>\` provides an \`extensionId\`. Use \`list-extensions\` only to browse or resolve an unknown name. Use \`hide-extension\` when the user wants a shared extension removed only from their own view. Do not query the legacy \`tools\` table directly.
2279
-
2280
- ### Extensions vs. Code Changes — Pick the Right Path
2281
-
2282
- If the user wants a **one-off interactive answer in chat**, use \`render-inline-extension\`. If they want a **new reusable self-contained surface** (custom widget, dashboard, list, viewer, calculator), use \`create-extension\` — extensions ship instantly without a PR. Extensions can render only on their own page or in an existing named slot; they cannot inject UI into arbitrary native components. If the exact request changes host chrome, native components, layout, styles, routes, business logic, or needs placement where no slot exists, treat it as a source-code change and use the normal \`connect-builder\` flow even if the user called it an extension. Never stop at "extensions cannot do that" or silently offer a different placement; explain the boundary briefly and continue the code-change handoff.`
2283
- : `### Extensions Disabled
2284
-
2285
- Extension creation and management tools are disabled for this app. Do not claim you can create, edit, hide, or delete Agent-Native extensions unless the template exposes its own typed action for that workflow.`;
2286
- const PROD_FRAMEWORK_PROMPT = `## Agent-Native Framework — Production Mode
2287
-
2288
- You are an AI agent in an agent-native application, running in **production mode**.
2289
-
2290
- The agent and the UI are equal partners — everything the UI can do, you can do via your tools, and vice versa. They share the same SQL database and stay in sync automatically.
2291
-
2292
- **In production mode, you operate through registered actions exposed as tools.** These are your capabilities — use them to read data, take actions, and help the user. You cannot edit source code or access the filesystem directly. Your tools are the app's API.
2293
-
2294
- ### Plan Mode
2295
-
2296
- If the current turn is in Plan mode, plan before anything gets written. This applies to ${planModeArtifactList}. Use only read-only tools, clarify the goal when needed, and return a concrete plan for approval. Do not call ${planModeBlockedTools} until the user switches back to Act mode.
2297
-
2298
- ${extensionInstructionsFull}
2299
-
2300
- ### Code Changes Not Available — Call \`connect-builder\` Immediately
2301
-
2302
- ${extensionConnectBuilderGuard}
2303
-
2304
- In Act mode, when the user asks you to change the UI, modify code, add a feature, fix a bug in the app itself, change styles, add a hook, create a component, add a route, add an integration, or anything else that requires editing source files — you MUST take exactly these steps, in order:
2305
-
2306
- 1. Briefly acknowledge the user's specific request in their own terms — one short clause naming what they asked for (e.g. "Got it — wider subject lines in the email list."). Do NOT restate the request verbatim, do NOT add a generic preamble, and do NOT promise outcomes. Skip this step entirely if the user already knows you're handing off (e.g. they said "send this to Builder").
2307
- 2. Call the \`connect-builder\` tool, passing the user's full request verbatim as the \`prompt\` argument. This renders an inline card. The returned \`builderEnabled\` flag is authoritative: \`true\` means Builder Cloud Agents can take the code-change handoff; \`false\` means this still requires a code change, but no Builder Cloud Agent can run from this workspace. If Builder is connected and \`builderEnabled\` is true, the card hands the prompt off to Builder's cloud agent on one click and returns a branch URL. If Builder is not connected and \`builderEnabled\` is true, it shows the Connect Builder flow. If \`builderEnabled\` is false, it still shows the card, but as a code-change fallback instead of a runnable cloud handoff.
2308
- 3. After the card renders, inspect the tool result and write one sentence that frames the next click around what the user just asked — not as a Builder pitch. If \`builderEnabled\` is true and the card can send, say something like "Click Send to Builder and it'll wire that up for you." If the user needs to connect first, say something like "Connect Builder once and it'll handle this and future changes." If \`builderEnabled\` is false, say: "This requires a code change. Edit locally or use Builder.io to edit this code in the cloud and continue customizing the app any way you like." Do NOT say "click Send to Builder", mention a branch URL, say the card is pre-loaded, or imply a Builder Cloud Agent can run when \`builderEnabled\` is false.
2309
-
2310
- When \`builderEnabled\` is false, Builder Cloud Agents are not self-serve from Builder org settings. Do NOT tell the user to go to Builder org settings, beta features, "Cloud Agents", or "AI Agents" to enable them. The only allowed guidance is the card's code-change fallback: edit locally, use Agent Native Desktop, or use Builder.io to edit this code in the cloud and continue customizing the app any way you like.
2311
-
2312
- **Act-mode handoff — do exactly this:** The moment a code change is requested, call \`connect-builder\` with the user's verbatim request, then write one sentence framing the next click. That is the whole job: Builder plans and edits in its own sandbox, so the planning, file-mapping, and code all happen there, not here. Keep your turn to the call plus that one sentence — skip code exploration, implementation plans, \`resources\` writes of specs, and sub-agents (they have no code-editing tools either). You don't need filesystem access to recommend Builder, so don't reach for it or list tools you lack.
2313
-
2314
- Builder Cloud Agents are the recommended path when \`builderEnabled\` is true because they are one-click and run in the cloud. Local dev, Agent Native Desktop, and Builder.io cloud editing are the fallback when \`builderEnabled\` is false.
2315
- ${FRAMEWORK_CORE}`;
2316
- const DEV_FRAMEWORK_PROMPT = `## Agent-Native Framework — Development Mode
2317
-
2318
- You are an AI agent in an agent-native application, running in **development mode**.
2319
-
2320
- The agent and the UI are equal partners — everything the UI can do, you can do via tools/scripts, and vice versa. They share the same SQL database and stay in sync automatically.
2321
-
2322
- **In development mode, you have full local access — use it with senior-engineer judgment** (read before you edit, keep changes scoped, verify before you claim done):
2323
- - Run any shell command via the \`bash\` tool (node, curl, pnpm, rg, git, etc.), including arbitrary code: \`bash({ command: 'node -e "console.log(1+1)"' })\`
2324
- - Read and write any file on the filesystem; edit source, install packages, modify the app
2325
- - Query and modify the database
2326
- - Call external APIs (via bash with curl, or via scripts)
2327
-
2328
- When no dedicated tool/action exists for what you need, reach for \`bash\` — e.g. \`bash({ command: 'curl -s https://api.example.com/data' })\`.
2329
-
2330
- **Template-specific actions are invoked via bash, NOT as direct tools.** In dev mode, the only tools registered as native tool calls are framework-level utilities (bash, read, edit, write, database, resources, chat, teams, jobs). Anything from the template's \`actions/\` directory must be run through bash: \`bash({ command: 'pnpm action <name> --arg value' })\`. The "Available Actions" section below shows the exact CLI syntax for each one — copy that command verbatim and pass it to \`bash\`. Do not try to call template actions by name as if they were tools; they will not appear in your tool list.
2331
-
2332
- When editing code, follow the agent-native architecture:
2333
- - Every feature needs all four areas: UI + scripts + skills/instructions + application-state sync
2334
- - All SQL must be dialect-agnostic (works on SQLite and Postgres)
2335
- - No Node.js-specific APIs in server routes (must work on Cloudflare Workers, etc.)
2336
- - Use shadcn/ui components and Tabler Icons for all UI work
2337
- ${FRAMEWORK_CORE}`;
2338
- const PROD_FRAMEWORK_PROMPT_COMPACT = `## Agent-Native Framework — Production Mode
2339
-
2340
- You are an AI agent in an agent-native application, running in **production mode**.
2341
-
2342
- The agent and the UI are equal partners — everything the UI can do, you can do via your tools, and vice versa. They share the same SQL database and stay in sync automatically.
2343
-
2344
- **In production mode, you operate through registered actions exposed as tools.** These are your capabilities — use them to read data, take actions, and help the user. You cannot edit source code or access the filesystem directly. Your tools are the app's API.
2345
-
2346
- ### Plan Mode
2347
-
2348
- If the turn is in Plan mode, plan before anything gets written — including ${planModeArtifactList}. Use read-only tools only and do not call ${planModeBlockedTools} until the user switches back to Act mode.
2349
-
2350
- ${extensionInstructionsCompact}
2351
-
2352
- ### Code Changes — Call \`connect-builder\`
2353
-
2354
- In Act mode, when a request genuinely needs a source-code edit (per the rules above), do this in order: (1) briefly acknowledge the user's specific ask in their own terms — one short clause, no preamble — then (2) call \`connect-builder\` with the user's request as the \`prompt\`, then (3) inspect \`builderEnabled\` in the result and write one sentence framing the next click around what they asked for, not a Builder pitch. When \`builderEnabled\` is true, Builder Cloud Agents can take the handoff; when \`builderEnabled\` is false, say this requires a code change and they can edit locally or use Builder.io to edit this code in the cloud and continue customizing the app any way they like. Do NOT write code, list files, make plans, or spawn sub-agents. Mention \`npx agent-native create <app-name>\`, Agent Native Desktop, or the code-change fallback when Builder Cloud Agents aren't available. Never tell users to enable Builder Cloud Agents from Builder org settings, beta features, "Cloud Agents", or "AI Agents"; they are not self-serve there.
2355
- ${FRAMEWORK_CORE_COMPACT}`;
2356
- const DEV_FRAMEWORK_PROMPT_COMPACT = `## Agent-Native Framework — Development Mode
2357
-
2358
- You are an AI agent in an agent-native application, running in **development mode**.
2359
-
2360
- The agent and the UI are equal partners — everything the UI can do, you can do via tools/scripts, and vice versa. They share the same SQL database and stay in sync automatically.
2361
-
2362
- **In development mode, you have full local access** — shell, filesystem, database, external APIs, source edits, and package installs. Use it with senior-engineer judgment: read before you edit, keep changes scoped, verify before you claim done.
2363
-
2364
- **Template-specific actions are invoked via bash, NOT as direct tools.** Run them with: \`bash({ command: 'pnpm action <name> --arg value' })\`. See the "Available Actions" section below for CLI syntax.
2365
-
2366
- When editing code, follow the agent-native architecture:
2367
- - Every feature needs all four areas: UI + scripts + skills/instructions + application-state sync
2368
- - All SQL must be dialect-agnostic (works on SQLite and Postgres)
2369
- - No Node.js-specific APIs in server routes (must work on Cloudflare Workers, etc.)
2370
- - Use shadcn/ui components and Tabler Icons for all UI work
2371
- ${FRAMEWORK_CORE_COMPACT}`;
2372
- return {
2373
- FRAMEWORK_CORE,
2374
- FRAMEWORK_CORE_COMPACT,
2375
- PROD_FRAMEWORK_PROMPT,
2376
- DEV_FRAMEWORK_PROMPT,
2377
- PROD_FRAMEWORK_PROMPT_COMPACT,
2378
- DEV_FRAMEWORK_PROMPT_COMPACT,
2379
- };
2380
- }
2381
- export const _agentChatPromptSectionsForTests = (() => {
2382
- // Built with default (no template-specific) examples for test stability.
2383
- const { FRAMEWORK_CORE: frameworkCore, FRAMEWORK_CORE_COMPACT: frameworkCoreCompact, } = buildFrameworkPrompts();
2384
- return {
2385
- frameworkCore,
2386
- frameworkCoreCompact,
2387
- frameworkContextSections: FRAMEWORK_CONTEXT_SECTIONS,
2388
- buildFrameworkPrompts,
2389
- generateActionsPrompt,
2390
- createDataWidgetActionEntries,
2391
- };
2392
- })();
2393
- /**
2394
- * Pre-load the agent's context: AGENTS.md (workspace/template/runtime
2395
- * instructions), the skills index, shared LEARNINGS.md (team notes), a shared
2396
- * resource index, and memory/MEMORY.md (personal structured memory index).
2397
- * These all get appended to the system prompt so the agent has everything it
2398
- * needs from the first turn.
2399
- *
2400
- * Six sources are layered:
2401
- *
2402
- * 1. `<workspace>` — AGENTS.md from the enterprise workspace core.
2403
- * 2. `<template>` — AGENTS.md + skills index from the Vite plugin bundle.
2404
- * 3. `<workspace>` — SQL workspace AGENTS.md and instructions/*.md.
2405
- * Runtime global defaults managed from Dispatch and inherited by apps.
2406
- * 4. `<app-default>` — legacy app-wide SQL defaults.
2407
- * 5. `<shared>` — organization AGENTS.md, instructions, and LEARNINGS.md.
2408
- * These are isolated by active org and override app/workspace defaults.
2409
- * 6. `<personal>` — memory/MEMORY.md from the SQL personal scope. The
2410
- * current user's structured memory index.
2411
- *
2412
- * Each source is read independently — no copying between them. Editing
2413
- * AGENTS.md and restarting the server is all it takes; Vite HMR invalidates
2414
- * the bundle in dev so changes land instantly.
2415
- */
2416
- export async function loadResourcesForPrompt(owner, compact = false, selfAppId, orgId = getRequestOrgId() ?? null) {
2417
- await ensurePersonalDefaults(owner);
2418
- const sections = [];
2419
- const promptResourceMaxChars = compact
2420
- ? COMPACT_PROMPT_RESOURCE_MAX_CHARS
2421
- : SHARED_PROMPT_RESOURCE_MAX_CHARS;
2422
- // 1. Workspace AGENTS.md + skills merged into the template bundle.
2423
- try {
2424
- const { loadAgentsBundle, generateSkillsPromptBlock, getRuntimeSkills } = await import("./agents-bundle.js");
2425
- const bundle = await loadAgentsBundle();
2426
- // Workspace-core AGENTS.md (enterprise-wide instructions), if present.
2427
- if (bundle.workspaceAgentsMd && bundle.workspaceAgentsMd.trim()) {
2428
- const block = promptResourceBlock({
2429
- name: "AGENTS.md",
2430
- scope: "workspace",
2431
- path: "AGENTS.md",
2432
- content: bundle.workspaceAgentsMd,
2433
- maxChars: promptResourceMaxChars,
2434
- readHint: 'Use docs-search --slug "agents-workspace" to read the full workspace AGENTS.md.',
2435
- });
2436
- if (block)
2437
- sections.push(block);
2438
- }
2439
- // 2. Template AGENTS.md — always included (critical template instructions).
2440
- if (bundle.agentsMd.trim()) {
2441
- const block = promptResourceBlock({
2442
- name: "AGENTS.md",
2443
- scope: "template",
2444
- path: "AGENTS.md",
2445
- content: bundle.agentsMd,
2446
- maxChars: promptResourceMaxChars,
2447
- readHint: 'Use docs-search --slug "agents-template" to read the full template AGENTS.md.',
2448
- });
2449
- if (block)
2450
- sections.push(block);
2451
- }
2452
- // In compact mode, skip the full skills block — the agent can use
2453
- // `docs-search` to find skills when it needs them. Either way, `scope: dev`
2454
- // skills are excluded: they're for the human's coding agent, not runtime.
2455
- const runtimeSkills = getRuntimeSkills(bundle);
2456
- if (!compact) {
2457
- const skillsBlock = generateSkillsPromptBlock(bundle);
2458
- if (skillsBlock)
2459
- sections.push(skillsBlock);
2460
- }
2461
- else if (runtimeSkills.length > 0) {
2462
- const lines = runtimeSkills.map((s) => {
2463
- const description = s.meta.description?.trim()
2464
- ? ` - ${ensureSentence(s.meta.description)}`
2465
- : "";
2466
- return `- \`${s.meta.name}\`${description} Read with \`docs-search --slug "${skillDocsSlug(s.meta.name)}"\` before starting a task it applies to.`;
2467
- });
2468
- sections.push(`<skills-summary>\nCodebase skills bundled from \`.agents/skills/\` (or legacy \`.agent/skills/\`) are available as docs-search pages. Do not use MCP resource reads for these skills.\n\n${lines.join("\n")}\n</skills-summary>`);
2469
- }
2470
- }
2471
- catch { }
2472
- // 3. Runtime workspace resources. These are global defaults inherited by
2473
- // every app in the workspace, not copied into app scopes. They may come from
2474
- // SQL, Dispatch, or local file mode.
2475
- const workspaceAgents = await loadAgentsResourceForPrompt(WORKSPACE_OWNER, "workspace", promptResourceMaxChars);
2476
- if (workspaceAgents)
2477
- sections.push(workspaceAgents);
2478
- sections.push(...(await loadInstructionResourcesForPrompt(WORKSPACE_OWNER, "workspace-instruction", promptResourceMaxChars)));
2479
- const organizationOwner = sharedResourceOwner(orgId);
2480
- // 4. Legacy app-wide defaults. Existing deployments keep their seeded
2481
- // shared guidance as an inherited fallback; organization writes never
2482
- // mutate this owner.
2483
- const appDefaultAgents = await loadAgentsResourceForPrompt(SHARED_OWNER, organizationOwner === SHARED_OWNER ? "shared" : "app-default", promptResourceMaxChars);
2484
- if (appDefaultAgents)
2485
- sections.push(appDefaultAgents);
2486
- sections.push(...(await loadInstructionResourcesForPrompt(SHARED_OWNER, organizationOwner === SHARED_OWNER
2487
- ? "shared-instruction"
2488
- : "app-default-instruction", promptResourceMaxChars)));
2489
- // 5. Active organization resources. These are the durable team rules and
2490
- // learnings that Slack/integration runs share with interactive app chat.
2491
- if (organizationOwner !== SHARED_OWNER) {
2492
- const organizationAgents = await loadAgentsResourceForPrompt(organizationOwner, "shared", promptResourceMaxChars);
2493
- if (organizationAgents)
2494
- sections.push(organizationAgents);
2495
- sections.push(...(await loadInstructionResourcesForPrompt(organizationOwner, "shared-instruction", promptResourceMaxChars)));
2496
- }
2497
- // 6. Personal SQL resources. These come last in the instruction stack so a
2498
- // user can narrow or override organization/app and workspace defaults.
2499
- if (owner !== SHARED_OWNER && owner !== WORKSPACE_OWNER) {
2500
- const personalAgents = await loadAgentsResourceForPrompt(owner, "personal", promptResourceMaxChars);
2501
- if (personalAgents)
2502
- sections.push(personalAgents);
2503
- sections.push(...(await loadInstructionResourcesForPrompt(owner, "personal-instruction", promptResourceMaxChars)));
2504
- }
2505
- const resourceSkillsBlock = await loadResourceSkillsPromptBlock(owner, orgId);
2506
- if (resourceSkillsBlock)
2507
- sections.push(resourceSkillsBlock);
2508
- let sharedLearnings = null;
2509
- try {
2510
- sharedLearnings =
2511
- (organizationOwner !== SHARED_OWNER
2512
- ? await resourceGetByPath(organizationOwner, "LEARNINGS.md")
2513
- : null) ?? (await resourceGetByPath(SHARED_OWNER, "LEARNINGS.md"));
2514
- }
2515
- catch { }
2516
- if (compact) {
2517
- // Integration/Slack turns use compact context, but organization learnings
2518
- // are operational routing input, not optional background. Preload the
2519
- // bounded shared file so canonical destinations/fields are available on
2520
- // the first turn; keep personal memory on-demand to preserve the compact
2521
- // budget.
2522
- if (sharedLearnings?.content?.trim()) {
2523
- const block = promptResourceBlock({
2524
- name: "LEARNINGS.md",
2525
- scope: "shared",
2526
- path: "LEARNINGS.md",
2527
- content: sharedLearnings.content,
2528
- maxChars: COMPACT_PROMPT_RESOURCE_MAX_CHARS,
2529
- });
2530
- if (block)
2531
- sections.push(block);
2532
- }
2533
- sections.push(`<context-note>Organization learnings above and your personal memory (memory/MEMORY.md) are available via the \`resources\` tool. Save durable team facts and routing conventions to shared LEARNINGS.md; keep personal preferences in save-memory.</context-note>`);
2534
- }
2535
- else {
2536
- // LEARNINGS.md from SQL (template-level instructions are in AGENTS.md above).
2537
- if (sharedLearnings?.content?.trim()) {
2538
- sections.push(`<resource name="LEARNINGS.md" scope="shared">\n${sharedLearnings.content.trim()}\n</resource>`);
2539
- }
2540
- // 3. Personal memory index (skip if owner is the shared sentinel)
2541
- if (owner !== SHARED_OWNER) {
2542
- try {
2543
- const memoryIndex = await resourceGetByPath(owner, "memory/MEMORY.md");
2544
- if (memoryIndex?.content?.trim()) {
2545
- sections.push(`<resource name="memory/MEMORY.md" scope="personal">\n${memoryIndex.content.trim()}\n</resource>`);
2546
- }
2547
- }
2548
- catch { }
2549
- }
2550
- }
2551
- const workspaceResourceIndex = await loadResourceIndexForPrompt(WORKSPACE_OWNER, "workspace");
2552
- if (workspaceResourceIndex)
2553
- sections.push(workspaceResourceIndex);
2554
- const appDefaultResourceIndex = await loadResourceIndexForPrompt(SHARED_OWNER, "shared");
2555
- if (appDefaultResourceIndex)
2556
- sections.push(appDefaultResourceIndex);
2557
- if (organizationOwner !== SHARED_OWNER) {
2558
- const organizationResourceIndex = await loadResourceIndexForPrompt(organizationOwner, "shared");
2559
- if (organizationResourceIndex)
2560
- sections.push(organizationResourceIndex);
2561
- }
2562
- try {
2563
- const agents = (await discoverAgents(selfAppId)).slice(0, 30);
2564
- if (agents.length > 0) {
2565
- const lines = agents.map((agent) => `- ${agent.name} (${agent.id}) — ${agent.description || "Connected A2A app"}`);
2566
- sections.push(`<available-apps>\nWorkspace apps available over A2A/call-agent:\n${lines.join("\n")}\n\nUse \`call-agent\` with the app id when another app owns the work or data. Use tool-search or app-specific actions for details only when needed.\n</available-apps>`);
2567
- }
2568
- }
2569
- catch {
2570
- // Agent discovery is helpful context, not required for the run.
2571
- }
2572
- if (sections.length === 0)
2573
- return "";
2574
- return ("\n\nThe following resources contain template-specific instructions and user context. Use the information in them to help the user.\n\n" +
2575
- sections.join("\n\n"));
2576
- }
2577
- /**
2578
- * Build the per-request SQL-schema context block. Reads AGENT_ORG_ID live
2579
- * from the environment so scheduler/A2A/HTTP call sites all see whatever
2580
- * org was just resolved for this request.
2581
- */
2582
- async function buildSchemaBlock(owner, databaseTools = "read") {
2583
- try {
2584
- return await loadSchemaPromptBlock({
2585
- owner,
2586
- orgId: getRequestOrgId() ?? null,
2587
- databaseTools,
2588
- });
2589
- }
2590
- catch {
2591
- return "";
2592
- }
2593
- }
2594
- /**
2595
- * Generates a system prompt section describing registered template actions.
2596
- * This helps the agent prefer template-specific actions over raw db-query/db-exec.
2597
- *
2598
- * Two output modes:
2599
- *
2600
- * - `"tool"` — used in production, where template actions are registered
2601
- * as native Anthropic tools. Output reads `name(arg*: type; ...) — desc`.
2602
- * - `"cli"` — used in dev, where template actions are NOT registered as
2603
- * native tools and must be invoked via `bash(command="pnpm action ...")`.
2604
- * Output reads `pnpm action name --arg <type> [--opt <type>] — desc`.
2605
- */
2606
- function generateActionsPrompt(registry, mode = "tool") {
2607
- if (!registry || Object.keys(registry).length === 0)
2608
- return "";
2609
- const actionEntries = Object.entries(registry);
2610
- const nativeWidgetNote = (entry) => entry.chatUI && typeof entry.chatUI.renderer === "string"
2611
- ? ` Native chat widget: \`${entry.chatUI.renderer}\`.`
2612
- : "";
2613
- if (mode === "tool") {
2614
- const summaryLines = actionEntries.map(([name, entry]) => {
2615
- const desc = compactPromptLine(entry.tool.description, MAX_ACTION_SUMMARY_DESCRIPTION_CHARS);
2616
- return `- \`${name}\` — ${desc}${nativeWidgetNote(entry)}`;
2617
- });
2618
- return `\n\n## Available Actions
2619
-
2620
- **Use these actions directly as tool calls.** They handle database access, validation, and business logic internally. The native tool schemas contain the full parameter details.
2621
-
2622
- ${summaryLines.join("\n")}`;
2623
- }
2624
- const lines = actionEntries.map(([name, entry]) => {
2625
- const desc = entry.tool.description;
2626
- const params = entry.tool.parameters?.properties;
2627
- const requiredFields = new Set(entry.tool.parameters?.required ?? []);
2628
- // CLI mode: emit `pnpm action <name> --required <type> [--optional <type>]`
2629
- if (!params || Object.keys(params).length === 0) {
2630
- return `- \`pnpm action ${name}\` — ${desc}${nativeWidgetNote(entry)}`;
2631
- }
2632
- const entries = Object.entries(params);
2633
- // Required first (alphabetical), then optional (alphabetical)
2634
- entries.sort(([a], [b]) => {
2635
- const ar = requiredFields.has(a) ? 0 : 1;
2636
- const br = requiredFields.has(b) ? 0 : 1;
2637
- if (ar !== br)
2638
- return ar - br;
2639
- return a.localeCompare(b);
2640
- });
2641
- const required = [];
2642
- const optional = [];
2643
- const requiredNames = [];
2644
- for (const [k, v] of entries) {
2645
- const type = v.type ?? "any";
2646
- const flag = `--${k} <${type}>`;
2647
- if (requiredFields.has(k)) {
2648
- required.push(flag);
2649
- requiredNames.push(`--${k}`);
2650
- }
2651
- else {
2652
- optional.push(`[${flag}]`);
2653
- }
2654
- }
2655
- const cmd = ["pnpm action " + name, ...required, ...optional].join(" ");
2656
- const requiredNote = requiredNames.length > 0 ? ` Required: ${requiredNames.join(", ")}.` : "";
2657
- return `- \`${cmd}\` — ${desc}.${requiredNote}${nativeWidgetNote(entry)}`;
2658
- });
2659
- return `\n\n## Available Actions
2660
-
2661
- **These template actions are NOT exposed as direct tools in dev mode. To run any of them, use the \`bash\` tool with the exact command shown below.** Example: \`bash(command="pnpm action add-slide --deckId abc --content 'Hello'")\`.
2662
-
2663
- Do NOT try to call these by name as if they were tools — they will not exist in your tool list. Always go through \`bash\`.
2664
-
2665
- ${lines.join("\n")}`;
2666
- }
2667
- function generateCorpusToolsPrompt(registry) {
2668
- const hasProviderApi = "provider-api-request" in registry;
2669
- const hasProviderCorpusJob = "provider-corpus-job" in registry;
2670
- const providerDiscoveryTools = [
2671
- "provider-api-catalog" in registry ? "`provider-api-catalog`" : null,
2672
- "provider-api-docs" in registry ? "`provider-api-docs`" : null,
2673
- ].filter(Boolean);
2674
- const hasRunCode = "run-code" in registry;
2675
- const hasStagedDataset = "query-staged-dataset" in registry;
2676
- if (!hasProviderApi &&
2677
- !hasProviderCorpusJob &&
2678
- !hasRunCode &&
2679
- !hasStagedDataset)
2680
- return "";
2681
- const available = [
2682
- ...providerDiscoveryTools,
2683
- hasProviderApi ? "`provider-api-request`" : null,
2684
- hasProviderCorpusJob ? "`provider-corpus-job`" : null,
2685
- hasStagedDataset ? "`query-staged-dataset`" : null,
2686
- hasRunCode ? "`run-code`" : null,
2687
- ].filter(Boolean);
2688
- return `\n\n## Broad Provider And Corpus Workflows
2689
-
2690
- Available corpus-capable tools: ${available.join(", ")}.
2691
-
2692
- For broad provider searches, raw API access, multi-page cohorts, cross-source joins, classification/counting over records, or absence-sensitive answers, do not stop at a bounded shortcut action. Use the provider's broad API/search/list surface, fetch every relevant page or an explicit bounded cohort, stage/save large responses when needed, and reduce the corpus with durable corpus jobs, staged-dataset queries, or code execution.
2693
-
2694
- When \`provider-corpus-job\` is available, prefer it for transcript/message/ticket/issue/document scans that may exceed one turn, need provider-side backoff, or need a defensible "not found" conclusion. Use operation="start" with mode="paginated-search" for any paginated provider endpoint, or mode="batch-search" when a prior cohort of ids/records must feed a second provider endpoint. Continue paused jobs with operation="continue" until status is completed or quota_wait, then read operation="results". In run-code, prefer providerFetchAll() for short cursor/page/offset pagination and providerRequest() when response status, headers, or truncation metadata matters. Report source, filters, row counts, pagination/truncation, failed pages, quota_wait times, and remaining gaps.`;
2695
- }
52
+ // ---------------------------------------------------------------------------
53
+ // The bulk of this file's former implementation now lives in focused sibling
54
+ // modules under `./agent-chat/`. This file re-imports them (and re-exports
55
+ // the ones that were already part of the public surface) so
56
+ // `createAgentChatPlugin` below stays a thinner orchestrator.
57
+ // ---------------------------------------------------------------------------
58
+ import { createA2AEngineToolSurface, filterAgentTools, filterPublicAgentActions, filterReadOnlyActions, resolveInitialToolNames, runA2AAgentLoop, assembleA2AFinalResponse, buildPublicAgentA2ASkills, resolveArtifactBaseUrl, } from "./agent-chat/action-filters-a2a.js";
59
+ import { createBuilderBrowserTool, createTeamTools, } from "./agent-chat/browser-team-tools.js";
60
+ import { createDataWidgetActionEntries, createFrameworkContextEntry, createRefreshScreenEntry, createUrlTools, } from "./agent-chat/context-tools.js";
61
+ import { _agentChatPromptSectionsForTests, buildFrameworkPrompts, buildSchemaBlock, collectFiles, corpusToolNamesTaughtByPrompt, generateActionsPrompt, generateCorpusToolsPrompt, } from "./agent-chat/framework-prompts.js";
62
+ import { finalizeClaimedAgentChatProcessRunFailure } from "./agent-chat/process-run-failure.js";
63
+ import { loadResourcesForPrompt, resourceScopeForOwner, } from "./agent-chat/prompt-resources.js";
64
+ import { shouldDisableRecurringJobsRuntime } from "./agent-chat/recurring-jobs-runtime.js";
65
+ import { isLocalhost, shouldBlockInProductCodeEditingSurface, } from "./agent-chat/request-surface.js";
66
+ import { loadRunCodeToolEntries } from "./agent-chat/run-code-tools.js";
67
+ import { createAgentEngineScriptEntries, createAgentLoopSettingsScriptEntries, createCallAgentScriptEntry, createChatScriptEntries, createDbScriptEntries, createDocsScriptEntries, createResourceScriptEntries, } from "./agent-chat/script-entries.js";
68
+ import { parseSkillFrontmatter } from "./agent-chat/skill-frontmatter.js";
69
+ export { loadResourcesForPrompt };
70
+ export { _agentChatPromptSectionsForTests };
71
+ export { buildPublicAgentA2ASkills };
72
+ export { assembleA2AFinalResponse };
73
+ export { runA2AAgentLoop };
74
+ export { createA2AEngineToolSurface };
75
+ export { shouldBlockInProductCodeEditingSurface };
76
+ export { loadRunCodeToolEntries };
77
+ export { shouldDisableRecurringJobsRuntime };
78
+ export { finalizeClaimedAgentChatProcessRunFailure };
2696
79
  /**
2697
- * Creates a Nitro plugin that mounts the agent chat endpoint.
2698
- *
2699
- * In dev mode (NODE_ENV !== "production"), automatically includes
2700
- * file system, bash, and database tools alongside any template-specific actions.
80
+ * Returns whether `owner` has already finished (or explicitly skipped) the
81
+ * First-Session Personalization flow, via the owner-scoped
82
+ * `application_state` "personalization" flag the agent itself writes
83
+ * (`writeAppState("personalization", { done: true })` see
84
+ * FIRST_SESSION_PERSONALIZATION in prompts/framework-core.ts).
2701
85
  *
2702
- * Usage in templates:
2703
- * ```ts
2704
- * // server/plugins/agent-chat.ts
2705
- * import { readBody, createAgentChatPlugin } from "@agent-native/core/server";
2706
- * import { scriptRegistry } from "../../scripts/registry.js";
2707
- *
2708
- * export default createAgentChatPlugin({
2709
- * scripts: scriptRegistry,
2710
- * systemPrompt: "You are an email assistant...",
2711
- * });
2712
- * ```
86
+ * This used to be gated on "does this thread have prior messages", which
87
+ * flips false the instant a second request comes in for the SAME thread —
88
+ * making turn 2's system prompt diverge from turn 1's and invalidating the
89
+ * prompt-cache prefix on every thread's second request. The flow itself
90
+ * spans two turns (turn 1 asks the personalization questions and waits;
91
+ * turn 2 answers them and only then writes the "done" flag), so this flag
92
+ * is still false when BOTH turns' system prompts are assembled — turn 1
93
+ * and turn 2 come out byte-identical. It only flips once the flow
94
+ * completes, and it never flips back, so every later turn (and every
95
+ * later thread the same owner creates) stays consistent from then on. As
96
+ * a bonus, it also fixes a latent waste: the old gate re-included the
97
+ * ~1.5KB block on turn 1 of every new thread a user ever created, even
98
+ * long after they'd completed personalization once.
2713
99
  */
2714
- async function collectFiles(dir, prefix, depth, results) {
2715
- if (depth > 4 || results.length >= 500)
2716
- return;
2717
- const skip = new Set([
2718
- "node_modules",
2719
- ".git",
2720
- ".next",
2721
- ".output",
2722
- "dist",
2723
- ".cache",
2724
- ".turbo",
2725
- "data",
2726
- ]);
2727
- let entries;
2728
- try {
2729
- const fs = await lazyFs();
2730
- entries = fs.readdirSync(dir, { withFileTypes: true });
2731
- }
2732
- catch {
2733
- return;
2734
- }
2735
- for (const entry of entries) {
2736
- if (results.length >= 500)
2737
- return;
2738
- if (skip.has(entry.name) || entry.name.startsWith("."))
2739
- continue;
2740
- const relPath = prefix ? `${prefix}/${entry.name}` : entry.name;
2741
- const isDir = entry.isDirectory();
2742
- results.push({
2743
- path: relPath,
2744
- name: entry.name,
2745
- type: isDir ? "folder" : "file",
2746
- });
2747
- if (isDir)
2748
- await collectFiles(nodePath.join(dir, entry.name), relPath, depth + 1, results);
2749
- }
2750
- }
2751
- function parseSkillFrontmatter(content) {
2752
- const frontmatter = parseFrontmatter(content);
2753
- const userInvocable = getFrontmatterValue(frontmatter, "user-invocable");
2754
- const scope = normalizeSkillFrontmatterScope(getFrontmatterValue(frontmatter, "scope"));
2755
- return {
2756
- name: getFrontmatterValue(frontmatter, "name"),
2757
- description: getFrontmatterValue(frontmatter, "description"),
2758
- scope,
2759
- userInvocable: userInvocable === undefined
2760
- ? undefined
2761
- : userInvocable.toLowerCase() === "true",
2762
- };
2763
- }
2764
- function normalizeSkillFrontmatterScope(value) {
2765
- if (!value)
2766
- return undefined;
2767
- const normalized = value.trim().toLowerCase();
2768
- if (normalized === "runtime" ||
2769
- normalized === "dev" ||
2770
- normalized === "both") {
2771
- return normalized;
2772
- }
2773
- return "both";
2774
- }
2775
- function isLocalhost(event) {
100
+ export async function hasCompletedFirstSessionPersonalization(owner) {
2776
101
  try {
2777
- const host = event.node?.req?.headers?.host || event.headers?.get?.("host") || "";
2778
- const hostname = host.split(":")[0];
2779
- return (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1");
102
+ const state = await appStateGet(owner, "personalization");
103
+ return state?.done === true;
2780
104
  }
2781
105
  catch {
106
+ // Fail open to "not done" — same default as a brand-new user (block
107
+ // shown) rather than silently skipping personalization because of a
108
+ // transient appstate read error.
2782
109
  return false;
2783
110
  }
2784
111
  }
2785
- function normalizeAgentChatRequestSurface(value) {
2786
- const normalized = (value ?? "").trim().toLowerCase();
2787
- if (normalized === "app" ||
2788
- normalized === "dev-frame" ||
2789
- normalized === "desktop") {
2790
- return normalized;
2791
- }
2792
- return null;
2793
- }
2794
- function isBrowserUserAgent(userAgent) {
2795
- return /Mozilla\/|Chrome\/|Safari\/|Firefox\/|Edg\//i.test(userAgent ?? "");
2796
- }
2797
- export function shouldBlockInProductCodeEditingSurface(input) {
2798
- const surface = normalizeAgentChatRequestSurface(input.surface);
2799
- if (surface === "dev-frame")
2800
- return false;
2801
- if (surface === "desktop")
2802
- return false;
2803
- if (surface === "app")
2804
- return true;
2805
- // Legacy clients used to send `frame` for any iframe, which includes the
2806
- // app-rendered sidebar inside preview frames. Treat unknown explicit surface
2807
- // values as app-owned so they cannot accidentally receive dev code tools.
2808
- if (input.surface && input.surface.trim())
2809
- return true;
2810
- const userAgent = input.userAgent ?? "";
2811
- if (/AgentNativeDesktop/i.test(userAgent))
2812
- return false;
2813
- // Missing header from an older browser client. Be conservative for browser
2814
- // UAs on any host, because preview URLs can be non-local while still running
2815
- // a dev-mode app whose in-product chat would be reloaded by source edits.
2816
- if (isBrowserUserAgent(userAgent))
2817
- return true;
2818
- const host = (input.host ?? "").toLowerCase();
2819
- const hostname = host.split(":")[0] ?? "";
2820
- return (hostname === "localhost" ||
2821
- hostname === "127.0.0.1" ||
2822
- hostname === "::1" ||
2823
- hostname === "[::1]");
2824
- }
2825
- /**
2826
- * Load the sandboxed code-execution tool entries for one action registry:
2827
- * `run-code` plus its `get-code-execution` poll companion. The poll tool is
2828
- * registered ALONGSIDE run-code everywhere run-code appears, so the durable
2829
- * background-execution guidance run-code emits ("check it with
2830
- * get-code-execution") always points at a callable tool. Returns an empty
2831
- * registry when the coding module is unavailable (e.g. bundled browser
2832
- * build), mirroring the prior silent-skip behavior.
2833
- *
2834
- * Exported for tests — the plugin init calls this for the prod, lean, and dev
2835
- * tool bags, so a spec on this helper pins the real registration wiring.
2836
- */
2837
- export async function loadRunCodeToolEntries(supplier, runCodeOptions) {
2838
- try {
2839
- const { createRunCodeEntry, createGetCodeExecutionEntry } = await import("../coding-tools/run-code.js");
2840
- const entries = {
2841
- "run-code": createRunCodeEntry(supplier, runCodeOptions),
2842
- "get-code-execution": createGetCodeExecutionEntry(),
2843
- };
2844
- // Data programs: stored JS scripts executed through this same run-code
2845
- // sandbox, cached in SQL, and rendered by dashboard panels. Registered
2846
- // identically to run-code — same try/dynamic-import guard, silently
2847
- // skipped when the module is unavailable (e.g. bundled browser build) —
2848
- // so every app gets the primitive without per-template wiring.
2849
- try {
2850
- const { initDataPrograms, createDataProgramActions } = await import("../data-programs/index.js");
2851
- const appId = resolveDataProgramsAppId();
2852
- initDataPrograms({ appId, getActions: supplier });
2853
- Object.assign(entries, createDataProgramActions({ appId, getActions: supplier }));
2854
- }
2855
- catch {
2856
- // Module unavailable — skip silently, mirroring the run-code guard above.
2857
- }
2858
- return entries;
2859
- }
2860
- catch {
2861
- // Module unavailable (e.g. bundled browser build) — skip silently.
2862
- return {};
2863
- }
2864
- }
2865
112
  /**
2866
- * Resolve the stable app identity data programs are scoped under. Mirrors
2867
- * the precedent in `cli/agent.ts` (`AGENT_NATIVE_APP_ID` env override, then
2868
- * `APP_ID`, then a fixed fallback) — data programs don't need a per-call
2869
- * agent-supplied appId the way staged datasets do (staged datasets are
2870
- * scratch space the agent explicitly stages into); a data program is a
2871
- * persisted resource scoped to "this app deployment".
113
+ * In-memory rate-limit tracker for `/generate-title`. Keyed by user email,
114
+ * value is recent invocation timestamps within the rolling window. Stale
115
+ * entries are pruned on read.
2872
116
  */
2873
- function resolveDataProgramsAppId() {
2874
- return (process.env.AGENT_NATIVE_APP_ID?.trim() ||
2875
- process.env.APP_ID?.trim() ||
2876
- process.env.APP_NAME?.trim() ||
2877
- "app");
2878
- }
2879
- function isTruthyEnv(value) {
2880
- return /^(1|true|yes|on)$/i.test(value?.trim() ?? "");
2881
- }
2882
- function isLoopbackAppUrl(value) {
2883
- const raw = value?.trim();
2884
- if (!raw)
2885
- return false;
2886
- const candidates = /^[a-z][a-z0-9+.-]*:\/\//i.test(raw)
2887
- ? [raw]
2888
- : [raw, `http://${raw}`];
2889
- for (const candidate of candidates) {
2890
- try {
2891
- const url = new URL(candidate);
2892
- const host = url.hostname.toLowerCase().replace(/^\[|\]$/g, "");
2893
- if (host === "localhost" ||
2894
- host === "127.0.0.1" ||
2895
- host === "0.0.0.0" ||
2896
- host === "::1" ||
2897
- host === "tauri.localhost" ||
2898
- host.endsWith(".localhost")) {
2899
- return true;
2900
- }
2901
- }
2902
- catch { }
2903
- }
2904
- return false;
2905
- }
2906
- export function shouldDisableRecurringJobsRuntime(env = process.env) {
2907
- if (isTruthyEnv(env.AGENT_NATIVE_DISABLE_RECURRING_JOBS))
2908
- return true;
2909
- const isLocalRuntime = env.NODE_ENV === "development" ||
2910
- env.NODE_ENV === "test" ||
2911
- [
2912
- env.APP_URL,
2913
- env.BETTER_AUTH_URL,
2914
- env.DEPLOY_URL,
2915
- env.URL,
2916
- env.VITE_APP_URL,
2917
- env.VITE_WORKSPACE_GATEWAY_URL,
2918
- env.WORKSPACE_GATEWAY_URL,
2919
- ].some(isLoopbackAppUrl);
2920
- if (isLocalRuntime &&
2921
- isTruthyEnv(env.AGENT_NATIVE_ENABLE_LOCAL_RECURRING_JOBS)) {
2922
- return false;
2923
- }
2924
- return isLocalRuntime;
2925
- }
2926
- export async function finalizeClaimedAgentChatProcessRunFailure(runId, err, deps = {}) {
2927
- const readClaim = deps.readBackgroundRunClaim ?? readBackgroundRunClaim;
2928
- const record = deps.recordRunDiagnostic ?? recordRunDiagnostic;
2929
- const setError = deps.setRunError ?? setRunError;
2930
- const setTerminalReason = deps.setRunTerminalReason ?? setRunTerminalReason;
2931
- const updateStatus = deps.updateRunStatusIfRunning ?? updateRunStatusIfRunning;
2932
- const ensureTerminal = deps.ensureTerminalRunEvent ?? ensureTerminalRunEvent;
2933
- const message = err instanceof Error ? err.message : String(err);
2934
- await record(runId, RUN_DIAG_STAGE.routeThrew, message).catch(() => { });
2935
- const claim = await readClaim(runId).catch(() => null);
2936
- if (claim?.status !== "running" ||
2937
- claim.dispatchMode !== "background-processing") {
2938
- return false;
2939
- }
2940
- await setError(runId, CLAIMED_BACKGROUND_WORKER_FAILED_ERROR_EVENT.errorCode, `${CLAIMED_BACKGROUND_WORKER_FAILED_ERROR_EVENT.details} setupError=${message}`).catch(() => { });
2941
- const statusUpdated = await updateStatus(runId, "errored").catch(() => false);
2942
- if (statusUpdated) {
2943
- await setTerminalReason(runId, CLAIMED_BACKGROUND_WORKER_FAILED_ERROR_EVENT.errorCode).catch(() => { });
2944
- }
2945
- await ensureTerminal(runId, CLAIMED_BACKGROUND_WORKER_FAILED_ERROR_EVENT).catch(() => { });
2946
- return true;
2947
- }
117
+ const generateTitleRateLimit = new Map();
118
+ /** Only sweep drained rate-limit entries once the map grows past this size,
119
+ * so the common small-map case stays O(1). */
120
+ const RATE_LIMIT_SWEEP_THRESHOLD = 1000;
2948
121
  export function createAgentChatPlugin(options) {
2949
122
  return (nitroApp) => {
2950
123
  markDefaultPluginProvided(nitroApp, "agent-chat");
@@ -3106,8 +279,8 @@ export function createAgentChatPlugin(options) {
3106
279
  const refreshScreenTool = createRefreshScreenEntry();
3107
280
  const frameworkContextTool = createFrameworkContextEntry();
3108
281
  const leanPrompt = options?.leanPrompt === true;
3109
- const skipFilesContext = leanPrompt || options?.skipFilesContext === true;
3110
282
  const lazyContext = options?.lazyContext !== false && !leanPrompt;
283
+ const skipFilesContext = leanPrompt || (options?.skipFilesContext ?? lazyContext);
3111
284
  const urlTools = createUrlTools();
3112
285
  const engineScripts = await createAgentEngineScriptEntries(options?.appId);
3113
286
  const loopSettingsScripts = await createAgentLoopSettingsScriptEntries();
@@ -3275,6 +448,15 @@ export function createAgentChatPlugin(options) {
3275
448
  // `*All` sets are reserved for `httpActions`, which keeps agent-hidden
3276
449
  // actions reachable from the frontend / HTTP.
3277
450
  const templateScripts = filterAgentTools(templateScriptsAll);
451
+ // Compact is the safe default for every app, including generated and
452
+ // third-party apps that have not curated a starter list yet. Keep the
453
+ // app's own action surface immediately callable; framework, provider,
454
+ // and MCP tools remain discoverable through tool-search.
455
+ //
456
+ // This is the template-only baseline; the final `effectiveInitialToolNames`
457
+ // (below, after the run-code tools are built) additionally folds in
458
+ // whatever `generateCorpusToolsPrompt` teaches by name for this request.
459
+ const templateInitialToolNames = resolveInitialToolNames(templateScripts, options?.initialToolNames);
3278
460
  const discoveredActions = filterAgentTools(discoveredActionsAll);
3279
461
  // Per-request owner is read from the AsyncLocalStorage run context
3280
462
  // (populated by prepareRun). Module-scope `let` would race across
@@ -3488,6 +670,34 @@ export function createAgentChatPlugin(options) {
3488
670
  bridgeTools: options?.codeExecution?.bridgeTools,
3489
671
  })
3490
672
  : {};
673
+ // Registry `generateCorpusToolsPrompt` (below) reads from to decide what
674
+ // it teaches by name — kept as one value so the prompt text and the
675
+ // initial-tool-set expansion just below can never drift apart.
676
+ const corpusPromptRegistry = {
677
+ ...templateScripts,
678
+ ...(canToggle
679
+ ? devRunCodeTool
680
+ : resolvedProdCodeExec !== "off"
681
+ ? runCodeTool
682
+ : {}),
683
+ };
684
+ // `generateCorpusToolsPrompt` teaches provider-api-request /
685
+ // provider-corpus-job / query-staged-dataset / run-code BY NAME
686
+ // whenever they're registered, regardless of whether they made the
687
+ // curated initial-tool-names list — a prior comment here (since
688
+ // removed) warned this exact mismatch "caused prod runs to waste
689
+ // turns": the model reads about a tool in the system prompt, tries to
690
+ // call it immediately, and finds it missing from the very first
691
+ // engine request until it calls tool-search. Fold in exactly the tool
692
+ // names the corpus prompt would announce for THIS registry so the two
693
+ // always agree. `corpusToolNamesTaughtByPrompt` returns [] for apps
694
+ // that never emit the corpus prompt (no provider/run-code tools
695
+ // registered), so this never silently expands the initial set for
696
+ // apps that don't teach these tools by name.
697
+ const corpusToolNames = corpusToolNamesTaughtByPrompt(corpusPromptRegistry);
698
+ const effectiveInitialToolNames = corpusToolNames.length > 0
699
+ ? [...new Set([...templateInitialToolNames, ...corpusToolNames])]
700
+ : templateInitialToolNames;
3491
701
  const resolveExtraContext = async (event, owner) => {
3492
702
  if (!options?.extraContext)
3493
703
  return "";
@@ -3808,7 +1018,7 @@ export function createAgentChatPlugin(options) {
3808
1018
  ...(resolvedProdCodeExec !== "off" ? runCodeTool : {}),
3809
1019
  ...prodCodingTools,
3810
1020
  });
3811
- const a2aToolSurface = createA2AEngineToolSurface(actionsToEngineTools(a2aActions), options?.initialToolNames);
1021
+ const a2aToolSurface = createA2AEngineToolSurface(actionsToEngineTools(a2aActions), effectiveInitialToolNames);
3812
1022
  // Precise current time rides the user message (not the cached
3813
1023
  // system-prompt prefix) — same pattern as the interactive handler.
3814
1024
  const a2aMessages = [
@@ -3900,15 +1110,8 @@ export function createAgentChatPlugin(options) {
3900
1110
  // Dev: actions are invoked via bash — emit `pnpm action name --arg <type>`
3901
1111
  // and include discoveredActions too, since those are also missing
3902
1112
  // from the dev tool registry.
3903
- const corpusToolsPrompt = generateCorpusToolsPrompt({
3904
- ...templateScripts,
3905
- ...(canToggle
3906
- ? devRunCodeTool
3907
- : resolvedProdCodeExec !== "off"
3908
- ? runCodeTool
3909
- : {}),
3910
- });
3911
- const prodActionsPrompt = generateActionsPrompt(templateScripts, "tool") + corpusToolsPrompt;
1113
+ const corpusToolsPrompt = generateCorpusToolsPrompt(corpusPromptRegistry);
1114
+ const prodActionsPrompt = generateActionsPrompt(templateScripts, "tool", lazyContext ? effectiveInitialToolNames : undefined) + corpusToolsPrompt;
3912
1115
  const devActionsPrompt = generateActionsPrompt({ ...discoveredActions, ...templateScripts }, "cli") + corpusToolsPrompt;
3913
1116
  // Build system prompts — dynamic functions that pre-load resources per-request.
3914
1117
  // Production gets PROD_FRAMEWORK_PROMPT, dev gets DEV_FRAMEWORK_PROMPT.
@@ -4000,7 +1203,15 @@ export function createAgentChatPlugin(options) {
4000
1203
  ...(resolvedProdCodeExec !== "off" ? runCodeTool : {}),
4001
1204
  ...prodCodingTools,
4002
1205
  });
4003
- const mcpTools = actionsToEngineTools(mcpActions);
1206
+ // Same compact initial-tool surface as interactive chat and A2A:
1207
+ // template actions + the small framework default set stay visible
1208
+ // on the first request; everything else (provider, MCP, extension
1209
+ // schemas) is reachable through the attached `tool-search` entry
1210
+ // via `runAgentLoop`'s mid-run tool expansion. Without this, every
1211
+ // external host calling `ask_app` (MCP) paid for a near-full
1212
+ // catalog on its very first request, undermining the compact MCP
1213
+ // catalog this surface is supposed to keep external callers on.
1214
+ const mcpToolSurface = createA2AEngineToolSurface(actionsToEngineTools(mcpActions), effectiveInitialToolNames);
4004
1215
  const resources = await loadResourcesForPrompt(SHARED_OWNER, lazyContext, options?.appId);
4005
1216
  const schemaBlock = lazyContext
4006
1217
  ? ""
@@ -4036,7 +1247,8 @@ export function createAgentChatPlugin(options) {
4036
1247
  engine: mcpEngine,
4037
1248
  model,
4038
1249
  systemPrompt,
4039
- tools: mcpTools,
1250
+ tools: mcpToolSurface.tools,
1251
+ availableTools: mcpToolSurface.availableTools,
4040
1252
  messages: [
4041
1253
  {
4042
1254
  role: "user",
@@ -4525,7 +1737,7 @@ export function createAgentChatPlugin(options) {
4525
1737
  // and tokens that minimal/voice apps don't need.
4526
1738
  const leanBasePrompt = (options?.systemPrompt ?? "") + prodActionsPrompt;
4527
1739
  const anonymousReadOnlyPrompt = (options?.systemPrompt ?? PROD_FRAMEWORK_PROMPT_COMPACT) +
4528
- generateActionsPrompt(filterReadOnlyActions(templateScripts), "tool") +
1740
+ generateActionsPrompt(filterReadOnlyActions(templateScripts), "tool", lazyContext ? effectiveInitialToolNames : undefined) +
4529
1741
  "\n\nYou are answering from a public shared page. Treat the visible resource as read-only: do not create, edit, delete, comment on, share, or otherwise mutate app data. If the user asks for a change, describe what you would change or suggest signing in to edit.";
4530
1742
  // Per-request preamble shared by both prod and dev handlers. Resolves
4531
1743
  // owner + user API key onto the AsyncLocalStorage run context so
@@ -4565,19 +1777,6 @@ export function createAgentChatPlugin(options) {
4565
1777
  return "";
4566
1778
  return getModelFamilyOverlay(model);
4567
1779
  };
4568
- /**
4569
- * Returns whether this request is for a brand-new thread (no prior
4570
- * messages). Used to gate the First-Session Personalization block:
4571
- * once a thread has history the block is dead weight on every request.
4572
- *
4573
- * prepareRequest stashes `details.threadId` as `_requestThreadId` on
4574
- * runCtx before systemPrompt is assembled. A new thread has no threadId
4575
- * (the UI passes undefined until the first message creates the thread).
4576
- */
4577
- const isNewThread = () => {
4578
- const runCtx = ensureRequestRunContext();
4579
- return !runCtx?._requestThreadId;
4580
- };
4581
1780
  const runtimeContextForEvent = (event) => {
4582
1781
  const tzRaw = getHeader(event, "x-user-timezone");
4583
1782
  const timezone = typeof tzRaw === "string" &&
@@ -4631,11 +1830,13 @@ Non-code requests are still fine on this surface: read data, navigate the UI, su
4631
1830
  const codeEditingSurfaceRestriction = shouldBlockInProductCodeEditing(event)
4632
1831
  ? APP_RENDERED_CHAT_NO_DIRECT_CODE_PROMPT
4633
1832
  : "";
4634
- // Personalization block: only include on new threads (no prior messages).
4635
- // Once a thread exists, the agent has already run (or skipped) the flow.
4636
- const personalizationBlock = isNewThread()
4637
- ? FIRST_SESSION_PERSONALIZATION
4638
- : "";
1833
+ // Personalization block: included until this owner has finished (or
1834
+ // skipped) the flow see hasCompletedFirstSessionPersonalization
1835
+ // for why this is gated on the owner-scoped appstate flag rather
1836
+ // than "is this a new thread" (keeps turn 1 and turn 2 identical).
1837
+ const personalizationBlock = (await hasCompletedFirstSessionPersonalization(owner))
1838
+ ? ""
1839
+ : FIRST_SESSION_PERSONALIZATION;
4639
1840
  // Per-model overlay: nudge GPT/Gemini engines toward our behavioral norms.
4640
1841
  const modelOverlay = resolveModelOverlay();
4641
1842
  // Stable-first ordering: base prompt / schema / extra come before
@@ -4676,12 +1877,6 @@ Non-code requests are still fine on this surface: read data, navigate the UI, su
4676
1877
  durableBackgroundRuns: options?.durableBackgroundRuns,
4677
1878
  finalResponseGuard: options?.finalResponseGuard,
4678
1879
  prepareRequest: async (details) => {
4679
- // Stash the threadId on runCtx so systemPrompt can check isNewThread().
4680
- // prepareRequest fires before systemPromptPromise starts, so this is safe.
4681
- const runCtxForPrepare = ensureRequestRunContext();
4682
- if (runCtxForPrepare && details.threadId) {
4683
- runCtxForPrepare._requestThreadId = details.threadId;
4684
- }
4685
1880
  if (details.threadId && details.ownerEmail) {
4686
1881
  const existingThread = await getThread(details.threadId);
4687
1882
  if (existingThread) {
@@ -4729,7 +1924,7 @@ Non-code requests are still fine on this surface: read data, navigate the UI, su
4729
1924
  };
4730
1925
  },
4731
1926
  skipFilesContext,
4732
- initialToolNames: options?.initialToolNames,
1927
+ initialToolNames: effectiveInitialToolNames,
4733
1928
  ...(options?.toolLimits ? { toolLimits: options.toolLimits } : {}),
4734
1929
  onEngineResolved: (engine, model) => {
4735
1930
  const runCtx = ensureRequestRunContext();
@@ -4772,7 +1967,7 @@ Non-code requests are still fine on this surface: read data, navigate the UI, su
4772
1967
  finalResponseGuard: options?.finalResponseGuard,
4773
1968
  prepareRequest: options?.prepareRequest,
4774
1969
  skipFilesContext: true,
4775
- initialToolNames: options?.initialToolNames,
1970
+ initialToolNames: effectiveInitialToolNames,
4776
1971
  onEngineResolved: (engine, model) => {
4777
1972
  const runCtx = ensureRequestRunContext();
4778
1973
  if (runCtx) {
@@ -4859,9 +2054,9 @@ Non-code requests are still fine on this surface: read data, navigate the UI, su
4859
2054
  systemPrompt: async (event) => {
4860
2055
  const { owner, extra } = await prepareRun(event);
4861
2056
  const runtimeContext = runtimeContextForEvent(event);
4862
- const personalizationBlock = isNewThread()
4863
- ? FIRST_SESSION_PERSONALIZATION
4864
- : "";
2057
+ const personalizationBlock = (await hasCompletedFirstSessionPersonalization(owner))
2058
+ ? ""
2059
+ : FIRST_SESSION_PERSONALIZATION;
4865
2060
  const modelOverlay = resolveModelOverlay();
4866
2061
  // Stable-first ordering: runtimeContext (day-granular) is
4867
2062
  // appended LAST so a day rollover invalidates as little of the
@@ -4890,10 +2085,6 @@ Non-code requests are still fine on this surface: read data, navigate the UI, su
4890
2085
  durableBackgroundRuns: options?.durableBackgroundRuns,
4891
2086
  finalResponseGuard: options?.finalResponseGuard,
4892
2087
  prepareRequest: async (details) => {
4893
- const runCtxForPrepare = ensureRequestRunContext();
4894
- if (runCtxForPrepare && details.threadId) {
4895
- runCtxForPrepare._requestThreadId = details.threadId;
4896
- }
4897
2088
  if (details.threadId && details.ownerEmail) {
4898
2089
  const existingThread = await getThread(details.threadId);
4899
2090
  if (existingThread) {
@@ -4909,7 +2100,7 @@ Non-code requests are still fine on this surface: read data, navigate the UI, su
4909
2100
  return options?.prepareRequest?.(details);
4910
2101
  },
4911
2102
  skipFilesContext,
4912
- initialToolNames: options?.initialToolNames,
2103
+ initialToolNames: effectiveInitialToolNames,
4913
2104
  ...(options?.toolLimits ? { toolLimits: options.toolLimits } : {}),
4914
2105
  onEngineResolved: (engine, model) => {
4915
2106
  const runCtx = ensureRequestRunContext();
@@ -5057,6 +2248,19 @@ Non-code requests are still fine on this surface: read data, navigate the UI, su
5057
2248
  engine.defaultModel ??
5058
2249
  resolvedModel;
5059
2250
  const model = normalizeModelForEngine(engine, modelCandidate);
2251
+ // Intentionally NOT setting `initialToolNames` here (unlike
2252
+ // schedulerDeps/dispatcher above). `AgentTeamRunConfig.actions`
2253
+ // (buildSubAgentActions()) is already a small curated registry
2254
+ // — it excludes jobTools/automationTools/notificationTools/
2255
+ // progressTools/fetchTool/webSearchTool/toolActions, the exact
2256
+ // bloat those two surfaces needed to defer. There is no larger
2257
+ // catalog behind it for tool-search to expand into: it IS the
2258
+ // sub-agent's entire tool set. Worse, `buildSubAgentSystemPrompt`
2259
+ // (agent-teams.ts) literally lists every key of `actions` as
2260
+ // "Your available actions (...) work directly" — filtering to
2261
+ // anything narrower would contradict what the sub-agent was
2262
+ // just told, and filtering to the full set would only add a
2263
+ // tool-search schema with nothing new for it to find.
5060
2264
  return {
5061
2265
  baseSystemPrompt: basePrompt,
5062
2266
  actions: buildSubAgentActions(),
@@ -6767,6 +3971,19 @@ Non-code requests are still fine on this surface: read data, navigate the UI, su
6767
3971
  : await buildSchemaBlock(owner, databaseToolsMode);
6768
3972
  return basePrompt + resources + schemaBlock;
6769
3973
  },
3974
+ // `basePrompt` above is the same prompt the interactive chat
3975
+ // handler builds, so it teaches the same template actions plus
3976
+ // `manage-jobs` (Extended Capabilities / recurring jobs) and
3977
+ // `manage-progress` (SHARED_RULE_14) BY NAME — both are present in
3978
+ // getActions() via jobTools/progressTools. Keep the job runner's
3979
+ // first request on the same compact surface as interactive chat
3980
+ // instead of the full jobTools/automationTools/notificationTools/
3981
+ // fetchTool/webSearchTool/toolActions catalog every tick.
3982
+ getInitialToolNames: () => [
3983
+ ...effectiveInitialToolNames,
3984
+ "manage-jobs",
3985
+ "manage-progress",
3986
+ ],
6770
3987
  apiKey: options?.apiKey,
6771
3988
  model: options?.model,
6772
3989
  appId: options?.appId,
@@ -7038,6 +4255,13 @@ Non-code requests are still fine on this surface: read data, navigate the UI, su
7038
4255
  : await buildSchemaBlock(owner, databaseToolsMode);
7039
4256
  return basePrompt + resources + schemaBlock;
7040
4257
  },
4258
+ // See the matching comment on schedulerDeps.getInitialToolNames
4259
+ // above — same shared `basePrompt`, same reasoning.
4260
+ getInitialToolNames: () => [
4261
+ ...effectiveInitialToolNames,
4262
+ "manage-jobs",
4263
+ "manage-progress",
4264
+ ],
7041
4265
  apiKey: options?.apiKey,
7042
4266
  model: options?.model,
7043
4267
  appId: options?.appId,
@@ -7079,63 +4303,7 @@ Non-code requests are still fine on this surface: read data, navigate the UI, su
7079
4303
  * In production, provides only the default system prompt.
7080
4304
  */
7081
4305
  export const defaultAgentChatPlugin = createAgentChatPlugin();
7082
- // ---------------------------------------------------------------------------
7083
- // MCP client glue — a shared manager reference + a /_agent-native/mcp/status
7084
- // route so onboarding / settings UIs can see which MCP servers are live.
7085
- // ---------------------------------------------------------------------------
7086
- let _globalMcpManager = null;
7087
- function setGlobalMcpManager(manager) {
7088
- _globalMcpManager = manager;
7089
- }
7090
- /** Internal: access the current process's MCP client manager, if any. */
7091
- export function getGlobalMcpManager() {
7092
- return _globalMcpManager;
7093
- }
7094
- /** Internal: reload the process's MCP client manager after persisted settings change. */
7095
- export async function refreshGlobalMcpManager() {
7096
- const manager = getGlobalMcpManager();
7097
- if (!manager)
7098
- return false;
7099
- await manager.reconfigure(await buildMergedConfig());
7100
- return true;
7101
- }
7102
- function mountMcpHubStatusRoute(nitroApp) {
7103
- const mountedApps = (globalThis.__agentNativeMcpHubStatusMountedApps ??= new WeakSet());
7104
- if (mountedApps.has(nitroApp))
7105
- return;
7106
- mountedApps.add(nitroApp);
7107
- try {
7108
- getH3App(nitroApp).use("/_agent-native/mcp/hub/status", defineEventHandler(async (event) => {
7109
- if (getMethod(event) !== "GET") {
7110
- setResponseStatus(event, 405);
7111
- return { error: "Method not allowed" };
7112
- }
7113
- setResponseHeader(event, "Content-Type", "application/json");
7114
- return getHubStatus();
7115
- }));
7116
- }
7117
- catch (err) {
7118
- console.warn(`[mcp-client] Failed to mount /_agent-native/mcp/hub/status: ${err?.message ?? err}`);
7119
- }
7120
- }
7121
- function mountMcpStatusRoute(nitroApp, manager) {
7122
- // Idempotent per Nitro app; dev-all may host multiple templates in one process.
7123
- const mountedApps = (globalThis.__agentNativeMcpStatusMountedApps ??= new WeakSet());
7124
- if (mountedApps.has(nitroApp))
7125
- return;
7126
- mountedApps.add(nitroApp);
7127
- try {
7128
- getH3App(nitroApp).use("/_agent-native/mcp/status", defineEventHandler(async (event) => {
7129
- if (getMethod(event) !== "GET") {
7130
- setResponseStatus(event, 405);
7131
- return { error: "Method not allowed" };
7132
- }
7133
- setResponseHeader(event, "Content-Type", "application/json");
7134
- return manager.getStatus();
7135
- }));
7136
- }
7137
- catch (err) {
7138
- console.warn(`[mcp-client] Failed to mount /_agent-native/mcp/status: ${err?.message ?? err}`);
7139
- }
7140
- }
4306
+ import { setGlobalMcpManager, getGlobalMcpManager, refreshGlobalMcpManager, mountMcpHubStatusRoute, mountMcpStatusRoute, } from "./agent-chat/mcp-glue.js";
4307
+ export { getGlobalMcpManager };
4308
+ export { refreshGlobalMcpManager };
7141
4309
  //# sourceMappingURL=agent-chat-plugin.js.map