@agent-native/core 0.92.11 → 0.93.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 (777) hide show
  1. package/corpus/README.md +2 -2
  2. package/corpus/core/CHANGELOG.md +45 -0
  3. package/corpus/core/docs/content/automation-connectors.mdx +80 -0
  4. package/corpus/core/docs/content/extensions.mdx +8 -0
  5. package/corpus/core/docs/content/locales/ar-SA/extensions.mdx +8 -0
  6. package/corpus/core/docs/content/locales/ar-SA/messaging.mdx +84 -15
  7. package/corpus/core/docs/content/locales/ar-SA/template-clips.mdx +1 -0
  8. package/corpus/core/docs/content/locales/ar-SA/template-design.mdx +1 -0
  9. package/corpus/core/docs/content/locales/de-DE/extensions.mdx +10 -0
  10. package/corpus/core/docs/content/locales/de-DE/messaging.mdx +92 -15
  11. package/corpus/core/docs/content/locales/de-DE/template-clips.mdx +1 -0
  12. package/corpus/core/docs/content/locales/de-DE/template-design.mdx +1 -0
  13. package/corpus/core/docs/content/locales/es-ES/extensions.mdx +10 -0
  14. package/corpus/core/docs/content/locales/es-ES/messaging.mdx +91 -15
  15. package/corpus/core/docs/content/locales/es-ES/template-clips.mdx +1 -0
  16. package/corpus/core/docs/content/locales/es-ES/template-design.mdx +1 -0
  17. package/corpus/core/docs/content/locales/fr-FR/extensions.mdx +10 -0
  18. package/corpus/core/docs/content/locales/fr-FR/messaging.mdx +91 -15
  19. package/corpus/core/docs/content/locales/fr-FR/template-clips.mdx +1 -0
  20. package/corpus/core/docs/content/locales/fr-FR/template-design.mdx +1 -0
  21. package/corpus/core/docs/content/locales/hi-IN/extensions.mdx +8 -0
  22. package/corpus/core/docs/content/locales/hi-IN/messaging.mdx +81 -15
  23. package/corpus/core/docs/content/locales/hi-IN/template-clips.mdx +1 -0
  24. package/corpus/core/docs/content/locales/hi-IN/template-design.mdx +1 -0
  25. package/corpus/core/docs/content/locales/ja-JP/extensions.mdx +9 -0
  26. package/corpus/core/docs/content/locales/ja-JP/messaging.mdx +81 -15
  27. package/corpus/core/docs/content/locales/ja-JP/template-clips.mdx +1 -0
  28. package/corpus/core/docs/content/locales/ja-JP/template-design.mdx +1 -0
  29. package/corpus/core/docs/content/locales/ko-KR/extensions.mdx +8 -0
  30. package/corpus/core/docs/content/locales/ko-KR/messaging.mdx +80 -15
  31. package/corpus/core/docs/content/locales/ko-KR/template-clips.mdx +1 -0
  32. package/corpus/core/docs/content/locales/ko-KR/template-design.mdx +1 -0
  33. package/corpus/core/docs/content/locales/pt-BR/extensions.mdx +9 -0
  34. package/corpus/core/docs/content/locales/pt-BR/messaging.mdx +88 -15
  35. package/corpus/core/docs/content/locales/pt-BR/template-clips.mdx +1 -0
  36. package/corpus/core/docs/content/locales/pt-BR/template-design.mdx +1 -0
  37. package/corpus/core/docs/content/locales/zh-CN/extensions.mdx +6 -0
  38. package/corpus/core/docs/content/locales/zh-CN/messaging.mdx +78 -15
  39. package/corpus/core/docs/content/locales/zh-CN/template-clips.mdx +1 -0
  40. package/corpus/core/docs/content/locales/zh-CN/template-design.mdx +1 -0
  41. package/corpus/core/docs/content/locales/zh-TW/extensions.mdx +6 -0
  42. package/corpus/core/docs/content/locales/zh-TW/messaging.mdx +78 -15
  43. package/corpus/core/docs/content/locales/zh-TW/template-clips.mdx +1 -0
  44. package/corpus/core/docs/content/locales/zh-TW/template-design.mdx +1 -0
  45. package/corpus/core/docs/content/messaging.mdx +227 -45
  46. package/corpus/core/docs/content/template-clips.mdx +3 -0
  47. package/corpus/core/docs/content/template-design.mdx +4 -0
  48. package/corpus/core/package.json +5 -1
  49. package/corpus/core/src/a2a/artifact-response.ts +131 -2
  50. package/corpus/core/src/a2a/client.ts +10 -0
  51. package/corpus/core/src/a2a/handlers.ts +40 -76
  52. package/corpus/core/src/a2a/types.ts +2 -0
  53. package/corpus/core/src/agent/durable-background.ts +24 -0
  54. package/corpus/core/src/agent/production-agent.ts +48 -5
  55. package/corpus/core/src/agent/run-manager.ts +171 -20
  56. package/corpus/core/src/agent/run-store.ts +297 -42
  57. package/corpus/core/src/agent/types.ts +23 -0
  58. package/corpus/core/src/audit/record.ts +31 -0
  59. package/corpus/core/src/audit/store.ts +69 -3
  60. package/corpus/core/src/audit/types.ts +13 -0
  61. package/corpus/core/src/automation/index.ts +802 -0
  62. package/corpus/core/src/cli/create.ts +12 -5
  63. package/corpus/core/src/cli/design-connect.ts +596 -36
  64. package/corpus/core/src/client/AgentPanel.tsx +51 -6
  65. package/corpus/core/src/client/AssistantChat.tsx +274 -147
  66. package/corpus/core/src/client/MultiTabAssistantChat.tsx +3 -0
  67. package/corpus/core/src/client/RunStuckBanner.tsx +69 -20
  68. package/corpus/core/src/client/agent-chat-adapter.ts +110 -17
  69. package/corpus/core/src/client/automation.ts +22 -0
  70. package/corpus/core/src/client/chat/run-recovery.tsx +67 -50
  71. package/corpus/core/src/client/composer/TiptapComposer.tsx +8 -0
  72. package/corpus/core/src/client/index.ts +30 -0
  73. package/corpus/core/src/client/integrations/api.ts +295 -0
  74. package/corpus/core/src/client/integrations/index.ts +26 -0
  75. package/corpus/core/src/client/transcription/use-live-transcription.ts +68 -5
  76. package/corpus/core/src/client/use-run-stuck-detection.ts +41 -3
  77. package/corpus/core/src/deploy/build.ts +59 -3
  78. package/corpus/core/src/deploy/workspace-deploy.ts +37 -2
  79. package/corpus/core/src/file-upload/types.ts +2 -0
  80. package/corpus/core/src/index.ts +37 -0
  81. package/corpus/core/src/integrations/a2a-continuations-store.ts +6 -4
  82. package/corpus/core/src/integrations/adapters/discord.ts +362 -0
  83. package/corpus/core/src/integrations/adapters/index.ts +29 -0
  84. package/corpus/core/src/integrations/adapters/microsoft-teams.ts +411 -0
  85. package/corpus/core/src/integrations/adapters/slack.ts +861 -27
  86. package/corpus/core/src/integrations/adapters/telegram.ts +54 -15
  87. package/corpus/core/src/integrations/adapters/whatsapp.ts +41 -17
  88. package/corpus/core/src/integrations/catalog.ts +571 -0
  89. package/corpus/core/src/integrations/controls-store.ts +187 -0
  90. package/corpus/core/src/integrations/index.ts +100 -0
  91. package/corpus/core/src/integrations/installations-store.ts +677 -0
  92. package/corpus/core/src/integrations/integration-memory.ts +187 -0
  93. package/corpus/core/src/integrations/pending-tasks-retry-job.ts +6 -6
  94. package/corpus/core/src/integrations/pending-tasks-store.ts +83 -5
  95. package/corpus/core/src/integrations/plugin.ts +685 -47
  96. package/corpus/core/src/integrations/scope-store.ts +498 -0
  97. package/corpus/core/src/integrations/slack-manifest.ts +78 -0
  98. package/corpus/core/src/integrations/slack-oauth.ts +343 -0
  99. package/corpus/core/src/integrations/types.ts +179 -0
  100. package/corpus/core/src/integrations/usage-budget-store.ts +906 -0
  101. package/corpus/core/src/integrations/webhook-handler.ts +562 -51
  102. package/corpus/core/src/jobs/scheduler.ts +100 -2
  103. package/corpus/core/src/jobs/tools.ts +45 -9
  104. package/corpus/core/src/provider-api/index.ts +72 -1
  105. package/corpus/core/src/resources/handlers.ts +88 -14
  106. package/corpus/core/src/resources/script-helpers.ts +36 -7
  107. package/corpus/core/src/resources/store.ts +59 -52
  108. package/corpus/core/src/scripts/call-agent.ts +107 -1
  109. package/corpus/core/src/server/agent-chat-plugin.ts +294 -119
  110. package/corpus/core/src/server/auth.ts +10 -14
  111. package/corpus/core/src/server/builder-design-systems.ts +16 -1
  112. package/corpus/core/src/server/edge.ts +18 -0
  113. package/corpus/core/src/server/index.ts +26 -0
  114. package/corpus/core/src/server/request-context.ts +18 -0
  115. package/corpus/core/src/server/social-og-image.ts +3 -2
  116. package/corpus/core/src/styles/agent-native.css +62 -44
  117. package/corpus/core/src/templates/default/.agents/skills/capture-learnings/SKILL.md +22 -9
  118. package/corpus/core/src/templates/default/AGENTS.md +7 -3
  119. package/corpus/core/src/templates/workspace-core/.agents/skills/authentication/SKILL.md +1 -1
  120. package/corpus/core/src/templates/workspace-core/.agents/skills/capture-learnings/SKILL.md +22 -9
  121. package/corpus/core/src/templates/workspace-core/.agents/skills/extension-points/SKILL.md +6 -3
  122. package/corpus/core/src/templates/workspace-core/.agents/skills/extensions/SKILL.md +25 -0
  123. package/corpus/core/src/templates/workspace-core/.agents/skills/integration-webhooks/SKILL.md +15 -0
  124. package/corpus/core/src/templates/workspace-core/AGENTS.md +3 -2
  125. package/corpus/core/src/usage/store.ts +37 -2
  126. package/corpus/templates/analytics/.agents/skills/capture-learnings/SKILL.md +22 -9
  127. package/corpus/templates/analytics/.agents/skills/provider-api/SKILL.md +23 -0
  128. package/corpus/templates/analytics/.builder/skills/provider-api/SKILL.md +15 -0
  129. package/corpus/templates/analytics/actions/save-monitor.ts +25 -2
  130. package/corpus/templates/analytics/app/lib/data-sources.ts +28 -0
  131. package/corpus/templates/analytics/changelog/2026-07-10-agent-created-uptime-monitors-now-return-a-direct-link-to-th.md +6 -0
  132. package/corpus/templates/analytics/changelog/2026-07-10-dashboard-email-reports-still-arrive-when-screenshot-capture-temporarily-fails.md +6 -0
  133. package/corpus/templates/analytics/server/jobs/dashboard-report.ts +3 -7
  134. package/corpus/templates/analytics/server/lib/credential-keys.ts +12 -0
  135. package/corpus/templates/analytics/server/lib/dashboard-report.ts +5 -1
  136. package/corpus/templates/analytics/server/lib/provider-credentials.ts +2 -0
  137. package/corpus/templates/analytics/server/routes/api/test-connection.post.ts +16 -0
  138. package/corpus/templates/assets/.agents/skills/capture-learnings/SKILL.md +22 -9
  139. package/corpus/templates/brain/.agents/skills/capture-learnings/SKILL.md +22 -9
  140. package/corpus/templates/calendar/.agents/skills/capture-learnings/SKILL.md +22 -9
  141. package/corpus/templates/calendar/app/components/calendar/CommandPalette.tsx +98 -108
  142. package/corpus/templates/calendar/app/components/calendar/EventAttendeesSection.tsx +97 -90
  143. package/corpus/templates/calendar/changelog/2026-07-10-event-guest-details-and-option-menus-now-use-valid-accessibl.md +6 -0
  144. package/corpus/templates/calendar/changelog/2026-07-10-natural-language-event-phrases-stay-available-as-quick-creat.md +6 -0
  145. package/corpus/templates/chat/.agents/skills/capture-learnings/SKILL.md +22 -9
  146. package/corpus/templates/chat/changelog/2026-07-10-chat-now-makes-ai-connection-setup-clear-without-shifting-th.md +6 -0
  147. package/corpus/templates/clips/.agents/skills/capture-learnings/SKILL.md +22 -9
  148. package/corpus/templates/clips/.agents/skills/recording/SKILL.md +17 -1
  149. package/corpus/templates/clips/.agents/skills/video-sharing/SKILL.md +8 -0
  150. package/corpus/templates/clips/AGENTS.md +8 -3
  151. package/corpus/templates/clips/actions/finalize-recording.ts +63 -23
  152. package/corpus/templates/clips/actions/get-recording-player-data.ts +6 -2
  153. package/corpus/templates/clips/actions/lib/ensure-seekable-video.ts +72 -9
  154. package/corpus/templates/clips/actions/list-recordings.ts +19 -3
  155. package/corpus/templates/clips/actions/navigate.ts +2 -0
  156. package/corpus/templates/clips/actions/reprocess-recording.ts +20 -6
  157. package/corpus/templates/clips/actions/request-transcript.ts +16 -31
  158. package/corpus/templates/clips/actions/view-screen.ts +57 -5
  159. package/corpus/templates/clips/app/components/layout/Header.tsx +1 -0
  160. package/corpus/templates/clips/app/components/library/empty-state.tsx +2 -0
  161. package/corpus/templates/clips/app/components/library/library-grid.tsx +69 -42
  162. package/corpus/templates/clips/app/components/library/library-layout.tsx +15 -1
  163. package/corpus/templates/clips/app/components/library/recording-card.tsx +81 -68
  164. package/corpus/templates/clips/app/components/library/search-bar.tsx +4 -3
  165. package/corpus/templates/clips/app/components/player/delete-recording-menu.tsx +9 -3
  166. package/corpus/templates/clips/app/components/player/share-dialog.tsx +1 -1
  167. package/corpus/templates/clips/app/components/player/transcript-panel.tsx +27 -5
  168. package/corpus/templates/clips/app/hooks/use-library.ts +1 -1
  169. package/corpus/templates/clips/app/hooks/use-navigation-state.ts +10 -2
  170. package/corpus/templates/clips/app/hooks/use-player-shortcuts.ts +1 -0
  171. package/corpus/templates/clips/app/i18n/ar-SA.ts +7 -1
  172. package/corpus/templates/clips/app/i18n/de-DE.ts +7 -1
  173. package/corpus/templates/clips/app/i18n/en-US.ts +7 -1
  174. package/corpus/templates/clips/app/i18n/es-ES.ts +7 -1
  175. package/corpus/templates/clips/app/i18n/fr-FR.ts +7 -1
  176. package/corpus/templates/clips/app/i18n/hi-IN.ts +7 -1
  177. package/corpus/templates/clips/app/i18n/ja-JP.ts +7 -1
  178. package/corpus/templates/clips/app/i18n/ko-KR.ts +7 -1
  179. package/corpus/templates/clips/app/i18n/pt-BR.ts +7 -1
  180. package/corpus/templates/clips/app/i18n/zh-CN.ts +8 -1
  181. package/corpus/templates/clips/app/i18n/zh-TW.ts +8 -1
  182. package/corpus/templates/clips/app/lib/recording-visibility.ts +70 -0
  183. package/corpus/templates/clips/app/routes/_app.shared.tsx +20 -0
  184. package/corpus/templates/clips/app/routes/download.tsx +24 -8
  185. package/corpus/templates/clips/app/routes/r.$recordingId.tsx +115 -2
  186. package/corpus/templates/clips/app/routes/record.tsx +62 -0
  187. package/corpus/templates/clips/app/routes/share.$shareId.tsx +25 -16
  188. package/corpus/templates/clips/changelog/2026-07-10-clips-desktop-is-now-available-for-linux-with-appimage-debia.md +6 -0
  189. package/corpus/templates/clips/changelog/2026-07-10-clips-downloads-updates-sooner-in-the-background-and-offers-.md +6 -0
  190. package/corpus/templates/clips/changelog/2026-07-10-clips-shared-with-you-now-appear-in-a-searchable-shared-with.md +6 -0
  191. package/corpus/templates/clips/changelog/2026-07-10-clips-with-missing-mobile-video-frames-can-be-repaired-witho.md +6 -0
  192. package/corpus/templates/clips/changelog/2026-07-10-fixed-copying-agent-responses-and-transcript-text-from-recor.md +6 -0
  193. package/corpus/templates/clips/changelog/2026-07-10-mobile-camera-recordings-pause-while-backgrounded.md +6 -0
  194. package/corpus/templates/clips/changelog/2026-07-10-mp4-downloads-now-show-progress-immediately-after-the-option.md +6 -0
  195. package/corpus/templates/clips/changelog/2026-07-10-recording-pages-now-open-as-soon-as-you-stop-with-a-share-li.md +6 -0
  196. package/corpus/templates/clips/changelog/2026-07-10-recordings-now-seek-smoothly-downloads-use-the-correct-file-.md +6 -0
  197. package/corpus/templates/clips/changelog/2026-07-10-s3-compatible-storage-now-saves-hosted-recordings-without-re.md +6 -0
  198. package/corpus/templates/clips/desktop/README.md +22 -6
  199. package/corpus/templates/clips/desktop/package.json +1 -1
  200. package/corpus/templates/clips/desktop/src/app.tsx +32 -19
  201. package/corpus/templates/clips/desktop/src/components/ReadinessPanel.tsx +15 -9
  202. package/corpus/templates/clips/desktop/src/lib/finalization-guard.ts +22 -0
  203. package/corpus/templates/clips/desktop/src/lib/permissions.ts +3 -1
  204. package/corpus/templates/clips/desktop/src/lib/recorder.ts +97 -120
  205. package/corpus/templates/clips/desktop/src/lib/updater.ts +26 -4
  206. package/corpus/templates/clips/desktop/src/overlays/finalizing.tsx +4 -8
  207. package/corpus/templates/clips/desktop/src-tauri/Cargo.toml +1 -1
  208. package/corpus/templates/clips/desktop/src-tauri/src/clips/mod.rs +2 -2
  209. package/corpus/templates/clips/desktop/src-tauri/src/permission_status.rs +11 -7
  210. package/corpus/templates/clips/desktop/src-tauri/tauri.linux.conf.json +11 -0
  211. package/corpus/templates/clips/netlify.toml +3 -0
  212. package/corpus/templates/clips/server/lib/post-finalize-dispatch.ts +106 -0
  213. package/corpus/templates/clips/server/lib/public-agent-context.ts +9 -1
  214. package/corpus/templates/clips/server/lib/resumable-upload-provider.ts +52 -0
  215. package/corpus/templates/clips/server/lib/s3-upload-provider.ts +433 -85
  216. package/corpus/templates/clips/server/lib/video-remux.ts +114 -0
  217. package/corpus/templates/clips/server/routes/api/_agent-native-background/post-finalize-worker.post.ts +109 -0
  218. package/corpus/templates/clips/server/routes/api/clips-updater.json.get.ts +22 -11
  219. package/corpus/templates/clips/server/routes/api/public-recording.get.ts +4 -2
  220. package/corpus/templates/clips/server/routes/api/uploads/[recordingId]/abort.post.ts +47 -5
  221. package/corpus/templates/clips/server/routes/api/uploads/[recordingId]/chunk.post.ts +10 -2
  222. package/corpus/templates/clips/shared/share-loader-response.ts +12 -0
  223. package/corpus/templates/clips/shared/transcript-status.ts +40 -0
  224. package/corpus/templates/content/.agents/skills/capture-learnings/SKILL.md +22 -9
  225. package/corpus/templates/content/.agents/skills/content/SKILL.md +57 -5
  226. package/corpus/templates/content/AGENTS.md +65 -55
  227. package/corpus/templates/content/actions/_builder-cms-read-client.ts +92 -23
  228. package/corpus/templates/content/actions/_database-source-utils.ts +207 -41
  229. package/corpus/templates/content/actions/_property-utils.ts +30 -2
  230. package/corpus/templates/content/actions/add-content-database-source-field-property.ts +316 -121
  231. package/corpus/templates/content/actions/attach-content-database-source.ts +41 -17
  232. package/corpus/templates/content/actions/change-content-database-source-role.ts +46 -8
  233. package/corpus/templates/content/actions/submit-content-database-form.ts +497 -0
  234. package/corpus/templates/content/actions/suggest-source-join-key.ts +8 -1
  235. package/corpus/templates/content/actions/update-content-database-view.ts +8 -1
  236. package/corpus/templates/content/actions/view-screen.ts +4 -1
  237. package/corpus/templates/content/agent-native.app-skill.json +1 -1
  238. package/corpus/templates/content/app/components/editor/database/DatabaseView.tsx +250 -64
  239. package/corpus/templates/content/app/components/editor/database/FormView.tsx +460 -0
  240. package/corpus/templates/content/app/components/editor/database/navigation-state.ts +3 -0
  241. package/corpus/templates/content/app/components/editor/database/settings.tsx +30 -37
  242. package/corpus/templates/content/app/components/editor/database/shared.tsx +2 -0
  243. package/corpus/templates/content/app/components/editor/database/view-config.ts +29 -1
  244. package/corpus/templates/content/app/components/ui/textarea.tsx +1 -0
  245. package/corpus/templates/content/app/hooks/use-content-database.ts +22 -0
  246. package/corpus/templates/content/app/i18n/zh-TW.ts +21 -0
  247. package/corpus/templates/content/app/i18n-data.ts +225 -0
  248. package/corpus/templates/content/changelog/2026-07-09-builder-source-refreshes-now-keep-mapped-fields-such-as-topi.md +6 -0
  249. package/corpus/templates/content/changelog/2026-07-10-builder-backed-properties-now-load-current-source-values-as-.md +6 -0
  250. package/corpus/templates/content/changelog/2026-07-10-builder-database-refreshes-now-stay-explicit-and-accurate.md +6 -0
  251. package/corpus/templates/content/changelog/2026-07-10-database-form-views-now-collect-ordered-required-answers-and.md +6 -0
  252. package/corpus/templates/content/changelog/2026-07-10-database-tables-now-use-a-quieter-more-compact-layout-with-c.md +6 -0
  253. package/corpus/templates/content/changelog/2026-07-10-slack-intake-routes-to-content-database-forms.md +6 -0
  254. package/corpus/templates/content/parity/matrix.md +1 -0
  255. package/corpus/templates/content/parity/matrix.ts +18 -0
  256. package/corpus/templates/content/shared/api.ts +28 -1
  257. package/corpus/templates/content/shared/database-form.ts +53 -0
  258. package/corpus/templates/design/.agents/skills/capture-learnings/SKILL.md +22 -9
  259. package/corpus/templates/design/.agents/skills/design-generation/SKILL.md +26 -0
  260. package/corpus/templates/design/.agents/skills/design-systems/SKILL.md +85 -12
  261. package/corpus/templates/design/AGENTS.md +72 -18
  262. package/corpus/templates/design/DESIGN.md +1 -1
  263. package/corpus/templates/design/DEVELOPING.md +1 -1
  264. package/corpus/templates/design/FIGMA_INTEROPERABILITY.md +116 -0
  265. package/corpus/templates/design/actions/create-design-from-template.ts +220 -0
  266. package/corpus/templates/design/actions/create-design-system.ts +92 -16
  267. package/corpus/templates/design/actions/delete-design-template.ts +28 -0
  268. package/corpus/templates/design/actions/delete-file.ts +7 -0
  269. package/corpus/templates/design/actions/edit-design.ts +3 -0
  270. package/corpus/templates/design/actions/export-design-as-figma-svg.ts +137 -5
  271. package/corpus/templates/design/actions/export-pdf.ts +1 -1
  272. package/corpus/templates/design/actions/generate-design.ts +3 -0
  273. package/corpus/templates/design/actions/get-design-snapshot.ts +9 -0
  274. package/corpus/templates/design/actions/get-figma-connection-status.ts +26 -0
  275. package/corpus/templates/design/actions/get-figma-design-context.ts +138 -0
  276. package/corpus/templates/design/actions/get-figma-styles.ts +2 -2
  277. package/corpus/templates/design/actions/import-figma-clipboard.ts +112 -16
  278. package/corpus/templates/design/actions/import-figma-frame.ts +15 -4
  279. package/corpus/templates/design/actions/index-design-system-with-builder.ts +4 -0
  280. package/corpus/templates/design/actions/list-design-templates.ts +118 -0
  281. package/corpus/templates/design/actions/navigate.ts +16 -2
  282. package/corpus/templates/design/actions/provider-api-request.ts +11 -1
  283. package/corpus/templates/design/actions/save-design-as-template.ts +156 -0
  284. package/corpus/templates/design/actions/set-active-breakpoint.ts +13 -4
  285. package/corpus/templates/design/actions/take-design-screenshot.ts +73 -3
  286. package/corpus/templates/design/actions/update-file.ts +39 -22
  287. package/corpus/templates/design/actions/view-screen.ts +36 -1
  288. package/corpus/templates/design/actions/write-local-file.ts +50 -38
  289. package/corpus/templates/design/app/components/design/AutoLayoutSuggestionDialog.tsx +151 -0
  290. package/corpus/templates/design/app/components/design/CanvasContextMenu.tsx +20 -0
  291. package/corpus/templates/design/app/components/design/DesignCanvas.tsx +251 -22
  292. package/corpus/templates/design/app/components/design/DesignEditorSkeleton.tsx +3 -3
  293. package/corpus/templates/design/app/components/design/DesignImportPanel.tsx +384 -9
  294. package/corpus/templates/design/app/components/design/EditPanel.tsx +105 -32
  295. package/corpus/templates/design/app/components/design/MultiScreenCanvas.tsx +58 -28
  296. package/corpus/templates/design/app/components/design/TweaksPanel.tsx +6 -0
  297. package/corpus/templates/design/app/components/design/bridge/editor-chrome.bridge.ts +539 -53
  298. package/corpus/templates/design/app/components/design/bridge/embedded-wheel.bridge.ts +40 -0
  299. package/corpus/templates/design/app/components/design/code-workbench/CodeWorkbench.tsx +1 -0
  300. package/corpus/templates/design/app/components/design/code-workbench/explorer/ExplorerView.tsx +1 -0
  301. package/corpus/templates/design/app/components/design/code-workbench/explorer/FileTree.tsx +5 -1
  302. package/corpus/templates/design/app/components/design/code-workbench/workspace/create-providers.ts +2 -0
  303. package/corpus/templates/design/app/components/design/code-workbench/workspace/localhost-provider.ts +3 -1
  304. package/corpus/templates/design/app/components/design/code-workbench/workspace/types.ts +2 -0
  305. package/corpus/templates/design/app/components/design/edit-panel/element-identity.ts +19 -0
  306. package/corpus/templates/design/app/components/design/edit-panel/frame-presets-panel.tsx +1 -0
  307. package/corpus/templates/design/app/components/design/edit-panel/interaction-state-helpers.ts +27 -0
  308. package/corpus/templates/design/app/components/design/inspector/InteractionStatePanel.tsx +137 -81
  309. package/corpus/templates/design/app/components/design/inspector/frame-size-presets.ts +25 -5
  310. package/corpus/templates/design/app/components/design/multi-screen/chrome-transitions.ts +1 -1
  311. package/corpus/templates/design/app/components/design/multi-screen/frame-geometry.ts +220 -3
  312. package/corpus/templates/design/app/components/design/multi-screen/overview-layout.ts +13 -0
  313. package/corpus/templates/design/app/components/design/multi-screen/types.ts +22 -1
  314. package/corpus/templates/design/app/components/design/types.ts +4 -0
  315. package/corpus/templates/design/app/components/design-system/ProductionDesignSystemShowcase.tsx +208 -0
  316. package/corpus/templates/design/app/components/editor/FigmaLinkComposerBubble.tsx +321 -0
  317. package/corpus/templates/design/app/components/editor/PromptDialog.tsx +24 -4
  318. package/corpus/templates/design/app/components/layout/Layout.tsx +16 -2
  319. package/corpus/templates/design/app/components/layout/Sidebar.tsx +2 -0
  320. package/corpus/templates/design/app/components/templates/TemplatePreview.tsx +72 -0
  321. package/corpus/templates/design/app/global.css +2 -35
  322. package/corpus/templates/design/app/hooks/use-navigation-state.ts +10 -0
  323. package/corpus/templates/design/app/i18n/zh-TW.ts +127 -5
  324. package/corpus/templates/design/app/i18n-breakpoints.ts +209 -0
  325. package/corpus/templates/design/app/i18n-data.ts +1317 -59
  326. package/corpus/templates/design/app/i18n-template-feature.ts +458 -0
  327. package/corpus/templates/design/app/lib/design-clipboard.ts +202 -0
  328. package/corpus/templates/design/app/lib/design-file-upload.ts +87 -0
  329. package/corpus/templates/design/app/lib/design-import.ts +168 -11
  330. package/corpus/templates/design/app/lib/desktop-design-preview.ts +423 -0
  331. package/corpus/templates/design/app/lib/figma-clipboard.ts +74 -8
  332. package/corpus/templates/design/app/lib/figma-connection.ts +161 -0
  333. package/corpus/templates/design/app/lib/figma-svg-copy.ts +814 -22
  334. package/corpus/templates/design/app/lib/figma-url.ts +77 -0
  335. package/corpus/templates/design/app/lib/pending-generation.ts +35 -0
  336. package/corpus/templates/design/app/pages/DesignSystems.tsx +236 -177
  337. package/corpus/templates/design/app/pages/Index.tsx +38 -0
  338. package/corpus/templates/design/app/pages/Templates.tsx +498 -0
  339. package/corpus/templates/design/app/pages/design-editor/auto-layout-suggestion.ts +328 -0
  340. package/corpus/templates/design/app/pages/design-editor/clone-idrefs.ts +113 -0
  341. package/corpus/templates/design/app/pages/design-editor/created-screen-navigation.ts +55 -0
  342. package/corpus/templates/design/app/pages/design-editor/editor-session.ts +32 -0
  343. package/corpus/templates/design/app/pages/design-editor/editor-state.ts +49 -2
  344. package/corpus/templates/design/app/pages/design-editor/export-capture.ts +296 -0
  345. package/corpus/templates/design/app/pages/design-editor/history.ts +101 -2
  346. package/corpus/templates/design/app/pages/design-editor/layout-operations.ts +28 -1
  347. package/corpus/templates/design/app/pages/design-editor/overview-camera.ts +34 -0
  348. package/corpus/templates/design/app/pages/design-editor/pending-edits.ts +202 -6
  349. package/corpus/templates/design/app/pages/design-editor/pending-structure-verification.ts +92 -0
  350. package/corpus/templates/design/app/pages/design-editor/save-failure.ts +58 -0
  351. package/corpus/templates/design/app/routes/templates.tsx +4 -6
  352. package/corpus/templates/design/changelog/2026-07-10-app-workspaces-now-use-clean-borderless-main-surfaces-throug.md +6 -0
  353. package/corpus/templates/design/changelog/2026-07-10-ask-chat-what-s-in-a-figma-file-or-frame-structure-screensho.md +6 -0
  354. package/corpus/templates/design/changelog/2026-07-10-canvas-edits-now-reject-malformed-html-before-it-can-corrupt.md +6 -0
  355. package/corpus/templates/design/changelog/2026-07-10-complex-designs-now-export-as-valid-secure-svgs-and-crisp-ra.md +6 -0
  356. package/corpus/templates/design/changelog/2026-07-10-complex-figma-masks-arcs-rich-text-transformed-images-and-ad.md +6 -0
  357. package/corpus/templates/design/changelog/2026-07-10-copied-layers-paste-across-designs-and-browser-tabs.md +6 -0
  358. package/corpus/templates/design/changelog/2026-07-10-copy-and-download-editable-figma-svg.md +6 -0
  359. package/corpus/templates/design/changelog/2026-07-10-copying-design-text-now-pastes-readable-text-into-other-apps.md +6 -0
  360. package/corpus/templates/design/changelog/2026-07-10-deleted-screens-can-be-restored-with-undo-and-removed-again-.md +6 -0
  361. package/corpus/templates/design/changelog/2026-07-10-design-changes-now-save-before-switching-apps-and-retry-when.md +6 -0
  362. package/corpus/templates/design/changelog/2026-07-10-design-stays-usable-on-phones-by-keeping-editor-panels-and-f.md +6 -0
  363. package/corpus/templates/design/changelog/2026-07-10-download-all-screens-as-one-multi-page-pdf-from-the-overview.md +6 -0
  364. package/corpus/templates/design/changelog/2026-07-10-duplicated-layers-now-keep-labels-aria-relationships-fragmen.md +6 -0
  365. package/corpus/templates/design/changelog/2026-07-10-fig-import-results-stay-compact.md +6 -0
  366. package/corpus/templates/design/changelog/2026-07-10-figma-imports-now-load-real-fonts-fix-rotated-gradient-dashe.md +6 -0
  367. package/corpus/templates/design/changelog/2026-07-10-figma-links-in-chat-and-the-import-tab-now-offer-secure-one-.md +6 -0
  368. package/corpus/templates/design/changelog/2026-07-10-fixed-cmd-z-not-restoring-content-after-an-agent-driven-desi.md +6 -0
  369. package/corpus/templates/design/changelog/2026-07-10-fixed-download-pdf-being-unreachable-from-the-export-panel-e.md +6 -0
  370. package/corpus/templates/design/changelog/2026-07-10-fixed-dragging-a-layer-out-of-an-auto-layout-row-column-no-l.md +6 -0
  371. package/corpus/templates/design/changelog/2026-07-10-fixed-figma-svg-export-text-wrapping-sizing-and-inner-layer.md +6 -0
  372. package/corpus/templates/design/changelog/2026-07-10-fixed-hiding-or-locking-one-layer-no-longer-hides-or-blocks-.md +6 -0
  373. package/corpus/templates/design/changelog/2026-07-10-fixed-png-screenshots-of-tall-screens-being-cropped-to-one-v.md +6 -0
  374. package/corpus/templates/design/changelog/2026-07-10-fixed-png-svg-exports-capturing-broken-layout-when-webfonts-.md +6 -0
  375. package/corpus/templates/design/changelog/2026-07-10-frame-tool-now-offers-standard-ad-unit-size-presets-medium-r.md +6 -0
  376. package/corpus/templates/design/changelog/2026-07-10-full-view-controls-stay-within-their-frame-instead-of-coveri.md +6 -0
  377. package/corpus/templates/design/changelog/2026-07-10-hover-focus-focus-visible-pressed-and-disabled-states-now-pr.md +6 -0
  378. package/corpus/templates/design/changelog/2026-07-10-layer-drops-now-land-in-the-intended-grid-row-stay-visually-.md +6 -0
  379. package/corpus/templates/design/changelog/2026-07-10-local-code-workspaces-now-keep-unsaved-edits-across-panel-sw.md +6 -0
  380. package/corpus/templates/design/changelog/2026-07-10-local-visual-editing-now-keeps-authenticated-sessions-shared.md +6 -0
  381. package/corpus/templates/design/changelog/2026-07-10-long-running-agent-work-no-longer-shows-a-premature-stuck-wa.md +6 -0
  382. package/corpus/templates/design/changelog/2026-07-10-managed-figma-connections-are-recognized-automatically.md +6 -0
  383. package/corpus/templates/design/changelog/2026-07-10-new-designs-can-open-directly-in-the-editor-without-a-pr.md +6 -0
  384. package/corpus/templates/design/changelog/2026-07-10-new-screens-are-selected-and-revealed-immediately.md +6 -0
  385. package/corpus/templates/design/changelog/2026-07-10-new-text-layers-undo-as-one-safe-creation.md +6 -0
  386. package/corpus/templates/design/changelog/2026-07-10-preview-and-apply-inferred-auto-layout-without-changing-yo.md +5 -0
  387. package/corpus/templates/design/changelog/2026-07-10-print-pdf-exports-and-paper-size-presets-letter-a4-now-match.md +6 -0
  388. package/corpus/templates/design/changelog/2026-07-10-responsive-frame-editing.md +6 -0
  389. package/corpus/templates/design/changelog/2026-07-10-reusable-design-templates.md +6 -0
  390. package/corpus/templates/design/changelog/2026-07-10-screen-overview-frames-now-use-a-clearer-interact-action-wit.md +6 -0
  391. package/corpus/templates/design/changelog/2026-07-10-start-designs-from-source-linked-material-3-carbon-or-primer.md +6 -0
  392. package/corpus/templates/design/changelog/2026-07-10-tweaks-guidance.md +6 -0
  393. package/corpus/templates/design/changelog/2026-07-10-uploaded-fig-files-can-now-become-editable-design-screens-wi.md +6 -0
  394. package/corpus/templates/design/e2e/helpers.ts +3 -3
  395. package/corpus/templates/design/package.json +2 -0
  396. package/corpus/templates/design/scripts/qa-figma-stress-import.ts +96 -0
  397. package/corpus/templates/design/server/db/index.ts +10 -0
  398. package/corpus/templates/design/server/db/schema.ts +44 -0
  399. package/corpus/templates/design/server/handlers/import-design-file.ts +114 -80
  400. package/corpus/templates/design/server/handlers/index-design-system-with-builder.ts +19 -6
  401. package/corpus/templates/design/server/lib/design-export.ts +240 -3
  402. package/corpus/templates/design/server/lib/design-template-data.ts +89 -0
  403. package/corpus/templates/design/server/lib/design-to-figma-svg.ts +250 -26
  404. package/corpus/templates/design/server/lib/fig-file-decoder.ts +839 -0
  405. package/corpus/templates/design/server/lib/fig-file-import.ts +287 -0
  406. package/corpus/templates/design/server/lib/fig-file-limits.ts +3 -0
  407. package/corpus/templates/design/server/lib/fig-file-to-html.ts +2568 -0
  408. package/corpus/templates/design/server/lib/figma-design-context.ts +359 -0
  409. package/corpus/templates/design/server/lib/figma-node-import.ts +478 -22
  410. package/corpus/templates/design/server/lib/figma-node-to-html.ts +554 -29
  411. package/corpus/templates/design/server/lib/local-figma-qa-upload.ts +112 -0
  412. package/corpus/templates/design/server/lib/verify-write-grant.ts +16 -2
  413. package/corpus/templates/design/server/lib/visible-clipboard-html.ts +13 -3
  414. package/corpus/templates/design/server/plugins/agent-chat.ts +7 -0
  415. package/corpus/templates/design/server/plugins/db.ts +42 -0
  416. package/corpus/templates/design/server/plugins/local-figma-qa-upload.ts +7 -0
  417. package/corpus/templates/design/server/register-secrets.ts +8 -8
  418. package/corpus/templates/design/server/routes/api/qa-figma-import-assets/[assetId].get.ts +46 -0
  419. package/corpus/templates/design/server/source-workspace.ts +104 -12
  420. package/corpus/templates/design/shared/code-layer.ts +105 -28
  421. package/corpus/templates/design/shared/design-system-templates.ts +301 -0
  422. package/corpus/templates/design/shared/design-template-presets.ts +195 -0
  423. package/corpus/templates/design/shared/figma-url.ts +8 -0
  424. package/corpus/templates/design/shared/html-integrity.ts +306 -0
  425. package/corpus/templates/design/shared/interaction-states.ts +318 -23
  426. package/corpus/templates/design/shared/locked-layers.ts +151 -0
  427. package/corpus/templates/dispatch/.agents/skills/capture-learnings/SKILL.md +22 -9
  428. package/corpus/templates/dispatch/app/i18n/zh-TW.ts +48 -0
  429. package/corpus/templates/dispatch/app/i18n-data.ts +536 -1
  430. package/corpus/templates/dispatch/changelog/2026-07-10-connect-slack-workspaces-with-oauth-and-manage-channel-ident.md +6 -0
  431. package/corpus/templates/dispatch/changelog/2026-07-10-microsoft-teams-bots-and-discord-slash-commands-can-now-conn.md +6 -0
  432. package/corpus/templates/dispatch/changelog/2026-07-10-slack-and-telegram-now-route-uptime-monitor-requests-to-anal.md +6 -0
  433. package/corpus/templates/forms/.agents/skills/capture-learnings/SKILL.md +22 -9
  434. package/corpus/templates/forms/.agents/skills/form-publishing/SKILL.md +7 -0
  435. package/corpus/templates/forms/AGENTS.md +4 -0
  436. package/corpus/templates/forms/actions/create-form.ts +44 -7
  437. package/corpus/templates/forms/actions/lib/assert-publishable-form.ts +38 -0
  438. package/corpus/templates/forms/actions/patch-form-fields.ts +4 -0
  439. package/corpus/templates/forms/actions/update-form.ts +2 -36
  440. package/corpus/templates/forms/app/i18n/ar-SA.ts +3 -0
  441. package/corpus/templates/forms/app/i18n/de-DE.ts +3 -0
  442. package/corpus/templates/forms/app/i18n/en-US.ts +3 -0
  443. package/corpus/templates/forms/app/i18n/es-ES.ts +3 -0
  444. package/corpus/templates/forms/app/i18n/fr-FR.ts +3 -0
  445. package/corpus/templates/forms/app/i18n/hi-IN.ts +3 -0
  446. package/corpus/templates/forms/app/i18n/ja-JP.ts +3 -0
  447. package/corpus/templates/forms/app/i18n/ko-KR.ts +3 -0
  448. package/corpus/templates/forms/app/i18n/pt-BR.ts +3 -0
  449. package/corpus/templates/forms/app/i18n/zh-CN.ts +2 -0
  450. package/corpus/templates/forms/app/i18n/zh-TW.ts +3 -0
  451. package/corpus/templates/forms/app/pages/FormBuilderPage.tsx +17 -0
  452. package/corpus/templates/forms/changelog/2026-07-10-agent-created-published-forms-now-return-the-anonymous-publi.md +6 -0
  453. package/corpus/templates/forms/changelog/2026-07-10-published-forms-can-no-longer-be-edited-into-an-unusable-emp.md +6 -0
  454. package/corpus/templates/forms/server/handlers/submissions.ts +4 -3
  455. package/corpus/templates/forms/server/plugins/agent-chat.ts +1 -0
  456. package/corpus/templates/forms/shared/types.ts +5 -0
  457. package/corpus/templates/mail/.agents/skills/capture-learnings/SKILL.md +22 -9
  458. package/corpus/templates/mail/app/components/layout/AppLayout.tsx +2 -2
  459. package/corpus/templates/mail/changelog/2026-07-10-mail-navigation-now-uses-a-clean-borderless-drawer.md +6 -0
  460. package/corpus/templates/plan/.agents/skills/capture-learnings/SKILL.md +22 -9
  461. package/corpus/templates/plan/app/lib/plan-local-bridge.ts +4 -1
  462. package/corpus/templates/plan/changelog/2026-07-10-local-plans-now-keep-valid-content-visible-when-one-generate.md +6 -0
  463. package/corpus/templates/plan/server/lib/local-plan-files.ts +4 -1
  464. package/corpus/templates/slides/.agents/skills/capture-learnings/SKILL.md +22 -9
  465. package/dist/a2a/artifact-response.d.ts.map +1 -1
  466. package/dist/a2a/artifact-response.js +88 -2
  467. package/dist/a2a/artifact-response.js.map +1 -1
  468. package/dist/a2a/client.d.ts +9 -0
  469. package/dist/a2a/client.d.ts.map +1 -1
  470. package/dist/a2a/client.js +1 -0
  471. package/dist/a2a/client.js.map +1 -1
  472. package/dist/a2a/handlers.d.ts.map +1 -1
  473. package/dist/a2a/handlers.js +24 -69
  474. package/dist/a2a/handlers.js.map +1 -1
  475. package/dist/a2a/types.d.ts +2 -0
  476. package/dist/a2a/types.d.ts.map +1 -1
  477. package/dist/a2a/types.js.map +1 -1
  478. package/dist/agent/durable-background.d.ts +11 -0
  479. package/dist/agent/durable-background.d.ts.map +1 -1
  480. package/dist/agent/durable-background.js +17 -0
  481. package/dist/agent/durable-background.js.map +1 -1
  482. package/dist/agent/production-agent.d.ts +5 -3
  483. package/dist/agent/production-agent.d.ts.map +1 -1
  484. package/dist/agent/production-agent.js +34 -8
  485. package/dist/agent/production-agent.js.map +1 -1
  486. package/dist/agent/run-manager.d.ts +44 -2
  487. package/dist/agent/run-manager.d.ts.map +1 -1
  488. package/dist/agent/run-manager.js +124 -18
  489. package/dist/agent/run-manager.js.map +1 -1
  490. package/dist/agent/run-store.d.ts +109 -0
  491. package/dist/agent/run-store.d.ts.map +1 -1
  492. package/dist/agent/run-store.js +274 -37
  493. package/dist/agent/run-store.js.map +1 -1
  494. package/dist/agent/types.d.ts +22 -0
  495. package/dist/agent/types.d.ts.map +1 -1
  496. package/dist/agent/types.js.map +1 -1
  497. package/dist/audit/record.d.ts.map +1 -1
  498. package/dist/audit/record.js +29 -0
  499. package/dist/audit/record.js.map +1 -1
  500. package/dist/audit/store.d.ts.map +1 -1
  501. package/dist/audit/store.js +62 -3
  502. package/dist/audit/store.js.map +1 -1
  503. package/dist/audit/types.d.ts +13 -0
  504. package/dist/audit/types.d.ts.map +1 -1
  505. package/dist/audit/types.js.map +1 -1
  506. package/dist/automation/index.d.ts +193 -0
  507. package/dist/automation/index.d.ts.map +1 -0
  508. package/dist/automation/index.js +464 -0
  509. package/dist/automation/index.js.map +1 -0
  510. package/dist/cli/create.d.ts.map +1 -1
  511. package/dist/cli/create.js +10 -3
  512. package/dist/cli/create.js.map +1 -1
  513. package/dist/cli/design-connect.d.ts.map +1 -1
  514. package/dist/cli/design-connect.js +492 -35
  515. package/dist/cli/design-connect.js.map +1 -1
  516. package/dist/client/AgentPanel.d.ts +7 -1
  517. package/dist/client/AgentPanel.d.ts.map +1 -1
  518. package/dist/client/AgentPanel.js +32 -8
  519. package/dist/client/AgentPanel.js.map +1 -1
  520. package/dist/client/AssistantChat.d.ts +15 -0
  521. package/dist/client/AssistantChat.d.ts.map +1 -1
  522. package/dist/client/AssistantChat.js +115 -47
  523. package/dist/client/AssistantChat.js.map +1 -1
  524. package/dist/client/MultiTabAssistantChat.d.ts.map +1 -1
  525. package/dist/client/MultiTabAssistantChat.js +1 -1
  526. package/dist/client/MultiTabAssistantChat.js.map +1 -1
  527. package/dist/client/RunStuckBanner.d.ts +14 -1
  528. package/dist/client/RunStuckBanner.d.ts.map +1 -1
  529. package/dist/client/RunStuckBanner.js +35 -7
  530. package/dist/client/RunStuckBanner.js.map +1 -1
  531. package/dist/client/agent-chat-adapter.d.ts +4 -1
  532. package/dist/client/agent-chat-adapter.d.ts.map +1 -1
  533. package/dist/client/agent-chat-adapter.js +97 -16
  534. package/dist/client/agent-chat-adapter.js.map +1 -1
  535. package/dist/client/automation.d.ts +14 -0
  536. package/dist/client/automation.d.ts.map +1 -0
  537. package/dist/client/automation.js +9 -0
  538. package/dist/client/automation.js.map +1 -0
  539. package/dist/client/chat/run-recovery.d.ts +4 -0
  540. package/dist/client/chat/run-recovery.d.ts.map +1 -1
  541. package/dist/client/chat/run-recovery.js +12 -10
  542. package/dist/client/chat/run-recovery.js.map +1 -1
  543. package/dist/client/composer/TiptapComposer.d.ts.map +1 -1
  544. package/dist/client/composer/TiptapComposer.js +8 -0
  545. package/dist/client/composer/TiptapComposer.js.map +1 -1
  546. package/dist/client/index.d.ts +2 -0
  547. package/dist/client/index.d.ts.map +1 -1
  548. package/dist/client/index.js +2 -0
  549. package/dist/client/index.js.map +1 -1
  550. package/dist/client/integrations/api.d.ts +115 -0
  551. package/dist/client/integrations/api.d.ts.map +1 -0
  552. package/dist/client/integrations/api.js +123 -0
  553. package/dist/client/integrations/api.js.map +1 -0
  554. package/dist/client/integrations/index.d.ts +1 -0
  555. package/dist/client/integrations/index.d.ts.map +1 -1
  556. package/dist/client/integrations/index.js +1 -0
  557. package/dist/client/integrations/index.js.map +1 -1
  558. package/dist/client/transcription/use-live-transcription.d.ts.map +1 -1
  559. package/dist/client/transcription/use-live-transcription.js +59 -5
  560. package/dist/client/transcription/use-live-transcription.js.map +1 -1
  561. package/dist/client/use-run-stuck-detection.d.ts +16 -1
  562. package/dist/client/use-run-stuck-detection.d.ts.map +1 -1
  563. package/dist/client/use-run-stuck-detection.js +23 -4
  564. package/dist/client/use-run-stuck-detection.js.map +1 -1
  565. package/dist/collab/awareness.d.ts +2 -2
  566. package/dist/collab/awareness.d.ts.map +1 -1
  567. package/dist/deploy/build.d.ts.map +1 -1
  568. package/dist/deploy/build.js +49 -4
  569. package/dist/deploy/build.js.map +1 -1
  570. package/dist/deploy/workspace-deploy.d.ts.map +1 -1
  571. package/dist/deploy/workspace-deploy.js +31 -2
  572. package/dist/deploy/workspace-deploy.js.map +1 -1
  573. package/dist/file-upload/types.d.ts +2 -0
  574. package/dist/file-upload/types.d.ts.map +1 -1
  575. package/dist/file-upload/types.js.map +1 -1
  576. package/dist/index.d.ts +2 -0
  577. package/dist/index.d.ts.map +1 -1
  578. package/dist/index.js +2 -0
  579. package/dist/index.js.map +1 -1
  580. package/dist/integrations/a2a-continuations-store.d.ts.map +1 -1
  581. package/dist/integrations/a2a-continuations-store.js +6 -4
  582. package/dist/integrations/a2a-continuations-store.js.map +1 -1
  583. package/dist/integrations/adapters/discord.d.ts +3 -0
  584. package/dist/integrations/adapters/discord.d.ts.map +1 -0
  585. package/dist/integrations/adapters/discord.js +261 -0
  586. package/dist/integrations/adapters/discord.js.map +1 -0
  587. package/dist/integrations/adapters/index.d.ts +4 -0
  588. package/dist/integrations/adapters/index.d.ts.map +1 -0
  589. package/dist/integrations/adapters/index.js +26 -0
  590. package/dist/integrations/adapters/index.js.map +1 -0
  591. package/dist/integrations/adapters/microsoft-teams.d.ts +5 -0
  592. package/dist/integrations/adapters/microsoft-teams.d.ts.map +1 -0
  593. package/dist/integrations/adapters/microsoft-teams.js +295 -0
  594. package/dist/integrations/adapters/microsoft-teams.js.map +1 -0
  595. package/dist/integrations/adapters/slack.d.ts +8 -2
  596. package/dist/integrations/adapters/slack.d.ts.map +1 -1
  597. package/dist/integrations/adapters/slack.js +736 -27
  598. package/dist/integrations/adapters/slack.js.map +1 -1
  599. package/dist/integrations/adapters/telegram.d.ts +0 -2
  600. package/dist/integrations/adapters/telegram.d.ts.map +1 -1
  601. package/dist/integrations/adapters/telegram.js +49 -15
  602. package/dist/integrations/adapters/telegram.js.map +1 -1
  603. package/dist/integrations/adapters/whatsapp.d.ts +0 -2
  604. package/dist/integrations/adapters/whatsapp.d.ts.map +1 -1
  605. package/dist/integrations/adapters/whatsapp.js +40 -17
  606. package/dist/integrations/adapters/whatsapp.js.map +1 -1
  607. package/dist/integrations/catalog.d.ts +75 -0
  608. package/dist/integrations/catalog.d.ts.map +1 -0
  609. package/dist/integrations/catalog.js +451 -0
  610. package/dist/integrations/catalog.js.map +1 -0
  611. package/dist/integrations/controls-store.d.ts +44 -0
  612. package/dist/integrations/controls-store.d.ts.map +1 -0
  613. package/dist/integrations/controls-store.js +129 -0
  614. package/dist/integrations/controls-store.js.map +1 -0
  615. package/dist/integrations/index.d.ts +13 -1
  616. package/dist/integrations/index.d.ts.map +1 -1
  617. package/dist/integrations/index.js +9 -0
  618. package/dist/integrations/index.js.map +1 -1
  619. package/dist/integrations/installations-store.d.ts +112 -0
  620. package/dist/integrations/installations-store.d.ts.map +1 -0
  621. package/dist/integrations/installations-store.js +493 -0
  622. package/dist/integrations/installations-store.js.map +1 -0
  623. package/dist/integrations/integration-memory.d.ts +24 -0
  624. package/dist/integrations/integration-memory.d.ts.map +1 -0
  625. package/dist/integrations/integration-memory.js +136 -0
  626. package/dist/integrations/integration-memory.js.map +1 -0
  627. package/dist/integrations/pending-tasks-retry-job.d.ts.map +1 -1
  628. package/dist/integrations/pending-tasks-retry-job.js +6 -5
  629. package/dist/integrations/pending-tasks-retry-job.js.map +1 -1
  630. package/dist/integrations/pending-tasks-store.d.ts +17 -0
  631. package/dist/integrations/pending-tasks-store.d.ts.map +1 -1
  632. package/dist/integrations/pending-tasks-store.js +71 -5
  633. package/dist/integrations/pending-tasks-store.js.map +1 -1
  634. package/dist/integrations/plugin.d.ts.map +1 -1
  635. package/dist/integrations/plugin.js +520 -35
  636. package/dist/integrations/plugin.js.map +1 -1
  637. package/dist/integrations/scope-store.d.ts +65 -0
  638. package/dist/integrations/scope-store.d.ts.map +1 -0
  639. package/dist/integrations/scope-store.js +361 -0
  640. package/dist/integrations/scope-store.js.map +1 -0
  641. package/dist/integrations/slack-manifest.d.ts +66 -0
  642. package/dist/integrations/slack-manifest.d.ts.map +1 -0
  643. package/dist/integrations/slack-manifest.js +70 -0
  644. package/dist/integrations/slack-manifest.js.map +1 -0
  645. package/dist/integrations/slack-oauth.d.ts +99 -0
  646. package/dist/integrations/slack-oauth.d.ts.map +1 -0
  647. package/dist/integrations/slack-oauth.js +226 -0
  648. package/dist/integrations/slack-oauth.js.map +1 -0
  649. package/dist/integrations/types.d.ts +144 -0
  650. package/dist/integrations/types.d.ts.map +1 -1
  651. package/dist/integrations/types.js +16 -1
  652. package/dist/integrations/types.js.map +1 -1
  653. package/dist/integrations/usage-budget-store.d.ts +84 -0
  654. package/dist/integrations/usage-budget-store.d.ts.map +1 -0
  655. package/dist/integrations/usage-budget-store.js +650 -0
  656. package/dist/integrations/usage-budget-store.js.map +1 -0
  657. package/dist/integrations/webhook-handler.d.ts +4 -0
  658. package/dist/integrations/webhook-handler.d.ts.map +1 -1
  659. package/dist/integrations/webhook-handler.js +415 -47
  660. package/dist/integrations/webhook-handler.js.map +1 -1
  661. package/dist/jobs/scheduler.d.ts +6 -0
  662. package/dist/jobs/scheduler.d.ts.map +1 -1
  663. package/dist/jobs/scheduler.js +83 -4
  664. package/dist/jobs/scheduler.js.map +1 -1
  665. package/dist/jobs/tools.d.ts.map +1 -1
  666. package/dist/jobs/tools.js +43 -11
  667. package/dist/jobs/tools.js.map +1 -1
  668. package/dist/provider-api/index.d.ts +4 -4
  669. package/dist/provider-api/index.d.ts.map +1 -1
  670. package/dist/provider-api/index.js +72 -1
  671. package/dist/provider-api/index.js.map +1 -1
  672. package/dist/resources/handlers.d.ts.map +1 -1
  673. package/dist/resources/handlers.js +57 -15
  674. package/dist/resources/handlers.js.map +1 -1
  675. package/dist/resources/script-helpers.d.ts.map +1 -1
  676. package/dist/resources/script-helpers.js +34 -8
  677. package/dist/resources/script-helpers.js.map +1 -1
  678. package/dist/resources/store.d.ts +10 -0
  679. package/dist/resources/store.d.ts.map +1 -1
  680. package/dist/resources/store.js +54 -47
  681. package/dist/resources/store.js.map +1 -1
  682. package/dist/scripts/call-agent.d.ts.map +1 -1
  683. package/dist/scripts/call-agent.js +106 -1
  684. package/dist/scripts/call-agent.js.map +1 -1
  685. package/dist/server/agent-chat-plugin.d.ts +15 -4
  686. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  687. package/dist/server/agent-chat-plugin.js +248 -113
  688. package/dist/server/agent-chat-plugin.js.map +1 -1
  689. package/dist/server/auth.d.ts.map +1 -1
  690. package/dist/server/auth.js +10 -14
  691. package/dist/server/auth.js.map +1 -1
  692. package/dist/server/builder-design-systems.d.ts +3 -1
  693. package/dist/server/builder-design-systems.d.ts.map +1 -1
  694. package/dist/server/builder-design-systems.js +9 -2
  695. package/dist/server/builder-design-systems.js.map +1 -1
  696. package/dist/server/edge.d.ts +1 -1
  697. package/dist/server/edge.d.ts.map +1 -1
  698. package/dist/server/edge.js +1 -1
  699. package/dist/server/edge.js.map +1 -1
  700. package/dist/server/index.d.ts +2 -1
  701. package/dist/server/index.d.ts.map +1 -1
  702. package/dist/server/index.js +2 -1
  703. package/dist/server/index.js.map +1 -1
  704. package/dist/server/request-context.d.ts +18 -0
  705. package/dist/server/request-context.d.ts.map +1 -1
  706. package/dist/server/request-context.js.map +1 -1
  707. package/dist/server/social-og-image.d.ts.map +1 -1
  708. package/dist/server/social-og-image.js +3 -2
  709. package/dist/server/social-og-image.js.map +1 -1
  710. package/dist/server/transcribe-voice.d.ts +1 -1
  711. package/dist/styles/agent-native.css +62 -44
  712. package/dist/templates/default/.agents/skills/capture-learnings/SKILL.md +22 -9
  713. package/dist/templates/default/AGENTS.md +7 -3
  714. package/dist/templates/workspace-core/.agents/skills/authentication/SKILL.md +1 -1
  715. package/dist/templates/workspace-core/.agents/skills/capture-learnings/SKILL.md +22 -9
  716. package/dist/templates/workspace-core/.agents/skills/extension-points/SKILL.md +6 -3
  717. package/dist/templates/workspace-core/.agents/skills/extensions/SKILL.md +25 -0
  718. package/dist/templates/workspace-core/.agents/skills/integration-webhooks/SKILL.md +15 -0
  719. package/dist/templates/workspace-core/AGENTS.md +3 -2
  720. package/dist/usage/store.d.ts +7 -0
  721. package/dist/usage/store.d.ts.map +1 -1
  722. package/dist/usage/store.js +24 -3
  723. package/dist/usage/store.js.map +1 -1
  724. package/docs/content/automation-connectors.mdx +80 -0
  725. package/docs/content/extensions.mdx +8 -0
  726. package/docs/content/locales/ar-SA/extensions.mdx +8 -0
  727. package/docs/content/locales/ar-SA/messaging.mdx +84 -15
  728. package/docs/content/locales/ar-SA/template-clips.mdx +1 -0
  729. package/docs/content/locales/ar-SA/template-design.mdx +1 -0
  730. package/docs/content/locales/de-DE/extensions.mdx +10 -0
  731. package/docs/content/locales/de-DE/messaging.mdx +92 -15
  732. package/docs/content/locales/de-DE/template-clips.mdx +1 -0
  733. package/docs/content/locales/de-DE/template-design.mdx +1 -0
  734. package/docs/content/locales/es-ES/extensions.mdx +10 -0
  735. package/docs/content/locales/es-ES/messaging.mdx +91 -15
  736. package/docs/content/locales/es-ES/template-clips.mdx +1 -0
  737. package/docs/content/locales/es-ES/template-design.mdx +1 -0
  738. package/docs/content/locales/fr-FR/extensions.mdx +10 -0
  739. package/docs/content/locales/fr-FR/messaging.mdx +91 -15
  740. package/docs/content/locales/fr-FR/template-clips.mdx +1 -0
  741. package/docs/content/locales/fr-FR/template-design.mdx +1 -0
  742. package/docs/content/locales/hi-IN/extensions.mdx +8 -0
  743. package/docs/content/locales/hi-IN/messaging.mdx +81 -15
  744. package/docs/content/locales/hi-IN/template-clips.mdx +1 -0
  745. package/docs/content/locales/hi-IN/template-design.mdx +1 -0
  746. package/docs/content/locales/ja-JP/extensions.mdx +9 -0
  747. package/docs/content/locales/ja-JP/messaging.mdx +81 -15
  748. package/docs/content/locales/ja-JP/template-clips.mdx +1 -0
  749. package/docs/content/locales/ja-JP/template-design.mdx +1 -0
  750. package/docs/content/locales/ko-KR/extensions.mdx +8 -0
  751. package/docs/content/locales/ko-KR/messaging.mdx +80 -15
  752. package/docs/content/locales/ko-KR/template-clips.mdx +1 -0
  753. package/docs/content/locales/ko-KR/template-design.mdx +1 -0
  754. package/docs/content/locales/pt-BR/extensions.mdx +9 -0
  755. package/docs/content/locales/pt-BR/messaging.mdx +88 -15
  756. package/docs/content/locales/pt-BR/template-clips.mdx +1 -0
  757. package/docs/content/locales/pt-BR/template-design.mdx +1 -0
  758. package/docs/content/locales/zh-CN/extensions.mdx +6 -0
  759. package/docs/content/locales/zh-CN/messaging.mdx +78 -15
  760. package/docs/content/locales/zh-CN/template-clips.mdx +1 -0
  761. package/docs/content/locales/zh-CN/template-design.mdx +1 -0
  762. package/docs/content/locales/zh-TW/extensions.mdx +6 -0
  763. package/docs/content/locales/zh-TW/messaging.mdx +78 -15
  764. package/docs/content/locales/zh-TW/template-clips.mdx +1 -0
  765. package/docs/content/locales/zh-TW/template-design.mdx +1 -0
  766. package/docs/content/messaging.mdx +227 -45
  767. package/docs/content/template-clips.mdx +3 -0
  768. package/docs/content/template-design.mdx +4 -0
  769. package/package.json +5 -1
  770. package/src/templates/default/.agents/skills/capture-learnings/SKILL.md +22 -9
  771. package/src/templates/default/AGENTS.md +7 -3
  772. package/src/templates/workspace-core/.agents/skills/authentication/SKILL.md +1 -1
  773. package/src/templates/workspace-core/.agents/skills/capture-learnings/SKILL.md +22 -9
  774. package/src/templates/workspace-core/.agents/skills/extension-points/SKILL.md +6 -3
  775. package/src/templates/workspace-core/.agents/skills/extensions/SKILL.md +25 -0
  776. package/src/templates/workspace-core/.agents/skills/integration-webhooks/SKILL.md +15 -0
  777. package/src/templates/workspace-core/AGENTS.md +3 -2
@@ -298,6 +298,21 @@ queue + retry job for at-least-once delivery.
298
298
  6. **Reply not delivered?** The processor likely succeeded but
299
299
  `adapter.sendResponse` failed — check the adapter's outbound logs.
300
300
 
301
+ ## Automation connectors
302
+
303
+ Workflow systems such as n8n and Zapier are not messaging channels. Do not add
304
+ them as `PlatformAdapter`s or route them through `provider-api`.
305
+
306
+ For n8n-style workflow invocation and callbacks, use
307
+ `@agent-native/core/automation` with static workflow IDs and allow-listed
308
+ origins. Agents provide structured input, never a target URL or credential.
309
+ Callbacks must verify a configured secret/signature, claim a durable event ID,
310
+ enqueue work through the established queue, and acknowledge quickly.
311
+
312
+ Zapier is blueprint-only unless the app implements Zapier's explicit REST Hook
313
+ subscribe/unsubscribe contract or configures a separate Zapier MCP connection.
314
+ Do not imply a generic Zapier workflow-execution API exists.
315
+
301
316
  ## Related Skills
302
317
 
303
318
  - `server-plugins` — How `/_agent-native/` routes get mounted
@@ -71,8 +71,9 @@ agent should know.
71
71
 
72
72
  ## Adding Apps
73
73
 
74
- When a user asks from Dispatch chat or by tagging `@agent-native` in Slack to
75
- create, build, make, scaffold, or generate an "agent", classify the ask first.
74
+ When a user asks from Dispatch chat or through `@agent-native` in Slack or
75
+ Telegram to create, build, make, scaffold, or generate an "agent", classify
76
+ the ask first.
76
77
  Simple Dispatch-native behavior such as a reminder, digest, monitor, routing
77
78
  rule, saved instruction, or recurring workflow can stay in Dispatch as a
78
79
  recurring job/resource/destination. Robust unique products or teammates that
@@ -36,6 +36,13 @@ export interface UsageRecord {
36
36
  * provider-reported dollar cost so two surfaces agree exactly.
37
37
  */
38
38
  costCentsX100?: number;
39
+ orgId?: string;
40
+ runId?: string;
41
+ threadId?: string;
42
+ taskId?: string;
43
+ integrationScopeId?: string;
44
+ sourcePlatform?: string;
45
+ sourceId?: string;
39
46
  }
40
47
  /**
41
48
  * Calculate cost in centicents (1/100th of a cent).
@@ -1 +1 @@
1
- {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/usage/store.ts"],"names":[],"mappings":"AA6BA,eAAO,MAAM,sCAAsC,OAAO,CAAC;AAC3D,eAAO,MAAM,6BAA6B,KAAK,CAAC;AAEhD,MAAM,MAAM,gBAAgB,GAAG,KAAK,GAAG,iBAAiB,CAAC;AAEzD,MAAM,WAAW,gBA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NULL DEFAULT 'chat',
157
157
  app TEXT NOT NULL DEFAULT '',
158
158
  ref_id TEXT NOT NULL DEFAULT '',
159
+ org_id TEXT,
160
+ run_id TEXT,
161
+ thread_id TEXT,
162
+ task_id TEXT,
163
+ integration_scope_id TEXT,
164
+ source_platform TEXT,
165
+ source_id TEXT,
159
166
  created_at ${intType()} NOT NULL
160
167
  )
161
168
  `;
@@ -166,6 +173,13 @@ async function ensureUsageTable() {
166
173
  ["label", `TEXT NOT NULL DEFAULT 'chat'`],
167
174
  ["app", `TEXT NOT NULL DEFAULT ''`],
168
175
  ["ref_id", `TEXT NOT NULL DEFAULT ''`],
176
+ ["org_id", "TEXT"],
177
+ ["run_id", "TEXT"],
178
+ ["thread_id", "TEXT"],
179
+ ["task_id", "TEXT"],
180
+ ["integration_scope_id", "TEXT"],
181
+ ["source_platform", "TEXT"],
182
+ ["source_id", "TEXT"],
169
183
  ];
170
184
  if (isPostgres()) {
171
185
  // Hot path: the `token_usage` table and its index are virtually always
@@ -244,7 +258,7 @@ export async function recordUsage(recordOrOwner, inputTokens, outputTokens, mode
244
258
  model: model ?? "",
245
259
  }
246
260
  : recordOrOwner;
247
- const { ownerEmail, inputTokens: inTok, outputTokens: outTok, cacheReadTokens = 0, cacheWriteTokens = 0, model: modelName, label, app, refId, costCentsX100, } = record;
261
+ const { ownerEmail, inputTokens: inTok, outputTokens: outTok, cacheReadTokens = 0, cacheWriteTokens = 0, model: modelName, label, app, refId, costCentsX100, orgId, runId, threadId, taskId, integrationScopeId, sourcePlatform, sourceId, } = record;
248
262
  // Skip no-op writes (e.g. a stream aborted before any tokens flowed)
249
263
  if (!inTok && !outTok && !cacheReadTokens && !cacheWriteTokens)
250
264
  return;
@@ -269,8 +283,8 @@ export async function recordUsage(recordOrOwner, inputTokens, outputTokens, mode
269
283
  const id = Date.now() * 1000 + Math.floor(Math.random() * 1000);
270
284
  await client.execute({
271
285
  sql: `INSERT INTO token_usage
272
- (id, owner_email, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost_cents_x100, model, label, app, ref_id, created_at)
273
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
286
+ (id, owner_email, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost_cents_x100, model, label, app, ref_id, org_id, run_id, thread_id, task_id, integration_scope_id, source_platform, source_id, created_at)
287
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
274
288
  args: [
275
289
  id,
276
290
  ownerEmail,
@@ -283,6 +297,13 @@ export async function recordUsage(recordOrOwner, inputTokens, outputTokens, mode
283
297
  resolvedLabel,
284
298
  resolvedApp,
285
299
  resolvedRef,
300
+ orgId ?? null,
301
+ runId ?? null,
302
+ threadId ?? null,
303
+ taskId ?? null,
304
+ integrationScopeId ?? null,
305
+ sourcePlatform ?? null,
306
+ sourceId ?? null,
286
307
  Date.now(),
287
308
  ],
288
309
  });
@@ -1 +1 @@
1
- {"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/usage/store.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AACjE,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAcjE,MAAM,CAAC,MAAM,sCAAsC,GAAG,IAAI,CAAC;AAC3D,MAAM,CAAC,MAAM,6BAA6B,GAAG,EAAE,CAAC;AAahD,MAAM,CAAC,MAAM,iBAAiB,GAAqB;IACjD,IAAI,EAAE,KAAK;IACX,KAAK,EAAE,iBAAiB;IACxB,UAAU,EAAE,MAAM;IAClB,MAAM,EAAE,yBAAyB;CAClC,CAAC;AAEF,MAAM,CAAC,MAAM,4BAA4B,GAAqB;IAC5D,IAAI,EAAE,iBAAiB;IAC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AAG,CAAC,YAAY,IAAI,CAAC,CAAC;QAC1C,YAAY,EAAE,MAAM,CAAC,GAAG,CAAC,aAAa,IAAI,CAAC,CAAC;QAC5C,eAAe,EAAE,MAAM,CAAC,GAAG,CAAC,iBAAiB,IAAI,CAAC,CAAC;QACnD,gBAAgB,EAAE,MAAM,CAAC,GAAG,CAAC,kBAAkB,IAAI,CAAC,CAAC;QACrD,KAAK,EAAE,MAAM,CAAC,GAAG,CAAC,eAAe,IAAI,CAAC,CAAC,GAAG,GAAG;KAC9C,CAAC,CAAC,CAAC;IAEJ,OAAO;QACL,OAAO,EAAE,iBAAiB;QAC1B,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,GAAG,GAAG;QACtC,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC;QAChC,gBAAgB,EAAE,MAAM,CAAC,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC;QACvC,iBAAiB,EAAE,MAAM,CAAC,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC;QACzC,oBAAoB,EAAE,MAAM,CAAC,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC;QAC3C,qBAAqB,EAAE,MAAM,CAAC,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC;QAC5C,OAAO;QACP,OAAO,EAAE,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC;QAClC,OAAO,EAAE,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC;QAClC,KAAK,EAAE,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC;QAC9B,KAAK;QACL,MAAM;KACP,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Token usage tracking and cost monitoring.\n *\n * Every LLM call made by the framework records a row here so users can\n * see where their spend is going — chat vs automations vs background jobs\n * vs whatever else a template labels its prompts as.\n *\n * Cost is stored as \"centicents\" (1/100th of a cent) for integer precision.\n */\nimport { getDbExec, intType, isPostgres } from \"../db/client.js\";\nimport {\n ensureColumnExists,\n ensureIndexExists,\n ensureTableExists,\n} from \"../db/ddl-guard.js\";\nimport { widenIntColumnsToBigInt } from \"../db/widen-columns.js\";\n\n/**\n * Per-million-token pricing in cents. Cache read is typically ~10% of\n * input; cache write (5m TTL) is ~125%. Pricing is best-effort — keep\n * this table in sync with Anthropic's published prices.\n */\ninterface ModelPricing {\n input: number;\n output: number;\n cacheRead: number;\n cacheWrite: number;\n}\n\nexport const BUILDER_AGENT_CREDIT_MARGIN_MULTIPLIER = 1.25;\nexport const BUILDER_AGENT_CREDITS_PER_USD = 20;\n\nexport type UsageBillingUnit = \"usd\" | \"builder-credits\";\n\nexport interface UsageBillingMode {\n unit: UsageBillingUnit;\n label: string;\n shortLabel: string;\n source: \"estimated-provider-cost\" | \"builder-agent-credits\";\n hardCostMarginMultiplier?: number;\n creditsPerUsd?: number;\n}\n\nexport const USD_USAGE_BILLING: UsageBillingMode = {\n unit: \"usd\",\n label: \"Estimated spend\",\n shortLabel: \"Cost\",\n source: \"estimated-provider-cost\",\n};\n\nexport const BUILDER_CREDIT_USAGE_BILLING: UsageBillingMode = {\n unit: \"builder-credits\",\n label: \"Builder.io credit spend\",\n shortLabel: \"Credits\",\n source: \"builder-agent-credits\",\n hardCostMarginMultiplier: BUILDER_AGENT_CREDIT_MARGIN_MULTIPLIER,\n creditsPerUsd: BUILDER_AGENT_CREDITS_PER_USD,\n};\n\nexport function usageBillingForEngine(\n engineName: string | null | undefined,\n): UsageBillingMode {\n return engineName === \"builder\"\n ? BUILDER_CREDIT_USAGE_BILLING\n : USD_USAGE_BILLING;\n}\n\nexport function builderCreditsFromCostCents(cents: number): number {\n if (!Number.isFinite(cents) || cents <= 0) return 0;\n const dollars = cents / 100;\n const credits =\n dollars *\n BUILDER_AGENT_CREDIT_MARGIN_MULTIPLIER *\n BUILDER_AGENT_CREDITS_PER_USD;\n return Math.ceil(credits * 1000) / 1000;\n}\n\nconst PRICING: Array<{ match: RegExp; pricing: ModelPricing }> = [\n // ── Anthropic ──────────────────────────────────────────────────────────────\n // claude-fable-5: $10/$50 per MTok (Mythos-class, launched 2026-06-09)\n {\n match: /fable-5/i,\n pricing: { input: 1000, output: 5000, cacheRead: 100, cacheWrite: 1250 },\n },\n // claude-opus-4-8: $5/$25 standard mode (fast mode same as fable-5 $10/$50)\n // Use standard-mode pricing as default; fast-mode is a separate model id.\n {\n match: /opus-4-8/i,\n pricing: { input: 500, output: 2500, cacheRead: 50, cacheWrite: 625 },\n },\n // claude-opus-4-7 and older opus: ~$15/$75 per MTok\n {\n match: /opus/i,\n pricing: { input: 1500, output: 7500, cacheRead: 150, cacheWrite: 1875 },\n },\n {\n match: /haiku/i,\n pricing: { input: 100, output: 500, cacheRead: 10, cacheWrite: 125 },\n },\n // ── OpenAI / Codex ──────────────────────────────────────────────────────────\n // Published rates as of 2026-07; OpenAI bills cached input at a discount\n // and has no separate cache-write token charge, so cacheWrite is 0. Sol and\n // Terra have higher large-context rates after 272K tokens; this table tracks\n // the standard rate because usage rows do not preserve request context size.\n {\n match: /gpt-5[.-]6-sol/i,\n pricing: { input: 500, output: 3000, cacheRead: 50, cacheWrite: 0 },\n },\n {\n match: /gpt-5[.-]6-terra/i,\n pricing: { input: 250, output: 1500, cacheRead: 25, cacheWrite: 0 },\n },\n {\n match: /gpt-5[.-]6-luna/i,\n pricing: { input: 100, output: 600, cacheRead: 10, cacheWrite: 0 },\n },\n {\n match: /gpt-5/i,\n pricing: { input: 125, output: 1000, cacheRead: 12.5, cacheWrite: 0 },\n },\n // ── Google Gemini ───────────────────────────────────────────────────────────\n // Gemini 3 Pro / 3.1 Pro: ~$1.25/$10 per MTok (approximate; verify on billing)\n {\n match: /gemini-3[.-]1-pro/i,\n pricing: { input: 125, output: 1000, cacheRead: 31, cacheWrite: 0 },\n },\n // Gemini 3.5 Flash / 3 Flash: ~$0.15/$0.60 per MTok\n {\n match: /gemini-3[.-][0-9]+-flash/i,\n pricing: { input: 15, output: 60, cacheRead: 4, cacheWrite: 0 },\n },\n // Gemini 2.5 Pro/Flash (catch-all for older 2.5)\n {\n match: /gemini-2\\.5-pro/i,\n pricing: { input: 125, output: 1000, cacheRead: 31, cacheWrite: 0 },\n },\n {\n match: /gemini-2\\.5-flash/i,\n pricing: { input: 15, output: 60, cacheRead: 4, cacheWrite: 0 },\n },\n // ── Groq ────────────────────────────────────────────────────────────────────\n // Groq Llama 3.3 70B: $0.59/$0.79 per MTok\n {\n match: /llama-3\\.3-70b/i,\n pricing: { input: 59, output: 79, cacheRead: 0, cacheWrite: 0 },\n },\n // Groq Llama 3.1 8B instant: $0.05/$0.08 per MTok\n {\n match: /llama-3\\.1-8b|llama3-8b/i,\n pricing: { input: 5, output: 8, cacheRead: 0, cacheWrite: 0 },\n },\n // ── Mistral ─────────────────────────────────────────────────────────────────\n // Mistral Large: ~$2/$6 per MTok\n {\n match: /mistral-large/i,\n pricing: { input: 200, output: 600, cacheRead: 0, cacheWrite: 0 },\n },\n // Mistral Small/Medium: ~$0.2/$0.6 per MTok\n {\n match: /mistral-small|mistral-medium/i,\n pricing: { input: 20, output: 60, cacheRead: 0, cacheWrite: 0 },\n },\n // default → sonnet pricing ($3/$15 per MTok)\n {\n match: /.*/,\n pricing: { input: 300, output: 1500, cacheRead: 30, cacheWrite: 375 },\n },\n];\n\nfunction pricingFor(model: string): ModelPricing {\n for (const entry of PRICING) {\n if (entry.match.test(model)) return entry.pricing;\n }\n return PRICING[PRICING.length - 1]!.pricing;\n}\n\nexport interface UsageRecord {\n ownerEmail: string;\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n model: string;\n /** Category for this call — e.g. \"chat\", \"automation\", \"job\", \"custom-agent\". */\n label?: string;\n /** Optional template/app name (e.g. \"mail\"). Falls back to AGENT_APP / APP_NAME env. */\n app?: string;\n /**\n * Stable id of the thing this usage belongs to (e.g. a recap plan id). When\n * set, any prior row(s) with the same (label, refId) are deleted before\n * insert, so re-recording the same run overwrites instead of double-counting.\n */\n refId?: string;\n /**\n * Precomputed cost in centicents (1/100¢). When provided, it is stored\n * verbatim instead of being derived from tokens — e.g. to mirror a\n * provider-reported dollar cost so two surfaces agree exactly.\n */\n costCentsX100?: number;\n}\n\nlet _initPromise: Promise<void> | undefined;\n\nasync function ensureUsageTable(): Promise<void> {\n if (!_initPromise) {\n _initPromise = (async () => {\n const client = getDbExec();\n const createSql = `\n CREATE TABLE IF NOT EXISTS token_usage (\n id ${intType()} PRIMARY KEY,\n owner_email TEXT NOT NULL,\n input_tokens ${intType()} NOT NULL DEFAULT 0,\n output_tokens ${intType()} NOT NULL DEFAULT 0,\n cache_read_tokens ${intType()} NOT NULL DEFAULT 0,\n cache_write_tokens ${intType()} NOT NULL DEFAULT 0,\n cost_cents_x100 ${intType()} NOT NULL DEFAULT 0,\n model TEXT NOT NULL DEFAULT '',\n label TEXT NOT NULL DEFAULT 'chat',\n app TEXT NOT NULL DEFAULT '',\n ref_id TEXT NOT NULL DEFAULT '',\n created_at ${intType()} NOT NULL\n )\n `;\n\n // Additive columns for older deployments that pre-date the label/cache fields.\n const additions: Array<[string, string]> = [\n [\"cache_read_tokens\", `${intType()} NOT NULL DEFAULT 0`],\n [\"cache_write_tokens\", `${intType()} NOT NULL DEFAULT 0`],\n [\"label\", `TEXT NOT NULL DEFAULT 'chat'`],\n [\"app\", `TEXT NOT NULL DEFAULT ''`],\n [\"ref_id\", `TEXT NOT NULL DEFAULT ''`],\n ];\n\n if (isPostgres()) {\n // Hot path: the `token_usage` table and its index are virtually always\n // already present in production. Issuing `CREATE TABLE`/`ALTER TABLE`/\n // `CREATE INDEX` still takes a lock that, in a fresh background-worker\n // process behind a concurrent connection on the shared Neon DB, can\n // block ~indefinitely. The ensure* wrappers probe `information_schema`/\n // `pg_indexes` first (plain reads, no lock) and run DDL ONLY for what is\n // actually missing, bounded by a transaction-scoped `lock_timeout`. If a\n // swallowed lock-timeout leaves the schema still missing they RE-PROBE\n // and THROW rather than letting init memoize success against absent\n // schema.\n await ensureTableExists(\"token_usage\", createSql);\n // Add columns on older deployments — guarded so the hot path (columns\n // already present) skips the ACCESS EXCLUSIVE ALTER.\n for (const [col, def] of additions) {\n await ensureColumnExists(\n \"token_usage\",\n col,\n `ALTER TABLE token_usage ADD COLUMN IF NOT EXISTS ${col} ${def}`,\n );\n }\n // Older deployments created `created_at` as 32-bit `INTEGER`; on Postgres\n // the `Date.now()` written per run by recordUsage() overflows int4. Widen\n // it in place (no-op once done / on fresh BIGINT databases).\n await widenIntColumnsToBigInt(\"token_usage\", [\"created_at\"]);\n // Probe pg_indexes first (no lock) and skip the SHARE-locking CREATE\n // INDEX when the index is already present.\n await ensureIndexExists(\n \"idx_token_usage_owner_created\",\n `CREATE INDEX IF NOT EXISTS idx_token_usage_owner_created ON token_usage (owner_email, created_at)`,\n );\n return;\n }\n\n // SQLite (local dev): no lock problem — keep the original behaviour.\n await client.execute(createSql);\n // Add columns on older deployments that pre-date the label/cache\n // fields. Each ALTER is wrapped so a dialect without IF NOT EXISTS\n // (SQLite) still makes progress if only some columns are missing.\n for (const [col, def] of additions) {\n try {\n await client.execute(\n `ALTER TABLE token_usage ADD COLUMN ${col} ${def}`,\n );\n } catch {\n // Column already exists — ignore\n }\n }\n // Older deployments created `created_at` as 32-bit `INTEGER`; on Postgres\n // the `Date.now()` written per run by recordUsage() overflows int4. Widen\n // it in place (no-op once done / on fresh BIGINT databases).\n await widenIntColumnsToBigInt(\"token_usage\", [\"created_at\"]);\n try {\n await client.execute(\n `CREATE INDEX IF NOT EXISTS idx_token_usage_owner_created ON token_usage (owner_email, created_at)`,\n );\n } catch {}\n })().catch((err) => {\n // Retry init on the next call after a failed startup.\n _initPromise = undefined;\n throw err;\n });\n }\n return _initPromise;\n}\n\n/**\n * Calculate cost in centicents (1/100th of a cent).\n * Accepts cache tokens so callers that use prompt caching are priced\n * correctly. Non-cache-aware callers can pass 0 for the cache fields.\n */\nexport function calculateCost(\n inputTokens: number,\n outputTokens: number,\n model: string,\n cacheReadTokens = 0,\n cacheWriteTokens = 0,\n): number {\n const p = pricingFor(model);\n const rawCenticents =\n (inputTokens / 1_000_000) * p.input * 100 +\n (outputTokens / 1_000_000) * p.output * 100 +\n (cacheReadTokens / 1_000_000) * p.cacheRead * 100 +\n (cacheWriteTokens / 1_000_000) * p.cacheWrite * 100;\n return rawCenticents > 0 ? Math.max(1, Math.round(rawCenticents)) : 0;\n}\n\n/**\n * Record token usage from an LLM call.\n *\n * Accepts an object with the full set of fields. A positional overload\n * remains for backward compatibility with the older 4-arg signature.\n */\nexport async function recordUsage(record: UsageRecord): Promise<void>;\nexport async function recordUsage(\n ownerEmail: string,\n inputTokens: number,\n outputTokens: number,\n model: string,\n): Promise<void>;\nexport async function recordUsage(\n recordOrOwner: UsageRecord | string,\n inputTokens?: number,\n outputTokens?: number,\n model?: string,\n): Promise<void> {\n const record: UsageRecord =\n typeof recordOrOwner === \"string\"\n ? {\n ownerEmail: recordOrOwner,\n inputTokens: inputTokens ?? 0,\n outputTokens: outputTokens ?? 0,\n model: model ?? \"\",\n }\n : recordOrOwner;\n\n const {\n ownerEmail,\n inputTokens: inTok,\n outputTokens: outTok,\n cacheReadTokens = 0,\n cacheWriteTokens = 0,\n model: modelName,\n label,\n app,\n refId,\n costCentsX100,\n } = record;\n\n // Skip no-op writes (e.g. a stream aborted before any tokens flowed)\n if (!inTok && !outTok && !cacheReadTokens && !cacheWriteTokens) return;\n\n await ensureUsageTable();\n const client = getDbExec();\n const resolvedApp =\n app ?? process.env.AGENT_APP ?? process.env.APP_NAME ?? \"\";\n const resolvedLabel = label ?? \"chat\";\n const resolvedRef = refId ?? \"\";\n\n // Replace any prior usage for this (label, refId) so re-recording the same\n // run — e.g. a recap regenerated on a PR re-push — overwrites instead of\n // double-counting. No-op when refId is unset (the common per-call path).\n if (resolvedRef) {\n await client.execute({\n sql: `DELETE FROM token_usage WHERE label = ? AND ref_id = ?`,\n args: [resolvedLabel, resolvedRef],\n });\n }\n\n // Prefer an explicit precomputed cost (e.g. a provider-reported dollar cost);\n // otherwise derive it from tokens via the pricing table.\n const costX100 =\n costCentsX100 ??\n calculateCost(inTok, outTok, modelName, cacheReadTokens, cacheWriteTokens);\n const id = Date.now() * 1000 + Math.floor(Math.random() * 1000);\n await client.execute({\n sql: `INSERT INTO token_usage\n (id, owner_email, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost_cents_x100, model, label, app, ref_id, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n args: [\n id,\n ownerEmail,\n inTok,\n outTok,\n cacheReadTokens,\n cacheWriteTokens,\n costX100,\n modelName,\n resolvedLabel,\n resolvedApp,\n resolvedRef,\n Date.now(),\n ],\n });\n}\n\n/** Total cost (in cents) charged against a user, across all time. */\nexport async function getUserUsageCents(ownerEmail: string): Promise<number> {\n await ensureUsageTable();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT COALESCE(SUM(cost_cents_x100), 0) as total FROM token_usage WHERE owner_email = ?`,\n args: [ownerEmail],\n });\n const total = Number((rows[0] as { total?: number })?.total ?? 0);\n return total / 100;\n}\n\n// ─── Admin / UI queries ─────────────────────────────────────────────────\n\nexport interface UsageSummaryOptions {\n ownerEmail: string;\n /** Inclusive lower bound (ms since epoch). Defaults to 30 days ago. */\n sinceMs?: number;\n}\n\nexport interface UsageBucket {\n key: string;\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens: number;\n cacheWriteTokens: number;\n cents: number;\n calls: number;\n}\n\nexport interface DailyBucket {\n /** YYYY-MM-DD (UTC) */\n date: string;\n cents: number;\n calls: number;\n}\n\nexport interface UsageRecentEntry {\n id: number;\n createdAt: number;\n label: string;\n app: string;\n model: string;\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens: number;\n cacheWriteTokens: number;\n cents: number;\n}\n\nexport interface UsageSummary {\n billing?: UsageBillingMode;\n totalCents: number;\n totalCalls: number;\n totalInputTokens: number;\n totalOutputTokens: number;\n totalCacheReadTokens: number;\n totalCacheWriteTokens: number;\n sinceMs: number;\n byLabel: UsageBucket[];\n byModel: UsageBucket[];\n byApp: UsageBucket[];\n byDay: DailyBucket[];\n recent: UsageRecentEntry[];\n}\n\nconst DAY_MS = 86_400_000;\n\n/**\n * Produce an aggregated spend view for the Usage admin panel.\n * Scoped to the passed owner email; the UI always passes the session user.\n */\nexport async function getUsageSummary(\n options: UsageSummaryOptions,\n): Promise<UsageSummary> {\n await ensureUsageTable();\n const client = getDbExec();\n const sinceMs = options.sinceMs ?? Date.now() - 30 * DAY_MS;\n\n const totalRow = await client.execute({\n sql: `SELECT\n COALESCE(SUM(cost_cents_x100), 0) AS cents,\n COUNT(*) AS calls,\n COALESCE(SUM(input_tokens), 0) AS in_tok,\n COALESCE(SUM(output_tokens), 0) AS out_tok,\n COALESCE(SUM(cache_read_tokens), 0) AS cr_tok,\n COALESCE(SUM(cache_write_tokens), 0) AS cw_tok\n FROM token_usage WHERE owner_email = ? AND created_at >= ?`,\n args: [options.ownerEmail, sinceMs],\n });\n const t = (totalRow.rows[0] ?? {}) as Record<string, number | null>;\n\n const bucketSql = (col: string) => ({\n sql: `SELECT ${col} AS k,\n COALESCE(SUM(cost_cents_x100), 0) AS cents,\n COUNT(*) AS calls,\n COALESCE(SUM(input_tokens), 0) AS in_tok,\n COALESCE(SUM(output_tokens), 0) AS out_tok,\n COALESCE(SUM(cache_read_tokens), 0) AS cr_tok,\n COALESCE(SUM(cache_write_tokens), 0) AS cw_tok\n FROM token_usage\n WHERE owner_email = ? AND created_at >= ?\n GROUP BY ${col}\n ORDER BY cents DESC`,\n args: [options.ownerEmail, sinceMs],\n });\n\n const mapBuckets = (rows: unknown[]): UsageBucket[] =>\n rows.map((r) => {\n const row = r as Record<string, number | string | null>;\n return {\n key: String(row.k ?? \"\"),\n cents: Number(row.cents ?? 0) / 100,\n calls: Number(row.calls ?? 0),\n inputTokens: Number(row.in_tok ?? 0),\n outputTokens: Number(row.out_tok ?? 0),\n cacheReadTokens: Number(row.cr_tok ?? 0),\n cacheWriteTokens: Number(row.cw_tok ?? 0),\n };\n });\n\n const [byLabelR, byModelR, byAppR] = await Promise.all([\n client.execute(bucketSql(\"label\")),\n client.execute(bucketSql(\"model\")),\n client.execute(bucketSql(\"app\")),\n ]);\n\n // By-day aggregation — done in JS so we don't depend on dialect-specific\n // date functions (SQLite `strftime`, Postgres `to_char`). Cheap enough\n // for a 30-day window; if this grows, swap for a dialect-aware query.\n const dayRows = await client.execute({\n sql: `SELECT created_at, cost_cents_x100 FROM token_usage\n WHERE owner_email = ? AND created_at >= ?`,\n args: [options.ownerEmail, sinceMs],\n });\n const dayMap = new Map<string, { cents: number; calls: number }>();\n for (const row of dayRows.rows as Array<Record<string, number>>) {\n const date = new Date(Number(row.created_at)).toISOString().slice(0, 10);\n const prev = dayMap.get(date) ?? { cents: 0, calls: 0 };\n prev.cents += Number(row.cost_cents_x100 ?? 0);\n prev.calls += 1;\n dayMap.set(date, prev);\n }\n const byDay: DailyBucket[] = [...dayMap.entries()]\n .map(([date, v]) => ({\n date,\n cents: v.cents / 100,\n calls: v.calls,\n }))\n .sort((a, b) => a.date.localeCompare(b.date));\n\n const recentRows = await client.execute({\n sql: `SELECT id, created_at, label, app, model,\n input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,\n cost_cents_x100\n FROM token_usage\n WHERE owner_email = ?\n ORDER BY created_at DESC\n LIMIT 50`,\n args: [options.ownerEmail],\n });\n const recent: UsageRecentEntry[] = (\n recentRows.rows as Array<Record<string, number | string | null>>\n ).map((row) => ({\n id: Number(row.id),\n createdAt: Number(row.created_at),\n label: String(row.label ?? \"chat\"),\n app: String(row.app ?? \"\"),\n model: String(row.model ?? \"\"),\n inputTokens: Number(row.input_tokens ?? 0),\n outputTokens: Number(row.output_tokens ?? 0),\n cacheReadTokens: Number(row.cache_read_tokens ?? 0),\n cacheWriteTokens: Number(row.cache_write_tokens ?? 0),\n cents: Number(row.cost_cents_x100 ?? 0) / 100,\n }));\n\n return {\n billing: USD_USAGE_BILLING,\n totalCents: Number(t.cents ?? 0) / 100,\n totalCalls: Number(t.calls ?? 0),\n totalInputTokens: Number(t.in_tok ?? 0),\n totalOutputTokens: Number(t.out_tok ?? 0),\n totalCacheReadTokens: Number(t.cr_tok ?? 0),\n totalCacheWriteTokens: Number(t.cw_tok ?? 0),\n sinceMs,\n byLabel: mapBuckets(byLabelR.rows),\n byModel: mapBuckets(byModelR.rows),\n byApp: mapBuckets(byAppR.rows),\n byDay,\n recent,\n };\n}\n"]}
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/usage/store.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AACjE,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAcjE,MAAM,CAAC,MAAM,sCAAsC,GAAG,IAAI,CAAC;AAC3D,MAAM,CAAC,MAAM,6BAA6B,GAAG,EAAE,CAAC;AAahD,MAAM,CAAC,MAAM,iBAAiB,GAAqB;IACjD,IAAI,EAAE,KAAK;IACX,KAAK,EAAE,iBAAiB;IACxB,UAAU,EAAE,MAAM;IAClB,MAAM,EAAE,yBAAyB;CAClC,CAAC;AAEF,MAAM,CAAC,MAAM,4BAA4B,GAAqB;IAC5D,IAAI,EAAE,iBAAiB;IACvB,KAAK,EAAE,yBAAyB;IAChC,UAAU,EAAE,SAAS;IACrB,MAAM,EAAE,uBAAuB;IAC/B,wBAAwB,EAAE,sCAAsC;IAChE,aAAa,EAAE,6BAA6B;CAC7C,CAAC;AAEF,MAAM,UAAU,qBAAqB,CACnC,UAAqC;IAErC,OAAO,UAAU,KAAK,SAAS;QAC7B,CAAC,CAAC,4BAA4B;QAC9B,CAAC,CAAC,iBAAiB,CAAC;AACxB,CAAC;AAED,MAAM,UAAU,2BAA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CAAC;AACJ,CAAC","sourcesContent":["/**\n * Token usage tracking and cost monitoring.\n *\n * Every LLM call made by the framework records a row here so users can\n * see where their spend is going — chat vs automations vs background jobs\n * vs whatever else a template labels its prompts as.\n *\n * Cost is stored as \"centicents\" (1/100th of a cent) for integer precision.\n */\nimport { getDbExec, intType, isPostgres } from \"../db/client.js\";\nimport {\n ensureColumnExists,\n ensureIndexExists,\n ensureTableExists,\n} from \"../db/ddl-guard.js\";\nimport { widenIntColumnsToBigInt } from \"../db/widen-columns.js\";\n\n/**\n * Per-million-token pricing in cents. Cache read is typically ~10% of\n * input; cache write (5m TTL) is ~125%. Pricing is best-effort — keep\n * this table in sync with Anthropic's published prices.\n */\ninterface ModelPricing {\n input: number;\n output: number;\n cacheRead: number;\n cacheWrite: number;\n}\n\nexport const BUILDER_AGENT_CREDIT_MARGIN_MULTIPLIER = 1.25;\nexport const BUILDER_AGENT_CREDITS_PER_USD = 20;\n\nexport type UsageBillingUnit = \"usd\" | \"builder-credits\";\n\nexport interface UsageBillingMode {\n unit: UsageBillingUnit;\n label: string;\n shortLabel: string;\n source: \"estimated-provider-cost\" | \"builder-agent-credits\";\n hardCostMarginMultiplier?: number;\n creditsPerUsd?: number;\n}\n\nexport const USD_USAGE_BILLING: UsageBillingMode = {\n unit: \"usd\",\n label: \"Estimated spend\",\n shortLabel: \"Cost\",\n source: \"estimated-provider-cost\",\n};\n\nexport const BUILDER_CREDIT_USAGE_BILLING: UsageBillingMode = {\n unit: \"builder-credits\",\n label: \"Builder.io credit spend\",\n shortLabel: \"Credits\",\n source: \"builder-agent-credits\",\n hardCostMarginMultiplier: BUILDER_AGENT_CREDIT_MARGIN_MULTIPLIER,\n creditsPerUsd: BUILDER_AGENT_CREDITS_PER_USD,\n};\n\nexport function usageBillingForEngine(\n engineName: string | null | undefined,\n): UsageBillingMode {\n return engineName === \"builder\"\n ? BUILDER_CREDIT_USAGE_BILLING\n : USD_USAGE_BILLING;\n}\n\nexport function builderCreditsFromCostCents(cents: number): number {\n if (!Number.isFinite(cents) || cents <= 0) return 0;\n const dollars = cents / 100;\n const credits =\n dollars *\n BUILDER_AGENT_CREDIT_MARGIN_MULTIPLIER *\n BUILDER_AGENT_CREDITS_PER_USD;\n return Math.ceil(credits * 1000) / 1000;\n}\n\nconst PRICING: Array<{ match: RegExp; pricing: ModelPricing }> = [\n // ── Anthropic ──────────────────────────────────────────────────────────────\n // claude-fable-5: $10/$50 per MTok (Mythos-class, launched 2026-06-09)\n {\n match: /fable-5/i,\n pricing: { input: 1000, output: 5000, cacheRead: 100, cacheWrite: 1250 },\n },\n // claude-opus-4-8: $5/$25 standard mode (fast mode same as fable-5 $10/$50)\n // Use standard-mode pricing as default; fast-mode is a separate model id.\n {\n match: /opus-4-8/i,\n pricing: { input: 500, output: 2500, cacheRead: 50, cacheWrite: 625 },\n },\n // claude-opus-4-7 and older opus: ~$15/$75 per MTok\n {\n match: /opus/i,\n pricing: { input: 1500, output: 7500, cacheRead: 150, cacheWrite: 1875 },\n },\n {\n match: /haiku/i,\n pricing: { input: 100, output: 500, cacheRead: 10, cacheWrite: 125 },\n },\n // ── OpenAI / Codex ──────────────────────────────────────────────────────────\n // Published rates as of 2026-07; OpenAI bills cached input at a discount\n // and has no separate cache-write token charge, so cacheWrite is 0. Sol and\n // Terra have higher large-context rates after 272K tokens; this table tracks\n // the standard rate because usage rows do not preserve request context size.\n {\n match: /gpt-5[.-]6-sol/i,\n pricing: { input: 500, output: 3000, cacheRead: 50, cacheWrite: 0 },\n },\n {\n match: /gpt-5[.-]6-terra/i,\n pricing: { input: 250, output: 1500, cacheRead: 25, cacheWrite: 0 },\n },\n {\n match: /gpt-5[.-]6-luna/i,\n pricing: { input: 100, output: 600, cacheRead: 10, cacheWrite: 0 },\n },\n {\n match: /gpt-5/i,\n pricing: { input: 125, output: 1000, cacheRead: 12.5, cacheWrite: 0 },\n },\n // ── Google Gemini ───────────────────────────────────────────────────────────\n // Gemini 3 Pro / 3.1 Pro: ~$1.25/$10 per MTok (approximate; verify on billing)\n {\n match: /gemini-3[.-]1-pro/i,\n pricing: { input: 125, output: 1000, cacheRead: 31, cacheWrite: 0 },\n },\n // Gemini 3.5 Flash / 3 Flash: ~$0.15/$0.60 per MTok\n {\n match: /gemini-3[.-][0-9]+-flash/i,\n pricing: { input: 15, output: 60, cacheRead: 4, cacheWrite: 0 },\n },\n // Gemini 2.5 Pro/Flash (catch-all for older 2.5)\n {\n match: /gemini-2\\.5-pro/i,\n pricing: { input: 125, output: 1000, cacheRead: 31, cacheWrite: 0 },\n },\n {\n match: /gemini-2\\.5-flash/i,\n pricing: { input: 15, output: 60, cacheRead: 4, cacheWrite: 0 },\n },\n // ── Groq ────────────────────────────────────────────────────────────────────\n // Groq Llama 3.3 70B: $0.59/$0.79 per MTok\n {\n match: /llama-3\\.3-70b/i,\n pricing: { input: 59, output: 79, cacheRead: 0, cacheWrite: 0 },\n },\n // Groq Llama 3.1 8B instant: $0.05/$0.08 per MTok\n {\n match: /llama-3\\.1-8b|llama3-8b/i,\n pricing: { input: 5, output: 8, cacheRead: 0, cacheWrite: 0 },\n },\n // ── Mistral ─────────────────────────────────────────────────────────────────\n // Mistral Large: ~$2/$6 per MTok\n {\n match: /mistral-large/i,\n pricing: { input: 200, output: 600, cacheRead: 0, cacheWrite: 0 },\n },\n // Mistral Small/Medium: ~$0.2/$0.6 per MTok\n {\n match: /mistral-small|mistral-medium/i,\n pricing: { input: 20, output: 60, cacheRead: 0, cacheWrite: 0 },\n },\n // default → sonnet pricing ($3/$15 per MTok)\n {\n match: /.*/,\n pricing: { input: 300, output: 1500, cacheRead: 30, cacheWrite: 375 },\n },\n];\n\nfunction pricingFor(model: string): ModelPricing {\n for (const entry of PRICING) {\n if (entry.match.test(model)) return entry.pricing;\n }\n return PRICING[PRICING.length - 1]!.pricing;\n}\n\nexport interface UsageRecord {\n ownerEmail: string;\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n model: string;\n /** Category for this call — e.g. \"chat\", \"automation\", \"job\", \"custom-agent\". */\n label?: string;\n /** Optional template/app name (e.g. \"mail\"). Falls back to AGENT_APP / APP_NAME env. */\n app?: string;\n /**\n * Stable id of the thing this usage belongs to (e.g. a recap plan id). When\n * set, any prior row(s) with the same (label, refId) are deleted before\n * insert, so re-recording the same run overwrites instead of double-counting.\n */\n refId?: string;\n /**\n * Precomputed cost in centicents (1/100¢). When provided, it is stored\n * verbatim instead of being derived from tokens — e.g. to mirror a\n * provider-reported dollar cost so two surfaces agree exactly.\n */\n costCentsX100?: number;\n orgId?: string;\n runId?: string;\n threadId?: string;\n taskId?: string;\n integrationScopeId?: string;\n sourcePlatform?: string;\n sourceId?: string;\n}\n\nlet _initPromise: Promise<void> | undefined;\n\nasync function ensureUsageTable(): Promise<void> {\n if (!_initPromise) {\n _initPromise = (async () => {\n const client = getDbExec();\n const createSql = `\n CREATE TABLE IF NOT EXISTS token_usage (\n id ${intType()} PRIMARY KEY,\n owner_email TEXT NOT NULL,\n input_tokens ${intType()} NOT NULL DEFAULT 0,\n output_tokens ${intType()} NOT NULL DEFAULT 0,\n cache_read_tokens ${intType()} NOT NULL DEFAULT 0,\n cache_write_tokens ${intType()} NOT NULL DEFAULT 0,\n cost_cents_x100 ${intType()} NOT NULL DEFAULT 0,\n model TEXT NOT NULL DEFAULT '',\n label TEXT NOT NULL DEFAULT 'chat',\n app TEXT NOT NULL DEFAULT '',\n ref_id TEXT NOT NULL DEFAULT '',\n org_id TEXT,\n run_id TEXT,\n thread_id TEXT,\n task_id TEXT,\n integration_scope_id TEXT,\n source_platform TEXT,\n source_id TEXT,\n created_at ${intType()} NOT NULL\n )\n `;\n\n // Additive columns for older deployments that pre-date the label/cache fields.\n const additions: Array<[string, string]> = [\n [\"cache_read_tokens\", `${intType()} NOT NULL DEFAULT 0`],\n [\"cache_write_tokens\", `${intType()} NOT NULL DEFAULT 0`],\n [\"label\", `TEXT NOT NULL DEFAULT 'chat'`],\n [\"app\", `TEXT NOT NULL DEFAULT ''`],\n [\"ref_id\", `TEXT NOT NULL DEFAULT ''`],\n [\"org_id\", \"TEXT\"],\n [\"run_id\", \"TEXT\"],\n [\"thread_id\", \"TEXT\"],\n [\"task_id\", \"TEXT\"],\n [\"integration_scope_id\", \"TEXT\"],\n [\"source_platform\", \"TEXT\"],\n [\"source_id\", \"TEXT\"],\n ];\n\n if (isPostgres()) {\n // Hot path: the `token_usage` table and its index are virtually always\n // already present in production. Issuing `CREATE TABLE`/`ALTER TABLE`/\n // `CREATE INDEX` still takes a lock that, in a fresh background-worker\n // process behind a concurrent connection on the shared Neon DB, can\n // block ~indefinitely. The ensure* wrappers probe `information_schema`/\n // `pg_indexes` first (plain reads, no lock) and run DDL ONLY for what is\n // actually missing, bounded by a transaction-scoped `lock_timeout`. If a\n // swallowed lock-timeout leaves the schema still missing they RE-PROBE\n // and THROW rather than letting init memoize success against absent\n // schema.\n await ensureTableExists(\"token_usage\", createSql);\n // Add columns on older deployments — guarded so the hot path (columns\n // already present) skips the ACCESS EXCLUSIVE ALTER.\n for (const [col, def] of additions) {\n await ensureColumnExists(\n \"token_usage\",\n col,\n `ALTER TABLE token_usage ADD COLUMN IF NOT EXISTS ${col} ${def}`,\n );\n }\n // Older deployments created `created_at` as 32-bit `INTEGER`; on Postgres\n // the `Date.now()` written per run by recordUsage() overflows int4. Widen\n // it in place (no-op once done / on fresh BIGINT databases).\n await widenIntColumnsToBigInt(\"token_usage\", [\"created_at\"]);\n // Probe pg_indexes first (no lock) and skip the SHARE-locking CREATE\n // INDEX when the index is already present.\n await ensureIndexExists(\n \"idx_token_usage_owner_created\",\n `CREATE INDEX IF NOT EXISTS idx_token_usage_owner_created ON token_usage (owner_email, created_at)`,\n );\n return;\n }\n\n // SQLite (local dev): no lock problem — keep the original behaviour.\n await client.execute(createSql);\n // Add columns on older deployments that pre-date the label/cache\n // fields. Each ALTER is wrapped so a dialect without IF NOT EXISTS\n // (SQLite) still makes progress if only some columns are missing.\n for (const [col, def] of additions) {\n try {\n await client.execute(\n `ALTER TABLE token_usage ADD COLUMN ${col} ${def}`,\n );\n } catch {\n // Column already exists — ignore\n }\n }\n // Older deployments created `created_at` as 32-bit `INTEGER`; on Postgres\n // the `Date.now()` written per run by recordUsage() overflows int4. Widen\n // it in place (no-op once done / on fresh BIGINT databases).\n await widenIntColumnsToBigInt(\"token_usage\", [\"created_at\"]);\n try {\n await client.execute(\n `CREATE INDEX IF NOT EXISTS idx_token_usage_owner_created ON token_usage (owner_email, created_at)`,\n );\n } catch {}\n })().catch((err) => {\n // Retry init on the next call after a failed startup.\n _initPromise = undefined;\n throw err;\n });\n }\n return _initPromise;\n}\n\n/**\n * Calculate cost in centicents (1/100th of a cent).\n * Accepts cache tokens so callers that use prompt caching are priced\n * correctly. Non-cache-aware callers can pass 0 for the cache fields.\n */\nexport function calculateCost(\n inputTokens: number,\n outputTokens: number,\n model: string,\n cacheReadTokens = 0,\n cacheWriteTokens = 0,\n): number {\n const p = pricingFor(model);\n const rawCenticents =\n (inputTokens / 1_000_000) * p.input * 100 +\n (outputTokens / 1_000_000) * p.output * 100 +\n (cacheReadTokens / 1_000_000) * p.cacheRead * 100 +\n (cacheWriteTokens / 1_000_000) * p.cacheWrite * 100;\n return rawCenticents > 0 ? Math.max(1, Math.round(rawCenticents)) : 0;\n}\n\n/**\n * Record token usage from an LLM call.\n *\n * Accepts an object with the full set of fields. A positional overload\n * remains for backward compatibility with the older 4-arg signature.\n */\nexport async function recordUsage(record: UsageRecord): Promise<void>;\nexport async function recordUsage(\n ownerEmail: string,\n inputTokens: number,\n outputTokens: number,\n model: string,\n): Promise<void>;\nexport async function recordUsage(\n recordOrOwner: UsageRecord | string,\n inputTokens?: number,\n outputTokens?: number,\n model?: string,\n): Promise<void> {\n const record: UsageRecord =\n typeof recordOrOwner === \"string\"\n ? {\n ownerEmail: recordOrOwner,\n inputTokens: inputTokens ?? 0,\n outputTokens: outputTokens ?? 0,\n model: model ?? \"\",\n }\n : recordOrOwner;\n\n const {\n ownerEmail,\n inputTokens: inTok,\n outputTokens: outTok,\n cacheReadTokens = 0,\n cacheWriteTokens = 0,\n model: modelName,\n label,\n app,\n refId,\n costCentsX100,\n orgId,\n runId,\n threadId,\n taskId,\n integrationScopeId,\n sourcePlatform,\n sourceId,\n } = record;\n\n // Skip no-op writes (e.g. a stream aborted before any tokens flowed)\n if (!inTok && !outTok && !cacheReadTokens && !cacheWriteTokens) return;\n\n await ensureUsageTable();\n const client = getDbExec();\n const resolvedApp =\n app ?? process.env.AGENT_APP ?? process.env.APP_NAME ?? \"\";\n const resolvedLabel = label ?? \"chat\";\n const resolvedRef = refId ?? \"\";\n\n // Replace any prior usage for this (label, refId) so re-recording the same\n // run — e.g. a recap regenerated on a PR re-push — overwrites instead of\n // double-counting. No-op when refId is unset (the common per-call path).\n if (resolvedRef) {\n await client.execute({\n sql: `DELETE FROM token_usage WHERE label = ? AND ref_id = ?`,\n args: [resolvedLabel, resolvedRef],\n });\n }\n\n // Prefer an explicit precomputed cost (e.g. a provider-reported dollar cost);\n // otherwise derive it from tokens via the pricing table.\n const costX100 =\n costCentsX100 ??\n calculateCost(inTok, outTok, modelName, cacheReadTokens, cacheWriteTokens);\n const id = Date.now() * 1000 + Math.floor(Math.random() * 1000);\n await client.execute({\n sql: `INSERT INTO token_usage\n (id, owner_email, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost_cents_x100, model, label, app, ref_id, org_id, run_id, thread_id, task_id, integration_scope_id, source_platform, source_id, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n args: [\n id,\n ownerEmail,\n inTok,\n outTok,\n cacheReadTokens,\n cacheWriteTokens,\n costX100,\n modelName,\n resolvedLabel,\n resolvedApp,\n resolvedRef,\n orgId ?? null,\n runId ?? null,\n threadId ?? null,\n taskId ?? null,\n integrationScopeId ?? null,\n sourcePlatform ?? null,\n sourceId ?? null,\n Date.now(),\n ],\n });\n}\n\n/** Total cost (in cents) charged against a user, across all time. */\nexport async function getUserUsageCents(ownerEmail: string): Promise<number> {\n await ensureUsageTable();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT COALESCE(SUM(cost_cents_x100), 0) as total FROM token_usage WHERE owner_email = ?`,\n args: [ownerEmail],\n });\n const total = Number((rows[0] as { total?: number })?.total ?? 0);\n return total / 100;\n}\n\n// ─── Admin / UI queries ─────────────────────────────────────────────────\n\nexport interface UsageSummaryOptions {\n ownerEmail: string;\n /** Inclusive lower bound (ms since epoch). Defaults to 30 days ago. */\n sinceMs?: number;\n}\n\nexport interface UsageBucket {\n key: string;\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens: number;\n cacheWriteTokens: number;\n cents: number;\n calls: number;\n}\n\nexport interface DailyBucket {\n /** YYYY-MM-DD (UTC) */\n date: string;\n cents: number;\n calls: number;\n}\n\nexport interface UsageRecentEntry {\n id: number;\n createdAt: number;\n label: string;\n app: string;\n model: string;\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens: number;\n cacheWriteTokens: number;\n cents: number;\n}\n\nexport interface UsageSummary {\n billing?: UsageBillingMode;\n totalCents: number;\n totalCalls: number;\n totalInputTokens: number;\n totalOutputTokens: number;\n totalCacheReadTokens: number;\n totalCacheWriteTokens: number;\n sinceMs: number;\n byLabel: UsageBucket[];\n byModel: UsageBucket[];\n byApp: UsageBucket[];\n byDay: DailyBucket[];\n recent: UsageRecentEntry[];\n}\n\nconst DAY_MS = 86_400_000;\n\n/**\n * Produce an aggregated spend view for the Usage admin panel.\n * Scoped to the passed owner email; the UI always passes the session user.\n */\nexport async function getUsageSummary(\n options: UsageSummaryOptions,\n): Promise<UsageSummary> {\n await ensureUsageTable();\n const client = getDbExec();\n const sinceMs = options.sinceMs ?? Date.now() - 30 * DAY_MS;\n\n const totalRow = await client.execute({\n sql: `SELECT\n COALESCE(SUM(cost_cents_x100), 0) AS cents,\n COUNT(*) AS calls,\n COALESCE(SUM(input_tokens), 0) AS in_tok,\n COALESCE(SUM(output_tokens), 0) AS out_tok,\n COALESCE(SUM(cache_read_tokens), 0) AS cr_tok,\n COALESCE(SUM(cache_write_tokens), 0) AS cw_tok\n FROM token_usage WHERE owner_email = ? AND created_at >= ?`,\n args: [options.ownerEmail, sinceMs],\n });\n const t = (totalRow.rows[0] ?? {}) as Record<string, number | null>;\n\n const bucketSql = (col: string) => ({\n sql: `SELECT ${col} AS k,\n COALESCE(SUM(cost_cents_x100), 0) AS cents,\n COUNT(*) AS calls,\n COALESCE(SUM(input_tokens), 0) AS in_tok,\n COALESCE(SUM(output_tokens), 0) AS out_tok,\n COALESCE(SUM(cache_read_tokens), 0) AS cr_tok,\n COALESCE(SUM(cache_write_tokens), 0) AS cw_tok\n FROM token_usage\n WHERE owner_email = ? AND created_at >= ?\n GROUP BY ${col}\n ORDER BY cents DESC`,\n args: [options.ownerEmail, sinceMs],\n });\n\n const mapBuckets = (rows: unknown[]): UsageBucket[] =>\n rows.map((r) => {\n const row = r as Record<string, number | string | null>;\n return {\n key: String(row.k ?? \"\"),\n cents: Number(row.cents ?? 0) / 100,\n calls: Number(row.calls ?? 0),\n inputTokens: Number(row.in_tok ?? 0),\n outputTokens: Number(row.out_tok ?? 0),\n cacheReadTokens: Number(row.cr_tok ?? 0),\n cacheWriteTokens: Number(row.cw_tok ?? 0),\n };\n });\n\n const [byLabelR, byModelR, byAppR] = await Promise.all([\n client.execute(bucketSql(\"label\")),\n client.execute(bucketSql(\"model\")),\n client.execute(bucketSql(\"app\")),\n ]);\n\n // By-day aggregation — done in JS so we don't depend on dialect-specific\n // date functions (SQLite `strftime`, Postgres `to_char`). Cheap enough\n // for a 30-day window; if this grows, swap for a dialect-aware query.\n const dayRows = await client.execute({\n sql: `SELECT created_at, cost_cents_x100 FROM token_usage\n WHERE owner_email = ? AND created_at >= ?`,\n args: [options.ownerEmail, sinceMs],\n });\n const dayMap = new Map<string, { cents: number; calls: number }>();\n for (const row of dayRows.rows as Array<Record<string, number>>) {\n const date = new Date(Number(row.created_at)).toISOString().slice(0, 10);\n const prev = dayMap.get(date) ?? { cents: 0, calls: 0 };\n prev.cents += Number(row.cost_cents_x100 ?? 0);\n prev.calls += 1;\n dayMap.set(date, prev);\n }\n const byDay: DailyBucket[] = [...dayMap.entries()]\n .map(([date, v]) => ({\n date,\n cents: v.cents / 100,\n calls: v.calls,\n }))\n .sort((a, b) => a.date.localeCompare(b.date));\n\n const recentRows = await client.execute({\n sql: `SELECT id, created_at, label, app, model,\n input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,\n cost_cents_x100\n FROM token_usage\n WHERE owner_email = ?\n ORDER BY created_at DESC\n LIMIT 50`,\n args: [options.ownerEmail],\n });\n const recent: UsageRecentEntry[] = (\n recentRows.rows as Array<Record<string, number | string | null>>\n ).map((row) => ({\n id: Number(row.id),\n createdAt: Number(row.created_at),\n label: String(row.label ?? \"chat\"),\n app: String(row.app ?? \"\"),\n model: String(row.model ?? \"\"),\n inputTokens: Number(row.input_tokens ?? 0),\n outputTokens: Number(row.output_tokens ?? 0),\n cacheReadTokens: Number(row.cache_read_tokens ?? 0),\n cacheWriteTokens: Number(row.cache_write_tokens ?? 0),\n cents: Number(row.cost_cents_x100 ?? 0) / 100,\n }));\n\n return {\n billing: USD_USAGE_BILLING,\n totalCents: Number(t.cents ?? 0) / 100,\n totalCalls: Number(t.calls ?? 0),\n totalInputTokens: Number(t.in_tok ?? 0),\n totalOutputTokens: Number(t.out_tok ?? 0),\n totalCacheReadTokens: Number(t.cr_tok ?? 0),\n totalCacheWriteTokens: Number(t.cw_tok ?? 0),\n sinceMs,\n byLabel: mapBuckets(byLabelR.rows),\n byModel: mapBuckets(byModelR.rows),\n byApp: mapBuckets(byAppR.rows),\n byDay,\n recent,\n };\n}\n"]}
@@ -0,0 +1,80 @@
1
+ ---
2
+ title: "Automation connectors"
3
+ description: "Safely connect configured workflow systems without treating them as chat channels or generic provider APIs."
4
+ ---
5
+
6
+ # Automation connectors
7
+
8
+ Automation systems coordinate work. They are not messaging channels, and they are not a generic provider-data API.
9
+
10
+ Agent Native's automation connector runtime has two intentionally small directions:
11
+
12
+ - Invoke a **configured external workflow** from an action.
13
+ - Receive an **authenticated callback** from a configured workflow.
14
+
15
+ An app assigns each workflow a stable ID, a connector ID, input/output schemas, response behavior, credentials, timeout/retry limits, idempotency behavior, and capability flags. Agents pass the workflow ID and structured input; they never supply arbitrary target URLs or secret values.
16
+
17
+ ## Safety model
18
+
19
+ Outbound workflow definitions use a static HTTPS base URL and static path. The runtime restricts requests to the configured origin, rejects private-network targets and redirects, resolves `${keys.NAME}` server-side, bounds request and response sizes, applies a timeout, retries only transient failures, and redacts resolved values from responses and errors.
20
+
21
+ Workflow callbacks authenticate with either a shared secret, an HMAC-SHA256 signature, or an app-owned provider verifier. Callbacks that start agent work must provide:
22
+
23
+ 1. A durable, SQL-backed idempotency claim keyed by the provider event ID.
24
+ 2. A durable queue handoff that runs in a fresh execution.
25
+
26
+ The callback returns an acknowledgement quickly. Never run an agent loop inside a webhook request or rely on an in-memory deduplication map.
27
+
28
+ ## n8n
29
+
30
+ n8n is runtime-backed through configured Webhook workflows. Agent Native does **not** host or provision n8n.
31
+
32
+ Configure an n8n Webhook node with an explicit URL and one of n8n's supported authentication modes (Header, Basic, or JWT), then register that static URL/origin and the matching Agent Native secret reference. n8n supports immediate responses, final-node responses, and responses via a Respond to Webhook node; model the selected behavior as asynchronous or synchronous in the workflow definition.
33
+
34
+ For callbacks from n8n into Agent Native, configure an Agent Native callback URL and a shared-secret or HMAC adapter. Include a stable event ID header whenever n8n can retry delivery.
35
+
36
+ See the [n8n Webhook documentation](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.webhook/).
37
+
38
+ ## Zapier
39
+
40
+ Zapier is currently **blueprint-only** in the integration catalog. There is no generic Zapier workflow execution API in this runtime, and Zapier must not be presented as a chat channel or a provider-api preset.
41
+
42
+ Zapier REST Hook triggers are an app-integration contract: an app implements subscribe and unsubscribe endpoints, stores Zapier's unique target URL, and delivers events to that URL. A static inbound webhook is not a public Zapier REST Hook integration.
43
+
44
+ Zapier MCP is a separately configured remote MCP connection with a Zapier account and its own authorization flow. It is not interchangeable with an Agent Native workflow callback credential.
45
+
46
+ See [Zapier REST Hook triggers](https://docs.zapier.com/integrations/build/hook-trigger) and [Zapier MCP](https://docs.zapier.com/mcp/home).
47
+
48
+ ## App setup
49
+
50
+ Create a runtime and expose only the narrow action:
51
+
52
+ ```ts
53
+ import {
54
+ createAutomationRuntime,
55
+ createInvokeAutomationWorkflowAction,
56
+ } from "@agent-native/core/automation";
57
+
58
+ const automation = createAutomationRuntime({
59
+ workflows: [
60
+ /* app-owned static workflow definitions */
61
+ ],
62
+ resolveSecret: async (ref, context) => {
63
+ // Resolve a scoped vault/credential reference here. Never return it to UI.
64
+ return null;
65
+ },
66
+ claimInboundEvent: async ({ workflow, eventId }) => {
67
+ // Insert a unique SQL row and return false on a duplicate event.
68
+ return true;
69
+ },
70
+ enqueueInboundEvent: async ({ workflow, eventId, payload }) => {
71
+ // Reuse the app's established durable queue; do not run an agent here.
72
+ },
73
+ });
74
+
75
+ export default createInvokeAutomationWorkflowAction(automation);
76
+ ```
77
+
78
+ Mount callback handlers only under `/_agent-native/automations/`; all normal app operations remain actions. Keep the callback route minimal: authenticate, claim idempotency, enqueue, and acknowledge.
79
+
80
+ The client can call a registered action with `invokeConfiguredAutomationWorkflow()` from `@agent-native/core/client`; it does not hand-write a browser `fetch`.
@@ -17,6 +17,14 @@ If you've used QuickBooks Online, you've seen the model: QBO ships a core accoun
17
17
 
18
18
  The framing matters: an extension isn't a generic "do whatever you want" sandbox. It's a **mini-app that extends a specific template** — Mail, Analytics, Calendar, Clips, Design — and uses that template's actions and data. A Mail extension reads emails. An Analytics extension reads a dashboard's metrics. A Calendar extension acts on the open event. They feel like part of the host product because they _are_ part of the host product.
19
19
 
20
+ > **Extensions add UI; they do not rewrite the host UI.** An extension renders on
21
+ > its own page or inside a named [slot](#slots) exposed by the template. It
22
+ > cannot inject elements into arbitrary native components — for example, beside
23
+ > every attendee in Calendar — unless the template exposes a slot there. For
24
+ > deeper customization, ask the agent to edit the template's source code. Full
25
+ > code customization is a core Agent Native capability; extensions are the
26
+ > fast, no-deploy layer.
27
+
20
28
  Three things make extensions work:
21
29
 
22
30
  - **No code, no deploy.** The agent writes them and they're live in seconds. Stored in the database, not the repo.
@@ -11,6 +11,14 @@ description: "التطبيقات المصغرة التي ينشئها المست
11
11
 
12
12
  التأطير مهم: الإضافة ليست عبارة عن وضع حماية عام "افعل ما تريد". إنه **تطبيق صغير يعمل على توسيع قالب معين** - البريد والتحليلات والتقويم والقصاصات والتصميم - ويستخدم actions لهذا القالب وبياناته. ملحق البريد يقرأ رسائل البريد الإلكتروني. يقرأ ملحق Analytics مقاييس لوحة المعلومات. يعمل ملحق التقويم على الحدث المفتوح. إنهم يشعرون وكأنهم جزء من المنتج المضيف لأنهم _هم_ جزء من المنتج المضيف.
13
13
 
14
+ > **تضيف الامتدادات واجهة مستخدم، لكنها لا تعيد كتابة واجهة التطبيق
15
+ > المضيف.** يظهر الامتداد في صفحته الخاصة أو داخل [فتحة](#slots) مسماة
16
+ > يوفّرها القالب. ولا يمكنه إدراج عناصر داخل مكونات أصلية عشوائية — مثل
17
+ > وضع عنصر بجوار كل حاضر في التقويم — ما لم يوفّر القالب فتحة في ذلك الموضع.
18
+ > وللتخصيص الأعمق، اطلب من الوكيل تعديل التعليمات البرمجية المصدرية للقالب.
19
+ > يُعد التخصيص الكامل للتعليمات البرمجية قدرة أساسية في Agent Native؛ أما
20
+ > الامتدادات فهي طبقة سريعة لا تتطلب النشر.
21
+
14
22
  هناك ثلاثة أشياء تجعل الإضافات تعمل:
15
23
 
16
24
  - **لا يوجد تعليمات برمجية، ولا يوجد نشر.** يكتبها الوكيل وستكون مباشرة في ثوانٍ. مخزنة في قاعدة البيانات، وليس الريبو.
@@ -1,11 +1,15 @@
1
1
  ---
2
2
  title: "المراسلة"
3
- description: "تحدث إلى وكيلك من Slack أو البريد الإلكتروني أو Telegram أو WhatsApp - نفس الوكيل، نفس الذاكرة، نفس الأدوات."
3
+ description: "تحدث إلى وكيلك عبر Slack أو Microsoft Teams أو تفاعلات Discord أو البريد الإلكتروني أو Telegram أو WhatsApp."
4
4
  ---
5
5
 
6
6
  # المراسلة
7
7
 
8
- قم بتوصيل وكيلك بـ Slack أو البريد الإلكتروني أو Telegram أو WhatsApp حتى تتمكن من الدردشة معه من التطبيقات التي تستخدمها بالفعل. إنه نفس الوكيل - نفس الذاكرة، نفس الأدوات، نفس المواضيع - يمكن الوصول إليه من أماكن أكثر.
8
+ قم بتوصيل وكيلك بـ Slack أو Microsoft Teams أو تفاعلات Discord أو البريد الإلكتروني أو Telegram أو WhatsApp. إنه الوكيل نفسه بنفس الذاكرة والأدوات وسجل المحادثات.
9
+
10
+ > **نطاق الدعم بدقة:** يتحقق Teams من رموز JWT الرسمية لـ Bot Framework ويرد في المحادثة الأصلية. يدعم Discord أوامر الشرطة المائلة عبر تفاعلات HTTP الموقعة بـ Ed25519 مع إقرار مؤجل؛ ولا يستقبل رسائل الخادم العادية أو الرسائل المباشرة من دون تشغيل Gateway. يحتفظ Telegram بـ `message_thread_id` ويستخدم WhatsApp قيمة `wamid` الواردة للردود السياقية.
11
+ >
12
+ > يتطلب Teams القيم `MICROSOFT_TEAMS_APP_ID` و`MICROSOFT_TEAMS_APP_PASSWORD` و`MICROSOFT_TEAMS_ALLOWED_TENANT_IDS`. ويتطلب Discord القيم `DISCORD_APPLICATION_ID` و`DISCORD_PUBLIC_KEY`. كما يتطلب Telegram القيمة `TELEGRAM_WEBHOOK_SECRET` ويتطلب WhatsApp القيمة `WHATSAPP_APP_SECRET` بالإضافة إلى بيانات الاعتماد الحالية.
9
13
 
10
14
  > **هل تستخدم قالب الإرسال؟** تم إعداد كل هذا لك في **الإعدادات → المراسلة**. انقر لربط كل نظام أساسي — لن تحتاج إلى قراءة بقية هذه الصفحة إلا إذا كنت تقوم بتخصيص القالب الخاص بك أو إنشائه. راجع [Dispatch](/docs/dispatch) أو [Dispatch template reference](/docs/template-dispatch).
11
15
 
@@ -78,7 +82,6 @@ description: "تحدث إلى وكيلك من Slack أو البريد الإلك
78
82
  - `chat:write` — يتيح للوكيل إرسال الرسائل
79
83
  - `app_mentions:read` — يتيح للوكيل معرفة متى يتم ذكره @ (اختياري)
80
84
  - `im:history` — يتيح للوكيل قراءة الرسائل المباشرة المرسلة إليه
81
- - `assistant:write` — اختياري؛ يتيح لـ Slack عرض حالة "يفكر..." الأصلية في سلاسل الرسائل المساعدة
82
85
  - `users:read.email` — اختياري؛ تساعد القوالب مثل البريد في التحقق من البريد الإلكتروني للمرسل Slack للحصول على هوية قائمة انتظار المسودة
83
86
  3. انقر فوق **التثبيت على مساحة العمل** أعلى تلك الصفحة. سوف يمنحك Slack **رمز Bot User OAuth** الذي يبدأ بـ `xoxb-`. انسخه.
84
87
  4. انتقل إلى **المعلومات الأساسية** في الشريط الجانبي وانسخ **سر التوقيع**.
@@ -123,12 +126,76 @@ https://your-clips.example.com/api/slack/unfurl
123
126
 
124
127
  ### نصائح
125
128
 
126
- - **إشارات القناة** — لا يستجيب الروبوت إلا في القنوات عندما تتم الإشارة إليها بال@، وذلك لتجنب الضوضاء.
127
- - **الرسائل المباشرة** — يتم التعامل مع كل رسالة مباشرة على أنها محادثة خاصة مع الوكيل.
128
- - **نفس الهوية، جميع القنوات** إذا كان مستخدم Slack لديه نفس البريد الإلكتروني كمستخدم مسجل في تطبيقك، فسيعامله الوكيل على أنه نفس الشخص.
129
+ - **إشارات القناة** — استخدم @mention لبدء العمل. تُقبل الردود بلا إشارة فقط ما دام العمل نشطًا في سلسلة الرسائل نفسها.
130
+ - **الرسائل المباشرة** — الرسائل الخاصة المقبولة هي محادثات سرية، وتتطلب عضوًا موثّقًا في المؤسسة أو هوية Slack مرتبطة.
131
+ - **الهوية** يمكن للرسائل الخاصة ربط بريد Slack الموثق بالمستخدم نفسه في التطبيق؛ تستخدم القنوات المُدارة هوية الخدمة والسياسة الخاصة بها.
129
132
  - **قوائم الإنتاج المسموح بها** — قم بتعيين `SLACK_ALLOWED_TEAM_IDS`، وبالنسبة لتطبيقات Slack المشتركة، `SLACK_ALLOWED_API_APP_IDS` بحيث لا يمكن إعادة استخدام سر التوقيع الصالح بواسطة مساحة عمل غير متوقعة.
130
133
  - **نشر تطبيق Clips** — تستخدم مقاطع Agent-Native القابلة للتثبيت لـ Slack `SLACK_CLIENT_ID`، و`SLACK_CLIENT_SECRET`، و`SLACK_SIGNING_SECRET`، و`/api/slack/oauth/callback`. تحصل كل مساحة عمل Slack متصلة على رمز الروبوت المشفر الخاص بها في `app_secrets`؛ `SLACK_BOT_TOKEN` ما هو إلا نسخة احتياطية قديمة لمساحة عمل واحدة.
131
134
 
135
+ ### الإعداد المُدار عبر Add to Slack
136
+
137
+ OAuth المُدار هو الإعداد الموصى به. من **الإعدادات → المراسلة**، اختر
138
+ **Agent manifest** لتنزيل ملف `agent-native-slack-manifest.json` الخاص بمضيفك،
139
+ ثم استورده من **App Manifest** في Slack. يفعّل الملف تجربة `agent_view` الحالية
140
+ وعلامة تبويب **Messages** قابلة للكتابة للرسائل المباشرة. تحقّق من هذه النطاقات:
141
+
142
+ لا يتضمن البيان أيقونة التطبيق. ضمن **Basic Information → Display Information**،
143
+ ارفع أيقونة Agent Native كي تتطابق قائمة Agents مع هوية المنتج. يمكنك استخدام
144
+ `icon-512.svg` العام للتطبيق كمصدر وتحويله إلى تنسيق رفع يدعمه Slack عند الحاجة.
145
+
146
+ ```text
147
+ assistant:write
148
+ app_mentions:read
149
+ channels:history
150
+ channels:read
151
+ chat:write
152
+ files:read
153
+ groups:history
154
+ groups:read
155
+ im:history
156
+ im:read
157
+ mpim:history
158
+ mpim:read
159
+ pins:read
160
+ reactions:read
161
+ users:read
162
+ users:read.email
163
+ ```
164
+
165
+ اضبط OAuth Redirect URL على
166
+ `https://your-app.example.com/_agent-native/integrations/slack/oauth/callback`،
167
+ وEvent Subscriptions Request URL على
168
+ `https://your-app.example.com/_agent-native/integrations/slack/webhook`،
169
+ وInteractivity Request URL على
170
+ `https://your-app.example.com/_agent-native/integrations/slack/interactions`.
171
+ اشترك في `app_home_opened` و`app_context_changed` و`app_mention`
172
+ و`message.channels` و`message.groups` و`message.im` و`message.mpim`.
173
+ بعد إعداد `SLACK_CLIENT_ID` و`SLACK_CLIENT_SECRET`
174
+ و`SLACK_SIGNING_SECRET`، افتح **الإعدادات → المراسلة** وانقر **Add to Slack**.
175
+ يُخزّن كل تثبيت رمزًا مشفرًا منفصلًا، وتفصل مفاتيح المحادثة بين مساحة العمل
176
+ والتطبيق والقناة وسلسلة الرسائل.
177
+
178
+ أعد تثبيت تطبيق Slack بعد تغيير البيان أو النطاقات أو الأحداث أو Agent view أو
179
+ علامة تبويب Messages. يستخدم `app_home_opened` لاكتشاف فتح الرسائل المباشرة،
180
+ ويضيف `app_context_changed` سياق العرض الحالي، ويسلّم `message.im` الرسائل الخاصة.
181
+ قد يخفي مسؤولو Slack الوكلاء المثبتين عن المؤسسة، كما يمكن لكل مستخدم إخفاؤهم من
182
+ الشريط العلوي. إذا نجح التثبيت ولم يظهر الوكيل، فتحقق من عناصر التحكم هذه أو افتحه
183
+ من **Tools → Apps**.
184
+
185
+ لا تُقبل الرسائل الخاصة الشخصية في Slack إلا من عضو موثّق في مؤسسة Agent Native
186
+ أو من هوية Slack مرتبطة مسبقًا بذلك العضو. أما سياسات وميزانيات هوية الخدمة الخاصة
187
+ بالقناة فهي منفصلة.
188
+
189
+ أثناء تشغيل مهمة في سلسلة رسائل، تواصل الردود غير المشار إليها المهمة نفسها؛
190
+ ولا تبدأ محادثات القناة العامة مهمة. يحمّل الوكيل سياقًا محدودًا مع التفاعلات
191
+ ومراجع الملفات فقط، ويعرض خطة وتقدمًا مباشرًا مع أزرار الإلغاء والموافقة/الرفض.
192
+ الرسائل الخاصة تستخدم هوية المستخدم الشخصية، بينما تستخدم القنوات المُدارة هوية
193
+ خدمة صريحة وسياسات للضيوف وSlack Connect والنموذج الافتراضي. ذاكرة القناة صريحة
194
+ ومعزولة ولا تُحفظ تلقائيًا. تحتفظ الإجراءات الدورية التي تُنشأ من القناة بوجهة
195
+ Slack، وتفرض ميزانيات يومية أو شهرية للمؤسسة أو الطالب أو القناة مع سجل تدقيق كامل.
196
+ يتيح `assistant:write` أحداث سياق Agent View، بينما يتيح `chat:write` الردود
197
+ وتحديثات الحالة المباشرة.
198
+
132
199
  ## إعداد تيليجرام {#telegram}
133
200
 
134
201
  ### ما ستحتاج إليه
@@ -435,7 +502,9 @@ POST /_agent-native/integrations/telegram/setup
435
502
  | البريد الإلكتروني | `EMAIL_AGENT_ADDRESS`، بالإضافة إلى واحد من `RESEND_API_KEY` أو `SENDGRID_API_KEY` | `EMAIL_INBOUND_WEBHOOK_SECRET` |
436
503
  | واتساب | `WHATSAPP_ACCESS_TOKEN`, `WHATSAPP_VERIFY_TOKEN`, `WHATSAPP_PHONE_NUMBER_ID` | — |
437
504
 
438
- جميع بيانات الاعتماد موجودة في env vars - وليس قاعدة البيانات أبدًا، ولا كود المصدر أبدًا. استخدم إعدادات الشريط الجانبي UI أو لوحة البيئة الخاصة بموفر الاستضافة.
505
+ يتم حل بيانات اعتماد التكامل أولاً من الأسرار ذات النطاق لمالك التكامل (المستخدم ثم المؤسسة ثم مساحة العمل)؛ وتكون متغيرات بيئة النشر بديلاً للتثبيت المحلي أو أحادي المستأجر المقصود. تحفظ واجهة الإعداد أسراراً ذات نطاق؛ ولا تُعاد القيم أبداً إلى المتصفح أو تُخزَّن في كود المصدر.
506
+
507
+ محولات وقت التشغيل المضمنة هي **Slack** و**Telegram** و**WhatsApp Cloud API** والبريد الإلكتروني عبر webhooks لموفر الخدمة (Resend أو SendGrid). لا يمكن توصيل Discord أو Microsoft Teams حتى يتم تنفيذ محول تم التحقق منه وتسجيله.
439
508
 
440
509
  ### الترابط والهوية {#threading-and-identity}
441
510
 
@@ -481,13 +550,13 @@ import type {
481
550
  import type { EnvKeyConfig } from "@agent-native/core/server";
482
551
 
483
552
  const myAdapter: PlatformAdapter = {
484
- platform: "discord",
485
- label: "Discord",
553
+ platform: "my-chat",
554
+ label: "My Chat",
486
555
 
487
556
  // Env keys this adapter needs (rendered in the settings UI)
488
557
  getRequiredEnvKeys(): EnvKeyConfig[] {
489
558
  return [
490
- { key: "DISCORD_BOT_TOKEN", label: "Discord Bot Token", required: true },
559
+ { key: "MY_CHAT_BOT_TOKEN", label: "My Chat Bot Token", required: true },
491
560
  ];
492
561
  },
493
562
 
@@ -507,10 +576,10 @@ const myAdapter: PlatformAdapter = {
507
576
  // Return null to silently ignore the event (bot messages, edits, etc.).
508
577
  async parseIncomingMessage(event: H3Event): Promise<IncomingMessage | null> {
509
578
  return {
510
- platform: "discord",
579
+ platform: "my-chat",
511
580
  externalThreadId: "channel-or-thread-id",
512
581
  text: "the user's message",
513
- senderId: "discord-user-id",
582
+ senderId: "my-chat-user-id",
514
583
  platformContext: { channelId: "channel-id" },
515
584
  timestamp: Date.now(),
516
585
  };
@@ -538,10 +607,10 @@ const myAdapter: PlatformAdapter = {
538
607
  // baseUrl is the app's public URL, used for status checks that need it.
539
608
  async getStatus(baseUrl?: string) {
540
609
  return {
541
- platform: "discord",
542
- label: "Discord",
610
+ platform: "my-chat",
611
+ label: "My Chat",
543
612
  enabled: true,
544
- configured: !!process.env.DISCORD_BOT_TOKEN,
613
+ configured: !!process.env.MY_CHAT_BOT_TOKEN,
545
614
  };
546
615
  },
547
616
  };
@@ -77,6 +77,7 @@ search: "سجلات متصفح Clips، سجلات المطورين، سجلات
77
77
  ## ما يمكنك فعله به
78
78
 
79
79
  - **سجل شاشتك** باستخدام مسجل مدمج وتراكب كاميرا الويب والتقاط الصوت والإيقاف المؤقت/الاقتطاع.
80
+ - **استورد مقاطع فيديو Loom العامة.** على الويب، اختر **تسجيل ← استيراد Loom**، ثم الصق رابط مشاركة أو تضمين من Loom. يحفظ Clips نسخة في مكتبتك ويستورد النص العام عندما يكون متاحًا.
80
81
  - **التقط الاجتماعات من التقويم الخاص بك.** قم بتوصيل Google Calendar، وشاهد الاجتماعات القادمة في الشريط الجانبي، ثم اضغط على تسجيل أي اجتماع. ستحصل على نص مباشر بالإضافة إلى ملخص AI وملاحظات نقطية وعناصر عمل بمجرد انتهاء النص.
81
82
  - **إملاء الضغط والتحدث.** اضغط باستمرار على Fn على جهازك، وتحدث، وسيسقط النص المنظف في أي تطبيق تستخدمه. يتم الاحتفاظ بكل إملاء في سجل قابل للبحث مع النسخ الأصلية والإصدارات التي تم تنظيفها بواسطة الذكاء الاصطناعي جنبًا إلى جنب.
82
83
  - **احصل على عنوان وملخص وعلامات فصول يتم إنشاؤها تلقائيًا** لكل تسجيل — يقوم الوكيل بملئها وتحديثها باستمرار.
@@ -91,6 +91,7 @@ description: "استوديو نماذج أولية HTML للوكيل - يمكن
91
91
  ## ما يمكنك فعله به
92
92
 
93
93
  - **إنشاء نماذج أولية كاملة.** قم بوصف الشاشة أو الصفحة التي تحتاجها وسيقوم الوكيل بإنشاء مستند HTML صالح مع تصميم Tailwind وAlpine interactions.
94
+ - **ابدأ من قوالب قابلة لإعادة الاستخدام.** اختر مقاسًا جاهزًا للإعلانات أو مستندات الصفحة الواحدة أو صفحات الهبوط، أو احفظ أي تصميم مضمّن كقالب. تعدّل المطالبة المحتوى غير المقفل فقط وتحافظ على الشعارات والخلفيات المقفلة.
94
95
  - **مقارنة المتغيرات.** ابدأ باتجاهات متعددة، واختر الاتجاه الأقوى، ثم تابع التحسين.
95
96
  - **التعديل بشكل مرئي.** استخدم عناصر التحكم في التعديل المضمنة لإجراء التغييرات الشائعة، أو اطلب من الوكيل تحديثات النسخ والتخطيط واللون والتباعد والتفاعل.
96
97
  - **تطبيق أنظمة التصميم.** يمكنك حفظ تفضيلات نظام التصميم وإعادة استخدامها حتى يظل العمل الذي يتم إنشاؤه أقرب إلى علامتك التجارية.