qarpeo 0.1.34 → 0.2.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 (364) hide show
  1. package/README.md +114 -26
  2. package/dist/apps/cms.d.ts +4 -0
  3. package/dist/apps/comments.d.ts +4 -0
  4. package/dist/apps/payments.d.ts +4 -0
  5. package/dist/apps/store.d.ts +4 -0
  6. package/dist/chunks/auth-schema.mjs +169 -30
  7. package/dist/chunks/tools.mjs +1680 -0
  8. package/dist/cli/index.mjs +1256 -221
  9. package/dist/core/aliases.d.ts +5 -0
  10. package/dist/core/context.d.ts +10 -0
  11. package/dist/core/cross-drive.d.ts +2 -0
  12. package/dist/core/d1-migrate.d.ts +4 -0
  13. package/dist/core/devtools.d.ts +4 -0
  14. package/dist/core/nitro.d.ts +4 -0
  15. package/dist/core/schema.d.ts +4 -0
  16. package/dist/core/server-utils.d.ts +4 -0
  17. package/dist/core/wrangler.d.ts +4 -0
  18. package/dist/dev/wrangler.d.ts +1 -0
  19. package/dist/fate/index.d.ts +8 -8
  20. package/dist/features/agents.d.ts +4 -0
  21. package/dist/features/auth.d.ts +4 -0
  22. package/dist/features/bots.d.ts +4 -0
  23. package/dist/features/fate.d.ts +4 -0
  24. package/dist/features/mail.d.ts +4 -0
  25. package/dist/features/mcp.d.ts +4 -0
  26. package/dist/features/multitenant.d.ts +4 -0
  27. package/dist/features/notifications.d.ts +4 -0
  28. package/dist/features/realtime.d.ts +4 -0
  29. package/dist/module.d.ts +10 -2
  30. package/dist/module.mjs +6313 -5114
  31. package/dist/primitives/ai.d.ts +4 -0
  32. package/dist/primitives/analytics.d.ts +4 -0
  33. package/dist/primitives/blob.d.ts +4 -0
  34. package/dist/primitives/browser.d.ts +4 -0
  35. package/dist/primitives/cache.d.ts +4 -0
  36. package/dist/primitives/d1.d.ts +4 -0
  37. package/dist/primitives/do.d.ts +4 -0
  38. package/dist/primitives/email.d.ts +4 -0
  39. package/dist/primitives/hyperdrive.d.ts +4 -0
  40. package/dist/primitives/kv.d.ts +4 -0
  41. package/dist/primitives/queue.d.ts +4 -0
  42. package/dist/primitives/ratelimit.d.ts +4 -0
  43. package/dist/primitives/vectorize.d.ts +4 -0
  44. package/dist/primitives/workflows.d.ts +4 -0
  45. package/dist/runtime/ai.d.ts +3 -3
  46. package/dist/runtime/ai.mjs +8 -1
  47. package/dist/runtime/app/components/RealtimeCursors.vue +2 -2
  48. package/dist/runtime/app/composables/ai.d.ts +56 -29
  49. package/dist/runtime/app/composables/analytics.d.ts +26 -106
  50. package/dist/runtime/app/composables/api-tokens.d.ts +31 -34
  51. package/dist/runtime/app/composables/auth.d.ts +147 -51
  52. package/dist/runtime/app/composables/auth.mjs +0 -7
  53. package/dist/runtime/app/composables/chat.d.ts +38 -35
  54. package/dist/runtime/app/composables/cms-preview.d.ts +30 -25
  55. package/dist/runtime/app/composables/cms.d.ts +57 -282
  56. package/dist/runtime/app/composables/cms.mjs +0 -35
  57. package/dist/runtime/app/composables/comments.d.ts +32 -5
  58. package/dist/runtime/app/composables/comments.mjs +29 -1
  59. package/dist/runtime/app/composables/docs-version.d.ts +25 -28
  60. package/dist/runtime/app/composables/impersonation.d.ts +22 -5
  61. package/dist/runtime/app/composables/organization.d.ts +38 -91
  62. package/dist/runtime/app/composables/passkey.d.ts +22 -6
  63. package/dist/runtime/app/composables/passwordless.d.ts +24 -7
  64. package/dist/runtime/app/composables/payments.d.ts +50 -34
  65. package/dist/runtime/app/composables/payments.mjs +1 -0
  66. package/dist/runtime/app/composables/sse.d.ts +76 -0
  67. package/dist/runtime/app/composables/sse.mjs +152 -0
  68. package/dist/runtime/app/composables/storage.d.ts +53 -65
  69. package/dist/runtime/app/composables/storage.mjs +17 -0
  70. package/dist/runtime/app/composables/store.d.ts +198 -0
  71. package/dist/runtime/app/composables/store.mjs +414 -0
  72. package/dist/runtime/app/composables/tenant.d.ts +31 -72
  73. package/dist/runtime/app/composables/turnstile.d.ts +16 -3
  74. package/dist/runtime/app/composables/two-factor.d.ts +23 -6
  75. package/dist/runtime/app/pages/devtools/notifications.vue +30 -27
  76. package/dist/runtime/app/pages/devtools/realtime.vue +19 -31
  77. package/dist/runtime/app/pages/devtools.vue +0 -7
  78. package/dist/runtime/auth.d.ts +9 -9
  79. package/dist/runtime/blob.d.ts +10 -1
  80. package/dist/runtime/blob.mjs +83 -0
  81. package/dist/runtime/cache.d.ts +48 -0
  82. package/dist/runtime/cache.mjs +92 -0
  83. package/dist/runtime/comments.d.ts +4 -0
  84. package/dist/runtime/comments.mjs +2 -0
  85. package/dist/runtime/db.d.ts +21 -1
  86. package/dist/runtime/db.mjs +54 -0
  87. package/dist/runtime/drizzle.d.ts +4 -2
  88. package/dist/runtime/drizzle.mjs +68 -1
  89. package/dist/runtime/durable-object.d.ts +2 -0
  90. package/dist/runtime/durable-object.mjs +2 -0
  91. package/dist/runtime/email.d.ts +1 -1
  92. package/dist/runtime/email.mjs +1 -1
  93. package/dist/runtime/kv.mjs +50 -1
  94. package/dist/runtime/mcp.d.ts +2 -0
  95. package/dist/runtime/mcp.mjs +2 -0
  96. package/dist/runtime/queue.d.ts +12 -2
  97. package/dist/runtime/queue.mjs +19 -1
  98. package/dist/runtime/ratelimit.d.ts +1 -0
  99. package/dist/runtime/ratelimit.mjs +7 -0
  100. package/dist/runtime/schema.d.ts +313 -0
  101. package/dist/runtime/schema.mjs +259 -0
  102. package/dist/runtime/server/db/cms-schema.d.ts +1225 -171
  103. package/dist/runtime/server/db/cms-schema.mjs +69 -70
  104. package/dist/runtime/server/db/store-schema.d.ts +4344 -0
  105. package/dist/runtime/server/db/store-schema.mjs +266 -0
  106. package/dist/runtime/server/durable-objects/agent.mjs +35 -0
  107. package/dist/runtime/server/durable-objects/room.mjs +0 -1
  108. package/dist/runtime/server/middleware/ratelimit.mjs +10 -8
  109. package/dist/runtime/server/plugins/comments.d.ts +7 -0
  110. package/dist/runtime/server/plugins/comments.mjs +7 -0
  111. package/dist/runtime/server/plugins/email-inbound.d.ts +5 -0
  112. package/dist/runtime/server/plugins/email-inbound.mjs +17 -0
  113. package/dist/runtime/server/plugins/store.d.ts +7 -0
  114. package/dist/runtime/server/plugins/store.mjs +7 -0
  115. package/dist/runtime/server/routes/__qarpeo/db/tables.get.mjs +2 -2
  116. package/dist/runtime/server/routes/atom.xml.get.mjs +3 -1
  117. package/dist/runtime/server/routes/auth/2fa/disable.post.mjs +13 -2
  118. package/dist/runtime/server/routes/auth/2fa/setup.post.mjs +9 -3
  119. package/dist/runtime/server/routes/auth/2fa/verify.post.mjs +11 -3
  120. package/dist/runtime/server/routes/auth/account.delete.mjs +2 -1
  121. package/dist/runtime/server/routes/auth/audit-logs.get.mjs +1 -1
  122. package/dist/runtime/server/routes/auth/magic-link/send.post.d.ts +1 -9
  123. package/dist/runtime/server/routes/auth/magic-link/send.post.mjs +8 -0
  124. package/dist/runtime/server/routes/auth/organization/sso/[id].delete.mjs +1 -1
  125. package/dist/runtime/server/routes/auth/organization/sso/index.get.mjs +1 -1
  126. package/dist/runtime/server/routes/auth/organization/sso/index.post.mjs +1 -1
  127. package/dist/runtime/server/routes/auth/otp/send.post.d.ts +1 -9
  128. package/dist/runtime/server/routes/auth/otp/send.post.mjs +8 -0
  129. package/dist/runtime/server/routes/auth/sso/login.get.mjs +3 -3
  130. package/dist/runtime/server/routes/auth/sso/oidc/callback.get.mjs +1 -1
  131. package/dist/runtime/server/routes/auth/sso/saml/acs.post.mjs +2 -2
  132. package/dist/runtime/server/routes/auth/webauthn/login/options.post.mjs +1 -1
  133. package/dist/runtime/server/routes/auth/webauthn/login/verify.post.mjs +1 -1
  134. package/dist/runtime/server/routes/auth/webauthn/register/options.post.mjs +2 -2
  135. package/dist/runtime/server/routes/auth/webauthn/register/verify.post.mjs +1 -1
  136. package/dist/runtime/server/routes/cms/[collection]/[id]/preview-token.post.mjs +1 -1
  137. package/dist/runtime/server/routes/cms/[collection]/atom.xml.get.mjs +3 -1
  138. package/dist/runtime/server/routes/cms/[collection]/feed.xml.get.mjs +3 -1
  139. package/dist/runtime/server/routes/cms/bookmarks/[id].delete.mjs +1 -1
  140. package/dist/runtime/server/routes/cms/bookmarks/check.post.mjs +1 -1
  141. package/dist/runtime/server/routes/cms/bookmarks/index.get.mjs +1 -1
  142. package/dist/runtime/server/routes/cms/bookmarks/index.post.mjs +1 -1
  143. package/dist/runtime/server/routes/cms/deploy.post.mjs +1 -1
  144. package/dist/runtime/server/routes/cms/export.post.mjs +4 -3
  145. package/dist/runtime/server/routes/cms/search.get.mjs +7 -5
  146. package/dist/runtime/server/routes/cms/sync.post.mjs +2 -1
  147. package/dist/runtime/server/routes/comments/[id]/react.post.mjs +1 -2
  148. package/dist/runtime/server/routes/comments/[id]/report.post.d.ts +1 -1
  149. package/dist/runtime/server/routes/comments/[id]/report.post.mjs +0 -2
  150. package/dist/runtime/server/routes/comments/[id].delete.mjs +8 -4
  151. package/dist/runtime/server/routes/comments/[id].get.d.ts +1 -1
  152. package/dist/runtime/server/routes/comments/[id].get.mjs +1 -2
  153. package/dist/runtime/server/routes/comments/[id].patch.d.ts +1 -1
  154. package/dist/runtime/server/routes/comments/[id].patch.mjs +6 -3
  155. package/dist/runtime/server/routes/comments/batch.post.d.ts +2 -0
  156. package/dist/runtime/server/routes/comments/batch.post.mjs +33 -0
  157. package/dist/runtime/server/routes/comments/index.get.d.ts +1 -1
  158. package/dist/runtime/server/routes/comments/index.get.mjs +6 -4
  159. package/dist/runtime/server/routes/comments/index.post.d.ts +1 -1
  160. package/dist/runtime/server/routes/comments/index.post.mjs +6 -2
  161. package/dist/runtime/server/routes/feed.xml.get.mjs +3 -1
  162. package/dist/runtime/server/routes/sitemap.xml.get.mjs +3 -1
  163. package/dist/runtime/server/routes/storage/presigned-r2.post.d.ts +17 -0
  164. package/dist/runtime/server/routes/storage/presigned-r2.post.mjs +29 -0
  165. package/dist/runtime/server/routes/store/cart/index.delete.d.ts +6 -0
  166. package/dist/runtime/server/routes/store/cart/index.delete.mjs +11 -0
  167. package/dist/runtime/server/routes/store/cart/index.get.d.ts +5 -0
  168. package/dist/runtime/server/routes/store/cart/index.get.mjs +14 -0
  169. package/dist/runtime/server/routes/store/cart/items/[id].delete.d.ts +6 -0
  170. package/dist/runtime/server/routes/store/cart/items/[id].delete.mjs +25 -0
  171. package/dist/runtime/server/routes/store/cart/items/[id].patch.d.ts +6 -0
  172. package/dist/runtime/server/routes/store/cart/items/[id].patch.mjs +29 -0
  173. package/dist/runtime/server/routes/store/cart/items.post.d.ts +6 -0
  174. package/dist/runtime/server/routes/store/cart/items.post.mjs +36 -0
  175. package/dist/runtime/server/routes/store/categories/index.get.d.ts +2 -0
  176. package/dist/runtime/server/routes/store/categories/index.get.mjs +8 -0
  177. package/dist/runtime/server/routes/store/checkout.post.d.ts +6 -0
  178. package/dist/runtime/server/routes/store/checkout.post.mjs +21 -0
  179. package/dist/runtime/server/routes/store/coupons/apply.post.d.ts +7 -0
  180. package/dist/runtime/server/routes/store/coupons/apply.post.mjs +18 -0
  181. package/dist/runtime/server/routes/store/currencies.get.d.ts +15 -0
  182. package/dist/runtime/server/routes/store/currencies.get.mjs +13 -0
  183. package/dist/runtime/server/routes/store/orders/[id].get.d.ts +2 -0
  184. package/dist/runtime/server/routes/store/orders/[id].get.mjs +26 -0
  185. package/dist/runtime/server/routes/store/orders/download/[token].get.d.ts +7 -0
  186. package/dist/runtime/server/routes/store/orders/download/[token].get.mjs +57 -0
  187. package/dist/runtime/server/routes/store/orders/index.get.d.ts +5 -0
  188. package/dist/runtime/server/routes/store/orders/index.get.mjs +30 -0
  189. package/dist/runtime/server/routes/store/products/[slug].get.d.ts +2 -0
  190. package/dist/runtime/server/routes/store/products/[slug].get.mjs +18 -0
  191. package/dist/runtime/server/routes/store/products/index.get.d.ts +5 -0
  192. package/dist/runtime/server/routes/store/products/index.get.mjs +33 -0
  193. package/dist/runtime/server/routes/store/tax/calculate.post.d.ts +9 -0
  194. package/dist/runtime/server/routes/store/tax/calculate.post.mjs +18 -0
  195. package/dist/runtime/server/routes/tenants/[tenant]/domains/[domain]/index.delete.mjs +14 -1
  196. package/dist/runtime/server/routes/tenants/[tenant]/domains/[domain]/verify.post.mjs +14 -1
  197. package/dist/runtime/server/routes/tenants/[tenant]/domains/index.get.mjs +24 -1
  198. package/dist/runtime/server/routes/tenants/[tenant]/domains/index.post.mjs +6 -0
  199. package/dist/runtime/server/utils/ai.d.ts +146 -21
  200. package/dist/runtime/server/utils/ai.mjs +406 -11
  201. package/dist/runtime/server/utils/analytics-query.d.ts +13 -58
  202. package/dist/runtime/server/utils/audit.d.ts +5 -4
  203. package/dist/runtime/server/utils/audit.mjs +25 -14
  204. package/dist/runtime/server/utils/auth.d.ts +29 -12
  205. package/dist/runtime/server/utils/auth.mjs +88 -70
  206. package/dist/runtime/server/utils/bots.d.ts +20 -4
  207. package/dist/runtime/server/utils/bots.mjs +7 -3
  208. package/dist/runtime/server/utils/browser-utils.d.ts +23 -23
  209. package/dist/runtime/server/utils/cache.d.ts +31 -10
  210. package/dist/runtime/server/utils/cache.mjs +130 -53
  211. package/dist/runtime/server/utils/cms/collections.d.ts +23 -0
  212. package/dist/runtime/server/utils/cms/collections.mjs +143 -0
  213. package/dist/runtime/server/utils/cms/common.d.ts +9 -0
  214. package/dist/runtime/server/utils/cms/common.mjs +28 -0
  215. package/dist/runtime/server/utils/cms/git.mjs +2 -2
  216. package/dist/runtime/server/utils/cms/navigation.d.ts +46 -0
  217. package/dist/runtime/server/utils/cms/navigation.mjs +683 -0
  218. package/dist/runtime/server/utils/cms/preview.d.ts +11 -0
  219. package/dist/runtime/server/utils/cms/preview.mjs +50 -0
  220. package/dist/runtime/server/utils/cms/search.d.ts +1 -1
  221. package/dist/runtime/server/utils/cms/search.mjs +11 -7
  222. package/dist/runtime/server/utils/cms/sync.d.ts +34 -0
  223. package/dist/runtime/server/utils/cms/sync.mjs +1082 -0
  224. package/dist/runtime/server/utils/cms/taxonomy.d.ts +103 -0
  225. package/dist/runtime/server/utils/cms/taxonomy.mjs +348 -0
  226. package/dist/runtime/server/utils/cms.d.ts +13 -249
  227. package/dist/runtime/server/utils/cms.mjs +108 -2350
  228. package/dist/runtime/server/utils/comments-filter.d.ts +45 -0
  229. package/dist/runtime/server/utils/comments-filter.mjs +541 -0
  230. package/dist/runtime/server/utils/comments.d.ts +71 -0
  231. package/dist/runtime/server/utils/comments.mjs +137 -61
  232. package/dist/runtime/server/utils/config.d.ts +4 -3
  233. package/dist/runtime/server/utils/config.mjs +7 -6
  234. package/dist/runtime/server/utils/context.d.ts +14 -0
  235. package/dist/runtime/server/utils/context.mjs +2 -2
  236. package/dist/runtime/server/utils/crypto.d.ts +44 -5
  237. package/dist/runtime/server/utils/crypto.mjs +18 -0
  238. package/dist/runtime/server/utils/domains.mjs +9 -5
  239. package/dist/runtime/server/utils/drizzle.d.ts +35 -3
  240. package/dist/runtime/server/utils/drizzle.mjs +115 -6
  241. package/dist/runtime/server/utils/durable-object.d.ts +106 -0
  242. package/dist/runtime/server/utils/durable-object.mjs +628 -0
  243. package/dist/runtime/server/utils/email-inbound.d.ts +29 -0
  244. package/dist/runtime/server/utils/email-inbound.mjs +76 -0
  245. package/dist/runtime/server/utils/impersonation.d.ts +32 -2
  246. package/dist/runtime/server/utils/impersonation.mjs +16 -13
  247. package/dist/runtime/server/utils/lock.d.ts +71 -0
  248. package/dist/runtime/server/utils/lock.mjs +139 -0
  249. package/dist/runtime/server/utils/mail-suppression.mjs +7 -7
  250. package/dist/runtime/server/utils/mail.d.ts +30 -19
  251. package/dist/runtime/server/utils/mcp.d.ts +44 -0
  252. package/dist/runtime/server/utils/mcp.mjs +308 -0
  253. package/dist/runtime/server/utils/notifications.d.ts +72 -7
  254. package/dist/runtime/server/utils/notifications.mjs +67 -55
  255. package/dist/runtime/server/utils/oauth.d.ts +27 -4
  256. package/dist/runtime/server/utils/organization.d.ts +63 -7
  257. package/dist/runtime/server/utils/organization.mjs +26 -21
  258. package/dist/runtime/server/utils/passwordless.d.ts +62 -33
  259. package/dist/runtime/server/utils/payments.d.ts +51 -12
  260. package/dist/runtime/server/utils/payments.mjs +472 -282
  261. package/dist/runtime/server/utils/queue.d.ts +106 -13
  262. package/dist/runtime/server/utils/queue.mjs +313 -28
  263. package/dist/runtime/server/utils/rag.d.ts +42 -14
  264. package/dist/runtime/server/utils/rag.mjs +169 -4
  265. package/dist/runtime/server/utils/ratelimit.d.ts +34 -5
  266. package/dist/runtime/server/utils/ratelimit.mjs +95 -14
  267. package/dist/runtime/server/utils/realtime.d.ts +68 -52
  268. package/dist/runtime/server/utils/scheduled-task.d.ts +42 -1
  269. package/dist/runtime/server/utils/scheduled-task.mjs +29 -0
  270. package/dist/runtime/server/utils/schema-fallback.d.ts +1 -1
  271. package/dist/runtime/server/utils/schema-fallback.mjs +1 -1
  272. package/dist/runtime/server/utils/session.d.ts +84 -10
  273. package/dist/runtime/server/utils/session.mjs +12 -10
  274. package/dist/runtime/server/utils/sse.d.ts +75 -0
  275. package/dist/runtime/server/utils/sse.mjs +147 -0
  276. package/dist/runtime/server/utils/sso.d.ts +1 -1
  277. package/dist/runtime/server/utils/storage.d.ts +53 -4
  278. package/dist/runtime/server/utils/storage.mjs +15 -11
  279. package/dist/runtime/server/utils/store-localization.d.ts +51 -0
  280. package/dist/runtime/server/utils/store-localization.mjs +417 -0
  281. package/dist/runtime/server/utils/store.d.ts +207 -0
  282. package/dist/runtime/server/utils/store.mjs +2227 -0
  283. package/dist/runtime/server/utils/table-names.d.ts +51 -0
  284. package/dist/runtime/server/utils/table-names.mjs +69 -0
  285. package/dist/runtime/server/utils/tenant.d.ts +26 -2
  286. package/dist/runtime/server/utils/tenant.mjs +16 -12
  287. package/dist/runtime/server/utils/tools-registry-fallback.d.ts +1 -0
  288. package/dist/runtime/server/utils/tools-registry-fallback.mjs +1 -0
  289. package/dist/runtime/server/utils/totp.d.ts +45 -2
  290. package/dist/runtime/server/utils/tracker.d.ts +10 -11
  291. package/dist/runtime/server/utils/turnstile.d.ts +16 -1
  292. package/dist/runtime/server/utils/workflows.d.ts +92 -0
  293. package/dist/runtime/server/utils/workflows.mjs +299 -0
  294. package/dist/runtime/server.d.ts +8 -1
  295. package/dist/runtime/server.mjs +8 -5
  296. package/dist/runtime/service.d.ts +10 -10
  297. package/dist/runtime/storage.d.ts +1 -0
  298. package/dist/runtime/storage.mjs +1 -0
  299. package/dist/runtime/store.d.ts +4 -0
  300. package/dist/runtime/store.mjs +2 -0
  301. package/dist/runtime/test-utils.d.ts +11 -10
  302. package/dist/runtime/test-utils.mjs +64 -4
  303. package/dist/runtime/types/ai.d.ts +21 -2
  304. package/dist/runtime/types/d1.d.ts +17 -0
  305. package/dist/runtime/types/drizzle.d.ts +2 -2
  306. package/dist/runtime/types/durable-object.d.ts +62 -2
  307. package/dist/runtime/types/email.d.ts +46 -0
  308. package/dist/runtime/types/imports.d.ts +6 -1
  309. package/dist/runtime/types/index.d.ts +58 -0
  310. package/dist/runtime/types/index.mjs +3 -0
  311. package/dist/runtime/types/mcp.d.ts +83 -0
  312. package/dist/runtime/types/mcp.mjs +0 -0
  313. package/dist/runtime/types/queue.d.ts +36 -0
  314. package/dist/runtime/types/r2.d.ts +41 -0
  315. package/dist/runtime/types/store.d.ts +313 -0
  316. package/dist/runtime/types/store.mjs +0 -0
  317. package/dist/runtime/types/workflows.d.ts +98 -0
  318. package/dist/runtime/types/workflows.mjs +0 -0
  319. package/dist/runtime/workflows.d.ts +5 -0
  320. package/dist/runtime/workflows.mjs +2 -0
  321. package/dist/types/ai.d.ts +721 -0
  322. package/dist/types/cms.d.ts +710 -0
  323. package/dist/types.d.ts +430 -1292
  324. package/dist/utils/auth-schema.d.ts +3 -2
  325. package/dist/utils/bots.d.ts +20 -0
  326. package/dist/utils/comments-schema.d.ts +5 -4
  327. package/dist/utils/drizzle.d.ts +83 -3
  328. package/dist/utils/durable-objects.d.ts +10 -0
  329. package/dist/utils/email-inbound.d.ts +10 -0
  330. package/dist/utils/local-db.d.ts +1 -3
  331. package/dist/utils/mcp.d.ts +24 -0
  332. package/dist/utils/notifications-schema.d.ts +5 -4
  333. package/dist/utils/payments-schema.d.ts +4 -3
  334. package/dist/utils/store-schema.d.ts +14 -0
  335. package/dist/utils/table-names.d.ts +1 -0
  336. package/dist/utils/tenants-schema.d.ts +4 -3
  337. package/dist/utils/tools.d.ts +20 -0
  338. package/dist/utils/workflows.d.ts +8 -0
  339. package/package.json +34 -4
  340. package/dist/chunks/wrangler.mjs +0 -897
  341. package/dist/runtime/app/components/AuthRegister.vue +0 -306
  342. package/dist/runtime/app/components/AuthSessionsList.vue +0 -137
  343. package/dist/runtime/app/components/AuthSignIn.vue +0 -298
  344. package/dist/runtime/app/components/CMSBookmarkButton.vue +0 -59
  345. package/dist/runtime/app/components/CMSImage.vue +0 -47
  346. package/dist/runtime/app/components/CMSLocaleSwitcher.vue +0 -110
  347. package/dist/runtime/app/components/CMSNewsletter.vue +0 -81
  348. package/dist/runtime/app/components/CMSPreviewBanner.vue +0 -83
  349. package/dist/runtime/app/components/CMSTableOfContents.vue +0 -84
  350. package/dist/runtime/app/components/CMSVersionBanner.vue +0 -53
  351. package/dist/runtime/app/components/CMSVersionSwitcher.vue +0 -140
  352. package/dist/runtime/app/components/Comments.vue +0 -411
  353. package/dist/runtime/app/components/FileUpload.vue +0 -200
  354. package/dist/runtime/app/components/ImpersonationBanner.vue +0 -61
  355. package/dist/runtime/app/components/NotificationBell.vue +0 -263
  356. package/dist/runtime/app/components/NotificationList.vue +0 -205
  357. package/dist/runtime/app/components/NotificationPrompt.vue +0 -133
  358. package/dist/runtime/app/components/PricingGated.vue +0 -81
  359. package/dist/runtime/app/components/PricingTable.vue +0 -274
  360. package/dist/runtime/app/components/RealtimeChat.vue +0 -164
  361. package/dist/runtime/app/components/RealtimePresence.vue +0 -129
  362. package/dist/runtime/app/components/RealtimeStatus.vue +0 -79
  363. package/dist/runtime/app/components/SubscriptionCard.vue +0 -207
  364. package/dist/runtime/app/components/UserProfile.vue +0 -558
@@ -30,7 +30,13 @@ export default defineEventHandler(async (event) => {
30
30
  }
31
31
  } catch (err) {
32
32
  if (err.statusCode === 403) throw err;
33
+ throw createError({ statusCode: 500, message: "Authorization check failed." });
33
34
  }
35
+ } else {
36
+ throw createError({
37
+ statusCode: 403,
38
+ message: "Tenant has no organization; domain management requires an organization."
39
+ });
34
40
  }
35
41
  const body = await readBody(event).catch(() => ({}));
36
42
  const domain = body?.domain;
@@ -1,12 +1,38 @@
1
1
  import "#qarpeo/agents-registry";
2
+ import "#qarpeo/tools-registry";
2
3
  import type { RequestEvent } from "nuxt/server";
3
- import type { AgentDefinition, AgentMessage, AgentTool, StreamTextOptions, DurableObjectStub, GenerateImageOptions, GenerateImageResult, GenerateSpeechOptions, GenerateSpeechResult, TranscribeAudioInput, TranscribeAudioOptions, TranscribeAudioResult } from "../../../types";
4
+ import type { AgentDefinition, AgentMessage, AgentTool, StreamTextOptions, GenerateObjectOptions, GenerateObjectResult, DurableObjectStub, GenerateImageOptions, GenerateImageResult, GenerateSpeechOptions, GenerateSpeechResult, TranscribeAudioInput, TranscribeAudioOptions, TranscribeAudioResult } from "../../../types";
5
+ export type { GenerateObjectOptions, GenerateObjectResult, } from "../../../types";
4
6
  /** Registers an agent definition in the shared server runtime registry. */
5
7
  export declare function registerAgentDefinition(definition: AgentDefinition): void;
6
8
  /** Retrieves a registered agent definition by its unique name. */
7
9
  export declare function getAgentDefinition(name: string): AgentDefinition | undefined;
8
10
  /** Retrieves all currently registered agent definitions. */
9
11
  export declare function getAllAgentDefinitions(): AgentDefinition[];
12
+ /**
13
+ * Registers a named tool into the shared server-side global tool registry.
14
+ * Called automatically by the generated `#qarpeo/tools-registry` module for
15
+ * every export found in `server/tools/`.
16
+ */
17
+ export declare function registerGlobalTool(name: string, tool: AgentTool): void;
18
+ /**
19
+ * Retrieves a registered global tool by name.
20
+ *
21
+ * @example
22
+ * const tool = getGlobalTool("searchDocs")
23
+ */
24
+ export declare function getGlobalTool(name: string): AgentTool | undefined;
25
+ /**
26
+ * Retrieves all tools registered in the global tool registry (from `server/tools/`).
27
+ * Useful for passing all shared tools to an agent definition.
28
+ *
29
+ * @example
30
+ * export default defineAgent({
31
+ * name: "support",
32
+ * tools: getGlobalTools(),
33
+ * })
34
+ */
35
+ export declare function getGlobalTools(): Record<string, AgentTool>;
10
36
  /**
11
37
  * Define a typed tool for an edge agent or LLM function call.
12
38
  *
@@ -39,25 +65,84 @@ export declare function defineTool<TParams = any, TResult = any>(tool: AgentTool
39
65
  export declare function defineAgent(definition: AgentDefinition): AgentDefinition;
40
66
  /** Retrieves the Durable Object stub for a specific agent instance. */
41
67
  export declare function getAgentDurableObject(agentName: string, id?: string, bindingName?: string, event?: RequestEvent): DurableObjectStub;
42
- export declare function useAgent(agentName: string, id?: string, event?: RequestEvent): {
43
- chat(message: string, options?: {
44
- stream?: boolean;
45
- model?: string;
46
- system?: string;
47
- maxSteps?: number;
48
- maxTokens?: number;
49
- temperature?: number;
50
- gateway?: {
51
- id: string;
52
- skipCache?: boolean;
53
- cacheTtl?: number;
54
- };
55
- }): Promise<Response>;
56
- history(): Promise<AgentMessage[]>;
57
- clear(): Promise<void>;
58
- getState(): Promise<Record<string, any>>;
59
- setState(state: Record<string, any>): Promise<void>;
60
- };
68
+ /**
69
+ * Server-side client to interact with a stateful edge agent.
70
+ *
71
+ * @example
72
+ * const agent = useAgent("support", "user_123")
73
+ * const res = await agent.chat("Where is my package?")
74
+ */
75
+ export interface ExtractedToolCall {
76
+ id: string;
77
+ name: string;
78
+ arguments: Record<string, any>;
79
+ }
80
+ /** Normalizes tool definitions from either an array [tool1, tool2] or a record { tool1, tool2 }. */
81
+ export declare function normalizeTools(toolsInput?: Record<string, AgentTool> | AgentTool[]): Map<string, AgentTool>;
82
+ /**
83
+ * Robustly parses tool calls from Workers AI responses, JSON schemas, or tool payloads. Supports:
84
+ * 1. Workers AI / OpenAI native tool_calls array
85
+ * 2. Llama 3.1/3.3 <tool_call> tags
86
+ * 3. Markdown ```json code blocks
87
+ * 4. Raw JSON strings
88
+ */
89
+ export declare function extractToolCalls(res: any, accumulatedText: string): ExtractedToolCall[];
90
+ export declare function serializeToolSchemas(toolsInput?: Record<string, AgentTool> | AgentTool[]): any[] | undefined;
91
+ export interface AgentChatOptions {
92
+ /** Whether to stream the response back. */
93
+ stream?: boolean;
94
+ /** Model override for this conversation turn. */
95
+ model?: string;
96
+ /** System prompt override. */
97
+ system?: string;
98
+ /** Maximum autonomous tool execution steps. */
99
+ maxSteps?: number;
100
+ /** Maximum generation tokens. */
101
+ maxTokens?: number;
102
+ /** Sampling temperature. */
103
+ temperature?: number;
104
+ /** Cloudflare AI Gateway routing options. */
105
+ gateway?: {
106
+ id: string;
107
+ skipCache?: boolean;
108
+ cacheTtl?: number;
109
+ };
110
+ /** Tool definitions override. */
111
+ tools?: any;
112
+ [key: string]: any;
113
+ }
114
+ export interface UseAgentReturn {
115
+ /** Sends a message to the agent and returns the Response (streamed or JSON). */
116
+ chat: (message: string, options?: AgentChatOptions) => Promise<Response>;
117
+ /** Fetches complete conversation history from the Durable Object. */
118
+ history: () => Promise<AgentMessage[]>;
119
+ /** Clears conversation history and state in the Durable Object. */
120
+ clear: () => Promise<void>;
121
+ /** Retrieves custom persisted agent state. */
122
+ getState: () => Promise<Record<string, any>>;
123
+ /** Updates custom persisted agent state. */
124
+ setState: (state: Record<string, any>) => Promise<void>;
125
+ }
126
+ /** Resolves Cloudflare AI Gateway routing options from parameters or environment variables. */
127
+ export declare function resolveAiGateway(optsGateway?: {
128
+ id: string;
129
+ skipCache?: boolean;
130
+ cacheTtl?: number;
131
+ }): {
132
+ id: string;
133
+ skipCache?: boolean;
134
+ cacheTtl?: number;
135
+ } | undefined;
136
+ /**
137
+ * Accesses an Edge AI Agent backed by Cloudflare Durable Objects.
138
+ *
139
+ * @example
140
+ * ```ts
141
+ * const agent = useAgent("support", "user_123")
142
+ * const res = await agent.chat("How do I reset my password?")
143
+ * ```
144
+ */
145
+ export declare function useAgent(agentName: string, id?: string, event?: RequestEvent): UseAgentReturn;
61
146
  /**
62
147
  * Generate vector embeddings for text using Cloudflare Workers AI.
63
148
  *
@@ -80,8 +165,48 @@ export interface SimilaritySearchOptions {
80
165
  }
81
166
  /** Performs vector similarity search using Cloudflare Vectorize. */
82
167
  export declare function similaritySearch(indexName: string, query: string, options?: SimilaritySearchOptions): Promise<any[]>;
83
- /** Generate a complete text response using Cloudflare Workers AI. */
168
+ /** Detects whether an input schema is a Zod schema. */
169
+ export declare function isZodSchema(schema: any): boolean;
170
+ /**
171
+ * Converts a Zod schema or plain JSON schema into a valid JSON Schema object
172
+ * suitable for Cloudflare Workers AI constrained decoding (response_format).
173
+ */
174
+ export declare function schemaToJsonSchema(schema: any): Record<string, any>;
175
+ /**
176
+ * Robustly extracts and parses a JSON object or array from a model response string.
177
+ * Strips markdown code fences (```json ... ```) and handles leading/trailing prose.
178
+ */
179
+ export declare function extractJsonObject(input: any): any;
180
+ /**
181
+ * Synthesizes a valid default mock object conforming to a JSON Schema.
182
+ * Used during local development and testing when no Cloudflare AI token is present.
183
+ */
184
+ export declare function synthesizeMockFromSchema(jsonSchema: Record<string, any>): any;
185
+ /** Generate a complete text response using Cloudflare Workers AI with optional autonomous tool calling. */
84
186
  export declare function generateText(options: StreamTextOptions): Promise<string>;
187
+ /**
188
+ * Generates a structured, strongly-typed JSON object using Cloudflare Workers AI
189
+ * constrained decoding (JSON schema) and schema validation.
190
+ *
191
+ * Supports Zod schemas (`z.object({...})`) or plain JSON schemas.
192
+ *
193
+ * @example
194
+ * ```ts
195
+ * import { z } from "zod"
196
+ * import { ai } from "qarpeo/server"
197
+ *
198
+ * const profile = await ai.generateObject({
199
+ * prompt: "Extract user info: Alice Smith, 29 years old, loves hiking and photography",
200
+ * schema: z.object({
201
+ * name: z.string(),
202
+ * age: z.number(),
203
+ * interests: z.array(z.string()),
204
+ * }),
205
+ * })
206
+ * console.log(profile.object.name) // "Alice Smith"
207
+ * ```
208
+ */
209
+ export declare function generateObject<T = any>(options: GenerateObjectOptions<T>): Promise<GenerateObjectResult<T>>;
85
210
  /** Stream text directly via Server-Sent Events using Cloudflare Workers AI. */
86
211
  export declare function streamText(options: StreamTextOptions): Promise<Response>;
87
212
  /**
@@ -1,4 +1,6 @@
1
1
  import "#qarpeo/agents-registry";
2
+ import "#qarpeo/tools-registry";
3
+ import { z } from "zod";
2
4
  import { getAIBinding } from "../../ai.mjs";
3
5
  import { getCloudflareEnv } from "../../bindings.mjs";
4
6
  import { getR2Binding } from "../../blob.mjs";
@@ -22,6 +24,25 @@ export function getAgentDefinition(name) {
22
24
  export function getAllAgentDefinitions() {
23
25
  return Array.from(getAgentRegistry().values());
24
26
  }
27
+ const GLOBAL_TOOL_REGISTRY_KEY = "__qarpeo_tool_registry__";
28
+ function getToolRegistry() {
29
+ const g = globalThis;
30
+ if (!g[GLOBAL_TOOL_REGISTRY_KEY]) {
31
+ g[GLOBAL_TOOL_REGISTRY_KEY] = /* @__PURE__ */ new Map();
32
+ }
33
+ return g[GLOBAL_TOOL_REGISTRY_KEY];
34
+ }
35
+ export function registerGlobalTool(name, tool) {
36
+ if (name && tool) {
37
+ getToolRegistry().set(name, { ...tool, name: tool.name ?? name });
38
+ }
39
+ }
40
+ export function getGlobalTool(name) {
41
+ return getToolRegistry().get(name);
42
+ }
43
+ export function getGlobalTools() {
44
+ return Object.fromEntries(getToolRegistry());
45
+ }
25
46
  export function defineTool(tool) {
26
47
  return tool;
27
48
  }
@@ -40,7 +61,85 @@ export function getAgentDurableObject(agentName, id = "default", bindingName = "
40
61
  const doId = binding.idFromName(`${agentName}:${id}`);
41
62
  return binding.get(doId);
42
63
  }
43
- function serializeToolSchemas(toolsInput) {
64
+ export function normalizeTools(toolsInput) {
65
+ const map = /* @__PURE__ */ new Map();
66
+ if (!toolsInput) return map;
67
+ if (Array.isArray(toolsInput)) {
68
+ for (const t of toolsInput) {
69
+ if (t && t.name) {
70
+ map.set(t.name, t);
71
+ }
72
+ }
73
+ } else if (typeof toolsInput === "object") {
74
+ for (const [key, t] of Object.entries(toolsInput)) {
75
+ if (t) {
76
+ map.set(t.name || key, { ...t, name: t.name || key });
77
+ }
78
+ }
79
+ }
80
+ return map;
81
+ }
82
+ export function extractToolCalls(res, accumulatedText) {
83
+ const calls = [];
84
+ const rawCalls = res?.tool_calls || res?.toolCalls;
85
+ if (Array.isArray(rawCalls) && rawCalls.length > 0) {
86
+ for (const tc of rawCalls) {
87
+ const name = tc.name || tc.function?.name;
88
+ let args = tc.arguments || tc.function?.arguments || {};
89
+ if (typeof args === "string") {
90
+ try {
91
+ args = JSON.parse(args);
92
+ } catch {
93
+ }
94
+ }
95
+ if (name) {
96
+ calls.push({
97
+ id: tc.id || `call_${crypto.randomUUID().replace(/-/g, "").slice(0, 20)}`,
98
+ name,
99
+ arguments: args
100
+ });
101
+ }
102
+ }
103
+ }
104
+ if (calls.length === 0 && accumulatedText) {
105
+ const xmlRegex = /<tool_call>([\s\S]*?)<\/tool_call>/gi;
106
+ let xmlMatch;
107
+ while ((xmlMatch = xmlRegex.exec(accumulatedText)) !== null) {
108
+ try {
109
+ const parsed = JSON.parse(xmlMatch[1].trim());
110
+ const name = parsed.name || parsed.function?.name;
111
+ const args = parsed.arguments || parsed.parameters || parsed.function?.arguments || {};
112
+ if (name) {
113
+ calls.push({
114
+ id: parsed.id || `call_${crypto.randomUUID().replace(/-/g, "").slice(0, 20)}`,
115
+ name,
116
+ arguments: typeof args === "string" ? JSON.parse(args) : args
117
+ });
118
+ }
119
+ } catch {
120
+ }
121
+ }
122
+ }
123
+ if (calls.length === 0 && accumulatedText) {
124
+ try {
125
+ const match = accumulatedText.match(/```(?:json)?\s*(\{[\s\S]*?"name"[\s\S]*?\})\s*```/i);
126
+ if (match && match[1]) {
127
+ const parsed = JSON.parse(match[1]);
128
+ const name = parsed.name || parsed.function?.name;
129
+ if (name && (parsed.arguments || parsed.parameters || parsed.function?.arguments)) {
130
+ calls.push({
131
+ id: parsed.id || `call_${crypto.randomUUID().replace(/-/g, "").slice(0, 20)}`,
132
+ name,
133
+ arguments: parsed.arguments || parsed.parameters || parsed.function?.arguments || {}
134
+ });
135
+ }
136
+ }
137
+ } catch {
138
+ }
139
+ }
140
+ return calls;
141
+ }
142
+ export function serializeToolSchemas(toolsInput) {
44
143
  if (!toolsInput) return void 0;
45
144
  const list = [];
46
145
  if (Array.isArray(toolsInput)) {
@@ -66,6 +165,14 @@ function serializeToolSchemas(toolsInput) {
66
165
  }
67
166
  return list.length > 0 ? list : void 0;
68
167
  }
168
+ export function resolveAiGateway(optsGateway) {
169
+ if (optsGateway?.id) return optsGateway;
170
+ const envGateway = globalThis.process?.env?.CLOUDFLARE_AI_GATEWAY || globalThis.process?.env?.AI_GATEWAY;
171
+ if (envGateway) {
172
+ return { id: envGateway, skipCache: optsGateway?.skipCache ?? false };
173
+ }
174
+ return void 0;
175
+ }
69
176
  export function useAgent(agentName, id = "default", event) {
70
177
  const stub = getAgentDurableObject(agentName, id, "QARPEO_AGENT_DO", event);
71
178
  const def = getAgentDefinition(agentName);
@@ -171,6 +278,110 @@ export async function similaritySearch(indexName, query, options) {
171
278
  const results = await vectorize.query(vector, queryOpts);
172
279
  return results.matches || [];
173
280
  }
281
+ export function isZodSchema(schema) {
282
+ return Boolean(
283
+ schema && typeof schema === "object" && typeof schema.safeParse === "function"
284
+ );
285
+ }
286
+ export function schemaToJsonSchema(schema) {
287
+ if (!schema) {
288
+ return { type: "object", properties: {} };
289
+ }
290
+ if (isZodSchema(schema)) {
291
+ try {
292
+ if (typeof z.toJSONSchema === "function") {
293
+ const converted = z.toJSONSchema(schema);
294
+ if (converted && typeof converted === "object") {
295
+ const { $schema, ...clean } = converted;
296
+ return clean;
297
+ }
298
+ }
299
+ } catch {
300
+ }
301
+ if (schema.shape && typeof schema.shape === "object") {
302
+ const properties = {};
303
+ const required = [];
304
+ for (const [key] of Object.entries(schema.shape)) {
305
+ properties[key] = { type: "string" };
306
+ required.push(key);
307
+ }
308
+ return { type: "object", properties, required };
309
+ }
310
+ }
311
+ if (typeof schema === "object") {
312
+ const { $schema, ...clean } = schema;
313
+ return clean;
314
+ }
315
+ return { type: "object", properties: {} };
316
+ }
317
+ export function extractJsonObject(input) {
318
+ if (input !== null && typeof input === "object") {
319
+ return input;
320
+ }
321
+ if (typeof input !== "string") {
322
+ throw new Error(`[qarpeo:ai] Cannot parse JSON from non-string value: ${typeof input}`);
323
+ }
324
+ const trimmed = input.trim();
325
+ try {
326
+ return JSON.parse(trimmed);
327
+ } catch {
328
+ }
329
+ const fenceMatch = trimmed.match(/```(?:json)?\s*([\s\S]*?)\s*```/i);
330
+ if (fenceMatch && fenceMatch[1]) {
331
+ try {
332
+ return JSON.parse(fenceMatch[1].trim());
333
+ } catch {
334
+ }
335
+ }
336
+ const firstBrace = trimmed.indexOf("{");
337
+ const firstBracket = trimmed.indexOf("[");
338
+ let startIdx = -1;
339
+ let endIdx = -1;
340
+ if (firstBrace !== -1 && (firstBracket === -1 || firstBrace < firstBracket)) {
341
+ startIdx = firstBrace;
342
+ endIdx = trimmed.lastIndexOf("}");
343
+ } else if (firstBracket !== -1) {
344
+ startIdx = firstBracket;
345
+ endIdx = trimmed.lastIndexOf("]");
346
+ }
347
+ if (startIdx !== -1 && endIdx !== -1 && endIdx > startIdx) {
348
+ const candidate = trimmed.slice(startIdx, endIdx + 1);
349
+ try {
350
+ return JSON.parse(candidate);
351
+ } catch {
352
+ }
353
+ }
354
+ throw new Error(
355
+ `[qarpeo:ai] Failed to extract valid JSON from model response: "${trimmed.slice(0, 100)}..."`
356
+ );
357
+ }
358
+ export function synthesizeMockFromSchema(jsonSchema) {
359
+ if (!jsonSchema || typeof jsonSchema !== "object") return {};
360
+ if (jsonSchema.type === "object" || jsonSchema.properties) {
361
+ const result = {};
362
+ const props = jsonSchema.properties || {};
363
+ for (const [key, propDef] of Object.entries(props)) {
364
+ if (propDef.type === "string") {
365
+ result[key] = propDef.default ?? `mock_${key}`;
366
+ } else if (propDef.type === "number" || propDef.type === "integer") {
367
+ result[key] = propDef.default ?? 42;
368
+ } else if (propDef.type === "boolean") {
369
+ result[key] = propDef.default ?? true;
370
+ } else if (propDef.type === "array") {
371
+ result[key] = propDef.default ?? (propDef.items?.type === "string" ? ["item_1", "item_2"] : []);
372
+ } else if (propDef.type === "object" || propDef.properties) {
373
+ result[key] = synthesizeMockFromSchema(propDef);
374
+ } else {
375
+ result[key] = propDef.default ?? `mock_${key}`;
376
+ }
377
+ }
378
+ return result;
379
+ }
380
+ if (jsonSchema.type === "array") {
381
+ return [];
382
+ }
383
+ return {};
384
+ }
174
385
  export async function generateText(options) {
175
386
  const model = options.model || "@cf/meta/llama-3.3-70b-instruct";
176
387
  const ai = getAIBinding(options.binding, options.event);
@@ -185,13 +396,193 @@ export async function generateText(options) {
185
396
  }
186
397
  const aiOptions = {
187
398
  messages,
188
- temperature: options.temperature
399
+ temperature: options.temperature,
400
+ max_tokens: options.maxTokens
189
401
  };
190
- if (options.gateway) {
191
- aiOptions.gateway = options.gateway;
402
+ const gateway = resolveAiGateway(options.gateway);
403
+ if (gateway) {
404
+ aiOptions.gateway = gateway;
405
+ }
406
+ if (!options.tools) {
407
+ const result = await ai.run(model, aiOptions);
408
+ return result?.response || String(result || "");
409
+ }
410
+ const toolsMap = normalizeTools(options.tools);
411
+ const serializedTools = serializeToolSchemas(options.tools);
412
+ if (serializedTools && serializedTools.length > 0) {
413
+ aiOptions.tools = serializedTools.map((t) => ({
414
+ type: "function",
415
+ function: {
416
+ name: t.name,
417
+ description: t.description || "",
418
+ parameters: t.parameters || { type: "object", properties: {} }
419
+ }
420
+ }));
421
+ }
422
+ const maxSteps = options.maxSteps ?? 5;
423
+ let step = 0;
424
+ let finalResponse = "";
425
+ while (step < maxSteps) {
426
+ step++;
427
+ const result = await ai.run(model, aiOptions);
428
+ const rawResponse = result?.response || "";
429
+ const toolCalls = extractToolCalls(result, typeof rawResponse === "string" ? rawResponse : "");
430
+ if (toolCalls.length === 0) {
431
+ finalResponse = typeof rawResponse === "string" ? rawResponse : JSON.stringify(rawResponse);
432
+ break;
433
+ }
434
+ messages.push({
435
+ role: "assistant",
436
+ content: rawResponse || "",
437
+ tool_calls: toolCalls.map((tc) => ({
438
+ id: tc.id,
439
+ type: "function",
440
+ function: { name: tc.name, arguments: JSON.stringify(tc.arguments) }
441
+ }))
442
+ });
443
+ for (const call of toolCalls) {
444
+ const tool = toolsMap.get(call.name);
445
+ let toolResult;
446
+ if (tool && typeof tool.execute === "function") {
447
+ try {
448
+ toolResult = await tool.execute(call.arguments, {
449
+ toolCallId: call.id,
450
+ event: options.event
451
+ });
452
+ } catch (toolErr) {
453
+ toolResult = { error: toolErr?.message || String(toolErr) };
454
+ }
455
+ } else {
456
+ toolResult = { error: `Tool "${call.name}" not found` };
457
+ }
458
+ messages.push({
459
+ role: "tool",
460
+ name: call.name,
461
+ tool_call_id: call.id,
462
+ content: typeof toolResult === "string" ? toolResult : JSON.stringify(toolResult)
463
+ });
464
+ }
465
+ }
466
+ return finalResponse;
467
+ }
468
+ export async function generateObject(options) {
469
+ if (!options || !options.schema) {
470
+ throw new Error("[qarpeo:ai:generateObject] 'schema' option is required.");
471
+ }
472
+ const model = options.model || "@cf/meta/llama-3.3-70b-instruct";
473
+ const jsonSchema = schemaToJsonSchema(options.schema);
474
+ const schemaName = options.schemaName || "output";
475
+ const systemInstructions = [
476
+ options.system || "You are a precise data extraction and JSON generation engine.",
477
+ `Return ONLY a valid JSON object matching the JSON schema below. Do not wrap in markdown fences or include explanations.`,
478
+ `Schema: ${schemaName}`,
479
+ options.schemaDescription ? `Description: ${options.schemaDescription}` : "",
480
+ `JSON Schema: ${JSON.stringify(jsonSchema)}`
481
+ ].filter(Boolean).join("\n\n");
482
+ const messages = [{ role: "system", content: systemInstructions }];
483
+ if (options.messages && Array.isArray(options.messages)) {
484
+ messages.push(...options.messages.map((m) => ({ role: m.role, content: m.content })));
485
+ } else if (options.prompt) {
486
+ messages.push({ role: "user", content: options.prompt });
192
487
  }
193
- const result = await ai.run(model, aiOptions);
194
- return result?.response || String(result || "");
488
+ const aiOptions = {
489
+ messages,
490
+ temperature: options.temperature ?? 0.1,
491
+ max_tokens: options.maxTokens
492
+ };
493
+ const gateway = resolveAiGateway(options.gateway);
494
+ if (gateway) {
495
+ aiOptions.gateway = gateway;
496
+ }
497
+ const mode = options.mode || "auto";
498
+ if (mode === "json_schema" || mode === "auto") {
499
+ aiOptions.response_format = {
500
+ type: "json_schema",
501
+ json_schema: {
502
+ name: schemaName,
503
+ strict: true,
504
+ schema: jsonSchema
505
+ }
506
+ };
507
+ } else if (mode === "json_object") {
508
+ aiOptions.response_format = { type: "json_object" };
509
+ } else if (mode === "tool_call") {
510
+ aiOptions.tools = [
511
+ {
512
+ type: "function",
513
+ function: {
514
+ name: schemaName,
515
+ description: options.schemaDescription || "Structured output extractor",
516
+ parameters: jsonSchema
517
+ }
518
+ }
519
+ ];
520
+ }
521
+ let rawResult;
522
+ try {
523
+ const ai = getAIBinding(options.binding, options.event);
524
+ rawResult = await ai.run(model, aiOptions);
525
+ } catch (err) {
526
+ if (err?.message?.includes("was not found")) {
527
+ const mockObj = synthesizeMockFromSchema(jsonSchema);
528
+ const validatedMock = isZodSchema(options.schema) ? options.schema.safeParse(mockObj).data ?? mockObj : mockObj;
529
+ return {
530
+ object: validatedMock,
531
+ text: JSON.stringify(validatedMock),
532
+ usage: { promptTokens: 10, completionTokens: 20, totalTokens: 30 },
533
+ finishReason: "stop"
534
+ };
535
+ }
536
+ throw err;
537
+ }
538
+ if (mode === "tool_call") {
539
+ const calls = extractToolCalls(rawResult, rawResult?.response || "");
540
+ if (calls.length > 0 && calls[0]?.arguments) {
541
+ const parsedObj = calls[0].arguments;
542
+ if (isZodSchema(options.schema)) {
543
+ const val = options.schema.safeParse(parsedObj);
544
+ if (!val.success) {
545
+ throw new Error(
546
+ `[qarpeo:ai:generateObject] Schema validation failed: ${val.error.message}`
547
+ );
548
+ }
549
+ return {
550
+ object: val.data,
551
+ text: JSON.stringify(val.data),
552
+ finishReason: "stop"
553
+ };
554
+ }
555
+ return {
556
+ object: parsedObj,
557
+ text: JSON.stringify(parsedObj),
558
+ finishReason: "stop"
559
+ };
560
+ }
561
+ }
562
+ const rawText = typeof rawResult?.response === "string" ? rawResult.response : typeof rawResult === "string" ? rawResult : JSON.stringify(rawResult?.response || rawResult || {});
563
+ const parsed = extractJsonObject(rawText);
564
+ let finalObject;
565
+ if (isZodSchema(options.schema)) {
566
+ const parseResult = options.schema.safeParse(parsed);
567
+ if (!parseResult.success) {
568
+ throw new Error(
569
+ `[qarpeo:ai:generateObject] Schema validation failed: ${parseResult.error.message}`
570
+ );
571
+ }
572
+ finalObject = parseResult.data;
573
+ } else {
574
+ finalObject = parsed;
575
+ }
576
+ return {
577
+ object: finalObject,
578
+ text: rawText,
579
+ usage: rawResult?.usage ? {
580
+ promptTokens: rawResult.usage.prompt_tokens ?? rawResult.usage.promptTokens,
581
+ completionTokens: rawResult.usage.completion_tokens ?? rawResult.usage.completionTokens,
582
+ totalTokens: rawResult.usage.total_tokens ?? rawResult.usage.totalTokens
583
+ } : void 0,
584
+ finishReason: rawResult?.finish_reason || "stop"
585
+ };
195
586
  }
196
587
  export async function streamText(options) {
197
588
  const model = options.model || "@cf/meta/llama-3.3-70b-instruct";
@@ -215,8 +606,9 @@ export async function streamText(options) {
215
606
  temperature: options.temperature,
216
607
  stream: true
217
608
  };
218
- if (options.gateway) {
219
- runOptions.gateway = options.gateway;
609
+ const streamGateway = resolveAiGateway(options.gateway);
610
+ if (streamGateway) {
611
+ runOptions.gateway = streamGateway;
220
612
  }
221
613
  const aiStream = await ai.run(model, runOptions);
222
614
  if (aiStream && typeof aiStream.getReader === "function") {
@@ -504,7 +896,8 @@ export async function generateImage(options) {
504
896
  const imgBytes = await toUint8Array(opts.image);
505
897
  inputs.image = Array.from(imgBytes);
506
898
  }
507
- const aiOptions = opts.gateway ? { gateway: opts.gateway } : void 0;
899
+ const gateway = resolveAiGateway(opts.gateway);
900
+ const aiOptions = gateway ? { gateway } : void 0;
508
901
  const rawResult = await ai.run(model, inputs, aiOptions);
509
902
  if (rawResult?.image && typeof rawResult.image === "string") {
510
903
  uint8Array = await toUint8Array(rawResult.image);
@@ -562,7 +955,8 @@ export async function generateSpeech(options) {
562
955
  const ai = getAIBinding(opts.binding, opts.event);
563
956
  const inputs = { text };
564
957
  if (opts.lang) inputs.lang = opts.lang;
565
- const aiOptions = opts.gateway ? { gateway: opts.gateway } : void 0;
958
+ const gateway = resolveAiGateway(opts.gateway);
959
+ const aiOptions = gateway ? { gateway } : void 0;
566
960
  const rawResult = await ai.run(model, inputs, aiOptions);
567
961
  uint8Array = await toUint8Array(rawResult);
568
962
  } catch (err) {
@@ -615,7 +1009,8 @@ export async function transcribeAudio(options) {
615
1009
  };
616
1010
  if (opts.language) inputs.language = opts.language;
617
1011
  if (opts.task) inputs.task = opts.task;
618
- const aiOptions = opts.gateway ? { gateway: opts.gateway } : void 0;
1012
+ const gateway = resolveAiGateway(opts.gateway);
1013
+ const aiOptions = gateway ? { gateway } : void 0;
619
1014
  const rawResult = await ai.run(model, inputs, aiOptions);
620
1015
  const text = rawResult?.text || "";
621
1016
  const wordCount = rawResult?.word_count || (text ? text.trim().split(/\s+/).length : 0);