@agent-native/core 0.96.0 → 0.97.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (450) hide show
  1. package/README.md +6 -0
  2. package/corpus/README.md +2 -2
  3. package/corpus/core/CHANGELOG.md +39 -0
  4. package/corpus/core/docs/content/audit-log.mdx +2 -1
  5. package/corpus/core/docs/content/automations.mdx +7 -7
  6. package/corpus/core/docs/content/creating-templates.mdx +1 -1
  7. package/corpus/core/docs/content/internationalization.mdx +2 -1
  8. package/corpus/core/docs/content/locales/ar-SA/audit-log.mdx +2 -1
  9. package/corpus/core/docs/content/locales/ar-SA/automations.mdx +7 -7
  10. package/corpus/core/docs/content/locales/ar-SA/getting-started.mdx +7 -1
  11. package/corpus/core/docs/content/locales/ar-SA/internationalization.mdx +1 -1
  12. package/corpus/core/docs/content/locales/ar-SA/package-lifecycle.mdx +19 -0
  13. package/corpus/core/docs/content/locales/ar-SA/sandbox-adapters.mdx +18 -7
  14. package/corpus/core/docs/content/locales/ar-SA/security.mdx +8 -0
  15. package/corpus/core/docs/content/locales/de-DE/audit-log.mdx +2 -1
  16. package/corpus/core/docs/content/locales/de-DE/automations.mdx +7 -7
  17. package/corpus/core/docs/content/locales/de-DE/getting-started.mdx +7 -1
  18. package/corpus/core/docs/content/locales/de-DE/internationalization.mdx +1 -1
  19. package/corpus/core/docs/content/locales/de-DE/package-lifecycle.mdx +22 -0
  20. package/corpus/core/docs/content/locales/de-DE/sandbox-adapters.mdx +18 -7
  21. package/corpus/core/docs/content/locales/de-DE/security.mdx +8 -0
  22. package/corpus/core/docs/content/locales/es-ES/audit-log.mdx +2 -1
  23. package/corpus/core/docs/content/locales/es-ES/automations.mdx +7 -7
  24. package/corpus/core/docs/content/locales/es-ES/getting-started.mdx +7 -1
  25. package/corpus/core/docs/content/locales/es-ES/internationalization.mdx +1 -1
  26. package/corpus/core/docs/content/locales/es-ES/package-lifecycle.mdx +22 -0
  27. package/corpus/core/docs/content/locales/es-ES/sandbox-adapters.mdx +18 -7
  28. package/corpus/core/docs/content/locales/es-ES/security.mdx +8 -0
  29. package/corpus/core/docs/content/locales/fr-FR/audit-log.mdx +2 -1
  30. package/corpus/core/docs/content/locales/fr-FR/automations.mdx +7 -7
  31. package/corpus/core/docs/content/locales/fr-FR/getting-started.mdx +7 -1
  32. package/corpus/core/docs/content/locales/fr-FR/internationalization.mdx +1 -1
  33. package/corpus/core/docs/content/locales/fr-FR/package-lifecycle.mdx +21 -0
  34. package/corpus/core/docs/content/locales/fr-FR/sandbox-adapters.mdx +19 -8
  35. package/corpus/core/docs/content/locales/fr-FR/security.mdx +8 -0
  36. package/corpus/core/docs/content/locales/hi-IN/audit-log.mdx +2 -1
  37. package/corpus/core/docs/content/locales/hi-IN/automations.mdx +7 -7
  38. package/corpus/core/docs/content/locales/hi-IN/getting-started.mdx +7 -1
  39. package/corpus/core/docs/content/locales/hi-IN/internationalization.mdx +1 -1
  40. package/corpus/core/docs/content/locales/hi-IN/package-lifecycle.mdx +20 -0
  41. package/corpus/core/docs/content/locales/hi-IN/sandbox-adapters.mdx +18 -7
  42. package/corpus/core/docs/content/locales/hi-IN/security.mdx +8 -0
  43. package/corpus/core/docs/content/locales/ja-JP/audit-log.mdx +2 -1
  44. package/corpus/core/docs/content/locales/ja-JP/automations.mdx +7 -7
  45. package/corpus/core/docs/content/locales/ja-JP/getting-started.mdx +7 -1
  46. package/corpus/core/docs/content/locales/ja-JP/internationalization.mdx +1 -1
  47. package/corpus/core/docs/content/locales/ja-JP/package-lifecycle.mdx +21 -0
  48. package/corpus/core/docs/content/locales/ja-JP/sandbox-adapters.mdx +17 -6
  49. package/corpus/core/docs/content/locales/ja-JP/security.mdx +8 -0
  50. package/corpus/core/docs/content/locales/ko-KR/audit-log.mdx +2 -1
  51. package/corpus/core/docs/content/locales/ko-KR/automations.mdx +7 -7
  52. package/corpus/core/docs/content/locales/ko-KR/getting-started.mdx +7 -1
  53. package/corpus/core/docs/content/locales/ko-KR/internationalization.mdx +1 -1
  54. package/corpus/core/docs/content/locales/ko-KR/package-lifecycle.mdx +20 -0
  55. package/corpus/core/docs/content/locales/ko-KR/sandbox-adapters.mdx +17 -6
  56. package/corpus/core/docs/content/locales/ko-KR/security.mdx +8 -0
  57. package/corpus/core/docs/content/locales/pt-BR/audit-log.mdx +2 -1
  58. package/corpus/core/docs/content/locales/pt-BR/automations.mdx +7 -7
  59. package/corpus/core/docs/content/locales/pt-BR/getting-started.mdx +7 -1
  60. package/corpus/core/docs/content/locales/pt-BR/internationalization.mdx +1 -1
  61. package/corpus/core/docs/content/locales/pt-BR/package-lifecycle.mdx +21 -0
  62. package/corpus/core/docs/content/locales/pt-BR/sandbox-adapters.mdx +18 -7
  63. package/corpus/core/docs/content/locales/pt-BR/security.mdx +8 -0
  64. package/corpus/core/docs/content/locales/zh-CN/audit-log.mdx +2 -1
  65. package/corpus/core/docs/content/locales/zh-CN/automations.mdx +7 -7
  66. package/corpus/core/docs/content/locales/zh-CN/getting-started.mdx +6 -4
  67. package/corpus/core/docs/content/locales/zh-CN/internationalization.mdx +1 -1
  68. package/corpus/core/docs/content/locales/zh-CN/package-lifecycle.mdx +19 -0
  69. package/corpus/core/docs/content/locales/zh-CN/sandbox-adapters.mdx +17 -6
  70. package/corpus/core/docs/content/locales/zh-CN/security.mdx +8 -0
  71. package/corpus/core/docs/content/locales/zh-TW/audit-log.mdx +2 -1
  72. package/corpus/core/docs/content/locales/zh-TW/automations.mdx +7 -7
  73. package/corpus/core/docs/content/locales/zh-TW/getting-started.mdx +6 -4
  74. package/corpus/core/docs/content/locales/zh-TW/internationalization.mdx +1 -1
  75. package/corpus/core/docs/content/locales/zh-TW/package-lifecycle.mdx +19 -0
  76. package/corpus/core/docs/content/locales/zh-TW/sandbox-adapters.mdx +18 -7
  77. package/corpus/core/docs/content/locales/zh-TW/security.mdx +8 -0
  78. package/corpus/core/docs/content/package-lifecycle.mdx +51 -0
  79. package/corpus/core/docs/content/sandbox-adapters.mdx +16 -5
  80. package/corpus/core/package.json +9 -2
  81. package/corpus/core/src/a2a/auth-policy.ts +33 -0
  82. package/corpus/core/src/agent/durable-background.ts +15 -7
  83. package/corpus/core/src/agent/run-store.ts +13 -4
  84. package/corpus/core/src/audit/actions/export-audit-events.ts +162 -0
  85. package/corpus/core/src/audit/store.ts +8 -3
  86. package/corpus/core/src/audit/types.ts +3 -0
  87. package/corpus/core/src/cli/doctor.ts +396 -0
  88. package/corpus/core/src/cli/index.ts +56 -0
  89. package/corpus/core/src/cli/info.ts +3 -3
  90. package/corpus/core/src/cli/package-lifecycle.ts +821 -0
  91. package/corpus/core/src/client/agent-chat-adapter.ts +9 -9
  92. package/corpus/core/src/guards/db-tool-scoping.ts +129 -0
  93. package/corpus/core/src/guards/index.ts +23 -0
  94. package/corpus/core/src/guards/no-drizzle-push.ts +116 -0
  95. package/corpus/core/src/guards/no-env-credentials.ts +229 -0
  96. package/corpus/core/src/guards/no-env-mutation.ts +114 -0
  97. package/corpus/core/src/guards/no-localhost-fallback.ts +124 -0
  98. package/corpus/core/src/guards/no-unscoped-credentials.ts +227 -0
  99. package/corpus/core/src/guards/no-unscoped-queries.ts +834 -0
  100. package/corpus/core/src/guards/scan-utils.ts +105 -0
  101. package/corpus/core/src/guards/types.ts +30 -0
  102. package/corpus/core/src/org/accept-pending.ts +9 -1
  103. package/corpus/core/src/org/migrations.ts +41 -0
  104. package/corpus/core/src/package-lifecycle/index.ts +1 -0
  105. package/corpus/core/src/package-lifecycle/manifest.ts +120 -0
  106. package/corpus/core/src/provider-api/custom-registry.ts +56 -0
  107. package/corpus/core/src/provider-api/index.ts +2 -0
  108. package/corpus/core/src/secrets/storage.ts +47 -27
  109. package/corpus/core/src/server/action-discovery.ts +4 -0
  110. package/corpus/core/src/server/agent-chat-plugin.ts +54 -12
  111. package/corpus/core/src/server/core-routes-plugin.ts +30 -14
  112. package/corpus/core/src/server/csrf.ts +24 -5
  113. package/corpus/core/src/server/framework-request-handler.ts +34 -0
  114. package/corpus/core/src/server/google-realtime-session.ts +1 -36
  115. package/corpus/core/src/server/poll.ts +24 -2
  116. package/corpus/core/src/server/realtime-voice.ts +9 -0
  117. package/corpus/core/src/server/request-origin.ts +63 -0
  118. package/corpus/core/src/server/transcribe-voice.ts +1 -50
  119. package/corpus/core/src/templates/default/package.json +2 -2
  120. package/corpus/core/src/templates/headless/package.json +0 -1
  121. package/corpus/core/src/templates/workspace-core/.agents/skills/audit-log/SKILL.md +3 -0
  122. package/corpus/core/src/templates/workspace-core/.agents/skills/automations/SKILL.md +1 -1
  123. package/corpus/core/src/templates/workspace-core/package.json +0 -1
  124. package/corpus/core/src/templates/workspace-root/package.json +0 -1
  125. package/corpus/core/src/triggers/actions.ts +11 -3
  126. package/corpus/core/src/triggers/types.ts +7 -1
  127. package/corpus/templates/analytics/actions/compose-dashboard.ts +65 -37
  128. package/corpus/templates/analytics/actions/mutate-dashboard.ts +73 -24
  129. package/corpus/templates/analytics/actions/reorder-dashboard-panels.ts +16 -13
  130. package/corpus/templates/analytics/actions/update-dashboard.ts +53 -42
  131. package/corpus/templates/analytics/changelog/2026-07-10-dashboard-edits-from-the-agent-and-the-ui-at-the-same-time-n.md +6 -0
  132. package/corpus/templates/analytics/changelog/2026-07-10-timed-out-bigquery-jobs-are-now-cancelled-so-they-stop-consu.md +6 -0
  133. package/corpus/templates/analytics/package.json +1 -2
  134. package/corpus/templates/analytics/server/lib/bigquery.ts +3 -2
  135. package/corpus/templates/analytics/server/lib/dashboards-store.ts +154 -11
  136. package/corpus/templates/assets/package.json +1 -2
  137. package/corpus/templates/brain/package.json +1 -2
  138. package/corpus/templates/calendar/package.json +1 -2
  139. package/corpus/templates/chat/package.json +1 -2
  140. package/corpus/templates/clips/changelog/2026-07-10-atomic-view-tracking.md +6 -0
  141. package/corpus/templates/clips/chrome-extension/package.json +3 -2
  142. package/corpus/templates/clips/desktop/package.json +6 -4
  143. package/corpus/templates/clips/desktop/src/lib/recorder.ts +26 -13
  144. package/corpus/templates/clips/desktop/src/lib/voice-dictation.ts +4 -1
  145. package/corpus/templates/clips/package.json +1 -2
  146. package/corpus/templates/clips/server/db/schema.ts +29 -17
  147. package/corpus/templates/clips/server/plugins/db.ts +8 -0
  148. package/corpus/templates/clips/server/routes/api/view-event.post.ts +260 -105
  149. package/corpus/templates/content/.agents/skills/notion-integration/SKILL.md +16 -0
  150. package/corpus/templates/content/AGENTS.md +72 -62
  151. package/corpus/templates/content/actions/_content-database-source-adapters.ts +84 -0
  152. package/corpus/templates/content/actions/_database-source-utils.ts +206 -96
  153. package/corpus/templates/content/actions/_notion-database-source-adapter.ts +216 -0
  154. package/corpus/templates/content/actions/_position-utils.ts +76 -0
  155. package/corpus/templates/content/actions/_property-utils.ts +31 -20
  156. package/corpus/templates/content/actions/add-database-item.ts +52 -39
  157. package/corpus/templates/content/actions/attach-content-database-source.ts +95 -11
  158. package/corpus/templates/content/actions/change-content-database-source-role.ts +24 -1
  159. package/corpus/templates/content/actions/configure-document-property.ts +36 -27
  160. package/corpus/templates/content/actions/create-content-database.ts +40 -30
  161. package/corpus/templates/content/actions/create-document.ts +39 -32
  162. package/corpus/templates/content/actions/duplicate-document-property.ts +37 -28
  163. package/corpus/templates/content/actions/list-notion-database-sources.ts +80 -0
  164. package/corpus/templates/content/actions/move-document.ts +64 -48
  165. package/corpus/templates/content/actions/refresh-content-database-source.ts +42 -3
  166. package/corpus/templates/content/actions/share-local-file-document.ts +36 -27
  167. package/corpus/templates/content/actions/suggest-source-join-key.ts +39 -16
  168. package/corpus/templates/content/app/components/editor/database/DatabaseView.tsx +89 -23
  169. package/corpus/templates/content/app/components/editor/database/settings.tsx +1 -1
  170. package/corpus/templates/content/app/hooks/use-content-database.ts +18 -1
  171. package/corpus/templates/content/app/i18n/zh-TW.ts +4 -0
  172. package/corpus/templates/content/app/i18n-data.ts +40 -0
  173. package/corpus/templates/content/changelog/2026-07-10-failed-row-creation-and-source-attach-now-show-an-error-inst.md +6 -0
  174. package/corpus/templates/content/changelog/2026-07-10-items-added-at-the-same-time-no-longer-end-up-with-identical.md +6 -0
  175. package/corpus/templates/content/changelog/2026-07-10-notion-databases-can-add-read-only-details-to-content-tables.md +6 -0
  176. package/corpus/templates/content/package.json +1 -2
  177. package/corpus/templates/content/parity/matrix.md +25 -25
  178. package/corpus/templates/content/parity/matrix.ts +1 -0
  179. package/corpus/templates/content/server/routes/api/documents/[id]/move.patch.ts +43 -26
  180. package/corpus/templates/content/shared/api.ts +16 -1
  181. package/corpus/templates/design/.agents/skills/visual-edit/SKILL.md +8 -4
  182. package/corpus/templates/design/AGENTS.md +12 -2
  183. package/corpus/templates/design/DEVELOPING.md +10 -6
  184. package/corpus/templates/design/actions/apply-visual-edit.ts +191 -6
  185. package/corpus/templates/design/actions/duplicate-design.ts +31 -25
  186. package/corpus/templates/design/app/pages/design-editor/pending-edits.ts +5 -1
  187. package/corpus/templates/design/changelog/2026-07-10-duplicating-a-design-can-no-longer-produce-a-copy-with-missi.md +6 -0
  188. package/corpus/templates/design/changelog/2026-07-10-local-visual-edits-can-now-save-safe-leaf-text-class-and.md +6 -0
  189. package/corpus/templates/design/package.json +1 -1
  190. package/corpus/templates/design/shared/local-jsx-visual-edit.ts +388 -0
  191. package/corpus/templates/dispatch/package.json +1 -2
  192. package/corpus/templates/forms/actions/patch-form-fields.ts +82 -44
  193. package/corpus/templates/forms/changelog/2026-07-10-simultaneous-edits-to-different-form-fields-no-longer-overwr.md +6 -0
  194. package/corpus/templates/forms/package.json +1 -2
  195. package/corpus/templates/macros/package.json +1 -2
  196. package/corpus/templates/mail/app/components/email/EmailThread.tsx +3 -1
  197. package/corpus/templates/mail/changelog/2026-07-10-fixed-calendar-rsvp-buttons-in-emails-firing-duplicate-respo.md +6 -0
  198. package/corpus/templates/mail/package.json +1 -2
  199. package/corpus/templates/plan/actions/restore-plan-version.ts +126 -96
  200. package/corpus/templates/plan/changelog/2026-07-10-restoring-a-plan-version-can-no-longer-leave-a-plan-half-res.md +6 -0
  201. package/corpus/templates/plan/package.json +1 -2
  202. package/corpus/templates/plan/server/plans.ts +9 -2
  203. package/corpus/templates/slides/actions/list-decks.ts +28 -0
  204. package/corpus/templates/slides/app/components/deck/MermaidRenderer.tsx +41 -26
  205. package/corpus/templates/slides/app/components/design-system/DesignSystemSetup.tsx +4 -8
  206. package/corpus/templates/slides/app/components/editor/EditorSidebar.tsx +2 -4
  207. package/corpus/templates/slides/app/components/editor/EditorToolbar.tsx +4 -8
  208. package/corpus/templates/slides/app/components/editor/ExportMenu.tsx +5 -12
  209. package/corpus/templates/slides/app/components/editor/HistoryPanel.tsx +3 -6
  210. package/corpus/templates/slides/app/components/editor/ImageDropPromptPopover.tsx +3 -6
  211. package/corpus/templates/slides/app/components/editor/PromptDialog.tsx +2 -5
  212. package/corpus/templates/slides/app/context/DeckContext.tsx +47 -4
  213. package/corpus/templates/slides/app/pages/DeckEditor.tsx +11 -30
  214. package/corpus/templates/slides/app/pages/Index.tsx +2 -3
  215. package/corpus/templates/slides/app/root.tsx +0 -5
  216. package/corpus/templates/slides/changelog/2026-07-10-deck-lists-load-much-faster-and-no-longer-re-download-slide-.md +6 -0
  217. package/corpus/templates/slides/package.json +1 -2
  218. package/dist/a2a/auth-policy.d.ts +19 -0
  219. package/dist/a2a/auth-policy.d.ts.map +1 -1
  220. package/dist/a2a/auth-policy.js +32 -0
  221. package/dist/a2a/auth-policy.js.map +1 -1
  222. package/dist/agent/durable-background.d.ts +8 -5
  223. package/dist/agent/durable-background.d.ts.map +1 -1
  224. package/dist/agent/durable-background.js +15 -8
  225. package/dist/agent/durable-background.js.map +1 -1
  226. package/dist/agent/run-store.d.ts.map +1 -1
  227. package/dist/agent/run-store.js +9 -4
  228. package/dist/agent/run-store.js.map +1 -1
  229. package/dist/audit/actions/export-audit-events.d.ts +27 -0
  230. package/dist/audit/actions/export-audit-events.d.ts.map +1 -0
  231. package/dist/audit/actions/export-audit-events.js +144 -0
  232. package/dist/audit/actions/export-audit-events.js.map +1 -0
  233. package/dist/audit/store.d.ts +1 -0
  234. package/dist/audit/store.d.ts.map +1 -1
  235. package/dist/audit/store.js +8 -3
  236. package/dist/audit/store.js.map +1 -1
  237. package/dist/audit/types.d.ts +3 -0
  238. package/dist/audit/types.d.ts.map +1 -1
  239. package/dist/audit/types.js.map +1 -1
  240. package/dist/cli/doctor.d.ts +83 -0
  241. package/dist/cli/doctor.d.ts.map +1 -0
  242. package/dist/cli/doctor.js +277 -0
  243. package/dist/cli/doctor.js.map +1 -0
  244. package/dist/cli/index.js +50 -0
  245. package/dist/cli/index.js.map +1 -1
  246. package/dist/cli/info.js +3 -3
  247. package/dist/cli/info.js.map +1 -1
  248. package/dist/cli/package-lifecycle.d.ts +50 -0
  249. package/dist/cli/package-lifecycle.d.ts.map +1 -0
  250. package/dist/cli/package-lifecycle.js +560 -0
  251. package/dist/cli/package-lifecycle.js.map +1 -0
  252. package/dist/client/agent-chat-adapter.js +7 -3
  253. package/dist/client/agent-chat-adapter.js.map +1 -1
  254. package/dist/collab/struct-routes.d.ts +1 -1
  255. package/dist/guards/db-tool-scoping.d.ts +38 -0
  256. package/dist/guards/db-tool-scoping.d.ts.map +1 -0
  257. package/dist/guards/db-tool-scoping.js +114 -0
  258. package/dist/guards/db-tool-scoping.js.map +1 -0
  259. package/dist/guards/index.d.ts +23 -0
  260. package/dist/guards/index.d.ts.map +1 -0
  261. package/dist/guards/index.js +19 -0
  262. package/dist/guards/index.js.map +1 -0
  263. package/dist/guards/no-drizzle-push.d.ts +14 -0
  264. package/dist/guards/no-drizzle-push.d.ts.map +1 -0
  265. package/dist/guards/no-drizzle-push.js +97 -0
  266. package/dist/guards/no-drizzle-push.js.map +1 -0
  267. package/dist/guards/no-env-credentials.d.ts +36 -0
  268. package/dist/guards/no-env-credentials.d.ts.map +1 -0
  269. package/dist/guards/no-env-credentials.js +204 -0
  270. package/dist/guards/no-env-credentials.js.map +1 -0
  271. package/dist/guards/no-env-mutation.d.ts +23 -0
  272. package/dist/guards/no-env-mutation.d.ts.map +1 -0
  273. package/dist/guards/no-env-mutation.js +90 -0
  274. package/dist/guards/no-env-mutation.js.map +1 -0
  275. package/dist/guards/no-localhost-fallback.d.ts +30 -0
  276. package/dist/guards/no-localhost-fallback.d.ts.map +1 -0
  277. package/dist/guards/no-localhost-fallback.js +105 -0
  278. package/dist/guards/no-localhost-fallback.js.map +1 -0
  279. package/dist/guards/no-unscoped-credentials.d.ts +28 -0
  280. package/dist/guards/no-unscoped-credentials.d.ts.map +1 -0
  281. package/dist/guards/no-unscoped-credentials.js +199 -0
  282. package/dist/guards/no-unscoped-credentials.js.map +1 -0
  283. package/dist/guards/no-unscoped-queries.d.ts +32 -0
  284. package/dist/guards/no-unscoped-queries.d.ts.map +1 -0
  285. package/dist/guards/no-unscoped-queries.js +720 -0
  286. package/dist/guards/no-unscoped-queries.js.map +1 -0
  287. package/dist/guards/scan-utils.d.ts +28 -0
  288. package/dist/guards/scan-utils.d.ts.map +1 -0
  289. package/dist/guards/scan-utils.js +92 -0
  290. package/dist/guards/scan-utils.js.map +1 -0
  291. package/dist/guards/types.d.ts +28 -0
  292. package/dist/guards/types.d.ts.map +1 -0
  293. package/dist/guards/types.js +11 -0
  294. package/dist/guards/types.js.map +1 -0
  295. package/dist/org/accept-pending.d.ts.map +1 -1
  296. package/dist/org/accept-pending.js +9 -1
  297. package/dist/org/accept-pending.js.map +1 -1
  298. package/dist/org/migrations.d.ts +7 -2
  299. package/dist/org/migrations.d.ts.map +1 -1
  300. package/dist/org/migrations.js +41 -0
  301. package/dist/org/migrations.js.map +1 -1
  302. package/dist/package-lifecycle/index.d.ts +2 -0
  303. package/dist/package-lifecycle/index.d.ts.map +1 -0
  304. package/dist/package-lifecycle/index.js +2 -0
  305. package/dist/package-lifecycle/index.js.map +1 -0
  306. package/dist/package-lifecycle/manifest.d.ts +24 -0
  307. package/dist/package-lifecycle/manifest.d.ts.map +1 -0
  308. package/dist/package-lifecycle/manifest.js +81 -0
  309. package/dist/package-lifecycle/manifest.js.map +1 -0
  310. package/dist/progress/routes.d.ts +1 -1
  311. package/dist/provider-api/custom-registry.d.ts +32 -1
  312. package/dist/provider-api/custom-registry.d.ts.map +1 -1
  313. package/dist/provider-api/custom-registry.js +41 -1
  314. package/dist/provider-api/custom-registry.js.map +1 -1
  315. package/dist/provider-api/index.d.ts +1 -1
  316. package/dist/provider-api/index.d.ts.map +1 -1
  317. package/dist/provider-api/index.js +1 -1
  318. package/dist/provider-api/index.js.map +1 -1
  319. package/dist/secrets/storage.d.ts.map +1 -1
  320. package/dist/secrets/storage.js +45 -27
  321. package/dist/secrets/storage.js.map +1 -1
  322. package/dist/server/action-discovery.d.ts.map +1 -1
  323. package/dist/server/action-discovery.js +4 -0
  324. package/dist/server/action-discovery.js.map +1 -1
  325. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  326. package/dist/server/agent-chat-plugin.js +47 -13
  327. package/dist/server/agent-chat-plugin.js.map +1 -1
  328. package/dist/server/core-routes-plugin.d.ts.map +1 -1
  329. package/dist/server/core-routes-plugin.js +23 -12
  330. package/dist/server/core-routes-plugin.js.map +1 -1
  331. package/dist/server/csrf.d.ts.map +1 -1
  332. package/dist/server/csrf.js +18 -5
  333. package/dist/server/csrf.js.map +1 -1
  334. package/dist/server/framework-request-handler.d.ts.map +1 -1
  335. package/dist/server/framework-request-handler.js +34 -0
  336. package/dist/server/framework-request-handler.js.map +1 -1
  337. package/dist/server/google-realtime-session.d.ts.map +1 -1
  338. package/dist/server/google-realtime-session.js +2 -34
  339. package/dist/server/google-realtime-session.js.map +1 -1
  340. package/dist/server/poll.d.ts.map +1 -1
  341. package/dist/server/poll.js +24 -2
  342. package/dist/server/poll.js.map +1 -1
  343. package/dist/server/realtime-voice.d.ts.map +1 -1
  344. package/dist/server/realtime-voice.js +9 -0
  345. package/dist/server/realtime-voice.js.map +1 -1
  346. package/dist/server/request-origin.d.ts +10 -0
  347. package/dist/server/request-origin.d.ts.map +1 -0
  348. package/dist/server/request-origin.js +60 -0
  349. package/dist/server/request-origin.js.map +1 -0
  350. package/dist/server/transcribe-voice.d.ts.map +1 -1
  351. package/dist/server/transcribe-voice.js +2 -48
  352. package/dist/server/transcribe-voice.js.map +1 -1
  353. package/dist/templates/default/package.json +2 -2
  354. package/dist/templates/headless/package.json +0 -1
  355. package/dist/templates/workspace-core/.agents/skills/audit-log/SKILL.md +3 -0
  356. package/dist/templates/workspace-core/.agents/skills/automations/SKILL.md +1 -1
  357. package/dist/templates/workspace-core/package.json +0 -1
  358. package/dist/templates/workspace-root/package.json +0 -1
  359. package/dist/triggers/actions.d.ts.map +1 -1
  360. package/dist/triggers/actions.js +8 -3
  361. package/dist/triggers/actions.js.map +1 -1
  362. package/dist/triggers/types.d.ts +7 -1
  363. package/dist/triggers/types.d.ts.map +1 -1
  364. package/dist/triggers/types.js.map +1 -1
  365. package/docs/content/audit-log.mdx +2 -1
  366. package/docs/content/automations.mdx +7 -7
  367. package/docs/content/creating-templates.mdx +1 -1
  368. package/docs/content/internationalization.mdx +2 -1
  369. package/docs/content/locales/ar-SA/audit-log.mdx +2 -1
  370. package/docs/content/locales/ar-SA/automations.mdx +7 -7
  371. package/docs/content/locales/ar-SA/getting-started.mdx +7 -1
  372. package/docs/content/locales/ar-SA/internationalization.mdx +1 -1
  373. package/docs/content/locales/ar-SA/package-lifecycle.mdx +19 -0
  374. package/docs/content/locales/ar-SA/sandbox-adapters.mdx +18 -7
  375. package/docs/content/locales/ar-SA/security.mdx +8 -0
  376. package/docs/content/locales/de-DE/audit-log.mdx +2 -1
  377. package/docs/content/locales/de-DE/automations.mdx +7 -7
  378. package/docs/content/locales/de-DE/getting-started.mdx +7 -1
  379. package/docs/content/locales/de-DE/internationalization.mdx +1 -1
  380. package/docs/content/locales/de-DE/package-lifecycle.mdx +22 -0
  381. package/docs/content/locales/de-DE/sandbox-adapters.mdx +18 -7
  382. package/docs/content/locales/de-DE/security.mdx +8 -0
  383. package/docs/content/locales/es-ES/audit-log.mdx +2 -1
  384. package/docs/content/locales/es-ES/automations.mdx +7 -7
  385. package/docs/content/locales/es-ES/getting-started.mdx +7 -1
  386. package/docs/content/locales/es-ES/internationalization.mdx +1 -1
  387. package/docs/content/locales/es-ES/package-lifecycle.mdx +22 -0
  388. package/docs/content/locales/es-ES/sandbox-adapters.mdx +18 -7
  389. package/docs/content/locales/es-ES/security.mdx +8 -0
  390. package/docs/content/locales/fr-FR/audit-log.mdx +2 -1
  391. package/docs/content/locales/fr-FR/automations.mdx +7 -7
  392. package/docs/content/locales/fr-FR/getting-started.mdx +7 -1
  393. package/docs/content/locales/fr-FR/internationalization.mdx +1 -1
  394. package/docs/content/locales/fr-FR/package-lifecycle.mdx +21 -0
  395. package/docs/content/locales/fr-FR/sandbox-adapters.mdx +19 -8
  396. package/docs/content/locales/fr-FR/security.mdx +8 -0
  397. package/docs/content/locales/hi-IN/audit-log.mdx +2 -1
  398. package/docs/content/locales/hi-IN/automations.mdx +7 -7
  399. package/docs/content/locales/hi-IN/getting-started.mdx +7 -1
  400. package/docs/content/locales/hi-IN/internationalization.mdx +1 -1
  401. package/docs/content/locales/hi-IN/package-lifecycle.mdx +20 -0
  402. package/docs/content/locales/hi-IN/sandbox-adapters.mdx +18 -7
  403. package/docs/content/locales/hi-IN/security.mdx +8 -0
  404. package/docs/content/locales/ja-JP/audit-log.mdx +2 -1
  405. package/docs/content/locales/ja-JP/automations.mdx +7 -7
  406. package/docs/content/locales/ja-JP/getting-started.mdx +7 -1
  407. package/docs/content/locales/ja-JP/internationalization.mdx +1 -1
  408. package/docs/content/locales/ja-JP/package-lifecycle.mdx +21 -0
  409. package/docs/content/locales/ja-JP/sandbox-adapters.mdx +17 -6
  410. package/docs/content/locales/ja-JP/security.mdx +8 -0
  411. package/docs/content/locales/ko-KR/audit-log.mdx +2 -1
  412. package/docs/content/locales/ko-KR/automations.mdx +7 -7
  413. package/docs/content/locales/ko-KR/getting-started.mdx +7 -1
  414. package/docs/content/locales/ko-KR/internationalization.mdx +1 -1
  415. package/docs/content/locales/ko-KR/package-lifecycle.mdx +20 -0
  416. package/docs/content/locales/ko-KR/sandbox-adapters.mdx +17 -6
  417. package/docs/content/locales/ko-KR/security.mdx +8 -0
  418. package/docs/content/locales/pt-BR/audit-log.mdx +2 -1
  419. package/docs/content/locales/pt-BR/automations.mdx +7 -7
  420. package/docs/content/locales/pt-BR/getting-started.mdx +7 -1
  421. package/docs/content/locales/pt-BR/internationalization.mdx +1 -1
  422. package/docs/content/locales/pt-BR/package-lifecycle.mdx +21 -0
  423. package/docs/content/locales/pt-BR/sandbox-adapters.mdx +18 -7
  424. package/docs/content/locales/pt-BR/security.mdx +8 -0
  425. package/docs/content/locales/zh-CN/audit-log.mdx +2 -1
  426. package/docs/content/locales/zh-CN/automations.mdx +7 -7
  427. package/docs/content/locales/zh-CN/getting-started.mdx +6 -4
  428. package/docs/content/locales/zh-CN/internationalization.mdx +1 -1
  429. package/docs/content/locales/zh-CN/package-lifecycle.mdx +19 -0
  430. package/docs/content/locales/zh-CN/sandbox-adapters.mdx +17 -6
  431. package/docs/content/locales/zh-CN/security.mdx +8 -0
  432. package/docs/content/locales/zh-TW/audit-log.mdx +2 -1
  433. package/docs/content/locales/zh-TW/automations.mdx +7 -7
  434. package/docs/content/locales/zh-TW/getting-started.mdx +6 -4
  435. package/docs/content/locales/zh-TW/internationalization.mdx +1 -1
  436. package/docs/content/locales/zh-TW/package-lifecycle.mdx +19 -0
  437. package/docs/content/locales/zh-TW/sandbox-adapters.mdx +18 -7
  438. package/docs/content/locales/zh-TW/security.mdx +8 -0
  439. package/docs/content/package-lifecycle.mdx +51 -0
  440. package/docs/content/sandbox-adapters.mdx +16 -5
  441. package/package.json +10 -3
  442. package/src/templates/default/package.json +2 -2
  443. package/src/templates/headless/package.json +0 -1
  444. package/src/templates/workspace-core/.agents/skills/audit-log/SKILL.md +3 -0
  445. package/src/templates/workspace-core/.agents/skills/automations/SKILL.md +1 -1
  446. package/src/templates/workspace-core/package.json +0 -1
  447. package/src/templates/workspace-root/package.json +0 -1
  448. package/corpus/templates/slides/app/components/ui/toast.tsx +0 -1
  449. package/corpus/templates/slides/app/components/ui/toaster.tsx +0 -1
  450. package/corpus/templates/slides/app/hooks/use-toast.ts +0 -1
@@ -0,0 +1,60 @@
1
+ import { getRequestHeader } from "h3";
2
+ function isLoopbackHost(host) {
3
+ return host.startsWith("localhost:") || host.startsWith("127.0.0.1:");
4
+ }
5
+ /**
6
+ * Reject cross-site POSTs. Cookies are `SameSite=None; Secure` over HTTPS so
7
+ * the browser would otherwise attach the session to a forged form submission
8
+ * from evil.com, causing us to spend provider credits on the user's behalf.
9
+ * Same-origin browsers always send `Origin` on POST; if it's missing we fall
10
+ * back to `Sec-Fetch-Site` so Safari's fetch-spec behavior still works.
11
+ */
12
+ export function isSameOriginRequest(event) {
13
+ const host = getRequestHeader(event, "host");
14
+ const origin = getRequestHeader(event, "origin");
15
+ if (origin && host) {
16
+ try {
17
+ const parsed = new URL(origin);
18
+ const forwardedProto = getRequestHeader(event, "x-forwarded-proto");
19
+ const forwardedProtocol = forwardedProto === "https" || forwardedProto === "http"
20
+ ? `${forwardedProto}:`
21
+ : null;
22
+ const matchesScheme = forwardedProtocol
23
+ ? parsed.protocol === forwardedProtocol
24
+ : parsed.protocol === "https:" ||
25
+ (parsed.protocol === "http:" && isLoopbackHost(host));
26
+ if (parsed.host === host && matchesScheme)
27
+ return true;
28
+ // Tauri desktop dev serves the tray WebView from localhost:1420 while
29
+ // the app server lives on the template dev port. Production Tauri
30
+ // WebViews can also send a tauri://localhost origin. Trust that custom
31
+ // scheme, while limiting the web-scheme desktop origins below to a
32
+ // loopback app server so arbitrary websites still fail the CSRF check.
33
+ if (parsed.protocol === "tauri:" && parsed.hostname === "localhost") {
34
+ return true;
35
+ }
36
+ if ((parsed.protocol === "http:" || parsed.protocol === "https:") &&
37
+ parsed.hostname === "tauri.localhost" &&
38
+ isLoopbackHost(host)) {
39
+ return true;
40
+ }
41
+ if (parsed.protocol === "http:" &&
42
+ (parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1") &&
43
+ parsed.port === "1420" &&
44
+ isLoopbackHost(host)) {
45
+ return true;
46
+ }
47
+ return false;
48
+ }
49
+ catch {
50
+ return false;
51
+ }
52
+ }
53
+ const fetchSite = getRequestHeader(event, "sec-fetch-site");
54
+ if (fetchSite)
55
+ return fetchSite === "same-origin" || fetchSite === "none";
56
+ // No Origin and no Sec-Fetch-Site: likely a non-browser client (curl,
57
+ // server-side) — safe to allow, CSRF requires a browser with ambient cookies.
58
+ return true;
59
+ }
60
+ //# sourceMappingURL=request-origin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request-origin.js","sourceRoot":"","sources":["../../src/server/request-origin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAgB,MAAM,IAAI,CAAC;AAEpD,SAAS,cAAc,CAAC,IAAY;IAClC,OAAO,IAAI,CAAC,UAAU,CAAC,YAAY,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC;AACxE,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,mBAAmB,CAAC,KAAc;IAChD,MAAM,IAAI,GAAG,gBAAgB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC7C,MAAM,MAAM,GAAG,gBAAgB,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;IACjD,IAAI,MAAM,IAAI,IAAI,EAAE,CAAC;QACnB,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC;YAC/B,MAAM,cAAc,GAAG,gBAAgB,CAAC,KAAK,EAAE,mBAAmB,CAAC,CAAC;YACpE,MAAM,iBAAiB,GACrB,cAAc,KAAK,OAAO,IAAI,cAAc,KAAK,MAAM;gBACrD,CAAC,CAAC,GAAG,cAAc,GAAG;gBACtB,CAAC,CAAC,IAAI,CAAC;YACX,MAAM,aAAa,GAAG,iBAAiB;gBACrC,CAAC,CAAC,MAAM,CAAC,QAAQ,KAAK,iBAAiB;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nfunction isLoopbackHost(host: string): boolean {\n return host.startsWith(\"localhost:\") || host.startsWith(\"127.0.0.1:\");\n}\n\n/**\n * Reject cross-site POSTs. Cookies are `SameSite=None; Secure` over HTTPS so\n * the browser would otherwise attach the session to a forged form submission\n * from evil.com, causing us to spend provider credits on the user's behalf.\n * Same-origin browsers always send `Origin` on POST; if it's missing we fall\n * back to `Sec-Fetch-Site` so Safari's fetch-spec behavior still works.\n */\nexport function isSameOriginRequest(event: H3Event): boolean {\n const host = getRequestHeader(event, \"host\");\n const origin = getRequestHeader(event, \"origin\");\n if (origin && host) {\n try {\n const parsed = new URL(origin);\n const forwardedProto = getRequestHeader(event, \"x-forwarded-proto\");\n const forwardedProtocol =\n forwardedProto === \"https\" || forwardedProto === \"http\"\n ? `${forwardedProto}:`\n : null;\n const matchesScheme = forwardedProtocol\n ? parsed.protocol === forwardedProtocol\n : parsed.protocol === \"https:\" ||\n (parsed.protocol === \"http:\" && isLoopbackHost(host));\n if (parsed.host === host && matchesScheme) return true;\n // Tauri desktop dev serves the tray WebView from localhost:1420 while\n // the app server lives on the template dev port. Production Tauri\n // WebViews can also send a tauri://localhost origin. Trust that custom\n // scheme, while limiting the web-scheme desktop origins below to a\n // loopback app server so arbitrary websites still fail the CSRF check.\n if (parsed.protocol === \"tauri:\" && parsed.hostname === \"localhost\") {\n return true;\n }\n if (\n (parsed.protocol === \"http:\" || parsed.protocol === \"https:\") &&\n parsed.hostname === \"tauri.localhost\" &&\n isLoopbackHost(host)\n ) {\n return true;\n }\n if (\n parsed.protocol === \"http:\" &&\n (parsed.hostname === \"localhost\" || parsed.hostname === \"127.0.0.1\") &&\n parsed.port === \"1420\" &&\n isLoopbackHost(host)\n ) {\n return true;\n }\n return false;\n } catch {\n return false;\n }\n }\n const fetchSite = getRequestHeader(event, \"sec-fetch-site\");\n if (fetchSite) return fetchSite === \"same-origin\" || fetchSite === \"none\";\n // No Origin and no Sec-Fetch-Site: likely a non-browser client (curl,\n // server-side) — safe to allow, CSRF requires a browser with ambient cookies.\n return true;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"transcribe-voice.d.ts","sourceRoot":"","sources":["../../src/server/transcribe-voice.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AA8IH,wBAAgB,4BAA4B;;;;;;IAkY3C"}
1
+ {"version":3,"file":"transcribe-voice.d.ts","sourceRoot":"","sources":["../../src/server/transcribe-voice.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AA6FH,wBAAgB,4BAA4B;;;;;;IAkY3C"}
@@ -16,7 +16,7 @@
16
16
  * audio bodies aren't a clean fit for the action contract (actions are
17
17
  * typed JSON-in / JSON-out).
18
18
  */
19
- import { defineEventHandler, getMethod, getRequestHeader, readMultipartFormData, setResponseStatus, } from "h3";
19
+ import { defineEventHandler, getMethod, readMultipartFormData, setResponseStatus, } from "h3";
20
20
  import { createBuilderEngine } from "../agent/engine/builder-engine.js";
21
21
  import { appStateGet } from "../application-state/store.js";
22
22
  import { getOrgContext } from "../org/context.js";
@@ -25,6 +25,7 @@ import { applyVoiceContextReplacements, buildVoiceGuidanceBlock, parseVoiceConte
25
25
  import { getSession } from "./auth.js";
26
26
  import { resolveHasBuilderPrivateKey, resolveSecret, } from "./credential-provider.js";
27
27
  import { runWithRequestContext } from "./request-context.js";
28
+ import { isSameOriginRequest } from "./request-origin.js";
28
29
  const WHISPER_URL = "https://api.openai.com/v1/audio/transcriptions";
29
30
  const GROQ_URL = "https://api.groq.com/openai/v1/audio/transcriptions";
30
31
  const GROQ_CHAT_URL = "https://api.groq.com/openai/v1/chat/completions";
@@ -54,53 +55,6 @@ const BUILDER_GEMINI_TRANSCRIPTION_MODEL = "gemini-3-1-flash-lite";
54
55
  // managed provider above handles the newer Gemini 3.1 Flash-Lite preview.
55
56
  const GEMINI_MODEL = "gemini-2.0-flash-lite";
56
57
  const GEMINI_URL = `https://generativelanguage.googleapis.com/v1beta/models/${GEMINI_MODEL}:generateContent`;
57
- /**
58
- * Reject cross-site POSTs. Cookies are `SameSite=None; Secure` over HTTPS so
59
- * the browser would otherwise attach the session to a forged form submission
60
- * from evil.com, causing us to spend OpenAI credits on the user's behalf.
61
- * Same-origin browsers always send `Origin` on POST; if it's missing we fall
62
- * back to `Sec-Fetch-Site` so Safari's fetch-spec behavior still works.
63
- */
64
- function isSameOriginRequest(event) {
65
- const host = getRequestHeader(event, "host");
66
- const origin = getRequestHeader(event, "origin");
67
- if (origin && host) {
68
- try {
69
- const parsed = new URL(origin);
70
- if (parsed.host === host)
71
- return true;
72
- // Tauri desktop dev serves the tray WebView from localhost:1420 while
73
- // the app server lives on the template dev port. Production Tauri
74
- // WebViews can also send a tauri://localhost origin. Treat only those
75
- // desktop origins as trusted cross-origin callers; arbitrary websites
76
- // still fail the CSRF check.
77
- if (parsed.protocol === "tauri:" && parsed.hostname === "localhost") {
78
- return true;
79
- }
80
- if ((parsed.protocol === "http:" || parsed.protocol === "https:") &&
81
- parsed.hostname === "tauri.localhost" &&
82
- (host.startsWith("localhost:") || host.startsWith("127.0.0.1:"))) {
83
- return true;
84
- }
85
- if (parsed.protocol === "http:" &&
86
- (parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1") &&
87
- parsed.port === "1420" &&
88
- (host.startsWith("localhost:") || host.startsWith("127.0.0.1:"))) {
89
- return true;
90
- }
91
- return false;
92
- }
93
- catch {
94
- return false;
95
- }
96
- }
97
- const fetchSite = getRequestHeader(event, "sec-fetch-site");
98
- if (fetchSite)
99
- return fetchSite === "same-origin" || fetchSite === "none";
100
- // No Origin and no Sec-Fetch-Site: likely a non-browser client (curl,
101
- // server-side) — safe to allow, CSRF requires a browser with ambient cookies.
102
- return true;
103
- }
104
58
  /**
105
59
  * Derive an AbortSignal that fires when the client disconnects mid-request
106
60
  * (e.g. the desktop client's own 8s ceiling firing before a provider call's
@@ -1 +1 @@
1
- {"version":3,"file":"transcribe-voice.js","sourceRoot":"","sources":["../../src/server/transcribe-voice.ts"],"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,CAAC;IACJ,CAAC;IACD,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC;AACtB,CAAC","sourcesContent":["/**\n * POST /_agent-native/transcribe-voice\n *\n * Receives an audio blob from the agent sidebar composer and forwards it to\n * the configured transcription provider. Returns `{ text }` on success,\n * `{ error }` on failure.\n *\n * Key resolution order for BYOK providers:\n * 1. Request-scoped encrypted secret (`app_secrets`: user, org, workspace).\n * 2. Env var fallback only outside authenticated request contexts.\n *\n * If no server provider is configured, returns 400 with an error the\n * composer UI can surface (the client falls back to Web Speech when possible).\n *\n * This is a framework route rather than a `defineAction` because multipart\n * audio bodies aren't a clean fit for the action contract (actions are\n * typed JSON-in / JSON-out).\n */\n\nimport {\n defineEventHandler,\n getMethod,\n getRequestHeader,\n readMultipartFormData,\n setResponseStatus,\n type H3Event,\n} from \"h3\";\n\nimport { createBuilderEngine } from \"../agent/engine/builder-engine.js\";\nimport { appStateGet } from \"../application-state/store.js\";\nimport { getOrgContext } from \"../org/context.js\";\nimport { transcribeWithBuilder } from \"../transcription/builder-transcription.js\";\nimport {\n applyVoiceContextReplacements,\n buildVoiceGuidanceBlock,\n parseVoiceContextPack,\n voiceContextTermsOnly,\n type VoiceContextPack,\n} from \"../voice/index.js\";\nimport { getSession } from \"./auth.js\";\nimport {\n resolveHasBuilderPrivateKey,\n resolveSecret,\n} from \"./credential-provider.js\";\nimport { runWithRequestContext } from \"./request-context.js\";\n\nconst WHISPER_URL = \"https://api.openai.com/v1/audio/transcriptions\";\nconst GROQ_URL = \"https://api.groq.com/openai/v1/audio/transcriptions\";\nconst GROQ_CHAT_URL = \"https://api.groq.com/openai/v1/chat/completions\";\nconst GROQ_MODEL = \"whisper-large-v3-turbo\";\nconst GROQ_CLEANUP_MODEL = \"llama-3.3-70b-versatile\";\nconst OPENAI_MODEL = \"whisper-1\";\nconst OPENAI_CHAT_URL = \"https://api.openai.com/v1/chat/completions\";\nconst OPENAI_CLEANUP_MODEL = \"gpt-5.6-luna\";\nconst MAX_AUDIO_BYTES = 25 * 1024 * 1024; // Whisper hard limit.\n// Hard cap for the dictation-cleanup text path (`sanitizeTranscriptText`\n// below). This endpoint has no `task` field — it's always the Hold-Fn\n// dictation cleanup pass — but a long session (many minutes across\n// multiple pause-triggered final segments) can still exceed a tight cap.\n// 150k gives real headroom for a long dictation session while still\n// bounding worst-case request size; truncation (when it does happen) keeps\n// both ends of the text instead of silently dropping the tail.\nconst MAX_TRANSCRIPT_CHARS = 150_000;\n// Public Builder transcription model id. The Builder gateway maps this to\n// Gemini 3.1 Flash-Lite.\nconst BUILDER_GEMINI_TRANSCRIPTION_MODEL = \"gemini-3-1-flash-lite\";\n\n// Gemini Flash Lite BYOK path when GEMINI_API_KEY is configured.\n// Gemini accepts inline audio; we just give it the bytes and a \"transcribe\n// this\" prompt and it replies with text. 2.5x faster TTFT than 2.5 Flash\n// per Google's release notes, and noticeably snappier than the Whisper\n// round-trip even on a fast connection.\n// Keep the direct Google AI path on a stable public model id; Builder's\n// managed provider above handles the newer Gemini 3.1 Flash-Lite preview.\nconst GEMINI_MODEL = \"gemini-2.0-flash-lite\";\nconst GEMINI_URL = `https://generativelanguage.googleapis.com/v1beta/models/${GEMINI_MODEL}:generateContent`;\n\n/**\n * Reject cross-site POSTs. Cookies are `SameSite=None; Secure` over HTTPS so\n * the browser would otherwise attach the session to a forged form submission\n * from evil.com, causing us to spend OpenAI credits on the user's behalf.\n * Same-origin browsers always send `Origin` on POST; if it's missing we fall\n * back to `Sec-Fetch-Site` so Safari's fetch-spec behavior still works.\n */\nfunction isSameOriginRequest(event: H3Event): boolean {\n const host = getRequestHeader(event, \"host\");\n const origin = getRequestHeader(event, \"origin\");\n if (origin && host) {\n try {\n const parsed = new URL(origin);\n if (parsed.host === host) return true;\n // Tauri desktop dev serves the tray WebView from localhost:1420 while\n // the app server lives on the template dev port. Production Tauri\n // WebViews can also send a tauri://localhost origin. Treat only those\n // desktop origins as trusted cross-origin callers; arbitrary websites\n // still fail the CSRF check.\n if (parsed.protocol === \"tauri:\" && parsed.hostname === \"localhost\") {\n return true;\n }\n if (\n (parsed.protocol === \"http:\" || parsed.protocol === \"https:\") &&\n parsed.hostname === \"tauri.localhost\" &&\n (host.startsWith(\"localhost:\") || host.startsWith(\"127.0.0.1:\"))\n ) {\n return true;\n }\n if (\n parsed.protocol === \"http:\" &&\n (parsed.hostname === \"localhost\" || parsed.hostname === \"127.0.0.1\") &&\n parsed.port === \"1420\" &&\n (host.startsWith(\"localhost:\") || host.startsWith(\"127.0.0.1:\"))\n ) {\n return true;\n }\n return false;\n } catch {\n return false;\n }\n }\n const fetchSite = getRequestHeader(event, \"sec-fetch-site\");\n if (fetchSite) return fetchSite === \"same-origin\" || fetchSite === \"none\";\n // No Origin and no Sec-Fetch-Site: likely a non-browser client (curl,\n // server-side) — safe to allow, CSRF requires a browser with ambient cookies.\n return true;\n}\n\n/**\n * Derive an AbortSignal that fires when the client disconnects mid-request\n * (e.g. the desktop client's own 8s ceiling firing before a provider call's\n * longer timeout). Without this, an abandoned client connection leaves the\n * server-side provider fetch running for its full timeout, burning provider\n * quota/cost on a response nobody will read. `req.on(\"close\", ...)` fires on\n * abnormal/early disconnect in Node's http server; a stray fire after normal\n * completion is a harmless no-op since the response has already been sent.\n * Returns undefined if the underlying Node request isn't available (e.g. a\n * non-Node adapter), so callers fall back to their existing timeout-only\n * signal.\n */\nfunction clientDisconnectSignal(event: H3Event): AbortSignal | undefined {\n const req = event.node?.req as\n | (NodeJS.EventEmitter & { on?: (...args: any[]) => void })\n | undefined;\n if (!req?.on) return undefined;\n const controller = new AbortController();\n req.on(\"close\", () => controller.abort());\n return controller.signal;\n}\n\n/** Combine a provider call's own timeout signal with the request's optional\n * client-disconnect signal so either one aborts the upstream fetch. */\nfunction withClientAbort(\n timeoutSignal: AbortSignal,\n clientAbortSignal?: AbortSignal,\n): AbortSignal {\n return clientAbortSignal\n ? AbortSignal.any([timeoutSignal, clientAbortSignal])\n : timeoutSignal;\n}\n\nexport function createTranscribeVoiceHandler() {\n return defineEventHandler(async (event: H3Event) => {\n if (getMethod(event) !== \"POST\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n if (!isSameOriginRequest(event)) {\n setResponseStatus(event, 403);\n return { error: \"Cross-origin request rejected\" };\n }\n\n // One client-disconnect signal per request, threaded into every\n // provider-fetch AbortController below via AbortSignal.any so a client\n // giving up early aborts the same upstream fetch instead of leaving it\n // running for its full timeout.\n const clientAbort = clientDisconnectSignal(event);\n\n const parts = await readMultipartFormData(event).catch(() => null);\n const audio = parts?.find((p) => p.name === \"audio\");\n const textPart = parts?.find((p) => p.name === \"text\");\n const transcriptText = textPart?.data\n ? sanitizeTranscriptText(Buffer.from(textPart.data).toString(\"utf8\"))\n : undefined;\n if (!audio?.data?.length && !transcriptText) {\n setResponseStatus(event, 400);\n return { error: \"Missing audio or transcript payload\" };\n }\n if (audio?.data?.length && audio.data.length > MAX_AUDIO_BYTES) {\n setResponseStatus(event, 413);\n return { error: \"Audio too large (max 25 MB)\" };\n }\n\n const languagePart = parts?.find((p) => p.name === \"language\");\n const language = languagePart?.data\n ? Buffer.from(languagePart.data).toString(\"utf8\").trim().slice(0, 8)\n : undefined;\n const instructionsPart = parts?.find((p) => p.name === \"instructions\");\n const instructions = instructionsPart?.data\n ? sanitizeInstructions(\n Buffer.from(instructionsPart.data).toString(\"utf8\"),\n )\n : undefined;\n const voiceContextPart = parts?.find(\n (p) => p.name === \"voiceContext\" || p.name === \"contextPack\",\n );\n const voiceContext = voiceContextPart?.data\n ? parseVoiceContextPack(\n Buffer.from(voiceContextPart.data).toString(\"utf8\"),\n )\n : undefined;\n const voiceGuidance = buildVoiceGuidanceBlock({\n instructions,\n contextPack: voiceContextTermsOnly(voiceContext),\n });\n const applyVoiceContext = (value: string) =>\n applyVoiceContextReplacements(value, voiceContext).trim();\n\n // Resolve provider preference. Per-request \"provider\" form field takes\n // precedence (the desktop client sends it on every dictation press),\n // falling back to the user's stored `voice-transcription-prefs` app\n // state for the agent sidebar composer / web clients that don't send\n // it explicitly.\n const session = await getSession(event).catch(() => null);\n if (!session?.email && process.env.NODE_ENV === \"production\") {\n setResponseStatus(event, 401);\n return { error: \"Authentication required\" };\n }\n const orgCtx = session?.email\n ? await getOrgContext(event).catch(() => null)\n : null;\n const requestContext = {\n userEmail: session?.email,\n orgId: orgCtx?.orgId ?? undefined,\n };\n const withRequestContext = async <T>(fn: () => Promise<T>): Promise<T> =>\n requestContext.userEmail\n ? runWithRequestContext(requestContext, fn)\n : fn();\n const hasBuilderPrivateKey = async () =>\n withRequestContext(() => resolveHasBuilderPrivateKey());\n const transcribeWithBuilderForRequest = (\n opts: Parameters<typeof transcribeWithBuilder>[0],\n ) => withRequestContext(() => transcribeWithBuilder(opts));\n const sessionId = session?.email ?? \"local\";\n let providerPref: string | undefined;\n // CRITICAL: presence of the \"provider\" form field is the explicit\n // signal that the client is making a per-request choice. Even if\n // the value is \"auto\" (→ undefined providerPref → fallback chain),\n // we must NOT fall back to app-state's stored preference — the\n // client just told us what it wants. Without this gate, a stale\n // `voice-transcription-prefs.provider = \"browser\"` in app-state\n // (from earlier testing) would override the client's \"auto\" and\n // 400 with \"Voice provider is set to browser\".\n const providerPart = parts?.find((p) => p.name === \"provider\");\n let providerExplicit = false;\n if (providerPart?.data) {\n const v = Buffer.from(providerPart.data)\n .toString(\"utf8\")\n .trim()\n .toLowerCase();\n if (\n v === \"auto\" ||\n v === \"browser\" ||\n v === \"builder\" ||\n v === \"builder-gemini\" ||\n v === \"gemini\" ||\n v === \"openai\" ||\n v === \"groq\"\n ) {\n providerExplicit = true;\n providerPref = v === \"auto\" ? undefined : v;\n }\n }\n if (!providerExplicit) {\n try {\n const prefs = await appStateGet(sessionId, \"voice-transcription-prefs\");\n providerPref = (\n prefs as { provider?: string; value?: { provider?: string } } | null\n )?.provider;\n providerPref ??= (prefs as { value?: { provider?: string } } | null)\n ?.value?.provider;\n } catch {\n /* fall through — default to fallback chain */\n }\n }\n\n // Respect explicit \"browser\" preference — user chose Web Speech API and\n // does not want audio uploaded to any external provider. The client\n // shouldn't hit this endpoint when \"browser\" is selected; this is a\n // defense-in-depth refusal.\n if (providerPref === \"browser\" && !transcriptText) {\n setResponseStatus(event, 400);\n return {\n error:\n 'Voice provider is set to \"browser\" (Web Speech API only). Change the preference in Settings → Voice Transcription to use a server-side provider.',\n };\n }\n\n // Per-user-or-fallback API key resolution. Hoisted up so the Gemini\n // path below can use it without duplicating logic.\n async function resolveApiKey(key: string): Promise<string | undefined> {\n return (await withRequestContext(() => resolveSecret(key))) ?? undefined;\n }\n\n if (transcriptText) {\n return await cleanupTranscriptText({\n event,\n text: transcriptText,\n instructions: voiceGuidance,\n contextPack: voiceContext,\n providerPref,\n hasBuilderPrivateKey,\n withRequestContext,\n resolveApiKey,\n clientAbortSignal: clientAbort,\n });\n }\n\n if (!audio?.data?.length) {\n setResponseStatus(event, 400);\n return { error: \"Missing audio payload\" };\n }\n\n const mime = audio.type || \"audio/webm\";\n const audioBytes = new Uint8Array(\n audio.data.buffer,\n audio.data.byteOffset,\n audio.data.byteLength,\n );\n\n let builderError: string | null = null;\n\n // ── Strict per-provider preferences ─────────────────────────────────\n // When the user explicitly picks a single provider (gemini / builder /\n // groq), we only try that provider and surface its error rather than\n // silently falling through. \"auto\" / undefined keeps the existing\n // fallback chain below. \"openai\" is handled by the chain (it skips\n // earlier providers and lands on the Whisper path).\n\n if (providerPref === \"gemini\") {\n const geminiKey = await resolveApiKey(\"GEMINI_API_KEY\");\n if (!geminiKey) {\n setResponseStatus(event, 400);\n return {\n error:\n \"Gemini is selected but GEMINI_API_KEY is not configured. Add it in Settings → API Keys, or change the provider preference.\",\n };\n }\n try {\n const text = await transcribeWithGemini({\n audioBytes,\n mimeType: mime,\n apiKey: geminiKey,\n language: language || undefined,\n instructions: voiceGuidance,\n clientAbortSignal: clientAbort,\n });\n const trimmed = applyVoiceContext(text);\n if (!trimmed) {\n setResponseStatus(event, 502);\n return { error: \"Gemini returned an empty transcript.\" };\n }\n return { text: trimmed };\n } catch (err) {\n setResponseStatus(event, 502);\n return {\n error: `Gemini transcription failed: ${(err as Error)?.message ?? String(err)}`,\n };\n }\n }\n\n if (providerPref === \"builder\" || providerPref === \"builder-gemini\") {\n const label =\n providerPref === \"builder-gemini\"\n ? \"Builder Gemini Flash-Lite\"\n : \"Builder\";\n if (!(await hasBuilderPrivateKey())) {\n setResponseStatus(event, 400);\n return {\n error: `${label} is selected but Builder.io is not connected. Connect Builder.io in Settings, or change the provider preference.`,\n };\n }\n try {\n const result = await transcribeWithBuilderForRequest({\n audioBytes,\n mimeType: mime,\n model:\n providerPref === \"builder-gemini\"\n ? BUILDER_GEMINI_TRANSCRIPTION_MODEL\n : undefined,\n language: language || undefined,\n instructions: voiceGuidance,\n });\n return { text: applyVoiceContext(result.text ?? \"\") };\n } catch (err) {\n const message = (err as Error)?.message ?? String(err);\n if (message.includes(\"credits exhausted\")) {\n setResponseStatus(event, 402);\n return { error: message };\n }\n setResponseStatus(event, 502);\n return { error: `${label} transcription failed: ${message}` };\n }\n }\n\n if (providerPref === \"groq\") {\n const groqKey = await resolveApiKey(\"GROQ_API_KEY\");\n if (!groqKey) {\n setResponseStatus(event, 400);\n return {\n error:\n \"Groq is selected but GROQ_API_KEY is not configured. Add it in Settings → API Keys, or change the provider preference.\",\n };\n }\n return await callWhisperCompat({\n event,\n provider: {\n name: \"groq\",\n endpoint: GROQ_URL,\n model: GROQ_MODEL,\n apiKey: groqKey,\n },\n audioBytes,\n mime,\n language,\n instructions: voiceGuidance,\n contextPack: voiceContext,\n clientAbortSignal: clientAbort,\n });\n }\n\n // ── Auto / undefined / openai fallback chain ────────────────────────\n\n // ── Builder Gemini Flash-Lite path ─────────────────────────────────\n // First-priority in auto mode when Builder is connected. This lets users\n // try Gemini 3.1 Flash-Lite without bringing their own Google key.\n if (providerPref !== \"openai\" && (await hasBuilderPrivateKey())) {\n try {\n const result = await transcribeWithBuilderForRequest({\n audioBytes,\n mimeType: mime,\n model: BUILDER_GEMINI_TRANSCRIPTION_MODEL,\n language: language || undefined,\n instructions: voiceGuidance,\n });\n return { text: applyVoiceContext(result.text ?? \"\") };\n } catch (err) {\n const message = (err as Error)?.message ?? String(err);\n // Surface 402 (credits exhausted) as a 402 so the client can show\n // a specific upgrade prompt.\n if (message.includes(\"credits exhausted\")) {\n setResponseStatus(event, 402);\n return { error: message };\n }\n builderError = message;\n }\n }\n\n // ── Gemini Flash Lite BYOK path ────────────────────────────────────\n // If Builder is unavailable, try a user-provided Gemini key before\n // Whisper-compatible providers.\n if (providerPref !== \"openai\") {\n const geminiKey = await resolveApiKey(\"GEMINI_API_KEY\");\n if (geminiKey) {\n try {\n const text = await transcribeWithGemini({\n audioBytes,\n mimeType: mime,\n apiKey: geminiKey,\n language: language || undefined,\n instructions: voiceGuidance,\n clientAbortSignal: clientAbort,\n });\n const trimmed = applyVoiceContext(text);\n if (trimmed) {\n console.log(`[transcribe-voice] Gemini → ${trimmed.length} chars`);\n return { text: trimmed };\n }\n console.warn(\n \"[transcribe-voice] Gemini returned empty text — falling through to next provider\",\n );\n } catch (err) {\n console.warn(\n \"[transcribe-voice] Gemini path failed, falling through:\",\n (err as Error)?.message ?? err,\n );\n }\n }\n }\n\n // If Builder is unavailable, fall through to BYOK providers rather than\n // hard-failing. This mirrors Clips' batch transcription path.\n\n // ── Groq / OpenAI Whisper-compatible path ──────────────────────────\n // (resolveApiKey is hoisted above so the Gemini path can use it too.)\n\n let provider: {\n name: \"groq\" | \"openai\";\n endpoint: string;\n model: string;\n apiKey: string;\n } | null = null;\n\n if (providerPref !== \"openai\") {\n const groqKey = await resolveApiKey(\"GROQ_API_KEY\");\n if (groqKey) {\n provider = {\n name: \"groq\",\n endpoint: GROQ_URL,\n model: GROQ_MODEL,\n apiKey: groqKey,\n };\n }\n }\n if (!provider) {\n const openaiKey = await resolveApiKey(\"OPENAI_API_KEY\");\n if (openaiKey) {\n provider = {\n name: \"openai\",\n endpoint: WHISPER_URL,\n model: OPENAI_MODEL,\n apiKey: openaiKey,\n };\n }\n }\n\n if (!provider) {\n setResponseStatus(event, builderError ? 502 : 400);\n return {\n error: builderError\n ? `Builder transcription failed: ${builderError}. Add GEMINI_API_KEY, GROQ_API_KEY, or OPENAI_API_KEY in Settings → API Keys to enable a fallback provider.`\n : \"No voice transcription provider configured. Connect Builder.io or add GEMINI_API_KEY / GROQ_API_KEY / OPENAI_API_KEY in Settings → API Keys.\",\n };\n }\n\n return await callWhisperCompat({\n event,\n provider,\n audioBytes,\n mime,\n language,\n instructions: voiceGuidance,\n contextPack: voiceContext,\n clientAbortSignal: clientAbort,\n });\n });\n}\n\n/**\n * Posts the audio to a Whisper-compatible OpenAI-style endpoint (Groq or\n * OpenAI itself) and returns `{ text }` / `{ error }` shaped like the\n * other branches in `createTranscribeVoiceHandler`. Hoisted so the\n * strict-Groq preference path and the auto fallback chain share one\n * implementation.\n */\nasync function callWhisperCompat({\n event,\n provider,\n audioBytes,\n mime,\n language,\n instructions,\n contextPack,\n clientAbortSignal,\n}: {\n event: H3Event;\n provider: {\n name: \"groq\" | \"openai\";\n endpoint: string;\n model: string;\n apiKey: string;\n };\n audioBytes: Uint8Array;\n mime: string;\n language?: string;\n instructions?: string;\n contextPack?: VoiceContextPack;\n clientAbortSignal?: AbortSignal;\n}): Promise<{ text: string } | { error: string }> {\n const ext = pickExtension(mime);\n const filename = `composer-voice.${ext}`;\n\n const form = new FormData();\n form.append(\n \"file\",\n new Blob([audioBytes as BlobPart], { type: mime }),\n filename,\n );\n form.append(\"model\", provider.model);\n form.append(\"response_format\", \"json\");\n if (language) form.append(\"language\", language);\n if (instructions) form.append(\"prompt\", instructions);\n\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 45_000);\n try {\n const res = await fetch(provider.endpoint, {\n method: \"POST\",\n headers: { Authorization: `Bearer ${provider.apiKey}` },\n body: form,\n signal: withClientAbort(controller.signal, clientAbortSignal),\n });\n if (!res.ok) {\n const text = await res.text().catch(() => \"\");\n setResponseStatus(event, res.status === 401 ? 401 : 502);\n return {\n error:\n res.status === 401\n ? `${provider.name} rejected the API key. Update it in Settings → API Keys.`\n : `${provider.name} transcription error ${res.status}: ${text.slice(0, 300)}`,\n };\n }\n const data = (await res.json()) as { text?: string };\n return {\n text: applyVoiceContextReplacements(\n (data.text ?? \"\").trim(),\n contextPack,\n ).trim(),\n };\n } catch (err) {\n setResponseStatus(event, 502);\n return {\n error:\n (err as Error)?.name === \"AbortError\"\n ? `${provider.name} transcription timed out after 45 seconds.`\n : `Could not reach ${provider.name}: ${(err as Error)?.message ?? err}`,\n };\n } finally {\n clearTimeout(timeout);\n }\n}\n\nasync function cleanupTranscriptText({\n event,\n text,\n instructions,\n contextPack,\n providerPref,\n hasBuilderPrivateKey,\n withRequestContext,\n resolveApiKey,\n clientAbortSignal,\n}: {\n event: H3Event;\n text: string;\n instructions?: string;\n contextPack?: VoiceContextPack;\n providerPref?: string;\n hasBuilderPrivateKey: () => Promise<boolean>;\n withRequestContext: <T>(fn: () => Promise<T>) => Promise<T>;\n resolveApiKey: (key: string) => Promise<string | undefined>;\n clientAbortSignal?: AbortSignal;\n}): Promise<{ text: string } | { error: string }> {\n const original = text.trim();\n if (!original) return { text: \"\" };\n const finalizeText = (value: string) =>\n applyVoiceContextReplacements(value || original, contextPack).trim();\n\n if (providerPref === \"browser\") {\n return { text: finalizeText(original) };\n }\n\n if (providerPref === \"builder\" || providerPref === \"builder-gemini\") {\n if (!(await hasBuilderPrivateKey())) {\n setResponseStatus(event, 400);\n return {\n error:\n \"Builder.io cleanup is selected but Builder.io is not connected. Connect Builder.io in Settings, or change the provider preference.\",\n };\n }\n try {\n const cleaned = await withRequestContext(() =>\n cleanupWithBuilder({ text: original, instructions, clientAbortSignal }),\n );\n return { text: finalizeText(cleaned || original) };\n } catch (err) {\n setResponseStatus(event, 502);\n return {\n error: `Builder.io cleanup failed: ${(err as Error)?.message ?? String(err)}`,\n };\n }\n }\n\n if (providerPref === \"gemini\") {\n const geminiKey = await resolveApiKey(\"GEMINI_API_KEY\");\n if (!geminiKey) {\n setResponseStatus(event, 400);\n return {\n error:\n \"Gemini cleanup is selected but GEMINI_API_KEY is not configured.\",\n };\n }\n try {\n const cleaned = await cleanupWithGemini({\n text: original,\n apiKey: geminiKey,\n instructions,\n clientAbortSignal,\n });\n return { text: finalizeText(cleaned || original) };\n } catch (err) {\n setResponseStatus(event, 502);\n return {\n error: `Gemini cleanup failed: ${(err as Error)?.message ?? String(err)}`,\n };\n }\n }\n\n if (providerPref === \"openai\" || providerPref === \"groq\") {\n const keyName =\n providerPref === \"openai\" ? \"OPENAI_API_KEY\" : \"GROQ_API_KEY\";\n const apiKey = await resolveApiKey(keyName);\n if (!apiKey) {\n setResponseStatus(event, 400);\n return {\n error: `${providerPref} cleanup is selected but ${keyName} is not configured.`,\n };\n }\n try {\n const cleaned = await cleanupWithChatProvider({\n provider: providerPref,\n text: original,\n apiKey,\n instructions,\n clientAbortSignal,\n });\n return { text: finalizeText(cleaned || original) };\n } catch (err) {\n setResponseStatus(event, 502);\n return {\n error: `${providerPref} cleanup failed: ${(err as Error)?.message ?? String(err)}`,\n };\n }\n }\n\n if (await hasBuilderPrivateKey()) {\n try {\n const cleaned = await withRequestContext(() =>\n cleanupWithBuilder({ text: original, instructions, clientAbortSignal }),\n );\n if (cleaned) return { text: finalizeText(cleaned) };\n } catch {\n // Fall through to BYOK providers, then raw text.\n }\n }\n\n const geminiKey = await resolveApiKey(\"GEMINI_API_KEY\");\n if (geminiKey) {\n try {\n const cleaned = await cleanupWithGemini({\n text: original,\n apiKey: geminiKey,\n instructions,\n clientAbortSignal,\n });\n if (cleaned) return { text: finalizeText(cleaned) };\n } catch {\n // Fall through.\n }\n }\n\n const groqKey = await resolveApiKey(\"GROQ_API_KEY\");\n if (groqKey) {\n try {\n const cleaned = await cleanupWithChatProvider({\n provider: \"groq\",\n text: original,\n apiKey: groqKey,\n instructions,\n clientAbortSignal,\n });\n if (cleaned) return { text: finalizeText(cleaned) };\n } catch {\n // Fall through.\n }\n }\n\n const openaiKey = await resolveApiKey(\"OPENAI_API_KEY\");\n if (openaiKey) {\n try {\n const cleaned = await cleanupWithChatProvider({\n provider: \"openai\",\n text: original,\n apiKey: openaiKey,\n instructions,\n clientAbortSignal,\n });\n if (cleaned) return { text: finalizeText(cleaned) };\n } catch {\n // Fall through.\n }\n }\n\n return { text: finalizeText(original) };\n}\n\nasync function cleanupWithBuilder({\n text,\n instructions,\n clientAbortSignal,\n}: {\n text: string;\n instructions?: string;\n clientAbortSignal?: AbortSignal;\n}): Promise<string> {\n const engine = createBuilderEngine();\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 8_000);\n let streamedText = \"\";\n let finalText = \"\";\n let terminalError: string | undefined;\n try {\n for await (const event of engine.stream({\n model: BUILDER_GEMINI_TRANSCRIPTION_MODEL,\n systemPrompt: buildCleanupSystemPrompt(instructions),\n messages: [\n {\n role: \"user\",\n content: [{ type: \"text\", text: buildCleanupUserPrompt(text) }],\n },\n ],\n tools: [],\n abortSignal: withClientAbort(controller.signal, clientAbortSignal),\n maxOutputTokens: Math.min(4096, Math.max(512, text.length * 2)),\n temperature: 0,\n })) {\n if (event.type === \"text-delta\") streamedText += event.text;\n if (event.type === \"assistant-content\") {\n finalText = event.parts\n .filter((part) => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\")\n .trim();\n }\n if (event.type === \"stop\" && event.reason === \"error\") {\n terminalError = event.error ?? \"Builder gateway returned an error\";\n }\n }\n } finally {\n clearTimeout(timeout);\n }\n if (terminalError) throw new Error(terminalError);\n return stripTranscriptEnvelope(finalText || streamedText);\n}\n\nasync function cleanupWithGemini({\n text,\n apiKey,\n instructions,\n clientAbortSignal,\n}: {\n text: string;\n apiKey: string;\n instructions?: string;\n clientAbortSignal?: AbortSignal;\n}): Promise<string> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 8_000);\n try {\n const res = await fetch(GEMINI_URL, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-goog-api-key\": apiKey,\n },\n body: JSON.stringify({\n contents: [\n {\n parts: [\n { text: buildCleanupSystemPrompt(instructions) },\n { text: buildCleanupUserPrompt(text) },\n ],\n },\n ],\n generationConfig: { temperature: 0 },\n }),\n signal: withClientAbort(controller.signal, clientAbortSignal),\n });\n if (!res.ok) {\n const body = await res.text().catch(() => \"\");\n throw new Error(`Gemini ${res.status}: ${body.slice(0, 300)}`);\n }\n const data = (await res.json()) as {\n candidates?: Array<{\n content?: { parts?: Array<{ text?: string }> };\n }>;\n };\n const cleaned = data.candidates?.[0]?.content?.parts\n ?.map((p) => p.text ?? \"\")\n .join(\"\")\n .trim();\n return stripTranscriptEnvelope(cleaned ?? \"\");\n } finally {\n clearTimeout(timeout);\n }\n}\n\nasync function cleanupWithChatProvider({\n provider,\n text,\n apiKey,\n instructions,\n clientAbortSignal,\n}: {\n provider: \"openai\" | \"groq\";\n text: string;\n apiKey: string;\n instructions?: string;\n clientAbortSignal?: AbortSignal;\n}): Promise<string> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 8_000);\n const endpoint = provider === \"openai\" ? OPENAI_CHAT_URL : GROQ_CHAT_URL;\n const model =\n provider === \"openai\" ? OPENAI_CLEANUP_MODEL : GROQ_CLEANUP_MODEL;\n try {\n const res = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n model,\n messages: [\n { role: \"system\", content: buildCleanupSystemPrompt(instructions) },\n { role: \"user\", content: buildCleanupUserPrompt(text) },\n ],\n temperature: 0,\n }),\n signal: withClientAbort(controller.signal, clientAbortSignal),\n });\n if (!res.ok) {\n const body = await res.text().catch(() => \"\");\n throw new Error(`${provider} ${res.status}: ${body.slice(0, 300)}`);\n }\n const data = (await res.json()) as {\n choices?: Array<{ message?: { content?: string } }>;\n };\n return stripTranscriptEnvelope(\n data.choices?.[0]?.message?.content?.trim() ?? \"\",\n );\n } finally {\n clearTimeout(timeout);\n }\n}\n\nfunction pickExtension(mime: string): string {\n const lower = mime.toLowerCase();\n if (lower.includes(\"mp4\") || lower.includes(\"m4a\")) return \"mp4\";\n if (lower.includes(\"mpeg\") || lower.includes(\"mp3\")) return \"mp3\";\n if (lower.includes(\"ogg\")) return \"ogg\";\n if (lower.includes(\"wav\")) return \"wav\";\n return \"webm\";\n}\n\nfunction sanitizeInstructions(value: string): string | undefined {\n const trimmed = value.replace(/\\0/g, \"\").trim();\n if (!trimmed) return undefined;\n return trimmed.slice(0, 3000);\n}\n\nfunction sanitizeTranscriptText(value: string): string | undefined {\n const trimmed = value.replace(/\\0/g, \"\").trim();\n if (!trimmed) return undefined;\n if (trimmed.length <= MAX_TRANSCRIPT_CHARS) return trimmed;\n // Truncate the middle rather than the tail — losing the end of a long\n // dictation silently (previous behavior) is worse than losing the middle,\n // since users notice a cut-off ending immediately but rarely proofread\n // the entire cleaned output against the original.\n console.warn(\n `[transcribe-voice] transcript truncated: ${trimmed.length} chars exceeds ${MAX_TRANSCRIPT_CHARS} cap`,\n );\n const marker = \"\\n[... transcript truncated ...]\\n\";\n const keepChars = MAX_TRANSCRIPT_CHARS - marker.length;\n const headChars = Math.floor((keepChars * 2) / 3);\n const tailChars = keepChars - headChars;\n return (\n trimmed.slice(0, headChars) +\n marker +\n trimmed.slice(trimmed.length - tailChars)\n );\n}\n\nfunction buildCleanupSystemPrompt(instructions?: string): string {\n const custom = instructions\n ? `\\n\\nUser's custom cleanup instructions:\\n${instructions}`\n : \"\";\n return `You clean up live speech-recognition transcripts before paste.\n\nRules:\n- Preserve the speaker's meaning and voice.\n- Fix obvious recognition mistakes, punctuation, capitalization, spacing, and casing.\n- Remove false starts and filler only when they are clearly not intentional.\n- Do not add facts, explanations, headings, bullets, quotes, or markdown.\n- Output only the cleaned transcript text.${custom}`;\n}\n\nfunction buildCleanupUserPrompt(text: string): string {\n return `Clean up this transcript and return only the final text:\\n\\n<transcript>\\n${text}\\n</transcript>`;\n}\n\nfunction stripTranscriptEnvelope(value: string): string {\n return value\n .trim()\n .replace(/^```(?:text)?\\s*/i, \"\")\n .replace(/\\s*```$/i, \"\")\n .replace(/^[\"“](.*)[\"”]$/s, \"$1\")\n .trim();\n}\n\nfunction buildGeminiTranscriptionPrompt({\n language,\n instructions,\n}: {\n language?: string;\n instructions?: string;\n}): string {\n const base = language\n ? `Transcribe the speech in this audio (language: ${language}).`\n : \"Transcribe the speech in this audio.\";\n const custom = instructions\n ? `\\n\\nAdditional user instructions for transcription cleanup:\\n${instructions}\\n\\nApply these only to formatting, casing, punctuation, vocabulary, and cleanup. Do not add content that is not present in the audio.`\n : \"\";\n return `${base} Output only the transcript text — no preamble, no quotes, no formatting.${custom}`;\n}\n\n/**\n * Transcribe audio via Gemini Flash Lite.\n *\n * Gemini accepts the audio inline as base64 alongside a text prompt; we\n * ask for just the transcript with no preamble. 30s timeout — Gemini is\n * fast and we'd rather fall through to Whisper than wait longer.\n *\n * Gemini's documented audio formats are WAV / MP3 / AIFF / AAC / OGG /\n * FLAC — webm/opus is not officially supported but in practice it\n * accepts webm too. If Gemini rejects it the caller falls through.\n */\nasync function transcribeWithGemini({\n audioBytes,\n mimeType,\n apiKey,\n language,\n instructions,\n clientAbortSignal,\n}: {\n audioBytes: Uint8Array;\n mimeType: string;\n apiKey: string;\n language?: string;\n instructions?: string;\n clientAbortSignal?: AbortSignal;\n}): Promise<string> {\n const base64 = uint8ArrayToBase64(audioBytes);\n const prompt = buildGeminiTranscriptionPrompt({ language, instructions });\n\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 30_000);\n try {\n const res = await fetch(GEMINI_URL, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-goog-api-key\": apiKey,\n },\n body: JSON.stringify({\n contents: [\n {\n parts: [\n { text: prompt },\n {\n inlineData: {\n mimeType: normalizeAudioMimeForGemini(mimeType),\n data: base64,\n },\n },\n ],\n },\n ],\n // Keep generation tight — we want the transcript verbatim, no\n // creative reinterpretation.\n generationConfig: { temperature: 0 },\n }),\n signal: withClientAbort(controller.signal, clientAbortSignal),\n });\n if (!res.ok) {\n const body = await res.text().catch(() => \"\");\n throw new Error(`Gemini ${res.status}: ${body.slice(0, 300)}`);\n }\n const data = (await res.json()) as {\n candidates?: Array<{\n content?: { parts?: Array<{ text?: string }> };\n }>;\n };\n const text = data.candidates?.[0]?.content?.parts\n ?.map((p) => p.text ?? \"\")\n .join(\"\")\n .trim();\n return text ?? \"\";\n } finally {\n clearTimeout(timeout);\n }\n}\n\nfunction normalizeAudioMimeForGemini(mime: string): string {\n // Strip codec parameters — Gemini doesn't need them and some variants\n // (e.g. \"audio/webm;codecs=opus\") are rejected as unknown.\n const lower = mime.toLowerCase().split(\";\")[0].trim();\n if (!lower) return \"audio/webm\";\n return lower;\n}\n\nfunction uint8ArrayToBase64(bytes: Uint8Array): string {\n if (typeof Buffer !== \"undefined\") {\n return Buffer.from(bytes).toString(\"base64\");\n }\n // Fallback for non-Node runtimes — chunk to avoid stack overflow.\n let binary = \"\";\n const chunk = 0x8000;\n for (let i = 0; i < bytes.length; i += chunk) {\n binary += String.fromCharCode(\n ...bytes.subarray(i, Math.min(i + chunk, bytes.length)),\n );\n }\n return btoa(binary);\n}\n"]}
1
+ {"version":3,"file":"transcribe-voice.js","sourceRoot":"","sources":["../../src/server/transcribe-voice.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EACL,kBAAkB,EAClB,SAAS,EACT,qBAAqB,EACrB,iBAAiB,GAElB,MAAM,IAAI,CAAC;AAEZ,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AACxE,OAAO,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAClF,OAAO,EACL,6BAA6B,EAC7B,u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IAAI,EAAE,CAAC;IACtD,IAAI,CAAC,KAAK;QAAE,OAAO,YAAY,CAAC;IAChC,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,kBAAkB,CAAC,KAAiB;IAC3C,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE,CAAC;QAClC,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IAC/C,CAAC;IACD,kEAAkE;IAClE,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,MAAM,KAAK,GAAG,MAAM,CAAC;IACrB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,IAAI,KAAK,EAAE,CAAC;QAC7C,MAAM,IAAI,MAAM,CAAC,YAAY,CAC3B,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,KAAK,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,CACxD,CAAC;IACJ,CAAC;IACD,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC;AACtB,CAAC","sourcesContent":["/**\n * POST /_agent-native/transcribe-voice\n *\n * Receives an audio blob from the agent sidebar composer and forwards it to\n * the configured transcription provider. Returns `{ text }` on success,\n * `{ error }` on failure.\n *\n * Key resolution order for BYOK providers:\n * 1. Request-scoped encrypted secret (`app_secrets`: user, org, workspace).\n * 2. Env var fallback only outside authenticated request contexts.\n *\n * If no server provider is configured, returns 400 with an error the\n * composer UI can surface (the client falls back to Web Speech when possible).\n *\n * This is a framework route rather than a `defineAction` because multipart\n * audio bodies aren't a clean fit for the action contract (actions are\n * typed JSON-in / JSON-out).\n */\n\nimport {\n defineEventHandler,\n getMethod,\n readMultipartFormData,\n setResponseStatus,\n type H3Event,\n} from \"h3\";\n\nimport { createBuilderEngine } from \"../agent/engine/builder-engine.js\";\nimport { appStateGet } from \"../application-state/store.js\";\nimport { getOrgContext } from \"../org/context.js\";\nimport { transcribeWithBuilder } from \"../transcription/builder-transcription.js\";\nimport {\n applyVoiceContextReplacements,\n buildVoiceGuidanceBlock,\n parseVoiceContextPack,\n voiceContextTermsOnly,\n type VoiceContextPack,\n} from \"../voice/index.js\";\nimport { getSession } from \"./auth.js\";\nimport {\n resolveHasBuilderPrivateKey,\n resolveSecret,\n} from \"./credential-provider.js\";\nimport { runWithRequestContext } from \"./request-context.js\";\nimport { isSameOriginRequest } from \"./request-origin.js\";\n\nconst WHISPER_URL = \"https://api.openai.com/v1/audio/transcriptions\";\nconst GROQ_URL = \"https://api.groq.com/openai/v1/audio/transcriptions\";\nconst GROQ_CHAT_URL = \"https://api.groq.com/openai/v1/chat/completions\";\nconst GROQ_MODEL = \"whisper-large-v3-turbo\";\nconst GROQ_CLEANUP_MODEL = \"llama-3.3-70b-versatile\";\nconst OPENAI_MODEL = \"whisper-1\";\nconst OPENAI_CHAT_URL = \"https://api.openai.com/v1/chat/completions\";\nconst OPENAI_CLEANUP_MODEL = \"gpt-5.6-luna\";\nconst MAX_AUDIO_BYTES = 25 * 1024 * 1024; // Whisper hard limit.\n// Hard cap for the dictation-cleanup text path (`sanitizeTranscriptText`\n// below). This endpoint has no `task` field — it's always the Hold-Fn\n// dictation cleanup pass — but a long session (many minutes across\n// multiple pause-triggered final segments) can still exceed a tight cap.\n// 150k gives real headroom for a long dictation session while still\n// bounding worst-case request size; truncation (when it does happen) keeps\n// both ends of the text instead of silently dropping the tail.\nconst MAX_TRANSCRIPT_CHARS = 150_000;\n// Public Builder transcription model id. The Builder gateway maps this to\n// Gemini 3.1 Flash-Lite.\nconst BUILDER_GEMINI_TRANSCRIPTION_MODEL = \"gemini-3-1-flash-lite\";\n\n// Gemini Flash Lite BYOK path when GEMINI_API_KEY is configured.\n// Gemini accepts inline audio; we just give it the bytes and a \"transcribe\n// this\" prompt and it replies with text. 2.5x faster TTFT than 2.5 Flash\n// per Google's release notes, and noticeably snappier than the Whisper\n// round-trip even on a fast connection.\n// Keep the direct Google AI path on a stable public model id; Builder's\n// managed provider above handles the newer Gemini 3.1 Flash-Lite preview.\nconst GEMINI_MODEL = \"gemini-2.0-flash-lite\";\nconst GEMINI_URL = `https://generativelanguage.googleapis.com/v1beta/models/${GEMINI_MODEL}:generateContent`;\n\n/**\n * Derive an AbortSignal that fires when the client disconnects mid-request\n * (e.g. the desktop client's own 8s ceiling firing before a provider call's\n * longer timeout). Without this, an abandoned client connection leaves the\n * server-side provider fetch running for its full timeout, burning provider\n * quota/cost on a response nobody will read. `req.on(\"close\", ...)` fires on\n * abnormal/early disconnect in Node's http server; a stray fire after normal\n * completion is a harmless no-op since the response has already been sent.\n * Returns undefined if the underlying Node request isn't available (e.g. a\n * non-Node adapter), so callers fall back to their existing timeout-only\n * signal.\n */\nfunction clientDisconnectSignal(event: H3Event): AbortSignal | undefined {\n const req = event.node?.req as\n | (NodeJS.EventEmitter & { on?: (...args: any[]) => void })\n | undefined;\n if (!req?.on) return undefined;\n const controller = new AbortController();\n req.on(\"close\", () => controller.abort());\n return controller.signal;\n}\n\n/** Combine a provider call's own timeout signal with the request's optional\n * client-disconnect signal so either one aborts the upstream fetch. */\nfunction withClientAbort(\n timeoutSignal: AbortSignal,\n clientAbortSignal?: AbortSignal,\n): AbortSignal {\n return clientAbortSignal\n ? AbortSignal.any([timeoutSignal, clientAbortSignal])\n : timeoutSignal;\n}\n\nexport function createTranscribeVoiceHandler() {\n return defineEventHandler(async (event: H3Event) => {\n if (getMethod(event) !== \"POST\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n if (!isSameOriginRequest(event)) {\n setResponseStatus(event, 403);\n return { error: \"Cross-origin request rejected\" };\n }\n\n // One client-disconnect signal per request, threaded into every\n // provider-fetch AbortController below via AbortSignal.any so a client\n // giving up early aborts the same upstream fetch instead of leaving it\n // running for its full timeout.\n const clientAbort = clientDisconnectSignal(event);\n\n const parts = await readMultipartFormData(event).catch(() => null);\n const audio = parts?.find((p) => p.name === \"audio\");\n const textPart = parts?.find((p) => p.name === \"text\");\n const transcriptText = textPart?.data\n ? sanitizeTranscriptText(Buffer.from(textPart.data).toString(\"utf8\"))\n : undefined;\n if (!audio?.data?.length && !transcriptText) {\n setResponseStatus(event, 400);\n return { error: \"Missing audio or transcript payload\" };\n }\n if (audio?.data?.length && audio.data.length > MAX_AUDIO_BYTES) {\n setResponseStatus(event, 413);\n return { error: \"Audio too large (max 25 MB)\" };\n }\n\n const languagePart = parts?.find((p) => p.name === \"language\");\n const language = languagePart?.data\n ? Buffer.from(languagePart.data).toString(\"utf8\").trim().slice(0, 8)\n : undefined;\n const instructionsPart = parts?.find((p) => p.name === \"instructions\");\n const instructions = instructionsPart?.data\n ? sanitizeInstructions(\n Buffer.from(instructionsPart.data).toString(\"utf8\"),\n )\n : undefined;\n const voiceContextPart = parts?.find(\n (p) => p.name === \"voiceContext\" || p.name === \"contextPack\",\n );\n const voiceContext = voiceContextPart?.data\n ? parseVoiceContextPack(\n Buffer.from(voiceContextPart.data).toString(\"utf8\"),\n )\n : undefined;\n const voiceGuidance = buildVoiceGuidanceBlock({\n instructions,\n contextPack: voiceContextTermsOnly(voiceContext),\n });\n const applyVoiceContext = (value: string) =>\n applyVoiceContextReplacements(value, voiceContext).trim();\n\n // Resolve provider preference. Per-request \"provider\" form field takes\n // precedence (the desktop client sends it on every dictation press),\n // falling back to the user's stored `voice-transcription-prefs` app\n // state for the agent sidebar composer / web clients that don't send\n // it explicitly.\n const session = await getSession(event).catch(() => null);\n if (!session?.email && process.env.NODE_ENV === \"production\") {\n setResponseStatus(event, 401);\n return { error: \"Authentication required\" };\n }\n const orgCtx = session?.email\n ? await getOrgContext(event).catch(() => null)\n : null;\n const requestContext = {\n userEmail: session?.email,\n orgId: orgCtx?.orgId ?? undefined,\n };\n const withRequestContext = async <T>(fn: () => Promise<T>): Promise<T> =>\n requestContext.userEmail\n ? runWithRequestContext(requestContext, fn)\n : fn();\n const hasBuilderPrivateKey = async () =>\n withRequestContext(() => resolveHasBuilderPrivateKey());\n const transcribeWithBuilderForRequest = (\n opts: Parameters<typeof transcribeWithBuilder>[0],\n ) => withRequestContext(() => transcribeWithBuilder(opts));\n const sessionId = session?.email ?? \"local\";\n let providerPref: string | undefined;\n // CRITICAL: presence of the \"provider\" form field is the explicit\n // signal that the client is making a per-request choice. Even if\n // the value is \"auto\" (→ undefined providerPref → fallback chain),\n // we must NOT fall back to app-state's stored preference — the\n // client just told us what it wants. Without this gate, a stale\n // `voice-transcription-prefs.provider = \"browser\"` in app-state\n // (from earlier testing) would override the client's \"auto\" and\n // 400 with \"Voice provider is set to browser\".\n const providerPart = parts?.find((p) => p.name === \"provider\");\n let providerExplicit = false;\n if (providerPart?.data) {\n const v = Buffer.from(providerPart.data)\n .toString(\"utf8\")\n .trim()\n .toLowerCase();\n if (\n v === \"auto\" ||\n v === \"browser\" ||\n v === \"builder\" ||\n v === \"builder-gemini\" ||\n v === \"gemini\" ||\n v === \"openai\" ||\n v === \"groq\"\n ) {\n providerExplicit = true;\n providerPref = v === \"auto\" ? undefined : v;\n }\n }\n if (!providerExplicit) {\n try {\n const prefs = await appStateGet(sessionId, \"voice-transcription-prefs\");\n providerPref = (\n prefs as { provider?: string; value?: { provider?: string } } | null\n )?.provider;\n providerPref ??= (prefs as { value?: { provider?: string } } | null)\n ?.value?.provider;\n } catch {\n /* fall through — default to fallback chain */\n }\n }\n\n // Respect explicit \"browser\" preference — user chose Web Speech API and\n // does not want audio uploaded to any external provider. The client\n // shouldn't hit this endpoint when \"browser\" is selected; this is a\n // defense-in-depth refusal.\n if (providerPref === \"browser\" && !transcriptText) {\n setResponseStatus(event, 400);\n return {\n error:\n 'Voice provider is set to \"browser\" (Web Speech API only). Change the preference in Settings → Voice Transcription to use a server-side provider.',\n };\n }\n\n // Per-user-or-fallback API key resolution. Hoisted up so the Gemini\n // path below can use it without duplicating logic.\n async function resolveApiKey(key: string): Promise<string | undefined> {\n return (await withRequestContext(() => resolveSecret(key))) ?? undefined;\n }\n\n if (transcriptText) {\n return await cleanupTranscriptText({\n event,\n text: transcriptText,\n instructions: voiceGuidance,\n contextPack: voiceContext,\n providerPref,\n hasBuilderPrivateKey,\n withRequestContext,\n resolveApiKey,\n clientAbortSignal: clientAbort,\n });\n }\n\n if (!audio?.data?.length) {\n setResponseStatus(event, 400);\n return { error: \"Missing audio payload\" };\n }\n\n const mime = audio.type || \"audio/webm\";\n const audioBytes = new Uint8Array(\n audio.data.buffer,\n audio.data.byteOffset,\n audio.data.byteLength,\n );\n\n let builderError: string | null = null;\n\n // ── Strict per-provider preferences ─────────────────────────────────\n // When the user explicitly picks a single provider (gemini / builder /\n // groq), we only try that provider and surface its error rather than\n // silently falling through. \"auto\" / undefined keeps the existing\n // fallback chain below. \"openai\" is handled by the chain (it skips\n // earlier providers and lands on the Whisper path).\n\n if (providerPref === \"gemini\") {\n const geminiKey = await resolveApiKey(\"GEMINI_API_KEY\");\n if (!geminiKey) {\n setResponseStatus(event, 400);\n return {\n error:\n \"Gemini is selected but GEMINI_API_KEY is not configured. Add it in Settings → API Keys, or change the provider preference.\",\n };\n }\n try {\n const text = await transcribeWithGemini({\n audioBytes,\n mimeType: mime,\n apiKey: geminiKey,\n language: language || undefined,\n instructions: voiceGuidance,\n clientAbortSignal: clientAbort,\n });\n const trimmed = applyVoiceContext(text);\n if (!trimmed) {\n setResponseStatus(event, 502);\n return { error: \"Gemini returned an empty transcript.\" };\n }\n return { text: trimmed };\n } catch (err) {\n setResponseStatus(event, 502);\n return {\n error: `Gemini transcription failed: ${(err as Error)?.message ?? String(err)}`,\n };\n }\n }\n\n if (providerPref === \"builder\" || providerPref === \"builder-gemini\") {\n const label =\n providerPref === \"builder-gemini\"\n ? \"Builder Gemini Flash-Lite\"\n : \"Builder\";\n if (!(await hasBuilderPrivateKey())) {\n setResponseStatus(event, 400);\n return {\n error: `${label} is selected but Builder.io is not connected. Connect Builder.io in Settings, or change the provider preference.`,\n };\n }\n try {\n const result = await transcribeWithBuilderForRequest({\n audioBytes,\n mimeType: mime,\n model:\n providerPref === \"builder-gemini\"\n ? BUILDER_GEMINI_TRANSCRIPTION_MODEL\n : undefined,\n language: language || undefined,\n instructions: voiceGuidance,\n });\n return { text: applyVoiceContext(result.text ?? \"\") };\n } catch (err) {\n const message = (err as Error)?.message ?? String(err);\n if (message.includes(\"credits exhausted\")) {\n setResponseStatus(event, 402);\n return { error: message };\n }\n setResponseStatus(event, 502);\n return { error: `${label} transcription failed: ${message}` };\n }\n }\n\n if (providerPref === \"groq\") {\n const groqKey = await resolveApiKey(\"GROQ_API_KEY\");\n if (!groqKey) {\n setResponseStatus(event, 400);\n return {\n error:\n \"Groq is selected but GROQ_API_KEY is not configured. Add it in Settings → API Keys, or change the provider preference.\",\n };\n }\n return await callWhisperCompat({\n event,\n provider: {\n name: \"groq\",\n endpoint: GROQ_URL,\n model: GROQ_MODEL,\n apiKey: groqKey,\n },\n audioBytes,\n mime,\n language,\n instructions: voiceGuidance,\n contextPack: voiceContext,\n clientAbortSignal: clientAbort,\n });\n }\n\n // ── Auto / undefined / openai fallback chain ────────────────────────\n\n // ── Builder Gemini Flash-Lite path ─────────────────────────────────\n // First-priority in auto mode when Builder is connected. This lets users\n // try Gemini 3.1 Flash-Lite without bringing their own Google key.\n if (providerPref !== \"openai\" && (await hasBuilderPrivateKey())) {\n try {\n const result = await transcribeWithBuilderForRequest({\n audioBytes,\n mimeType: mime,\n model: BUILDER_GEMINI_TRANSCRIPTION_MODEL,\n language: language || undefined,\n instructions: voiceGuidance,\n });\n return { text: applyVoiceContext(result.text ?? \"\") };\n } catch (err) {\n const message = (err as Error)?.message ?? String(err);\n // Surface 402 (credits exhausted) as a 402 so the client can show\n // a specific upgrade prompt.\n if (message.includes(\"credits exhausted\")) {\n setResponseStatus(event, 402);\n return { error: message };\n }\n builderError = message;\n }\n }\n\n // ── Gemini Flash Lite BYOK path ────────────────────────────────────\n // If Builder is unavailable, try a user-provided Gemini key before\n // Whisper-compatible providers.\n if (providerPref !== \"openai\") {\n const geminiKey = await resolveApiKey(\"GEMINI_API_KEY\");\n if (geminiKey) {\n try {\n const text = await transcribeWithGemini({\n audioBytes,\n mimeType: mime,\n apiKey: geminiKey,\n language: language || undefined,\n instructions: voiceGuidance,\n clientAbortSignal: clientAbort,\n });\n const trimmed = applyVoiceContext(text);\n if (trimmed) {\n console.log(`[transcribe-voice] Gemini → ${trimmed.length} chars`);\n return { text: trimmed };\n }\n console.warn(\n \"[transcribe-voice] Gemini returned empty text — falling through to next provider\",\n );\n } catch (err) {\n console.warn(\n \"[transcribe-voice] Gemini path failed, falling through:\",\n (err as Error)?.message ?? err,\n );\n }\n }\n }\n\n // If Builder is unavailable, fall through to BYOK providers rather than\n // hard-failing. This mirrors Clips' batch transcription path.\n\n // ── Groq / OpenAI Whisper-compatible path ──────────────────────────\n // (resolveApiKey is hoisted above so the Gemini path can use it too.)\n\n let provider: {\n name: \"groq\" | \"openai\";\n endpoint: string;\n model: string;\n apiKey: string;\n } | null = null;\n\n if (providerPref !== \"openai\") {\n const groqKey = await resolveApiKey(\"GROQ_API_KEY\");\n if (groqKey) {\n provider = {\n name: \"groq\",\n endpoint: GROQ_URL,\n model: GROQ_MODEL,\n apiKey: groqKey,\n };\n }\n }\n if (!provider) {\n const openaiKey = await resolveApiKey(\"OPENAI_API_KEY\");\n if (openaiKey) {\n provider = {\n name: \"openai\",\n endpoint: WHISPER_URL,\n model: OPENAI_MODEL,\n apiKey: openaiKey,\n };\n }\n }\n\n if (!provider) {\n setResponseStatus(event, builderError ? 502 : 400);\n return {\n error: builderError\n ? `Builder transcription failed: ${builderError}. Add GEMINI_API_KEY, GROQ_API_KEY, or OPENAI_API_KEY in Settings → API Keys to enable a fallback provider.`\n : \"No voice transcription provider configured. Connect Builder.io or add GEMINI_API_KEY / GROQ_API_KEY / OPENAI_API_KEY in Settings → API Keys.\",\n };\n }\n\n return await callWhisperCompat({\n event,\n provider,\n audioBytes,\n mime,\n language,\n instructions: voiceGuidance,\n contextPack: voiceContext,\n clientAbortSignal: clientAbort,\n });\n });\n}\n\n/**\n * Posts the audio to a Whisper-compatible OpenAI-style endpoint (Groq or\n * OpenAI itself) and returns `{ text }` / `{ error }` shaped like the\n * other branches in `createTranscribeVoiceHandler`. Hoisted so the\n * strict-Groq preference path and the auto fallback chain share one\n * implementation.\n */\nasync function callWhisperCompat({\n event,\n provider,\n audioBytes,\n mime,\n language,\n instructions,\n contextPack,\n clientAbortSignal,\n}: {\n event: H3Event;\n provider: {\n name: \"groq\" | \"openai\";\n endpoint: string;\n model: string;\n apiKey: string;\n };\n audioBytes: Uint8Array;\n mime: string;\n language?: string;\n instructions?: string;\n contextPack?: VoiceContextPack;\n clientAbortSignal?: AbortSignal;\n}): Promise<{ text: string } | { error: string }> {\n const ext = pickExtension(mime);\n const filename = `composer-voice.${ext}`;\n\n const form = new FormData();\n form.append(\n \"file\",\n new Blob([audioBytes as BlobPart], { type: mime }),\n filename,\n );\n form.append(\"model\", provider.model);\n form.append(\"response_format\", \"json\");\n if (language) form.append(\"language\", language);\n if (instructions) form.append(\"prompt\", instructions);\n\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 45_000);\n try {\n const res = await fetch(provider.endpoint, {\n method: \"POST\",\n headers: { Authorization: `Bearer ${provider.apiKey}` },\n body: form,\n signal: withClientAbort(controller.signal, clientAbortSignal),\n });\n if (!res.ok) {\n const text = await res.text().catch(() => \"\");\n setResponseStatus(event, res.status === 401 ? 401 : 502);\n return {\n error:\n res.status === 401\n ? `${provider.name} rejected the API key. Update it in Settings → API Keys.`\n : `${provider.name} transcription error ${res.status}: ${text.slice(0, 300)}`,\n };\n }\n const data = (await res.json()) as { text?: string };\n return {\n text: applyVoiceContextReplacements(\n (data.text ?? \"\").trim(),\n contextPack,\n ).trim(),\n };\n } catch (err) {\n setResponseStatus(event, 502);\n return {\n error:\n (err as Error)?.name === \"AbortError\"\n ? `${provider.name} transcription timed out after 45 seconds.`\n : `Could not reach ${provider.name}: ${(err as Error)?.message ?? err}`,\n };\n } finally {\n clearTimeout(timeout);\n }\n}\n\nasync function cleanupTranscriptText({\n event,\n text,\n instructions,\n contextPack,\n providerPref,\n hasBuilderPrivateKey,\n withRequestContext,\n resolveApiKey,\n clientAbortSignal,\n}: {\n event: H3Event;\n text: string;\n instructions?: string;\n contextPack?: VoiceContextPack;\n providerPref?: string;\n hasBuilderPrivateKey: () => Promise<boolean>;\n withRequestContext: <T>(fn: () => Promise<T>) => Promise<T>;\n resolveApiKey: (key: string) => Promise<string | undefined>;\n clientAbortSignal?: AbortSignal;\n}): Promise<{ text: string } | { error: string }> {\n const original = text.trim();\n if (!original) return { text: \"\" };\n const finalizeText = (value: string) =>\n applyVoiceContextReplacements(value || original, contextPack).trim();\n\n if (providerPref === \"browser\") {\n return { text: finalizeText(original) };\n }\n\n if (providerPref === \"builder\" || providerPref === \"builder-gemini\") {\n if (!(await hasBuilderPrivateKey())) {\n setResponseStatus(event, 400);\n return {\n error:\n \"Builder.io cleanup is selected but Builder.io is not connected. Connect Builder.io in Settings, or change the provider preference.\",\n };\n }\n try {\n const cleaned = await withRequestContext(() =>\n cleanupWithBuilder({ text: original, instructions, clientAbortSignal }),\n );\n return { text: finalizeText(cleaned || original) };\n } catch (err) {\n setResponseStatus(event, 502);\n return {\n error: `Builder.io cleanup failed: ${(err as Error)?.message ?? String(err)}`,\n };\n }\n }\n\n if (providerPref === \"gemini\") {\n const geminiKey = await resolveApiKey(\"GEMINI_API_KEY\");\n if (!geminiKey) {\n setResponseStatus(event, 400);\n return {\n error:\n \"Gemini cleanup is selected but GEMINI_API_KEY is not configured.\",\n };\n }\n try {\n const cleaned = await cleanupWithGemini({\n text: original,\n apiKey: geminiKey,\n instructions,\n clientAbortSignal,\n });\n return { text: finalizeText(cleaned || original) };\n } catch (err) {\n setResponseStatus(event, 502);\n return {\n error: `Gemini cleanup failed: ${(err as Error)?.message ?? String(err)}`,\n };\n }\n }\n\n if (providerPref === \"openai\" || providerPref === \"groq\") {\n const keyName =\n providerPref === \"openai\" ? \"OPENAI_API_KEY\" : \"GROQ_API_KEY\";\n const apiKey = await resolveApiKey(keyName);\n if (!apiKey) {\n setResponseStatus(event, 400);\n return {\n error: `${providerPref} cleanup is selected but ${keyName} is not configured.`,\n };\n }\n try {\n const cleaned = await cleanupWithChatProvider({\n provider: providerPref,\n text: original,\n apiKey,\n instructions,\n clientAbortSignal,\n });\n return { text: finalizeText(cleaned || original) };\n } catch (err) {\n setResponseStatus(event, 502);\n return {\n error: `${providerPref} cleanup failed: ${(err as Error)?.message ?? String(err)}`,\n };\n }\n }\n\n if (await hasBuilderPrivateKey()) {\n try {\n const cleaned = await withRequestContext(() =>\n cleanupWithBuilder({ text: original, instructions, clientAbortSignal }),\n );\n if (cleaned) return { text: finalizeText(cleaned) };\n } catch {\n // Fall through to BYOK providers, then raw text.\n }\n }\n\n const geminiKey = await resolveApiKey(\"GEMINI_API_KEY\");\n if (geminiKey) {\n try {\n const cleaned = await cleanupWithGemini({\n text: original,\n apiKey: geminiKey,\n instructions,\n clientAbortSignal,\n });\n if (cleaned) return { text: finalizeText(cleaned) };\n } catch {\n // Fall through.\n }\n }\n\n const groqKey = await resolveApiKey(\"GROQ_API_KEY\");\n if (groqKey) {\n try {\n const cleaned = await cleanupWithChatProvider({\n provider: \"groq\",\n text: original,\n apiKey: groqKey,\n instructions,\n clientAbortSignal,\n });\n if (cleaned) return { text: finalizeText(cleaned) };\n } catch {\n // Fall through.\n }\n }\n\n const openaiKey = await resolveApiKey(\"OPENAI_API_KEY\");\n if (openaiKey) {\n try {\n const cleaned = await cleanupWithChatProvider({\n provider: \"openai\",\n text: original,\n apiKey: openaiKey,\n instructions,\n clientAbortSignal,\n });\n if (cleaned) return { text: finalizeText(cleaned) };\n } catch {\n // Fall through.\n }\n }\n\n return { text: finalizeText(original) };\n}\n\nasync function cleanupWithBuilder({\n text,\n instructions,\n clientAbortSignal,\n}: {\n text: string;\n instructions?: string;\n clientAbortSignal?: AbortSignal;\n}): Promise<string> {\n const engine = createBuilderEngine();\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 8_000);\n let streamedText = \"\";\n let finalText = \"\";\n let terminalError: string | undefined;\n try {\n for await (const event of engine.stream({\n model: BUILDER_GEMINI_TRANSCRIPTION_MODEL,\n systemPrompt: buildCleanupSystemPrompt(instructions),\n messages: [\n {\n role: \"user\",\n content: [{ type: \"text\", text: buildCleanupUserPrompt(text) }],\n },\n ],\n tools: [],\n abortSignal: withClientAbort(controller.signal, clientAbortSignal),\n maxOutputTokens: Math.min(4096, Math.max(512, text.length * 2)),\n temperature: 0,\n })) {\n if (event.type === \"text-delta\") streamedText += event.text;\n if (event.type === \"assistant-content\") {\n finalText = event.parts\n .filter((part) => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\")\n .trim();\n }\n if (event.type === \"stop\" && event.reason === \"error\") {\n terminalError = event.error ?? \"Builder gateway returned an error\";\n }\n }\n } finally {\n clearTimeout(timeout);\n }\n if (terminalError) throw new Error(terminalError);\n return stripTranscriptEnvelope(finalText || streamedText);\n}\n\nasync function cleanupWithGemini({\n text,\n apiKey,\n instructions,\n clientAbortSignal,\n}: {\n text: string;\n apiKey: string;\n instructions?: string;\n clientAbortSignal?: AbortSignal;\n}): Promise<string> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 8_000);\n try {\n const res = await fetch(GEMINI_URL, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-goog-api-key\": apiKey,\n },\n body: JSON.stringify({\n contents: [\n {\n parts: [\n { text: buildCleanupSystemPrompt(instructions) },\n { text: buildCleanupUserPrompt(text) },\n ],\n },\n ],\n generationConfig: { temperature: 0 },\n }),\n signal: withClientAbort(controller.signal, clientAbortSignal),\n });\n if (!res.ok) {\n const body = await res.text().catch(() => \"\");\n throw new Error(`Gemini ${res.status}: ${body.slice(0, 300)}`);\n }\n const data = (await res.json()) as {\n candidates?: Array<{\n content?: { parts?: Array<{ text?: string }> };\n }>;\n };\n const cleaned = data.candidates?.[0]?.content?.parts\n ?.map((p) => p.text ?? \"\")\n .join(\"\")\n .trim();\n return stripTranscriptEnvelope(cleaned ?? \"\");\n } finally {\n clearTimeout(timeout);\n }\n}\n\nasync function cleanupWithChatProvider({\n provider,\n text,\n apiKey,\n instructions,\n clientAbortSignal,\n}: {\n provider: \"openai\" | \"groq\";\n text: string;\n apiKey: string;\n instructions?: string;\n clientAbortSignal?: AbortSignal;\n}): Promise<string> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 8_000);\n const endpoint = provider === \"openai\" ? OPENAI_CHAT_URL : GROQ_CHAT_URL;\n const model =\n provider === \"openai\" ? OPENAI_CLEANUP_MODEL : GROQ_CLEANUP_MODEL;\n try {\n const res = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n model,\n messages: [\n { role: \"system\", content: buildCleanupSystemPrompt(instructions) },\n { role: \"user\", content: buildCleanupUserPrompt(text) },\n ],\n temperature: 0,\n }),\n signal: withClientAbort(controller.signal, clientAbortSignal),\n });\n if (!res.ok) {\n const body = await res.text().catch(() => \"\");\n throw new Error(`${provider} ${res.status}: ${body.slice(0, 300)}`);\n }\n const data = (await res.json()) as {\n choices?: Array<{ message?: { content?: string } }>;\n };\n return stripTranscriptEnvelope(\n data.choices?.[0]?.message?.content?.trim() ?? \"\",\n );\n } finally {\n clearTimeout(timeout);\n }\n}\n\nfunction pickExtension(mime: string): string {\n const lower = mime.toLowerCase();\n if (lower.includes(\"mp4\") || lower.includes(\"m4a\")) return \"mp4\";\n if (lower.includes(\"mpeg\") || lower.includes(\"mp3\")) return \"mp3\";\n if (lower.includes(\"ogg\")) return \"ogg\";\n if (lower.includes(\"wav\")) return \"wav\";\n return \"webm\";\n}\n\nfunction sanitizeInstructions(value: string): string | undefined {\n const trimmed = value.replace(/\\0/g, \"\").trim();\n if (!trimmed) return undefined;\n return trimmed.slice(0, 3000);\n}\n\nfunction sanitizeTranscriptText(value: string): string | undefined {\n const trimmed = value.replace(/\\0/g, \"\").trim();\n if (!trimmed) return undefined;\n if (trimmed.length <= MAX_TRANSCRIPT_CHARS) return trimmed;\n // Truncate the middle rather than the tail — losing the end of a long\n // dictation silently (previous behavior) is worse than losing the middle,\n // since users notice a cut-off ending immediately but rarely proofread\n // the entire cleaned output against the original.\n console.warn(\n `[transcribe-voice] transcript truncated: ${trimmed.length} chars exceeds ${MAX_TRANSCRIPT_CHARS} cap`,\n );\n const marker = \"\\n[... transcript truncated ...]\\n\";\n const keepChars = MAX_TRANSCRIPT_CHARS - marker.length;\n const headChars = Math.floor((keepChars * 2) / 3);\n const tailChars = keepChars - headChars;\n return (\n trimmed.slice(0, headChars) +\n marker +\n trimmed.slice(trimmed.length - tailChars)\n );\n}\n\nfunction buildCleanupSystemPrompt(instructions?: string): string {\n const custom = instructions\n ? `\\n\\nUser's custom cleanup instructions:\\n${instructions}`\n : \"\";\n return `You clean up live speech-recognition transcripts before paste.\n\nRules:\n- Preserve the speaker's meaning and voice.\n- Fix obvious recognition mistakes, punctuation, capitalization, spacing, and casing.\n- Remove false starts and filler only when they are clearly not intentional.\n- Do not add facts, explanations, headings, bullets, quotes, or markdown.\n- Output only the cleaned transcript text.${custom}`;\n}\n\nfunction buildCleanupUserPrompt(text: string): string {\n return `Clean up this transcript and return only the final text:\\n\\n<transcript>\\n${text}\\n</transcript>`;\n}\n\nfunction stripTranscriptEnvelope(value: string): string {\n return value\n .trim()\n .replace(/^```(?:text)?\\s*/i, \"\")\n .replace(/\\s*```$/i, \"\")\n .replace(/^[\"“](.*)[\"”]$/s, \"$1\")\n .trim();\n}\n\nfunction buildGeminiTranscriptionPrompt({\n language,\n instructions,\n}: {\n language?: string;\n instructions?: string;\n}): string {\n const base = language\n ? `Transcribe the speech in this audio (language: ${language}).`\n : \"Transcribe the speech in this audio.\";\n const custom = instructions\n ? `\\n\\nAdditional user instructions for transcription cleanup:\\n${instructions}\\n\\nApply these only to formatting, casing, punctuation, vocabulary, and cleanup. Do not add content that is not present in the audio.`\n : \"\";\n return `${base} Output only the transcript text — no preamble, no quotes, no formatting.${custom}`;\n}\n\n/**\n * Transcribe audio via Gemini Flash Lite.\n *\n * Gemini accepts the audio inline as base64 alongside a text prompt; we\n * ask for just the transcript with no preamble. 30s timeout — Gemini is\n * fast and we'd rather fall through to Whisper than wait longer.\n *\n * Gemini's documented audio formats are WAV / MP3 / AIFF / AAC / OGG /\n * FLAC — webm/opus is not officially supported but in practice it\n * accepts webm too. If Gemini rejects it the caller falls through.\n */\nasync function transcribeWithGemini({\n audioBytes,\n mimeType,\n apiKey,\n language,\n instructions,\n clientAbortSignal,\n}: {\n audioBytes: Uint8Array;\n mimeType: string;\n apiKey: string;\n language?: string;\n instructions?: string;\n clientAbortSignal?: AbortSignal;\n}): Promise<string> {\n const base64 = uint8ArrayToBase64(audioBytes);\n const prompt = buildGeminiTranscriptionPrompt({ language, instructions });\n\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 30_000);\n try {\n const res = await fetch(GEMINI_URL, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-goog-api-key\": apiKey,\n },\n body: JSON.stringify({\n contents: [\n {\n parts: [\n { text: prompt },\n {\n inlineData: {\n mimeType: normalizeAudioMimeForGemini(mimeType),\n data: base64,\n },\n },\n ],\n },\n ],\n // Keep generation tight — we want the transcript verbatim, no\n // creative reinterpretation.\n generationConfig: { temperature: 0 },\n }),\n signal: withClientAbort(controller.signal, clientAbortSignal),\n });\n if (!res.ok) {\n const body = await res.text().catch(() => \"\");\n throw new Error(`Gemini ${res.status}: ${body.slice(0, 300)}`);\n }\n const data = (await res.json()) as {\n candidates?: Array<{\n content?: { parts?: Array<{ text?: string }> };\n }>;\n };\n const text = data.candidates?.[0]?.content?.parts\n ?.map((p) => p.text ?? \"\")\n .join(\"\")\n .trim();\n return text ?? \"\";\n } finally {\n clearTimeout(timeout);\n }\n}\n\nfunction normalizeAudioMimeForGemini(mime: string): string {\n // Strip codec parameters — Gemini doesn't need them and some variants\n // (e.g. \"audio/webm;codecs=opus\") are rejected as unknown.\n const lower = mime.toLowerCase().split(\";\")[0].trim();\n if (!lower) return \"audio/webm\";\n return lower;\n}\n\nfunction uint8ArrayToBase64(bytes: Uint8Array): string {\n if (typeof Buffer !== \"undefined\") {\n return Buffer.from(bytes).toString(\"base64\");\n }\n // Fallback for non-Node runtimes — chunk to avoid stack overflow.\n let binary = \"\";\n const chunk = 0x8000;\n for (let i = 0; i < bytes.length; i += chunk) {\n binary += String.fromCharCode(\n ...bytes.subarray(i, Math.min(i + chunk, bytes.length)),\n );\n }\n return btoa(binary);\n}\n"]}
@@ -7,6 +7,7 @@
7
7
  "build": "agent-native build",
8
8
  "start": "agent-native start",
9
9
  "typecheck": "agent-native typecheck",
10
+ "doctor": "agent-native doctor",
10
11
  "action": "agent-native action",
11
12
  "script": "agent-native script",
12
13
  "skills:update": "agent-native skills update scaffold --project",
@@ -43,8 +44,7 @@
43
44
  "tailwind-merge": "^3.5.0",
44
45
  "tailwindcss": "^4.1.18",
45
46
  "tsx": "^4.20.3",
46
- "typescript": "catalog:",
47
47
  "typescript-7": "catalog:",
48
- "vite": "^8.0.0"
48
+ "vite": "8.1.0"
49
49
  }
50
50
  }
@@ -19,7 +19,6 @@
19
19
  "@types/node": "^24.2.1",
20
20
  "oxfmt": "catalog:",
21
21
  "tsx": "^4.20.3",
22
- "typescript": "catalog:",
23
22
  "typescript-7": "catalog:"
24
23
  }
25
24
  }
@@ -77,6 +77,9 @@ SQL to the caller — they never leak another tenant's rows:
77
77
  (`agent` | `human` | `system`), `status`, `threadId`/`turnId`, `action`,
78
78
  `sinceMs`, `limit`.
79
79
  - `get-audit-event` — one event by id, with its redacted input payload.
80
+ - `export-audit-events` — bulk CSV/NDJSON export (same filters minus `limit`,
81
+ plus `format` and `maxRows`) for offline/compliance pulls; itself audited
82
+ via `onRead`.
80
83
 
81
84
  Call them from the UI with `useActionQuery` to build an activity feed or a
82
85
  "who changed this" line — never hand-write a fetch to the audit table.
@@ -61,7 +61,7 @@ Use the web-request tool with ${keys.SLACK_WEBHOOK}.
61
61
  | `triggerType` | `"schedule" \| "event"` | How the automation fires |
62
62
  | `event` | `string?` | Event name to subscribe to (event triggers) |
63
63
  | `condition` | `string?` | Natural-language condition evaluated before dispatch |
64
- | `mode` | `"agentic" \| "deterministic"` | Full agent loop vs. fixed action set |
64
+ | `mode` | `"agentic"` | Full agent loop (only supported mode; `"deterministic"` was removed never implemented, rejected at define time) |
65
65
  | `model` | `string?` | Override the model for this trigger's agent loop |
66
66
  | `domain` | `string?` | Grouping tag (mail, calendar, clips, etc.) |
67
67
  | `createdBy` | `string?` | Owner email |
@@ -32,7 +32,6 @@
32
32
  "prepare": "tsc"
33
33
  },
34
34
  "devDependencies": {
35
- "typescript": "catalog:",
36
35
  "typescript-7": "catalog:"
37
36
  }
38
37
  }
@@ -20,7 +20,6 @@
20
20
  "@types/node": "^24.2.1",
21
21
  "oxfmt": "catalog:",
22
22
  "tsx": "catalog:",
23
- "typescript": "catalog:",
24
23
  "typescript-7": "catalog:"
25
24
  },
26
25
  "packageManager": "pnpm@10.14.0",
@@ -1 +1 @@
1
- {"version":3,"file":"actions.d.ts","sourceRoot":"","sources":["../../src/triggers/actions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAgNhE,wBAAgB,2BAA2B,CACzC,cAAc,EAAE,MAAM,MAAM,GAC3B,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAuG7B"}
1
+ {"version":3,"file":"actions.d.ts","sourceRoot":"","sources":["../../src/triggers/actions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAwNhE,wBAAgB,2BAA2B,CACzC,cAAc,EAAE,MAAM,MAAM,GAC3B,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAuG7B"}
@@ -83,6 +83,11 @@ async function handleDefine(args, getCurrentUser) {
83
83
  if (existing) {
84
84
  return `Error: An automation named "${name}" already exists. Use a different name or delete the existing one first.`;
85
85
  }
86
+ if (args.mode === "deterministic") {
87
+ return ("Error: Deterministic mode was removed — it was never implemented and " +
88
+ "automations that set it never fired. Create the automation without " +
89
+ "mode (agentic), and describe the exact fixed steps in the automation body.");
90
+ }
86
91
  const triggerType = args.trigger_type === "schedule" ? "schedule" : "event";
87
92
  const meta = {
88
93
  schedule: args.schedule || "",
@@ -90,7 +95,7 @@ async function handleDefine(args, getCurrentUser) {
90
95
  triggerType,
91
96
  event: args.event || undefined,
92
97
  condition: args.condition || undefined,
93
- mode: args.mode === "deterministic" ? "deterministic" : "agentic",
98
+ mode: "agentic",
94
99
  domain: args.domain || undefined,
95
100
  createdBy: owner,
96
101
  runAs: "creator",
@@ -205,8 +210,8 @@ export function createAutomationToolEntries(getCurrentUser) {
205
210
  },
206
211
  mode: {
207
212
  type: "string",
208
- description: '"agentic" (full agent loop, can use tools) or "deterministic" (fixed actions only). Used by define.',
209
- enum: ["agentic", "deterministic"],
213
+ description: '"agentic" (full agent loop, can use tools) the only supported mode. Used by define.',
214
+ enum: ["agentic"],
210
215
  },
211
216
  domain: {
212
217
  type: "string",