@agent-native/core 0.5.0-dev.b51eaae → 0.7.1

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 (1011) hide show
  1. package/README.md +49 -37
  2. package/dist/a2a/agent-card.d.ts.map +1 -1
  3. package/dist/a2a/agent-card.js +12 -1
  4. package/dist/a2a/agent-card.js.map +1 -1
  5. package/dist/a2a/client.d.ts +11 -0
  6. package/dist/a2a/client.d.ts.map +1 -1
  7. package/dist/a2a/client.js +38 -1
  8. package/dist/a2a/client.js.map +1 -1
  9. package/dist/a2a/index.d.ts +1 -1
  10. package/dist/a2a/index.d.ts.map +1 -1
  11. package/dist/a2a/index.js +1 -1
  12. package/dist/a2a/index.js.map +1 -1
  13. package/dist/a2a/server.d.ts +4 -0
  14. package/dist/a2a/server.d.ts.map +1 -1
  15. package/dist/a2a/server.js +53 -8
  16. package/dist/a2a/server.js.map +1 -1
  17. package/dist/a2a/types.d.ts +1 -0
  18. package/dist/a2a/types.d.ts.map +1 -1
  19. package/dist/action.d.ts +64 -30
  20. package/dist/action.d.ts.map +1 -1
  21. package/dist/action.js +224 -27
  22. package/dist/action.js.map +1 -1
  23. package/dist/agent/engine/ai-sdk-engine.d.ts +24 -0
  24. package/dist/agent/engine/ai-sdk-engine.d.ts.map +1 -0
  25. package/dist/agent/engine/ai-sdk-engine.js +302 -0
  26. package/dist/agent/engine/ai-sdk-engine.js.map +1 -0
  27. package/dist/agent/engine/anthropic-engine.d.ts +24 -0
  28. package/dist/agent/engine/anthropic-engine.d.ts.map +1 -0
  29. package/dist/agent/engine/anthropic-engine.js +169 -0
  30. package/dist/agent/engine/anthropic-engine.js.map +1 -0
  31. package/dist/agent/engine/builtin.d.ts +12 -0
  32. package/dist/agent/engine/builtin.d.ts.map +1 -0
  33. package/dist/agent/engine/builtin.js +72 -0
  34. package/dist/agent/engine/builtin.js.map +1 -0
  35. package/dist/agent/engine/index.d.ts +9 -0
  36. package/dist/agent/engine/index.d.ts.map +1 -0
  37. package/dist/agent/engine/index.js +8 -0
  38. package/dist/agent/engine/index.js.map +1 -0
  39. package/dist/agent/engine/registry.d.ts +61 -0
  40. package/dist/agent/engine/registry.d.ts.map +1 -0
  41. package/dist/agent/engine/registry.js +101 -0
  42. package/dist/agent/engine/registry.js.map +1 -0
  43. package/dist/agent/engine/translate-ai-sdk.d.ts +20 -0
  44. package/dist/agent/engine/translate-ai-sdk.d.ts.map +1 -0
  45. package/dist/agent/engine/translate-ai-sdk.js +174 -0
  46. package/dist/agent/engine/translate-ai-sdk.js.map +1 -0
  47. package/dist/agent/engine/translate-anthropic.d.ts +23 -0
  48. package/dist/agent/engine/translate-anthropic.d.ts.map +1 -0
  49. package/dist/agent/engine/translate-anthropic.js +140 -0
  50. package/dist/agent/engine/translate-anthropic.js.map +1 -0
  51. package/dist/agent/engine/types.d.ts +168 -0
  52. package/dist/agent/engine/types.d.ts.map +1 -0
  53. package/dist/agent/engine/types.js +13 -0
  54. package/dist/agent/engine/types.js.map +1 -0
  55. package/dist/agent/production-agent.d.ts +48 -2
  56. package/dist/agent/production-agent.d.ts.map +1 -1
  57. package/dist/agent/production-agent.js +369 -79
  58. package/dist/agent/production-agent.js.map +1 -1
  59. package/dist/agent/run-manager.d.ts +1 -1
  60. package/dist/agent/run-manager.d.ts.map +1 -1
  61. package/dist/agent/run-manager.js +15 -9
  62. package/dist/agent/run-manager.js.map +1 -1
  63. package/dist/agent/run-store.d.ts.map +1 -1
  64. package/dist/agent/run-store.js +5 -5
  65. package/dist/agent/run-store.js.map +1 -1
  66. package/dist/agent/thread-data-builder.d.ts +1 -0
  67. package/dist/agent/thread-data-builder.d.ts.map +1 -1
  68. package/dist/agent/thread-data-builder.js +4 -1
  69. package/dist/agent/thread-data-builder.js.map +1 -1
  70. package/dist/agent/types.d.ts +23 -2
  71. package/dist/agent/types.d.ts.map +1 -1
  72. package/dist/application-state/handlers.d.ts +8 -8
  73. package/dist/application-state/handlers.d.ts.map +1 -1
  74. package/dist/application-state/handlers.js +3 -2
  75. package/dist/application-state/handlers.js.map +1 -1
  76. package/dist/application-state/script-helpers.d.ts.map +1 -1
  77. package/dist/application-state/script-helpers.js +47 -9
  78. package/dist/application-state/script-helpers.js.map +1 -1
  79. package/dist/chat-threads/store.d.ts +14 -0
  80. package/dist/chat-threads/store.d.ts.map +1 -1
  81. package/dist/chat-threads/store.js +32 -0
  82. package/dist/chat-threads/store.js.map +1 -1
  83. package/dist/cli/create-workspace.d.ts +8 -0
  84. package/dist/cli/create-workspace.d.ts.map +1 -0
  85. package/dist/cli/create-workspace.js +18 -0
  86. package/dist/cli/create-workspace.js.map +1 -0
  87. package/dist/cli/create.d.ts +36 -2
  88. package/dist/cli/create.d.ts.map +1 -1
  89. package/dist/cli/create.js +509 -61
  90. package/dist/cli/create.js.map +1 -1
  91. package/dist/cli/index.js +73 -6
  92. package/dist/cli/index.js.map +1 -1
  93. package/dist/cli/workspacify.d.ts +18 -0
  94. package/dist/cli/workspacify.d.ts.map +1 -0
  95. package/dist/cli/workspacify.js +74 -0
  96. package/dist/cli/workspacify.js.map +1 -0
  97. package/dist/client/AgentPanel.d.ts +6 -2
  98. package/dist/client/AgentPanel.d.ts.map +1 -1
  99. package/dist/client/AgentPanel.js +314 -180
  100. package/dist/client/AgentPanel.js.map +1 -1
  101. package/dist/client/AgentTaskCard.d.ts +12 -0
  102. package/dist/client/AgentTaskCard.d.ts.map +1 -0
  103. package/dist/client/AgentTaskCard.js +146 -0
  104. package/dist/client/AgentTaskCard.js.map +1 -0
  105. package/dist/client/AssistantChat.d.ts +13 -2
  106. package/dist/client/AssistantChat.d.ts.map +1 -1
  107. package/dist/client/AssistantChat.js +344 -122
  108. package/dist/client/AssistantChat.js.map +1 -1
  109. package/dist/client/MultiTabAssistantChat.d.ts +7 -1
  110. package/dist/client/MultiTabAssistantChat.d.ts.map +1 -1
  111. package/dist/client/MultiTabAssistantChat.js +345 -63
  112. package/dist/client/MultiTabAssistantChat.js.map +1 -1
  113. package/dist/client/PoweredByBadge.js +2 -2
  114. package/dist/client/PoweredByBadge.js.map +1 -1
  115. package/dist/client/Turnstile.d.ts.map +1 -1
  116. package/dist/client/Turnstile.js +2 -3
  117. package/dist/client/Turnstile.js.map +1 -1
  118. package/dist/client/agent-chat-adapter.d.ts.map +1 -1
  119. package/dist/client/agent-chat-adapter.js +63 -2
  120. package/dist/client/agent-chat-adapter.js.map +1 -1
  121. package/dist/client/agent-chat.d.ts +14 -1
  122. package/dist/client/agent-chat.d.ts.map +1 -1
  123. package/dist/client/agent-chat.js +4 -2
  124. package/dist/client/agent-chat.js.map +1 -1
  125. package/dist/client/components/CodeAgentIndicator.d.ts +14 -0
  126. package/dist/client/components/CodeAgentIndicator.d.ts.map +1 -0
  127. package/dist/client/components/CodeAgentIndicator.js +29 -0
  128. package/dist/client/components/CodeAgentIndicator.js.map +1 -0
  129. package/dist/client/components/CodeRequiredDialog.d.ts.map +1 -1
  130. package/dist/client/components/CodeRequiredDialog.js +86 -5
  131. package/dist/client/components/CodeRequiredDialog.js.map +1 -1
  132. package/dist/client/composer/MentionPopover.d.ts +4 -1
  133. package/dist/client/composer/MentionPopover.d.ts.map +1 -1
  134. package/dist/client/composer/MentionPopover.js +51 -8
  135. package/dist/client/composer/MentionPopover.js.map +1 -1
  136. package/dist/client/composer/TiptapComposer.d.ts +8 -1
  137. package/dist/client/composer/TiptapComposer.d.ts.map +1 -1
  138. package/dist/client/composer/TiptapComposer.js +149 -17
  139. package/dist/client/composer/TiptapComposer.js.map +1 -1
  140. package/dist/client/composer/index.d.ts +1 -1
  141. package/dist/client/composer/index.d.ts.map +1 -1
  142. package/dist/client/composer/types.d.ts +6 -1
  143. package/dist/client/composer/types.d.ts.map +1 -1
  144. package/dist/client/composer/use-mention-search.d.ts.map +1 -1
  145. package/dist/client/composer/use-mention-search.js +46 -13
  146. package/dist/client/composer/use-mention-search.js.map +1 -1
  147. package/dist/client/frame-protocol.d.ts +54 -0
  148. package/dist/client/frame-protocol.d.ts.map +1 -0
  149. package/dist/client/frame-protocol.js +9 -0
  150. package/dist/client/frame-protocol.js.map +1 -0
  151. package/dist/client/frame.d.ts +56 -0
  152. package/dist/client/frame.d.ts.map +1 -0
  153. package/dist/client/{harness.js → frame.js} +49 -26
  154. package/dist/client/frame.js.map +1 -0
  155. package/dist/client/index.d.ts +7 -3
  156. package/dist/client/index.d.ts.map +1 -1
  157. package/dist/client/index.js +6 -3
  158. package/dist/client/index.js.map +1 -1
  159. package/dist/client/integrations/IntegrationCard.d.ts +6 -0
  160. package/dist/client/integrations/IntegrationCard.d.ts.map +1 -0
  161. package/dist/client/integrations/IntegrationCard.js +45 -0
  162. package/dist/client/integrations/IntegrationCard.js.map +1 -0
  163. package/dist/client/integrations/IntegrationsPanel.d.ts +2 -0
  164. package/dist/client/integrations/IntegrationsPanel.d.ts.map +1 -0
  165. package/dist/client/integrations/IntegrationsPanel.js +162 -0
  166. package/dist/client/integrations/IntegrationsPanel.js.map +1 -0
  167. package/dist/client/integrations/index.d.ts +4 -0
  168. package/dist/client/integrations/index.d.ts.map +1 -0
  169. package/dist/client/integrations/index.js +3 -0
  170. package/dist/client/integrations/index.js.map +1 -0
  171. package/dist/client/integrations/useIntegrationStatus.d.ts +15 -0
  172. package/dist/client/integrations/useIntegrationStatus.d.ts.map +1 -0
  173. package/dist/client/integrations/useIntegrationStatus.js +37 -0
  174. package/dist/client/integrations/useIntegrationStatus.js.map +1 -0
  175. package/dist/client/onboarding/OnboardingBanner.d.ts +13 -0
  176. package/dist/client/onboarding/OnboardingBanner.d.ts.map +1 -0
  177. package/dist/client/onboarding/OnboardingBanner.js +36 -0
  178. package/dist/client/onboarding/OnboardingBanner.js.map +1 -0
  179. package/dist/client/onboarding/OnboardingPanel.d.ts +16 -0
  180. package/dist/client/onboarding/OnboardingPanel.d.ts.map +1 -0
  181. package/dist/client/onboarding/OnboardingPanel.js +360 -0
  182. package/dist/client/onboarding/OnboardingPanel.js.map +1 -0
  183. package/dist/client/onboarding/SetupButton.d.ts +10 -0
  184. package/dist/client/onboarding/SetupButton.d.ts.map +1 -0
  185. package/dist/client/onboarding/SetupButton.js +26 -0
  186. package/dist/client/onboarding/SetupButton.js.map +1 -0
  187. package/dist/client/onboarding/index.d.ts +12 -0
  188. package/dist/client/onboarding/index.d.ts.map +1 -0
  189. package/dist/client/onboarding/index.js +11 -0
  190. package/dist/client/onboarding/index.js.map +1 -0
  191. package/dist/client/onboarding/use-onboarding.d.ts +34 -0
  192. package/dist/client/onboarding/use-onboarding.d.ts.map +1 -0
  193. package/dist/client/onboarding/use-onboarding.js +101 -0
  194. package/dist/client/onboarding/use-onboarding.js.map +1 -0
  195. package/dist/client/org/InvitationBanner.d.ts +9 -0
  196. package/dist/client/org/InvitationBanner.d.ts.map +1 -0
  197. package/dist/client/org/InvitationBanner.js +17 -0
  198. package/dist/client/org/InvitationBanner.js.map +1 -0
  199. package/dist/client/org/OrgSwitcher.d.ts +14 -0
  200. package/dist/client/org/OrgSwitcher.d.ts.map +1 -0
  201. package/dist/client/org/OrgSwitcher.js +51 -0
  202. package/dist/client/org/OrgSwitcher.js.map +1 -0
  203. package/dist/client/org/TeamPage.d.ts +28 -0
  204. package/dist/client/org/TeamPage.d.ts.map +1 -0
  205. package/dist/client/org/TeamPage.js +216 -0
  206. package/dist/client/org/TeamPage.js.map +1 -0
  207. package/dist/client/org/hooks.d.ts +14 -0
  208. package/dist/client/org/hooks.d.ts.map +1 -0
  209. package/dist/client/org/hooks.js +101 -0
  210. package/dist/client/org/hooks.js.map +1 -0
  211. package/dist/client/org/index.d.ts +6 -0
  212. package/dist/client/org/index.d.ts.map +1 -0
  213. package/dist/client/org/index.js +6 -0
  214. package/dist/client/org/index.js.map +1 -0
  215. package/dist/client/resources/ResourceEditor.d.ts +8 -1
  216. package/dist/client/resources/ResourceEditor.d.ts.map +1 -1
  217. package/dist/client/resources/ResourceEditor.js +141 -89
  218. package/dist/client/resources/ResourceEditor.js.map +1 -1
  219. package/dist/client/resources/ResourceTree.d.ts +5 -1
  220. package/dist/client/resources/ResourceTree.d.ts.map +1 -1
  221. package/dist/client/resources/ResourceTree.js +33 -5
  222. package/dist/client/resources/ResourceTree.js.map +1 -1
  223. package/dist/client/resources/ResourcesPanel.d.ts.map +1 -1
  224. package/dist/client/resources/ResourcesPanel.js +260 -109
  225. package/dist/client/resources/ResourcesPanel.js.map +1 -1
  226. package/dist/client/resources/use-resources.d.ts +15 -0
  227. package/dist/client/resources/use-resources.d.ts.map +1 -1
  228. package/dist/client/resources/use-resources.js +2 -2
  229. package/dist/client/resources/use-resources.js.map +1 -1
  230. package/dist/client/settings/AgentsSection.d.ts +2 -0
  231. package/dist/client/settings/AgentsSection.d.ts.map +1 -0
  232. package/dist/client/settings/AgentsSection.js +198 -0
  233. package/dist/client/settings/AgentsSection.js.map +1 -0
  234. package/dist/client/settings/BackgroundAgentSection.d.ts +2 -0
  235. package/dist/client/settings/BackgroundAgentSection.d.ts.map +1 -0
  236. package/dist/client/settings/BackgroundAgentSection.js +46 -0
  237. package/dist/client/settings/BackgroundAgentSection.js.map +1 -0
  238. package/dist/client/settings/BrowserSection.d.ts +2 -0
  239. package/dist/client/settings/BrowserSection.d.ts.map +1 -0
  240. package/dist/client/settings/BrowserSection.js +10 -0
  241. package/dist/client/settings/BrowserSection.js.map +1 -0
  242. package/dist/client/settings/ComingSoonSection.d.ts +13 -0
  243. package/dist/client/settings/ComingSoonSection.d.ts.map +1 -0
  244. package/dist/client/settings/ComingSoonSection.js +9 -0
  245. package/dist/client/settings/ComingSoonSection.js.map +1 -0
  246. package/dist/client/settings/LLMSection.d.ts +2 -0
  247. package/dist/client/settings/LLMSection.d.ts.map +1 -0
  248. package/dist/client/settings/LLMSection.js +64 -0
  249. package/dist/client/settings/LLMSection.js.map +1 -0
  250. package/dist/client/settings/SettingsPanel.d.ts +8 -0
  251. package/dist/client/settings/SettingsPanel.d.ts.map +1 -0
  252. package/dist/client/settings/SettingsPanel.js +118 -0
  253. package/dist/client/settings/SettingsPanel.js.map +1 -0
  254. package/dist/client/settings/SettingsSection.d.ts +19 -0
  255. package/dist/client/settings/SettingsSection.d.ts.map +1 -0
  256. package/dist/client/settings/SettingsSection.js +10 -0
  257. package/dist/client/settings/SettingsSection.js.map +1 -0
  258. package/dist/client/settings/index.d.ts +3 -0
  259. package/dist/client/settings/index.d.ts.map +1 -0
  260. package/dist/client/settings/index.js +3 -0
  261. package/dist/client/settings/index.js.map +1 -0
  262. package/dist/client/settings/useBuilderStatus.d.ts +22 -0
  263. package/dist/client/settings/useBuilderStatus.d.ts.map +1 -0
  264. package/dist/client/settings/useBuilderStatus.js +41 -0
  265. package/dist/client/settings/useBuilderStatus.js.map +1 -0
  266. package/dist/client/sse-event-processor.d.ts +9 -1
  267. package/dist/client/sse-event-processor.d.ts.map +1 -1
  268. package/dist/client/sse-event-processor.js +36 -3
  269. package/dist/client/sse-event-processor.js.map +1 -1
  270. package/dist/client/terminal/AgentTerminal.d.ts +4 -4
  271. package/dist/client/terminal/AgentTerminal.d.ts.map +1 -1
  272. package/dist/client/terminal/AgentTerminal.js +14 -14
  273. package/dist/client/terminal/AgentTerminal.js.map +1 -1
  274. package/dist/client/use-action.d.ts +51 -0
  275. package/dist/client/use-action.d.ts.map +1 -0
  276. package/dist/client/use-action.js +102 -0
  277. package/dist/client/use-action.js.map +1 -0
  278. package/dist/client/use-avatar.d.ts +15 -0
  279. package/dist/client/use-avatar.d.ts.map +1 -0
  280. package/dist/client/use-avatar.js +116 -0
  281. package/dist/client/use-avatar.js.map +1 -0
  282. package/dist/client/use-chat-threads.d.ts +1 -1
  283. package/dist/client/use-chat-threads.d.ts.map +1 -1
  284. package/dist/client/use-chat-threads.js +34 -18
  285. package/dist/client/use-chat-threads.js.map +1 -1
  286. package/dist/client/use-dev-mode.d.ts.map +1 -1
  287. package/dist/client/use-dev-mode.js +2 -0
  288. package/dist/client/use-dev-mode.js.map +1 -1
  289. package/dist/client/use-send-to-agent-chat.d.ts +7 -4
  290. package/dist/client/use-send-to-agent-chat.d.ts.map +1 -1
  291. package/dist/client/use-send-to-agent-chat.js +31 -10
  292. package/dist/client/use-send-to-agent-chat.js.map +1 -1
  293. package/dist/collab/awareness.d.ts +41 -0
  294. package/dist/collab/awareness.d.ts.map +1 -0
  295. package/dist/collab/awareness.js +82 -0
  296. package/dist/collab/awareness.js.map +1 -0
  297. package/dist/collab/client.d.ts +49 -0
  298. package/dist/collab/client.d.ts.map +1 -0
  299. package/dist/collab/client.js +250 -0
  300. package/dist/collab/client.js.map +1 -0
  301. package/dist/collab/emitter.d.ts +12 -0
  302. package/dist/collab/emitter.d.ts.map +1 -0
  303. package/dist/collab/emitter.js +16 -0
  304. package/dist/collab/emitter.js.map +1 -0
  305. package/dist/collab/index.d.ts +7 -0
  306. package/dist/collab/index.d.ts.map +1 -0
  307. package/dist/collab/index.js +14 -0
  308. package/dist/collab/index.js.map +1 -0
  309. package/dist/collab/routes.d.ts +69 -0
  310. package/dist/collab/routes.d.ts.map +1 -0
  311. package/dist/collab/routes.js +98 -0
  312. package/dist/collab/routes.js.map +1 -0
  313. package/dist/collab/storage.d.ts +18 -0
  314. package/dist/collab/storage.d.ts.map +1 -0
  315. package/dist/collab/storage.js +94 -0
  316. package/dist/collab/storage.js.map +1 -0
  317. package/dist/collab/text-to-yjs.d.ts +23 -0
  318. package/dist/collab/text-to-yjs.d.ts.map +1 -0
  319. package/dist/collab/text-to-yjs.js +63 -0
  320. package/dist/collab/text-to-yjs.js.map +1 -0
  321. package/dist/collab/xml-ops.d.ts +20 -0
  322. package/dist/collab/xml-ops.d.ts.map +1 -0
  323. package/dist/collab/xml-ops.js +59 -0
  324. package/dist/collab/xml-ops.js.map +1 -0
  325. package/dist/collab/ydoc-manager.d.ts +52 -0
  326. package/dist/collab/ydoc-manager.d.ts.map +1 -0
  327. package/dist/collab/ydoc-manager.js +154 -0
  328. package/dist/collab/ydoc-manager.js.map +1 -0
  329. package/dist/db/client.d.ts +10 -0
  330. package/dist/db/client.d.ts.map +1 -1
  331. package/dist/db/client.js +43 -2
  332. package/dist/db/client.js.map +1 -1
  333. package/dist/db/create-get-db.js.map +1 -1
  334. package/dist/db/index.d.ts +1 -1
  335. package/dist/db/index.d.ts.map +1 -1
  336. package/dist/db/index.js +1 -1
  337. package/dist/db/index.js.map +1 -1
  338. package/dist/db/migrations.d.ts +9 -1
  339. package/dist/db/migrations.d.ts.map +1 -1
  340. package/dist/db/migrations.js +45 -20
  341. package/dist/db/migrations.js.map +1 -1
  342. package/dist/db/schema.d.ts +8 -1
  343. package/dist/db/schema.d.ts.map +1 -1
  344. package/dist/db/schema.js +13 -2
  345. package/dist/db/schema.js.map +1 -1
  346. package/dist/deploy/build.js +795 -86
  347. package/dist/deploy/build.js.map +1 -1
  348. package/dist/deploy/route-discovery.d.ts +22 -4
  349. package/dist/deploy/route-discovery.d.ts.map +1 -1
  350. package/dist/deploy/route-discovery.js +148 -35
  351. package/dist/deploy/route-discovery.js.map +1 -1
  352. package/dist/deploy/workspace-core.d.ts +28 -0
  353. package/dist/deploy/workspace-core.d.ts.map +1 -0
  354. package/dist/deploy/workspace-core.js +223 -0
  355. package/dist/deploy/workspace-core.js.map +1 -0
  356. package/dist/deploy/workspace-deploy.d.ts +11 -0
  357. package/dist/deploy/workspace-deploy.d.ts.map +1 -0
  358. package/dist/deploy/workspace-deploy.js +148 -0
  359. package/dist/deploy/workspace-deploy.js.map +1 -0
  360. package/dist/file-upload/builder.d.ts +11 -0
  361. package/dist/file-upload/builder.d.ts.map +1 -0
  362. package/dist/file-upload/builder.js +53 -0
  363. package/dist/file-upload/builder.js.map +1 -0
  364. package/dist/file-upload/index.d.ts +4 -0
  365. package/dist/file-upload/index.d.ts.map +1 -0
  366. package/dist/file-upload/index.js +3 -0
  367. package/dist/file-upload/index.js.map +1 -0
  368. package/dist/file-upload/registry.d.ts +23 -0
  369. package/dist/file-upload/registry.d.ts.map +1 -0
  370. package/dist/file-upload/registry.js +52 -0
  371. package/dist/file-upload/registry.js.map +1 -0
  372. package/dist/file-upload/types.d.ts +37 -0
  373. package/dist/file-upload/types.d.ts.map +1 -0
  374. package/dist/file-upload/types.js +10 -0
  375. package/dist/file-upload/types.js.map +1 -0
  376. package/dist/index.browser.d.ts +2 -0
  377. package/dist/index.browser.d.ts.map +1 -1
  378. package/dist/index.browser.js +4 -0
  379. package/dist/index.browser.js.map +1 -1
  380. package/dist/index.d.ts +3 -3
  381. package/dist/index.d.ts.map +1 -1
  382. package/dist/index.js +2 -2
  383. package/dist/index.js.map +1 -1
  384. package/dist/integrations/adapters/google-docs.d.ts +89 -0
  385. package/dist/integrations/adapters/google-docs.d.ts.map +1 -0
  386. package/dist/integrations/adapters/google-docs.js +261 -0
  387. package/dist/integrations/adapters/google-docs.js.map +1 -0
  388. package/dist/integrations/adapters/slack.d.ts +10 -0
  389. package/dist/integrations/adapters/slack.d.ts.map +1 -0
  390. package/dist/integrations/adapters/slack.js +249 -0
  391. package/dist/integrations/adapters/slack.js.map +1 -0
  392. package/dist/integrations/adapters/telegram.d.ts +12 -0
  393. package/dist/integrations/adapters/telegram.d.ts.map +1 -0
  394. package/dist/integrations/adapters/telegram.js +216 -0
  395. package/dist/integrations/adapters/telegram.js.map +1 -0
  396. package/dist/integrations/adapters/whatsapp.d.ts +14 -0
  397. package/dist/integrations/adapters/whatsapp.d.ts.map +1 -0
  398. package/dist/integrations/adapters/whatsapp.js +205 -0
  399. package/dist/integrations/adapters/whatsapp.js.map +1 -0
  400. package/dist/integrations/config-store.d.ts +24 -0
  401. package/dist/integrations/config-store.d.ts.map +1 -0
  402. package/dist/integrations/config-store.js +92 -0
  403. package/dist/integrations/config-store.js.map +1 -0
  404. package/dist/integrations/google-docs-poller.d.ts +54 -0
  405. package/dist/integrations/google-docs-poller.d.ts.map +1 -0
  406. package/dist/integrations/google-docs-poller.js +442 -0
  407. package/dist/integrations/google-docs-poller.js.map +1 -0
  408. package/dist/integrations/index.d.ts +10 -0
  409. package/dist/integrations/index.d.ts.map +1 -0
  410. package/dist/integrations/index.js +13 -0
  411. package/dist/integrations/index.js.map +1 -0
  412. package/dist/integrations/plugin.d.ts +20 -0
  413. package/dist/integrations/plugin.d.ts.map +1 -0
  414. package/dist/integrations/plugin.js +260 -0
  415. package/dist/integrations/plugin.js.map +1 -0
  416. package/dist/integrations/thread-mapping-store.d.ts +25 -0
  417. package/dist/integrations/thread-mapping-store.d.ts.map +1 -0
  418. package/dist/integrations/thread-mapping-store.js +95 -0
  419. package/dist/integrations/thread-mapping-store.js.map +1 -0
  420. package/dist/integrations/types.d.ts +144 -0
  421. package/dist/integrations/types.d.ts.map +1 -0
  422. package/dist/integrations/types.js +2 -0
  423. package/dist/integrations/types.js.map +1 -0
  424. package/dist/integrations/webhook-handler.d.ts +40 -0
  425. package/dist/integrations/webhook-handler.d.ts.map +1 -0
  426. package/dist/integrations/webhook-handler.js +220 -0
  427. package/dist/integrations/webhook-handler.js.map +1 -0
  428. package/dist/jobs/cron.d.ts +14 -0
  429. package/dist/jobs/cron.d.ts.map +1 -0
  430. package/dist/jobs/cron.js +100 -0
  431. package/dist/jobs/cron.js.map +1 -0
  432. package/dist/jobs/index.d.ts +4 -0
  433. package/dist/jobs/index.d.ts.map +1 -0
  434. package/dist/jobs/index.js +4 -0
  435. package/dist/jobs/index.js.map +1 -0
  436. package/dist/jobs/scheduler.d.ts +32 -0
  437. package/dist/jobs/scheduler.d.ts.map +1 -0
  438. package/dist/jobs/scheduler.js +226 -0
  439. package/dist/jobs/scheduler.js.map +1 -0
  440. package/dist/jobs/tools.d.ts +3 -0
  441. package/dist/jobs/tools.d.ts.map +1 -0
  442. package/dist/jobs/tools.js +209 -0
  443. package/dist/jobs/tools.js.map +1 -0
  444. package/dist/mcp/index.d.ts +3 -0
  445. package/dist/mcp/index.d.ts.map +1 -0
  446. package/dist/mcp/index.js +2 -0
  447. package/dist/mcp/index.js.map +1 -0
  448. package/dist/mcp/server.d.ts +26 -0
  449. package/dist/mcp/server.d.ts.map +1 -0
  450. package/dist/mcp/server.js +182 -0
  451. package/dist/mcp/server.js.map +1 -0
  452. package/dist/mcp-client/config.d.ts +46 -0
  453. package/dist/mcp-client/config.d.ts.map +1 -0
  454. package/dist/mcp-client/config.js +152 -0
  455. package/dist/mcp-client/config.js.map +1 -0
  456. package/dist/mcp-client/index.d.ts +17 -0
  457. package/dist/mcp-client/index.d.ts.map +1 -0
  458. package/dist/mcp-client/index.js +53 -0
  459. package/dist/mcp-client/index.js.map +1 -0
  460. package/dist/mcp-client/manager.d.ts +76 -0
  461. package/dist/mcp-client/manager.d.ts.map +1 -0
  462. package/dist/mcp-client/manager.js +212 -0
  463. package/dist/mcp-client/manager.js.map +1 -0
  464. package/dist/oauth-tokens/index.d.ts +1 -1
  465. package/dist/oauth-tokens/index.d.ts.map +1 -1
  466. package/dist/oauth-tokens/index.js +1 -1
  467. package/dist/oauth-tokens/index.js.map +1 -1
  468. package/dist/oauth-tokens/store.d.ts +5 -0
  469. package/dist/oauth-tokens/store.d.ts.map +1 -1
  470. package/dist/oauth-tokens/store.js +33 -8
  471. package/dist/oauth-tokens/store.js.map +1 -1
  472. package/dist/onboarding/default-steps.d.ts +10 -0
  473. package/dist/onboarding/default-steps.d.ts.map +1 -0
  474. package/dist/onboarding/default-steps.js +164 -0
  475. package/dist/onboarding/default-steps.js.map +1 -0
  476. package/dist/onboarding/index.d.ts +12 -0
  477. package/dist/onboarding/index.d.ts.map +1 -0
  478. package/dist/onboarding/index.js +11 -0
  479. package/dist/onboarding/index.js.map +1 -0
  480. package/dist/onboarding/plugin.d.ts +19 -0
  481. package/dist/onboarding/plugin.d.ts.map +1 -0
  482. package/dist/onboarding/plugin.js +147 -0
  483. package/dist/onboarding/plugin.js.map +1 -0
  484. package/dist/onboarding/registry.d.ts +24 -0
  485. package/dist/onboarding/registry.d.ts.map +1 -0
  486. package/dist/onboarding/registry.js +40 -0
  487. package/dist/onboarding/registry.js.map +1 -0
  488. package/dist/onboarding/types.d.ts +71 -0
  489. package/dist/onboarding/types.d.ts.map +1 -0
  490. package/dist/onboarding/types.js +10 -0
  491. package/dist/onboarding/types.js.map +1 -0
  492. package/dist/org/context.d.ts +11 -0
  493. package/dist/org/context.d.ts.map +1 -0
  494. package/dist/org/context.js +61 -0
  495. package/dist/org/context.js.map +1 -0
  496. package/dist/org/handlers.d.ts +66 -0
  497. package/dist/org/handlers.d.ts.map +1 -0
  498. package/dist/org/handlers.js +306 -0
  499. package/dist/org/handlers.js.map +1 -0
  500. package/dist/org/index.d.ts +7 -0
  501. package/dist/org/index.d.ts.map +1 -0
  502. package/dist/org/index.js +11 -0
  503. package/dist/org/index.js.map +1 -0
  504. package/dist/org/migrations.d.ts +10 -0
  505. package/dist/org/migrations.d.ts.map +1 -0
  506. package/dist/org/migrations.js +39 -0
  507. package/dist/org/migrations.js.map +1 -0
  508. package/dist/org/plugin.d.ts +26 -0
  509. package/dist/org/plugin.d.ts.map +1 -0
  510. package/dist/org/plugin.js +94 -0
  511. package/dist/org/plugin.js.map +1 -0
  512. package/dist/org/schema.d.ts +301 -0
  513. package/dist/org/schema.d.ts.map +1 -0
  514. package/dist/org/schema.js +23 -0
  515. package/dist/org/schema.js.map +1 -0
  516. package/dist/org/types.d.ts +42 -0
  517. package/dist/org/types.d.ts.map +1 -0
  518. package/dist/org/types.js +5 -0
  519. package/dist/org/types.js.map +1 -0
  520. package/dist/resources/agents.d.ts +4 -0
  521. package/dist/resources/agents.d.ts.map +1 -0
  522. package/dist/resources/agents.js +44 -0
  523. package/dist/resources/agents.js.map +1 -0
  524. package/dist/resources/handlers.d.ts +27 -1
  525. package/dist/resources/handlers.d.ts.map +1 -1
  526. package/dist/resources/handlers.js +121 -11
  527. package/dist/resources/handlers.js.map +1 -1
  528. package/dist/resources/metadata.d.ts +48 -0
  529. package/dist/resources/metadata.d.ts.map +1 -0
  530. package/dist/resources/metadata.js +150 -0
  531. package/dist/resources/metadata.js.map +1 -0
  532. package/dist/resources/script-helpers.d.ts.map +1 -1
  533. package/dist/resources/script-helpers.js +3 -2
  534. package/dist/resources/script-helpers.js.map +1 -1
  535. package/dist/resources/store.d.ts +5 -0
  536. package/dist/resources/store.d.ts.map +1 -1
  537. package/dist/resources/store.js +76 -17
  538. package/dist/resources/store.js.map +1 -1
  539. package/dist/scripts/agent-engines/list-agent-engines.d.ts +7 -0
  540. package/dist/scripts/agent-engines/list-agent-engines.d.ts.map +1 -0
  541. package/dist/scripts/agent-engines/list-agent-engines.js +42 -0
  542. package/dist/scripts/agent-engines/list-agent-engines.js.map +1 -0
  543. package/dist/scripts/agent-engines/set-agent-engine.d.ts +7 -0
  544. package/dist/scripts/agent-engines/set-agent-engine.d.ts.map +1 -0
  545. package/dist/scripts/agent-engines/set-agent-engine.js +57 -0
  546. package/dist/scripts/agent-engines/set-agent-engine.js.map +1 -0
  547. package/dist/scripts/agent-engines/test-agent-engine.d.ts +7 -0
  548. package/dist/scripts/agent-engines/test-agent-engine.d.ts.map +1 -0
  549. package/dist/scripts/agent-engines/test-agent-engine.js +102 -0
  550. package/dist/scripts/agent-engines/test-agent-engine.js.map +1 -0
  551. package/dist/scripts/call-agent.d.ts +1 -1
  552. package/dist/scripts/call-agent.d.ts.map +1 -1
  553. package/dist/scripts/call-agent.js +13 -8
  554. package/dist/scripts/call-agent.js.map +1 -1
  555. package/dist/scripts/chat/index.d.ts +2 -0
  556. package/dist/scripts/chat/index.d.ts.map +1 -0
  557. package/dist/scripts/chat/index.js +5 -0
  558. package/dist/scripts/chat/index.js.map +1 -0
  559. package/dist/scripts/chat/open-chat.d.ts +11 -0
  560. package/dist/scripts/chat/open-chat.d.ts.map +1 -0
  561. package/dist/scripts/chat/open-chat.js +48 -0
  562. package/dist/scripts/chat/open-chat.js.map +1 -0
  563. package/dist/scripts/chat/search-chats.d.ts +10 -0
  564. package/dist/scripts/chat/search-chats.d.ts.map +1 -0
  565. package/dist/scripts/chat/search-chats.js +90 -0
  566. package/dist/scripts/chat/search-chats.js.map +1 -0
  567. package/dist/scripts/core-scripts.d.ts.map +1 -1
  568. package/dist/scripts/core-scripts.js +4 -0
  569. package/dist/scripts/core-scripts.js.map +1 -1
  570. package/dist/scripts/db/check-scoping.d.ts +14 -0
  571. package/dist/scripts/db/check-scoping.d.ts.map +1 -0
  572. package/dist/scripts/db/check-scoping.js +174 -0
  573. package/dist/scripts/db/check-scoping.js.map +1 -0
  574. package/dist/scripts/db/exec.d.ts +3 -2
  575. package/dist/scripts/db/exec.d.ts.map +1 -1
  576. package/dist/scripts/db/exec.js +35 -19
  577. package/dist/scripts/db/exec.js.map +1 -1
  578. package/dist/scripts/db/index.d.ts.map +1 -1
  579. package/dist/scripts/db/index.js +2 -0
  580. package/dist/scripts/db/index.js.map +1 -1
  581. package/dist/scripts/db/patch.d.ts +50 -0
  582. package/dist/scripts/db/patch.d.ts.map +1 -0
  583. package/dist/scripts/db/patch.js +392 -0
  584. package/dist/scripts/db/patch.js.map +1 -0
  585. package/dist/scripts/db/scoping.d.ts +8 -2
  586. package/dist/scripts/db/scoping.d.ts.map +1 -1
  587. package/dist/scripts/db/scoping.js +66 -47
  588. package/dist/scripts/db/scoping.js.map +1 -1
  589. package/dist/scripts/dev/index.d.ts.map +1 -1
  590. package/dist/scripts/dev/index.js +64 -1
  591. package/dist/scripts/dev/index.js.map +1 -1
  592. package/dist/scripts/docs/index.d.ts +2 -0
  593. package/dist/scripts/docs/index.d.ts.map +1 -0
  594. package/dist/scripts/docs/index.js +4 -0
  595. package/dist/scripts/docs/index.js.map +1 -0
  596. package/dist/scripts/docs/search.d.ts +13 -0
  597. package/dist/scripts/docs/search.d.ts.map +1 -0
  598. package/dist/scripts/docs/search.js +130 -0
  599. package/dist/scripts/docs/search.js.map +1 -0
  600. package/dist/scripts/parse-args.d.ts +14 -0
  601. package/dist/scripts/parse-args.d.ts.map +1 -0
  602. package/dist/scripts/parse-args.js +45 -0
  603. package/dist/scripts/parse-args.js.map +1 -0
  604. package/dist/scripts/resources/delete-memory.d.ts +7 -0
  605. package/dist/scripts/resources/delete-memory.d.ts.map +1 -0
  606. package/dist/scripts/resources/delete-memory.js +49 -0
  607. package/dist/scripts/resources/delete-memory.js.map +1 -0
  608. package/dist/scripts/resources/delete.d.ts.map +1 -1
  609. package/dist/scripts/resources/delete.js +2 -1
  610. package/dist/scripts/resources/delete.js.map +1 -1
  611. package/dist/scripts/resources/index.d.ts.map +1 -1
  612. package/dist/scripts/resources/index.js +2 -0
  613. package/dist/scripts/resources/index.js.map +1 -1
  614. package/dist/scripts/resources/list.d.ts.map +1 -1
  615. package/dist/scripts/resources/list.js +2 -1
  616. package/dist/scripts/resources/list.js.map +1 -1
  617. package/dist/scripts/resources/migrate-learnings.d.ts.map +1 -1
  618. package/dist/scripts/resources/migrate-learnings.js +2 -1
  619. package/dist/scripts/resources/migrate-learnings.js.map +1 -1
  620. package/dist/scripts/resources/read.d.ts.map +1 -1
  621. package/dist/scripts/resources/read.js +2 -1
  622. package/dist/scripts/resources/read.js.map +1 -1
  623. package/dist/scripts/resources/save-memory.d.ts +9 -0
  624. package/dist/scripts/resources/save-memory.d.ts.map +1 -0
  625. package/dist/scripts/resources/save-memory.js +78 -0
  626. package/dist/scripts/resources/save-memory.js.map +1 -0
  627. package/dist/scripts/resources/write.d.ts.map +1 -1
  628. package/dist/scripts/resources/write.js +2 -1
  629. package/dist/scripts/resources/write.js.map +1 -1
  630. package/dist/scripts/runner.d.ts.map +1 -1
  631. package/dist/scripts/runner.js +10 -2
  632. package/dist/scripts/runner.js.map +1 -1
  633. package/dist/scripts/utils.d.ts +9 -8
  634. package/dist/scripts/utils.d.ts.map +1 -1
  635. package/dist/scripts/utils.js +40 -35
  636. package/dist/scripts/utils.js.map +1 -1
  637. package/dist/server/action-discovery.d.ts +5 -0
  638. package/dist/server/action-discovery.d.ts.map +1 -1
  639. package/dist/server/action-discovery.js +132 -33
  640. package/dist/server/action-discovery.js.map +1 -1
  641. package/dist/server/action-routes.d.ts +15 -0
  642. package/dist/server/action-routes.d.ts.map +1 -0
  643. package/dist/server/action-routes.js +111 -0
  644. package/dist/server/action-routes.js.map +1 -0
  645. package/dist/server/agent-chat-plugin.d.ts +23 -0
  646. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  647. package/dist/server/agent-chat-plugin.js +1474 -266
  648. package/dist/server/agent-chat-plugin.js.map +1 -1
  649. package/dist/server/agent-discovery.d.ts +8 -3
  650. package/dist/server/agent-discovery.d.ts.map +1 -1
  651. package/dist/server/agent-discovery.js +57 -8
  652. package/dist/server/agent-discovery.js.map +1 -1
  653. package/dist/server/agent-teams.d.ts +70 -0
  654. package/dist/server/agent-teams.d.ts.map +1 -0
  655. package/dist/server/agent-teams.js +368 -0
  656. package/dist/server/agent-teams.js.map +1 -0
  657. package/dist/server/agents-bundle.d.ts +115 -0
  658. package/dist/server/agents-bundle.d.ts.map +1 -0
  659. package/dist/server/agents-bundle.js +275 -0
  660. package/dist/server/agents-bundle.js.map +1 -0
  661. package/dist/server/auth-plugin.d.ts +3 -3
  662. package/dist/server/auth-plugin.d.ts.map +1 -1
  663. package/dist/server/auth-plugin.js +9 -10
  664. package/dist/server/auth-plugin.js.map +1 -1
  665. package/dist/server/auth.d.ts +55 -33
  666. package/dist/server/auth.d.ts.map +1 -1
  667. package/dist/server/auth.js +640 -610
  668. package/dist/server/auth.js.map +1 -1
  669. package/dist/server/better-auth-instance.d.ts +72 -0
  670. package/dist/server/better-auth-instance.d.ts.map +1 -0
  671. package/dist/server/better-auth-instance.js +340 -0
  672. package/dist/server/better-auth-instance.js.map +1 -0
  673. package/dist/server/builder-browser.d.ts +40 -0
  674. package/dist/server/builder-browser.d.ts.map +1 -0
  675. package/dist/server/builder-browser.js +166 -0
  676. package/dist/server/builder-browser.js.map +1 -0
  677. package/dist/server/collab-plugin.d.ts +29 -0
  678. package/dist/server/collab-plugin.d.ts.map +1 -0
  679. package/dist/server/collab-plugin.js +85 -0
  680. package/dist/server/collab-plugin.js.map +1 -0
  681. package/dist/server/core-routes-plugin.d.ts +0 -3
  682. package/dist/server/core-routes-plugin.d.ts.map +1 -1
  683. package/dist/server/core-routes-plugin.js +248 -32
  684. package/dist/server/core-routes-plugin.js.map +1 -1
  685. package/dist/server/create-server.d.ts +1 -1
  686. package/dist/server/create-server.d.ts.map +1 -1
  687. package/dist/server/create-server.js +39 -16
  688. package/dist/server/create-server.js.map +1 -1
  689. package/dist/server/credential-provider.d.ts +37 -0
  690. package/dist/server/credential-provider.d.ts.map +1 -0
  691. package/dist/server/credential-provider.js +49 -0
  692. package/dist/server/credential-provider.js.map +1 -0
  693. package/dist/server/framework-request-handler.d.ts +47 -0
  694. package/dist/server/framework-request-handler.d.ts.map +1 -0
  695. package/dist/server/framework-request-handler.js +207 -0
  696. package/dist/server/framework-request-handler.js.map +1 -0
  697. package/dist/server/google-auth-plugin.d.ts +4 -0
  698. package/dist/server/google-auth-plugin.d.ts.map +1 -1
  699. package/dist/server/google-auth-plugin.js +14 -13
  700. package/dist/server/google-auth-plugin.js.map +1 -1
  701. package/dist/server/google-oauth.d.ts +3 -3
  702. package/dist/server/google-oauth.d.ts.map +1 -1
  703. package/dist/server/google-oauth.js +51 -24
  704. package/dist/server/google-oauth.js.map +1 -1
  705. package/dist/server/h3-helpers.d.ts +23 -0
  706. package/dist/server/h3-helpers.d.ts.map +1 -0
  707. package/dist/server/h3-helpers.js +37 -0
  708. package/dist/server/h3-helpers.js.map +1 -0
  709. package/dist/server/index.d.ts +12 -4
  710. package/dist/server/index.d.ts.map +1 -1
  711. package/dist/server/index.js +15 -4
  712. package/dist/server/index.js.map +1 -1
  713. package/dist/server/local-migration.d.ts +32 -0
  714. package/dist/server/local-migration.d.ts.map +1 -0
  715. package/dist/server/local-migration.js +205 -0
  716. package/dist/server/local-migration.js.map +1 -0
  717. package/dist/server/oauth-helpers.d.ts +5 -6
  718. package/dist/server/oauth-helpers.d.ts.map +1 -1
  719. package/dist/server/oauth-helpers.js +10 -11
  720. package/dist/server/oauth-helpers.js.map +1 -1
  721. package/dist/server/onboarding-html.d.ts +24 -0
  722. package/dist/server/onboarding-html.d.ts.map +1 -0
  723. package/dist/server/onboarding-html.js +438 -0
  724. package/dist/server/onboarding-html.js.map +1 -0
  725. package/dist/server/poll.d.ts +7 -2
  726. package/dist/server/poll.d.ts.map +1 -1
  727. package/dist/server/poll.js +48 -1
  728. package/dist/server/poll.js.map +1 -1
  729. package/dist/server/request-context.d.ts +20 -0
  730. package/dist/server/request-context.d.ts.map +1 -0
  731. package/dist/server/request-context.js +41 -0
  732. package/dist/server/request-context.js.map +1 -0
  733. package/dist/server/resources-plugin.d.ts.map +1 -1
  734. package/dist/server/resources-plugin.js +4 -3
  735. package/dist/server/resources-plugin.js.map +1 -1
  736. package/dist/server/schema-prompt.d.ts +16 -0
  737. package/dist/server/schema-prompt.d.ts.map +1 -0
  738. package/dist/server/schema-prompt.js +275 -0
  739. package/dist/server/schema-prompt.js.map +1 -0
  740. package/dist/server/sse.d.ts +3 -20
  741. package/dist/server/sse.d.ts.map +1 -1
  742. package/dist/server/sse.js +1 -29
  743. package/dist/server/sse.js.map +1 -1
  744. package/dist/server/ssr-handler.d.ts +6 -0
  745. package/dist/server/ssr-handler.d.ts.map +1 -0
  746. package/dist/server/ssr-handler.js +55 -0
  747. package/dist/server/ssr-handler.js.map +1 -0
  748. package/dist/settings/handlers.d.ts +3 -3
  749. package/dist/settings/handlers.d.ts.map +1 -1
  750. package/dist/settings/handlers.js +2 -1
  751. package/dist/settings/handlers.js.map +1 -1
  752. package/dist/settings/index.d.ts +1 -0
  753. package/dist/settings/index.d.ts.map +1 -1
  754. package/dist/settings/index.js +2 -0
  755. package/dist/settings/index.js.map +1 -1
  756. package/dist/settings/org-settings.d.ts +22 -0
  757. package/dist/settings/org-settings.d.ts.map +1 -0
  758. package/dist/settings/org-settings.js +45 -0
  759. package/dist/settings/org-settings.js.map +1 -0
  760. package/dist/shared/agent-chat.d.ts +5 -5
  761. package/dist/shared/agent-chat.d.ts.map +1 -1
  762. package/dist/shared/agent-chat.js +8 -8
  763. package/dist/shared/agent-chat.js.map +1 -1
  764. package/dist/shared/agent-env.d.ts +1 -1
  765. package/dist/shared/agent-env.js +1 -1
  766. package/dist/shared/runtime.d.ts +14 -0
  767. package/dist/shared/runtime.d.ts.map +1 -0
  768. package/dist/shared/runtime.js +25 -0
  769. package/dist/shared/runtime.js.map +1 -0
  770. package/dist/templates/default/.agents/skills/actions/SKILL.md +143 -0
  771. package/dist/templates/default/.agents/skills/agent-engines/SKILL.md +127 -0
  772. package/dist/templates/default/.agents/skills/capture-learnings/SKILL.md +50 -0
  773. package/dist/templates/default/.agents/skills/create-skill/SKILL.md +167 -0
  774. package/dist/templates/default/.agents/skills/delegate-to-agent/SKILL.md +90 -0
  775. package/dist/templates/default/.agents/skills/frontend-design/SKILL.md +69 -0
  776. package/dist/templates/default/.agents/skills/real-time-collab/SKILL.md +183 -0
  777. package/dist/templates/default/.agents/skills/real-time-sync/SKILL.md +112 -0
  778. package/dist/templates/default/.agents/skills/security/SKILL.md +213 -0
  779. package/dist/templates/default/.agents/skills/self-modifying-code/SKILL.md +79 -0
  780. package/{src/templates/default/.agents/skills/files-as-database → dist/templates/default/.agents/skills/storing-data}/SKILL.md +7 -1
  781. package/dist/templates/default/.claude/settings.json +100 -0
  782. package/dist/templates/default/.env.example +5 -0
  783. package/dist/templates/default/.prettierrc +5 -0
  784. package/dist/templates/default/AGENTS.md +110 -0
  785. package/dist/templates/default/DEVELOPING.md +117 -0
  786. package/dist/templates/default/_gitignore +38 -0
  787. package/dist/templates/default/actions/hello.ts +20 -0
  788. package/dist/templates/default/actions/navigate.ts +53 -0
  789. package/dist/templates/default/actions/run.ts +2 -0
  790. package/dist/templates/default/actions/view-screen.ts +39 -0
  791. package/dist/templates/default/app/entry.client.tsx +4 -0
  792. package/dist/templates/default/app/entry.server.tsx +56 -0
  793. package/dist/templates/default/app/global.css +95 -0
  794. package/dist/templates/default/app/lib/utils.ts +1 -0
  795. package/dist/templates/default/app/root.tsx +110 -0
  796. package/dist/templates/default/app/routes/_index.tsx +62 -0
  797. package/dist/templates/default/app/routes.ts +4 -0
  798. package/dist/templates/default/app/vite-env.d.ts +6 -0
  799. package/dist/templates/default/components.json +20 -0
  800. package/dist/templates/default/data/.gitkeep +0 -0
  801. package/dist/templates/default/data/sync-config.json +1 -0
  802. package/dist/templates/default/learnings.defaults.md +5 -0
  803. package/dist/templates/default/learnings.md +0 -0
  804. package/dist/templates/default/package.json +46 -0
  805. package/dist/templates/default/postcss.config.js +6 -0
  806. package/dist/templates/default/public/icon-180.svg +4 -0
  807. package/dist/templates/default/public/icon-192.svg +4 -0
  808. package/dist/templates/default/public/icon-512.svg +4 -0
  809. package/dist/templates/default/public/manifest.json +13 -0
  810. package/dist/templates/default/react-router.config.ts +6 -0
  811. package/dist/templates/default/server/middleware/auth.ts +15 -0
  812. package/dist/templates/default/server/plugins/.gitkeep +0 -0
  813. package/dist/templates/default/server/routes/[...page].get.ts +5 -0
  814. package/dist/templates/default/server/routes/api/hello.get.ts +5 -0
  815. package/dist/templates/default/shared/api.ts +6 -0
  816. package/dist/templates/default/ssr-entry.ts +20 -0
  817. package/dist/templates/default/tailwind.config.ts +7 -0
  818. package/dist/templates/default/tsconfig.json +11 -0
  819. package/dist/templates/default/vite.config.ts +6 -0
  820. package/dist/templates/workspace-core/AGENTS.md +62 -0
  821. package/dist/templates/workspace-core/actions/company-directory.ts +38 -0
  822. package/dist/templates/workspace-core/package.json +39 -0
  823. package/dist/templates/workspace-core/skills/company-policies/SKILL.md +42 -0
  824. package/dist/templates/workspace-core/src/client/AuthenticatedLayout.tsx +37 -0
  825. package/dist/templates/workspace-core/src/client/index.ts +26 -0
  826. package/dist/templates/workspace-core/src/credentials.ts +29 -0
  827. package/dist/templates/workspace-core/src/index.ts +21 -0
  828. package/dist/templates/workspace-core/src/server/agent-chat-plugin.ts +30 -0
  829. package/dist/templates/workspace-core/src/server/auth-plugin.ts +35 -0
  830. package/dist/templates/workspace-core/src/server/index.ts +22 -0
  831. package/dist/templates/workspace-core/tailwind.preset.ts +34 -0
  832. package/dist/templates/workspace-core/tsconfig.json +9 -0
  833. package/dist/templates/workspace-root/.env.example +37 -0
  834. package/dist/templates/workspace-root/README.md +62 -0
  835. package/dist/templates/workspace-root/_gitignore +23 -0
  836. package/dist/templates/workspace-root/package.json +18 -0
  837. package/dist/templates/workspace-root/pnpm-workspace.yaml +3 -0
  838. package/dist/templates/workspace-root/tsconfig.base.json +21 -0
  839. package/dist/terminal/cli-registry.d.ts +1 -1
  840. package/dist/terminal/cli-registry.d.ts.map +1 -1
  841. package/dist/terminal/cli-registry.js +7 -7
  842. package/dist/terminal/cli-registry.js.map +1 -1
  843. package/dist/terminal/pty-server.d.ts +1 -1
  844. package/dist/terminal/pty-server.d.ts.map +1 -1
  845. package/dist/terminal/pty-server.js +34 -12
  846. package/dist/terminal/pty-server.js.map +1 -1
  847. package/dist/terminal/terminal-plugin.d.ts +0 -9
  848. package/dist/terminal/terminal-plugin.d.ts.map +1 -1
  849. package/dist/terminal/terminal-plugin.js +57 -14
  850. package/dist/terminal/terminal-plugin.js.map +1 -1
  851. package/dist/usage/store.d.ts +29 -0
  852. package/dist/usage/store.d.ts.map +1 -0
  853. package/dist/usage/store.js +102 -0
  854. package/dist/usage/store.js.map +1 -0
  855. package/dist/vite/action-types-plugin.d.ts +13 -0
  856. package/dist/vite/action-types-plugin.d.ts.map +1 -0
  857. package/dist/vite/action-types-plugin.js +132 -0
  858. package/dist/vite/action-types-plugin.js.map +1 -0
  859. package/dist/vite/agents-bundle-plugin.d.ts +3 -0
  860. package/dist/vite/agents-bundle-plugin.d.ts.map +1 -0
  861. package/dist/vite/agents-bundle-plugin.js +137 -0
  862. package/dist/vite/agents-bundle-plugin.js.map +1 -0
  863. package/dist/vite/client.d.ts +21 -0
  864. package/dist/vite/client.d.ts.map +1 -1
  865. package/dist/vite/client.js +297 -37
  866. package/dist/vite/client.js.map +1 -1
  867. package/dist/vite/index.d.ts +2 -1
  868. package/dist/vite/index.d.ts.map +1 -1
  869. package/dist/vite/index.js +2 -1
  870. package/dist/vite/index.js.map +1 -1
  871. package/docs/content/a2a-protocol.md +223 -0
  872. package/docs/content/actions.md +129 -0
  873. package/docs/content/agent-mentions.md +171 -0
  874. package/docs/content/authentication.md +155 -0
  875. package/docs/content/cli-adapters.md +244 -0
  876. package/docs/content/client.md +175 -0
  877. package/docs/content/context-awareness.md +168 -0
  878. package/docs/content/creating-templates.md +311 -0
  879. package/docs/content/database.md +82 -0
  880. package/docs/content/deployment.md +180 -0
  881. package/docs/content/enterprise-workspace.md +235 -0
  882. package/docs/content/faq.md +101 -0
  883. package/docs/content/file-uploads.md +102 -0
  884. package/docs/content/frames.md +47 -0
  885. package/docs/content/getting-started.md +104 -0
  886. package/docs/content/integrations.md +198 -0
  887. package/docs/content/key-concepts.md +246 -0
  888. package/docs/content/mcp-clients.md +110 -0
  889. package/docs/content/mcp-protocol.md +168 -0
  890. package/docs/content/onboarding.md +107 -0
  891. package/docs/content/real-time-collaboration.md +185 -0
  892. package/docs/content/resources.md +277 -0
  893. package/docs/content/security.md +158 -0
  894. package/docs/content/server.md +200 -0
  895. package/docs/content/skills-guide.md +107 -0
  896. package/docs/content/what-is-agent-native.md +100 -0
  897. package/docs/content/workspace-management.md +224 -0
  898. package/package.json +78 -20
  899. package/src/templates/default/.agents/skills/actions/SKILL.md +14 -7
  900. package/src/templates/default/.agents/skills/agent-engines/SKILL.md +127 -0
  901. package/src/templates/default/.agents/skills/real-time-collab/SKILL.md +183 -0
  902. package/src/templates/default/.agents/skills/security/SKILL.md +213 -0
  903. package/src/templates/default/.agents/skills/storing-data/SKILL.md +116 -0
  904. package/src/templates/default/.claude/settings.json +13 -0
  905. package/src/templates/default/AGENTS.md +25 -9
  906. package/src/templates/default/_gitignore +1 -0
  907. package/src/templates/default/actions/view-screen.ts +1 -1
  908. package/src/templates/default/app/root.tsx +4 -1
  909. package/src/templates/default/package.json +2 -2
  910. package/src/templates/default/server/middleware/auth.ts +15 -0
  911. package/src/templates/default/server/routes/[...page].get.ts +2 -9
  912. package/src/templates/default/ssr-entry.ts +20 -0
  913. package/src/templates/workspace-core/AGENTS.md +62 -0
  914. package/src/templates/workspace-core/actions/company-directory.ts +38 -0
  915. package/src/templates/workspace-core/package.json +39 -0
  916. package/src/templates/workspace-core/skills/company-policies/SKILL.md +42 -0
  917. package/src/templates/workspace-core/src/client/AuthenticatedLayout.tsx +37 -0
  918. package/src/templates/workspace-core/src/client/index.ts +26 -0
  919. package/src/templates/workspace-core/src/credentials.ts +29 -0
  920. package/src/templates/workspace-core/src/index.ts +21 -0
  921. package/src/templates/workspace-core/src/server/agent-chat-plugin.ts +30 -0
  922. package/src/templates/workspace-core/src/server/auth-plugin.ts +35 -0
  923. package/src/templates/workspace-core/src/server/index.ts +22 -0
  924. package/src/templates/workspace-core/tailwind.preset.ts +34 -0
  925. package/src/templates/workspace-core/tsconfig.json +9 -0
  926. package/src/templates/workspace-root/.env.example +37 -0
  927. package/src/templates/workspace-root/README.md +62 -0
  928. package/src/templates/workspace-root/_gitignore +23 -0
  929. package/src/templates/workspace-root/package.json +18 -0
  930. package/src/templates/workspace-root/pnpm-workspace.yaml +3 -0
  931. package/src/templates/workspace-root/tsconfig.base.json +21 -0
  932. package/dist/adapters/convex/adapter.d.ts +0 -24
  933. package/dist/adapters/convex/adapter.d.ts.map +0 -1
  934. package/dist/adapters/convex/adapter.js +0 -125
  935. package/dist/adapters/convex/adapter.js.map +0 -1
  936. package/dist/adapters/convex/index.d.ts +0 -4
  937. package/dist/adapters/convex/index.d.ts.map +0 -1
  938. package/dist/adapters/convex/index.js +0 -3
  939. package/dist/adapters/convex/index.js.map +0 -1
  940. package/dist/adapters/drizzle/adapter.d.ts +0 -36
  941. package/dist/adapters/drizzle/adapter.d.ts.map +0 -1
  942. package/dist/adapters/drizzle/adapter.js +0 -210
  943. package/dist/adapters/drizzle/adapter.js.map +0 -1
  944. package/dist/adapters/drizzle/index.d.ts +0 -3
  945. package/dist/adapters/drizzle/index.d.ts.map +0 -1
  946. package/dist/adapters/drizzle/index.js +0 -3
  947. package/dist/adapters/drizzle/index.js.map +0 -1
  948. package/dist/adapters/drizzle/schema.d.ts +0 -146
  949. package/dist/adapters/drizzle/schema.d.ts.map +0 -1
  950. package/dist/adapters/drizzle/schema.js +0 -20
  951. package/dist/adapters/drizzle/schema.js.map +0 -1
  952. package/dist/adapters/firestore/adapter.d.ts +0 -48
  953. package/dist/adapters/firestore/adapter.d.ts.map +0 -1
  954. package/dist/adapters/firestore/adapter.js +0 -62
  955. package/dist/adapters/firestore/adapter.js.map +0 -1
  956. package/dist/adapters/firestore/index.d.ts +0 -4
  957. package/dist/adapters/firestore/index.d.ts.map +0 -1
  958. package/dist/adapters/firestore/index.js +0 -3
  959. package/dist/adapters/firestore/index.js.map +0 -1
  960. package/dist/adapters/supabase/adapter.d.ts +0 -43
  961. package/dist/adapters/supabase/adapter.d.ts.map +0 -1
  962. package/dist/adapters/supabase/adapter.js +0 -137
  963. package/dist/adapters/supabase/adapter.js.map +0 -1
  964. package/dist/adapters/supabase/index.d.ts +0 -3
  965. package/dist/adapters/supabase/index.d.ts.map +0 -1
  966. package/dist/adapters/supabase/index.js +0 -3
  967. package/dist/adapters/supabase/index.js.map +0 -1
  968. package/dist/adapters/sync/config.d.ts +0 -40
  969. package/dist/adapters/sync/config.d.ts.map +0 -1
  970. package/dist/adapters/sync/config.js +0 -209
  971. package/dist/adapters/sync/config.js.map +0 -1
  972. package/dist/adapters/sync/create-file-sync.d.ts +0 -32
  973. package/dist/adapters/sync/create-file-sync.d.ts.map +0 -1
  974. package/dist/adapters/sync/create-file-sync.js +0 -218
  975. package/dist/adapters/sync/create-file-sync.js.map +0 -1
  976. package/dist/adapters/sync/file-sync.d.ts +0 -94
  977. package/dist/adapters/sync/file-sync.d.ts.map +0 -1
  978. package/dist/adapters/sync/file-sync.js +0 -671
  979. package/dist/adapters/sync/file-sync.js.map +0 -1
  980. package/dist/adapters/sync/index.d.ts +0 -6
  981. package/dist/adapters/sync/index.d.ts.map +0 -1
  982. package/dist/adapters/sync/index.js +0 -6
  983. package/dist/adapters/sync/index.js.map +0 -1
  984. package/dist/adapters/sync/merge.d.ts +0 -21
  985. package/dist/adapters/sync/merge.d.ts.map +0 -1
  986. package/dist/adapters/sync/merge.js +0 -132
  987. package/dist/adapters/sync/merge.js.map +0 -1
  988. package/dist/adapters/sync/types.d.ts +0 -62
  989. package/dist/adapters/sync/types.d.ts.map +0 -1
  990. package/dist/adapters/sync/types.js +0 -23
  991. package/dist/adapters/sync/types.js.map +0 -1
  992. package/dist/client/harness.d.ts +0 -48
  993. package/dist/client/harness.d.ts.map +0 -1
  994. package/dist/client/harness.js.map +0 -1
  995. package/dist/client/use-file-sync-status.d.ts +0 -21
  996. package/dist/client/use-file-sync-status.d.ts.map +0 -1
  997. package/dist/client/use-file-sync-status.js +0 -65
  998. package/dist/client/use-file-sync-status.js.map +0 -1
  999. package/dist/server/default-watcher.d.ts +0 -23
  1000. package/dist/server/default-watcher.d.ts.map +0 -1
  1001. package/dist/server/default-watcher.js +0 -57
  1002. package/dist/server/default-watcher.js.map +0 -1
  1003. package/dist/server/file-sync-plugin.d.ts +0 -7
  1004. package/dist/server/file-sync-plugin.d.ts.map +0 -1
  1005. package/dist/server/file-sync-plugin.js +0 -38
  1006. package/dist/server/file-sync-plugin.js.map +0 -1
  1007. package/dist/vite/dev-api-server.d.ts +0 -10
  1008. package/dist/vite/dev-api-server.d.ts.map +0 -1
  1009. package/dist/vite/dev-api-server.js +0 -243
  1010. package/dist/vite/dev-api-server.js.map +0 -1
  1011. /package/{src/templates/default/application-state/.gitkeep → dist/templates/default/.ignore} +0 -0
@@ -1,11 +1,29 @@
1
- import { createProductionAgentHandler, getActiveRunForThreadAsync, abortRun, subscribeToRun, } from "../agent/production-agent.js";
1
+ import { runWithRequestContext, getRequestOrgId } from "./request-context.js";
2
+ import { getH3App } from "./framework-request-handler.js";
3
+ import { createProductionAgentHandler, runAgentLoop, actionsToEngineTools, getActiveRunForThreadAsync, abortRun, subscribeToRun, } from "../agent/production-agent.js";
4
+ import { resolveEngine, createAnthropicEngine } from "../agent/engine/index.js";
5
+ import { McpClientManager, loadMcpConfig, autoDetectMcpConfig, mcpToolsToActionEntries, } from "../mcp-client/index.js";
6
+ import { discoverAgents } from "./agent-discovery.js";
7
+ import { loadSchemaPromptBlock } from "./schema-prompt.js";
2
8
  import { buildAssistantMessage, extractThreadMeta, } from "../agent/thread-data-builder.js";
3
- import { defineEventHandler, readBody, setResponseStatus, setResponseHeader, getMethod, getQuery, } from "h3";
9
+ import { defineEventHandler, setResponseStatus, setResponseHeader, getMethod, getQuery, } from "h3";
4
10
  import { getSession } from "./auth.js";
11
+ import { getOrigin } from "./google-oauth.js";
5
12
  import { createThread, getThread, listThreads, searchThreads, updateThreadData, deleteThread, } from "../chat-threads/store.js";
6
13
  import { resourceListAccessible, resourceList, resourceGet, resourceGetByPath, ensurePersonalDefaults, SHARED_OWNER, } from "../resources/store.js";
7
- import fs from "node:fs";
8
14
  import nodePath from "node:path";
15
+ import { readBody } from "./h3-helpers.js";
16
+ import { getBuilderBrowserConnectUrl, requestBuilderBrowserConnection, } from "./builder-browser.js";
17
+ // Lazy fs — loaded via dynamic import() on first use.
18
+ // This avoids require() which bundlers convert to createRequire(import.meta.url)
19
+ // that crashes on CF Workers where import.meta.url is undefined.
20
+ let _fs;
21
+ async function lazyFs() {
22
+ if (!_fs) {
23
+ _fs = await import("node:fs");
24
+ }
25
+ return _fs;
26
+ }
9
27
  /**
10
28
  * Wraps a core CLI script (that writes to console.log) as a ActionEntry
11
29
  * by capturing stdout.
@@ -54,16 +72,53 @@ function wrapCliScript(tool, cliDefault) {
54
72
  },
55
73
  };
56
74
  }
75
+ /**
76
+ * Creates the docs-search tool so agents can look up framework documentation.
77
+ * Docs are bundled in @agent-native/core and read via fs at runtime.
78
+ */
79
+ async function createDocsScriptEntries() {
80
+ try {
81
+ const mod = await import("../scripts/docs/search.js");
82
+ return {
83
+ "docs-search": wrapCliScript({
84
+ description: "Search and read agent-native framework documentation. Use --list to see all pages, --query to search, --slug to read a specific page.",
85
+ parameters: {
86
+ type: "object",
87
+ properties: {
88
+ query: {
89
+ type: "string",
90
+ description: "Search term to find relevant docs (e.g. 'actions', 'authentication', 'database')",
91
+ },
92
+ slug: {
93
+ type: "string",
94
+ description: "Read a specific doc page by slug (e.g. 'actions', 'authentication', 'database')",
95
+ },
96
+ list: {
97
+ type: "string",
98
+ description: 'Set to "true" to list all available doc pages',
99
+ enum: ["true"],
100
+ },
101
+ },
102
+ },
103
+ }, mod.default),
104
+ };
105
+ }
106
+ catch {
107
+ return {};
108
+ }
109
+ }
57
110
  /**
58
111
  * Creates resource ScriptEntries available in both prod and dev modes.
59
112
  */
60
113
  async function createResourceScriptEntries() {
61
114
  try {
62
- const [list, read, write, del] = await Promise.all([
115
+ const [list, read, write, del, saveMem, delMem] = await Promise.all([
63
116
  import("../scripts/resources/list.js"),
64
117
  import("../scripts/resources/read.js"),
65
118
  import("../scripts/resources/write.js"),
66
119
  import("../scripts/resources/delete.js"),
120
+ import("../scripts/resources/save-memory.js"),
121
+ import("../scripts/resources/delete-memory.js"),
67
122
  ]);
68
123
  return {
69
124
  "resource-list": wrapCliScript({
@@ -150,6 +205,45 @@ async function createResourceScriptEntries() {
150
205
  required: ["path"],
151
206
  },
152
207
  }, del.default),
208
+ "save-memory": wrapCliScript({
209
+ 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.",
210
+ parameters: {
211
+ type: "object",
212
+ properties: {
213
+ name: {
214
+ type: "string",
215
+ description: "Short kebab-case identifier (e.g. 'coding-style', 'deploy-process'). Used as the filename.",
216
+ },
217
+ type: {
218
+ type: "string",
219
+ description: "Memory category",
220
+ enum: ["user", "feedback", "project", "reference"],
221
+ },
222
+ description: {
223
+ type: "string",
224
+ description: "One-line summary shown in the memory index (keep under 80 chars)",
225
+ },
226
+ content: {
227
+ type: "string",
228
+ description: "The memory content in markdown. For updates, read first and provide full updated content.",
229
+ },
230
+ },
231
+ required: ["name", "type", "description", "content"],
232
+ },
233
+ }, saveMem.default),
234
+ "delete-memory": wrapCliScript({
235
+ description: "Delete a memory entry and remove it from the memory index.",
236
+ parameters: {
237
+ type: "object",
238
+ properties: {
239
+ name: {
240
+ type: "string",
241
+ description: "The memory name to delete (e.g. 'coding-style')",
242
+ },
243
+ },
244
+ required: ["name"],
245
+ },
246
+ }, delMem.default),
153
247
  };
154
248
  }
155
249
  catch {
@@ -157,16 +251,88 @@ async function createResourceScriptEntries() {
157
251
  return {};
158
252
  }
159
253
  }
254
+ /**
255
+ * Creates chat management ActionEntries (search-chats, open-chat).
256
+ */
257
+ async function createChatScriptEntries() {
258
+ try {
259
+ const [searchMod, openMod] = await Promise.all([
260
+ import("../scripts/chat/search-chats.js"),
261
+ import("../scripts/chat/open-chat.js"),
262
+ ]);
263
+ return {
264
+ "search-chats": wrapCliScript({
265
+ description: "Search or list past agent chat threads. Use this to find previous conversations by keyword.",
266
+ parameters: {
267
+ type: "object",
268
+ properties: {
269
+ query: {
270
+ type: "string",
271
+ description: "Search term to find chats by title, preview, or content",
272
+ },
273
+ limit: {
274
+ type: "string",
275
+ description: "Max number of results (default: 20)",
276
+ },
277
+ format: {
278
+ type: "string",
279
+ description: "Output format",
280
+ enum: ["json", "text"],
281
+ },
282
+ },
283
+ },
284
+ }, searchMod.default),
285
+ "open-chat": wrapCliScript({
286
+ description: "Open a chat thread in the UI as a new tab and focus it. Use search-chats first to find the thread ID.",
287
+ parameters: {
288
+ type: "object",
289
+ properties: {
290
+ id: {
291
+ type: "string",
292
+ description: "The chat thread ID to open",
293
+ },
294
+ },
295
+ required: ["id"],
296
+ },
297
+ }, openMod.default),
298
+ };
299
+ }
300
+ catch {
301
+ return {};
302
+ }
303
+ }
304
+ /**
305
+ * Creates agent engine management tools (list-agent-engines, set-agent-engine,
306
+ * test-agent-engine). Let the agent inspect and configure the active LLM engine.
307
+ */
308
+ async function createAgentEngineScriptEntries() {
309
+ try {
310
+ const [listMod, setMod, testMod] = await Promise.all([
311
+ import("../scripts/agent-engines/list-agent-engines.js"),
312
+ import("../scripts/agent-engines/set-agent-engine.js"),
313
+ import("../scripts/agent-engines/test-agent-engine.js"),
314
+ ]);
315
+ return {
316
+ "list-agent-engines": { tool: listMod.tool, run: listMod.run },
317
+ "set-agent-engine": { tool: setMod.tool, run: setMod.run },
318
+ "test-agent-engine": { tool: testMod.tool, run: testMod.run },
319
+ };
320
+ }
321
+ catch {
322
+ return {};
323
+ }
324
+ }
160
325
  /**
161
326
  * Creates the call-agent ActionEntry for cross-agent A2A communication.
327
+ * Binds selfAppId so the agent cannot call itself via call-agent.
162
328
  */
163
- async function createCallAgentScriptEntry() {
329
+ async function createCallAgentScriptEntry(selfAppId) {
164
330
  try {
165
331
  const mod = await import("../scripts/call-agent.js");
166
332
  return {
167
333
  "call-agent": {
168
334
  tool: mod.tool,
169
- run: mod.run,
335
+ run: (args, context) => mod.run(args, context, selfAppId),
170
336
  },
171
337
  };
172
338
  }
@@ -174,6 +340,269 @@ async function createCallAgentScriptEntry() {
174
340
  return {};
175
341
  }
176
342
  }
343
+ function createBuilderBrowserTool(deps) {
344
+ return {
345
+ "get-browser-connection": {
346
+ tool: {
347
+ description: "Provision a Builder-backed browser session and return browser websocket connection details. If Builder browser access is not configured yet, this returns setup guidance instead.",
348
+ parameters: {
349
+ type: "object",
350
+ properties: {
351
+ sessionId: {
352
+ type: "string",
353
+ description: "Stable browser session identifier. Reuse it to reconnect to the same browser session.",
354
+ },
355
+ projectId: {
356
+ type: "string",
357
+ description: "Optional Builder project or space identifier to scope the session.",
358
+ },
359
+ branchName: {
360
+ type: "string",
361
+ description: "Optional branch name for Builder preview sessions.",
362
+ },
363
+ proxyOrigin: {
364
+ type: "string",
365
+ description: "Optional source origin to proxy from when browsing a local app.",
366
+ },
367
+ proxyDefaultOrigin: {
368
+ type: "string",
369
+ description: "Optional default origin that the browser should use for proxied requests.",
370
+ },
371
+ proxyDestination: {
372
+ type: "string",
373
+ description: "Optional destination origin for proxying local development traffic.",
374
+ },
375
+ },
376
+ required: ["sessionId"],
377
+ },
378
+ },
379
+ run: async (args) => {
380
+ if (!process.env.BUILDER_PRIVATE_KEY ||
381
+ !process.env.BUILDER_PUBLIC_KEY) {
382
+ return JSON.stringify({
383
+ configured: false,
384
+ message: "Builder browser access is not configured. Connect Builder from the workspace Resources panel before requesting a browser session.",
385
+ connectUrl: getBuilderBrowserConnectUrl(deps.getOrigin()),
386
+ });
387
+ }
388
+ const connection = await requestBuilderBrowserConnection({
389
+ sessionId: args.sessionId,
390
+ projectId: args.projectId,
391
+ branchName: args.branchName,
392
+ proxyOrigin: args.proxyOrigin,
393
+ proxyDefaultOrigin: args.proxyDefaultOrigin,
394
+ proxyDestination: args.proxyDestination,
395
+ });
396
+ return JSON.stringify({
397
+ configured: true,
398
+ sessionId: args.sessionId,
399
+ ...connection,
400
+ });
401
+ },
402
+ },
403
+ };
404
+ }
405
+ /**
406
+ * Creates agent team orchestration tools (spawn-task, task-status, read-task-result).
407
+ * These let the main agent spawn sub-agents and coordinate work.
408
+ */
409
+ function createTeamTools(deps) {
410
+ return {
411
+ "spawn-task": {
412
+ tool: {
413
+ description: "Spawn a sub-agent to handle a task in the background. The sub-agent runs independently with its own conversation thread. Use this to delegate work so the main chat stays free for new requests. A live preview card will appear in the chat showing the sub-agent's progress.",
414
+ parameters: {
415
+ type: "object",
416
+ properties: {
417
+ task: {
418
+ type: "string",
419
+ description: "Clear description of what the sub-agent should accomplish",
420
+ },
421
+ instructions: {
422
+ type: "string",
423
+ description: "Optional additional instructions or context for the sub-agent",
424
+ },
425
+ name: {
426
+ type: "string",
427
+ description: "Short name for the sub-agent tab (e.g. 'Research', 'Draft email'). If omitted, derived from the task.",
428
+ },
429
+ agent: {
430
+ type: "string",
431
+ description: "Optional custom agent profile from agents/*.md to use for this task.",
432
+ },
433
+ },
434
+ required: ["task"],
435
+ },
436
+ },
437
+ run: async (args) => {
438
+ // Capture the send function NOW (at spawn time) so that
439
+ // concurrent runs don't clobber each other's send reference.
440
+ const capturedSend = deps.getSend();
441
+ const { spawnTask } = await import("./agent-teams.js");
442
+ // Filter out team orchestration tools so sub-agents can't spawn sub-agents
443
+ const teamToolNames = new Set([
444
+ "spawn-task",
445
+ "task-status",
446
+ "read-task-result",
447
+ "send-to-task",
448
+ "list-tasks",
449
+ ]);
450
+ const subAgentActions = Object.fromEntries(Object.entries(deps.getActions()).filter(([name]) => !teamToolNames.has(name)));
451
+ let instructions = args.instructions;
452
+ let selectedModel = deps.getModel();
453
+ let selectedName = args.name || "";
454
+ if (args.agent) {
455
+ const { findAccessibleCustomAgent } = await import("../resources/agents.js");
456
+ const profile = await findAccessibleCustomAgent(deps.getOwner(), args.agent);
457
+ if (!profile) {
458
+ throw new Error(`Custom agent not found: ${args.agent}`);
459
+ }
460
+ const profileInstructions = `## Custom Agent Profile: ${profile.name}\n\n` +
461
+ (profile.description ? `${profile.description}\n\n` : "") +
462
+ profile.instructions;
463
+ instructions = instructions
464
+ ? `${profileInstructions}\n\n## Extra Task Context\n\n${instructions}`
465
+ : profileInstructions;
466
+ selectedModel = profile.model ?? selectedModel;
467
+ selectedName = selectedName || profile.name;
468
+ }
469
+ const task = await spawnTask({
470
+ description: args.task,
471
+ instructions,
472
+ ownerEmail: deps.getOwner(),
473
+ systemPrompt: deps.getSystemPrompt(),
474
+ actions: subAgentActions,
475
+ engine: deps.getEngine(),
476
+ model: selectedModel,
477
+ parentThreadId: deps.getParentThreadId(),
478
+ parentSend: (event) => {
479
+ if (capturedSend)
480
+ capturedSend(event);
481
+ },
482
+ });
483
+ return JSON.stringify({
484
+ taskId: task.taskId,
485
+ threadId: task.threadId,
486
+ status: task.status,
487
+ description: task.description,
488
+ name: selectedName,
489
+ });
490
+ },
491
+ },
492
+ "task-status": {
493
+ tool: {
494
+ description: "Check the status of a sub-agent task. Returns current status, preview of output, and current step.",
495
+ parameters: {
496
+ type: "object",
497
+ properties: {
498
+ taskId: {
499
+ type: "string",
500
+ description: "The task ID returned by spawn-task",
501
+ },
502
+ },
503
+ required: ["taskId"],
504
+ },
505
+ },
506
+ run: async (args) => {
507
+ const { getTask } = await import("./agent-teams.js");
508
+ const task = await getTask(args.taskId);
509
+ if (!task)
510
+ return JSON.stringify({ error: "Task not found" });
511
+ return JSON.stringify({
512
+ taskId: task.taskId,
513
+ threadId: task.threadId,
514
+ status: task.status,
515
+ description: task.description,
516
+ preview: task.preview,
517
+ currentStep: task.currentStep,
518
+ summary: task.summary,
519
+ });
520
+ },
521
+ },
522
+ "read-task-result": {
523
+ tool: {
524
+ description: "Read the result of a completed sub-agent task. Returns the full output summary.",
525
+ parameters: {
526
+ type: "object",
527
+ properties: {
528
+ taskId: {
529
+ type: "string",
530
+ description: "The task ID returned by spawn-task",
531
+ },
532
+ },
533
+ required: ["taskId"],
534
+ },
535
+ },
536
+ run: async (args) => {
537
+ const { getTask } = await import("./agent-teams.js");
538
+ const task = await getTask(args.taskId);
539
+ if (!task)
540
+ return JSON.stringify({ error: "Task not found" });
541
+ if (task.status === "running") {
542
+ return JSON.stringify({
543
+ status: "running",
544
+ preview: task.preview,
545
+ message: "Task is still running. Check back later.",
546
+ });
547
+ }
548
+ return JSON.stringify({
549
+ taskId: task.taskId,
550
+ status: task.status,
551
+ summary: task.summary,
552
+ preview: task.preview,
553
+ });
554
+ },
555
+ },
556
+ "send-to-task": {
557
+ tool: {
558
+ description: "Send a message or update to a running sub-agent. Use this to redirect, add context, or give feedback to a sub-agent while it's working.",
559
+ parameters: {
560
+ type: "object",
561
+ properties: {
562
+ taskId: {
563
+ type: "string",
564
+ description: "The task ID returned by spawn-task",
565
+ },
566
+ message: {
567
+ type: "string",
568
+ description: "Message to send to the sub-agent",
569
+ },
570
+ },
571
+ required: ["taskId", "message"],
572
+ },
573
+ },
574
+ run: async (args) => {
575
+ const { sendToTask } = await import("./agent-teams.js");
576
+ const result = await sendToTask(args.taskId, args.message);
577
+ return JSON.stringify(result);
578
+ },
579
+ },
580
+ "list-tasks": {
581
+ tool: {
582
+ description: "List all sub-agent tasks and their current status. Use this to see what's running, completed, or failed.",
583
+ parameters: {
584
+ type: "object",
585
+ properties: {},
586
+ },
587
+ },
588
+ run: async () => {
589
+ const { listTasks } = await import("./agent-teams.js");
590
+ const tasks = await listTasks();
591
+ if (tasks.length === 0) {
592
+ return "No sub-agent tasks.";
593
+ }
594
+ return JSON.stringify(tasks.map((t) => ({
595
+ taskId: t.taskId,
596
+ threadId: t.threadId,
597
+ description: t.description,
598
+ status: t.status,
599
+ currentStep: t.currentStep,
600
+ hasResult: t.summary.length > 0,
601
+ })), null, 2);
602
+ },
603
+ },
604
+ };
605
+ }
177
606
  /**
178
607
  * Framework-level instructions injected into every agent's system prompt.
179
608
  * This is the single source of truth for the core philosophy, rules, and patterns.
@@ -187,23 +616,124 @@ const FRAMEWORK_CORE = `
187
616
  ### Core Rules
188
617
 
189
618
  1. **Data lives in SQL** — All app state is in a SQL database (could be SQLite, Postgres, Turso, or Cloudflare D1 — never assume which). Use the available database tools.
190
- 2. **Context awareness** — Before taking action, understand what the user is looking at. Use the \`view-screen\` tool if available it returns the current UI state (which page, which item is focused, what's selected).
619
+ 2. **Context awareness** — The user's current screen state is automatically included in each message as a \`<current-screen>\` block. Use it to understand what the user is looking at. You can still call \`view-screen\` for a more detailed snapshot if needed, but you should NOT need to call it before every action.
191
620
  3. **Navigate the UI** — Use the \`navigate\` tool to switch views, open items, or focus elements for the user.
192
621
  4. **Application state** — Ephemeral UI state (drafts, selections, navigation) lives in \`application_state\`. Use \`readAppState\`/\`writeAppState\` to read and write it. When you write state, the UI updates automatically.
193
- 5. **Resources for memory** — Use the Resources system for persistent notes and context. Update LEARNINGS.md when you learn user preferences or corrections. Update the shared AGENTS.md for instructions that should apply to all users.
622
+ 5. **Memory** — Use the structured memory system to persist knowledge across sessions. Use \`save-memory\` proactively when you learn preferences, corrections, or project context. Update shared AGENTS.md for instructions that should apply to all users.
623
+ 6. **Security** — Always use \`defineAction\` with a Zod \`schema:\` for input validation. Never construct SQL with string concatenation — use parameterized queries via db-query/db-exec. Never use \`dangerouslySetInnerHTML\`, \`innerHTML\`, or \`eval()\`. Never expose secrets in responses or source code. Every table with user data must have \`owner_email\`.
194
624
 
195
625
  ### Resources
196
626
 
197
- You have access to a Resources system for persistent notes, learnings, and context files.
627
+ You have access to a Resources system for persistent notes and context files.
198
628
  Use resource-list, resource-read, resource-write, and resource-delete to manage resources.
199
629
  Resources can be personal (per-user) or shared (team-wide). By default, resources are personal.
200
630
 
201
- When you learn something important (user corrections, preferences, patterns), update the "LEARNINGS.md" resource. Keep it tidy — revise, consolidate, and remove outdated entries rather than only appending.
202
- When the user gives instructions that should apply to all users/sessions, update the shared "AGENTS.md" resource instead.
631
+ When the user gives instructions that should apply to all users/sessions, update the shared "AGENTS.md" resource.
203
632
 
204
633
  ### Navigation Rule
205
634
 
206
635
  When the user says "show me", "go to", "open", "switch to", or similar navigation language, ALWAYS use the \`navigate\` action to update the UI. The user expects to SEE the result in the main app, not just read it in chat. Navigate first, then fetch/display data.
636
+
637
+ ### Chat History
638
+
639
+ You can search and restore previous chat conversations:
640
+ - \`search-chats\` — Search or list past chat threads by keyword
641
+ - \`open-chat\` — Open a chat thread in the UI as a new tab and focus it
642
+
643
+ When the user asks to find a previous conversation, use \`search-chats\` first to find matching threads, then \`open-chat\` to restore the one they want.
644
+
645
+ ### Agent Teams — Orchestration
646
+
647
+ You are an orchestrator. For complex or multi-step tasks, delegate to sub-agents:
648
+ - \`spawn-task\` — Spawn a sub-agent for a task. It runs in its own thread while you stay available. A live preview card appears in the chat. You can optionally choose a custom agent profile from \`agents/*.md\`.
649
+ - \`task-status\` — Check the progress of a running sub-agent.
650
+ - \`read-task-result\` — Read the result when a sub-agent finishes.
651
+
652
+ **When to delegate vs do directly:**
653
+ - **Delegate** when the task involves multiple tool calls, research, content generation, or anything that takes more than a few seconds. Examples: "create a deck about X", "analyze the data and write a report", "look up Y and draft an email about it".
654
+ - **Do directly** for quick single-step tasks like navigation, reading state, or answering simple questions.
655
+ - **Spawn multiple sub-agents** when the user asks for multiple independent things — they'll run in parallel.
656
+
657
+ **How to orchestrate:**
658
+ 1. When the user asks for something complex, spawn a sub-agent with a clear task description.
659
+ 2. Tell the user what you've started ("I'm having a sub-agent research that for you").
660
+ 3. You can keep chatting — sub-agents run independently.
661
+ 4. Use \`read-task-result\` to check results when needed, or the user can see live progress in the card.
662
+ 5. If the user's request has multiple steps, you can spawn one sub-agent per step, or chain them.
663
+
664
+ Sub-agents have access to all template tools but **cannot spawn sub-agents themselves** — only you (the orchestrator) can do that. Give the sub-agent a specific, actionable task description — it will figure out which tools to use. If a matching custom agent profile exists, pass it via the \`agent\` parameter on \`spawn-task\`.
665
+
666
+ ### Recurring Jobs
667
+
668
+ You can create recurring jobs that run on a cron schedule. Jobs are resource files under \`jobs/\`. Each job has a cron schedule and instructions that the agent executes automatically.
669
+
670
+ - \`create-job\` — Create a new recurring job with a cron schedule and instructions
671
+ - \`list-jobs\` — List all recurring jobs and their status (schedule, last run, next run, errors)
672
+ - \`update-job\` — Update a job's schedule, instructions, or toggle enabled/disabled
673
+ - Delete a job with \`resource-delete --path jobs/<name>.md\`
674
+
675
+ When the user asks for something recurring ("every morning", "daily at 9am", "weekly on Mondays"), create a job. Convert natural language to 5-field cron format:
676
+ - "every morning" / "daily at 9am" → \`0 9 * * *\`
677
+ - "every weekday at 9am" → \`0 9 * * 1-5\`
678
+ - "every hour" → \`0 * * * *\`
679
+ - "every 30 minutes" → \`*/30 * * * *\`
680
+ - "every monday at 9am" → \`0 9 * * 1\`
681
+ - "twice a day" / "morning and evening" → \`0 9,17 * * *\`
682
+
683
+ Job instructions should be self-contained — include which actions to call, what conditions to check, and what to do with results. The agent executing the job has access to all the same tools you do.
684
+
685
+ ### Browser Access
686
+
687
+ Use \`get-browser-connection\` when you need a real browser session backed by Builder. It returns websocket connection details for a provisioned browser session.
688
+
689
+ - If the tool says Builder is not configured, tell the user to connect Builder from the workspace Resources panel.
690
+ - Reuse a stable \`sessionId\` when you want to reconnect to the same browser session.
691
+ - Include proxy parameters when you need the browser to reach a local dev server through Builder's browser connection flow.
692
+
693
+ ### call-agent — External Apps Only
694
+
695
+ 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.
696
+
697
+ **NEVER use \`call-agent\` to:**
698
+ - Call your own app by name (if you are the "macros" agent, never do \`call-agent(agent="macros")\`)
699
+ - Perform tasks you can accomplish with your own registered tools
700
+ - Wrap your own actions in an A2A round-trip
701
+
702
+ **ONLY use \`call-agent\` when:**
703
+ - The user explicitly asks you to communicate with a different app (e.g., "ask the mail agent to...")
704
+ - You need data that only another deployed app can provide
705
+ - You are coordinating across genuinely separate apps
706
+
707
+ If \`call-agent\` returns an error saying the agent is yourself — stop and use your own tools instead.
708
+
709
+ ### Structured Memory
710
+
711
+ You have a structured memory system. Your memory index (\`memory/MEMORY.md\`) is loaded at the start of every conversation (shown above). Individual memories are stored as separate files under \`memory/\`.
712
+
713
+ **Tools:**
714
+ - \`save-memory\` — Create or update a memory. Provide name, type, description, and content. Atomically updates both the memory file and the index.
715
+ - \`delete-memory\` — Remove a memory and its index entry.
716
+ - \`resource-read --path memory/<name>.md\` — Read the full content of a specific memory when you need details beyond the index.
717
+
718
+ **Memory types:**
719
+ - \`user\` — Preferences, role, personal context, contacts
720
+ - \`feedback\` — Corrections ("don't do X, do Y instead"), confirmed approaches
721
+ - \`project\` — Ongoing work context, decisions, status
722
+ - \`reference\` — Pointers to external systems, URLs, API details
723
+
724
+ **When to save (do it proactively, don't ask permission):**
725
+ - User corrects your approach → save as \`feedback\`
726
+ - User shares preferences (tone, style, workflow) → save as \`user\`
727
+ - You discover a non-obvious pattern or gotcha → save as \`feedback\`
728
+ - User provides personal context (contacts, team, domain) → save as \`user\`
729
+ - A project gains enough context to track → save as \`project\`
730
+
731
+ **Rules:**
732
+ - Don't save things obvious from the code or standard framework behavior
733
+ - When updating an existing memory, read it first and merge — don't overwrite blindly
734
+ - Keep descriptions concise — the index is loaded every message
735
+ - One memory per logical topic (e.g. 'coding-style', 'project-alpha')
736
+ - Don't save temporary debugging notes or ephemeral task details
207
737
  `;
208
738
  const PROD_FRAMEWORK_PROMPT = `## Agent-Native Framework — Production Mode
209
739
 
@@ -212,6 +742,21 @@ You are an AI agent in an agent-native application, running in **production mode
212
742
  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.
213
743
 
214
744
  **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.
745
+
746
+ ### Code Changes Not Available
747
+
748
+ When the user asks you to change the UI, modify code, add features, fix bugs in the app itself, change styles, or do anything that requires editing source files — you MUST respond with this exact message (replacing APP_NAME with the current app name from the URL hostname):
749
+
750
+ > This app is running in hosted mode and I can't make code changes here. To customize this app:
751
+ >
752
+ > **Option 1:** Connect to [Builder.io](https://www.builder.io/m/agent-native) for a full development environment
753
+ >
754
+ > **Option 2:** Clone and run locally:
755
+ > \`\`\`
756
+ > npx agent-native create APP_NAME
757
+ > \`\`\`
758
+
759
+ Do NOT attempt to work around this limitation. Do NOT say "I can't do that" without providing the options above. Always include both the Builder.io link and the CLI command.
215
760
  ${FRAMEWORK_CORE}`;
216
761
  const DEV_FRAMEWORK_PROMPT = `## Agent-Native Framework — Development Mode
217
762
 
@@ -219,7 +764,17 @@ You are an AI agent in an agent-native application, running in **development mod
219
764
 
220
765
  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.
221
766
 
222
- **In development mode, you have full access to the project filesystem, shell, and database** — in addition to all the app's production tools. You can edit source code, run commands, install packages, and modify the app directly.
767
+ **In development mode, you have UNRESTRICTED access.** You can:
768
+ - Run ANY shell command via the \`shell\` tool (bash, node, curl, pnpm, etc.)
769
+ - Execute arbitrary code: \`shell({ command: 'node -e "console.log(1+1)"' })\`
770
+ - Read/write any file on the filesystem
771
+ - Query and modify the database
772
+ - Call external APIs (via shell with curl, or via scripts)
773
+ - Edit source code, install packages, modify the app
774
+
775
+ **There are NO restrictions in dev mode.** If a dedicated tool/action doesn't exist for what you need, use \`shell\` to run any command. For example: \`shell({ command: 'curl -s https://api.example.com/data' })\`
776
+
777
+ **Template-specific actions are invoked via shell, NOT as direct tools.** In dev mode, the only tools registered as native tool calls are framework-level utilities (shell, file ops, resources, chat, teams, jobs). Anything from the template's \`actions/\` directory must be run through shell: \`shell({ 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 \`shell\`. Do not try to call template actions by name as if they were tools; they will not appear in your tool list.
223
778
 
224
779
  When editing code, follow the agent-native architecture:
225
780
  - Every feature needs all four areas: UI + scripts + skills/instructions + application-state sync
@@ -229,59 +784,180 @@ When editing code, follow the agent-native architecture:
229
784
  ${FRAMEWORK_CORE}`;
230
785
  const DEFAULT_SYSTEM_PROMPT = PROD_FRAMEWORK_PROMPT;
231
786
  /**
232
- * Pre-load AGENTS.md and LEARNINGS.md (personal + shared) and append to the system prompt.
233
- * This ensures the agent always has the user's context without needing to call tools first.
787
+ * Pre-load the agent's context: AGENTS.md (template instructions), the skills
788
+ * index, shared LEARNINGS.md (team notes), and memory/MEMORY.md (personal
789
+ * structured memory index). These all get appended to the system prompt so
790
+ * the agent has everything it needs from the first turn.
791
+ *
792
+ * Four sources are layered:
793
+ *
794
+ * 1. `<workspace>` — AGENTS.md from the enterprise workspace core.
795
+ * 2. `<template>` — AGENTS.md + skills index from the Vite plugin bundle.
796
+ * 3. `<shared>` — LEARNINGS.md from the SQL shared scope. Team-level notes.
797
+ * 4. `<personal>` — memory/MEMORY.md from the SQL personal scope. The
798
+ * current user's structured memory index.
799
+ *
800
+ * Each source is read independently — no copying between them. Editing
801
+ * AGENTS.md and restarting the server is all it takes; Vite HMR invalidates
802
+ * the bundle in dev so changes land instantly.
234
803
  */
235
804
  async function loadResourcesForPrompt(owner) {
236
805
  await ensurePersonalDefaults(owner);
237
- const resourceNames = ["AGENTS.md", "LEARNINGS.md"];
238
806
  const sections = [];
239
- for (const name of resourceNames) {
240
- // Read shared
807
+ // 1. Workspace AGENTS.md + skills merged into the template bundle.
808
+ try {
809
+ const { loadAgentsBundle, generateSkillsPromptBlock } = await import("./agents-bundle.js");
810
+ const bundle = await loadAgentsBundle();
811
+ // Workspace-core AGENTS.md (enterprise-wide instructions), if present.
812
+ if (bundle.workspaceAgentsMd && bundle.workspaceAgentsMd.trim()) {
813
+ sections.push(`<resource name="AGENTS.md" scope="workspace">\n${bundle.workspaceAgentsMd.trim()}\n</resource>`);
814
+ }
815
+ // 2. Template AGENTS.md.
816
+ if (bundle.agentsMd.trim()) {
817
+ sections.push(`<resource name="AGENTS.md" scope="template">\n${bundle.agentsMd.trim()}\n</resource>`);
818
+ }
819
+ const skillsBlock = generateSkillsPromptBlock(bundle);
820
+ if (skillsBlock)
821
+ sections.push(skillsBlock);
822
+ }
823
+ catch { }
824
+ // LEARNINGS.md from SQL (template-level instructions are in AGENTS.md above).
825
+ // 2. Shared SQL scope
826
+ try {
827
+ const shared = await resourceGetByPath(SHARED_OWNER, "LEARNINGS.md");
828
+ if (shared?.content?.trim()) {
829
+ sections.push(`<resource name="LEARNINGS.md" scope="shared">\n${shared.content.trim()}\n</resource>`);
830
+ }
831
+ }
832
+ catch { }
833
+ // 3. Personal memory index (skip if owner is the shared sentinel)
834
+ if (owner !== SHARED_OWNER) {
241
835
  try {
242
- const shared = await resourceGetByPath(SHARED_OWNER, name);
243
- if (shared?.content?.trim()) {
244
- sections.push(`<resource name="${name}" scope="shared">\n${shared.content.trim()}\n</resource>`);
836
+ const memoryIndex = await resourceGetByPath(owner, "memory/MEMORY.md");
837
+ if (memoryIndex?.content?.trim()) {
838
+ sections.push(`<resource name="memory/MEMORY.md" scope="personal">\n${memoryIndex.content.trim()}\n</resource>`);
245
839
  }
246
840
  }
247
841
  catch { }
248
- // Read personal (skip if owner is the shared sentinel)
249
- if (owner !== SHARED_OWNER) {
250
- try {
251
- const personal = await resourceGetByPath(owner, name);
252
- if (personal?.content?.trim()) {
253
- sections.push(`<resource name="${name}" scope="personal">\n${personal.content.trim()}\n</resource>`);
254
- }
255
- }
256
- catch { }
257
- }
258
842
  }
259
843
  if (sections.length === 0)
260
844
  return "";
261
845
  return ("\n\nThe following resources contain template-specific instructions and user context. Use the information in them to help the user.\n\n" +
262
846
  sections.join("\n\n"));
263
847
  }
848
+ /**
849
+ * Build the per-request SQL-schema context block. Reads AGENT_ORG_ID live
850
+ * from the environment so scheduler/A2A/HTTP call sites all see whatever
851
+ * org was just resolved for this request.
852
+ */
853
+ async function buildSchemaBlock(owner, hasRawDbTools) {
854
+ try {
855
+ return await loadSchemaPromptBlock({
856
+ owner,
857
+ orgId: getRequestOrgId() ?? null,
858
+ hasRawDbTools,
859
+ });
860
+ }
861
+ catch {
862
+ return "";
863
+ }
864
+ }
264
865
  /** @deprecated Kept for backward compat — dev prompt is now part of DEV_FRAMEWORK_PROMPT */
265
866
  const DEFAULT_DEV_PROMPT = "";
266
867
  /**
267
868
  * Generates a system prompt section describing registered template actions.
268
869
  * This helps the agent prefer template-specific actions over raw db-query/db-exec.
870
+ *
871
+ * Two output modes:
872
+ *
873
+ * - `"tool"` — used in production, where template actions are registered
874
+ * as native Anthropic tools. Output reads `name(arg*: type; ...) — desc`.
875
+ * - `"cli"` — used in dev, where template actions are NOT registered as
876
+ * native tools and must be invoked via `shell(command="pnpm action ...")`.
877
+ * Output reads `pnpm action name --arg <type> [--opt <type>] — desc`.
269
878
  */
270
- function generateActionsPrompt(registry) {
879
+ function generateActionsPrompt(registry, mode = "tool") {
271
880
  if (!registry || Object.keys(registry).length === 0)
272
881
  return "";
273
882
  const lines = Object.entries(registry).map(([name, entry]) => {
274
883
  const desc = entry.tool.description;
275
884
  const params = entry.tool.parameters?.properties;
885
+ const requiredFields = new Set(entry.tool.parameters?.required ?? []);
886
+ if (mode === "cli") {
887
+ // CLI mode: emit `pnpm action <name> --required <type> [--optional <type>]`
888
+ if (!params || Object.keys(params).length === 0) {
889
+ return `- \`pnpm action ${name}\` — ${desc}`;
890
+ }
891
+ const entries = Object.entries(params);
892
+ // Required first (alphabetical), then optional (alphabetical)
893
+ entries.sort(([a], [b]) => {
894
+ const ar = requiredFields.has(a) ? 0 : 1;
895
+ const br = requiredFields.has(b) ? 0 : 1;
896
+ if (ar !== br)
897
+ return ar - br;
898
+ return a.localeCompare(b);
899
+ });
900
+ const required = [];
901
+ const optional = [];
902
+ const requiredNames = [];
903
+ for (const [k, v] of entries) {
904
+ const type = v.type ?? "any";
905
+ const flag = `--${k} <${type}>`;
906
+ if (requiredFields.has(k)) {
907
+ required.push(flag);
908
+ requiredNames.push(`--${k}`);
909
+ }
910
+ else {
911
+ optional.push(`[${flag}]`);
912
+ }
913
+ }
914
+ const cmd = ["pnpm action " + name, ...required, ...optional].join(" ");
915
+ const requiredNote = requiredNames.length > 0
916
+ ? ` Required: ${requiredNames.join(", ")}.`
917
+ : "";
918
+ return `- \`${cmd}\` — ${desc}.${requiredNote}`;
919
+ }
920
+ // tool mode (production / native tool calls)
276
921
  if (params) {
277
- const paramList = Object.entries(params)
278
- .map(([k, v]) => `--${k}${v.description ? ` (${v.description})` : ""}`)
279
- .join(", ");
280
- return `- \`${name}\` — ${desc} Args: ${paramList}`;
922
+ // Order required params first, then optional. Mark required with "*"
923
+ // and include type + description so the agent knows exactly how to call.
924
+ const entries = Object.entries(params);
925
+ entries.sort(([a], [b]) => {
926
+ const ar = requiredFields.has(a) ? 0 : 1;
927
+ const br = requiredFields.has(b) ? 0 : 1;
928
+ if (ar !== br)
929
+ return ar - br;
930
+ return a.localeCompare(b);
931
+ });
932
+ const paramList = entries
933
+ .map(([k, v]) => {
934
+ const isRequired = requiredFields.has(k);
935
+ const type = v.type ?? "any";
936
+ const marker = isRequired ? "*" : "?";
937
+ const descPart = v.description ? ` — ${v.description}` : "";
938
+ return `${k}${marker}: ${type}${descPart}`;
939
+ })
940
+ .join("; ");
941
+ return `- \`${name}\`(${paramList}) — ${desc}`;
281
942
  }
282
- return `- \`${name}\` — ${desc}`;
943
+ return `- \`${name}\`() — ${desc}`;
283
944
  });
284
- return `\n\n## Available Actions\n\nThese are your registered template actions. ALWAYS prefer these over raw db-query/db-exec when a matching action exists:\n\n${lines.join("\n")}`;
945
+ if (mode === "cli") {
946
+ return `\n\n## Available Actions
947
+
948
+ **These template actions are NOT exposed as direct tools in dev mode. To run any of them, use the \`shell\` tool with the exact command shown below.** Example: \`shell(command="pnpm action add-slide --deckId abc --content 'Hello'")\`.
949
+
950
+ Do NOT try to call these by name as if they were tools — they will not exist in your tool list. Always go through \`shell\`.
951
+
952
+ ${lines.join("\n")}`;
953
+ }
954
+ return `\n\n## Available Actions
955
+
956
+ **Use these actions directly to accomplish tasks. Do NOT use \`db-schema\`, \`search-files\`, or \`shell\` to explore the app — these actions already connect to the correct database and services.**
957
+
958
+ Parameter notation: \`name*\` = required, \`name?\` = optional. Always pass the tool's parameters as a JSON object to the tool_use call — never via shell or string-concatenated CLI flags.
959
+
960
+ ${lines.join("\n")}`;
285
961
  }
286
962
  /**
287
963
  * Creates a Nitro plugin that mounts the agent chat endpoint.
@@ -292,7 +968,7 @@ function generateActionsPrompt(registry) {
292
968
  * Usage in templates:
293
969
  * ```ts
294
970
  * // server/plugins/agent-chat.ts
295
- * import { createAgentChatPlugin } from "@agent-native/core/server";
971
+ * import { readBody, createAgentChatPlugin } from "@agent-native/core/server";
296
972
  * import { scriptRegistry } from "../../scripts/registry.js";
297
973
  *
298
974
  * export default createAgentChatPlugin({
@@ -301,7 +977,7 @@ function generateActionsPrompt(registry) {
301
977
  * });
302
978
  * ```
303
979
  */
304
- function collectFiles(dir, prefix, depth, results) {
980
+ async function collectFiles(dir, prefix, depth, results) {
305
981
  if (depth > 4 || results.length >= 500)
306
982
  return;
307
983
  const skip = new Set([
@@ -316,6 +992,7 @@ function collectFiles(dir, prefix, depth, results) {
316
992
  ]);
317
993
  let entries;
318
994
  try {
995
+ const fs = await lazyFs();
319
996
  entries = fs.readdirSync(dir, { withFileTypes: true });
320
997
  }
321
998
  catch {
@@ -334,7 +1011,7 @@ function collectFiles(dir, prefix, depth, results) {
334
1011
  type: isDir ? "folder" : "file",
335
1012
  });
336
1013
  if (isDir)
337
- collectFiles(nodePath.join(dir, entry.name), relPath, depth + 1, results);
1014
+ await collectFiles(nodePath.join(dir, entry.name), relPath, depth + 1, results);
338
1015
  }
339
1016
  }
340
1017
  function parseSkillFrontmatter(content) {
@@ -358,28 +1035,229 @@ function isLocalhost(event) {
358
1035
  }
359
1036
  export function createAgentChatPlugin(options) {
360
1037
  return async (nitroApp) => {
1038
+ // Wait for default framework plugins (auth, core-routes, integrations, ...)
1039
+ // to finish mounting their middleware before we register our own. Without
1040
+ // this, requests can race ahead of the bootstrap and hit the SSR catch-all.
1041
+ const { awaitBootstrap } = await import("./framework-request-handler.js");
1042
+ await awaitBootstrap(nitroApp);
361
1043
  const env = process.env.NODE_ENV;
362
1044
  // AGENT_MODE=production forces production agent constraints even in dev
363
1045
  const canToggle = (env === "development" || env === "test") &&
364
1046
  process.env.AGENT_MODE !== "production";
365
1047
  const routePath = options?.path ?? "/_agent-native/agent-chat";
1048
+ // Initialize MCP client (connects to user-configured local MCP servers).
1049
+ // Graceful-degrade: any failure yields zero MCP tools and agent-chat keeps
1050
+ // working as before. No-op outside Node runtimes.
1051
+ let mcpConfig = loadMcpConfig();
1052
+ if (!mcpConfig) {
1053
+ mcpConfig = autoDetectMcpConfig();
1054
+ if (mcpConfig) {
1055
+ const detected = Object.keys(mcpConfig.servers).join(", ");
1056
+ console.log(`[mcp-client] auto-detected ${detected}, registering as MCP server — set AGENT_NATIVE_DISABLE_MCP_AUTODETECT=1 to opt out`);
1057
+ }
1058
+ else {
1059
+ console.log("[mcp-client] no mcp.config.json and no auto-detectable servers — skipping MCP tools");
1060
+ }
1061
+ }
1062
+ else if (mcpConfig.source) {
1063
+ console.log(`[mcp-client] loaded config from ${mcpConfig.source} (${Object.keys(mcpConfig.servers).length} server(s))`);
1064
+ }
1065
+ const mcpManager = new McpClientManager(mcpConfig);
1066
+ try {
1067
+ await mcpManager.start();
1068
+ }
1069
+ catch (err) {
1070
+ console.warn(`[mcp-client] start() failed: ${err?.message ?? err}. Continuing without MCP tools.`);
1071
+ }
1072
+ setGlobalMcpManager(mcpManager);
1073
+ const mcpActionEntries = mcpToolsToActionEntries(mcpManager);
1074
+ // Mount status route so tooling/onboarding can inspect MCP state.
1075
+ mountMcpStatusRoute(nitroApp, mcpManager);
1076
+ // Ensure we tear down child processes if the host shuts down cleanly.
1077
+ if (typeof process !== "undefined" &&
1078
+ typeof process.once === "function" &&
1079
+ !globalThis.__agentNativeMcpExitHooked) {
1080
+ globalThis.__agentNativeMcpExitHooked = true;
1081
+ const stop = () => {
1082
+ const mgr = getGlobalMcpManager();
1083
+ if (mgr)
1084
+ void mgr.stop();
1085
+ };
1086
+ process.once("exit", stop);
1087
+ process.once("SIGTERM", stop);
1088
+ process.once("SIGINT", stop);
1089
+ }
366
1090
  // Resolve actions — prefer `actions`, fall back to deprecated `scripts`
367
1091
  const rawActions = options?.actions ?? options?.scripts;
368
1092
  const templateScripts = typeof rawActions === "function"
369
1093
  ? await rawActions()
370
1094
  : (rawActions ?? {});
371
- // Resource and cross-agent scripts are available in both prod and dev modes
1095
+ // Resource, chat, docs, and cross-agent scripts are available in both prod and dev modes
372
1096
  const resourceScripts = await createResourceScriptEntries();
373
- const callAgentScript = await createCallAgentScriptEntry();
1097
+ const docsScripts = await createDocsScriptEntries();
1098
+ const engineScripts = await createAgentEngineScriptEntries();
1099
+ const chatScripts = {
1100
+ ...(await createChatScriptEntries()),
1101
+ ...engineScripts,
1102
+ };
1103
+ const callAgentScript = await createCallAgentScriptEntry(options?.appId);
1104
+ let _currentRequestOrigin = "http://localhost:3000";
1105
+ const browserTools = createBuilderBrowserTool({
1106
+ getOrigin: () => _currentRequestOrigin,
1107
+ });
374
1108
  // Auto-mount A2A protocol endpoints so every app is discoverable
375
1109
  // and callable by other agents via the standard protocol.
376
- // The custom handler calls the local agent-chat endpoint to process
377
- // A2A messages using the same production agent pipeline.
378
- const allScripts = {
379
- ...templateScripts,
380
- ...resourceScripts,
381
- ...callAgentScript,
382
- };
1110
+ // In dev mode, include dev scripts (filesystem-discovered) so the A2A agent
1111
+ // has access to the same tools as the interactive agent.
1112
+ let devScriptsForA2A = {};
1113
+ let discoveredActions = {};
1114
+ if (canToggle) {
1115
+ try {
1116
+ const { createDevScriptRegistry } = await import("../scripts/dev/index.js");
1117
+ devScriptsForA2A = await createDevScriptRegistry();
1118
+ }
1119
+ catch { }
1120
+ // Auto-discover template action files and register as shell-based tools.
1121
+ // This ensures templates without a custom agent-chat plugin (e.g., analytics)
1122
+ // still have their domain actions available as tools.
1123
+ try {
1124
+ const fs = await import("fs");
1125
+ const pathMod = await import("path");
1126
+ const cwd = process.cwd();
1127
+ const skipFiles = new Set([
1128
+ "helpers",
1129
+ "run",
1130
+ "registry",
1131
+ "_utils",
1132
+ "db-connect",
1133
+ "db-status",
1134
+ ]);
1135
+ for (const dir of ["actions", "scripts"]) {
1136
+ const actionsDir = pathMod.join(cwd, dir);
1137
+ const _fs = await lazyFs();
1138
+ if (!_fs.existsSync(actionsDir))
1139
+ continue;
1140
+ const files = _fs
1141
+ .readdirSync(actionsDir)
1142
+ .filter((f) => f.endsWith(".ts") &&
1143
+ !f.startsWith("_") &&
1144
+ !skipFiles.has(f.replace(/\.ts$/, "")));
1145
+ for (const file of files) {
1146
+ const name = file.replace(/\.ts$/, "");
1147
+ if (templateScripts[name] || devScriptsForA2A[name])
1148
+ continue;
1149
+ // Try to load the action module directly so we get the real
1150
+ // run function (not a shell wrapper). This makes HTTP endpoints
1151
+ // work correctly. Only fall back to shell wrapper if the import
1152
+ // fails (e.g., CLI-style scripts that throw at top level).
1153
+ const filePath = pathMod.join(actionsDir, file);
1154
+ try {
1155
+ const mod = await import(/* @vite-ignore */ filePath);
1156
+ const def = mod.default && typeof mod.default === "object"
1157
+ ? mod.default
1158
+ : mod;
1159
+ if (def?.tool && typeof def.run === "function") {
1160
+ discoveredActions[name] = {
1161
+ tool: def.tool,
1162
+ run: def.run,
1163
+ ...(def.http !== undefined ? { http: def.http } : {}),
1164
+ };
1165
+ continue;
1166
+ }
1167
+ }
1168
+ catch {
1169
+ // Fall through to shell wrapper for CLI-style scripts
1170
+ // (and .ts files Node can't parse natively).
1171
+ }
1172
+ // Static-parse the source for `http: false` or
1173
+ // `http: { method: "GET" }` so the shell-wrapper fallback still
1174
+ // mounts HTTP routes with the correct method. We can't load the
1175
+ // .ts module to read the real defineAction object in this Node
1176
+ // context, so this regex sniff is the best we can do until the
1177
+ // discovery is moved into a Vite-aware codepath.
1178
+ let httpConfig;
1179
+ try {
1180
+ const src = _fs.readFileSync(filePath, "utf-8");
1181
+ if (/\bhttp\s*:\s*false\b/.test(src)) {
1182
+ httpConfig = false;
1183
+ }
1184
+ else {
1185
+ const httpStart = src.search(/\bhttp\s*:\s*\{/);
1186
+ if (httpStart >= 0) {
1187
+ const window = src.slice(httpStart, httpStart + 200);
1188
+ const m = window.match(/method\s*:\s*['"`](GET|POST|PUT|DELETE)['"`]/);
1189
+ const p = window.match(/path\s*:\s*['"`]([^'"`]+)['"`]/);
1190
+ if (m || p) {
1191
+ httpConfig = {
1192
+ ...(m
1193
+ ? {
1194
+ method: m[1],
1195
+ }
1196
+ : {}),
1197
+ ...(p ? { path: p[1] } : {}),
1198
+ };
1199
+ }
1200
+ }
1201
+ }
1202
+ }
1203
+ catch {
1204
+ // File read failed — leave httpConfig undefined (default POST)
1205
+ }
1206
+ // Fallback: shell-based wrapper for CLI-style scripts
1207
+ discoveredActions[name] = {
1208
+ tool: {
1209
+ description: `Run the ${name} action. Use: pnpm action ${name} --arg=value`,
1210
+ parameters: {
1211
+ type: "object",
1212
+ properties: {
1213
+ args: {
1214
+ type: "string",
1215
+ description: "CLI arguments as a string (e.g., --metrics=sessions --days=7)",
1216
+ },
1217
+ },
1218
+ },
1219
+ },
1220
+ run: async (input) => {
1221
+ const shellEntry = devScriptsForA2A["shell"];
1222
+ if (!shellEntry)
1223
+ return "Error: shell not available";
1224
+ return shellEntry.run({
1225
+ command: `pnpm action ${name} ${input.args || ""}`.trim(),
1226
+ });
1227
+ },
1228
+ ...(httpConfig !== undefined ? { http: httpConfig } : {}),
1229
+ };
1230
+ }
1231
+ }
1232
+ if (Object.keys(discoveredActions).length > 0 && process.env.DEBUG)
1233
+ console.log(`[agent-chat] Auto-discovered ${Object.keys(discoveredActions).length} action(s): ${Object.keys(discoveredActions).join(", ")}`);
1234
+ }
1235
+ catch { }
1236
+ }
1237
+ // In dev mode, template actions (templateScripts and discoveredActions) are
1238
+ // NOT registered as native tools — the agent invokes them via shell instead.
1239
+ // This avoids degenerate empty-object tool calls that Anthropic models
1240
+ // sometimes emit for actions with complex schemas. Production keeps the
1241
+ // native registration since it has no shell access.
1242
+ const allScripts = canToggle
1243
+ ? {
1244
+ ...resourceScripts,
1245
+ ...docsScripts,
1246
+ ...chatScripts,
1247
+ ...callAgentScript,
1248
+ ...browserTools,
1249
+ ...devScriptsForA2A,
1250
+ }
1251
+ : {
1252
+ ...discoveredActions,
1253
+ ...templateScripts,
1254
+ ...resourceScripts,
1255
+ ...docsScripts,
1256
+ ...chatScripts,
1257
+ ...callAgentScript,
1258
+ ...browserTools,
1259
+ ...devScriptsForA2A,
1260
+ };
383
1261
  const { mountA2A } = await import("../a2a/server.js");
384
1262
  mountA2A(nitroApp, {
385
1263
  name: options?.appId
@@ -394,12 +1272,9 @@ export function createAgentChatPlugin(options) {
394
1272
  streaming: true,
395
1273
  handler: async function* (message, context) {
396
1274
  // Resolve the caller's identity for user-scoped data access.
397
- // Dev: use most recent session from local DB (single user, no verification).
398
- // Prod: verify Google OAuth token from caller, check email domain.
399
1275
  const isDev = process.env.NODE_ENV !== "production";
400
1276
  let userEmail;
401
1277
  if (isDev) {
402
- // Dev mode: trust the caller's claimed email, or auto-detect from local sessions
403
1278
  userEmail = context.metadata?.userEmail || undefined;
404
1279
  if (!userEmail) {
405
1280
  try {
@@ -416,7 +1291,6 @@ export function createAgentChatPlugin(options) {
416
1291
  }
417
1292
  }
418
1293
  else {
419
- // Prod mode: verify identity via Google OAuth token
420
1294
  const googleToken = context.metadata?.googleToken;
421
1295
  if (googleToken) {
422
1296
  try {
@@ -447,109 +1321,162 @@ export function createAgentChatPlugin(options) {
447
1321
  };
448
1322
  return;
449
1323
  }
450
- const Anthropic = (await import("@anthropic-ai/sdk")).default;
451
- const apiKey = options?.apiKey ?? process.env.ANTHROPIC_API_KEY;
452
- if (!apiKey) {
453
- yield {
454
- role: "agent",
455
- parts: [
456
- {
457
- type: "text",
458
- text: "Anthropic API key is not configured. Set ANTHROPIC_API_KEY in .env.",
459
- },
460
- ],
461
- };
462
- return;
463
- }
464
- const client = new Anthropic({ apiKey });
465
- const model = options?.model ?? "claude-sonnet-4-6";
466
- // Load shared AGENTS.md resource so the agent knows how to use its tools
1324
+ // Use the SAME agent setup as the interactive chat — identical tools,
1325
+ // prompt, and capabilities. The A2A agent IS the app's agent.
1326
+ const a2aEngine = await resolveEngine({
1327
+ engineOption: options?.engine,
1328
+ apiKey: options?.apiKey,
1329
+ });
1330
+ // Use the same handler (dev or prod) that the interactive chat uses
1331
+ const handler = canToggle && devHandler ? devHandler : prodHandler;
1332
+ // Build the same system prompt the interactive agent uses
467
1333
  const owner = userEmail || "local@localhost";
468
1334
  const resources = await loadResourcesForPrompt(owner);
469
- const a2aSystemPrompt = `You are the ${options?.appId ?? "app"} agent responding to a request from another agent. Be concise and helpful. Use your tools to look up data or take actions as needed. Do not ask for clarification — use your tools to find the answer.` +
470
- resources;
471
- const tools = Object.entries(templateScripts).map(([name, entry]) => ({
472
- name,
473
- description: entry.tool.description,
474
- input_schema: entry.tool.parameters ?? {
475
- type: "object",
476
- properties: {},
477
- },
478
- }));
479
- const msgs = [{ role: "user", content: text }];
1335
+ const schemaBlock = await buildSchemaBlock(owner, canToggle);
1336
+ const systemPrompt = canToggle
1337
+ ? devPrompt + resources + schemaBlock
1338
+ : basePrompt + resources + schemaBlock;
1339
+ const model = options?.model ??
1340
+ (canToggle ? "claude-sonnet-4-6" : "claude-haiku-4-5-20251001");
1341
+ // Build tools — same as interactive handler but WITHOUT call-agent
1342
+ // to prevent infinite recursive A2A loops (agent calling itself).
1343
+ // In dev mode, template actions are invoked via shell (not native tools),
1344
+ // so they're omitted from the tool registry — see allScripts comment.
1345
+ const a2aActions = canToggle
1346
+ ? {
1347
+ ...resourceScripts,
1348
+ ...docsScripts,
1349
+ ...chatScripts,
1350
+ ...browserTools,
1351
+ ...devScriptsForA2A,
1352
+ }
1353
+ : {
1354
+ ...templateScripts,
1355
+ ...resourceScripts,
1356
+ ...docsScripts,
1357
+ ...chatScripts,
1358
+ ...browserTools,
1359
+ };
1360
+ const a2aTools = actionsToEngineTools(a2aActions);
1361
+ const a2aMessages = [
1362
+ { role: "user", content: [{ type: "text", text }] },
1363
+ ];
1364
+ // Run the SAME agent loop, collect text events, yield as A2A messages
480
1365
  let accumulatedText = "";
481
- for (let i = 0; i < 10; i++) {
482
- // Stream the Anthropic response so we can yield text chunks
483
- const apiStream = client.messages.stream({
484
- model,
485
- max_tokens: 4096,
486
- system: a2aSystemPrompt,
487
- tools: tools.length > 0 ? tools : undefined,
488
- messages: msgs,
489
- });
490
- // Yield text deltas as they arrive
491
- for await (const event of apiStream) {
492
- if (event.type === "content_block_delta" &&
493
- event.delta?.type === "text_delta") {
494
- accumulatedText += event.delta.text;
495
- yield {
496
- role: "agent",
497
- parts: [{ type: "text", text: accumulatedText }],
498
- };
1366
+ const controller = new AbortController();
1367
+ console.log(`[A2A] Starting agent loop: ${a2aTools.length} tools, prompt ${systemPrompt.length} chars`);
1368
+ await runAgentLoop({
1369
+ engine: a2aEngine,
1370
+ model,
1371
+ systemPrompt,
1372
+ tools: a2aTools,
1373
+ messages: a2aMessages,
1374
+ actions: a2aActions,
1375
+ send: (event) => {
1376
+ if (event.type === "text") {
1377
+ accumulatedText += event.text;
499
1378
  }
500
- }
501
- // Get the complete message for tool_use detection
502
- const finalMessage = await apiStream.finalMessage();
503
- const toolUseBlocks = finalMessage.content.filter((b) => b.type === "tool_use");
504
- if (toolUseBlocks.length === 0 ||
505
- finalMessage.stop_reason !== "tool_use") {
506
- break;
507
- }
508
- // Execute tools and continue the loop
509
- msgs.push({ role: "assistant", content: finalMessage.content });
510
- const toolResults = [];
511
- for (const tb of toolUseBlocks) {
512
- const script = allScripts[tb.name];
513
- let result = `Unknown tool: ${tb.name}`;
514
- if (script) {
515
- try {
516
- result = await script.run(tb.input);
517
- }
518
- catch (err) {
519
- result = `Error: ${err?.message}`;
520
- }
1379
+ else if (event.type === "tool_start") {
1380
+ console.log(`[A2A] Tool call: ${event.tool}`);
521
1381
  }
522
- toolResults.push({
523
- type: "tool_result",
524
- tool_use_id: tb.id,
525
- content: result,
526
- });
527
- }
528
- msgs.push({ role: "user", content: toolResults });
529
- }
530
- // Final yield if nothing was yielded yet
531
- if (!accumulatedText) {
532
- yield {
533
- role: "agent",
534
- parts: [{ type: "text", text: "(no response)" }],
535
- };
536
- }
1382
+ else if (event.type === "error") {
1383
+ console.error(`[A2A] Error: ${event.error}`);
1384
+ }
1385
+ else if (event.type === "done") {
1386
+ console.log(`[A2A] Done. Response: ${accumulatedText.length} chars`);
1387
+ }
1388
+ },
1389
+ signal: controller.signal,
1390
+ });
1391
+ console.log(`[A2A] Loop complete. Text: ${accumulatedText.slice(0, 100)}...`);
1392
+ // Yield the final accumulated text
1393
+ yield {
1394
+ role: "agent",
1395
+ parts: [
1396
+ {
1397
+ type: "text",
1398
+ text: accumulatedText || "(no response)",
1399
+ },
1400
+ ],
1401
+ };
537
1402
  },
538
1403
  });
539
1404
  // Generate an "Available Actions" section from template-specific actions
540
- // so the agent knows to use them instead of raw SQL
541
- const actionsPrompt = generateActionsPrompt(templateScripts);
1405
+ // so the agent knows to use them instead of raw SQL.
1406
+ //
1407
+ // Production: actions are native tools — emit `name(arg*: type) — desc`
1408
+ // Dev: actions are invoked via shell — emit `pnpm action name --arg <type>`
1409
+ // and include discoveredActions too, since those are also missing
1410
+ // from the dev tool registry.
1411
+ const prodActionsPrompt = generateActionsPrompt(templateScripts, "tool");
1412
+ const devActionsPrompt = generateActionsPrompt({ ...discoveredActions, ...templateScripts }, "cli");
542
1413
  // Build system prompts — dynamic functions that pre-load resources per-request.
543
1414
  // Production gets PROD_FRAMEWORK_PROMPT, dev gets DEV_FRAMEWORK_PROMPT.
544
1415
  // Custom systemPrompt from options overrides the framework default entirely.
545
- const prodPrompt = (options?.systemPrompt ?? PROD_FRAMEWORK_PROMPT) + actionsPrompt;
1416
+ const prodPrompt = (options?.systemPrompt ?? PROD_FRAMEWORK_PROMPT) + prodActionsPrompt;
546
1417
  const devPrompt = (options?.devSystemPrompt
547
1418
  ? options.devSystemPrompt +
548
1419
  (options?.systemPrompt ?? PROD_FRAMEWORK_PROMPT)
549
- : DEV_FRAMEWORK_PROMPT) + actionsPrompt;
1420
+ : DEV_FRAMEWORK_PROMPT) + devActionsPrompt;
550
1421
  // Keep legacy names for the composition below
551
1422
  const basePrompt = prodPrompt;
552
1423
  const devPrefix = options?.devSystemPrompt ?? DEFAULT_DEV_PROMPT;
1424
+ // Mount MCP remote server — same action registry as A2A + agent chat
1425
+ const { mountMCP } = await import("../mcp/server.js");
1426
+ mountMCP(nitroApp, {
1427
+ name: options?.appId
1428
+ ? options.appId.charAt(0).toUpperCase() + options.appId.slice(1)
1429
+ : "Agent",
1430
+ description: `Agent-native ${options?.appId ?? "app"} agent`,
1431
+ actions: allScripts,
1432
+ askAgent: async (message) => {
1433
+ const mcpEngine = await resolveEngine({
1434
+ engineOption: options?.engine,
1435
+ apiKey: options?.apiKey,
1436
+ });
1437
+ const model = options?.model ??
1438
+ (canToggle ? "claude-sonnet-4-6" : "claude-haiku-4-5-20251001");
1439
+ // Same actions as A2A — without call-agent to prevent loops.
1440
+ // In dev mode, template actions go through shell, not native tools.
1441
+ const mcpActions = canToggle
1442
+ ? {
1443
+ ...resourceScripts,
1444
+ ...docsScripts,
1445
+ ...chatScripts,
1446
+ ...devScriptsForA2A,
1447
+ }
1448
+ : {
1449
+ ...templateScripts,
1450
+ ...resourceScripts,
1451
+ ...docsScripts,
1452
+ ...chatScripts,
1453
+ };
1454
+ const mcpTools = actionsToEngineTools(mcpActions);
1455
+ const resources = await loadResourcesForPrompt("local@localhost");
1456
+ const schemaBlock = await buildSchemaBlock("local@localhost", canToggle);
1457
+ const systemPrompt = canToggle
1458
+ ? devPrompt + resources + schemaBlock
1459
+ : basePrompt + resources + schemaBlock;
1460
+ let accumulatedText = "";
1461
+ const controller = new AbortController();
1462
+ await runAgentLoop({
1463
+ engine: mcpEngine,
1464
+ model,
1465
+ systemPrompt,
1466
+ tools: mcpTools,
1467
+ messages: [
1468
+ { role: "user", content: [{ type: "text", text: message }] },
1469
+ ],
1470
+ actions: mcpActions,
1471
+ send: (event) => {
1472
+ if (event.type === "text")
1473
+ accumulatedText += event.text;
1474
+ },
1475
+ signal: controller.signal,
1476
+ });
1477
+ return accumulatedText || "(no response)";
1478
+ },
1479
+ });
553
1480
  // Resolve owner from the H3 event's session — matches how resources are created
554
1481
  const getOwnerFromEvent = async (event) => {
555
1482
  try {
@@ -560,6 +1487,20 @@ export function createAgentChatPlugin(options) {
560
1487
  return "local@localhost";
561
1488
  }
562
1489
  };
1490
+ // Auto-mount template actions as HTTP endpoints under /_agent-native/actions/
1491
+ // Include engine management scripts so the UI can call list/set/test-agent-engine.
1492
+ const httpActions = {
1493
+ ...discoveredActions,
1494
+ ...templateScripts,
1495
+ ...engineScripts,
1496
+ };
1497
+ if (Object.keys(httpActions).length > 0) {
1498
+ const { mountActionRoutes } = await import("./action-routes.js");
1499
+ mountActionRoutes(nitroApp, httpActions, {
1500
+ getOwnerFromEvent,
1501
+ resolveOrgId: options?.resolveOrgId,
1502
+ });
1503
+ }
563
1504
  // Callback to persist agent response when run finishes (even if client disconnected).
564
1505
  // Reconstructs the assistant message from buffered events and appends to thread_data.
565
1506
  const onRunComplete = async (run, threadId) => {
@@ -588,12 +1529,24 @@ export function createAgentChatPlugin(options) {
588
1529
  if (!Array.isArray(repo.messages))
589
1530
  repo.messages = [];
590
1531
  const lastMsg = repo.messages[repo.messages.length - 1];
591
- if (lastMsg?.role === "assistant") {
1532
+ // Check both wrapped ({ message: { role } }) and unwrapped ({ role }) formats
1533
+ const lastRole = lastMsg?.message?.role ?? lastMsg?.role;
1534
+ if (lastRole === "assistant") {
592
1535
  // Frontend already saved the assistant response — just bump timestamp
593
1536
  await updateThreadData(threadId, thread.threadData, thread.title, thread.preview, thread.messageCount);
594
1537
  return;
595
1538
  }
596
- repo.messages.push(assistantMsg);
1539
+ // Determine if repo uses wrapped format ({ message, parentId }) or flat format
1540
+ const isWrapped = lastMsg && "message" in lastMsg;
1541
+ if (isWrapped) {
1542
+ const parentId = repo.messages.length > 0
1543
+ ? (repo.messages[repo.messages.length - 1].message?.id ?? null)
1544
+ : null;
1545
+ repo.messages.push({ message: assistantMsg, parentId });
1546
+ }
1547
+ else {
1548
+ repo.messages.push(assistantMsg);
1549
+ }
597
1550
  const meta = extractThreadMeta(repo);
598
1551
  await updateThreadData(threadId, JSON.stringify(repo), meta.title || thread.title, meta.preview || thread.preview, repo.messages.length);
599
1552
  }
@@ -601,38 +1554,138 @@ export function createAgentChatPlugin(options) {
601
1554
  // Best-effort — don't break cleanup
602
1555
  }
603
1556
  };
604
- // Always build the production handler (includes resource tools + call-agent)
1557
+ // ─── Agent Teams: per-run send reference ─────────────────────────
1558
+ // Team tools need to emit events to the parent chat's SSE stream.
1559
+ // Each run gets its own send function, keyed by threadId so concurrent
1560
+ // requests for different threads don't clobber each other.
1561
+ const _runSendByThread = new Map();
1562
+ let _currentRunOwner = "local@localhost";
1563
+ let _currentRunThreadId = "";
1564
+ let _currentRunSystemPrompt = basePrompt;
1565
+ // Default to Haiku in production mode to manage costs for hosted apps
1566
+ const resolvedModel = options?.model ??
1567
+ (canToggle ? "claude-sonnet-4-6" : "claude-haiku-4-5-20251001");
1568
+ const teamTools = createTeamTools({
1569
+ getOwner: () => _currentRunOwner,
1570
+ getSystemPrompt: () => _currentRunSystemPrompt,
1571
+ getActions: () => canToggle
1572
+ ? {
1573
+ // Sub-agents spawned in dev mode also invoke template actions
1574
+ // via shell, so omit them from the native tool registry.
1575
+ ...resourceScripts,
1576
+ ...docsScripts,
1577
+ ...chatScripts,
1578
+ ...devScriptsForA2A,
1579
+ }
1580
+ : {
1581
+ ...templateScripts,
1582
+ ...resourceScripts,
1583
+ ...docsScripts,
1584
+ ...chatScripts,
1585
+ },
1586
+ getEngine: () => createAnthropicEngine({
1587
+ apiKey: options?.apiKey ?? process.env.ANTHROPIC_API_KEY,
1588
+ }),
1589
+ getModel: () => resolvedModel,
1590
+ getParentThreadId: () => _currentRunThreadId,
1591
+ getSend: () => {
1592
+ // Return the send for the current run's thread
1593
+ const send = _runSendByThread.get(_currentRunThreadId);
1594
+ return send ?? null;
1595
+ },
1596
+ });
1597
+ // Hook into the run lifecycle to set/clear the send reference.
1598
+ // Job management tools (create-job, list-jobs, update-job)
1599
+ let jobTools = {};
1600
+ try {
1601
+ const { createJobTools } = await import("../jobs/tools.js");
1602
+ jobTools = createJobTools();
1603
+ }
1604
+ catch { }
1605
+ const prodActions = {
1606
+ ...templateScripts,
1607
+ ...resourceScripts,
1608
+ ...docsScripts,
1609
+ ...chatScripts,
1610
+ ...callAgentScript,
1611
+ ...teamTools,
1612
+ ...jobTools,
1613
+ ...browserTools,
1614
+ ...mcpActionEntries,
1615
+ };
1616
+ // Always build the production handler (includes resource tools + call-agent + team tools)
1617
+ // In production mode (!canToggle), enable usage tracking and limits
1618
+ const isHostedProd = !canToggle;
605
1619
  const prodHandler = createProductionAgentHandler({
606
- actions: { ...templateScripts, ...resourceScripts, ...callAgentScript },
1620
+ actions: prodActions,
607
1621
  systemPrompt: async (event) => {
1622
+ _currentRequestOrigin = getOrigin(event);
608
1623
  const owner = await getOwnerFromEvent(event);
1624
+ _currentRunOwner = owner;
609
1625
  const resources = await loadResourcesForPrompt(owner);
610
- return basePrompt + resources;
1626
+ const schemaBlock = await buildSchemaBlock(owner, false);
1627
+ _currentRunSystemPrompt = basePrompt + resources + schemaBlock;
1628
+ return _currentRunSystemPrompt;
611
1629
  },
612
- model: options?.model,
1630
+ model: options?.model ??
1631
+ (isHostedProd ? "claude-haiku-4-5-20251001" : undefined),
613
1632
  apiKey: options?.apiKey,
614
- onRunComplete,
1633
+ onRunStart: (send, threadId) => {
1634
+ _runSendByThread.set(threadId, send);
1635
+ _currentRunThreadId = threadId;
1636
+ },
1637
+ onRunComplete: async (run, threadId) => {
1638
+ if (threadId)
1639
+ _runSendByThread.delete(threadId);
1640
+ await onRunComplete(run, threadId);
1641
+ },
1642
+ // Usage tracking for hosted production deployments
1643
+ trackUsage: isHostedProd,
1644
+ resolveOwnerEmail: isHostedProd ? getOwnerFromEvent : undefined,
615
1645
  });
616
1646
  // Build the dev handler (with filesystem/shell/db tools) if environment allows toggling
617
1647
  let devHandler = null;
618
1648
  if (canToggle) {
619
1649
  const { createDevScriptRegistry } = await import("../scripts/dev/index.js");
1650
+ // Dev mode: template actions (templateScripts and discoveredActions) are
1651
+ // intentionally OMITTED from the native tool registry. The agent invokes
1652
+ // them via `shell(command="pnpm action <name> ...")` instead. This mirrors
1653
+ // how Claude Code works locally and dramatically reduces the rate of
1654
+ // degenerate empty-object tool calls. The CLI syntax for each action is
1655
+ // listed in the dev system prompt's "Available Actions" section.
620
1656
  const devActions = {
621
- ...templateScripts,
622
1657
  ...resourceScripts,
1658
+ ...docsScripts,
1659
+ ...chatScripts,
623
1660
  ...callAgentScript,
1661
+ ...teamTools,
1662
+ ...jobTools,
1663
+ ...browserTools,
1664
+ ...mcpActionEntries,
624
1665
  ...(await createDevScriptRegistry()),
625
1666
  };
626
1667
  devHandler = createProductionAgentHandler({
627
1668
  actions: devActions,
628
1669
  systemPrompt: async (event) => {
1670
+ _currentRequestOrigin = getOrigin(event);
629
1671
  const owner = await getOwnerFromEvent(event);
1672
+ _currentRunOwner = owner;
630
1673
  const resources = await loadResourcesForPrompt(owner);
631
- return devPrompt + resources;
1674
+ const schemaBlock = await buildSchemaBlock(owner, true);
1675
+ _currentRunSystemPrompt = devPrompt + resources + schemaBlock;
1676
+ return _currentRunSystemPrompt;
632
1677
  },
633
1678
  model: options?.model,
634
1679
  apiKey: options?.apiKey,
635
- onRunComplete,
1680
+ onRunStart: (send, threadId) => {
1681
+ _runSendByThread.set(threadId, send);
1682
+ _currentRunThreadId = threadId;
1683
+ },
1684
+ onRunComplete: async (run, threadId) => {
1685
+ if (threadId)
1686
+ _runSendByThread.delete(threadId);
1687
+ await onRunComplete(run, threadId);
1688
+ },
636
1689
  });
637
1690
  }
638
1691
  // Resolve mention providers
@@ -643,7 +1696,7 @@ export function createAgentChatPlugin(options) {
643
1696
  // Mutable mode flag — starts in dev if environment allows
644
1697
  let currentDevMode = canToggle;
645
1698
  // Mount mode endpoint — GET returns current mode, POST toggles it (localhost only)
646
- nitroApp.h3App.use(`${routePath}/mode`, defineEventHandler(async (event) => {
1699
+ getH3App(nitroApp).use(`${routePath}/mode`, defineEventHandler(async (event) => {
647
1700
  if (getMethod(event) === "POST") {
648
1701
  if (!canToggle) {
649
1702
  setResponseStatus(event, 403);
@@ -666,7 +1719,7 @@ export function createAgentChatPlugin(options) {
666
1719
  }));
667
1720
  // Mount save-key BEFORE the prefix handler so it isn't shadowed
668
1721
  // Only functional in Node.js environments (writes to .env file)
669
- nitroApp.h3App.use(`${routePath}/save-key`, defineEventHandler(async (event) => {
1722
+ getH3App(nitroApp).use(`${routePath}/save-key`, defineEventHandler(async (event) => {
670
1723
  if (getMethod(event) !== "POST") {
671
1724
  setResponseStatus(event, 405);
672
1725
  return { error: "Method not allowed" };
@@ -682,7 +1735,7 @@ export function createAgentChatPlugin(options) {
682
1735
  const path = await import("path");
683
1736
  const { upsertEnvFile } = await import("./create-server.js");
684
1737
  const envPath = path.join(process.cwd(), ".env");
685
- upsertEnvFile(envPath, [
1738
+ await upsertEnvFile(envPath, [
686
1739
  { key: "ANTHROPIC_API_KEY", value: trimmedKey },
687
1740
  ]);
688
1741
  }
@@ -694,7 +1747,7 @@ export function createAgentChatPlugin(options) {
694
1747
  return { ok: true };
695
1748
  }));
696
1749
  // Mount file search endpoint
697
- nitroApp.h3App.use(`${routePath}/files`, defineEventHandler(async (event) => {
1750
+ getH3App(nitroApp).use(`${routePath}/files`, defineEventHandler(async (event) => {
698
1751
  if (getMethod(event) !== "GET") {
699
1752
  setResponseStatus(event, 405);
700
1753
  return { error: "Method not allowed" };
@@ -707,7 +1760,7 @@ export function createAgentChatPlugin(options) {
707
1760
  if (currentDevMode) {
708
1761
  const codebaseFiles = [];
709
1762
  try {
710
- collectFiles(process.cwd(), "", 0, codebaseFiles);
1763
+ await collectFiles(process.cwd(), "", 0, codebaseFiles);
711
1764
  }
712
1765
  catch {
713
1766
  // Filesystem access failed — skip
@@ -751,7 +1804,7 @@ export function createAgentChatPlugin(options) {
751
1804
  return { files: filtered.slice(0, 30) };
752
1805
  }));
753
1806
  // Mount skills listing endpoint
754
- nitroApp.h3App.use(`${routePath}/skills`, defineEventHandler(async (event) => {
1807
+ getH3App(nitroApp).use(`${routePath}/skills`, defineEventHandler(async (event) => {
755
1808
  if (getMethod(event) !== "GET") {
756
1809
  setResponseStatus(event, 405);
757
1810
  return { error: "Method not allowed" };
@@ -761,8 +1814,9 @@ export function createAgentChatPlugin(options) {
761
1814
  // In dev mode, scan .agents/skills/ directory
762
1815
  if (currentDevMode) {
763
1816
  try {
1817
+ const _fs = await lazyFs();
764
1818
  const skillsDir = nodePath.join(process.cwd(), ".agents", "skills");
765
- const entries = fs.readdirSync(skillsDir, {
1819
+ const entries = _fs.readdirSync(skillsDir, {
766
1820
  withFileTypes: true,
767
1821
  });
768
1822
  for (const entry of entries) {
@@ -772,7 +1826,7 @@ export function createAgentChatPlugin(options) {
772
1826
  if (entry.isDirectory()) {
773
1827
  // Subdirectory layout: .agents/skills/<name>/SKILL.md
774
1828
  const candidate = nodePath.join(skillsDir, entry.name, "SKILL.md");
775
- if (!fs.existsSync(candidate))
1829
+ if (!_fs.existsSync(candidate))
776
1830
  continue;
777
1831
  skillFilePath = candidate;
778
1832
  skillRelPath = `.agents/skills/${entry.name}/SKILL.md`;
@@ -786,7 +1840,7 @@ export function createAgentChatPlugin(options) {
786
1840
  continue;
787
1841
  }
788
1842
  try {
789
- const content = fs.readFileSync(skillFilePath, "utf-8");
1843
+ const content = _fs.readFileSync(skillFilePath, "utf-8");
790
1844
  const fm = parseSkillFrontmatter(content);
791
1845
  const skillName = fm.name || entry.name.replace(/\.md$/, "");
792
1846
  if (!seenNames.has(skillName)) {
@@ -851,107 +1905,166 @@ export function createAgentChatPlugin(options) {
851
1905
  return result;
852
1906
  }));
853
1907
  // Mount unified mentions endpoint (files + resources + custom providers)
854
- nitroApp.h3App.use(`${routePath}/mentions`, defineEventHandler(async (event) => {
1908
+ getH3App(nitroApp).use(`${routePath}/mentions`, defineEventHandler(async (event) => {
855
1909
  if (getMethod(event) !== "GET") {
856
1910
  setResponseStatus(event, 405);
857
1911
  return { error: "Method not allowed" };
858
1912
  }
859
1913
  const query = getQuery(event);
860
1914
  const q = typeof query.q === "string" ? query.q.toLowerCase() : "";
861
- const items = [];
862
- // 1. Built-in: files from codebase (dev mode only)
863
- if (currentDevMode) {
864
- const codebaseFiles = [];
865
- try {
866
- collectFiles(process.cwd(), "", 0, codebaseFiles);
867
- }
868
- catch { }
869
- for (const f of codebaseFiles) {
870
- items.push({
871
- id: `codebase:${f.path}`,
872
- label: f.name,
873
- description: f.path !== f.name ? f.path : undefined,
874
- icon: f.type,
875
- source: "codebase",
876
- refType: "file",
877
- refPath: f.path,
878
- section: "Files",
879
- });
880
- }
881
- }
882
- // 2. Built-in: resources from SQL
883
- try {
884
- const resources = currentDevMode
885
- ? await resourceListAccessible("local@localhost")
886
- : await resourceList(SHARED_OWNER);
887
- for (const r of resources) {
888
- const isShared = r.owner === SHARED_OWNER;
889
- items.push({
890
- id: `resource:${r.path}`,
891
- label: r.path.split("/").pop() || r.path,
892
- description: r.path,
893
- icon: "file",
894
- source: isShared ? "resource:shared" : "resource:private",
895
- refType: "file",
896
- refPath: r.path,
897
- section: "Files",
898
- });
899
- }
900
- }
901
- catch { }
902
- // 3. Custom mention providers
903
- const providerResults = await Promise.all(Object.entries(mentionProviders).map(async ([key, provider]) => {
904
- try {
905
- const providerItems = await provider.search(q);
906
- return providerItems.map((item) => ({
907
- id: item.id,
908
- label: item.label,
909
- description: item.description,
910
- icon: item.icon || provider.icon || "file",
911
- source: key,
912
- refType: item.refType,
913
- refPath: item.refPath,
914
- refId: item.refId,
915
- section: provider.label,
916
- }));
917
- }
918
- catch {
919
- return [];
920
- }
921
- }));
922
- for (const batch of providerResults) {
923
- items.push(...batch);
924
- }
925
- // 4. Discovered peer agents
926
- try {
927
- const { discoverAgents } = await import("./agent-discovery.js");
928
- const agents = discoverAgents(options?.appId);
929
- for (const agent of agents) {
930
- items.push({
931
- id: `agent:${agent.id}`,
932
- label: agent.name,
933
- description: agent.description,
934
- icon: "agent",
935
- source: "agent",
936
- refType: "agent",
937
- refPath: agent.url,
938
- refId: agent.id,
939
- section: "Agents",
940
- });
941
- }
942
- }
943
- catch {
944
- // Agent discovery not available — skip
945
- }
946
- // Filter by query and limit
947
- const filtered = q
948
- ? items.filter((item) => item.label.toLowerCase().includes(q) ||
949
- (item.description?.toLowerCase().includes(q) ?? false))
950
- : items;
951
- return { items: filtered.slice(0, 30) };
1915
+ const matchesQuery = (item) => !q ||
1916
+ item.label.toLowerCase().includes(q) ||
1917
+ (item.description?.toLowerCase().includes(q) ?? false);
1918
+ const enc = new TextEncoder();
1919
+ // Stream NDJSON — each source flushes its batch as soon as it's ready.
1920
+ setResponseHeader(event, "Content-Type", "application/x-ndjson");
1921
+ setResponseHeader(event, "Cache-Control", "no-cache");
1922
+ const stream = new ReadableStream({
1923
+ async start(controller) {
1924
+ const MAX_RESULTS = 50;
1925
+ let totalSent = 0;
1926
+ let cancelled = false;
1927
+ const flush = (batch) => {
1928
+ if (cancelled)
1929
+ return;
1930
+ const filtered = batch.filter(matchesQuery);
1931
+ if (filtered.length === 0)
1932
+ return;
1933
+ const remaining = MAX_RESULTS - totalSent;
1934
+ const toSend = filtered.slice(0, remaining);
1935
+ if (toSend.length > 0) {
1936
+ totalSent += toSend.length;
1937
+ try {
1938
+ controller.enqueue(enc.encode(JSON.stringify({ items: toSend }) + "\n"));
1939
+ }
1940
+ catch {
1941
+ // Stream was closed by client
1942
+ cancelled = true;
1943
+ }
1944
+ }
1945
+ };
1946
+ // All sources run in parallel; each flushes independently.
1947
+ const sources = [];
1948
+ // 1. Resources from SQL (fast — flush first)
1949
+ sources.push((async () => {
1950
+ try {
1951
+ const resources = currentDevMode
1952
+ ? await resourceListAccessible("local@localhost")
1953
+ : await resourceList(SHARED_OWNER);
1954
+ flush(resources.map((r) => {
1955
+ const isShared = r.owner === SHARED_OWNER;
1956
+ return {
1957
+ id: `resource:${r.path}`,
1958
+ label: r.path.split("/").pop() || r.path,
1959
+ description: r.path,
1960
+ icon: "file",
1961
+ source: isShared
1962
+ ? "resource:shared"
1963
+ : "resource:private",
1964
+ refType: "file",
1965
+ refPath: r.path,
1966
+ section: "Files",
1967
+ };
1968
+ }));
1969
+ }
1970
+ catch { }
1971
+ })());
1972
+ // 2. Codebase files (dev mode only — can be slow on large repos)
1973
+ if (currentDevMode) {
1974
+ sources.push((async () => {
1975
+ const codebaseFiles = [];
1976
+ try {
1977
+ await collectFiles(process.cwd(), "", 0, codebaseFiles);
1978
+ }
1979
+ catch { }
1980
+ flush(codebaseFiles.map((f) => ({
1981
+ id: `codebase:${f.path}`,
1982
+ label: f.name,
1983
+ description: f.path !== f.name ? f.path : undefined,
1984
+ icon: f.type,
1985
+ source: "codebase",
1986
+ refType: "file",
1987
+ refPath: f.path,
1988
+ section: "Files",
1989
+ })));
1990
+ })());
1991
+ }
1992
+ // 3. Custom mention providers (each flushes independently)
1993
+ for (const [key, provider] of Object.entries(mentionProviders)) {
1994
+ sources.push((async () => {
1995
+ try {
1996
+ const providerItems = await provider.search(q, event);
1997
+ flush(providerItems.map((item) => ({
1998
+ id: item.id,
1999
+ label: item.label,
2000
+ description: item.description,
2001
+ icon: item.icon || provider.icon || "file",
2002
+ source: key,
2003
+ refType: item.refType,
2004
+ refPath: item.refPath,
2005
+ refId: item.refId,
2006
+ section: provider.label,
2007
+ })));
2008
+ }
2009
+ catch (e) {
2010
+ console.error(`[agent-native] Mention provider "${key}" failed:`, e);
2011
+ }
2012
+ })());
2013
+ }
2014
+ // 4. Custom workspace agents
2015
+ sources.push((async () => {
2016
+ try {
2017
+ const owner = await getOwnerFromEvent(event);
2018
+ const { listAccessibleCustomAgents } = await import("../resources/agents.js");
2019
+ const agents = await listAccessibleCustomAgents(owner);
2020
+ flush(agents.map((agent) => ({
2021
+ id: `custom-agent:${agent.id}`,
2022
+ label: agent.name,
2023
+ description: agent.description || agent.path,
2024
+ icon: "agent",
2025
+ source: "agent:custom",
2026
+ refType: "custom-agent",
2027
+ refPath: agent.path,
2028
+ refId: agent.id,
2029
+ section: "Agents",
2030
+ })));
2031
+ }
2032
+ catch (e) {
2033
+ console.error("[agent-native] Custom agent discovery failed:", e);
2034
+ }
2035
+ })());
2036
+ // 5. Peer agent discovery (network call — often slowest)
2037
+ sources.push((async () => {
2038
+ try {
2039
+ const agents = await discoverAgents(options?.appId);
2040
+ flush(agents.map((agent) => ({
2041
+ id: `agent:${agent.id}`,
2042
+ label: agent.name,
2043
+ description: agent.description,
2044
+ icon: "agent",
2045
+ source: "agent",
2046
+ refType: "agent",
2047
+ refPath: agent.url,
2048
+ refId: agent.id,
2049
+ section: "Connected Agents",
2050
+ })));
2051
+ }
2052
+ catch (e) {
2053
+ console.error("[agent-native] Agent discovery failed:", e);
2054
+ }
2055
+ })());
2056
+ await Promise.all(sources);
2057
+ if (!cancelled)
2058
+ controller.close();
2059
+ },
2060
+ cancel() {
2061
+ // Client disconnected — stop enqueuing
2062
+ },
2063
+ });
2064
+ return stream;
952
2065
  }));
953
2066
  // ─── Generate thread title ──────────────────────────────────────────
954
- nitroApp.h3App.use(`${routePath}/generate-title`, defineEventHandler(async (event) => {
2067
+ getH3App(nitroApp).use(`${routePath}/generate-title`, defineEventHandler(async (event) => {
955
2068
  if (getMethod(event) !== "POST") {
956
2069
  setResponseStatus(event, 405);
957
2070
  return { error: "Method not allowed" };
@@ -963,10 +2076,12 @@ export function createAgentChatPlugin(options) {
963
2076
  setResponseStatus(event, 400);
964
2077
  return { error: "message is required" };
965
2078
  }
2079
+ // Strip mention markup: @[Name|type] → @Name
2080
+ const cleanMessage = message.replace(/@\[([^\]|]+)\|[^\]]*\]/g, "@$1");
966
2081
  const apiKey = process.env.ANTHROPIC_API_KEY;
967
2082
  if (!apiKey) {
968
2083
  // Fallback: truncate the message
969
- return { title: message.trim().slice(0, 60) };
2084
+ return { title: cleanMessage.trim().slice(0, 60) };
970
2085
  }
971
2086
  try {
972
2087
  const res = await fetch("https://api.anthropic.com/v1/messages", {
@@ -982,38 +2097,42 @@ export function createAgentChatPlugin(options) {
982
2097
  messages: [
983
2098
  {
984
2099
  role: "user",
985
- content: `Generate a very short title (3-6 words, no quotes) for a chat that starts with this message:\n\n${message.slice(0, 500)}`,
2100
+ content: `Generate a very short title (3-6 words, no quotes) for a chat that starts with this message:\n\n${cleanMessage.slice(0, 500)}`,
986
2101
  },
987
2102
  ],
988
2103
  }),
989
2104
  });
990
2105
  if (!res.ok) {
991
- return { title: message.trim().slice(0, 60) };
2106
+ return { title: cleanMessage.trim().slice(0, 60) };
992
2107
  }
993
2108
  const data = (await res.json());
994
2109
  const text = data.content?.[0]?.text?.trim();
995
- return { title: text || message.trim().slice(0, 60) };
2110
+ return { title: text || cleanMessage.trim().slice(0, 60) };
996
2111
  }
997
2112
  catch {
998
- return { title: message.trim().slice(0, 60) };
2113
+ return { title: cleanMessage.trim().slice(0, 60) };
999
2114
  }
1000
2115
  }));
1001
2116
  // ─── Run management endpoints (for hot-reload resilience) ─────────────
1002
2117
  // GET /runs/active?threadId=X — check if there's an active run for a thread
1003
- nitroApp.h3App.use(`${routePath}/runs`, defineEventHandler(async (event) => {
2118
+ getH3App(nitroApp).use(`${routePath}/runs`, defineEventHandler(async (event) => {
1004
2119
  // Auth check — ensure the user is authenticated
1005
2120
  await getOwnerFromEvent(event);
1006
2121
  const method = getMethod(event);
1007
2122
  const url = event.node?.req?.url || event.path || "";
1008
2123
  // Route: POST /runs/:id/abort
1009
- const abortMatch = url.match(/\/runs\/([^/?]+)\/abort/);
2124
+ // Match both full URL (/runs/{id}/abort) and h3 prefix-stripped (/{id}/abort)
2125
+ const abortMatch = url.match(/\/runs\/([^/?]+)\/abort/) ||
2126
+ url.match(/^\/([^/?]+)\/abort/);
1010
2127
  if (abortMatch && method === "POST") {
1011
2128
  const runId = decodeURIComponent(abortMatch[1]);
1012
2129
  abortRun(runId); // Aborts in-memory + marks aborted in SQL
1013
2130
  return { ok: true };
1014
2131
  }
1015
2132
  // Route: GET /runs/:id/events?after=N
1016
- const eventsMatch = url.match(/\/runs\/([^/?]+)\/events/);
2133
+ // Match both full URL (/runs/{id}/events) and h3 prefix-stripped (/{id}/events)
2134
+ const eventsMatch = url.match(/\/runs\/([^/?]+)\/events/) ||
2135
+ url.match(/^\/([^/?]+)\/events/);
1017
2136
  if (eventsMatch && method === "GET") {
1018
2137
  const runId = decodeURIComponent(eventsMatch[1]);
1019
2138
  const query = getQuery(event);
@@ -1054,7 +2173,7 @@ export function createAgentChatPlugin(options) {
1054
2173
  // ─── Thread management endpoints ──────────────────────────────────────
1055
2174
  // Single handler for /threads and /threads/:id — h3's use() does prefix
1056
2175
  // matching so we can't reliably split them into separate handlers.
1057
- nitroApp.h3App.use(`${routePath}/threads`, defineEventHandler(async (event) => {
2176
+ getH3App(nitroApp).use(`${routePath}/threads`, defineEventHandler(async (event) => {
1058
2177
  const owner = await getOwnerFromEvent(event);
1059
2178
  const method = getMethod(event);
1060
2179
  // Determine if this is a specific-thread request.
@@ -1116,6 +2235,7 @@ export function createAgentChatPlugin(options) {
1116
2235
  if (method === "POST") {
1117
2236
  const body = await readBody(event);
1118
2237
  const thread = await createThread(owner, {
2238
+ id: body?.id,
1119
2239
  title: body?.title ?? "",
1120
2240
  });
1121
2241
  return thread;
@@ -1127,7 +2247,7 @@ export function createAgentChatPlugin(options) {
1127
2247
  // This is mounted last because h3's use() is prefix-based, meaning /_agent-native/agent-chat
1128
2248
  // also matches /_agent-native/agent-chat/threads/... — we skip sub-path requests here so the
1129
2249
  // earlier-mounted handlers (mode, save-key, files, skills, mentions, threads) handle them.
1130
- nitroApp.h3App.use(routePath, defineEventHandler(async (event) => {
2250
+ getH3App(nitroApp).use(routePath, defineEventHandler(async (event) => {
1131
2251
  // Skip sub-path requests — they're handled by earlier-mounted handlers
1132
2252
  const url = event.node?.req?.url || event.path || "";
1133
2253
  const afterBase = url.slice(url.indexOf(routePath) + routePath.length);
@@ -1136,14 +2256,71 @@ export function createAgentChatPlugin(options) {
1136
2256
  setResponseStatus(event, 404);
1137
2257
  return { error: "Not found" };
1138
2258
  }
1139
- // Set AGENT_USER_EMAIL so scripts resolve the same owner as the session.
1140
- // Without this, scripts default to "local@localhost" and miss resources
1141
- // created by users who authenticated via OAuth (e.g., Gmail).
2259
+ // Resolve per-request auth context
1142
2260
  const owner = await getOwnerFromEvent(event);
2261
+ // Resolve org ID: explicit callback > session.orgId from Better Auth
2262
+ let resolvedOrgId;
2263
+ if (options?.resolveOrgId) {
2264
+ resolvedOrgId = (await options.resolveOrgId(event)) ?? undefined;
2265
+ }
2266
+ else {
2267
+ try {
2268
+ const session = await getSession(event);
2269
+ resolvedOrgId = session?.orgId ?? undefined;
2270
+ }
2271
+ catch {
2272
+ // Session not available
2273
+ }
2274
+ }
2275
+ // Also set process.env for backwards compat (CLI scripts, legacy readers)
1143
2276
  process.env.AGENT_USER_EMAIL = owner;
1144
- const handler = currentDevMode && devHandler ? devHandler : prodHandler;
1145
- return handler(event);
2277
+ if (resolvedOrgId) {
2278
+ process.env.AGENT_ORG_ID = resolvedOrgId;
2279
+ }
2280
+ else {
2281
+ delete process.env.AGENT_ORG_ID;
2282
+ }
2283
+ return runWithRequestContext({ userEmail: owner, orgId: resolvedOrgId }, () => {
2284
+ const handler = currentDevMode && devHandler ? devHandler : prodHandler;
2285
+ return handler(event);
2286
+ });
1146
2287
  }));
2288
+ // ─── Recurring Jobs Scheduler ──────────────────────────────────────
2289
+ // Poll every 60 seconds for due recurring jobs and execute them.
2290
+ // Uses setInterval so it works in all deployment environments without
2291
+ // requiring Nitro experimental tasks configuration.
2292
+ try {
2293
+ const { processRecurringJobs } = await import("../jobs/scheduler.js");
2294
+ const schedulerDeps = {
2295
+ getActions: () => ({
2296
+ ...templateScripts,
2297
+ ...resourceScripts,
2298
+ ...docsScripts,
2299
+ ...chatScripts,
2300
+ ...jobTools,
2301
+ }),
2302
+ getSystemPrompt: async (owner) => {
2303
+ const resources = await loadResourcesForPrompt(owner);
2304
+ const schemaBlock = await buildSchemaBlock(owner, false);
2305
+ return basePrompt + resources + schemaBlock;
2306
+ },
2307
+ apiKey: options?.apiKey ?? process.env.ANTHROPIC_API_KEY,
2308
+ model: resolvedModel,
2309
+ };
2310
+ // Start after a 10-second delay to let the server fully initialize
2311
+ setTimeout(() => {
2312
+ setInterval(() => {
2313
+ processRecurringJobs(schedulerDeps).catch((err) => {
2314
+ console.error("[recurring-jobs] Scheduler error:", err?.message);
2315
+ });
2316
+ }, 60_000);
2317
+ if (process.env.DEBUG)
2318
+ console.log("[recurring-jobs] Scheduler started (60s interval)");
2319
+ }, 10_000);
2320
+ }
2321
+ catch (err) {
2322
+ // Jobs module not available — skip silently
2323
+ }
1147
2324
  };
1148
2325
  }
1149
2326
  /**
@@ -1152,4 +2329,35 @@ export function createAgentChatPlugin(options) {
1152
2329
  * In production, provides only the default system prompt.
1153
2330
  */
1154
2331
  export const defaultAgentChatPlugin = createAgentChatPlugin();
2332
+ // ---------------------------------------------------------------------------
2333
+ // MCP client glue — a shared manager reference + a /_agent-native/mcp/status
2334
+ // route so onboarding / settings UIs can see which MCP servers are live.
2335
+ // ---------------------------------------------------------------------------
2336
+ let _globalMcpManager = null;
2337
+ function setGlobalMcpManager(manager) {
2338
+ _globalMcpManager = manager;
2339
+ }
2340
+ /** Internal: access the current process's MCP client manager, if any. */
2341
+ export function getGlobalMcpManager() {
2342
+ return _globalMcpManager;
2343
+ }
2344
+ function mountMcpStatusRoute(nitroApp, manager) {
2345
+ // Idempotent — agent-chat-plugin can be invoked once per process; guard anyway.
2346
+ if (globalThis.__agentNativeMcpStatusMounted)
2347
+ return;
2348
+ globalThis.__agentNativeMcpStatusMounted = true;
2349
+ try {
2350
+ getH3App(nitroApp).use("/_agent-native/mcp/status", defineEventHandler(async (event) => {
2351
+ if (getMethod(event) !== "GET") {
2352
+ setResponseStatus(event, 405);
2353
+ return { error: "Method not allowed" };
2354
+ }
2355
+ setResponseHeader(event, "Content-Type", "application/json");
2356
+ return manager.getStatus();
2357
+ }));
2358
+ }
2359
+ catch (err) {
2360
+ console.warn(`[mcp-client] Failed to mount /_agent-native/mcp/status: ${err?.message ?? err}`);
2361
+ }
2362
+ }
1155
2363
  //# sourceMappingURL=agent-chat-plugin.js.map