@desplega.ai/agent-swarm 2.14.0 → 2.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (344) hide show
  1. package/dist/acp-adapter-7jv7w8jh.js +17 -0
  2. package/dist/{acp-targets-23exz4z4.js → acp-targets-0ebmg3et.js} +10 -10
  3. package/dist/{actions-zcr25x27.js → actions-0ds9dx6c.js} +28 -28
  4. package/dist/{agent-fs-provision-7fa9e12e.js → agent-fs-provision-zpbxa9jc.js} +4 -4
  5. package/dist/{amp-adapter-s7ytmv6b.js → amp-adapter-awh5nn7a.js} +3 -3
  6. package/dist/{anthropic-messages-vdd1zmha.js → anthropic-messages-gtgp9r85.js} +17 -17
  7. package/dist/{app-5d3sz1hy.js → app-nzejkvpp.js} +10 -10
  8. package/dist/{approval-notifications-7qgkzkzx.js → approval-notifications-hbqtb2w3.js} +11 -11
  9. package/dist/{assistant-p2yvhc3j.js → assistant-1paft129.js} +29 -29
  10. package/dist/{boot-args-schema-ry6cb0p7.js → boot-args-schema-zs435mfx.js} +1 -1
  11. package/dist/{boot-reembed-2hkm3vz2.js → boot-reembed-7xq2qgg4.js} +1 -1
  12. package/dist/{boot-reembed-c9643ms3.js → boot-reembed-91qrd4mz.js} +1 -1
  13. package/dist/{boot-scrub-sweep-3ycxr51t.js → boot-scrub-sweep-3h5xscw6.js} +2 -2
  14. package/dist/{boot-seeds-2hzvvzg0.js → boot-seeds-xkxqa8zc.js} +4 -4
  15. package/dist/{boxd-9py3x0jb.js → boxd-464x3w4m.js} +3 -3
  16. package/dist/{claude-adapter-dnkww93e.js → claude-adapter-6d8eyf2f.js} +12 -13
  17. package/dist/{claude-managed-adapter-yk0cr5x6.js → claude-managed-adapter-jzxcaf9m.js} +4 -4
  18. package/dist/{claude-managed-setup-4byxpp47.js → claude-managed-setup-5fcx0qh3.js} +10 -10
  19. package/dist/{claude-sdk-session-4wf3dbvs.js → claude-sdk-session-11vhz1hc.js} +11442 -12786
  20. package/dist/{cli-2ckwgs7q.js → cli-02ba8qx5.js} +1 -1
  21. package/dist/{cli-wvgg7r4j.js → cli-08gfvs58.js} +2 -2
  22. package/dist/{cli-ad00h1st.js → cli-0dkpdvnn.js} +10 -10
  23. package/dist/{cli-879txsac.js → cli-0mq8kxfx.js} +4 -4
  24. package/dist/{cli-rp1n2xpd.js → cli-0nvqg1hb.js} +1 -1
  25. package/dist/{cli-qrwjk4xy.js → cli-0qyfna7a.js} +5 -5
  26. package/dist/cli-0vxbrxr3.js +1006 -0
  27. package/dist/{cli-vxmmttmt.js → cli-132h67ps.js} +52 -52
  28. package/dist/{cli-yd7e590v.js → cli-1e13gvfn.js} +14 -14
  29. package/dist/cli-1hj68b3h.js +30 -0
  30. package/dist/{cli-hzhv7yac.js → cli-1zbj28py.js} +1 -1
  31. package/dist/{cli-0k7ppk9k.js → cli-20mkgwev.js} +43 -38
  32. package/dist/{cli-ejnhs815.js → cli-288k5ep1.js} +11 -11
  33. package/dist/{cli-njvpngc6.js → cli-2n7qdqfv.js} +3 -3
  34. package/dist/{cli-r04ve9xw.js → cli-2r62jy9s.js} +1 -1
  35. package/dist/{cli-9j1t3kf6.js → cli-3179w2rz.js} +2 -2
  36. package/dist/cli-3a3hm1z8.js +15 -0
  37. package/dist/cli-3bagv8rt.js +37 -0
  38. package/dist/{cli-6ajyhxh7.js → cli-3bcsc3m7.js} +2 -2
  39. package/dist/{cli-jgq9xptq.js → cli-3g0vbq46.js} +4 -4
  40. package/dist/{cli-69szn7w7.js → cli-3ktfe5jx.js} +71 -47
  41. package/dist/{cli-yjb3cddd.js → cli-44r66df2.js} +1 -1
  42. package/dist/{cli-mv8ft7b0.js → cli-4y2bekkn.js} +3 -3
  43. package/dist/cli-547fsc36.js +15 -0
  44. package/dist/{cli-6p8p2e6r.js → cli-5pyes68e.js} +1278 -23
  45. package/dist/{cli-930zbczq.js → cli-5t00r6c9.js} +3 -3
  46. package/dist/{cli-kc7vd07m.js → cli-5xjdft4s.js} +3601 -1700
  47. package/dist/{cli-4dyzzkfb.js → cli-643skca1.js} +954 -180
  48. package/dist/{cli-vr4eyq6p.js → cli-6a77m17n.js} +540 -412
  49. package/dist/{cli-v41kn3cd.js → cli-6prwz0zn.js} +4427 -5566
  50. package/dist/{cli-1nfabrt4.js → cli-6xrbpj5j.js} +4 -4
  51. package/dist/{cli-meydjstb.js → cli-6yhjqd6k.js} +4965 -69
  52. package/dist/{cli-6yy4fepf.js → cli-727sq1f9.js} +4 -4
  53. package/dist/{cli-snxhtehz.js → cli-7abeph0b.js} +7 -8
  54. package/dist/{cli-ty3gha1p.js → cli-7b9bwrfg.js} +2 -2
  55. package/dist/{cli-g6a696c0.js → cli-7dwsn9y5.js} +4 -4
  56. package/dist/{cli-r9d2tya0.js → cli-7qkbab03.js} +5 -5
  57. package/dist/{cli-7ca8hczj.js → cli-7svwhw1a.js} +1 -1
  58. package/dist/{cli-ze1ndjs4.js → cli-83kf2y60.js} +8 -8
  59. package/dist/{cli-rs1rzwp4.js → cli-8crn0510.js} +1 -1
  60. package/dist/{cli-wym6rxgt.js → cli-8kemtj1r.js} +10 -15
  61. package/dist/{cli-md4tn21h.js → cli-967jrz7j.js} +40 -26
  62. package/dist/{cli-jcnc5ret.js → cli-976m0zcw.js} +38 -28
  63. package/dist/{cli-cbg0j1yt.js → cli-98sea4d9.js} +3 -3
  64. package/dist/{cli-xh5fpmg8.js → cli-9txap41q.js} +101 -18
  65. package/dist/{cli-24wervhz.js → cli-aktk3qt6.js} +3 -3
  66. package/dist/{cli-096aftq6.js → cli-b70cpf8f.js} +7 -7
  67. package/dist/{cli-2ap1the6.js → cli-by7s3n4p.js} +1 -1
  68. package/dist/{cli-w4bvtxet.js → cli-byzq8xht.js} +7 -7
  69. package/dist/{cli-phe2vcw5.js → cli-d1zkys4j.js} +150 -99
  70. package/dist/cli-dr6x9qdk.js +15 -0
  71. package/dist/cli-dt931hb8.js +9740 -0
  72. package/dist/{cli-0e914dp9.js → cli-e1wprqnd.js} +3 -3
  73. package/dist/{cli-2ayk9gn8.js → cli-e2wzzw17.js} +2 -2
  74. package/dist/{cli-1jx0srjt.js → cli-e9p9h14n.js} +1921 -80
  75. package/dist/{cli-2savn6mm.js → cli-eaqxkeq0.js} +10 -10
  76. package/dist/{cli-dw9rtjm3.js → cli-etykr11s.js} +3061 -727
  77. package/dist/{cli-73rmgm45.js → cli-f07sgaax.js} +2 -2
  78. package/dist/{cli-gc6b94tj.js → cli-fe8he9cy.js} +2 -2
  79. package/dist/{cli-s4pccby1.js → cli-h0edykd1.js} +1 -1
  80. package/dist/cli-h5cveb69.js +15 -0
  81. package/dist/{cli-gcyws2bp.js → cli-hamdfjtx.js} +2 -2
  82. package/dist/{cli-jwnac23b.js → cli-hh5m39pt.js} +1 -1
  83. package/dist/{cli-f9g96z28.js → cli-j8fmn3wv.js} +11 -11
  84. package/dist/cli-jngvszex.js +1514 -0
  85. package/dist/{cli-8vbxjzk0.js → cli-k791mabe.js} +6 -6
  86. package/dist/{cli-9fwznq4p.js → cli-k9m8fckz.js} +7 -7
  87. package/dist/{cli-39t9d248.js → cli-kz8rar0g.js} +1 -1
  88. package/dist/{cli-rzbsh6bw.js → cli-n15fhd43.js} +1 -1
  89. package/dist/{cli-wvbaq052.js → cli-nmdy8bzf.js} +10 -3
  90. package/dist/{cli-t9pzz2eq.js → cli-ntmjzyte.js} +4 -1
  91. package/dist/{cli-adzmmcvf.js → cli-ny8f5g7t.js} +2 -2
  92. package/dist/cli-p0g0erm9.js +15 -0
  93. package/dist/{cli-2zjxake1.js → cli-pgdqhdkw.js} +4 -4
  94. package/dist/cli-ph1jce1b.js +16 -0
  95. package/dist/{cli-v4z5v3jd.js → cli-phantfg3.js} +480 -328
  96. package/dist/{cli-2414h5r9.js → cli-rb1z91g8.js} +10221 -1397
  97. package/dist/{cli-a49frv85.js → cli-redtbppc.js} +1 -1
  98. package/dist/{cli-91amj3md.js → cli-s7bfz1ye.js} +15 -15
  99. package/dist/{cli-kg63yp1r.js → cli-sf5kp73f.js} +18 -18
  100. package/dist/{cli-fww016hh.js → cli-sq32dgfe.js} +1373 -7129
  101. package/dist/{cli-enavhq6r.js → cli-tbrjvrrg.js} +1 -1
  102. package/dist/{cli-84xn7bgz.js → cli-tdd9dvw6.js} +1 -1
  103. package/dist/{cli-qkbevqer.js → cli-tjrrabez.js} +3 -3
  104. package/dist/{cli-q457ga28.js → cli-tkrp183j.js} +11 -11
  105. package/dist/{cli-7w1fs01q.js → cli-trvtxwzt.js} +2 -2
  106. package/dist/{cli-ayxxkk3p.js → cli-v1rhq77v.js} +8 -8
  107. package/dist/{cli-9j47sgzy.js → cli-v3jxx8dv.js} +2 -2
  108. package/dist/{cli-f2rwt43y.js → cli-v84kb7af.js} +13 -13
  109. package/dist/{cli-3mhdmcd4.js → cli-vp2ksaq9.js} +1 -1
  110. package/dist/{cli-b0m3bg0f.js → cli-vrb8pvrf.js} +6 -6
  111. package/dist/cli-vxxdf2ma.js +15 -0
  112. package/dist/{cli-wd7b5hgc.js → cli-w81s97bn.js} +1 -1
  113. package/dist/{cli-bqfx72e6.js → cli-wkzrknpt.js} +1 -1
  114. package/dist/{cli-cg1q8ymp.js → cli-wqpvfq2m.js} +1 -1
  115. package/dist/{cli-pq0kv31y.js → cli-wsh5vfa7.js} +9 -9
  116. package/dist/{cli-shyhb4t5.js → cli-wtwe8vng.js} +39 -39
  117. package/dist/{cli-3wsabyt0.js → cli-ww8wxfzx.js} +2 -2
  118. package/dist/{cli-e8trbfx1.js → cli-x80zagf5.js} +1 -1
  119. package/dist/{cli-r495stwd.js → cli-xd6ntv7x.js} +2 -2
  120. package/dist/{cli-0h6m6z5g.js → cli-xmc2nrtv.js} +1 -1
  121. package/dist/{cli-q5n3deaf.js → cli-ytgtqsy9.js} +1 -1
  122. package/dist/{cli-srq69pn1.js → cli-yvnnyjxm.js} +1 -1
  123. package/dist/{cli-krk8y8c7.js → cli-z0c98h7h.js} +1747 -439
  124. package/dist/{cli-mw1tmn3x.js → cli-z0effej1.js} +7 -7
  125. package/dist/{cli-7g5qj2ca.js → cli-zcb64xzv.js} +1 -1
  126. package/dist/{cli-m0ea8ggd.js → cli-zdkcp8p0.js} +2 -2
  127. package/dist/{cli-37p61fcg.js → cli-zgsd2w2k.js} +20 -22
  128. package/dist/{cli-tc165vrb.js → cli-zmfs06hg.js} +7 -6
  129. package/dist/{cli-edxfzgah.js → cli-zvsy4abb.js} +4 -4
  130. package/dist/{cli-z8t4485r.js → cli-zyf288rw.js} +2 -2
  131. package/dist/cli.js +58 -59
  132. package/dist/{codex-adapter-eq61radw.js → codex-adapter-seht4h9t.js} +9 -9
  133. package/dist/{codex-hook-8nmepvz6.js → codex-hook-w5nmtrn2.js} +2 -2
  134. package/dist/{codex-login-vbd9707w.js → codex-login-67qarfcg.js} +1 -1
  135. package/dist/{codex-session-runner-rfx355h4.js → codex-session-runner-tq95x3gq.js} +10 -10
  136. package/dist/{commands-d1z0sx62.js → commands-0awwqxq5.js} +3 -3
  137. package/dist/{controller-9hz6d8x3.js → controller-hgjx521c.js} +4 -4
  138. package/dist/{controllers-connect-tz07d2xr.js → controllers-connect-j4kdmhfj.js} +28 -28
  139. package/dist/core-8fw1gwg7.js +41 -0
  140. package/dist/{cursor-adapter-ef22ze3j.js → cursor-adapter-0rg8wk6j.js} +2 -2
  141. package/dist/{db-gd81d68c.js → db-8xs2js3s.js} +3 -3
  142. package/dist/{db-vrckks6q.js → db-dd6hj211.js} +2 -2
  143. package/dist/{devin-adapter-kdt6a2bh.js → devin-adapter-tn1twrha.js} +1 -1
  144. package/dist/{devtools-qxfgbsqz.js → devtools-b8qts77k.js} +1 -1
  145. package/dist/{dispatcher-76as8w2t.js → dispatcher-v7drd034.js} +24 -24
  146. package/dist/{docker-51ta7jsh.js → docker-6007r2fj.js} +2 -2
  147. package/dist/{dsh-adapter-ypfvcdyz.js → dsh-adapter-ah8npj2x.js} +2 -2
  148. package/dist/{e2b-dm9r8hpy.js → e2b-hg80w0qr.js} +2 -2
  149. package/dist/{e2b-05kn3kpq.js → e2b-z1g7vpz6.js} +4 -4
  150. package/dist/{easter-egg-3d-sg21j15g.js → easter-egg-3d-8n4w3s9k.js} +1 -1
  151. package/dist/{embedding-space-zsdw37bb.js → embedding-space-0p921zt3.js} +5 -5
  152. package/dist/{embeddings-p4e3e1m6.js → embeddings-9s7kbrc6.js} +1 -1
  153. package/dist/emscripten-module-Q67P5WYC-3sde6cre.js +2458 -0
  154. package/dist/{event-bus-tvf2grf4.js → event-bus-pawddp92.js} +1 -1
  155. package/dist/{execute-nztd0af0.js → execute-x0fy9j0m.js} +1 -1
  156. package/dist/{external-channel-717yzn4d.js → external-channel-ktfvn29c.js} +2 -2
  157. package/dist/ffi-cbfmmtqk.js +85 -0
  158. package/dist/fx-adapter-15vjxvgm.js +20 -0
  159. package/dist/getMachineId-bsd-2rd3pnz7.js +36 -0
  160. package/dist/getMachineId-bsd-3p48mkt1.js +36 -0
  161. package/dist/{getMachineId-bsd-637a7rbk.js → getMachineId-bsd-bk6tmeen.js} +5 -5
  162. package/dist/getMachineId-bsd-pssqgwmm.js +37 -0
  163. package/dist/getMachineId-bsd-v218x3xd.js +36 -0
  164. package/dist/getMachineId-bsd-wbxcazef.js +36 -0
  165. package/dist/getMachineId-bsd-x0942pbz.js +36 -0
  166. package/dist/getMachineId-darwin-5qsy4qcg.js +36 -0
  167. package/dist/getMachineId-darwin-6v7zsshx.js +37 -0
  168. package/dist/getMachineId-darwin-fcc3fjag.js +36 -0
  169. package/dist/getMachineId-darwin-pg84hftj.js +36 -0
  170. package/dist/{getMachineId-darwin-9vytrcnn.js → getMachineId-darwin-tyyevt26.js} +5 -5
  171. package/dist/getMachineId-darwin-wagmbf0d.js +36 -0
  172. package/dist/getMachineId-darwin-zvkmwr3y.js +36 -0
  173. package/dist/{getMachineId-linux-mkzsvyyz.js → getMachineId-linux-2ncg1epd.js} +3 -3
  174. package/dist/getMachineId-linux-2tmt2ptc.js +29 -0
  175. package/dist/getMachineId-linux-empwyp2y.js +29 -0
  176. package/dist/getMachineId-linux-fanqd45b.js +29 -0
  177. package/dist/getMachineId-linux-h6fyga0x.js +29 -0
  178. package/dist/getMachineId-linux-tbhgz1k9.js +29 -0
  179. package/dist/getMachineId-linux-zrbyw7dt.js +29 -0
  180. package/dist/getMachineId-unsupported-29g9dkgv.js +19 -0
  181. package/dist/getMachineId-unsupported-8xfq8djv.js +19 -0
  182. package/dist/getMachineId-unsupported-8y9cag1p.js +19 -0
  183. package/dist/getMachineId-unsupported-a6sjrm02.js +19 -0
  184. package/dist/getMachineId-unsupported-bp3w7ds0.js +19 -0
  185. package/dist/{getMachineId-unsupported-4cfs2n11.js → getMachineId-unsupported-sj6fk8sw.js} +3 -3
  186. package/dist/getMachineId-unsupported-v0p5gdxp.js +19 -0
  187. package/dist/getMachineId-win-hc996p0x.js +38 -0
  188. package/dist/{getMachineId-win-154s3qma.js → getMachineId-win-msq9ad87.js} +6 -6
  189. package/dist/getMachineId-win-tajyqwd6.js +38 -0
  190. package/dist/getMachineId-win-tzc163da.js +38 -0
  191. package/dist/getMachineId-win-xdaa0mgq.js +38 -0
  192. package/dist/getMachineId-win-xk6p98m5.js +38 -0
  193. package/dist/getMachineId-win-xtk658fm.js +38 -0
  194. package/dist/{google-generative-ai-sw77egmr.js → google-generative-ai-nzndg246.js} +1 -1
  195. package/dist/{google-vertex-rrw93g8h.js → google-vertex-ragh3nnw.js} +1 -1
  196. package/dist/grok-adapter-77httan0.js +20 -0
  197. package/dist/handlers-c1jp5b6h.js +39 -0
  198. package/dist/heartbeat-5yaj6dym.js +49 -0
  199. package/dist/{hook-ctz0xmp3.js → hook-2jttae8s.js} +10 -11
  200. package/dist/hook-c99nycyh.js +21 -0
  201. package/dist/{http-zregegrx.js → http-7y9dbfrr.js} +155 -122
  202. package/dist/{index-kzdqn3dd.js → index-6g9rdcrj.js} +3036 -758
  203. package/dist/index-7dwh9kxh.js +41 -0
  204. package/dist/{index-ym9fgxad.js → index-8p03vx1h.js} +8 -8
  205. package/dist/{index-maddg9ys.js → index-cw8nxnba.js} +4330 -15375
  206. package/dist/{index-fdym6ryb.js → index-dm7c6hw5.js} +28 -28
  207. package/dist/index-fqf82sbk.js +10584 -0
  208. package/dist/{index-126v2d0t.js → index-g7rthzrv.js} +11 -2923
  209. package/dist/{index-x9qf8dg7.js → index-h9xnzfhx.js} +21 -20
  210. package/dist/{index-42jq9yy3.js → index-jvfp0j47.js} +516 -10
  211. package/dist/{index-mtnbhe12.js → index-q60mhcpd.js} +23631 -19921
  212. package/dist/{index-evay0xyk.js → index-qxcfv8vq.js} +1 -1
  213. package/dist/{index-rz8ve510.js → index-t274qhhs.js} +6 -6
  214. package/dist/{index-kdmkfjt7.js → index-t4n9z755.js} +3491 -2487
  215. package/dist/{index-7dgxveck.js → index-tcegcysh.js} +5 -5
  216. package/dist/{index-whysn1wf.js → index-tn1m3q9b.js} +3 -3
  217. package/dist/index-wp9tarbt.js +43 -0
  218. package/dist/{index-5kx15d19.js → index-xhp7yp3t.js} +1 -1
  219. package/dist/index-z6np2405.js +38 -0
  220. package/dist/{k8s-ejkk0aw7.js → k8s-mr1r12th.js} +2 -2
  221. package/dist/{keepalive-zdqay870.js → keepalive-7eyb8y4t.js} +4 -4
  222. package/dist/lead-50cgn8s1.js +81 -0
  223. package/dist/{maintenance-t5ndg11m.js → maintenance-tdrd8nwv.js} +1 -1
  224. package/dist/module-ES6BEMUI-6htewwha.js +1210 -0
  225. package/dist/{node-0as4n1ef.js → node-gbx1t3pa.js} +1 -1
  226. package/dist/{oauth-refresh-sweep-y9zyd7t6.js → oauth-refresh-sweep-f4c7g37h.js} +3 -3
  227. package/dist/{object-webhooks-mkca91s0.js → object-webhooks-p190rdxp.js} +7 -7
  228. package/dist/{onboard-ss995244.js → onboard-56h4sks6.js} +7 -7
  229. package/dist/{opencode-adapter-mwpz0278.js → opencode-adapter-xg3yxfr0.js} +8 -8
  230. package/dist/{otel-impl-6n6vva3x.js → otel-impl-kepzgm4n.js} +36360 -9179
  231. package/dist/{pending-2sxh1t6j.js → pending-xgv316w0.js} +25 -25
  232. package/dist/{pi-mono-adapter-sfb7zy43.js → pi-mono-adapter-txe0syzb.js} +19 -22
  233. package/dist/{pricing-refresh-h79bg4cf.js → pricing-refresh-041zpyhf.js} +2 -2
  234. package/dist/{rbac-roles-ckq0czp4.js → rbac-roles-8f3jbcaf.js} +2 -2
  235. package/dist/{rbac-roles-jg2e260w.js → rbac-roles-cw7rrw5b.js} +3 -3
  236. package/dist/{render-v2-ymbshmn0.js → render-v2-2ezw4mzt.js} +10 -10
  237. package/dist/{resume-jdhnt4jk.js → resume-p14wdx8m.js} +13 -13
  238. package/dist/{runtime-y28jhhnf.js → runtime-he7c9g1r.js} +1 -1
  239. package/dist/{session-access-k4ta5hvp.js → session-access-8jvq86fj.js} +5 -5
  240. package/dist/{session-source-backfill-528j4s8j.js → session-source-backfill-6fe3hcgb.js} +3 -3
  241. package/dist/{setup-d6pj82fr.js → setup-6v0bn4r1.js} +3 -3
  242. package/dist/thread-buffer-8860v1ta.js +40 -0
  243. package/dist/{token-util-pjgekqxr.js → token-util-hnzceyn9.js} +1 -1
  244. package/dist/{token-pgr2w4s3.js → token-xnc02n6w.js} +21 -14
  245. package/dist/{tree-visibility-kjxv3nxk.js → tree-visibility-g1a8ff4r.js} +2 -2
  246. package/dist/{user-merge-jobs-rabbncf6.js → user-merge-jobs-vjsps179.js} +3 -3
  247. package/dist/{virtual-modules-22k51txd.js → virtual-modules-mreda4fp.js} +3 -3
  248. package/dist/{work-objects-xtjbar3r.js → work-objects-hfw15e35.js} +26 -26
  249. package/dist/{worker-follow-up-fg48vk6d.js → worker-follow-up-gbaz2ydz.js} +24 -24
  250. package/dist/worker-hkm8ftqp.js +81 -0
  251. package/dist/{x-vfsqypht.js → x-k29vmskt.js} +2 -2
  252. package/openapi.json +57 -1
  253. package/package.json +39 -39
  254. package/src/be/db/model-profiles.ts +103 -12
  255. package/src/be/db/tasks/read.ts +5 -0
  256. package/src/be/db.ts +14 -4
  257. package/src/be/model-group-resolution.ts +134 -0
  258. package/src/be/model-tier-resolution.ts +120 -17
  259. package/src/be/model-validation.ts +9 -1
  260. package/src/be/runtime-pools/routing.ts +22 -8
  261. package/src/be/scripts/extract-schema.ts +7 -0
  262. package/src/be/swarm-config-guard.ts +17 -7
  263. package/src/commands/onboard/agent-fs-version.ts +1 -1
  264. package/src/extensions/contract-types.generated.ts +1 -1
  265. package/src/http/db-query.ts +8 -2
  266. package/src/http/operator-actor.ts +3 -8
  267. package/src/http/poll.ts +20 -1
  268. package/src/http/repos.ts +3 -1
  269. package/src/http/schedules.ts +23 -3
  270. package/src/http/tasks.ts +11 -1
  271. package/src/prompts/base-prompt.ts +10 -6
  272. package/src/prompts/session-templates.ts +3 -3
  273. package/src/providers/acp-targets.ts +1 -1
  274. package/src/providers/amp-adapter.ts +11 -9
  275. package/src/providers/cursor-adapter.ts +1 -1
  276. package/src/realtime/browser.generated.txt +1 -1
  277. package/src/scheduler/schedule-task.ts +1 -0
  278. package/src/scripts-runtime/types/swarm-extension.d.ts +2 -0
  279. package/src/slack/config.ts +4 -0
  280. package/src/slack/render-v2.ts +2 -1
  281. package/src/slack/responses.ts +2 -1
  282. package/src/tasks/follow-up-gate.ts +142 -38
  283. package/src/tasks/worker-follow-up.ts +126 -37
  284. package/src/tests/amp-adapter.test.ts +57 -9
  285. package/src/tests/base-prompt.test.ts +36 -2
  286. package/src/tests/db-retention-defaults.test.ts +28 -3
  287. package/src/tests/entrypoint-repo-autoclone-args.test.ts +10 -0
  288. package/src/tests/follow-up-gate-shadow.test.ts +268 -10
  289. package/src/tests/linear-outbound-sync.test.ts +59 -25
  290. package/src/tests/operator-actor-keyless.test.ts +103 -0
  291. package/src/tests/profile-tier-alias.test.ts +9 -3
  292. package/src/tests/runner-repo-clone-args.test.ts +15 -6
  293. package/src/tests/workflow-system-one-extraction.test.ts +21 -0
  294. package/src/tests/workflow-wait-filter.test.ts +7 -7
  295. package/src/tests/worktree-reaper.test.ts +15 -4
  296. package/src/tools/schedules/create-schedule.ts +20 -3
  297. package/src/tools/schedules/patch-schedule.ts +30 -4
  298. package/src/tools/schedules/update-schedule.ts +30 -4
  299. package/src/tools/send-task.ts +17 -3
  300. package/src/tools/slack-post.ts +7 -2
  301. package/src/tools/slack-reply.ts +6 -2
  302. package/src/tools/task-action.ts +16 -3
  303. package/src/tools/utils.ts +1 -1
  304. package/src/types.ts +10 -0
  305. package/src/utils/amp-models.ts +20 -4
  306. package/src/utils/secret-scrubber.ts +6 -4
  307. package/src/workflows/engine.ts +36 -8
  308. package/src/workflows/executors/agent-task.ts +13 -2
  309. package/src/workflows/executors/code-match.ts +11 -31
  310. package/src/workflows/executors/script.ts +13 -0
  311. package/src/workflows/executors/system-one-extraction.ts +9 -6
  312. package/src/workflows/executors/wait.ts +1 -1
  313. package/src/workflows/foreach-driver.ts +5 -1
  314. package/src/workflows/model-validation.ts +13 -1
  315. package/src/workflows/predicate-sandbox.ts +171 -0
  316. package/src/workflows/retry-poller.ts +1 -1
  317. package/src/workflows/wait-filter.ts +14 -192
  318. package/templates/skills/heartbeat-runbook/content.md +1 -0
  319. package/templates/skills/slack-interaction/content.md +4 -0
  320. package/templates/skills/swarm-docs/content.md +1 -0
  321. package/dist/acp-adapter-99n6z9ky.js +0 -17
  322. package/dist/cli-5ss6qqt9.js +0 -45
  323. package/dist/cli-dzzh58sy.js +0 -6996
  324. package/dist/cli-j9ccfveb.js +0 -1849
  325. package/dist/cli-mna6pmfx.js +0 -1485
  326. package/dist/cli-r8ddn0hf.js +0 -25583
  327. package/dist/core-dynsv289.js +0 -41
  328. package/dist/fx-adapter-9k0hptnz.js +0 -20
  329. package/dist/grok-adapter-skdj2pce.js +0 -20
  330. package/dist/handlers-5btjqkz6.js +0 -39
  331. package/dist/heartbeat-vfb1gy84.js +0 -49
  332. package/dist/hook-eh52p7yd.js +0 -22
  333. package/dist/index-7w8p6em0.js +0 -41
  334. package/dist/index-t56y945n.js +0 -4
  335. package/dist/index-vfemrwwk.js +0 -10002
  336. package/dist/index-vz4semsx.js +0 -38
  337. package/dist/index-y3s0xp2v.js +0 -43
  338. package/dist/lead-6cscw8a5.js +0 -82
  339. package/dist/thread-buffer-9w6x5zec.js +0 -40
  340. package/dist/worker-g4aj93dt.js +0 -82
  341. package/dist/{azure-openai-responses-jeaas6x0.js → azure-openai-responses-e76k86gf.js} +4 -4
  342. package/dist/{openai-codex-responses-70g39cgz.js → openai-codex-responses-z2h941b8.js} +4 -4
  343. package/dist/{openai-completions-cv3hp4h5.js → openai-completions-5bxdkeg9.js} +4 -4
  344. package/dist/{openai-responses-trsvnks6.js → openai-responses-dzf3e8r5.js} +4 -4
@@ -3,7 +3,7 @@ import {
3
3
  ampPinCatalogError,
4
4
  ampModelError,
5
5
  init_amp_models
6
- } from "./cli-wvbaq052.js";
6
+ } from "./cli-nmdy8bzf.js";
7
7
  import {
8
8
  ALL_TOOLS,
9
9
  init_tool_config
@@ -14,7 +14,7 @@ import {
14
14
  applyProviderQuotaReport,
15
15
  scrubProviderQuotaReport,
16
16
  init_provider_account_telemetry
17
- } from "./cli-cg1q8ymp.js";
17
+ } from "./cli-wqpvfq2m.js";
18
18
  import {
19
19
  CODEX_AUTH_FAILURE_BENCH_THRESHOLD,
20
20
  CODEX_AUTH_FAILURE_BENCH_MS,
@@ -42,11 +42,11 @@ import {
42
42
  init_identity_field_budget,
43
43
  contentSha256,
44
44
  init_profile_sync
45
- } from "./cli-wym6rxgt.js";
45
+ } from "./cli-8kemtj1r.js";
46
46
  import {
47
47
  isSlackConfigured,
48
48
  init_config5
49
- } from "./cli-t9pzz2eq.js";
49
+ } from "./cli-ntmjzyte.js";
50
50
  import {
51
51
  isSteeringEnabled2,
52
52
  init_steering_enabled
@@ -61,28 +61,6 @@ import {
61
61
  codexPlanFromClaim,
62
62
  init_subscription_plans
63
63
  } from "./cli-nh7x3133.js";
64
- import {
65
- activeModelBlock,
66
- init_model_rate_limit_windows,
67
- CREDENTIAL_SELECTION_STRATEGIES,
68
- keyUsageFromWindows,
69
- keyPaceFromWindows,
70
- init_key_usage,
71
- getModelAwareCredentialVars,
72
- deriveProviderFromKeyType,
73
- keySuffix,
74
- splitCredentialPool,
75
- selectCredential,
76
- init_credentials2
77
- } from "./cli-wd7b5hgc.js";
78
- import {
79
- registerTemplate,
80
- getAllTemplateDefinitions,
81
- init_registry3,
82
- configureDbResolver,
83
- init_resolver,
84
- init_session_templates
85
- } from "./cli-24wervhz.js";
86
64
  import {
87
65
  getOpenRouterAttributionHeaders,
88
66
  init_openrouter_base_url
@@ -127,12 +105,34 @@ import {
127
105
  SUPERSEDED_WORKFLOW_TASK_REASON,
128
106
  PageThemeTokensSchema,
129
107
  init_types5
130
- } from "./cli-tc165vrb.js";
108
+ } from "./cli-zmfs06hg.js";
109
+ import {
110
+ activeModelBlock,
111
+ init_model_rate_limit_windows,
112
+ CREDENTIAL_SELECTION_STRATEGIES,
113
+ keyUsageFromWindows,
114
+ keyPaceFromWindows,
115
+ init_key_usage,
116
+ getModelAwareCredentialVars,
117
+ deriveProviderFromKeyType,
118
+ keySuffix,
119
+ splitCredentialPool,
120
+ selectCredential,
121
+ init_credentials2
122
+ } from "./cli-w81s97bn.js";
123
+ import {
124
+ registerTemplate,
125
+ getAllTemplateDefinitions,
126
+ init_registry3,
127
+ configureDbResolver,
128
+ init_resolver,
129
+ init_session_templates
130
+ } from "./cli-aktk3qt6.js";
131
131
  import {
132
132
  setRuntimeModelCatalog,
133
133
  runtimeHarnessSections,
134
134
  init_runtime_model_catalog
135
- } from "./cli-7ca8hczj.js";
135
+ } from "./cli-7svwhw1a.js";
136
136
  import {
137
137
  init_zod
138
138
  } from "./cli-96234j5w.js";
@@ -153,6 +153,10 @@ import {
153
153
  literal2,
154
154
  exports_iso
155
155
  } from "./cli-qrzq3hvg.js";
156
+ import {
157
+ realtimeBus,
158
+ init_bus
159
+ } from "./cli-syfdvhkc.js";
156
160
  import {
157
161
  isEnvFlagEnabled,
158
162
  init_env_flag
@@ -160,16 +164,12 @@ import {
160
164
  import {
161
165
  init_package,
162
166
  package_default
163
- } from "./cli-shyhb4t5.js";
167
+ } from "./cli-wtwe8vng.js";
164
168
  import {
165
169
  getNodeEnv,
166
170
  isDevOrTestNodeEnv,
167
171
  init_node_env
168
172
  } from "./cli-rgeadyvq.js";
169
- import {
170
- realtimeBus,
171
- init_bus
172
- } from "./cli-syfdvhkc.js";
173
173
  import {
174
174
  chatgptSubscriptionModelId,
175
175
  isAlias,
@@ -192,7 +192,7 @@ import {
192
192
  registerVolatileSecret,
193
193
  registerSensitiveKeyName,
194
194
  init_secret_scrubber
195
- } from "./cli-r9d2tya0.js";
195
+ } from "./cli-7qkbab03.js";
196
196
  import {
197
197
  __toCommonJS,
198
198
  __commonJS,
@@ -5751,7 +5751,7 @@ var init_telemetry = __esm(() => {
5751
5751
  // src/telemetry-identity.ts
5752
5752
  async function loadUserRole(userId) {
5753
5753
  try {
5754
- const { getUserGrant } = await import("./rbac-roles-jg2e260w.js");
5754
+ const { getUserGrant } = await import("./rbac-roles-cw7rrw5b.js");
5755
5755
  const grant = await getUserGrant(userId);
5756
5756
  const role = grant.grantsAll ? "admin" : "member";
5757
5757
  const user = await getDbClient2().get("SELECT json_extract(metadata, '$.jobFunction') AS jobFunction FROM users WHERE id = ? AND json_valid(metadata)", [userId]);
@@ -6639,7 +6639,7 @@ function scheduleApprovalCardUpdates(approvals) {
6639
6639
  const posted = approvals.filter((approval) => approval.notificationChannels?.some((n) => n.channel === "slack" && n.messageTs));
6640
6640
  if (posted.length === 0)
6641
6641
  return;
6642
- getDbClient2().afterCommit(() => import("./approval-notifications-7qgkzkzx.js").then(({ updateResolvedApprovalCards }) => updateResolvedApprovalCards(posted)).catch((err) => console.error("[HITL] Slack card update not run:", scrubSecrets(err instanceof Error ? err.message : String(err)))));
6642
+ getDbClient2().afterCommit(() => import("./approval-notifications-hbqtb2w3.js").then(({ updateResolvedApprovalCards }) => updateResolvedApprovalCards(posted)).catch((err) => console.error("[HITL] Slack card update not run:", scrubSecrets(err instanceof Error ? err.message : String(err)))));
6643
6643
  }
6644
6644
  var init_approvals = __esm(() => {
6645
6645
  init_secret_scrubber();
@@ -8806,7 +8806,7 @@ async function applyCliSupport(resolution, harness, cliVersion) {
8806
8806
  return { ...resolution, resolvedModel: fallback, modelSource };
8807
8807
  }
8808
8808
  async function resolveClaimProfile(name, source, harness) {
8809
- const isTask = source === "profile:task";
8809
+ const isTask = source === "profile:task" || source === "profile:group";
8810
8810
  const profile = await getModelProfileByName(name);
8811
8811
  if (!profile) {
8812
8812
  return isTask ? { modelUnsupported: `[model-profile-missing] Model profile "${name}" no longer exists.` } : null;
@@ -8848,18 +8848,40 @@ async function resolveClaimProfile(name, source, harness) {
8848
8848
  resolution
8849
8849
  };
8850
8850
  }
8851
- async function resolveTierAlias(resolved, task, harness) {
8851
+ async function resolveTierAlias(resolved, task, agentId, harness, includeRepoSecrets) {
8852
8852
  const tier = parseModelTier(task.modelTier);
8853
8853
  if (!resolved || "harnessMismatch" in resolved || !tier || !harness)
8854
8854
  return null;
8855
- const name = `${harness}-${tier}`;
8855
+ const seeded = `${harness}-${tier}`;
8856
8856
  if (resolved.modelSource === "worker-env" || resolved.modelSource === "tier-config") {
8857
- console.log(`[model-tier] deprecated: ${resolved.modelSource} override for ${name}; edit profile ${name} instead`);
8857
+ console.log(`[model-tier] deprecated: ${resolved.modelSource} override for ${seeded}; edit profile ${seeded} instead`);
8858
8858
  return null;
8859
8859
  }
8860
8860
  if (resolved.modelSource !== "tier-default")
8861
8861
  return null;
8862
- const picked = await resolveClaimProfile(name, "profile:tier-alias", harness);
8862
+ const group = await resolveGroupForAgent(tier, agentId, {
8863
+ vcsRepo: task.vcsRepo,
8864
+ includeRepoSecrets
8865
+ });
8866
+ let name = seeded;
8867
+ let picked = null;
8868
+ if (group.kind === "resolved") {
8869
+ picked = await resolveClaimProfile(group.member, "profile:tier-alias", harness);
8870
+ if (picked && "profile" in picked) {
8871
+ name = group.member;
8872
+ const untouched = group.onHarness.length === 1 && group.onHarness[0] === seeded;
8873
+ if (!untouched) {
8874
+ picked = { ...picked, resolution: { ...picked.resolution, modelSource: "profile:group" } };
8875
+ }
8876
+ if (group.member !== seeded) {
8877
+ await logGroupResolution(task.id, agentId, tier, group.member, group.skipped);
8878
+ }
8879
+ }
8880
+ }
8881
+ if (!picked || !("profile" in picked)) {
8882
+ picked = await resolveClaimProfile(seeded, "profile:tier-alias", harness);
8883
+ name = seeded;
8884
+ }
8863
8885
  if (!picked || !("profile" in picked))
8864
8886
  return picked;
8865
8887
  if (isHarnessModelJudged(harness) && harnessModelMismatch(picked.resolution.resolvedModel, harness, (await loadResolutionCatalog()).catalog)) {
@@ -8868,14 +8890,41 @@ async function resolveTierAlias(resolved, task, harness) {
8868
8890
  }
8869
8891
  return picked;
8870
8892
  }
8893
+ async function logGroupResolution(taskId, agentId, group, member, skipped) {
8894
+ await createLogEntry2({
8895
+ eventType: "task_model_group_resolved",
8896
+ taskId,
8897
+ agentId,
8898
+ newValue: member,
8899
+ metadata: { group, member, skipped }
8900
+ });
8901
+ }
8902
+ async function resolveClaimGroup(group, task, agentId, harness, includeRepoSecrets) {
8903
+ const resolution = await resolveGroupForAgent(group, agentId, {
8904
+ vcsRepo: task.vcsRepo,
8905
+ includeRepoSecrets
8906
+ });
8907
+ if (resolution.kind === "missing") {
8908
+ return { modelUnsupported: `[model-group-missing] Model group "${group}" no longer exists.` };
8909
+ }
8910
+ if (resolution.kind === "none") {
8911
+ return { modelUnsupported: groupUnavailableMessage(group, harness, resolution.skipped) };
8912
+ }
8913
+ if (resolution.skipped.length > 0) {
8914
+ console.log(`[model-group] task ${task.id}: ${group} → ${resolution.member} (skipped: ${formatGroupSkips(resolution.skipped)})`);
8915
+ }
8916
+ await logGroupResolution(task.id, agentId, group, resolution.member, resolution.skipped);
8917
+ return await resolveClaimProfile(resolution.member, "profile:group", harness);
8918
+ }
8871
8919
  async function recordClaimModelResolution(task, agent, { includeRepoSecrets = true } = {}) {
8872
8920
  const harnessProvider = agent.harnessProvider ?? agent.provider ?? null;
8873
8921
  if (!task.model?.trim()) {
8874
8922
  const taskProfile = task.profile?.trim();
8875
- const agentDefault = taskProfile || parseModelTier(task.modelTier) ? null : await getAgentDefaultProfileName(agent.id);
8923
+ const taskGroup = taskProfile ? undefined : task.modelGroup?.trim();
8924
+ const agentDefault = taskProfile || taskGroup || parseModelTier(task.modelTier) ? null : await getAgentDefaultProfileName(agent.id);
8876
8925
  const repoKeys = agentDefault ? await repoModelOverrideKeys(task.vcsRepo, { includeSecrets: includeRepoSecrets }) : new Set;
8877
8926
  const defaultProfile = repoKeys.has("MODEL_OVERRIDE") ? null : agentDefault;
8878
- const picked = taskProfile ? await resolveClaimProfile(taskProfile, "profile:task", harnessProvider) : defaultProfile ? await resolveClaimProfile(defaultProfile, "profile:agent-default", harnessProvider) : null;
8927
+ const picked = taskProfile ? await resolveClaimProfile(taskProfile, "profile:task", harnessProvider) : taskGroup ? await resolveClaimGroup(taskGroup, task, agent.id, harnessProvider, includeRepoSecrets) : defaultProfile ? await resolveClaimProfile(defaultProfile, "profile:agent-default", harnessProvider) : null;
8879
8928
  if (picked && "modelUnsupported" in picked)
8880
8929
  return { modelUnsupported: picked.modelUnsupported };
8881
8930
  if (picked) {
@@ -8904,7 +8953,7 @@ async function recordClaimModelResolution(task, agent, { includeRepoSecrets = tr
8904
8953
  harnessProvider,
8905
8954
  workerOverrides: await getAgentModelTierOverrides(agent.id)
8906
8955
  });
8907
- const alias = await resolveTierAlias(resolvedTier, task, harnessProvider);
8956
+ const alias = await resolveTierAlias(resolvedTier, task, agent.id, harnessProvider, includeRepoSecrets);
8908
8957
  if (alias && "modelUnsupported" in alias)
8909
8958
  return { modelUnsupported: alias.modelUnsupported };
8910
8959
  if (alias) {
@@ -8952,6 +9001,7 @@ var init_model_tier_resolution = __esm(() => {
8952
9001
  init_model_profiles();
8953
9002
  init_harness_model_support();
8954
9003
  init_model_catalog_store();
9004
+ init_model_group_resolution();
8955
9005
  init_model_tier_keys();
8956
9006
  init_modelsdev_cache();
8957
9007
  init_model_tier_keys();
@@ -9003,6 +9053,9 @@ async function poolTaskRunsOnHarness(task, harness) {
9003
9053
  const profile = await getModelProfileByName(profileName);
9004
9054
  return !profile || !harness || profile.harness === harness;
9005
9055
  }
9056
+ const groupName = task?.modelGroup?.trim();
9057
+ if (groupName)
9058
+ return await groupHasMemberOnHarness(groupName, harness);
9006
9059
  const model = taskModelPin(task ?? {})?.trim();
9007
9060
  if (!model)
9008
9061
  return true;
@@ -9088,6 +9141,7 @@ var init_model_validation2 = __esm(() => {
9088
9141
  init_db4();
9089
9142
  init_model_profiles();
9090
9143
  init_model_catalog_store();
9144
+ init_model_group_resolution();
9091
9145
  init_model_tier_resolution();
9092
9146
  FREE_FORM_HARNESSES = new Set(["acp", "devin", "dsh", "cursor"]);
9093
9147
  CONTEXT_SUFFIX_RE = /\[1m\]$/i;
@@ -9298,6 +9352,76 @@ var init_model_profile_check = __esm(() => {
9298
9352
  STATE_RANK = { pass: 0, unverified: 1, warn: 2, fail: 3 };
9299
9353
  });
9300
9354
 
9355
+ // src/be/model-group-resolution.ts
9356
+ async function modelGroupMemberHarnesses(group) {
9357
+ const rows = await getDbClient2().query(`SELECT m.profileName AS profile, p.harness AS harness
9358
+ FROM model_groups g
9359
+ LEFT JOIN model_group_members m ON m.groupId = g.id
9360
+ LEFT JOIN model_profiles p ON p.name = m.profileName
9361
+ WHERE g.name = ?
9362
+ ORDER BY m.position`, [group.trim()]);
9363
+ if (rows.length === 0)
9364
+ return null;
9365
+ return rows.flatMap((row) => row.profile && row.harness ? [{ profile: row.profile, harness: row.harness }] : []);
9366
+ }
9367
+ function firstFailingCheck(result) {
9368
+ const row = result.profiles[0]?.checks.find((check) => check.state === "fail");
9369
+ if (!row)
9370
+ return "failed the profile check";
9371
+ return row.detail ? `${row.check}: ${row.detail}` : row.check;
9372
+ }
9373
+ async function resolveGroupForAgent(group, agentId, options = {}) {
9374
+ const members = await modelGroupMemberHarnesses(group);
9375
+ if (!members)
9376
+ return { kind: "missing" };
9377
+ const agent = await getAgentById2(agentId);
9378
+ const harness = agent?.harnessProvider ?? agent?.provider ?? null;
9379
+ const skipped = [];
9380
+ const from = options.startAfter ? members.findIndex((member) => member.profile === options.startAfter) + 1 : 0;
9381
+ for (let index = from;index < members.length; index++) {
9382
+ const member = members[index];
9383
+ if (options.skip?.has(member.profile))
9384
+ continue;
9385
+ if (member.harness !== harness) {
9386
+ if (options.sameHarnessOnly)
9387
+ continue;
9388
+ skipped.push({ profile: member.profile, reason: `harness: runs on ${member.harness}` });
9389
+ continue;
9390
+ }
9391
+ const result = await checkProfileForAgent(agentId, member.profile, {
9392
+ vcsRepo: options.vcsRepo,
9393
+ includeRepoSecrets: options.includeRepoSecrets,
9394
+ fallbacks: false
9395
+ });
9396
+ if (result?.ok) {
9397
+ const onHarness = members.filter((m) => m.harness === harness).map((m) => m.profile);
9398
+ return { kind: "resolved", member: member.profile, index, skipped, onHarness };
9399
+ }
9400
+ skipped.push({
9401
+ profile: member.profile,
9402
+ reason: result ? firstFailingCheck(result) : "not found"
9403
+ });
9404
+ }
9405
+ return { kind: "none", skipped };
9406
+ }
9407
+ function formatGroupSkips(skipped) {
9408
+ return skipped.map((skip) => `${skip.profile} (${skip.reason})`).join(", ");
9409
+ }
9410
+ function groupUnavailableMessage(group, harness, skipped) {
9411
+ const where = harness ? `this ${harness} agent` : "this agent";
9412
+ return `[model-group-unavailable] no member of "${group}" runs on ${where}${skipped.length > 0 ? `: ${formatGroupSkips(skipped)}` : ""}`;
9413
+ }
9414
+ async function groupHasMemberOnHarness(group, harness) {
9415
+ if (!harness)
9416
+ return true;
9417
+ const members = await modelGroupMemberHarnesses(group);
9418
+ return !members || members.some((member) => member.harness === harness);
9419
+ }
9420
+ var init_model_group_resolution = __esm(() => {
9421
+ init_db4();
9422
+ init_model_profile_check();
9423
+ });
9424
+
9301
9425
  // src/utils/provider-metadata.ts
9302
9426
  function parseProviderMeta(rawProvider, rawMeta) {
9303
9427
  if (!rawMeta || !rawProvider)
@@ -9615,6 +9739,7 @@ function rowToAgentTask(row) {
9615
9739
  resolvedEffort: ReasoningEffortSchema.safeParse(row.resolvedEffort).success ? row.resolvedEffort : undefined,
9616
9740
  profile: row.profile ?? undefined,
9617
9741
  resolvedProfile: row.resolvedProfile ?? undefined,
9742
+ modelGroup: row.modelGroup ?? undefined,
9618
9743
  fallbackHops: parseFallbackHops(row.fallbackHops),
9619
9744
  scheduleId: row.scheduleId ?? undefined,
9620
9745
  workflowRunId: row.workflowRunId ?? undefined,
@@ -9677,6 +9802,7 @@ function rowToAgentTaskSummary(row) {
9677
9802
  resolvedEffort: ReasoningEffortSchema.safeParse(row.resolvedEffort).success ? row.resolvedEffort : undefined,
9678
9803
  profile: row.profile ?? undefined,
9679
9804
  resolvedProfile: row.resolvedProfile ?? undefined,
9805
+ modelGroup: row.modelGroup ?? undefined,
9680
9806
  provider: row.provider ?? undefined,
9681
9807
  requestedByUserId: row.requestedByUserId ?? undefined,
9682
9808
  progress: row.progress ?? undefined,
@@ -10653,6 +10779,7 @@ var init_read = __esm(() => {
10653
10779
  agent_tasks.scheduleId, agent_tasks.model, agent_tasks.modelTier,
10654
10780
  agent_tasks.resolvedModel, agent_tasks.modelSource, agent_tasks.modelAlias, agent_tasks.effort,
10655
10781
  agent_tasks.resolvedEffort, agent_tasks.profile, agent_tasks.resolvedProfile,
10782
+ agent_tasks.modelGroup,
10656
10783
  agent_tasks.provider, agent_tasks.requestedByUserId, agent_tasks.progress,
10657
10784
  agent_tasks.createdAt, agent_tasks.lastUpdatedAt, agent_tasks.finishedAt,
10658
10785
  agent_tasks.statusKind, agent_tasks.peakContextPercent`,
@@ -10892,6 +11019,9 @@ async function repoModelOverrideKeys(vcsRepo, { includeSecrets = true } = {}) {
10892
11019
  return new Set(rows.map((row) => row.key));
10893
11020
  }
10894
11021
  async function taskProfileError(check) {
11022
+ const group = check.modelGroup?.trim();
11023
+ if (group)
11024
+ return await taskModelGroupError({ ...check, modelGroup: group });
10895
11025
  const name = check.profile?.trim();
10896
11026
  if (!name)
10897
11027
  return null;
@@ -10912,9 +11042,46 @@ async function taskProfileError(check) {
10912
11042
  return null;
10913
11043
  return formatProfileCheckFailures(result);
10914
11044
  }
11045
+ async function taskModelGroupError(check) {
11046
+ if (check.model?.trim() || check.modelTier?.trim() || check.profile?.trim()) {
11047
+ return "Pass `modelGroup`, or `model`/`modelTier`/`profile`, not both.";
11048
+ }
11049
+ if (!check.agentId) {
11050
+ return await modelGroupMemberHarnesses(check.modelGroup) ? null : unknownModelGroupMessage(check.modelGroup);
11051
+ }
11052
+ const resolution = await resolveGroupForAgent(check.modelGroup, check.agentId, {
11053
+ vcsRepo: check.vcsRepo
11054
+ });
11055
+ if (resolution.kind === "missing")
11056
+ return unknownModelGroupMessage(check.modelGroup);
11057
+ if (resolution.kind === "resolved")
11058
+ return null;
11059
+ const agent = await getAgentById2(check.agentId);
11060
+ return groupUnavailableMessage(check.modelGroup, agent?.harnessProvider ?? agent?.provider, resolution.skipped);
11061
+ }
11062
+ function unknownModelGroupMessage(name) {
11063
+ return `Unknown model group "${name}". List groups with GET /api/model-groups.`;
11064
+ }
11065
+ function modelGroupRefError(error) {
11066
+ const message = error instanceof Error ? error.message : "";
11067
+ return message.includes("model-group-missing:");
11068
+ }
10915
11069
  async function scheduleProfileUpdate(existing, patch) {
10916
11070
  const profile = patch.profile === undefined ? undefined : patch.profile?.trim() || null;
11071
+ const modelGroup = patch.modelGroup === undefined ? undefined : patch.modelGroup?.trim() || null;
10917
11072
  const agentId = patch.targetAgentId !== undefined ? patch.targetAgentId : existing.targetAgentId;
11073
+ if (modelGroup) {
11074
+ const error = await taskProfileError({
11075
+ modelGroup,
11076
+ profile,
11077
+ model: patch.model,
11078
+ modelTier: patch.modelTier,
11079
+ agentId
11080
+ });
11081
+ if (error)
11082
+ return { error };
11083
+ return { fields: { modelGroup, profile: null, model: null, modelTier: null } };
11084
+ }
10918
11085
  if (profile) {
10919
11086
  const error = await taskProfileError({
10920
11087
  profile,
@@ -10924,18 +11091,24 @@ async function scheduleProfileUpdate(existing, patch) {
10924
11091
  });
10925
11092
  if (error)
10926
11093
  return { error };
10927
- return { fields: { profile, model: null, modelTier: null } };
11094
+ return { fields: { profile, modelGroup: null, model: null, modelTier: null } };
10928
11095
  }
10929
- if (patch.model?.trim() || patch.modelTier?.trim() || profile === null) {
10930
- return { fields: { profile: null } };
11096
+ if (patch.model?.trim() || patch.modelTier?.trim()) {
11097
+ return { fields: { profile: null, modelGroup: null } };
10931
11098
  }
11099
+ const cleared = {
11100
+ ...profile === null ? { profile: null } : {},
11101
+ ...modelGroup === null ? { modelGroup: null } : {}
11102
+ };
10932
11103
  const agentChanged = patch.targetAgentId !== undefined && patch.targetAgentId !== existing.targetAgentId;
10933
- if (agentChanged && existing.profile) {
10934
- const error = await taskProfileError({ profile: existing.profile, agentId });
11104
+ if (agentChanged) {
11105
+ const keptProfile = profile === null ? null : existing.profile;
11106
+ const keptGroup = modelGroup === null ? null : existing.modelGroup;
11107
+ const error = keptGroup ? await taskProfileError({ modelGroup: keptGroup, agentId }) : keptProfile ? await taskProfileError({ profile: keptProfile, agentId }) : null;
10935
11108
  if (error)
10936
11109
  return { error };
10937
11110
  }
10938
- return { fields: {} };
11111
+ return { fields: cleared };
10939
11112
  }
10940
11113
  function effectiveOverride(row) {
10941
11114
  if (!row)
@@ -10954,7 +11127,9 @@ var MODEL_PROFILE_CONFIG_KEY = "MODEL_PROFILE", unreadableAllowlists, TASK_HOLDS
10954
11127
  WHERE j.value = model_profiles.name AND o.name <> model_profiles.name)`, MAX_MODEL_PROFILE_FALLBACKS = 10;
10955
11128
  var init_model_profiles = __esm(() => {
10956
11129
  init_types5();
11130
+ init_model_group_resolution();
10957
11131
  init_model_profile_check();
11132
+ init_agents();
10958
11133
  init_runtime2();
10959
11134
  init_read();
10960
11135
  unreadableAllowlists = new WeakSet;
@@ -12581,7 +12756,7 @@ async function completeTask2(id, output, options) {
12581
12756
  });
12582
12757
  } catch {}
12583
12758
  getDbClient2().afterCommit(() => {
12584
- import("./event-bus-tvf2grf4.js").then(({ workflowEventBus }) => {
12759
+ import("./event-bus-pawddp92.js").then(({ workflowEventBus }) => {
12585
12760
  workflowEventBus.emit("task.completed", {
12586
12761
  taskId: id,
12587
12762
  previousStatus: oldTask.status,
@@ -12638,7 +12813,7 @@ async function failTask2(id, reason, opts = {}) {
12638
12813
  });
12639
12814
  } catch {}
12640
12815
  getDbClient2().afterCommit(() => {
12641
- import("./event-bus-tvf2grf4.js").then(({ workflowEventBus }) => {
12816
+ import("./event-bus-pawddp92.js").then(({ workflowEventBus }) => {
12642
12817
  workflowEventBus.emit("task.failed", {
12643
12818
  taskId: id,
12644
12819
  previousStatus: oldTask.status,
@@ -12721,7 +12896,7 @@ async function cancelTask2(id, reason, options = {}) {
12721
12896
  });
12722
12897
  } catch {}
12723
12898
  getDbClient2().afterCommit(() => {
12724
- import("./event-bus-tvf2grf4.js").then(({ workflowEventBus }) => {
12899
+ import("./event-bus-pawddp92.js").then(({ workflowEventBus }) => {
12725
12900
  workflowEventBus.emit("task.cancelled", {
12726
12901
  taskId: id,
12727
12902
  previousStatus: oldTask.status,
@@ -12734,7 +12909,7 @@ async function cancelTask2(id, reason, options = {}) {
12734
12909
  if (row.source === "schedule" && row.taskType === "deferred" && row.parentTaskId) {
12735
12910
  getDbClient2().afterCommit(async () => {
12736
12911
  try {
12737
- const { createWorkerTaskFollowUp } = await import("./worker-follow-up-fg48vk6d.js");
12912
+ const { createWorkerTaskFollowUp } = await import("./worker-follow-up-gbaz2ydz.js");
12738
12913
  await createWorkerTaskFollowUp({
12739
12914
  task: rowToAgentTask(row),
12740
12915
  status: "failed",
@@ -12783,7 +12958,7 @@ async function skipTask2(id, reason, opts = {}) {
12783
12958
  });
12784
12959
  } catch {}
12785
12960
  getDbClient2().afterCommit(() => {
12786
- import("./event-bus-tvf2grf4.js").then(({ workflowEventBus }) => {
12961
+ import("./event-bus-pawddp92.js").then(({ workflowEventBus }) => {
12787
12962
  workflowEventBus.emit("task.skipped", {
12788
12963
  taskId: id,
12789
12964
  failureReason: skipReason,
@@ -12842,7 +13017,7 @@ async function supersedeTask2(id, args) {
12842
13017
  });
12843
13018
  } catch {}
12844
13019
  getDbClient2().afterCommit(() => {
12845
- import("./event-bus-tvf2grf4.js").then(({ workflowEventBus }) => {
13020
+ import("./event-bus-pawddp92.js").then(({ workflowEventBus }) => {
12846
13021
  workflowEventBus.emit("task.superseded", {
12847
13022
  taskId: id,
12848
13023
  reason: args.reason,
@@ -13078,7 +13253,7 @@ async function updateTaskProgress2(id, progress) {
13078
13253
  });
13079
13254
  } catch {}
13080
13255
  getDbClient2().afterCommit(() => {
13081
- import("./event-bus-tvf2grf4.js").then(({ workflowEventBus }) => {
13256
+ import("./event-bus-pawddp92.js").then(({ workflowEventBus }) => {
13082
13257
  workflowEventBus.emit("task.progress", {
13083
13258
  taskId: id,
13084
13259
  progress: scrubbedProgress,
@@ -13665,7 +13840,7 @@ function emitRunFinished(runId, workflowId, status) {
13665
13840
  }
13666
13841
  function emitBusEventAfterCommit(event, payload) {
13667
13842
  getDbClient2().afterCommit(() => {
13668
- import("./event-bus-tvf2grf4.js").then(({ workflowEventBus }) => {
13843
+ import("./event-bus-pawddp92.js").then(({ workflowEventBus }) => {
13669
13844
  workflowEventBus.emit(event, payload);
13670
13845
  }).catch((err) => console.error(`[db] ${event} event not emitted:`, scrubSecrets(err instanceof Error ? err.message : String(err))));
13671
13846
  });
@@ -14325,6 +14500,16 @@ function booleanValidators(keys) {
14325
14500
  }
14326
14501
  ]));
14327
14502
  }
14503
+ function scheduleIdsValidator(key) {
14504
+ const message = `Invalid ${key} (must be comma-separated schedule UUIDs)`;
14505
+ return {
14506
+ [key]: (value) => {
14507
+ if (typeof value !== "string")
14508
+ return message;
14509
+ return parseFollowUpGateScheduleIds(value).every(isFollowUpGateScheduleId) ? null : message;
14510
+ }
14511
+ };
14512
+ }
14328
14513
  function enumValidator(key, options) {
14329
14514
  const listed = options.filter(Boolean).join(", ");
14330
14515
  const message = `Invalid ${key} value (must be one of: ${listed}${options.includes("") ? ", or empty" : ""})`;
@@ -14514,7 +14699,8 @@ var init_swarm_config_guard = __esm(() => {
14514
14699
  "NODE_PATH",
14515
14700
  "BUN_OPTIONS",
14516
14701
  "GCONV_PATH",
14517
- "GLIBC_TUNABLES"
14702
+ "GLIBC_TUNABLES",
14703
+ "CLAUDE_BINARY"
14518
14704
  ]);
14519
14705
  API_PROCESS_CONTROL_ENV_PREFIXES = ["LD_", "DYLD_", "BASH_", "BUN_INSPECT"];
14520
14706
  API_ONLY_CONFIG_KEYS = new Set([
@@ -14652,13 +14838,9 @@ var init_swarm_config_guard = __esm(() => {
14652
14838
  ...enumValidator("MODEL_WINDOW_EXHAUSTED_POLICY", ["fail", "fallback"]),
14653
14839
  ...enumValidator("CREDENTIAL_SELECTION_STRATEGY", [...CREDENTIAL_SELECTION_STRATEGIES]),
14654
14840
  ...enumValidator("HEARTBEAT_CHECKLIST_GATE_MODE", ["shadow", "enforce"]),
14655
- ...enumValidator("FOLLOW_UP_GATE_MODE", ["off", "shadow"]),
14656
- FOLLOW_UP_GATE_SCHEDULE_IDS: (value) => {
14657
- const message = "Invalid FOLLOW_UP_GATE_SCHEDULE_IDS (must be comma-separated schedule UUIDs)";
14658
- if (typeof value !== "string")
14659
- return message;
14660
- return parseFollowUpGateScheduleIds(value).every(isFollowUpGateScheduleId) ? null : message;
14661
- },
14841
+ ...enumValidator("FOLLOW_UP_GATE_MODE", ["off", "shadow", "enforce"]),
14842
+ ...scheduleIdsValidator("FOLLOW_UP_GATE_SCHEDULE_IDS"),
14843
+ ...scheduleIdsValidator("FOLLOW_UP_GATE_ENFORCE_SCHEDULE_IDS"),
14662
14844
  ...enumValidator("SYSTEM_ONE_DEFAULT_PROVIDER", [...SYSTEM_ONE_DEFAULT_PROVIDER_OPTIONS]),
14663
14845
  ...enumValidator("SYSTEM_ONE_EXTRACT_DEFAULT_PROVIDER", [
14664
14846
  ...SYSTEM_ONE_EXTRACT_DEFAULT_PROVIDER_OPTIONS
@@ -14720,6 +14902,7 @@ var init_swarm_config_guard = __esm(() => {
14720
14902
  "CHAT_SDK_ENABLED",
14721
14903
  "SLACK_RENDER_V2",
14722
14904
  "SLACK_RENDER_V2_TASK_TREE_ENABLED",
14905
+ "SLACK_REPLY_FOOTER_ENABLED",
14723
14906
  "SLACK_RENDER_V2_DELEGATION",
14724
14907
  "SLACK_BLOCK_EXTERNAL_CHANNELS",
14725
14908
  "GITHUB_DISABLE",
@@ -15650,7 +15833,7 @@ var sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
15650
15833
  var init_sleep = () => {};
15651
15834
 
15652
15835
  // node_modules/openai/version.mjs
15653
- var VERSION = "6.40.0";
15836
+ var VERSION = "6.49.0";
15654
15837
  var init_version = () => {};
15655
15838
 
15656
15839
  // node_modules/openai/internal/detect-platform.mjs
@@ -16338,7 +16521,7 @@ var levelNumbers, parseLogLevel = (maybeLevel, sourceName, client) => {
16338
16521
  if (details.headers) {
16339
16522
  details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [
16340
16523
  name,
16341
- name.toLowerCase() === "authorization" || name.toLowerCase() === "api-key" || name.toLowerCase() === "x-api-key" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value
16524
+ name.toLowerCase() === "authorization" || name.toLowerCase() === "api-key" || name.toLowerCase() === "x-api-key" || name.toLowerCase() === "x-amz-security-token" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value
16342
16525
  ]));
16343
16526
  }
16344
16527
  if ("retryOfRequestLogID" in details) {
@@ -16540,14 +16723,45 @@ var init_streaming = __esm(() => {
16540
16723
  let consumed = false;
16541
16724
  async function* iterLines() {
16542
16725
  const lineDecoder = new LineDecoder;
16543
- const iter = ReadableStreamToAsyncIterable(readableStream);
16544
- for await (const chunk of iter) {
16545
- for (const line of lineDecoder.decode(chunk)) {
16726
+ const reader = readableStream.getReader();
16727
+ let closed = false;
16728
+ let cancelPromise;
16729
+ const cancel = () => {
16730
+ cancelPromise ?? (cancelPromise = reader.cancel());
16731
+ cancelPromise.catch(() => {});
16732
+ };
16733
+ controller.signal.addEventListener("abort", cancel, { once: true });
16734
+ try {
16735
+ if (controller.signal.aborted) {
16736
+ cancel();
16737
+ return;
16738
+ }
16739
+ while (true) {
16740
+ const { value: chunk, done } = await reader.read();
16741
+ if (done) {
16742
+ closed = true;
16743
+ break;
16744
+ }
16745
+ if (controller.signal.aborted)
16746
+ return;
16747
+ for (const line of lineDecoder.decode(chunk)) {
16748
+ if (controller.signal.aborted)
16749
+ return;
16750
+ yield line;
16751
+ }
16752
+ }
16753
+ if (controller.signal.aborted)
16754
+ return;
16755
+ for (const line of lineDecoder.flush()) {
16756
+ if (controller.signal.aborted)
16757
+ return;
16546
16758
  yield line;
16547
16759
  }
16548
- }
16549
- for (const line of lineDecoder.flush()) {
16550
- yield line;
16760
+ } finally {
16761
+ controller.signal.removeEventListener("abort", cancel);
16762
+ if (!closed)
16763
+ cancel();
16764
+ reader.releaseLock();
16551
16765
  }
16552
16766
  }
16553
16767
  async function* iterator() {
@@ -16565,7 +16779,7 @@ var init_streaming = __esm(() => {
16565
16779
  }
16566
16780
  done = true;
16567
16781
  } catch (e) {
16568
- if (isAbortError(e))
16782
+ if (controller.signal.aborted || isAbortError(e))
16569
16783
  return;
16570
16784
  throw e;
16571
16785
  } finally {
@@ -16945,13 +17159,17 @@ class WorkloadIdentityAuth {
16945
17159
  throw APIError.generate(response.status, body, `Token exchange failed with status ${response.status}`, response.headers);
16946
17160
  }
16947
17161
  const tokenResponse = await response.json();
16948
- const expiresIn = tokenResponse.expires_in || 3600;
17162
+ if (typeof tokenResponse !== "object" || tokenResponse === null || !("access_token" in tokenResponse) || typeof tokenResponse.access_token !== "string" || tokenResponse.access_token.trim().length === 0) {
17163
+ throw new OpenAIError("Token exchange response missing 'access_token' field");
17164
+ }
17165
+ const accessToken = tokenResponse.access_token;
17166
+ const expiresIn = tokenResponse.expires_in ?? 3600;
16949
17167
  const expiresAt = Date.now() + expiresIn * 1000;
16950
17168
  this.cachedToken = {
16951
- token: tokenResponse.access_token,
17169
+ token: accessToken,
16952
17170
  expiresAt
16953
17171
  };
16954
- return tokenResponse.access_token;
17172
+ return accessToken;
16955
17173
  }
16956
17174
  isTokenExpired(cachedToken) {
16957
17175
  return Date.now() >= cachedToken.expiresAt;
@@ -16976,7 +17194,88 @@ var init_workload_identity_auth = __esm(() => {
16976
17194
  };
16977
17195
  });
16978
17196
 
17197
+ // node_modules/openai/internal/headers.mjs
17198
+ function* iterateHeaders(headers) {
17199
+ if (!headers)
17200
+ return;
17201
+ if (brand_privateNullableHeaders in headers) {
17202
+ const { values, nulls } = headers;
17203
+ yield* values.entries();
17204
+ for (const name of nulls) {
17205
+ yield [name, null];
17206
+ }
17207
+ return;
17208
+ }
17209
+ let shouldClear = false;
17210
+ let iter;
17211
+ if (headers instanceof Headers) {
17212
+ iter = headers.entries();
17213
+ } else if (isReadonlyArray(headers)) {
17214
+ iter = headers;
17215
+ } else {
17216
+ shouldClear = true;
17217
+ iter = Object.entries(headers ?? {});
17218
+ }
17219
+ for (let row of iter) {
17220
+ const name = row[0];
17221
+ if (typeof name !== "string")
17222
+ throw new TypeError("expected header name to be a string");
17223
+ const values = isReadonlyArray(row[1]) ? row[1] : [row[1]];
17224
+ let didClear = false;
17225
+ for (const value of values) {
17226
+ if (value === undefined)
17227
+ continue;
17228
+ if (shouldClear && !didClear) {
17229
+ didClear = true;
17230
+ yield [name, null];
17231
+ }
17232
+ yield [name, value];
17233
+ }
17234
+ }
17235
+ }
17236
+ var brand_privateNullableHeaders, httpTokenHeaderName, buildHeaders = (newHeaders) => {
17237
+ const targetHeaders = new Headers;
17238
+ const nullHeaders = new Set;
17239
+ for (const headers of newHeaders) {
17240
+ const seenHeaders = new Set;
17241
+ for (const [name, value] of iterateHeaders(headers)) {
17242
+ if (!httpTokenHeaderName.test(name)) {
17243
+ throw new TypeError(`Header name must be a valid HTTP token ["${name}"]`);
17244
+ }
17245
+ const lowerName = name.toLowerCase();
17246
+ if (!seenHeaders.has(lowerName)) {
17247
+ targetHeaders.delete(lowerName);
17248
+ seenHeaders.add(lowerName);
17249
+ }
17250
+ if (value === null) {
17251
+ targetHeaders.delete(lowerName);
17252
+ nullHeaders.add(lowerName);
17253
+ } else {
17254
+ targetHeaders.append(lowerName, value);
17255
+ nullHeaders.delete(lowerName);
17256
+ }
17257
+ }
17258
+ }
17259
+ return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders };
17260
+ };
17261
+ var init_headers = __esm(() => {
17262
+ init_values();
17263
+ brand_privateNullableHeaders = /* @__PURE__ */ Symbol("brand.privateNullableHeaders");
17264
+ httpTokenHeaderName = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
17265
+ });
17266
+
16979
17267
  // node_modules/openai/internal/uploads.mjs
17268
+ function toStreamingFile(data, name, options) {
17269
+ if (!name) {
17270
+ throw new TypeError("toStreamingFile requires a non-empty file name");
17271
+ }
17272
+ return {
17273
+ [brand_privateStreamingFile]: true,
17274
+ data,
17275
+ name,
17276
+ ...options?.type ? { type: options.type } : {}
17277
+ };
17278
+ }
16980
17279
  function makeFile(fileBits, fileName, options) {
16981
17280
  checkFileSupport();
16982
17281
  return new File(fileBits, fileName ?? "unknown_file", options);
@@ -17004,7 +17303,108 @@ function supportsFormData(fetchObject) {
17004
17303
  supportsFormDataMap.set(fetch2, promise);
17005
17304
  return promise;
17006
17305
  }
17007
- var checkFileSupport = () => {
17306
+ async function* iterateMultipartBody(body, boundary) {
17307
+ for await (const { key, value } of iterateFormEntries(body)) {
17308
+ yield encodeUTF8(`--${boundary}\r
17309
+ `);
17310
+ if (isUploadable(value)) {
17311
+ const filename = getStreamingFileName(value);
17312
+ const type = getStreamingFileType(value);
17313
+ yield encodeUTF8(`Content-Disposition: form-data; name="${escapeHeaderValue(key)}"; filename="${escapeHeaderValue(filename)}"\r
17314
+ ` + `Content-Type: ${type}\r
17315
+ \r
17316
+ `);
17317
+ yield* iterateBytes(getStreamingFileData(value));
17318
+ } else {
17319
+ yield encodeUTF8(`Content-Disposition: form-data; name="${escapeHeaderValue(key)}"\r
17320
+ \r
17321
+ ${String(value)}`);
17322
+ }
17323
+ yield encodeUTF8(`\r
17324
+ `);
17325
+ }
17326
+ yield encodeUTF8(`--${boundary}--\r
17327
+ `);
17328
+ }
17329
+ async function* iterateFormEntries(body) {
17330
+ if (!body || typeof body !== "object")
17331
+ return;
17332
+ for (const [key, value] of Object.entries(body)) {
17333
+ yield* iterateFormValue(key, value);
17334
+ }
17335
+ }
17336
+ async function* iterateFormValue(key, value) {
17337
+ if (value === undefined)
17338
+ return;
17339
+ if (value == null) {
17340
+ throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
17341
+ }
17342
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || isUploadable(value)) {
17343
+ yield { key, value };
17344
+ } else if (Array.isArray(value)) {
17345
+ for (const entry of value) {
17346
+ yield* iterateFormValue(key + "[]", entry);
17347
+ }
17348
+ } else if (typeof value === "object") {
17349
+ for (const [name, prop] of Object.entries(value)) {
17350
+ yield* iterateFormValue(`${key}[${name}]`, prop);
17351
+ }
17352
+ } else {
17353
+ throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
17354
+ }
17355
+ }
17356
+ function getStreamingFileName(value) {
17357
+ return isStreamingFile(value) ? value.name : getName(value) ?? "unknown_file";
17358
+ }
17359
+ function getStreamingFileType(value) {
17360
+ if (isStreamingFile(value))
17361
+ return value.type || "application/octet-stream";
17362
+ if (isNamedBlob(value) && value.type)
17363
+ return value.type;
17364
+ if (value instanceof Response)
17365
+ return value.headers.get("content-type") || "application/octet-stream";
17366
+ return "application/octet-stream";
17367
+ }
17368
+ function getStreamingFileData(value) {
17369
+ if (isStreamingFile(value))
17370
+ return value.data;
17371
+ return value;
17372
+ }
17373
+ async function* iterateBytes(value) {
17374
+ if (typeof value === "string") {
17375
+ yield encodeUTF8(value);
17376
+ } else if (ArrayBuffer.isView(value)) {
17377
+ yield new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
17378
+ } else if (value instanceof ArrayBuffer) {
17379
+ yield new Uint8Array(value);
17380
+ } else if (value instanceof Response) {
17381
+ if (value.body) {
17382
+ yield* iterateBytes(value.body);
17383
+ } else {
17384
+ yield* iterateBytes(await value.blob());
17385
+ }
17386
+ } else if (value instanceof Blob) {
17387
+ if (typeof value.stream === "function") {
17388
+ yield* iterateBytes(value.stream());
17389
+ } else {
17390
+ yield new Uint8Array(await value.arrayBuffer());
17391
+ }
17392
+ } else if (isReadableStream(value)) {
17393
+ for await (const chunk of ReadableStreamToAsyncIterable(value)) {
17394
+ yield* iterateBytes(chunk);
17395
+ }
17396
+ } else if (isAsyncIterable(value)) {
17397
+ for await (const chunk of value) {
17398
+ yield* iterateBytes(chunk);
17399
+ }
17400
+ } else {
17401
+ throw new TypeError(`Invalid streaming file chunk: ${String(value)}`);
17402
+ }
17403
+ }
17404
+ function escapeHeaderValue(value) {
17405
+ return value.replace(/["\\\r\n]/g, (character) => encodeURIComponent(character));
17406
+ }
17407
+ var brand_privateStreamingFile, checkFileSupport = () => {
17008
17408
  if (typeof File === "undefined") {
17009
17409
  const { process: process2 } = globalThis;
17010
17410
  const isOldNode = typeof process2?.versions?.node === "string" && parseInt(process2.versions.node.split(".")) < 20;
@@ -17013,8 +17413,14 @@ var checkFileSupport = () => {
17013
17413
  }, isAsyncIterable = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function", maybeMultipartFormRequestOptions = async (opts, fetch2) => {
17014
17414
  if (!hasUploadableValue(opts.body))
17015
17415
  return opts;
17416
+ if (hasStreamingUploadableValue(opts.body)) {
17417
+ return createStreamingFormRequestOptions(opts);
17418
+ }
17016
17419
  return { ...opts, body: await createForm(opts.body, fetch2) };
17017
17420
  }, multipartFormRequestOptions = async (opts, fetch2) => {
17421
+ if (hasStreamingUploadableValue(opts.body)) {
17422
+ return createStreamingFormRequestOptions(opts);
17423
+ }
17018
17424
  return { ...opts, body: await createForm(opts.body, fetch2) };
17019
17425
  }, supportsFormDataMap, createForm = async (body, fetch2) => {
17020
17426
  if (!await supportsFormData(fetch2)) {
@@ -17023,7 +17429,19 @@ var checkFileSupport = () => {
17023
17429
  const form = new FormData;
17024
17430
  await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));
17025
17431
  return form;
17026
- }, isNamedBlob = (value) => value instanceof Blob && ("name" in value), isUploadable = (value) => typeof value === "object" && value !== null && (value instanceof Response || isAsyncIterable(value) || isNamedBlob(value)), hasUploadableValue = (value) => {
17432
+ }, isNamedBlob = (value) => value instanceof Blob && ("name" in value), isReadableStream = (value) => typeof value === "object" && value !== null && ("getReader" in value) && typeof value.getReader === "function", isStreamingFile = (value) => typeof value === "object" && value !== null && (brand_privateStreamingFile in value), isUploadable = (value) => typeof value === "object" && value !== null && (value instanceof Response || isAsyncIterable(value) || isReadableStream(value) || isStreamingFile(value) || isNamedBlob(value)), hasStreamingUploadableValue = (value) => {
17433
+ if (isStreamingFile(value) || isAsyncIterable(value) || isReadableStream(value))
17434
+ return true;
17435
+ if (Array.isArray(value))
17436
+ return value.some(hasStreamingUploadableValue);
17437
+ if (value && typeof value === "object" && !isNamedBlob(value) && !(value instanceof Response)) {
17438
+ for (const k in value) {
17439
+ if (hasStreamingUploadableValue(value[k]))
17440
+ return true;
17441
+ }
17442
+ }
17443
+ return false;
17444
+ }, hasUploadableValue = (value) => {
17027
17445
  if (isUploadable(value))
17028
17446
  return true;
17029
17447
  if (Array.isArray(value))
@@ -17035,6 +17453,14 @@ var checkFileSupport = () => {
17035
17453
  }
17036
17454
  }
17037
17455
  return false;
17456
+ }, createStreamingFormRequestOptions = (opts) => {
17457
+ const boundary = `openai-${Math.random().toString(36).slice(2)}`;
17458
+ const body = ReadableStreamFrom(iterateMultipartBody(opts.body, boundary));
17459
+ return {
17460
+ ...opts,
17461
+ body,
17462
+ headers: buildHeaders([{ "content-type": `multipart/form-data; boundary=${boundary}` }, opts.headers])
17463
+ };
17038
17464
  }, addFormValue = async (form, key, value) => {
17039
17465
  if (value === undefined)
17040
17466
  return;
@@ -17058,7 +17484,10 @@ var checkFileSupport = () => {
17058
17484
  }
17059
17485
  };
17060
17486
  var init_uploads = __esm(() => {
17487
+ init_headers();
17061
17488
  init_shims();
17489
+ init_bytes();
17490
+ brand_privateStreamingFile = /* @__PURE__ */ Symbol("brand.privateStreamingFile");
17062
17491
  supportsFormDataMap = /* @__PURE__ */ new WeakMap;
17063
17492
  });
17064
17493
 
@@ -17117,6 +17546,7 @@ var init_to_file = __esm(() => {
17117
17546
 
17118
17547
  // node_modules/openai/core/uploads.mjs
17119
17548
  var init_uploads2 = __esm(() => {
17549
+ init_uploads();
17120
17550
  init_to_file();
17121
17551
  });
17122
17552
 
@@ -17334,6 +17764,7 @@ class EventStream {
17334
17764
  _EventStream_resolveEndPromise.set(this, () => {});
17335
17765
  _EventStream_rejectEndPromise.set(this, () => {});
17336
17766
  _EventStream_listeners.set(this, {});
17767
+ _EventStream_abortListeners.set(this, []);
17337
17768
  _EventStream_ended.set(this, false);
17338
17769
  _EventStream_errored.set(this, false);
17339
17770
  _EventStream_aborted.set(this, false);
@@ -17351,8 +17782,13 @@ class EventStream {
17351
17782
  }
17352
17783
  _run(executor) {
17353
17784
  setTimeout(() => {
17354
- executor().then(() => {
17355
- this._emitFinal();
17785
+ Promise.resolve().then(executor).then(() => {
17786
+ try {
17787
+ this._emitFinal();
17788
+ } catch (error) {
17789
+ __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_handleError).call(this, error);
17790
+ return;
17791
+ }
17356
17792
  this._emit("end");
17357
17793
  }, __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_handleError).bind(this));
17358
17794
  }, 0);
@@ -17375,6 +17811,17 @@ class EventStream {
17375
17811
  abort() {
17376
17812
  this.controller.abort();
17377
17813
  }
17814
+ _listenForAbort(signal) {
17815
+ if (!signal || this.ended)
17816
+ return;
17817
+ if (signal.aborted) {
17818
+ this.controller.abort();
17819
+ return;
17820
+ }
17821
+ const listener = () => this.controller.abort();
17822
+ signal.addEventListener("abort", listener, { once: true });
17823
+ __classPrivateFieldGet(this, _EventStream_abortListeners, "f").push({ signal, listener });
17824
+ }
17378
17825
  on(event, listener) {
17379
17826
  const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = []);
17380
17827
  listeners.push({ listener });
@@ -17402,6 +17849,90 @@ class EventStream {
17402
17849
  this.once(event, resolve);
17403
17850
  });
17404
17851
  }
17852
+ events(event) {
17853
+ const pushQueue = [];
17854
+ const readQueue = [];
17855
+ let ended = this.ended;
17856
+ let failure;
17857
+ let failureDelivered = false;
17858
+ const doneResult = () => ({ value: undefined, done: true });
17859
+ const finishReaders = () => {
17860
+ while (readQueue.length) {
17861
+ readQueue.shift().resolve(doneResult());
17862
+ }
17863
+ };
17864
+ const rejectReader = () => {
17865
+ if (!failure || failureDelivered || !readQueue.length)
17866
+ return;
17867
+ failureDelivered = true;
17868
+ readQueue.shift().reject(failure);
17869
+ };
17870
+ const cleanup = () => {
17871
+ this.off(event, onEvent);
17872
+ this.off("end", onEnd);
17873
+ if (event !== "error")
17874
+ this.off("error", onFailure);
17875
+ if (event !== "abort")
17876
+ this.off("abort", onFailure);
17877
+ };
17878
+ const onEvent = (...args) => {
17879
+ if (ended)
17880
+ return;
17881
+ const reader = readQueue.shift();
17882
+ if (reader) {
17883
+ reader.resolve({ value: args, done: false });
17884
+ } else {
17885
+ pushQueue.push(args);
17886
+ }
17887
+ };
17888
+ const onFailure = (error) => {
17889
+ failure = error;
17890
+ if (!pushQueue.length)
17891
+ rejectReader();
17892
+ };
17893
+ const onEnd = () => {
17894
+ ended = true;
17895
+ cleanup();
17896
+ if (!pushQueue.length) {
17897
+ rejectReader();
17898
+ finishReaders();
17899
+ }
17900
+ };
17901
+ if (!ended) {
17902
+ this.on(event, onEvent);
17903
+ this.on("end", onEnd);
17904
+ if (event !== "error")
17905
+ this.on("error", onFailure);
17906
+ if (event !== "abort")
17907
+ this.on("abort", onFailure);
17908
+ }
17909
+ return {
17910
+ next: () => {
17911
+ const value = pushQueue.shift();
17912
+ if (value)
17913
+ return Promise.resolve({ value, done: false });
17914
+ if (failure && !failureDelivered) {
17915
+ failureDelivered = true;
17916
+ return Promise.reject(failure);
17917
+ }
17918
+ if (ended)
17919
+ return Promise.resolve(doneResult());
17920
+ return new Promise((resolve, reject) => {
17921
+ readQueue.push({ resolve, reject });
17922
+ });
17923
+ },
17924
+ return: () => {
17925
+ ended = true;
17926
+ pushQueue.length = 0;
17927
+ cleanup();
17928
+ finishReaders();
17929
+ return Promise.resolve(doneResult());
17930
+ },
17931
+ [Symbol.asyncIterator]() {
17932
+ return this;
17933
+ }
17934
+ };
17935
+ }
17405
17936
  async done() {
17406
17937
  __classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f");
17407
17938
  await __classPrivateFieldGet(this, _EventStream_endPromise, "f");
@@ -17411,6 +17942,7 @@ class EventStream {
17411
17942
  return;
17412
17943
  }
17413
17944
  if (event === "end") {
17945
+ __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_removeAbortListeners).call(this);
17414
17946
  __classPrivateFieldSet(this, _EventStream_ended, true, "f");
17415
17947
  __classPrivateFieldGet(this, _EventStream_resolveEndPromise, "f").call(this);
17416
17948
  }
@@ -17441,11 +17973,15 @@ class EventStream {
17441
17973
  }
17442
17974
  _emitFinal() {}
17443
17975
  }
17444
- var _EventStream_instances, _EventStream_connectedPromise, _EventStream_resolveConnectedPromise, _EventStream_rejectConnectedPromise, _EventStream_endPromise, _EventStream_resolveEndPromise, _EventStream_rejectEndPromise, _EventStream_listeners, _EventStream_ended, _EventStream_errored, _EventStream_aborted, _EventStream_catchingPromiseCreated, _EventStream_handleError;
17976
+ var _EventStream_instances, _EventStream_connectedPromise, _EventStream_resolveConnectedPromise, _EventStream_rejectConnectedPromise, _EventStream_endPromise, _EventStream_resolveEndPromise, _EventStream_rejectEndPromise, _EventStream_listeners, _EventStream_abortListeners, _EventStream_ended, _EventStream_errored, _EventStream_aborted, _EventStream_catchingPromiseCreated, _EventStream_removeAbortListeners, _EventStream_handleError;
17445
17977
  var init_EventStream = __esm(() => {
17446
17978
  init_tslib();
17447
17979
  init_error2();
17448
- _EventStream_connectedPromise = new WeakMap, _EventStream_resolveConnectedPromise = new WeakMap, _EventStream_rejectConnectedPromise = new WeakMap, _EventStream_endPromise = new WeakMap, _EventStream_resolveEndPromise = new WeakMap, _EventStream_rejectEndPromise = new WeakMap, _EventStream_listeners = new WeakMap, _EventStream_ended = new WeakMap, _EventStream_errored = new WeakMap, _EventStream_aborted = new WeakMap, _EventStream_catchingPromiseCreated = new WeakMap, _EventStream_instances = new WeakSet, _EventStream_handleError = function _EventStream_handleError(error) {
17980
+ _EventStream_connectedPromise = new WeakMap, _EventStream_resolveConnectedPromise = new WeakMap, _EventStream_rejectConnectedPromise = new WeakMap, _EventStream_endPromise = new WeakMap, _EventStream_resolveEndPromise = new WeakMap, _EventStream_rejectEndPromise = new WeakMap, _EventStream_listeners = new WeakMap, _EventStream_abortListeners = new WeakMap, _EventStream_ended = new WeakMap, _EventStream_errored = new WeakMap, _EventStream_aborted = new WeakMap, _EventStream_catchingPromiseCreated = new WeakMap, _EventStream_instances = new WeakSet, _EventStream_removeAbortListeners = function _EventStream_removeAbortListeners() {
17981
+ for (const { signal, listener } of __classPrivateFieldGet(this, _EventStream_abortListeners, "f").splice(0)) {
17982
+ signal.removeEventListener("abort", listener);
17983
+ }
17984
+ }, _EventStream_handleError = function _EventStream_handleError(error) {
17449
17985
  __classPrivateFieldSet(this, _EventStream_errored, true, "f");
17450
17986
  if (error instanceof Error && error.name === "AbortError") {
17451
17987
  error = new APIUserAbortError;
@@ -17473,10 +18009,58 @@ function isRunnableFunctionWithParse(fn) {
17473
18009
  var init_RunnableFunction = () => {};
17474
18010
 
17475
18011
  // node_modules/openai/lib/AbstractChatCompletionRunner.mjs
18012
+ function normalizeToolCallIds(chatCompletion) {
18013
+ for (const choice of chatCompletion.choices) {
18014
+ for (const toolCall of choice.message.tool_calls ?? []) {
18015
+ if (!toolCall.id) {
18016
+ toolCall.id = `call_${uuid4()}`;
18017
+ }
18018
+ }
18019
+ }
18020
+ }
18021
+ function toRequestMessage(message) {
18022
+ if (!isAssistantMessage(message))
18023
+ return message;
18024
+ const requestMessage = { role: "assistant" };
18025
+ if (message.audio != null)
18026
+ requestMessage.audio = { id: message.audio.id };
18027
+ if (message.content !== undefined)
18028
+ requestMessage.content = message.content;
18029
+ if (message.function_call != null)
18030
+ requestMessage.function_call = message.function_call;
18031
+ if (message.name !== undefined)
18032
+ requestMessage.name = message.name;
18033
+ if (message.refusal != null)
18034
+ requestMessage.refusal = message.refusal;
18035
+ if (message.tool_calls !== undefined) {
18036
+ requestMessage.tool_calls = message.tool_calls.map((toolCall) => {
18037
+ if (toolCall.type === "custom") {
18038
+ return {
18039
+ id: toolCall.id,
18040
+ type: toolCall.type,
18041
+ custom: {
18042
+ input: toolCall.custom.input,
18043
+ name: toolCall.custom.name
18044
+ }
18045
+ };
18046
+ }
18047
+ return {
18048
+ id: toolCall.id,
18049
+ type: toolCall.type,
18050
+ function: {
18051
+ arguments: toolCall.function.arguments,
18052
+ name: toolCall.function.name
18053
+ }
18054
+ };
18055
+ });
18056
+ }
18057
+ return requestMessage;
18058
+ }
17476
18059
  var _AbstractChatCompletionRunner_instances, _AbstractChatCompletionRunner_getFinalContent, _AbstractChatCompletionRunner_getFinalMessage, _AbstractChatCompletionRunner_getFinalFunctionToolCall, _AbstractChatCompletionRunner_getFinalFunctionToolCallResult, _AbstractChatCompletionRunner_calculateTotalUsage, _AbstractChatCompletionRunner_validateParams, _AbstractChatCompletionRunner_stringifyFunctionCallResult, DEFAULT_MAX_CHAT_COMPLETIONS = 10, AbstractChatCompletionRunner;
17477
18060
  var init_AbstractChatCompletionRunner = __esm(() => {
17478
18061
  init_tslib();
17479
18062
  init_error2();
18063
+ init_uuid();
17480
18064
  init_parser();
17481
18065
  init_chatCompletionUtils();
17482
18066
  init_EventStream();
@@ -17489,6 +18073,7 @@ var init_AbstractChatCompletionRunner = __esm(() => {
17489
18073
  this.messages = [];
17490
18074
  }
17491
18075
  _addChatCompletion(chatCompletion) {
18076
+ normalizeToolCallIds(chatCompletion);
17492
18077
  this._chatCompletions.push(chatCompletion);
17493
18078
  this._emit("chatCompletion", chatCompletion);
17494
18079
  const message = chatCompletion.choices[0]?.message;
@@ -17564,12 +18149,7 @@ var init_AbstractChatCompletionRunner = __esm(() => {
17564
18149
  }
17565
18150
  }
17566
18151
  async _createChatCompletion(client, params, options) {
17567
- const signal = options?.signal;
17568
- if (signal) {
17569
- if (signal.aborted)
17570
- this.controller.abort();
17571
- signal.addEventListener("abort", () => this.controller.abort());
17572
- }
18152
+ this._listenForAbort(options?.signal);
17573
18153
  __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params);
17574
18154
  const chatCompletion = await client.chat.completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal });
17575
18155
  this._connected();
@@ -17581,11 +18161,12 @@ var init_AbstractChatCompletionRunner = __esm(() => {
17581
18161
  }
17582
18162
  return await this._createChatCompletion(client, params, options);
17583
18163
  }
17584
- async _runTools(client, params, options) {
18164
+ async _runTools(client, params, runner, options) {
17585
18165
  const role = "tool";
17586
- const { tool_choice = "auto", stream, ...restParams } = params;
18166
+ const { tool_choice = "auto", stream, toolContext: inputToolContext, ...restParams } = params;
18167
+ const toolContext = inputToolContext;
17587
18168
  const singleFunctionToCall = typeof tool_choice !== "string" && tool_choice.type === "function" && tool_choice?.function?.name;
17588
- const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {};
18169
+ const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS, afterCompletion } = options || {};
17589
18170
  const inputTools = params.tools.map((tool) => {
17590
18171
  if (isAutoParsableTool(tool)) {
17591
18172
  if (!tool.$callback) {
@@ -17623,50 +18204,74 @@ var init_AbstractChatCompletionRunner = __esm(() => {
17623
18204
  for (const message of params.messages) {
17624
18205
  this._addMessage(message, false);
17625
18206
  }
18207
+ const runToolCall = async (toolCall) => {
18208
+ if (toolCall.type !== "function")
18209
+ return { message: undefined, functionCalled: false };
18210
+ const tool_call_id = toolCall.id;
18211
+ const { name, arguments: args } = toolCall.function;
18212
+ const fn = functionsByName[name];
18213
+ if (!fn) {
18214
+ const content = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys(functionsByName).map((name) => JSON.stringify(name)).join(", ")}. Please try again`;
18215
+ return { message: { role, tool_call_id, content }, functionCalled: false };
18216
+ }
18217
+ if (singleFunctionToCall && singleFunctionToCall !== name) {
18218
+ const content = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`;
18219
+ return { message: { role, tool_call_id, content }, functionCalled: false };
18220
+ }
18221
+ let rawContent;
18222
+ if (isRunnableFunctionWithParse(fn)) {
18223
+ let parsed;
18224
+ try {
18225
+ parsed = await fn.parse(args);
18226
+ } catch (error) {
18227
+ const content = error instanceof Error ? error.message : String(error);
18228
+ return { message: { role, tool_call_id, content }, functionCalled: false };
18229
+ }
18230
+ rawContent = await fn.function(parsed, runner, toolContext);
18231
+ } else {
18232
+ rawContent = await fn.function(args, runner, toolContext);
18233
+ }
18234
+ const content = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);
18235
+ return { message: { role, tool_call_id, content }, functionCalled: true };
18236
+ };
17626
18237
  for (let i = 0;i < maxChatCompletions; ++i) {
17627
18238
  const chatCompletion = await this._createChatCompletion(client, {
17628
18239
  ...restParams,
17629
18240
  tool_choice,
17630
18241
  tools,
17631
- messages: [...this.messages]
18242
+ messages: this.messages.map(toRequestMessage)
17632
18243
  }, options);
17633
18244
  const message = chatCompletion.choices[0]?.message;
17634
18245
  if (!message) {
17635
18246
  throw new OpenAIError(`missing message in ChatCompletion response`);
17636
18247
  }
17637
18248
  if (!message.tool_calls?.length) {
18249
+ await afterCompletion?.(chatCompletion, runner);
17638
18250
  return;
17639
18251
  }
17640
- for (const tool_call of message.tool_calls) {
17641
- if (tool_call.type !== "function")
17642
- continue;
17643
- const tool_call_id = tool_call.id;
17644
- const { name, arguments: args } = tool_call.function;
17645
- const fn = functionsByName[name];
17646
- if (!fn) {
17647
- const content = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys(functionsByName).map((name) => JSON.stringify(name)).join(", ")}. Please try again`;
17648
- this._addMessage({ role, tool_call_id, content });
17649
- continue;
17650
- } else if (singleFunctionToCall && singleFunctionToCall !== name) {
17651
- const content = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`;
17652
- this._addMessage({ role, tool_call_id, content });
17653
- continue;
18252
+ if (singleFunctionToCall || params.parallel_tool_calls === false) {
18253
+ for (const toolCall of message.tool_calls) {
18254
+ const result = await runToolCall(toolCall);
18255
+ if (result.message)
18256
+ this._addMessage(result.message);
18257
+ if (singleFunctionToCall && result.functionCalled) {
18258
+ await afterCompletion?.(chatCompletion, runner);
18259
+ return;
18260
+ }
17654
18261
  }
17655
- let parsed;
17656
- try {
17657
- parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args;
17658
- } catch (error) {
17659
- const content = error instanceof Error ? error.message : String(error);
17660
- this._addMessage({ role, tool_call_id, content });
17661
- continue;
18262
+ } else {
18263
+ const results = await Promise.allSettled(message.tool_calls.map(runToolCall));
18264
+ for (const result of results) {
18265
+ if (result.status === "rejected")
18266
+ throw result.reason;
17662
18267
  }
17663
- const rawContent = await fn.function(parsed, this);
17664
- const content = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);
17665
- this._addMessage({ role, tool_call_id, content });
17666
- if (singleFunctionToCall) {
17667
- return;
18268
+ for (const result of results) {
18269
+ if (result.status === "fulfilled" && result.value.message) {
18270
+ this._addMessage(result.value.message);
18271
+ }
17668
18272
  }
17669
18273
  }
18274
+ await afterCompletion?.(chatCompletion, runner);
17670
18275
  }
17671
18276
  return;
17672
18277
  }
@@ -17691,7 +18296,12 @@ var init_AbstractChatCompletionRunner = __esm(() => {
17691
18296
  for (let i = this.messages.length - 1;i >= 0; i--) {
17692
18297
  const message = this.messages[i];
17693
18298
  if (isAssistantMessage(message) && message?.tool_calls?.length) {
17694
- return message.tool_calls.filter((x) => x.type === "function").at(-1)?.function;
18299
+ for (let j = message.tool_calls.length - 1;j >= 0; j--) {
18300
+ const toolCall = message.tool_calls[j];
18301
+ if (toolCall?.type === "function") {
18302
+ return toolCall.function;
18303
+ }
18304
+ }
17695
18305
  }
17696
18306
  }
17697
18307
  return;
@@ -17738,7 +18348,7 @@ var init_ChatCompletionRunner = __esm(() => {
17738
18348
  ...options,
17739
18349
  headers: { ...options?.headers, "X-Stainless-Helper-Method": "runTools" }
17740
18350
  };
17741
- runner._run(() => runner._runTools(client, params, opts));
18351
+ runner._run(() => runner._runTools(client, params, runner, opts));
17742
18352
  return runner;
17743
18353
  }
17744
18354
  _addMessage(message, emit = true) {
@@ -17960,16 +18570,41 @@ var init_streaming2 = __esm(() => {
17960
18570
  });
17961
18571
 
17962
18572
  // node_modules/openai/lib/ChatCompletionStream.mjs
17963
- function finalizeChatCompletion(snapshot, params) {
18573
+ function makeChatCompletionReadableStreamMessageChunk(chunk, message, toolCallIds) {
18574
+ const payload = {
18575
+ type: "message",
18576
+ message,
18577
+ ...toolCallIds ? { tool_call_ids: toolCallIds } : {}
18578
+ };
18579
+ return {
18580
+ id: chunk.id,
18581
+ choices: [],
18582
+ created: chunk.created,
18583
+ model: chunk.model,
18584
+ object: `${CHAT_COMPLETION_READABLE_STREAM_MESSAGE_PREFIX}${JSON.stringify(payload)}`
18585
+ };
18586
+ }
18587
+ function isChatCompletionReadableStreamMessage(item) {
18588
+ return "type" in item && item.type === "message" && "message" in item || "object" in item && typeof item.object === "string" && item.object.startsWith(CHAT_COMPLETION_READABLE_STREAM_MESSAGE_PREFIX);
18589
+ }
18590
+ function getChatCompletionReadableStreamMessage(item) {
18591
+ if ("type" in item) {
18592
+ return item;
18593
+ }
18594
+ return JSON.parse(item.object.slice(CHAT_COMPLETION_READABLE_STREAM_MESSAGE_PREFIX.length));
18595
+ }
18596
+ function finalizeChatCompletion(snapshot, params, audioDoneChoiceIndexes) {
17964
18597
  const { id, choices, created, model, system_fingerprint, ...rest } = snapshot;
17965
18598
  const completion = {
17966
18599
  ...rest,
17967
18600
  id,
17968
18601
  choices: choices.map(({ message, finish_reason, index, logprobs, ...choiceRest }) => {
17969
- if (!finish_reason) {
18602
+ const { content = null, function_call, tool_calls, audio, ...messageRest } = message;
18603
+ const finishReason = finish_reason ?? (audioDoneChoiceIndexes.has(index) && isCompleteAudio(audio) ? "stop" : null);
18604
+ if (!finishReason) {
17970
18605
  throw new OpenAIError(`missing finish_reason for choice ${index}`);
17971
18606
  }
17972
- const { content = null, function_call, tool_calls, ...messageRest } = message;
18607
+ const audioResponse = audio ? { audio } : {};
17973
18608
  const role = message.role;
17974
18609
  if (!role) {
17975
18610
  throw new OpenAIError(`missing role for choice ${index}`);
@@ -17985,12 +18620,13 @@ function finalizeChatCompletion(snapshot, params) {
17985
18620
  return {
17986
18621
  ...choiceRest,
17987
18622
  message: {
18623
+ ...audioResponse,
17988
18624
  content,
17989
18625
  function_call: { arguments: args, name },
17990
18626
  role,
17991
18627
  refusal: message.refusal ?? null
17992
18628
  },
17993
- finish_reason,
18629
+ finish_reason: finishReason,
17994
18630
  index,
17995
18631
  logprobs
17996
18632
  };
@@ -17999,20 +18635,17 @@ function finalizeChatCompletion(snapshot, params) {
17999
18635
  return {
18000
18636
  ...choiceRest,
18001
18637
  index,
18002
- finish_reason,
18638
+ finish_reason: finishReason,
18003
18639
  logprobs,
18004
18640
  message: {
18005
18641
  ...messageRest,
18642
+ ...audioResponse,
18006
18643
  role,
18007
18644
  content,
18008
18645
  refusal: message.refusal ?? null,
18009
18646
  tool_calls: tool_calls.map((tool_call, i) => {
18010
18647
  const { function: fn, type, id, ...toolRest } = tool_call;
18011
18648
  const { arguments: args, name, ...fnRest } = fn || {};
18012
- if (id == null) {
18013
- throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].id
18014
- ${str2(snapshot)}`);
18015
- }
18016
18649
  if (type == null) {
18017
18650
  throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].type
18018
18651
  ${str2(snapshot)}`);
@@ -18025,15 +18658,20 @@ ${str2(snapshot)}`);
18025
18658
  throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.arguments
18026
18659
  ${str2(snapshot)}`);
18027
18660
  }
18028
- return { ...toolRest, id, type, function: { ...fnRest, name, arguments: args } };
18661
+ return {
18662
+ ...toolRest,
18663
+ id: id || `call_${uuid4()}`,
18664
+ type,
18665
+ function: { ...fnRest, name, arguments: args }
18666
+ };
18029
18667
  })
18030
18668
  }
18031
18669
  };
18032
18670
  }
18033
18671
  return {
18034
18672
  ...choiceRest,
18035
- message: { ...messageRest, content, role, refusal: message.refusal ?? null },
18036
- finish_reason,
18673
+ message: { ...messageRest, ...audioResponse, content, role, refusal: message.refusal ?? null },
18674
+ finish_reason: finishReason,
18037
18675
  index,
18038
18676
  logprobs
18039
18677
  };
@@ -18045,6 +18683,9 @@ ${str2(snapshot)}`);
18045
18683
  };
18046
18684
  return maybeParseChatCompletion(completion, params);
18047
18685
  }
18686
+ function isCompleteAudio(audio) {
18687
+ return audio?.id != null && audio.data != null && audio.transcript != null && audio.expires_at != null;
18688
+ }
18048
18689
  function str2(x) {
18049
18690
  return JSON.stringify(x);
18050
18691
  }
@@ -18052,11 +18693,12 @@ function assertIsEmpty(obj) {
18052
18693
  return;
18053
18694
  }
18054
18695
  function assertNever(_x) {}
18055
- var _ChatCompletionStream_instances, _ChatCompletionStream_params, _ChatCompletionStream_choiceEventStates, _ChatCompletionStream_currentChatCompletionSnapshot, _ChatCompletionStream_beginRequest, _ChatCompletionStream_getChoiceEventState, _ChatCompletionStream_addChunk, _ChatCompletionStream_emitToolCallDoneEvent, _ChatCompletionStream_emitContentDoneEvents, _ChatCompletionStream_endRequest, _ChatCompletionStream_getAutoParseableResponseFormat, _ChatCompletionStream_accumulateChatCompletion, ChatCompletionStream;
18696
+ var _ChatCompletionStream_instances, _ChatCompletionStream_params, _ChatCompletionStream_audioDoneChoiceIndexes, _ChatCompletionStream_choiceEventStates, _ChatCompletionStream_currentChatCompletionSnapshot, _ChatCompletionStream_beginRequest, _ChatCompletionStream_getChoiceEventState, _ChatCompletionStream_addChunk, _ChatCompletionStream_emitToolCallDoneEvent, _ChatCompletionStream_emitContentDoneEvents, _ChatCompletionStream_endRequest, _ChatCompletionStream_getAutoParseableResponseFormat, _ChatCompletionStream_accumulateChatCompletion, CHAT_COMPLETION_READABLE_STREAM_MESSAGE_PREFIX = "chat.completion.chunk.message:", ChatCompletionStream;
18056
18697
  var init_ChatCompletionStream = __esm(() => {
18057
18698
  init_tslib();
18058
18699
  init_parser2();
18059
18700
  init_error2();
18701
+ init_uuid();
18060
18702
  init_parser();
18061
18703
  init_streaming2();
18062
18704
  init_AbstractChatCompletionRunner();
@@ -18065,9 +18707,11 @@ var init_ChatCompletionStream = __esm(() => {
18065
18707
  super();
18066
18708
  _ChatCompletionStream_instances.add(this);
18067
18709
  _ChatCompletionStream_params.set(this, undefined);
18710
+ _ChatCompletionStream_audioDoneChoiceIndexes.set(this, undefined);
18068
18711
  _ChatCompletionStream_choiceEventStates.set(this, undefined);
18069
18712
  _ChatCompletionStream_currentChatCompletionSnapshot.set(this, undefined);
18070
18713
  __classPrivateFieldSet(this, _ChatCompletionStream_params, params, "f");
18714
+ __classPrivateFieldSet(this, _ChatCompletionStream_audioDoneChoiceIndexes, new Set, "f");
18071
18715
  __classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f");
18072
18716
  }
18073
18717
  get currentChatCompletionSnapshot() {
@@ -18085,12 +18729,7 @@ var init_ChatCompletionStream = __esm(() => {
18085
18729
  }
18086
18730
  async _createChatCompletion(client, params, options) {
18087
18731
  super._createChatCompletion;
18088
- const signal = options?.signal;
18089
- if (signal) {
18090
- if (signal.aborted)
18091
- this.controller.abort();
18092
- signal.addEventListener("abort", () => this.controller.abort());
18093
- }
18732
+ this._listenForAbort(options?.signal);
18094
18733
  __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
18095
18734
  const stream = await client.chat.completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal });
18096
18735
  this._connected();
@@ -18103,31 +18742,52 @@ var init_ChatCompletionStream = __esm(() => {
18103
18742
  return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
18104
18743
  }
18105
18744
  async _fromReadableStream(readableStream, options) {
18106
- const signal = options?.signal;
18107
- if (signal) {
18108
- if (signal.aborted)
18109
- this.controller.abort();
18110
- signal.addEventListener("abort", () => this.controller.abort());
18111
- }
18745
+ this._listenForAbort(options?.signal);
18112
18746
  __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
18113
18747
  this._connected();
18114
18748
  const stream = Stream.fromReadableStream(readableStream, this.controller);
18115
18749
  let chatId;
18116
- for await (const chunk of stream) {
18117
- if (chatId && chatId !== chunk.id) {
18750
+ for await (const item of stream) {
18751
+ if (isChatCompletionReadableStreamMessage(item)) {
18752
+ const message = getChatCompletionReadableStreamMessage(item);
18753
+ if (__classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f")) {
18754
+ const toolCalls = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f").choices[0]?.message.tool_calls;
18755
+ for (const [index, id] of message.tool_call_ids?.entries() ?? []) {
18756
+ const toolCall = toolCalls?.[index];
18757
+ if (toolCall && id) {
18758
+ toolCall.id = id;
18759
+ }
18760
+ }
18761
+ this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
18762
+ chatId = undefined;
18763
+ }
18764
+ this._addMessage(message.message);
18765
+ continue;
18766
+ }
18767
+ const chunk = item;
18768
+ if (chatId && chunk.id && chatId !== chunk.id) {
18118
18769
  this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
18119
18770
  }
18120
18771
  __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
18121
- chatId = chunk.id;
18772
+ if (chunk.id)
18773
+ chatId = chunk.id;
18122
18774
  }
18123
18775
  if (stream.controller.signal?.aborted) {
18124
18776
  throw new APIUserAbortError;
18125
18777
  }
18126
- return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
18778
+ if (__classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f")) {
18779
+ return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
18780
+ }
18781
+ const lastChatCompletion = this._chatCompletions[this._chatCompletions.length - 1];
18782
+ if (lastChatCompletion) {
18783
+ return lastChatCompletion;
18784
+ }
18785
+ throw new OpenAIError(`request ended without sending any chunks`);
18127
18786
  }
18128
- [(_ChatCompletionStream_params = new WeakMap, _ChatCompletionStream_choiceEventStates = new WeakMap, _ChatCompletionStream_currentChatCompletionSnapshot = new WeakMap, _ChatCompletionStream_instances = new WeakSet, _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest2() {
18787
+ [(_ChatCompletionStream_params = new WeakMap, _ChatCompletionStream_audioDoneChoiceIndexes = new WeakMap, _ChatCompletionStream_choiceEventStates = new WeakMap, _ChatCompletionStream_currentChatCompletionSnapshot = new WeakMap, _ChatCompletionStream_instances = new WeakSet, _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest2() {
18129
18788
  if (this.ended)
18130
18789
  return;
18790
+ __classPrivateFieldSet(this, _ChatCompletionStream_audioDoneChoiceIndexes, new Set, "f");
18131
18791
  __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f");
18132
18792
  }, _ChatCompletionStream_getChoiceEventState = function _ChatCompletionStream_getChoiceEventState2(choice) {
18133
18793
  let state = __classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index];
@@ -18151,17 +18811,18 @@ var init_ChatCompletionStream = __esm(() => {
18151
18811
  this._emit("chunk", chunk, completion);
18152
18812
  for (const choice of chunk.choices) {
18153
18813
  const choiceSnapshot = completion.choices[choice.index];
18154
- if (choice.delta.content != null && choiceSnapshot.message?.role === "assistant" && choiceSnapshot.message?.content) {
18155
- this._emit("content", choice.delta.content, choiceSnapshot.message.content);
18814
+ const { delta } = choice;
18815
+ if (delta?.content != null && choiceSnapshot.message?.role === "assistant" && choiceSnapshot.message?.content) {
18816
+ this._emit("content", delta.content, choiceSnapshot.message.content);
18156
18817
  this._emit("content.delta", {
18157
- delta: choice.delta.content,
18818
+ delta: delta.content,
18158
18819
  snapshot: choiceSnapshot.message.content,
18159
18820
  parsed: choiceSnapshot.message.parsed
18160
18821
  });
18161
18822
  }
18162
- if (choice.delta.refusal != null && choiceSnapshot.message?.role === "assistant" && choiceSnapshot.message?.refusal) {
18823
+ if (delta?.refusal != null && choiceSnapshot.message?.role === "assistant" && choiceSnapshot.message?.refusal) {
18163
18824
  this._emit("refusal.delta", {
18164
- delta: choice.delta.refusal,
18825
+ delta: delta.refusal,
18165
18826
  snapshot: choiceSnapshot.message.refusal
18166
18827
  });
18167
18828
  }
@@ -18184,7 +18845,7 @@ var init_ChatCompletionStream = __esm(() => {
18184
18845
  __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);
18185
18846
  }
18186
18847
  }
18187
- for (const toolCall of choice.delta.tool_calls ?? []) {
18848
+ for (const toolCall of delta?.tool_calls ?? []) {
18188
18849
  if (state.current_tool_call_index !== toolCall.index) {
18189
18850
  __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
18190
18851
  if (state.current_tool_call_index != null) {
@@ -18193,7 +18854,7 @@ var init_ChatCompletionStream = __esm(() => {
18193
18854
  }
18194
18855
  state.current_tool_call_index = toolCall.index;
18195
18856
  }
18196
- for (const toolCallDelta of choice.delta.tool_calls ?? []) {
18857
+ for (const toolCallDelta of delta?.tool_calls ?? []) {
18197
18858
  const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallDelta.index];
18198
18859
  if (!toolCallSnapshot?.type) {
18199
18860
  continue;
@@ -18264,9 +18925,11 @@ var init_ChatCompletionStream = __esm(() => {
18264
18925
  if (!snapshot) {
18265
18926
  throw new OpenAIError(`request ended without sending any chunks`);
18266
18927
  }
18928
+ const audioDoneChoiceIndexes = __classPrivateFieldGet(this, _ChatCompletionStream_audioDoneChoiceIndexes, "f");
18929
+ __classPrivateFieldSet(this, _ChatCompletionStream_audioDoneChoiceIndexes, new Set, "f");
18267
18930
  __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f");
18268
18931
  __classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f");
18269
- return finalizeChatCompletion(snapshot, __classPrivateFieldGet(this, _ChatCompletionStream_params, "f"));
18932
+ return finalizeChatCompletion(snapshot, __classPrivateFieldGet(this, _ChatCompletionStream_params, "f"), audioDoneChoiceIndexes);
18270
18933
  }, _ChatCompletionStream_getAutoParseableResponseFormat = function _ChatCompletionStream_getAutoParseableResponseFormat2() {
18271
18934
  const responseFormat = __classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.response_format;
18272
18935
  if (isAutoParsableResponseFormat(responseFormat)) {
@@ -18274,7 +18937,7 @@ var init_ChatCompletionStream = __esm(() => {
18274
18937
  }
18275
18938
  return null;
18276
18939
  }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion2(chunk) {
18277
- var _a, _b, _c, _d;
18940
+ var _a, _b, _c, _d, _e;
18278
18941
  let snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
18279
18942
  const { choices, ...rest } = chunk;
18280
18943
  if (!snapshot) {
@@ -18282,7 +18945,7 @@ var init_ChatCompletionStream = __esm(() => {
18282
18945
  ...rest,
18283
18946
  choices: []
18284
18947
  }, "f");
18285
- } else {
18948
+ } else if (chunk.id) {
18286
18949
  Object.assign(snapshot, rest);
18287
18950
  }
18288
18951
  for (const { delta, finish_reason, index, logprobs = null, ...other } of chunk.choices) {
@@ -18321,14 +18984,30 @@ var init_ChatCompletionStream = __esm(() => {
18321
18984
  Object.assign(choice, other);
18322
18985
  if (!delta)
18323
18986
  continue;
18324
- const { content, refusal, function_call, role, tool_calls, ...rest } = delta;
18987
+ __classPrivateFieldGet(this, _ChatCompletionStream_audioDoneChoiceIndexes, "f").delete(index);
18988
+ const { audio, content, refusal, function_call, role, tool_calls, ...rest } = delta;
18325
18989
  assertIsEmpty(rest);
18326
18990
  Object.assign(choice.message, rest);
18991
+ if (audio?.expires_at != null && audio.id == null && audio.data == null && audio.transcript == null && content == null && refusal == null && function_call == null && role == null && tool_calls == null && Object.keys(rest).length === 0) {
18992
+ __classPrivateFieldGet(this, _ChatCompletionStream_audioDoneChoiceIndexes, "f").add(index);
18993
+ }
18327
18994
  if (refusal) {
18328
18995
  choice.message.refusal = (choice.message.refusal || "") + refusal;
18329
18996
  }
18330
18997
  if (role)
18331
18998
  choice.message.role = role;
18999
+ if (audio) {
19000
+ const audioSnapshot = (_c = choice.message).audio ?? (_c.audio = {});
19001
+ if (audio.id != null)
19002
+ audioSnapshot.id = audio.id;
19003
+ if (audio.data != null)
19004
+ audioSnapshot.data = (audioSnapshot.data ?? "") + audio.data;
19005
+ if (audio.transcript != null) {
19006
+ audioSnapshot.transcript = (audioSnapshot.transcript ?? "") + audio.transcript;
19007
+ }
19008
+ if (audio.expires_at != null)
19009
+ audioSnapshot.expires_at = audio.expires_at;
19010
+ }
18332
19011
  if (function_call) {
18333
19012
  if (!choice.message.function_call) {
18334
19013
  choice.message.function_call = function_call;
@@ -18336,7 +19015,7 @@ var init_ChatCompletionStream = __esm(() => {
18336
19015
  if (function_call.name)
18337
19016
  choice.message.function_call.name = function_call.name;
18338
19017
  if (function_call.arguments) {
18339
- (_c = choice.message.function_call).arguments ?? (_c.arguments = "");
19018
+ (_d = choice.message.function_call).arguments ?? (_d.arguments = "");
18340
19019
  choice.message.function_call.arguments += function_call.arguments;
18341
19020
  }
18342
19021
  }
@@ -18344,14 +19023,14 @@ var init_ChatCompletionStream = __esm(() => {
18344
19023
  if (content) {
18345
19024
  choice.message.content = (choice.message.content || "") + content;
18346
19025
  if (!choice.message.refusal && __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) {
18347
- choice.message.parsed = partialParse(choice.message.content);
19026
+ choice.message.parsed = choice.message.content.trim() ? partialParse(choice.message.content) : null;
18348
19027
  }
18349
19028
  }
18350
19029
  if (tool_calls) {
18351
19030
  if (!choice.message.tool_calls)
18352
19031
  choice.message.tool_calls = [];
18353
19032
  for (const { index, id, type, function: fn, ...rest } of tool_calls) {
18354
- const tool_call = (_d = choice.message.tool_calls)[index] ?? (_d[index] = {});
19033
+ const tool_call = (_e = choice.message.tool_calls)[index] ?? (_e[index] = {});
18355
19034
  Object.assign(tool_call, rest);
18356
19035
  if (id)
18357
19036
  tool_call.id = id;
@@ -18432,19 +19111,95 @@ var init_ChatCompletionStream = __esm(() => {
18432
19111
  var ChatCompletionStreamingRunner;
18433
19112
  var init_ChatCompletionStreamingRunner = __esm(() => {
18434
19113
  init_ChatCompletionStream();
19114
+ init_error2();
19115
+ init_streaming2();
19116
+ init_chatCompletionUtils();
18435
19117
  ChatCompletionStreamingRunner = class ChatCompletionStreamingRunner extends ChatCompletionStream {
18436
19118
  static fromReadableStream(stream) {
18437
19119
  const runner = new ChatCompletionStreamingRunner(null);
18438
19120
  runner._run(() => runner._fromReadableStream(stream));
18439
19121
  return runner;
18440
19122
  }
19123
+ toReadableStream() {
19124
+ const pushQueue = [];
19125
+ const readQueue = [];
19126
+ let done = false;
19127
+ let lastChunk;
19128
+ let toolCallIds;
19129
+ const pushEvent = (event) => {
19130
+ const reader = readQueue.shift();
19131
+ if (reader) {
19132
+ reader.resolve(event);
19133
+ } else {
19134
+ pushQueue.push(event);
19135
+ }
19136
+ };
19137
+ this.on("chunk", (chunk) => {
19138
+ lastChunk = chunk;
19139
+ pushEvent(chunk);
19140
+ });
19141
+ this.on("message", (message) => {
19142
+ if (isAssistantMessage(message)) {
19143
+ toolCallIds = message.tool_calls?.map((toolCall) => toolCall.id);
19144
+ return;
19145
+ }
19146
+ if (isToolMessage(message)) {
19147
+ if (!lastChunk) {
19148
+ throw new OpenAIError("cannot serialize a tool message before receiving any chunks");
19149
+ }
19150
+ pushEvent(makeChatCompletionReadableStreamMessageChunk(lastChunk, message, toolCallIds));
19151
+ }
19152
+ });
19153
+ this.on("end", () => {
19154
+ done = true;
19155
+ for (const reader of readQueue) {
19156
+ reader.resolve(undefined);
19157
+ }
19158
+ readQueue.length = 0;
19159
+ });
19160
+ this.on("abort", (err) => {
19161
+ done = true;
19162
+ for (const reader of readQueue) {
19163
+ reader.reject(err);
19164
+ }
19165
+ readQueue.length = 0;
19166
+ });
19167
+ this.on("error", (err) => {
19168
+ done = true;
19169
+ for (const reader of readQueue) {
19170
+ reader.reject(err);
19171
+ }
19172
+ readQueue.length = 0;
19173
+ });
19174
+ const iterator = () => ({
19175
+ next: async () => {
19176
+ if (!pushQueue.length) {
19177
+ if (done) {
19178
+ return { value: undefined, done: true };
19179
+ }
19180
+ return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((event) => event ? { value: event, done: false } : { value: undefined, done: true });
19181
+ }
19182
+ const event = pushQueue.shift();
19183
+ if (!event) {
19184
+ return { value: undefined, done: true };
19185
+ }
19186
+ return { value: event, done: false };
19187
+ },
19188
+ return: async () => {
19189
+ this.abort();
19190
+ return { value: undefined, done: true };
19191
+ }
19192
+ });
19193
+ const stream = new Stream(iterator, this.controller);
19194
+ return stream.toReadableStream();
19195
+ }
18441
19196
  static runTools(client, params, options) {
18442
19197
  const runner = new ChatCompletionStreamingRunner(params);
18443
19198
  const opts = {
18444
19199
  ...options,
18445
19200
  headers: { ...options?.headers, "X-Stainless-Helper-Method": "runTools" }
18446
19201
  };
18447
- runner._run(() => runner._runTools(client, params, opts));
19202
+ runner._run(() => runner._runTools(client, params, runner, opts));
18448
19203
  return runner;
18449
19204
  }
18450
19205
  };
@@ -18776,6 +19531,12 @@ var init_spend_alerts = __esm(() => {
18776
19531
  __security: { adminAPIKeyAuth: true }
18777
19532
  });
18778
19533
  }
19534
+ retrieve(alertID, options) {
19535
+ return this._client.get(path3`/organization/spend_alerts/${alertID}`, {
19536
+ ...options,
19537
+ __security: { adminAPIKeyAuth: true }
19538
+ });
19539
+ }
18779
19540
  update(alertID, body, options) {
18780
19541
  return this._client.post(path3`/organization/spend_alerts/${alertID}`, {
18781
19542
  body,
@@ -18795,6 +19556,33 @@ var init_spend_alerts = __esm(() => {
18795
19556
  };
18796
19557
  });
18797
19558
 
19559
+ // node_modules/openai/resources/admin/organization/spend-limit.mjs
19560
+ var SpendLimit;
19561
+ var init_spend_limit = __esm(() => {
19562
+ init_resource();
19563
+ SpendLimit = class SpendLimit extends APIResource {
19564
+ retrieve(options) {
19565
+ return this._client.get("/organization/spend_limit", {
19566
+ ...options,
19567
+ __security: { adminAPIKeyAuth: true }
19568
+ });
19569
+ }
19570
+ update(body, options) {
19571
+ return this._client.post("/organization/spend_limit", {
19572
+ body,
19573
+ ...options,
19574
+ __security: { adminAPIKeyAuth: true }
19575
+ });
19576
+ }
19577
+ delete(options) {
19578
+ return this._client.delete("/organization/spend_limit", {
19579
+ ...options,
19580
+ __security: { adminAPIKeyAuth: true }
19581
+ });
19582
+ }
19583
+ };
19584
+ });
19585
+
18798
19586
  // node_modules/openai/resources/admin/organization/usage.mjs
18799
19587
  var Usage;
18800
19588
  var init_usage = __esm(() => {
@@ -19187,69 +19975,69 @@ var init_roles3 = __esm(() => {
19187
19975
  };
19188
19976
  });
19189
19977
 
19190
- // node_modules/openai/resources/admin/organization/projects/service-accounts.mjs
19191
- var ServiceAccounts;
19192
- var init_service_accounts = __esm(() => {
19978
+ // node_modules/openai/resources/admin/organization/projects/spend-alerts.mjs
19979
+ var SpendAlerts2;
19980
+ var init_spend_alerts2 = __esm(() => {
19193
19981
  init_resource();
19194
19982
  init_pagination();
19195
19983
  init_path();
19196
- ServiceAccounts = class ServiceAccounts extends APIResource {
19984
+ SpendAlerts2 = class SpendAlerts2 extends APIResource {
19197
19985
  create(projectID, body, options) {
19198
- return this._client.post(path3`/organization/projects/${projectID}/service_accounts`, {
19986
+ return this._client.post(path3`/organization/projects/${projectID}/spend_alerts`, {
19199
19987
  body,
19200
19988
  ...options,
19201
19989
  __security: { adminAPIKeyAuth: true }
19202
19990
  });
19203
19991
  }
19204
- retrieve(serviceAccountID, params, options) {
19992
+ retrieve(alertID, params, options) {
19205
19993
  const { project_id } = params;
19206
- return this._client.get(path3`/organization/projects/${project_id}/service_accounts/${serviceAccountID}`, {
19994
+ return this._client.get(path3`/organization/projects/${project_id}/spend_alerts/${alertID}`, {
19207
19995
  ...options,
19208
19996
  __security: { adminAPIKeyAuth: true }
19209
19997
  });
19210
19998
  }
19211
- update(serviceAccountID, params, options) {
19999
+ update(alertID, params, options) {
19212
20000
  const { project_id, ...body } = params;
19213
- return this._client.post(path3`/organization/projects/${project_id}/service_accounts/${serviceAccountID}`, { body, ...options, __security: { adminAPIKeyAuth: true } });
20001
+ return this._client.post(path3`/organization/projects/${project_id}/spend_alerts/${alertID}`, {
20002
+ body,
20003
+ ...options,
20004
+ __security: { adminAPIKeyAuth: true }
20005
+ });
19214
20006
  }
19215
20007
  list(projectID, query = {}, options) {
19216
- return this._client.getAPIList(path3`/organization/projects/${projectID}/service_accounts`, ConversationCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
20008
+ return this._client.getAPIList(path3`/organization/projects/${projectID}/spend_alerts`, ConversationCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
19217
20009
  }
19218
- delete(serviceAccountID, params, options) {
20010
+ delete(alertID, params, options) {
19219
20011
  const { project_id } = params;
19220
- return this._client.delete(path3`/organization/projects/${project_id}/service_accounts/${serviceAccountID}`, { ...options, __security: { adminAPIKeyAuth: true } });
20012
+ return this._client.delete(path3`/organization/projects/${project_id}/spend_alerts/${alertID}`, {
20013
+ ...options,
20014
+ __security: { adminAPIKeyAuth: true }
20015
+ });
19221
20016
  }
19222
20017
  };
19223
20018
  });
19224
20019
 
19225
- // node_modules/openai/resources/admin/organization/projects/spend-alerts.mjs
19226
- var SpendAlerts2;
19227
- var init_spend_alerts2 = __esm(() => {
20020
+ // node_modules/openai/resources/admin/organization/projects/spend-limit.mjs
20021
+ var SpendLimit2;
20022
+ var init_spend_limit2 = __esm(() => {
19228
20023
  init_resource();
19229
- init_pagination();
19230
20024
  init_path();
19231
- SpendAlerts2 = class SpendAlerts2 extends APIResource {
19232
- create(projectID, body, options) {
19233
- return this._client.post(path3`/organization/projects/${projectID}/spend_alerts`, {
19234
- body,
20025
+ SpendLimit2 = class SpendLimit2 extends APIResource {
20026
+ retrieve(projectID, options) {
20027
+ return this._client.get(path3`/organization/projects/${projectID}/spend_limit`, {
19235
20028
  ...options,
19236
20029
  __security: { adminAPIKeyAuth: true }
19237
20030
  });
19238
20031
  }
19239
- update(alertID, params, options) {
19240
- const { project_id, ...body } = params;
19241
- return this._client.post(path3`/organization/projects/${project_id}/spend_alerts/${alertID}`, {
20032
+ update(projectID, body, options) {
20033
+ return this._client.post(path3`/organization/projects/${projectID}/spend_limit`, {
19242
20034
  body,
19243
20035
  ...options,
19244
20036
  __security: { adminAPIKeyAuth: true }
19245
20037
  });
19246
20038
  }
19247
- list(projectID, query = {}, options) {
19248
- return this._client.getAPIList(path3`/organization/projects/${projectID}/spend_alerts`, ConversationCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
19249
- }
19250
- delete(alertID, params, options) {
19251
- const { project_id } = params;
19252
- return this._client.delete(path3`/organization/projects/${project_id}/spend_alerts/${alertID}`, {
20039
+ delete(projectID, options) {
20040
+ return this._client.delete(path3`/organization/projects/${projectID}/spend_limit`, {
19253
20041
  ...options,
19254
20042
  __security: { adminAPIKeyAuth: true }
19255
20043
  });
@@ -19335,6 +20123,61 @@ var init_groups2 = __esm(() => {
19335
20123
  Groups2.Roles = Roles4;
19336
20124
  });
19337
20125
 
20126
+ // node_modules/openai/resources/admin/organization/projects/service-accounts/api-keys.mjs
20127
+ var APIKeys2;
20128
+ var init_api_keys3 = __esm(() => {
20129
+ init_resource();
20130
+ init_path();
20131
+ APIKeys2 = class APIKeys2 extends APIResource {
20132
+ create(serviceAccountID, params, options) {
20133
+ const { project_id, ...body } = params;
20134
+ return this._client.post(path3`/organization/projects/${project_id}/service_accounts/${serviceAccountID}/api_keys`, { body, ...options, __security: { adminAPIKeyAuth: true } });
20135
+ }
20136
+ };
20137
+ });
20138
+
20139
+ // node_modules/openai/resources/admin/organization/projects/service-accounts/service-accounts.mjs
20140
+ var ServiceAccounts;
20141
+ var init_service_accounts = __esm(() => {
20142
+ init_resource();
20143
+ init_api_keys3();
20144
+ init_api_keys3();
20145
+ init_pagination();
20146
+ init_path();
20147
+ ServiceAccounts = class ServiceAccounts extends APIResource {
20148
+ constructor() {
20149
+ super(...arguments);
20150
+ this.apiKeys = new APIKeys2(this._client);
20151
+ }
20152
+ create(projectID, body, options) {
20153
+ return this._client.post(path3`/organization/projects/${projectID}/service_accounts`, {
20154
+ body,
20155
+ ...options,
20156
+ __security: { adminAPIKeyAuth: true }
20157
+ });
20158
+ }
20159
+ retrieve(serviceAccountID, params, options) {
20160
+ const { project_id } = params;
20161
+ return this._client.get(path3`/organization/projects/${project_id}/service_accounts/${serviceAccountID}`, {
20162
+ ...options,
20163
+ __security: { adminAPIKeyAuth: true }
20164
+ });
20165
+ }
20166
+ update(serviceAccountID, params, options) {
20167
+ const { project_id, ...body } = params;
20168
+ return this._client.post(path3`/organization/projects/${project_id}/service_accounts/${serviceAccountID}`, { body, ...options, __security: { adminAPIKeyAuth: true } });
20169
+ }
20170
+ list(projectID, query = {}, options) {
20171
+ return this._client.getAPIList(path3`/organization/projects/${projectID}/service_accounts`, ConversationCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
20172
+ }
20173
+ delete(serviceAccountID, params, options) {
20174
+ const { project_id } = params;
20175
+ return this._client.delete(path3`/organization/projects/${project_id}/service_accounts/${serviceAccountID}`, { ...options, __security: { adminAPIKeyAuth: true } });
20176
+ }
20177
+ };
20178
+ ServiceAccounts.APIKeys = APIKeys2;
20179
+ });
20180
+
19338
20181
  // node_modules/openai/resources/admin/organization/projects/users/roles.mjs
19339
20182
  var Roles5;
19340
20183
  var init_roles5 = __esm(() => {
@@ -19438,12 +20281,14 @@ var init_projects = __esm(() => {
19438
20281
  init_rate_limits();
19439
20282
  init_roles3();
19440
20283
  init_roles3();
19441
- init_service_accounts();
19442
- init_service_accounts();
19443
20284
  init_spend_alerts2();
19444
20285
  init_spend_alerts2();
20286
+ init_spend_limit2();
20287
+ init_spend_limit2();
19445
20288
  init_groups2();
19446
20289
  init_groups2();
20290
+ init_service_accounts();
20291
+ init_service_accounts();
19447
20292
  init_users2();
19448
20293
  init_users2();
19449
20294
  init_pagination();
@@ -19460,6 +20305,7 @@ var init_projects = __esm(() => {
19460
20305
  this.groups = new Groups2(this._client);
19461
20306
  this.roles = new Roles3(this._client);
19462
20307
  this.dataRetention = new DataRetention2(this._client);
20308
+ this.spendLimit = new SpendLimit2(this._client);
19463
20309
  this.spendAlerts = new SpendAlerts2(this._client);
19464
20310
  this.certificates = new Certificates2(this._client);
19465
20311
  }
@@ -19506,6 +20352,7 @@ var init_projects = __esm(() => {
19506
20352
  Projects.Groups = Groups2;
19507
20353
  Projects.Roles = Roles3;
19508
20354
  Projects.DataRetention = DataRetention2;
20355
+ Projects.SpendLimit = SpendLimit2;
19509
20356
  Projects.SpendAlerts = SpendAlerts2;
19510
20357
  Projects.Certificates = Certificates2;
19511
20358
  });
@@ -19605,6 +20452,8 @@ var init_organization = __esm(() => {
19605
20452
  init_roles();
19606
20453
  init_spend_alerts();
19607
20454
  init_spend_alerts();
20455
+ init_spend_limit();
20456
+ init_spend_limit();
19608
20457
  init_usage();
19609
20458
  init_usage();
19610
20459
  init_groups();
@@ -19624,6 +20473,7 @@ var init_organization = __esm(() => {
19624
20473
  this.groups = new Groups(this._client);
19625
20474
  this.roles = new Roles(this._client);
19626
20475
  this.dataRetention = new DataRetention(this._client);
20476
+ this.spendLimit = new SpendLimit(this._client);
19627
20477
  this.spendAlerts = new SpendAlerts(this._client);
19628
20478
  this.certificates = new Certificates(this._client);
19629
20479
  this.projects = new Projects(this._client);
@@ -19637,6 +20487,7 @@ var init_organization = __esm(() => {
19637
20487
  Organization.Groups = Groups;
19638
20488
  Organization.Roles = Roles;
19639
20489
  Organization.DataRetention = DataRetention;
20490
+ Organization.SpendLimit = SpendLimit;
19640
20491
  Organization.SpendAlerts = SpendAlerts;
19641
20492
  Organization.Certificates = Certificates;
19642
20493
  Organization.Projects = Projects;
@@ -19657,72 +20508,6 @@ var init_admin = __esm(() => {
19657
20508
  Admin.Organization = Organization;
19658
20509
  });
19659
20510
 
19660
- // node_modules/openai/internal/headers.mjs
19661
- function* iterateHeaders(headers) {
19662
- if (!headers)
19663
- return;
19664
- if (brand_privateNullableHeaders in headers) {
19665
- const { values, nulls } = headers;
19666
- yield* values.entries();
19667
- for (const name of nulls) {
19668
- yield [name, null];
19669
- }
19670
- return;
19671
- }
19672
- let shouldClear = false;
19673
- let iter;
19674
- if (headers instanceof Headers) {
19675
- iter = headers.entries();
19676
- } else if (isReadonlyArray(headers)) {
19677
- iter = headers;
19678
- } else {
19679
- shouldClear = true;
19680
- iter = Object.entries(headers ?? {});
19681
- }
19682
- for (let row of iter) {
19683
- const name = row[0];
19684
- if (typeof name !== "string")
19685
- throw new TypeError("expected header name to be a string");
19686
- const values = isReadonlyArray(row[1]) ? row[1] : [row[1]];
19687
- let didClear = false;
19688
- for (const value of values) {
19689
- if (value === undefined)
19690
- continue;
19691
- if (shouldClear && !didClear) {
19692
- didClear = true;
19693
- yield [name, null];
19694
- }
19695
- yield [name, value];
19696
- }
19697
- }
19698
- }
19699
- var brand_privateNullableHeaders, buildHeaders = (newHeaders) => {
19700
- const targetHeaders = new Headers;
19701
- const nullHeaders = new Set;
19702
- for (const headers of newHeaders) {
19703
- const seenHeaders = new Set;
19704
- for (const [name, value] of iterateHeaders(headers)) {
19705
- const lowerName = name.toLowerCase();
19706
- if (!seenHeaders.has(lowerName)) {
19707
- targetHeaders.delete(name);
19708
- seenHeaders.add(lowerName);
19709
- }
19710
- if (value === null) {
19711
- targetHeaders.delete(name);
19712
- nullHeaders.add(lowerName);
19713
- } else {
19714
- targetHeaders.append(name, value);
19715
- nullHeaders.delete(lowerName);
19716
- }
19717
- }
19718
- }
19719
- return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders };
19720
- };
19721
- var init_headers = __esm(() => {
19722
- init_values();
19723
- brand_privateNullableHeaders = /* @__PURE__ */ Symbol("brand.privateNullableHeaders");
19724
- });
19725
-
19726
20511
  // node_modules/openai/resources/audio/speech.mjs
19727
20512
  var Speech;
19728
20513
  var init_speech = __esm(() => {
@@ -20010,6 +20795,131 @@ var init_chatkit = __esm(() => {
20010
20795
  ChatKit.Threads = Threads;
20011
20796
  });
20012
20797
 
20798
+ // node_modules/openai/resources/beta/responses/input-items.mjs
20799
+ var InputItems;
20800
+ var init_input_items = __esm(() => {
20801
+ init_resource();
20802
+ init_pagination();
20803
+ init_headers();
20804
+ init_path();
20805
+ InputItems = class InputItems extends APIResource {
20806
+ list(responseID, params = {}, options) {
20807
+ const { betas, ...query } = params ?? {};
20808
+ return this._client.getAPIList(path3`/responses/${responseID}/input_items?beta=true`, CursorPage, {
20809
+ query,
20810
+ ...options,
20811
+ headers: buildHeaders([
20812
+ { ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : undefined },
20813
+ options?.headers
20814
+ ]),
20815
+ __security: { bearerAuth: true }
20816
+ });
20817
+ }
20818
+ };
20819
+ });
20820
+
20821
+ // node_modules/openai/resources/beta/responses/input-tokens.mjs
20822
+ var InputTokens;
20823
+ var init_input_tokens = __esm(() => {
20824
+ init_resource();
20825
+ init_headers();
20826
+ InputTokens = class InputTokens extends APIResource {
20827
+ count(params = {}, options) {
20828
+ const { betas, ...body } = params ?? {};
20829
+ return this._client.post("/responses/input_tokens?beta=true", {
20830
+ body,
20831
+ ...options,
20832
+ headers: buildHeaders([
20833
+ { ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : undefined },
20834
+ options?.headers
20835
+ ]),
20836
+ __security: { bearerAuth: true }
20837
+ });
20838
+ }
20839
+ };
20840
+ });
20841
+
20842
+ // node_modules/openai/resources/beta/responses/responses.mjs
20843
+ var Responses;
20844
+ var init_responses = __esm(() => {
20845
+ init_resource();
20846
+ init_input_items();
20847
+ init_input_items();
20848
+ init_input_tokens();
20849
+ init_input_tokens();
20850
+ init_headers();
20851
+ init_path();
20852
+ Responses = class Responses extends APIResource {
20853
+ constructor() {
20854
+ super(...arguments);
20855
+ this.inputItems = new InputItems(this._client);
20856
+ this.inputTokens = new InputTokens(this._client);
20857
+ }
20858
+ create(params, options) {
20859
+ const { betas, ...body } = params;
20860
+ return this._client.post("/responses?beta=true", {
20861
+ body,
20862
+ ...options,
20863
+ headers: buildHeaders([
20864
+ { ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : undefined },
20865
+ options?.headers
20866
+ ]),
20867
+ stream: params.stream ?? false,
20868
+ __security: { bearerAuth: true }
20869
+ });
20870
+ }
20871
+ retrieve(responseID, params = {}, options) {
20872
+ const { betas, ...query } = params ?? {};
20873
+ return this._client.get(path3`/responses/${responseID}?beta=true`, {
20874
+ query,
20875
+ ...options,
20876
+ headers: buildHeaders([
20877
+ { ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : undefined },
20878
+ options?.headers
20879
+ ]),
20880
+ stream: params?.stream ?? false,
20881
+ __security: { bearerAuth: true }
20882
+ });
20883
+ }
20884
+ delete(responseID, params = {}, options) {
20885
+ const { betas } = params ?? {};
20886
+ return this._client.delete(path3`/responses/${responseID}?beta=true`, {
20887
+ ...options,
20888
+ headers: buildHeaders([
20889
+ { Accept: "*/*", ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : undefined },
20890
+ options?.headers
20891
+ ]),
20892
+ __security: { bearerAuth: true }
20893
+ });
20894
+ }
20895
+ cancel(responseID, params = {}, options) {
20896
+ const { betas } = params ?? {};
20897
+ return this._client.post(path3`/responses/${responseID}/cancel?beta=true`, {
20898
+ ...options,
20899
+ headers: buildHeaders([
20900
+ { ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : undefined },
20901
+ options?.headers
20902
+ ]),
20903
+ __security: { bearerAuth: true }
20904
+ });
20905
+ }
20906
+ compact(params, options) {
20907
+ const { betas, ...body } = params;
20908
+ return this._client.post("/responses/compact?beta=true", {
20909
+ body,
20910
+ ...options,
20911
+ headers: buildHeaders([
20912
+ { ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : undefined },
20913
+ options?.headers
20914
+ ]),
20915
+ __security: { bearerAuth: true }
20916
+ });
20917
+ }
20918
+ };
20919
+ Responses.InputItems = InputItems;
20920
+ Responses.InputTokens = InputTokens;
20921
+ });
20922
+
20013
20923
  // node_modules/openai/resources/beta/threads/messages.mjs
20014
20924
  var Messages2;
20015
20925
  var init_messages2 = __esm(() => {
@@ -20165,11 +21075,12 @@ var init_AssistantStream = __esm(() => {
20165
21075
  const readQueue = [];
20166
21076
  let done = false;
20167
21077
  this.on("event", (event) => {
21078
+ const eventCopy = structuredClone(event);
20168
21079
  const reader = readQueue.shift();
20169
21080
  if (reader) {
20170
- reader.resolve(event);
21081
+ reader.resolve(eventCopy);
20171
21082
  } else {
20172
- pushQueue.push(event);
21083
+ pushQueue.push(eventCopy);
20173
21084
  }
20174
21085
  });
20175
21086
  this.on("end", () => {
@@ -20216,12 +21127,7 @@ var init_AssistantStream = __esm(() => {
20216
21127
  return runner;
20217
21128
  }
20218
21129
  async _fromReadableStream(readableStream, options) {
20219
- const signal = options?.signal;
20220
- if (signal) {
20221
- if (signal.aborted)
20222
- this.controller.abort();
20223
- signal.addEventListener("abort", () => this.controller.abort());
20224
- }
21130
+ this._listenForAbort(options?.signal);
20225
21131
  this._connected();
20226
21132
  const stream = Stream.fromReadableStream(readableStream, this.controller);
20227
21133
  for await (const event of stream) {
@@ -20245,12 +21151,7 @@ var init_AssistantStream = __esm(() => {
20245
21151
  return runner;
20246
21152
  }
20247
21153
  async _createToolAssistantStream(run, runId, params, options) {
20248
- const signal = options?.signal;
20249
- if (signal) {
20250
- if (signal.aborted)
20251
- this.controller.abort();
20252
- signal.addEventListener("abort", () => this.controller.abort());
20253
- }
21154
+ this._listenForAbort(options?.signal);
20254
21155
  const body = { ...params, stream: true };
20255
21156
  const stream = await run.submitToolOutputs(runId, body, {
20256
21157
  ...options,
@@ -20308,12 +21209,7 @@ var init_AssistantStream = __esm(() => {
20308
21209
  return __classPrivateFieldGet(this, _AssistantStream_finalRun, "f");
20309
21210
  }
20310
21211
  async _createThreadAssistantStream(thread, params, options) {
20311
- const signal = options?.signal;
20312
- if (signal) {
20313
- if (signal.aborted)
20314
- this.controller.abort();
20315
- signal.addEventListener("abort", () => this.controller.abort());
20316
- }
21212
+ this._listenForAbort(options?.signal);
20317
21213
  const body = { ...params, stream: true };
20318
21214
  const stream = await thread.createAndRun(body, { ...options, signal: this.controller.signal });
20319
21215
  this._connected();
@@ -20326,12 +21222,7 @@ var init_AssistantStream = __esm(() => {
20326
21222
  return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
20327
21223
  }
20328
21224
  async _createAssistantStream(run, threadId, params, options) {
20329
- const signal = options?.signal;
20330
- if (signal) {
20331
- if (signal.aborted)
20332
- this.controller.abort();
20333
- signal.addEventListener("abort", () => this.controller.abort());
20334
- }
21225
+ this._listenForAbort(options?.signal);
20335
21226
  const body = { ...params, stream: true };
20336
21227
  const stream = await run.create(threadId, body, { ...options, signal: this.controller.signal });
20337
21228
  this._connected();
@@ -20383,7 +21274,7 @@ var init_AssistantStream = __esm(() => {
20383
21274
  }
20384
21275
  const accEntry = accValue[index];
20385
21276
  if (accEntry == null) {
20386
- accValue.push(deltaEntry);
21277
+ accValue[index] = deltaEntry;
20387
21278
  } else {
20388
21279
  accValue[index] = this.accumulateDelta(accEntry, deltaEntry);
20389
21280
  }
@@ -20870,18 +21761,22 @@ var init_beta = __esm(() => {
20870
21761
  init_realtime();
20871
21762
  init_chatkit();
20872
21763
  init_chatkit();
21764
+ init_responses();
21765
+ init_responses();
20873
21766
  init_threads2();
20874
21767
  init_threads2();
20875
21768
  Beta = class Beta extends APIResource {
20876
21769
  constructor() {
20877
21770
  super(...arguments);
20878
21771
  this.realtime = new Realtime(this._client);
21772
+ this.responses = new Responses(this._client);
20879
21773
  this.chatkit = new ChatKit(this._client);
20880
21774
  this.assistants = new Assistants(this._client);
20881
21775
  this.threads = new Threads2(this._client);
20882
21776
  }
20883
21777
  };
20884
21778
  Beta.Realtime = Realtime;
21779
+ Beta.Responses = Responses;
20885
21780
  Beta.ChatKit = ChatKit;
20886
21781
  Beta.Assistants = Assistants;
20887
21782
  Beta.Threads = Threads2;
@@ -21616,7 +22511,7 @@ var init_realtime2 = __esm(() => {
21616
22511
  // node_modules/openai/lib/ResponsesParser.mjs
21617
22512
  function maybeParseResponse(response, params) {
21618
22513
  if (!params || !hasAutoParseableInput2(params)) {
21619
- return {
22514
+ const parsed = {
21620
22515
  ...response,
21621
22516
  output_parsed: null,
21622
22517
  output: response.output.map((item) => {
@@ -21639,23 +22534,25 @@ function maybeParseResponse(response, params) {
21639
22534
  }
21640
22535
  })
21641
22536
  };
22537
+ if (needsOutputText(response, parsed)) {
22538
+ addOutputText(parsed);
22539
+ }
22540
+ return parsed;
21642
22541
  }
21643
22542
  return parseResponse(response, params);
21644
22543
  }
21645
22544
  function parseResponse(response, params) {
22545
+ const shouldParse = !response.status || response.status === "completed";
21646
22546
  const output = response.output.map((item) => {
21647
22547
  if (item.type === "function_call") {
21648
- return {
21649
- ...item,
21650
- parsed_arguments: parseToolCall2(params, item)
21651
- };
22548
+ return shouldParse ? parseToolCall2(params, item) : { ...item, parsed_arguments: null };
21652
22549
  }
21653
22550
  if (item.type === "message") {
21654
22551
  const content = item.content.map((content) => {
21655
22552
  if (content.type === "output_text") {
21656
22553
  return {
21657
22554
  ...content,
21658
- parsed: parseTextFormat(params, content.text)
22555
+ parsed: shouldParse ? parseTextFormat(params, content.text) : null
21659
22556
  };
21660
22557
  }
21661
22558
  return content;
@@ -21668,7 +22565,7 @@ function parseResponse(response, params) {
21668
22565
  return item;
21669
22566
  });
21670
22567
  const parsed = Object.assign({}, response, { output });
21671
- if (!Object.getOwnPropertyDescriptor(response, "output_text")) {
22568
+ if (needsOutputText(response, parsed)) {
21672
22569
  addOutputText(parsed);
21673
22570
  }
21674
22571
  Object.defineProperty(parsed, "output_parsed", {
@@ -21703,7 +22600,7 @@ function hasAutoParseableInput2(params) {
21703
22600
  if (isAutoParsableResponseFormat(params.text?.format)) {
21704
22601
  return true;
21705
22602
  }
21706
- return false;
22603
+ return Array.isArray(params.tools) && params.tools.some((tool) => isAutoParsableTool2(tool) || tool.type === "function" && tool.strict === true);
21707
22604
  }
21708
22605
  function isAutoParsableTool2(tool) {
21709
22606
  return tool?.["$brand"] === "auto-parseable-tool";
@@ -21719,6 +22616,9 @@ function parseToolCall2(params, toolCall) {
21719
22616
  parsed_arguments: isAutoParsableTool2(inputTool) ? inputTool.$parseRaw(toolCall.arguments) : inputTool?.strict ? JSON.parse(toolCall.arguments) : null
21720
22617
  };
21721
22618
  }
22619
+ function needsOutputText(response, target) {
22620
+ return !Object.getOwnPropertyDescriptor(response, "output_text") || target.output_text == null;
22621
+ }
21722
22622
  function addOutputText(rsp) {
21723
22623
  const texts = [];
21724
22624
  for (const output of rsp.output) {
@@ -21738,16 +22638,411 @@ var init_ResponsesParser = __esm(() => {
21738
22638
  init_parser();
21739
22639
  });
21740
22640
 
22641
+ // node_modules/openai/lib/responses/ResponseAccumulator.mjs
22642
+ function accumulateResponse(event, snapshot) {
22643
+ if (!snapshot) {
22644
+ if (event.type !== "response.created") {
22645
+ throw new OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${event.type}`);
22646
+ }
22647
+ return cloneResponse(event.response);
22648
+ }
22649
+ switch (event.type) {
22650
+ case "response.output_item.added": {
22651
+ snapshot.output.push(structuredClone(event.item));
22652
+ if (event.item.type === "message") {
22653
+ addOutputText(snapshot);
22654
+ }
22655
+ break;
22656
+ }
22657
+ case "response.output_item.done": {
22658
+ getOutput(snapshot, event.output_index);
22659
+ snapshot.output[event.output_index] = structuredClone(event.item);
22660
+ if (event.item.type === "message") {
22661
+ addOutputText(snapshot);
22662
+ }
22663
+ break;
22664
+ }
22665
+ case "response.content_part.added": {
22666
+ const output = getOutput(snapshot, event.output_index);
22667
+ const type = output.type;
22668
+ const part = event.part;
22669
+ if (type === "message" && part.type !== "reasoning_text") {
22670
+ output.content.push(structuredClone(part));
22671
+ if (part.type === "output_text") {
22672
+ addOutputText(snapshot);
22673
+ }
22674
+ } else if (type === "reasoning" && part.type === "reasoning_text") {
22675
+ if (!output.content) {
22676
+ output.content = [];
22677
+ }
22678
+ output.content.push(structuredClone(part));
22679
+ }
22680
+ break;
22681
+ }
22682
+ case "response.content_part.done": {
22683
+ const output = getOutput(snapshot, event.output_index);
22684
+ const part = event.part;
22685
+ if (output.type === "message" && part.type !== "reasoning_text") {
22686
+ getContent(output.content, event.content_index);
22687
+ output.content[event.content_index] = structuredClone(part);
22688
+ if (part.type === "output_text") {
22689
+ addOutputText(snapshot);
22690
+ }
22691
+ } else if (output.type === "reasoning" && part.type === "reasoning_text") {
22692
+ const content = output.content;
22693
+ if (!content) {
22694
+ throw new OpenAIError(`missing content at index ${event.content_index}`);
22695
+ }
22696
+ getContent(content, event.content_index);
22697
+ content[event.content_index] = structuredClone(part);
22698
+ }
22699
+ break;
22700
+ }
22701
+ case "response.output_text.delta": {
22702
+ const output = getOutput(snapshot, event.output_index);
22703
+ if (output.type === "message") {
22704
+ const content = getContent(output.content, event.content_index);
22705
+ if (content.type !== "output_text") {
22706
+ throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
22707
+ }
22708
+ content.text += event.delta;
22709
+ snapshot.output_text += event.delta;
22710
+ }
22711
+ break;
22712
+ }
22713
+ case "response.output_text.done": {
22714
+ const output = getOutput(snapshot, event.output_index);
22715
+ if (output.type === "message") {
22716
+ const content = getContent(output.content, event.content_index);
22717
+ if (content.type !== "output_text") {
22718
+ throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
22719
+ }
22720
+ content.text = event.text;
22721
+ addOutputText(snapshot);
22722
+ }
22723
+ break;
22724
+ }
22725
+ case "response.output_text.annotation.added": {
22726
+ const output = getOutput(snapshot, event.output_index);
22727
+ if (output.type === "message") {
22728
+ const content = getContent(output.content, event.content_index);
22729
+ if (content.type !== "output_text") {
22730
+ throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
22731
+ }
22732
+ content.annotations[event.annotation_index] = structuredClone(event.annotation);
22733
+ }
22734
+ break;
22735
+ }
22736
+ case "response.refusal.delta": {
22737
+ const output = getOutput(snapshot, event.output_index);
22738
+ if (output.type === "message") {
22739
+ const content = getContent(output.content, event.content_index);
22740
+ if (content.type !== "refusal") {
22741
+ throw new OpenAIError(`expected content to be 'refusal', got ${content.type}`);
22742
+ }
22743
+ content.refusal += event.delta;
22744
+ }
22745
+ break;
22746
+ }
22747
+ case "response.refusal.done": {
22748
+ const output = getOutput(snapshot, event.output_index);
22749
+ if (output.type === "message") {
22750
+ const content = getContent(output.content, event.content_index);
22751
+ if (content.type !== "refusal") {
22752
+ throw new OpenAIError(`expected content to be 'refusal', got ${content.type}`);
22753
+ }
22754
+ content.refusal = event.refusal;
22755
+ }
22756
+ break;
22757
+ }
22758
+ case "response.function_call_arguments.delta": {
22759
+ const output = getOutput(snapshot, event.output_index);
22760
+ if (output.type === "function_call") {
22761
+ output.arguments += event.delta;
22762
+ }
22763
+ break;
22764
+ }
22765
+ case "response.function_call_arguments.done": {
22766
+ const output = getOutput(snapshot, event.output_index);
22767
+ if (output.type === "function_call") {
22768
+ output.arguments = event.arguments;
22769
+ }
22770
+ break;
22771
+ }
22772
+ case "response.reasoning_text.delta": {
22773
+ const output = getOutput(snapshot, event.output_index);
22774
+ if (output.type === "reasoning") {
22775
+ if (!output.content) {
22776
+ throw new OpenAIError(`missing content at index ${event.content_index}`);
22777
+ }
22778
+ const content = getContent(output.content, event.content_index);
22779
+ if (content.type !== "reasoning_text") {
22780
+ throw new OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`);
22781
+ }
22782
+ content.text += event.delta;
22783
+ }
22784
+ break;
22785
+ }
22786
+ case "response.reasoning_text.done": {
22787
+ const output = getOutput(snapshot, event.output_index);
22788
+ if (output.type === "reasoning") {
22789
+ if (!output.content) {
22790
+ throw new OpenAIError(`missing content at index ${event.content_index}`);
22791
+ }
22792
+ const content = getContent(output.content, event.content_index);
22793
+ if (content.type !== "reasoning_text") {
22794
+ throw new OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`);
22795
+ }
22796
+ content.text = event.text;
22797
+ }
22798
+ break;
22799
+ }
22800
+ case "response.reasoning_summary_part.added": {
22801
+ const output = getOutput(snapshot, event.output_index);
22802
+ if (output.type === "reasoning") {
22803
+ output.summary.push(structuredClone(event.part));
22804
+ }
22805
+ break;
22806
+ }
22807
+ case "response.reasoning_summary_part.done": {
22808
+ const output = getOutput(snapshot, event.output_index);
22809
+ if (output.type === "reasoning") {
22810
+ getContent(output.summary, event.summary_index);
22811
+ output.summary[event.summary_index] = structuredClone(event.part);
22812
+ }
22813
+ break;
22814
+ }
22815
+ case "response.reasoning_summary_text.delta": {
22816
+ const output = getOutput(snapshot, event.output_index);
22817
+ if (output.type === "reasoning") {
22818
+ const part = getContent(output.summary, event.summary_index);
22819
+ part.text += event.delta;
22820
+ }
22821
+ break;
22822
+ }
22823
+ case "response.reasoning_summary_text.done": {
22824
+ const output = getOutput(snapshot, event.output_index);
22825
+ if (output.type === "reasoning") {
22826
+ const part = getContent(output.summary, event.summary_index);
22827
+ part.text = event.text;
22828
+ }
22829
+ break;
22830
+ }
22831
+ case "response.custom_tool_call_input.delta": {
22832
+ const output = getOutput(snapshot, event.output_index);
22833
+ if (output.type === "custom_tool_call") {
22834
+ output.input += event.delta;
22835
+ }
22836
+ break;
22837
+ }
22838
+ case "response.custom_tool_call_input.done": {
22839
+ const output = getOutput(snapshot, event.output_index);
22840
+ if (output.type === "custom_tool_call") {
22841
+ output.input = event.input;
22842
+ }
22843
+ break;
22844
+ }
22845
+ case "response.mcp_call_arguments.delta": {
22846
+ const output = getOutput(snapshot, event.output_index);
22847
+ if (output.type === "mcp_call") {
22848
+ output.arguments += event.delta;
22849
+ }
22850
+ break;
22851
+ }
22852
+ case "response.mcp_call_arguments.done": {
22853
+ const output = getOutput(snapshot, event.output_index);
22854
+ if (output.type === "mcp_call") {
22855
+ output.arguments = event.arguments;
22856
+ }
22857
+ break;
22858
+ }
22859
+ case "response.code_interpreter_call_code.delta": {
22860
+ const output = getOutput(snapshot, event.output_index);
22861
+ if (output.type === "code_interpreter_call") {
22862
+ output.code = (output.code ?? "") + event.delta;
22863
+ }
22864
+ break;
22865
+ }
22866
+ case "response.code_interpreter_call_code.done": {
22867
+ const output = getOutput(snapshot, event.output_index);
22868
+ if (output.type === "code_interpreter_call") {
22869
+ output.code = event.code;
22870
+ }
22871
+ break;
22872
+ }
22873
+ case "response.code_interpreter_call.in_progress": {
22874
+ const output = getOutput(snapshot, event.output_index);
22875
+ if (output.type === "code_interpreter_call") {
22876
+ output.status = "in_progress";
22877
+ }
22878
+ break;
22879
+ }
22880
+ case "response.code_interpreter_call.interpreting": {
22881
+ const output = getOutput(snapshot, event.output_index);
22882
+ if (output.type === "code_interpreter_call") {
22883
+ output.status = "interpreting";
22884
+ }
22885
+ break;
22886
+ }
22887
+ case "response.code_interpreter_call.completed": {
22888
+ const output = getOutput(snapshot, event.output_index);
22889
+ if (output.type === "code_interpreter_call") {
22890
+ output.status = "completed";
22891
+ }
22892
+ break;
22893
+ }
22894
+ case "response.file_search_call.in_progress": {
22895
+ const output = getOutput(snapshot, event.output_index);
22896
+ if (output.type === "file_search_call") {
22897
+ output.status = "in_progress";
22898
+ }
22899
+ break;
22900
+ }
22901
+ case "response.file_search_call.searching": {
22902
+ const output = getOutput(snapshot, event.output_index);
22903
+ if (output.type === "file_search_call") {
22904
+ output.status = "searching";
22905
+ }
22906
+ break;
22907
+ }
22908
+ case "response.file_search_call.completed": {
22909
+ const output = getOutput(snapshot, event.output_index);
22910
+ if (output.type === "file_search_call") {
22911
+ output.status = "completed";
22912
+ }
22913
+ break;
22914
+ }
22915
+ case "response.web_search_call.in_progress": {
22916
+ const output = getOutput(snapshot, event.output_index);
22917
+ if (output.type === "web_search_call") {
22918
+ output.status = "in_progress";
22919
+ }
22920
+ break;
22921
+ }
22922
+ case "response.web_search_call.searching": {
22923
+ const output = getOutput(snapshot, event.output_index);
22924
+ if (output.type === "web_search_call") {
22925
+ output.status = "searching";
22926
+ }
22927
+ break;
22928
+ }
22929
+ case "response.web_search_call.completed": {
22930
+ const output = getOutput(snapshot, event.output_index);
22931
+ if (output.type === "web_search_call") {
22932
+ output.status = "completed";
22933
+ }
22934
+ break;
22935
+ }
22936
+ case "response.image_generation_call.in_progress": {
22937
+ const output = getOutput(snapshot, event.output_index);
22938
+ if (output.type === "image_generation_call") {
22939
+ output.status = "in_progress";
22940
+ }
22941
+ break;
22942
+ }
22943
+ case "response.image_generation_call.generating": {
22944
+ const output = getOutput(snapshot, event.output_index);
22945
+ if (output.type === "image_generation_call") {
22946
+ output.status = "generating";
22947
+ }
22948
+ break;
22949
+ }
22950
+ case "response.image_generation_call.completed": {
22951
+ const output = getOutput(snapshot, event.output_index);
22952
+ if (output.type === "image_generation_call") {
22953
+ output.status = "completed";
22954
+ }
22955
+ break;
22956
+ }
22957
+ case "response.mcp_call.in_progress": {
22958
+ const output = getOutput(snapshot, event.output_index);
22959
+ if (output.type === "mcp_call") {
22960
+ output.status = "in_progress";
22961
+ }
22962
+ break;
22963
+ }
22964
+ case "response.mcp_call.completed": {
22965
+ const output = getOutput(snapshot, event.output_index);
22966
+ if (output.type === "mcp_call") {
22967
+ output.status = "completed";
22968
+ }
22969
+ break;
22970
+ }
22971
+ case "response.mcp_call.failed": {
22972
+ const output = getOutput(snapshot, event.output_index);
22973
+ if (output.type === "mcp_call") {
22974
+ output.status = "failed";
22975
+ }
22976
+ break;
22977
+ }
22978
+ case "response.created":
22979
+ case "response.queued":
22980
+ case "response.in_progress":
22981
+ case "response.completed":
22982
+ case "response.failed":
22983
+ case "response.incomplete": {
22984
+ snapshot = cloneResponse(event.response);
22985
+ break;
22986
+ }
22987
+ case "response.audio.delta":
22988
+ case "response.audio.done":
22989
+ case "response.audio.transcript.delta":
22990
+ case "response.audio.transcript.done":
22991
+ case "response.image_generation_call.partial_image":
22992
+ case "response.mcp_list_tools.in_progress":
22993
+ case "response.mcp_list_tools.completed":
22994
+ case "response.mcp_list_tools.failed":
22995
+ case "keepalive":
22996
+ case "error": {
22997
+ break;
22998
+ }
22999
+ default: {
23000
+ assertNever3(event);
23001
+ }
23002
+ }
23003
+ return snapshot;
23004
+ }
23005
+ function cloneResponse(response) {
23006
+ const snapshot = structuredClone(response);
23007
+ if (!Object.getOwnPropertyDescriptor(snapshot, "output_text") || snapshot.output_text == null) {
23008
+ addOutputText(snapshot);
23009
+ }
23010
+ return snapshot;
23011
+ }
23012
+ function getOutput(snapshot, outputIndex) {
23013
+ const output = snapshot.output[outputIndex];
23014
+ if (!output) {
23015
+ throw new OpenAIError(`missing output at index ${outputIndex}`);
23016
+ }
23017
+ return output;
23018
+ }
23019
+ function getContent(content, contentIndex) {
23020
+ const part = content[contentIndex];
23021
+ if (!part) {
23022
+ throw new OpenAIError(`missing content at index ${contentIndex}`);
23023
+ }
23024
+ return part;
23025
+ }
23026
+ function assertNever3(value) {
23027
+ throw new OpenAIError(`Unhandled response stream event: ${JSON.stringify(value)}`);
23028
+ }
23029
+ var init_ResponseAccumulator = __esm(() => {
23030
+ init_error2();
23031
+ init_ResponsesParser();
23032
+ });
23033
+
21741
23034
  // node_modules/openai/lib/responses/ResponseStream.mjs
21742
23035
  function finalizeResponse(snapshot, params) {
21743
23036
  return maybeParseResponse(snapshot, params);
21744
23037
  }
21745
- var _ResponseStream_instances, _ResponseStream_params, _ResponseStream_currentResponseSnapshot, _ResponseStream_finalResponse, _ResponseStream_beginRequest, _ResponseStream_addEvent, _ResponseStream_endRequest, _ResponseStream_accumulateResponse, ResponseStream;
23038
+ var _ResponseStream_instances, _ResponseStream_params, _ResponseStream_currentResponseSnapshot, _ResponseStream_finalResponse, _ResponseStream_beginRequest, _ResponseStream_addEvent, _ResponseStream_endRequest, ResponseStream;
21746
23039
  var init_ResponseStream = __esm(() => {
21747
23040
  init_tslib();
21748
23041
  init_error2();
21749
23042
  init_EventStream();
23043
+ init_ResponseAccumulator();
21750
23044
  init_ResponsesParser();
23045
+ init_streaming2();
21751
23046
  ResponseStream = class ResponseStream extends EventStream {
21752
23047
  constructor(params) {
21753
23048
  super();
@@ -21765,13 +23060,13 @@ var init_ResponseStream = __esm(() => {
21765
23060
  }));
21766
23061
  return runner;
21767
23062
  }
23063
+ static fromReadableStream(stream) {
23064
+ const runner = new ResponseStream(null);
23065
+ runner._run(() => runner._fromReadableStream(stream));
23066
+ return runner;
23067
+ }
21768
23068
  async _createOrRetrieveResponse(client, params, options) {
21769
- const signal = options?.signal;
21770
- if (signal) {
21771
- if (signal.aborted)
21772
- this.controller.abort();
21773
- signal.addEventListener("abort", () => this.controller.abort());
21774
- }
23069
+ this._listenForAbort(options?.signal);
21775
23070
  __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_beginRequest).call(this);
21776
23071
  let stream;
21777
23072
  let starting_after = null;
@@ -21790,6 +23085,19 @@ var init_ResponseStream = __esm(() => {
21790
23085
  }
21791
23086
  return __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_endRequest).call(this);
21792
23087
  }
23088
+ async _fromReadableStream(readableStream, options) {
23089
+ this._listenForAbort(options?.signal);
23090
+ __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_beginRequest).call(this);
23091
+ this._connected();
23092
+ const stream = Stream.fromReadableStream(readableStream, this.controller);
23093
+ for await (const event of stream) {
23094
+ __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_addEvent).call(this, event, null);
23095
+ }
23096
+ if (stream.controller.signal?.aborted) {
23097
+ throw new APIUserAbortError;
23098
+ }
23099
+ return __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_endRequest).call(this);
23100
+ }
21793
23101
  [(_ResponseStream_params = new WeakMap, _ResponseStream_currentResponseSnapshot = new WeakMap, _ResponseStream_finalResponse = new WeakMap, _ResponseStream_instances = new WeakSet, _ResponseStream_beginRequest = function _ResponseStream_beginRequest2() {
21794
23102
  if (this.ended)
21795
23103
  return;
@@ -21802,7 +23110,8 @@ var init_ResponseStream = __esm(() => {
21802
23110
  this._emit(name, event);
21803
23111
  }
21804
23112
  };
21805
- const response = __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_accumulateResponse).call(this, event);
23113
+ const response = accumulateResponse(event, __classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f"));
23114
+ __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, response, "f");
21806
23115
  maybeEmit("event", event);
21807
23116
  switch (event.type) {
21808
23117
  case "response.output_text.delta": {
@@ -21854,87 +23163,6 @@ var init_ResponseStream = __esm(() => {
21854
23163
  const parsedResponse = finalizeResponse(snapshot, __classPrivateFieldGet(this, _ResponseStream_params, "f"));
21855
23164
  __classPrivateFieldSet(this, _ResponseStream_finalResponse, parsedResponse, "f");
21856
23165
  return parsedResponse;
21857
- }, _ResponseStream_accumulateResponse = function _ResponseStream_accumulateResponse2(event) {
21858
- let snapshot = __classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f");
21859
- if (!snapshot) {
21860
- if (event.type !== "response.created") {
21861
- throw new OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${event.type}`);
21862
- }
21863
- snapshot = __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, "f");
21864
- return snapshot;
21865
- }
21866
- switch (event.type) {
21867
- case "response.output_item.added": {
21868
- snapshot.output.push(event.item);
21869
- break;
21870
- }
21871
- case "response.content_part.added": {
21872
- const output = snapshot.output[event.output_index];
21873
- if (!output) {
21874
- throw new OpenAIError(`missing output at index ${event.output_index}`);
21875
- }
21876
- const type = output.type;
21877
- const part = event.part;
21878
- if (type === "message" && part.type !== "reasoning_text") {
21879
- output.content.push(part);
21880
- } else if (type === "reasoning" && part.type === "reasoning_text") {
21881
- if (!output.content) {
21882
- output.content = [];
21883
- }
21884
- output.content.push(part);
21885
- }
21886
- break;
21887
- }
21888
- case "response.output_text.delta": {
21889
- const output = snapshot.output[event.output_index];
21890
- if (!output) {
21891
- throw new OpenAIError(`missing output at index ${event.output_index}`);
21892
- }
21893
- if (output.type === "message") {
21894
- const content = output.content[event.content_index];
21895
- if (!content) {
21896
- throw new OpenAIError(`missing content at index ${event.content_index}`);
21897
- }
21898
- if (content.type !== "output_text") {
21899
- throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
21900
- }
21901
- content.text += event.delta;
21902
- }
21903
- break;
21904
- }
21905
- case "response.function_call_arguments.delta": {
21906
- const output = snapshot.output[event.output_index];
21907
- if (!output) {
21908
- throw new OpenAIError(`missing output at index ${event.output_index}`);
21909
- }
21910
- if (output.type === "function_call") {
21911
- output.arguments += event.delta;
21912
- }
21913
- break;
21914
- }
21915
- case "response.reasoning_text.delta": {
21916
- const output = snapshot.output[event.output_index];
21917
- if (!output) {
21918
- throw new OpenAIError(`missing output at index ${event.output_index}`);
21919
- }
21920
- if (output.type === "reasoning") {
21921
- const content = output.content?.[event.content_index];
21922
- if (!content) {
21923
- throw new OpenAIError(`missing content at index ${event.content_index}`);
21924
- }
21925
- if (content.type !== "reasoning_text") {
21926
- throw new OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`);
21927
- }
21928
- content.text += event.delta;
21929
- }
21930
- break;
21931
- }
21932
- case "response.completed": {
21933
- __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, "f");
21934
- break;
21935
- }
21936
- }
21937
- return snapshot;
21938
23166
  }, Symbol.asyncIterator)]() {
21939
23167
  const pushQueue = [];
21940
23168
  const readQueue = [];
@@ -21996,12 +23224,12 @@ var init_ResponseStream = __esm(() => {
21996
23224
  });
21997
23225
 
21998
23226
  // node_modules/openai/resources/responses/input-items.mjs
21999
- var InputItems;
22000
- var init_input_items = __esm(() => {
23227
+ var InputItems2;
23228
+ var init_input_items2 = __esm(() => {
22001
23229
  init_resource();
22002
23230
  init_pagination();
22003
23231
  init_path();
22004
- InputItems = class InputItems extends APIResource {
23232
+ InputItems2 = class InputItems2 extends APIResource {
22005
23233
  list(responseID, query = {}, options) {
22006
23234
  return this._client.getAPIList(path3`/responses/${responseID}/input_items`, CursorPage, { query, ...options, __security: { bearerAuth: true } });
22007
23235
  }
@@ -22009,10 +23237,10 @@ var init_input_items = __esm(() => {
22009
23237
  });
22010
23238
 
22011
23239
  // node_modules/openai/resources/responses/input-tokens.mjs
22012
- var InputTokens;
22013
- var init_input_tokens = __esm(() => {
23240
+ var InputTokens2;
23241
+ var init_input_tokens2 = __esm(() => {
22014
23242
  init_resource();
22015
- InputTokens = class InputTokens extends APIResource {
23243
+ InputTokens2 = class InputTokens2 extends APIResource {
22016
23244
  count(body = {}, options) {
22017
23245
  return this._client.post("/responses/input_tokens", {
22018
23246
  body,
@@ -22024,22 +23252,22 @@ var init_input_tokens = __esm(() => {
22024
23252
  });
22025
23253
 
22026
23254
  // node_modules/openai/resources/responses/responses.mjs
22027
- var Responses;
22028
- var init_responses = __esm(() => {
23255
+ var Responses2;
23256
+ var init_responses2 = __esm(() => {
22029
23257
  init_ResponsesParser();
22030
23258
  init_ResponseStream();
22031
23259
  init_resource();
22032
- init_input_items();
22033
- init_input_items();
22034
- init_input_tokens();
22035
- init_input_tokens();
23260
+ init_input_items2();
23261
+ init_input_items2();
23262
+ init_input_tokens2();
23263
+ init_input_tokens2();
22036
23264
  init_headers();
22037
23265
  init_path();
22038
- Responses = class Responses extends APIResource {
23266
+ Responses2 = class Responses2 extends APIResource {
22039
23267
  constructor() {
22040
23268
  super(...arguments);
22041
- this.inputItems = new InputItems(this._client);
22042
- this.inputTokens = new InputTokens(this._client);
23269
+ this.inputItems = new InputItems2(this._client);
23270
+ this.inputTokens = new InputTokens2(this._client);
22043
23271
  }
22044
23272
  create(body, options) {
22045
23273
  return this._client.post("/responses", {
@@ -22090,8 +23318,8 @@ var init_responses = __esm(() => {
22090
23318
  return this._client.post("/responses/compact", { body, ...options, __security: { bearerAuth: true } });
22091
23319
  }
22092
23320
  };
22093
- Responses.InputItems = InputItems;
22094
- Responses.InputTokens = InputTokens;
23321
+ Responses2.InputItems = InputItems2;
23322
+ Responses2.InputTokens = InputTokens2;
22095
23323
  });
22096
23324
 
22097
23325
  // node_modules/openai/resources/skills/content.mjs
@@ -22720,7 +23948,7 @@ var init_resources = __esm(() => {
22720
23948
  init_models();
22721
23949
  init_moderations();
22722
23950
  init_realtime2();
22723
- init_responses();
23951
+ init_responses2();
22724
23952
  init_skills();
22725
23953
  init_uploads3();
22726
23954
  init_vector_stores();
@@ -22730,9 +23958,28 @@ var init_resources = __esm(() => {
22730
23958
  init_shared();
22731
23959
  });
22732
23960
 
23961
+ // node_modules/openai/internal/provider.mjs
23962
+ function configureProvider(provider) {
23963
+ const definition = providerDefinitions.get(provider);
23964
+ if (!definition) {
23965
+ throw new Error("Invalid provider. Providers must be created with createProvider().");
23966
+ }
23967
+ return definition.configure();
23968
+ }
23969
+ var providerDefinitionsKey, providerGlobal, existingProviderDefinitions, providerDefinitions;
23970
+ var init_provider = __esm(() => {
23971
+ providerDefinitionsKey = Symbol.for("openai.node.providerDefinitions.v1");
23972
+ providerGlobal = globalThis;
23973
+ existingProviderDefinitions = providerGlobal[providerDefinitionsKey];
23974
+ providerDefinitions = existingProviderDefinitions ?? new WeakMap;
23975
+ if (!existingProviderDefinitions) {
23976
+ Object.defineProperty(providerGlobal, providerDefinitionsKey, { value: providerDefinitions });
23977
+ }
23978
+ });
23979
+
22733
23980
  // node_modules/openai/client.mjs
22734
23981
  class OpenAI2 {
22735
- constructor({ baseURL = readEnv("OPENAI_BASE_URL"), apiKey = readEnv("OPENAI_API_KEY") ?? null, adminAPIKey = readEnv("OPENAI_ADMIN_KEY") ?? null, organization = readEnv("OPENAI_ORG_ID") ?? null, project = readEnv("OPENAI_PROJECT_ID") ?? null, webhookSecret = readEnv("OPENAI_WEBHOOK_SECRET") ?? null, workloadIdentity, ...opts } = {}) {
23982
+ constructor(clientOptions = {}) {
22736
23983
  _OpenAI_instances.add(this);
22737
23984
  _OpenAI_encoder.set(this, undefined);
22738
23985
  this.completions = new Completions2(this);
@@ -22751,13 +23998,22 @@ class OpenAI2 {
22751
23998
  this.batches = new Batches(this);
22752
23999
  this.uploads = new Uploads(this);
22753
24000
  this.admin = new Admin(this);
22754
- this.responses = new Responses(this);
24001
+ this.responses = new Responses2(this);
22755
24002
  this.realtime = new Realtime2(this);
22756
24003
  this.conversations = new Conversations(this);
22757
24004
  this.evals = new Evals(this);
22758
24005
  this.containers = new Containers(this);
22759
24006
  this.skills = new Skills(this);
22760
24007
  this.videos = new Videos(this);
24008
+ const provider = clientOptions.provider;
24009
+ if (provider) {
24010
+ const conflictingOptions = ["apiKey", "adminAPIKey", "workloadIdentity", "baseURL"].filter((key) => clientOptions[key] != null);
24011
+ if (conflictingOptions.length) {
24012
+ throw new OpenAIError(`The \`provider\` option cannot be used with ${conflictingOptions.map((key) => `\`${key}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`);
24013
+ }
24014
+ }
24015
+ const { baseURL = provider ? null : readEnv("OPENAI_BASE_URL"), apiKey = provider ? null : readEnv("OPENAI_API_KEY") ?? null, adminAPIKey = provider ? null : readEnv("OPENAI_ADMIN_KEY") ?? null, organization = provider ? null : readEnv("OPENAI_ORG_ID") ?? null, project = provider ? null : readEnv("OPENAI_PROJECT_ID") ?? null, webhookSecret = readEnv("OPENAI_WEBHOOK_SECRET") ?? null, workloadIdentity, ...opts } = clientOptions;
24016
+ const providerRuntime = provider ? configureProvider(provider) : undefined;
22761
24017
  const options = {
22762
24018
  apiKey,
22763
24019
  adminAPIKey,
@@ -22765,13 +24021,14 @@ class OpenAI2 {
22765
24021
  project,
22766
24022
  webhookSecret,
22767
24023
  workloadIdentity,
24024
+ provider,
22768
24025
  ...opts,
22769
- baseURL: baseURL || `https://api.openai.com/v1`
24026
+ baseURL: providerRuntime?.baseURL ?? (baseURL || `https://api.openai.com/v1`)
22770
24027
  };
22771
24028
  if (apiKey && workloadIdentity) {
22772
24029
  throw new OpenAIError("The `apiKey` and `workloadIdentity` options are mutually exclusive");
22773
24030
  }
22774
- if (!apiKey && !adminAPIKey && !workloadIdentity) {
24031
+ if (!providerRuntime && !apiKey && !adminAPIKey && !workloadIdentity) {
22775
24032
  throw new OpenAIError("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");
22776
24033
  }
22777
24034
  if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) {
@@ -22796,7 +24053,7 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
22796
24053
  this.maxRetries = options.maxRetries ?? 2;
22797
24054
  this.fetch = options.fetch ?? getDefaultFetch();
22798
24055
  __classPrivateFieldSet(this, _OpenAI_encoder, FallbackEncoder, "f");
22799
- const customHeadersEnv = readEnv("OPENAI_CUSTOM_HEADERS");
24056
+ const customHeadersEnv = provider ? undefined : readEnv("OPENAI_CUSTOM_HEADERS");
22800
24057
  if (customHeadersEnv) {
22801
24058
  const parsed = {};
22802
24059
  for (const line of customHeadersEnv.split(`
@@ -22809,6 +24066,7 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
22809
24066
  options.defaultHeaders = buildHeaders([parsed, options.defaultHeaders]);
22810
24067
  }
22811
24068
  this._options = options;
24069
+ this._provider = providerRuntime;
22812
24070
  if (workloadIdentity) {
22813
24071
  this._workloadIdentityAuth = new WorkloadIdentityAuth(workloadIdentity, this.fetch);
22814
24072
  }
@@ -22819,7 +24077,9 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
22819
24077
  this.webhookSecret = webhookSecret;
22820
24078
  }
22821
24079
  withOptions(options) {
22822
- const client = new this.constructor({
24080
+ const inheritedProvider = this._options.provider;
24081
+ const provider = options.provider ?? inheritedProvider;
24082
+ const inheritedOptions = {
22823
24083
  ...this._options,
22824
24084
  baseURL: this.baseURL,
22825
24085
  maxRetries: this.maxRetries,
@@ -22833,8 +24093,23 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
22833
24093
  workloadIdentity: this._options.workloadIdentity,
22834
24094
  organization: this.organization,
22835
24095
  project: this.project,
22836
- webhookSecret: this.webhookSecret,
22837
- ...options
24096
+ webhookSecret: this.webhookSecret
24097
+ };
24098
+ if (provider) {
24099
+ delete inheritedOptions.apiKey;
24100
+ delete inheritedOptions.adminAPIKey;
24101
+ delete inheritedOptions.workloadIdentity;
24102
+ delete inheritedOptions.baseURL;
24103
+ if (provider !== inheritedProvider) {
24104
+ delete inheritedOptions.organization;
24105
+ delete inheritedOptions.project;
24106
+ delete inheritedOptions.defaultHeaders;
24107
+ }
24108
+ }
24109
+ const client = new this.constructor({
24110
+ ...inheritedOptions,
24111
+ ...options,
24112
+ provider
22838
24113
  });
22839
24114
  return client;
22840
24115
  }
@@ -22893,6 +24168,8 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
22893
24168
  return APIError.generate(status, error, message, headers);
22894
24169
  }
22895
24170
  async _callApiKey() {
24171
+ if (this._provider)
24172
+ return false;
22896
24173
  const apiKey = this._options.apiKey;
22897
24174
  if (typeof apiKey !== "function")
22898
24175
  return false;
@@ -22924,6 +24201,8 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
22924
24201
  return url.toString();
22925
24202
  }
22926
24203
  async prepareOptions(options) {
24204
+ if (this._provider)
24205
+ return;
22927
24206
  const security = options.__security ?? { bearerAuth: true };
22928
24207
  if (security.bearerAuth) {
22929
24208
  await this._callApiKey();
@@ -22963,7 +24242,9 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
22963
24242
  const { req, url, timeout } = await this.buildRequest(options, {
22964
24243
  retryCount: maxRetries - retriesRemaining
22965
24244
  });
24245
+ const hasStreamingBody = options.__metadata?.["hasStreamingBody"] === true;
22966
24246
  await this.prepareRequest(req, { url, options });
24247
+ await this._provider?.prepareRequest?.(req, { url, options });
22967
24248
  const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0");
22968
24249
  const retryLogStr = retryOfRequestLogID === undefined ? "" : `, retryOf: ${retryOfRequestLogID}`;
22969
24250
  const startTime = Date.now();
@@ -22987,7 +24268,7 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
22987
24268
  throw new APIUserAbortError;
22988
24269
  }
22989
24270
  const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
22990
- if (retriesRemaining) {
24271
+ if (retriesRemaining && !hasStreamingBody) {
22991
24272
  loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`);
22992
24273
  loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({
22993
24274
  retryOfRequestLogID,
@@ -22997,8 +24278,9 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
22997
24278
  }));
22998
24279
  return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
22999
24280
  }
23000
- loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`);
23001
- loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails({
24281
+ const terminalMessage = hasStreamingBody ? "error; streaming body cannot be retried" : "error; no more retries left";
24282
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${terminalMessage}`);
24283
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${terminalMessage})`, formatRequestDetails({
23002
24284
  retryOfRequestLogID,
23003
24285
  url,
23004
24286
  durationMs: headersTime - startTime,
@@ -23030,7 +24312,7 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
23030
24312
  }, retriesRemaining, retryOfRequestLogID ?? requestLogID);
23031
24313
  }
23032
24314
  const shouldRetry = await this.shouldRetry(response);
23033
- if (retriesRemaining && shouldRetry) {
24315
+ if (retriesRemaining && shouldRetry && !hasStreamingBody) {
23034
24316
  const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
23035
24317
  await CancelReadableStream(response.body);
23036
24318
  loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
@@ -23043,7 +24325,7 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
23043
24325
  }));
23044
24326
  return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
23045
24327
  }
23046
- const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
24328
+ const retryMessage = shouldRetry ? hasStreamingBody ? `error; streaming body cannot be retried` : `error; no more retries left` : `error; not retryable`;
23047
24329
  loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
23048
24330
  const errText = await response.text().catch((err) => castToError(err).message);
23049
24331
  const errJSON = safeJSON(errText);
@@ -23206,19 +24488,25 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
23206
24488
  "OpenAI-Organization": this.organization,
23207
24489
  "OpenAI-Project": this.project
23208
24490
  },
23209
- await this.authHeaders(options, options.__security ?? { bearerAuth: true }),
24491
+ this._provider ? undefined : await this.authHeaders(options, options.__security ?? { bearerAuth: true }),
23210
24492
  this._options.defaultHeaders,
23211
24493
  bodyHeaders,
23212
24494
  options.headers
23213
24495
  ]);
23214
- this.validateHeaders(headers, options.__security ?? { bearerAuth: true });
24496
+ if (!this._provider) {
24497
+ this.validateHeaders(headers, options.__security ?? { bearerAuth: true });
24498
+ }
23215
24499
  return headers.values;
23216
24500
  }
23217
24501
  _makeAbort(controller) {
23218
24502
  return () => controller.abort();
23219
24503
  }
23220
- buildBody({ options: { body, headers: rawHeaders } }) {
24504
+ buildBody({ options }) {
24505
+ const { body, headers: rawHeaders } = options;
23221
24506
  if (!body) {
24507
+ if (body === undefined && "body" in options) {
24508
+ return { ...__classPrivateFieldGet(this, _OpenAI_encoder, "f").call(this, { body, headers: buildHeaders([rawHeaders]) }), isStreamingBody: false };
24509
+ }
23222
24510
  return { bodyHeaders: undefined, body: undefined, isStreamingBody: false };
23223
24511
  }
23224
24512
  const headers = buildHeaders([rawHeaders]);
@@ -23297,18 +24585,19 @@ var init_client = __esm(() => {
23297
24585
  init_fine_tuning();
23298
24586
  init_graders2();
23299
24587
  init_realtime2();
23300
- init_responses();
24588
+ init_responses2();
23301
24589
  init_skills();
23302
24590
  init_uploads3();
23303
24591
  init_vector_stores();
23304
24592
  init_webhooks();
23305
24593
  init_detect_platform();
23306
24594
  init_headers();
24595
+ init_provider();
23307
24596
  init_env();
23308
24597
  init_log();
23309
24598
  init_values();
23310
24599
  _a2 = OpenAI2, _OpenAI_encoder = new WeakMap, _OpenAI_instances = new WeakSet, _OpenAI_baseURLOverridden = function _OpenAI_baseURLOverridden() {
23311
- return this.baseURL !== "https://api.openai.com/v1";
24600
+ return this._provider !== undefined || this.baseURL !== "https://api.openai.com/v1";
23312
24601
  };
23313
24602
  OpenAI2.OpenAI = _a2;
23314
24603
  OpenAI2.DEFAULT_TIMEOUT = 600000;
@@ -23327,6 +24616,7 @@ var init_client = __esm(() => {
23327
24616
  OpenAI2.UnprocessableEntityError = UnprocessableEntityError;
23328
24617
  OpenAI2.InvalidWebhookSignatureError = InvalidWebhookSignatureError;
23329
24618
  OpenAI2.toFile = toFile;
24619
+ OpenAI2.toStreamingFile = toStreamingFile;
23330
24620
  OpenAI2.Completions = Completions2;
23331
24621
  OpenAI2.Chat = Chat;
23332
24622
  OpenAI2.Embeddings = Embeddings;
@@ -23343,7 +24633,7 @@ var init_client = __esm(() => {
23343
24633
  OpenAI2.Batches = Batches;
23344
24634
  OpenAI2.Uploads = Uploads;
23345
24635
  OpenAI2.Admin = Admin;
23346
- OpenAI2.Responses = Responses;
24636
+ OpenAI2.Responses = Responses2;
23347
24637
  OpenAI2.Realtime = Realtime2;
23348
24638
  OpenAI2.Conversations = Conversations;
23349
24639
  OpenAI2.Evals = Evals;
@@ -23372,6 +24662,16 @@ var init_azure = __esm(() => {
23372
24662
  ]);
23373
24663
  });
23374
24664
 
24665
+ // node_modules/openai/bedrock.mjs
24666
+ var init_bedrock = __esm(() => {
24667
+ init_error2();
24668
+ init_client();
24669
+ init_headers();
24670
+ init_utils2();
24671
+ init_ResponsesParser();
24672
+ init_resources();
24673
+ });
24674
+
23375
24675
  // node_modules/openai/index.mjs
23376
24676
  var init_openai2 = __esm(() => {
23377
24677
  init_client();
@@ -23381,6 +24681,7 @@ var init_openai2 = __esm(() => {
23381
24681
  init_pagination();
23382
24682
  init_error();
23383
24683
  init_azure();
24684
+ init_bedrock();
23384
24685
  });
23385
24686
 
23386
24687
  // node_modules/oauth4webapi/build/index.js
@@ -23436,7 +24737,7 @@ var USER_AGENT, ERR_INVALID_ARG_VALUE = "ERR_INVALID_ARG_VALUE", ERR_INVALID_ARG
23436
24737
  var init_build = __esm(() => {
23437
24738
  if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
23438
24739
  const NAME = "oauth4webapi";
23439
- const VERSION = "v3.8.5";
24740
+ const VERSION = "v3.8.8";
23440
24741
  USER_AGENT = `${NAME}/${VERSION}`;
23441
24742
  }
23442
24743
  allowInsecureRequests = Symbol();
@@ -23895,7 +25196,7 @@ function noteEmbeddingSuccess() {
23895
25196
  const report = (what) => (err) => {
23896
25197
  console.error(`[memory] ${what} backfill after embeddings recovered failed:`, err.message);
23897
25198
  };
23898
- backfill2 = import("./embedding-space-zsdw37bb.js").then(({ runEmbeddingMaintenance }) => runEmbeddingMaintenance({ backfill: true })).catch(report("Embedding")).finally(() => {
25199
+ backfill2 = import("./embedding-space-0p921zt3.js").then(({ runEmbeddingMaintenance }) => runEmbeddingMaintenance({ backfill: true })).catch(report("Embedding")).finally(() => {
23899
25200
  backfill2 = null;
23900
25201
  });
23901
25202
  }
@@ -26489,7 +27790,7 @@ async function loadSecretRegistry() {
26489
27790
  result.failed += 1;
26490
27791
  }
26491
27792
  try {
26492
- const { loadRuntimeControllerSecrets } = await import("./db-gd81d68c.js");
27793
+ const { loadRuntimeControllerSecrets } = await import("./db-8xs2js3s.js");
26493
27794
  const loaded = await loadRuntimeControllerSecrets();
26494
27795
  result.runtimeController = loaded.count;
26495
27796
  result.failed += loaded.failed;
@@ -26650,7 +27951,7 @@ async function requestSteering(args) {
26650
27951
  }
26651
27952
  const requestedMode = args.mode ?? "queue";
26652
27953
  const onUnsupported = args.onUnsupported ?? "degrade";
26653
- const { dispatchPre, extensionIdForAgent } = await import("./dispatcher-76as8w2t.js");
27954
+ const { dispatchPre, extensionIdForAgent } = await import("./dispatcher-v7drd034.js");
26654
27955
  const preSteer = await dispatchPre("pre.task.steer", {
26655
27956
  task,
26656
27957
  message: args.message,
@@ -28800,10 +30101,10 @@ async function createTaskExtended2(task, options) {
28800
30101
  vcsProvider, vcsRepo, vcsEventType, vcsNumber, vcsCommentId, vcsAuthor, vcsUrl,
28801
30102
  vcsInstallationId, vcsNodeId,
28802
30103
  agentmailInboxId, agentmailMessageId, agentmailThreadId,
28803
- mentionMessageId, mentionChannelId, dir, parentTaskId, dispatchedByTaskId, model, modelTier, effort, profile, fallbackHops, scheduleId,
30104
+ mentionMessageId, mentionChannelId, dir, parentTaskId, dispatchedByTaskId, model, modelTier, effort, profile, modelGroup, fallbackHops, scheduleId,
28804
30105
  workflowRunId, workflowRunStepId, outputSchema, followUpConfig, requestedByUserId, requestedByUserIdInherited, contextKey, routingAffinity, swarmVersion, createdAt, lastUpdatedAt, created_by, updated_by, isHumanFree,
28805
30106
  sourceStepId, sourceScriptRunId
28806
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`, [
30107
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`, [
28807
30108
  id,
28808
30109
  insertKey,
28809
30110
  options?.agentId ?? null,
@@ -28846,6 +30147,7 @@ async function createTaskExtended2(task, options) {
28846
30147
  options?.modelTier ?? null,
28847
30148
  options?.effort ?? null,
28848
30149
  options?.profile?.trim() || null,
30150
+ options?.modelGroup?.trim() || null,
28849
30151
  options?.fallbackHops?.length ? JSON.stringify(options.fallbackHops) : null,
28850
30152
  options?.scheduleId ?? null,
28851
30153
  options?.workflowRunId ?? null,
@@ -28914,7 +30216,7 @@ async function createTaskExtended2(task, options) {
28914
30216
  priority: row.priority
28915
30217
  }, (task) => task !== null, row.requestedByUserId);
28916
30218
  getDbClient2().afterCommit(() => {
28917
- import("./event-bus-tvf2grf4.js").then(({ workflowEventBus }) => {
30219
+ import("./event-bus-pawddp92.js").then(({ workflowEventBus }) => {
28918
30220
  workflowEventBus.emit("task.created", {
28919
30221
  taskId: row.id,
28920
30222
  task: row.task,
@@ -28996,7 +30298,7 @@ async function releaseTask2(taskId, wakeSnapshot) {
28996
30298
  } catch {}
28997
30299
  if (isRuntimePoolsEnabled() && !wakeSnapshot)
28998
30300
  getDbClient2().afterCommit(() => {
28999
- import("./event-bus-tvf2grf4.js").then(({ workflowEventBus }) => workflowEventBus.emit("task.unassigned", { taskId })).catch((error) => console.error("[db] Routing event failed:", scrubSecrets(String(error))));
30301
+ import("./event-bus-pawddp92.js").then(({ workflowEventBus }) => workflowEventBus.emit("task.unassigned", { taskId })).catch((error) => console.error("[db] Routing event failed:", scrubSecrets(String(error))));
29000
30302
  });
29001
30303
  }
29002
30304
  return row ? rowToAgentTask(row) : null;
@@ -29066,7 +30368,7 @@ async function rejectTask2(taskId, agentId, reason) {
29066
30368
  } catch {}
29067
30369
  if (isRuntimePoolsEnabled())
29068
30370
  getDbClient2().afterCommit(() => {
29069
- import("./event-bus-tvf2grf4.js").then(({ workflowEventBus }) => workflowEventBus.emit("task.unassigned", { taskId })).catch((error) => console.error("[db] Routing event failed:", scrubSecrets(String(error))));
30371
+ import("./event-bus-pawddp92.js").then(({ workflowEventBus }) => workflowEventBus.emit("task.unassigned", { taskId })).catch((error) => console.error("[db] Routing event failed:", scrubSecrets(String(error))));
29070
30372
  });
29071
30373
  }
29072
30374
  return row ? rowToAgentTask(row) : null;
@@ -30450,6 +31752,7 @@ function rowToScheduledTask(row) {
30450
31752
  model: row.model ?? undefined,
30451
31753
  modelTier: parseModelTier(row.modelTier) ?? undefined,
30452
31754
  profile: row.profile ?? undefined,
31755
+ modelGroup: row.modelGroup ?? undefined,
30453
31756
  scheduleType: row.scheduleType,
30454
31757
  targetType: row.targetType,
30455
31758
  workflowId: row.workflowId ?? undefined,
@@ -30540,11 +31843,11 @@ async function createScheduledTask2(data) {
30540
31843
  id, "key", name, description, cronExpression, intervalMs, taskTemplate,
30541
31844
  taskType, tags, priority, targetAgentId, enabled, nextRunAt,
30542
31845
  createdByAgentId, parentTaskId, requestedDelayMs, requestedRunAt,
30543
- timezone, model, modelTier, profile, scheduleType,
31846
+ timezone, model, modelTier, profile, modelGroup, scheduleType,
30544
31847
  targetType, workflowId, scriptName, scriptArgs, params, requiredParams, requires,
30545
31848
  createdAt, lastUpdatedAt,
30546
31849
  created_by, updated_by, updatedByAgentId
30547
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`, [
31850
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`, [
30548
31851
  id,
30549
31852
  normalizeAssetKey(data.key ?? defaultAssetKey("schedule", id)),
30550
31853
  data.name,
@@ -30566,6 +31869,7 @@ async function createScheduledTask2(data) {
30566
31869
  data.model ?? null,
30567
31870
  data.modelTier ?? null,
30568
31871
  data.profile ?? null,
31872
+ data.modelGroup ?? null,
30569
31873
  data.scheduleType ?? "recurring",
30570
31874
  data.targetType ?? "agent-task",
30571
31875
  data.workflowId ?? null,
@@ -30667,6 +31971,10 @@ async function updateScheduledTask2(id, data) {
30667
31971
  updates.push("profile = ?");
30668
31972
  params.push(data.profile);
30669
31973
  }
31974
+ if (data.modelGroup !== undefined) {
31975
+ updates.push("modelGroup = ?");
31976
+ params.push(data.modelGroup);
31977
+ }
30670
31978
  if (data.scheduleType !== undefined) {
30671
31979
  updates.push("scheduleType = ?");
30672
31980
  params.push(data.scheduleType);
@@ -30729,7 +32037,7 @@ async function deleteScheduledTask2(id) {
30729
32037
  const parent = await getTaskById2(deferred.parentTaskId);
30730
32038
  if (!parent?.deferredAt)
30731
32039
  return;
30732
- const { createWorkerTaskFollowUp } = await import("./worker-follow-up-fg48vk6d.js");
32040
+ const { createWorkerTaskFollowUp } = await import("./worker-follow-up-gbaz2ydz.js");
30733
32041
  await createWorkerTaskFollowUp({
30734
32042
  task: parent,
30735
32043
  status: "failed",
@@ -35102,7 +36410,7 @@ var init_db4 = __esm(() => {
35102
36410
  configureAgentDependencies({
35103
36411
  createLogEntry: (entry) => createLogEntry2(entry),
35104
36412
  installSystemDefaultSkillsForAgent: (agentId) => installSystemDefaultSkillsForAgent2(agentId),
35105
- resolvePendingImportAssignments: async (agent) => (await import("./pending-2sxh1t6j.js")).resolvePendingImportAssignments(agent)
36413
+ resolvePendingImportAssignments: async (agent) => (await import("./pending-xgv316w0.js")).resolvePendingImportAssignments(agent)
35106
36414
  });
35107
36415
  configureTaskWriteDependencies({
35108
36416
  createLogEntry: (...args) => createLogEntry2(...args),
@@ -35152,4 +36460,4 @@ var init_db4 = __esm(() => {
35152
36460
  };
35153
36461
  });
35154
36462
 
35155
- export { auditAssetKeys, init_asset_key_audit, CredentialBindingSchema, placeholderForConfigKey, CredentialBroker, defaultCredentialBindings, isPrivateAddress, assertUrlSafe, EgressDeniedError, createGuardedFetch, createSsrfGuardedFetch, parseEgressAllowlist, init_egress_guard, init_credential_broker, encryptSecret, decryptSecret, init_secrets_cipher, getEncryptionKey, init_key_bootstrap, init_crypto, withLoopPath, bindLoopPath, startEventLoopLagProbe, stopEventLoopLagProbe, init_event_loop_lag, DbTransactionDeadlineError, isInTransaction, init_db_client, breaksJsonValidity, scrubJsonValue, foldHexCopies, init_scrub_json, sealJson, openSealedJson, init_sealed_json, getPromptTemplateDefaultDrift, init_default_drift, init_templates2, init_templates3, wasDbCreatedThisBoot, isSqliteVecAvailable2, resolveSqliteVecExtensionPath2, __resetSqliteVecExtensionPathCacheForTests2, initDb2, getDb2, closeDb2, getDbClient2, init_runtime2, SessionCostConflictError2, insertSessionCost2, slackContextKey, chatSdkContextKey, chatThreadOfContextKey, agentmailContextKey, githubContextKey, gitlabContextKey, azureDevOpsContextKey, azureDevOpsWorkItemContextKey, bitbucketContextKey, linearContextKey, buildJiraContextKey, scheduleContextKey, workflowContextKey, agentContextKey, pageContextKey, APP_SESSION_KEY_PATTERN, appSessionContextKey, init_context_key, sessionSourceKey, sourceOfKey, SOURCE_GROUPS_READ_ONLY, sourceMoveError, init_source_key, TaskCreationBlockedError, TaskRoutingAuthorizationError, init_errors2, checkSlackRoutingCoherence, init_slack_routing, init_catalog, catalog_default, COMPANY_TEAM_SIZES, COMPANY_USE_CASES, USER_FUNCTIONS, reportedUseCase, reportedUserFunction, init_company_profile, mapTriggerSurface, init_telemetry_context, TELEMETRY_PROXY_ORIGIN, normalizeOrgWebsite, orgLogoUrl, isFilledOrgLogoUrl, init_org_website, beginRequestAuthScope, setRequestAuth, getRequestAuth, getCurrentRequestAuth, runWithoutRequestAuth, authUserId, authUser, isOperatorAuth, getCurrentRequestUserId, getCurrentRunProvenance, init_request_auth_context, setTelemetryIngestObserver, isTelemetryEnabled, _resolveIntegrationType, _resolveIntegrationProvider, initTelemetry, setTelemetryRoleResolver, setTelemetryFunctionResolver, isTelemetryReady, track, trackRelayed, telemetry, emitIntegrationConnected, init_telemetry, isRbacEnabled, decideAdmission, decideToolAdmission, grantLeadEquivalence, revokeLeadEquivalence, init_elevated_agents, LEGACY_RULES, setAuditSink, clearAuditSink, can, init_can, PermissionVerbSchema, init_rbac, randomChars, init_short_id, CHAT_SDK_ADAPTER_NAMES, CHAT_SDK_ADAPTER_SCHEMAS, ChatSdkAdaptersDraftSchema, firstIssueText, isAdapterEntryEnabled, init_schema, TELEMETRY_RANKING_KEY, PUBLIC_RANKING_ENABLED_KEY, RANKING_CATEGORIES, readTelemetryRanking, rankingFormSchema, buildListing, init_telemetry_ranking, resolveQuickJSPoolSize, init_quickjs_pool_config, SLACK_REACTION_DEFAULTS, SLACK_REACTION_CONFIG_KEYS, reactionName, isSlackIconConfigKey, reactionStatusIcon, iconPrefix, completedStatusIcon, init_reaction_shortcode, UI_SPEC_SCRIPT_ACTIONS_KEY, parseScriptActionAllowlist, init_script_allowlist, API_DRAINING_HEADER, API_DRAIN_MAX_MS_LIMIT, isApiDrainingResponse, init_api_drain2, isEnvExportRestrictedKey, init_config_env_export, isValidTimezone, formatDeferralDateTime, init_deferral_time, parseEnabledTools, init_enabled_tools, parseFollowUpGateScheduleIds, isFollowUpGateScheduleId, init_follow_up_gate_schedule_ids, parseTaskToolManifest, CHAT_TASK_ONLY_TOOLS, isChatSdkTask, selectTaskTools, init_task_tool_manifest, tierConfigKey, init_model_tier_keys, isApiOnlyConfigKey, isInternalConfigKey, internalConfigKeyError, isHumanOnlyConfigKey, humanOnlyConfigKeyError, humanOnlyConfigKeyPageError, isReservedConfigKey, reservedKeyError, MAX_DB_RETENTION_DAYS, DB_RETENTION_TUNING_BOUNDS, APPS_JSON_COLUMN_MAX_BYTES_BOUNDS, APPS_DEFINITION_LIMIT_BOUNDS, CODEX_OAUTH_KEEP_WARM_MAX_AGE_HOURS_BOUNDS, SCHEDULER_INTERVAL_MS_BOUNDS, validateRuntimeTokenTtlHours, validateControllerTokenTtlDays, validateControllerGraceSec, validateConfigValue, validateConfigEntry, validateExportToEnv, init_swarm_config_guard, cachedUserRole, cachedUserFunction, invalidateTelemetryUserRole, configureOrgDomainPersistence, recomputeOrgDomain, scheduleOrgDomainRecompute, init_telemetry_identity, resolveTriggerSurface, emitTaskTelemetry, init_telemetry_trigger, MASKED_SECRET_VALUE, init_config_secrets, HeartbeatExpiryError, init_heartbeat_expiry, isEffectiveOutputSchema, init_output_schema, isRuntimePoolsEnabled, init_runtime_pools_flag, normalizeDate, normalizeDateRequired, init_date_utils, rowToAgent, updateAgentCredentialState2, updateAgentCredentialMissing2, AgentDeletedError2, isAgentDeleted2, createAgent2, getAgentById2, EXTENSION_AGENT_ROLE2, NOT_EXTENSION_AGENT_SQL2, isExtensionAgent2, extensionAgentAssignmentError2, ReservedAgentRoleError2, reservedRoleViolation2, ExtensionAgentAssignmentError2, getAllAgents2, getAgentStatusCounts2, getLeadAgent2, updateAgentStatus2, updateAgentMaxTasks2, updateAgentProvider2, setAgentHarnessProvider2, updateAgentCredStatus2, listAgentsWithCredStatusByProvider2, getAgentHarnessProviders2, updateAgentActivity2, MAX_EMPTY_POLLS2, incrementEmptyPollCount2, resetEmptyPollCount2, shouldBlockPolling2, deleteAgent2, getActiveTaskCount2, hasCapacity2, getRemainingCapacity2, updateAgentStatusFromCapacity2, isPoolAffinityEnforcementEnabled2, buildRoutingAffinityFromAgent2, isAgentEligibleForTask2, getAgentDailyTaskCounts2, init_agents, closeSlackTreeIfSettled, getSlackThreadsOfTasks, slackThreadHasBotReplySince, slackThreadHasAgentReplyOnTasksSince, slackThreadHasOutcomeWork, observeSlackTreeVisibility, getSlackProcessingThreads, init_slack_trees, WorkflowReplayStateError, init_workflow_replay, getWorkflowRunTriggeredByAgentId, getWorkflowRunSummary, getWorkflowRunStepsSlimByRunId, WORKFLOW_RUN_TREE_MAX_DEPTH, WorkflowRunTreeError, getRunLineageBlock, getWorkflowRunTreeIds, getWorkflowRunStatus, getOpenWorkflowTreeTaskIds, getTaskIdsWithDependents, workflowRunTreeHasOpenWork, getWorkflowRunTree, cancelOpenWorkflowTreeSteps, disarmWorkflowTreeRetries, cancelLiveWorkflowTreeRuns, getChildWorkflowRunId, isParentStepAttemptCurrent, getRunningSubWorkflowSteps, getWorkflowRunParent, getWorkflowRunLineage, getSettledChildRunParentSteps, emitRunFinished, createForeachChildSteps, createForeachAttemptSteps, init_workflow_runs, OpenAI2, init_openai2, generateRandomCodeVerifier, generateRandomState, calculatePKCECodeChallenge, init_build, isInvalidClientError, publicEndpointSsrfOptions, mcpOAuthSsrfOptions, discoverProtectedResourceMetadata, discoverAuthorizationServerMetadata, normalizeTokenEndpointAuthMethod, resolveAdvertisedTokenEndpointAuthMethod, authMethodForStoredClient, selectDcrTokenEndpointAuthMethod, registerClient, buildAuthorizeUrl, exchangeCodeForTokens, refreshMcpToken, revokeMcpToken, computeExpiresAt, init_mcp_wrapper, LEARNING_TTL_DAYS, LEARNING_DUPLICATE_MIN_SIMILARITY, CANDIDATE_SET_MULTIPLIER, isGraphExpansionEnabled, EMBEDDING_DIMENSIONS, init_constants2, LONGTERM_ROOT, LEARNINGS_ROOT, MEMORY_KEY_PATTERN, MEMORY_KEY_PATTERN_MESSAGE, MEMORY_KEY_MAX_LENGTH, isLongtermKey, longtermKeyError, isConsolidatedKey, consolidatedKeyMessage, resolveStoreKey, init_key_paths, computeScore, rerank, init_reranker, isReviewTaskId, dropReviewTaskCompletions, init_review_recall_filter, searchMemoryCandidates, init_search_candidates, memorySearchReader, init_search_reader, rowToCandidate, init_sqlite_store, getEmbeddingProvider2, resetEmbeddingProvider2, getMemoryStore2, setDeploymentEnvReader2, embeddingEndpoint2, init_memory, embeddingProvider2, computeScriptEmbedding2, writeScriptEmbedding2, embedScript2, searchScripts2, reembedAllScripts2, init_embeddings, upsertScriptByName, getScript, getGlobalScriptContentHashes, getScriptById, getScriptVersion, listScripts, listScriptVersions, deleteScript, touchScratchScriptLastUsed, restoreScratchScriptLastUsedIfUnchanged, createScriptApi, listScriptApisForScript, getScriptApiById, getScriptApiSecret, updateScriptApi, rotateScriptApiSecret, deleteScriptApi, recordScriptApiUsage, init_db3, oauthSecretName, registerStoredSecret, loadSecretRegistry, init_secret_registry, getDefaultAuthorizationIdForProvider, getOAuthApp, getOAuthAppById, getOAuthAppIdByProvider, createOAuthApp, updateOAuthAppById, upsertOAuthApp, listAuthorizationsForApp, getAuthorizationById, upsertAuthorization, updateAuthorizationTokens, updateAuthorizationIdentity, deleteAuthorizationById, deleteAuthorizationsForApp, createOAuthPending, consumeOAuthPending, gcOAuthPending, markAuthorizationRefreshFailed, hasOAuthTokens, getOAuthTokens, listAuthorizationSweepRows, listKeepAliveAuthorizations, deleteOAuthTokens, acquireOAuthRefreshLock, releaseOAuthRefreshLock, init_oauth, normalizeVcsRepo, vcsRepoName, vcsRepoUrlMatches, init_vcs_repo_match, taskModelPin, resumedTaskModelSelection, init_model_pin, normalizeModelKey, init_pricing_normalize, buildModelsDevSeedRows, seedPricingFromModelsDev, init_seed_pricing, buildCatalogEntries, replaceModelCatalog, touchModelCatalogCheckedAt, countModelCatalog, getModelCatalogMeta, updateModelCatalogMeta, upsertModelCatalogOverlay, deleteModelCatalogOverlay, expireMatchedOverlays, applyOverlayPricingRows, reloadModelsCatalog, loadModelsCatalog, init_model_catalog_store, listHarnessModelSupport, recordHarnessModelSupport, agentRanModel, getAgentHarnessCliVersion, setAgentHarnessCliVersion, init_harness_model_support, sanitizeModelTierOverrides, parseModelTierOverridesHeader, modelTierOverridesDiffer, setAgentModelTierOverrides, previewModelTiers, recordClaimModelResolution, init_model_tier_resolution, harnessModelErrorFor, poolTaskRunsOnHarness, explicitModelError, explicitModelErrorForAgent, init_model_validation2, runtimeReadsRepoSecrets, vcsRepoId, configPools, checkProfileForAgent, formatProfileCheckFailures, init_model_profile_check, startTaskSearchBackfill, stopTaskSearchBackfill, init_search_index, rowToAgentTask, getTaskById2, getChildTasks2, TASK_LINEAGE_LIMITS2, getTaskLineage2, hasNonTerminalResumeChild2, SUPERSEDED_RESUME_REPAIR_WINDOW_MS2, getSupersededTasksWithoutResume2, getSupersededTasksWithUnsettledDependents2, hasNonTerminalRerouteDecisionChild2, getTasksByAgentId2, getTasksDispatchedFrom2, getAgentCurrentTask2, getTasksByStatus2, findTaskByVcs2, findActiveTasksByVcs2, findTaskByGitHub2, readableSessionCondition, getAllTasks2, getTasksCount2, getTaskStats2, getCompletedSlackTasks2, getPendingSlackRelayTasks2, markSlackRelayAttempted2, markSlackRelayDelivered2, markFinalizedSlackRelaysDelivered2, getPendingChatRelayTasks2, giveUpStaleChatRelays2, markChatRelayAttempted2, recordChatRelayError2, markChatRelayDelivered2, markChatRelayGivenUp2, getRecentlyFinishedWorkerTasks2, markTasksNotified2, resetTasksNotified2, getInProgressSlackTasks2, getSlackTasksMissingTree2, getInProgressTasksByContextKey2, isLinearTrackerContextKey2, findExistingLinearTrackerContextWork2, getLatestTaskByContextKey2, getLatestScriptRunStepTaskByContextKey2, getAgentWorkingOnThread2, getLatestActiveTaskInThread2, getLatestLeadTaskInThread2, getAgentWorkingOnContextKey2, getLatestTaskByContextKeyPrefix2, getLatestActiveTaskByContextKey2, getLatestLeadTaskByContextKey2, getFirstTaskInThread2, getMostRecentTaskInThread2, findCompletedTasksInThread2, findRecentFailedTaskInThread2, countAgentDispatchesInThread2, findRecentCancelledTaskInThread2, init_read, MODEL_PROFILE_CONFIG_KEY, hasUnreadableCredentialAllowlist, listModelProfiles, getModelProfileByName, createModelProfile, updateModelProfile, TASK_HOLDS_PROFILE_SQL, repairWindowStart, modelProfileReferences, modelProfileRefError, isModelNameTakenError, deleteModelProfile, MAX_MODEL_PROFILE_FALLBACKS, modelProfileFallbacksError, taskProfileError, scheduleProfileUpdate, init_model_profiles, SESSION_ACTIVITY_REFRESH_MIN_INTERVAL_MS2, refreshActiveSessionOnActivity2, getActiveSessionById, init_active_sessions, STEERING_MOVED_ERROR, SteeringRequestError, SteeringBlockedError, isSteeringEnabled, getTaskSteeringFields, getTaskSteeringFieldsForTasks, promotePendingSteeringForTask, markSteeringUndeliverable, carryUnhandledSteering, requestSteering, init_steering2, onTaskStarted, init_task_lifecycle_events, listApprovalRequestSummaries2, getPendingApprovalVoteState2, recordApprovalVotes2, getPendingApprovalsForTasks2, approvalCancellationNotificationKey, listUndeliveredCancelledApprovalRequestIds, init_approvals, computeContentHash2, createContextVersion2, getLatestContextVersion2, getContextVersion2, getContextVersionHistory2, AssetKeyMovesBlockedError2, assertAssetKeyMovesAllowed2, moveTaskChainKeyInTx2, moveSessionChains, moveKeyFavorites, listPrefixRoots, listSharedPrefixRoots, init_session_moves, getSessionGroupKey, sessionSummaryQuery, getSessionReadState, getSessionTree, triageSessionList, init_session_tree, setHumanFreeQueueListener, reclassifyTaskHumanFree, drainHumanFreeReclassifyQueue, init_human_free, channelTopic, addWorkerSubscription, removeWorkerSubscription, listSubscribedWorkerAgents, init_channels, publishWorkerNudge, init_worker_nudges, createTask2, getPendingTaskForAgent2, assignUnassignedTaskPending2, startTask2, updateTaskClaudeSessionId2, recordTaskProviderIfUnset2, updateTaskTitle2, updateTaskTags2, setTaskTitleIfUnset2, completeTask2, failTask2, overwriteTerminalTaskResultText2, cancelTask2, skipTask2, supersedeTask2, markWorkflowStepTaskSuperseded2, settleSupersededTaskDependents2, backfillSupersedeTaskResumeTaskId2, pauseTask2, resumeTask2, getPausedTasksForAgent2, getOrphanedInProgressTasksForAgent2, resetOrphanedInProgressTasksForAgent2, getRecentlyCancelledTasksForAgent2, deleteTask2, updateTaskProgress2, init_write, quoteSqlIdentifier, USER_REFERENCE_COLUMNS_SQL, userReferenceRewriteSql, WORKFLOW_CONTEXT_REQUESTER_SQL, init_user_references, IdempotencyKeyTakenError, sha256, workflowRequestFingerprint, requestFingerprint, findAcceptedWorkflowOperation, assertWorkflowIdempotencyKeyUnused, recordAcceptedWorkflowOperation, init_workflow_idempotency, PINNED_WORKFLOW_KEYS2, toPinnedDefinition2, pinWorkflowDefinition2, getRunWorkflow2, deleteOrphanedRunDefinitions, init_workflow_run_definitions, getWorkflowsByEventName2, recordKeySeatMismatch2, recordKeyValidation2, retirePoolKeyStatus, init_api_keys, getScriptRunExecutionArgs2, getScriptRunFollowUpGuard2, setScriptRunFollowUpGuard2, setSkillUpdatedBy2, literalPrefixPattern2, getSlackRenderV2ActivatedAt2, ensureSlackRenderV2Activation2, getSlackDelegationActivatedAt2, ensureSlackDelegationActivation2, isPendingSlackMessage2, isSettledSlackMessage2, recordSlackMessage2, reserveSlackMessage2, bindSlackMessageTimestamp2, updateSlackMessageRecord2, markSlackTreeRendered2, deleteSlackMessageRecord2, getSlackTreeMessage2, getSlackTreeMessageByThread2, getSlackOutcomeMessage2, getResolvableDeferralOutcomes2, markSlackDeferralResolved2, noteSlackOutcomeDeliveryFailure2, abandonSlackOutcomeDelivery2, getSlackTreeMessages2, getSlackMessageByChannelTs2, getSlackTasksInThread2, listSlackThreadsAwaitingHuman2, isSlackThreadAwaitingHuman2, markTaskSlackReplySent2, setSlackMessageTracking2, updateTaskVcs2, insertTaskAttachment2, recordTaskPullRequestAttachments2, getAssetKeyMappingByProvider2, upsertAssetKeyMapping2, getAssetKeyMapping2, listAssetSummaries2, moveAssetKey2, deleteTaskAttachment2, replaceTaskAttachment2, getTaskAttachments2, createSteeringMessage2, getSteeringMessagesForTask2, getSteeringMessageById2, getPendingSteeringForTask2, getPendingSteeringForAgent2, markSteeringDelivered2, markSteeringHandled2, markSteeringPromoted2, cancelPendingSteeringForTask2, hasPendingSteering2, getAgentWithTasks2, getAllAgentsWithTasks2, createLogEntry2, getLogsByAgentId2, getLogsByTaskId2, getLogsByTaskIdAndEventType2, getLogsByTaskIdChronological2, getLogsByEventType2, getAllLogs2, findRecentSimilarTasks2, createTaskExtended2, claimTask2, releaseTask2, acceptTask2, rejectTask2, moveTaskToBacklog2, moveTaskFromBacklog2, promoteDraftTask2, refreshDraftTaskLease2, promoteAbandonedDraftTasks2, releaseStaleReviewingTasks2, releaseStaleOfferedTasksForOfflineAgents2, getOfferedTasksForAgent2, claimOfferedTask2, getUnassignedTasksCount2, getUnassignedTaskIds2, getUnassignedTaskIdsForAgent2, checkDependencies2, getDependentTasks2, cascadeFailDependents2, updateAgentProfile2, updateAgentName2, createChannel2, getMessageById2, getChannelById2, getChannelByName2, getAllChannels2, deleteChannel2, postMessage2, getChannelMessages2, updateReadState2, getLastReadAt2, getUnreadMessages2, getMentionsForAgent2, getInboxSummary2, claimMentions2, releaseMentionProcessing2, releaseStaleMentionProcessing2, createService2, getServiceById2, getServiceByAgentAndName2, getServicesByAgentId2, getAllServices2, updateServiceStatus2, deleteService2, upsertService2, deleteServicesByAgentId2, createSessionLogs2, getSessionLogsByTaskId2, getSessionLogsBySession2, createSessionCost2, getSessionCostsByTaskId2, getSessionCostsByAgentId2, getAllSessionCosts2, getSessionCostsFiltered2, UNATTRIBUTED_USER_ID2, getSessionCostSummary2, getAttributionByPerson2, getDashboardCostSummary2, createInboxMessage2, getInboxMessageById2, getUnreadInboxMessages2, claimInboxMessages2, markInboxMessageRead2, markInboxMessageResponded2, markInboxMessageDelegated2, releaseStaleProcessingInbox2, getConcurrentContext2, getScheduledTasks2, getScheduledTaskById2, getScheduledTaskByName2, createScheduledTask2, updateScheduledTask2, deleteScheduledTask2, getDueScheduledTasks2, autoEncryptLegacyPlaintextSecrets2, maskSecrets2, getSwarmConfigs2, getInjectableGlobalConfigs2, getSwarmConfigById2, getSwarmConfigLookupById2, upsertSwarmConfig2, emitBuiltInIntegrationConnectedOnce2, deleteSwarmConfig2, deleteSwarmConfigByKey2, getResolvedConfig2, getSwarmRepos2, getSwarmRepoById2, getSwarmRepoByName2, getSwarmRepoByUrl2, createSwarmRepo2, updateSwarmRepo2, deleteSwarmRepo2, getAgentMailInboxMapping2, getAgentMailInboxMappingsByAgent2, getAllAgentMailInboxMappings2, createAgentMailInboxMapping2, deleteAgentMailInboxMapping2, findTaskByAgentMailThread2, insertActiveSession2, deleteActiveSession2, deleteActiveSessionById2, getActiveSessions2, heartbeatActiveSession2, cleanupStaleSessions2, cleanupAgentSessions2, updateActiveSessionProviderSessionId2, getActiveSessionForTask2, reassociateSessionLogs2, getStalledInProgressTasks2, getStalePinnedResumes2, failPendingResumeIfUnclaimed2, getIdleWorkersWithCapacity2, getUnassignedPoolTasks2, getStaleUnassignedAffinityTasks2, getRecentFailedTasks2, getRecentCompletedCount2, getRecentFailedCount2, createWorkflow2, getWorkflow2, listWorkflows2, updateWorkflow2, deleteWorkflow2, getWorkflowsByScheduleId2, createWorkflowRun2, getWorkflowRun2, updateWorkflowRun2, listWorkflowRuns2, countWorkflowRuns2, listWorkflowRunsPage2, createWorkflowRunStep2, getWorkflowRunStep2, updateWorkflowRunStep2, getWorkflowRunStepsByRunId2, getStuckWorkflowRuns2, getLastSuccessfulRun2, getLastRunStart2, getRetryableSteps2, getCompletedStepNodeIds2, getTaskByWorkflowRunStepId2, detachTaskFromWorkflowRunStep2, getStepByIdempotencyKey2, getStepCountForNode2, getLatestStepForNode2, getCurrentStepForNode2, createWorkflowVersion2, getWorkflowVersions2, getWorkflowVersion2, createAppVersion2, getAppVersions2, getAppVersion2, createPage2, getPage2, getPageBySlug2, getLatestPageBySlug2, listPagesByAgent2, listAllPages2, countAllPages2, countPagesByAgent2, updatePage2, deletePage2, incrementPageViewCount2, createPageVersion2, getPageVersions2, getPageVersion2, createMetric2, getMetric2, getMetricBySlug2, listMetricsByAgent2, listAllMetrics2, countAllMetrics2, countMetricsByAgent2, updateMetric2, deleteMetric2, createMetricVersion2, getMetricVersions2, getMetricVersion2, getPromptTemplates2, getPromptTemplateById2, upsertPromptTemplate2, deletePromptTemplate2, resetPromptTemplateToDefault2, getPromptTemplateHistory2, resolvePromptTemplate2, checkoutPromptTemplate2, getAllChannelActivityCursors2, getChannelActivityCursor2, upsertChannelActivityCursor2, createApprovalRequest2, getApprovalRequestById2, resolveApprovalRequest2, cancelApprovalRequestById2, cancelPendingApprovalRequestsForRun2, listCancelledApprovalRequestsForRun2, listCancelledApprovalRequestsForStep2, claimApprovalCancellationNotification2, completeApprovalCancellationNotificationClaim2, releaseApprovalCancellationNotificationClaim2, updateApprovalRequestNotifications2, listApprovalRequests2, getStuckApprovalRuns2, getApprovalRequestByStepId2, getExpiredPendingApprovals2, getStaleApprovalRequests2, createWaitState2, getWaitStateById2, getWaitStateByStepId2, getDueWaitStates2, getPendingEventWaitNames2, getPendingWaitsByEvent2, resolveWaitState2, getStuckWaitRuns2, SKILL_FILE_LIMITS2, normalizeSkillFilePath2, createSkill2, updateSkill2, listSkillFileManifest2, getSkillFiles2, getSkillFile2, upsertSkillFile2, upsertSkillFiles2, deleteSkillFile2, deleteSkill2, getSkillById2, getSkillByName2, listSkills2, searchSkills2, installSkill2, getSystemDefaultSkills2, installSystemDefaultSkillsForAgent2, uninstallSkill2, getAgentSkills2, toggleAgentSkill2, createMcpServer2, emitMcpServerConnectedTelemetry2, updateMcpServer2, deleteMcpServer2, getMcpServerById2, getMcpServerByName2, listMcpServers2, installMcpServer2, uninstallMcpServer2, getAgentMcpServers2, createContextSnapshot2, getContextSnapshotsByTaskId2, getContextSnapshotsBySessionId2, getContextSummaryByTaskId2, getAvailableKeyIndices2, recordKeyUsage2, setApiKeyPlan2, markKeyRateLimited2, recordKeyAuthFailure2, recordKeyRateLimitWindows2, setApiKeyName2, clearKeyRateLimit2, getKeyStatuses2, getKeyCostSummary2, getUserById2, getAllUsers2, createUser2, updateUser2, deleteUser2, listInboxState2, upsertInboxState2, listFavorites2, listUserFavorites2, getFavoriteItemIdSet2, setFavorite2, setUserFavorite2, withFavoriteFlags2, listTaskTemplates2, getRootTaskChain2, listRecentSessions2, countSessions2, getBudget2, getBudgets2, upsertBudget2, deleteBudget2, getAllPricingRows2, getPricingRows2, getActivePricingRow2, insertPricingRow2, deletePricingRow2, getDailySpendForAgent2, getDailySpendGlobal2, getDailySpendForUser2, recordBudgetRefusalNotification2, getBudgetRefusalNotification2, getRecentBudgetRefusalNotifications2, hasBudgetRefusalNotificationToday2, setBudgetRefusalFollowUpTaskId2, getLiveAgentCounts2, getReadyAgentCounts2, getInstanceActivity2, getSwarmMetrics2, hasFirstCompletedTask2, getKv2, sweepExpiredKv2, sweepExpiredKvPrefix2, upsertKv2, claimKv2, deleteKv2, KvTypeCollisionError2, incrKv2, kvPrefixUpperBound2, listKv2, countKv2, createScriptRun2, recordInlineScriptRun2, getScriptRun2, getScriptRunByIdempotencyKey2, listScriptRuns2, countScriptRuns2, countActiveScriptRuns2, updateScriptRun2, updateScriptRunIfNotTerminal2, updateScriptRunIfRunning2, getRunningScriptRuns2, getScriptRunJournalStep2, upsertScriptRunJournalStep2, listScriptRunJournalSteps2, countScriptRunJournalSteps2, countScriptRunJournalAgentTaskSteps2, exports_db, init_db4 };
36463
+ export { auditAssetKeys, init_asset_key_audit, CredentialBindingSchema, placeholderForConfigKey, CredentialBroker, defaultCredentialBindings, isPrivateAddress, assertUrlSafe, EgressDeniedError, createGuardedFetch, createSsrfGuardedFetch, parseEgressAllowlist, init_egress_guard, init_credential_broker, encryptSecret, decryptSecret, init_secrets_cipher, getEncryptionKey, init_key_bootstrap, init_crypto, withLoopPath, bindLoopPath, startEventLoopLagProbe, stopEventLoopLagProbe, init_event_loop_lag, DbTransactionDeadlineError, isInTransaction, init_db_client, breaksJsonValidity, scrubJsonValue, foldHexCopies, init_scrub_json, sealJson, openSealedJson, init_sealed_json, getPromptTemplateDefaultDrift, init_default_drift, init_templates2, init_templates3, wasDbCreatedThisBoot, isSqliteVecAvailable2, resolveSqliteVecExtensionPath2, __resetSqliteVecExtensionPathCacheForTests2, initDb2, getDb2, closeDb2, getDbClient2, init_runtime2, SessionCostConflictError2, insertSessionCost2, slackContextKey, chatSdkContextKey, chatThreadOfContextKey, agentmailContextKey, githubContextKey, gitlabContextKey, azureDevOpsContextKey, azureDevOpsWorkItemContextKey, bitbucketContextKey, linearContextKey, buildJiraContextKey, scheduleContextKey, workflowContextKey, agentContextKey, pageContextKey, APP_SESSION_KEY_PATTERN, appSessionContextKey, init_context_key, sessionSourceKey, sourceOfKey, SOURCE_GROUPS_READ_ONLY, sourceMoveError, init_source_key, TaskCreationBlockedError, TaskRoutingAuthorizationError, init_errors2, checkSlackRoutingCoherence, init_slack_routing, init_catalog, catalog_default, COMPANY_TEAM_SIZES, COMPANY_USE_CASES, USER_FUNCTIONS, reportedUseCase, reportedUserFunction, init_company_profile, mapTriggerSurface, init_telemetry_context, TELEMETRY_PROXY_ORIGIN, normalizeOrgWebsite, orgLogoUrl, isFilledOrgLogoUrl, init_org_website, beginRequestAuthScope, setRequestAuth, getRequestAuth, getCurrentRequestAuth, runWithoutRequestAuth, authUserId, authUser, isOperatorAuth, getCurrentRequestUserId, getCurrentRunProvenance, init_request_auth_context, setTelemetryIngestObserver, isTelemetryEnabled, _resolveIntegrationType, _resolveIntegrationProvider, initTelemetry, setTelemetryRoleResolver, setTelemetryFunctionResolver, isTelemetryReady, track, trackRelayed, telemetry, emitIntegrationConnected, init_telemetry, isRbacEnabled, decideAdmission, decideToolAdmission, grantLeadEquivalence, revokeLeadEquivalence, init_elevated_agents, LEGACY_RULES, setAuditSink, clearAuditSink, can, init_can, PermissionVerbSchema, init_rbac, randomChars, init_short_id, CHAT_SDK_ADAPTER_NAMES, CHAT_SDK_ADAPTER_SCHEMAS, ChatSdkAdaptersDraftSchema, firstIssueText, isAdapterEntryEnabled, init_schema, TELEMETRY_RANKING_KEY, PUBLIC_RANKING_ENABLED_KEY, RANKING_CATEGORIES, readTelemetryRanking, rankingFormSchema, buildListing, init_telemetry_ranking, resolveQuickJSPoolSize, init_quickjs_pool_config, SLACK_REACTION_DEFAULTS, SLACK_REACTION_CONFIG_KEYS, reactionName, isSlackIconConfigKey, reactionStatusIcon, iconPrefix, completedStatusIcon, init_reaction_shortcode, UI_SPEC_SCRIPT_ACTIONS_KEY, parseScriptActionAllowlist, init_script_allowlist, API_DRAINING_HEADER, API_DRAIN_MAX_MS_LIMIT, isApiDrainingResponse, init_api_drain2, isEnvExportRestrictedKey, init_config_env_export, isValidTimezone, formatDeferralDateTime, init_deferral_time, parseEnabledTools, init_enabled_tools, parseFollowUpGateScheduleIds, isFollowUpGateScheduleId, init_follow_up_gate_schedule_ids, parseTaskToolManifest, CHAT_TASK_ONLY_TOOLS, isChatSdkTask, selectTaskTools, init_task_tool_manifest, tierConfigKey, init_model_tier_keys, isApiOnlyConfigKey, isInternalConfigKey, internalConfigKeyError, isHumanOnlyConfigKey, humanOnlyConfigKeyError, humanOnlyConfigKeyPageError, isReservedConfigKey, reservedKeyError, MAX_DB_RETENTION_DAYS, DB_RETENTION_TUNING_BOUNDS, APPS_JSON_COLUMN_MAX_BYTES_BOUNDS, APPS_DEFINITION_LIMIT_BOUNDS, CODEX_OAUTH_KEEP_WARM_MAX_AGE_HOURS_BOUNDS, SCHEDULER_INTERVAL_MS_BOUNDS, validateRuntimeTokenTtlHours, validateControllerTokenTtlDays, validateControllerGraceSec, validateConfigValue, validateConfigEntry, validateExportToEnv, init_swarm_config_guard, cachedUserRole, cachedUserFunction, invalidateTelemetryUserRole, configureOrgDomainPersistence, recomputeOrgDomain, scheduleOrgDomainRecompute, init_telemetry_identity, resolveTriggerSurface, emitTaskTelemetry, init_telemetry_trigger, MASKED_SECRET_VALUE, init_config_secrets, HeartbeatExpiryError, init_heartbeat_expiry, isEffectiveOutputSchema, init_output_schema, isRuntimePoolsEnabled, init_runtime_pools_flag, normalizeDate, normalizeDateRequired, init_date_utils, rowToAgent, updateAgentCredentialState2, updateAgentCredentialMissing2, AgentDeletedError2, isAgentDeleted2, createAgent2, getAgentById2, EXTENSION_AGENT_ROLE2, NOT_EXTENSION_AGENT_SQL2, isExtensionAgent2, extensionAgentAssignmentError2, ReservedAgentRoleError2, reservedRoleViolation2, ExtensionAgentAssignmentError2, getAllAgents2, getAgentStatusCounts2, getLeadAgent2, updateAgentStatus2, updateAgentMaxTasks2, updateAgentProvider2, setAgentHarnessProvider2, updateAgentCredStatus2, listAgentsWithCredStatusByProvider2, getAgentHarnessProviders2, updateAgentActivity2, MAX_EMPTY_POLLS2, incrementEmptyPollCount2, resetEmptyPollCount2, shouldBlockPolling2, deleteAgent2, getActiveTaskCount2, hasCapacity2, getRemainingCapacity2, updateAgentStatusFromCapacity2, isPoolAffinityEnforcementEnabled2, buildRoutingAffinityFromAgent2, isAgentEligibleForTask2, getAgentDailyTaskCounts2, init_agents, closeSlackTreeIfSettled, getSlackThreadsOfTasks, slackThreadHasBotReplySince, slackThreadHasAgentReplyOnTasksSince, slackThreadHasOutcomeWork, observeSlackTreeVisibility, getSlackProcessingThreads, init_slack_trees, WorkflowReplayStateError, init_workflow_replay, getWorkflowRunTriggeredByAgentId, getWorkflowRunSummary, getWorkflowRunStepsSlimByRunId, WORKFLOW_RUN_TREE_MAX_DEPTH, WorkflowRunTreeError, getRunLineageBlock, getWorkflowRunTreeIds, getWorkflowRunStatus, getOpenWorkflowTreeTaskIds, getTaskIdsWithDependents, workflowRunTreeHasOpenWork, getWorkflowRunTree, cancelOpenWorkflowTreeSteps, disarmWorkflowTreeRetries, cancelLiveWorkflowTreeRuns, getChildWorkflowRunId, isParentStepAttemptCurrent, getRunningSubWorkflowSteps, getWorkflowRunParent, getWorkflowRunLineage, getSettledChildRunParentSteps, emitRunFinished, createForeachChildSteps, createForeachAttemptSteps, init_workflow_runs, OpenAI2, init_openai2, generateRandomCodeVerifier, generateRandomState, calculatePKCECodeChallenge, init_build, isInvalidClientError, publicEndpointSsrfOptions, mcpOAuthSsrfOptions, discoverProtectedResourceMetadata, discoverAuthorizationServerMetadata, normalizeTokenEndpointAuthMethod, resolveAdvertisedTokenEndpointAuthMethod, authMethodForStoredClient, selectDcrTokenEndpointAuthMethod, registerClient, buildAuthorizeUrl, exchangeCodeForTokens, refreshMcpToken, revokeMcpToken, computeExpiresAt, init_mcp_wrapper, LEARNING_TTL_DAYS, LEARNING_DUPLICATE_MIN_SIMILARITY, CANDIDATE_SET_MULTIPLIER, isGraphExpansionEnabled, EMBEDDING_DIMENSIONS, init_constants2, LONGTERM_ROOT, LEARNINGS_ROOT, MEMORY_KEY_PATTERN, MEMORY_KEY_PATTERN_MESSAGE, MEMORY_KEY_MAX_LENGTH, isLongtermKey, longtermKeyError, isConsolidatedKey, consolidatedKeyMessage, resolveStoreKey, init_key_paths, computeScore, rerank, init_reranker, isReviewTaskId, dropReviewTaskCompletions, init_review_recall_filter, searchMemoryCandidates, init_search_candidates, memorySearchReader, init_search_reader, rowToCandidate, init_sqlite_store, getEmbeddingProvider2, resetEmbeddingProvider2, getMemoryStore2, setDeploymentEnvReader2, embeddingEndpoint2, init_memory, embeddingProvider2, computeScriptEmbedding2, writeScriptEmbedding2, embedScript2, searchScripts2, reembedAllScripts2, init_embeddings, upsertScriptByName, getScript, getGlobalScriptContentHashes, getScriptById, getScriptVersion, listScripts, listScriptVersions, deleteScript, touchScratchScriptLastUsed, restoreScratchScriptLastUsedIfUnchanged, createScriptApi, listScriptApisForScript, getScriptApiById, getScriptApiSecret, updateScriptApi, rotateScriptApiSecret, deleteScriptApi, recordScriptApiUsage, init_db3, oauthSecretName, registerStoredSecret, loadSecretRegistry, init_secret_registry, getDefaultAuthorizationIdForProvider, getOAuthApp, getOAuthAppById, getOAuthAppIdByProvider, createOAuthApp, updateOAuthAppById, upsertOAuthApp, listAuthorizationsForApp, getAuthorizationById, upsertAuthorization, updateAuthorizationTokens, updateAuthorizationIdentity, deleteAuthorizationById, deleteAuthorizationsForApp, createOAuthPending, consumeOAuthPending, gcOAuthPending, markAuthorizationRefreshFailed, hasOAuthTokens, getOAuthTokens, listAuthorizationSweepRows, listKeepAliveAuthorizations, deleteOAuthTokens, acquireOAuthRefreshLock, releaseOAuthRefreshLock, init_oauth, normalizeVcsRepo, vcsRepoName, vcsRepoUrlMatches, init_vcs_repo_match, taskModelPin, resumedTaskModelSelection, init_model_pin, normalizeModelKey, init_pricing_normalize, buildModelsDevSeedRows, seedPricingFromModelsDev, init_seed_pricing, buildCatalogEntries, replaceModelCatalog, touchModelCatalogCheckedAt, countModelCatalog, getModelCatalogMeta, updateModelCatalogMeta, upsertModelCatalogOverlay, deleteModelCatalogOverlay, expireMatchedOverlays, applyOverlayPricingRows, reloadModelsCatalog, loadModelsCatalog, init_model_catalog_store, listHarnessModelSupport, recordHarnessModelSupport, agentRanModel, getAgentHarnessCliVersion, setAgentHarnessCliVersion, init_harness_model_support, sanitizeModelTierOverrides, parseModelTierOverridesHeader, modelTierOverridesDiffer, setAgentModelTierOverrides, previewModelTiers, recordClaimModelResolution, init_model_tier_resolution, harnessModelErrorFor, poolTaskRunsOnHarness, explicitModelError, explicitModelErrorForAgent, init_model_validation2, runtimeReadsRepoSecrets, vcsRepoId, configPools, checkProfileForAgent, formatProfileCheckFailures, init_model_profile_check, firstFailingCheck, resolveGroupForAgent, init_model_group_resolution, startTaskSearchBackfill, stopTaskSearchBackfill, init_search_index, rowToAgentTask, getTaskById2, getChildTasks2, TASK_LINEAGE_LIMITS2, getTaskLineage2, hasNonTerminalResumeChild2, SUPERSEDED_RESUME_REPAIR_WINDOW_MS2, getSupersededTasksWithoutResume2, getSupersededTasksWithUnsettledDependents2, hasNonTerminalRerouteDecisionChild2, getTasksByAgentId2, getTasksDispatchedFrom2, getAgentCurrentTask2, getTasksByStatus2, findTaskByVcs2, findActiveTasksByVcs2, findTaskByGitHub2, readableSessionCondition, getAllTasks2, getTasksCount2, getTaskStats2, getCompletedSlackTasks2, getPendingSlackRelayTasks2, markSlackRelayAttempted2, markSlackRelayDelivered2, markFinalizedSlackRelaysDelivered2, getPendingChatRelayTasks2, giveUpStaleChatRelays2, markChatRelayAttempted2, recordChatRelayError2, markChatRelayDelivered2, markChatRelayGivenUp2, getRecentlyFinishedWorkerTasks2, markTasksNotified2, resetTasksNotified2, getInProgressSlackTasks2, getSlackTasksMissingTree2, getInProgressTasksByContextKey2, isLinearTrackerContextKey2, findExistingLinearTrackerContextWork2, getLatestTaskByContextKey2, getLatestScriptRunStepTaskByContextKey2, getAgentWorkingOnThread2, getLatestActiveTaskInThread2, getLatestLeadTaskInThread2, getAgentWorkingOnContextKey2, getLatestTaskByContextKeyPrefix2, getLatestActiveTaskByContextKey2, getLatestLeadTaskByContextKey2, getFirstTaskInThread2, getMostRecentTaskInThread2, findCompletedTasksInThread2, findRecentFailedTaskInThread2, countAgentDispatchesInThread2, findRecentCancelledTaskInThread2, init_read, MODEL_PROFILE_CONFIG_KEY, hasUnreadableCredentialAllowlist, listModelProfiles, getModelProfileByName, createModelProfile, updateModelProfile, TASK_HOLDS_PROFILE_SQL, repairWindowStart, modelProfileReferences, modelProfileRefError, isModelNameTakenError, deleteModelProfile, MAX_MODEL_PROFILE_FALLBACKS, modelProfileFallbacksError, taskProfileError, modelGroupRefError, scheduleProfileUpdate, init_model_profiles, SESSION_ACTIVITY_REFRESH_MIN_INTERVAL_MS2, refreshActiveSessionOnActivity2, getActiveSessionById, init_active_sessions, STEERING_MOVED_ERROR, SteeringRequestError, SteeringBlockedError, isSteeringEnabled, getTaskSteeringFields, getTaskSteeringFieldsForTasks, promotePendingSteeringForTask, markSteeringUndeliverable, carryUnhandledSteering, requestSteering, init_steering2, onTaskStarted, init_task_lifecycle_events, listApprovalRequestSummaries2, getPendingApprovalVoteState2, recordApprovalVotes2, getPendingApprovalsForTasks2, approvalCancellationNotificationKey, listUndeliveredCancelledApprovalRequestIds, init_approvals, computeContentHash2, createContextVersion2, getLatestContextVersion2, getContextVersion2, getContextVersionHistory2, AssetKeyMovesBlockedError2, assertAssetKeyMovesAllowed2, moveTaskChainKeyInTx2, moveSessionChains, moveKeyFavorites, listPrefixRoots, listSharedPrefixRoots, init_session_moves, getSessionGroupKey, sessionSummaryQuery, getSessionReadState, getSessionTree, triageSessionList, init_session_tree, setHumanFreeQueueListener, reclassifyTaskHumanFree, drainHumanFreeReclassifyQueue, init_human_free, channelTopic, addWorkerSubscription, removeWorkerSubscription, listSubscribedWorkerAgents, init_channels, publishWorkerNudge, init_worker_nudges, createTask2, getPendingTaskForAgent2, assignUnassignedTaskPending2, startTask2, updateTaskClaudeSessionId2, recordTaskProviderIfUnset2, updateTaskTitle2, updateTaskTags2, setTaskTitleIfUnset2, completeTask2, failTask2, overwriteTerminalTaskResultText2, cancelTask2, skipTask2, supersedeTask2, markWorkflowStepTaskSuperseded2, settleSupersededTaskDependents2, backfillSupersedeTaskResumeTaskId2, pauseTask2, resumeTask2, getPausedTasksForAgent2, getOrphanedInProgressTasksForAgent2, resetOrphanedInProgressTasksForAgent2, getRecentlyCancelledTasksForAgent2, deleteTask2, updateTaskProgress2, init_write, quoteSqlIdentifier, USER_REFERENCE_COLUMNS_SQL, userReferenceRewriteSql, WORKFLOW_CONTEXT_REQUESTER_SQL, init_user_references, IdempotencyKeyTakenError, sha256, workflowRequestFingerprint, requestFingerprint, findAcceptedWorkflowOperation, assertWorkflowIdempotencyKeyUnused, recordAcceptedWorkflowOperation, init_workflow_idempotency, PINNED_WORKFLOW_KEYS2, toPinnedDefinition2, pinWorkflowDefinition2, getRunWorkflow2, deleteOrphanedRunDefinitions, init_workflow_run_definitions, getWorkflowsByEventName2, recordKeySeatMismatch2, recordKeyValidation2, retirePoolKeyStatus, init_api_keys, getScriptRunExecutionArgs2, getScriptRunFollowUpGuard2, setScriptRunFollowUpGuard2, setSkillUpdatedBy2, literalPrefixPattern2, getSlackRenderV2ActivatedAt2, ensureSlackRenderV2Activation2, getSlackDelegationActivatedAt2, ensureSlackDelegationActivation2, isPendingSlackMessage2, isSettledSlackMessage2, recordSlackMessage2, reserveSlackMessage2, bindSlackMessageTimestamp2, updateSlackMessageRecord2, markSlackTreeRendered2, deleteSlackMessageRecord2, getSlackTreeMessage2, getSlackTreeMessageByThread2, getSlackOutcomeMessage2, getResolvableDeferralOutcomes2, markSlackDeferralResolved2, noteSlackOutcomeDeliveryFailure2, abandonSlackOutcomeDelivery2, getSlackTreeMessages2, getSlackMessageByChannelTs2, getSlackTasksInThread2, listSlackThreadsAwaitingHuman2, isSlackThreadAwaitingHuman2, markTaskSlackReplySent2, setSlackMessageTracking2, updateTaskVcs2, insertTaskAttachment2, recordTaskPullRequestAttachments2, getAssetKeyMappingByProvider2, upsertAssetKeyMapping2, getAssetKeyMapping2, listAssetSummaries2, moveAssetKey2, deleteTaskAttachment2, replaceTaskAttachment2, getTaskAttachments2, createSteeringMessage2, getSteeringMessagesForTask2, getSteeringMessageById2, getPendingSteeringForTask2, getPendingSteeringForAgent2, markSteeringDelivered2, markSteeringHandled2, markSteeringPromoted2, cancelPendingSteeringForTask2, hasPendingSteering2, getAgentWithTasks2, getAllAgentsWithTasks2, createLogEntry2, getLogsByAgentId2, getLogsByTaskId2, getLogsByTaskIdAndEventType2, getLogsByTaskIdChronological2, getLogsByEventType2, getAllLogs2, findRecentSimilarTasks2, createTaskExtended2, claimTask2, releaseTask2, acceptTask2, rejectTask2, moveTaskToBacklog2, moveTaskFromBacklog2, promoteDraftTask2, refreshDraftTaskLease2, promoteAbandonedDraftTasks2, releaseStaleReviewingTasks2, releaseStaleOfferedTasksForOfflineAgents2, getOfferedTasksForAgent2, claimOfferedTask2, getUnassignedTasksCount2, getUnassignedTaskIds2, getUnassignedTaskIdsForAgent2, checkDependencies2, getDependentTasks2, cascadeFailDependents2, updateAgentProfile2, updateAgentName2, createChannel2, getMessageById2, getChannelById2, getChannelByName2, getAllChannels2, deleteChannel2, postMessage2, getChannelMessages2, updateReadState2, getLastReadAt2, getUnreadMessages2, getMentionsForAgent2, getInboxSummary2, claimMentions2, releaseMentionProcessing2, releaseStaleMentionProcessing2, createService2, getServiceById2, getServiceByAgentAndName2, getServicesByAgentId2, getAllServices2, updateServiceStatus2, deleteService2, upsertService2, deleteServicesByAgentId2, createSessionLogs2, getSessionLogsByTaskId2, getSessionLogsBySession2, createSessionCost2, getSessionCostsByTaskId2, getSessionCostsByAgentId2, getAllSessionCosts2, getSessionCostsFiltered2, UNATTRIBUTED_USER_ID2, getSessionCostSummary2, getAttributionByPerson2, getDashboardCostSummary2, createInboxMessage2, getInboxMessageById2, getUnreadInboxMessages2, claimInboxMessages2, markInboxMessageRead2, markInboxMessageResponded2, markInboxMessageDelegated2, releaseStaleProcessingInbox2, getConcurrentContext2, getScheduledTasks2, getScheduledTaskById2, getScheduledTaskByName2, createScheduledTask2, updateScheduledTask2, deleteScheduledTask2, getDueScheduledTasks2, autoEncryptLegacyPlaintextSecrets2, maskSecrets2, getSwarmConfigs2, getInjectableGlobalConfigs2, getSwarmConfigById2, getSwarmConfigLookupById2, upsertSwarmConfig2, emitBuiltInIntegrationConnectedOnce2, deleteSwarmConfig2, deleteSwarmConfigByKey2, getResolvedConfig2, getSwarmRepos2, getSwarmRepoById2, getSwarmRepoByName2, getSwarmRepoByUrl2, createSwarmRepo2, updateSwarmRepo2, deleteSwarmRepo2, getAgentMailInboxMapping2, getAgentMailInboxMappingsByAgent2, getAllAgentMailInboxMappings2, createAgentMailInboxMapping2, deleteAgentMailInboxMapping2, findTaskByAgentMailThread2, insertActiveSession2, deleteActiveSession2, deleteActiveSessionById2, getActiveSessions2, heartbeatActiveSession2, cleanupStaleSessions2, cleanupAgentSessions2, updateActiveSessionProviderSessionId2, getActiveSessionForTask2, reassociateSessionLogs2, getStalledInProgressTasks2, getStalePinnedResumes2, failPendingResumeIfUnclaimed2, getIdleWorkersWithCapacity2, getUnassignedPoolTasks2, getStaleUnassignedAffinityTasks2, getRecentFailedTasks2, getRecentCompletedCount2, getRecentFailedCount2, createWorkflow2, getWorkflow2, listWorkflows2, updateWorkflow2, deleteWorkflow2, getWorkflowsByScheduleId2, createWorkflowRun2, getWorkflowRun2, updateWorkflowRun2, listWorkflowRuns2, countWorkflowRuns2, listWorkflowRunsPage2, createWorkflowRunStep2, getWorkflowRunStep2, updateWorkflowRunStep2, getWorkflowRunStepsByRunId2, getStuckWorkflowRuns2, getLastSuccessfulRun2, getLastRunStart2, getRetryableSteps2, getCompletedStepNodeIds2, getTaskByWorkflowRunStepId2, detachTaskFromWorkflowRunStep2, getStepByIdempotencyKey2, getStepCountForNode2, getLatestStepForNode2, getCurrentStepForNode2, createWorkflowVersion2, getWorkflowVersions2, getWorkflowVersion2, createAppVersion2, getAppVersions2, getAppVersion2, createPage2, getPage2, getPageBySlug2, getLatestPageBySlug2, listPagesByAgent2, listAllPages2, countAllPages2, countPagesByAgent2, updatePage2, deletePage2, incrementPageViewCount2, createPageVersion2, getPageVersions2, getPageVersion2, createMetric2, getMetric2, getMetricBySlug2, listMetricsByAgent2, listAllMetrics2, countAllMetrics2, countMetricsByAgent2, updateMetric2, deleteMetric2, createMetricVersion2, getMetricVersions2, getMetricVersion2, getPromptTemplates2, getPromptTemplateById2, upsertPromptTemplate2, deletePromptTemplate2, resetPromptTemplateToDefault2, getPromptTemplateHistory2, resolvePromptTemplate2, checkoutPromptTemplate2, getAllChannelActivityCursors2, getChannelActivityCursor2, upsertChannelActivityCursor2, createApprovalRequest2, getApprovalRequestById2, resolveApprovalRequest2, cancelApprovalRequestById2, cancelPendingApprovalRequestsForRun2, listCancelledApprovalRequestsForRun2, listCancelledApprovalRequestsForStep2, claimApprovalCancellationNotification2, completeApprovalCancellationNotificationClaim2, releaseApprovalCancellationNotificationClaim2, updateApprovalRequestNotifications2, listApprovalRequests2, getStuckApprovalRuns2, getApprovalRequestByStepId2, getExpiredPendingApprovals2, getStaleApprovalRequests2, createWaitState2, getWaitStateById2, getWaitStateByStepId2, getDueWaitStates2, getPendingEventWaitNames2, getPendingWaitsByEvent2, resolveWaitState2, getStuckWaitRuns2, SKILL_FILE_LIMITS2, normalizeSkillFilePath2, createSkill2, updateSkill2, listSkillFileManifest2, getSkillFiles2, getSkillFile2, upsertSkillFile2, upsertSkillFiles2, deleteSkillFile2, deleteSkill2, getSkillById2, getSkillByName2, listSkills2, searchSkills2, installSkill2, getSystemDefaultSkills2, installSystemDefaultSkillsForAgent2, uninstallSkill2, getAgentSkills2, toggleAgentSkill2, createMcpServer2, emitMcpServerConnectedTelemetry2, updateMcpServer2, deleteMcpServer2, getMcpServerById2, getMcpServerByName2, listMcpServers2, installMcpServer2, uninstallMcpServer2, getAgentMcpServers2, createContextSnapshot2, getContextSnapshotsByTaskId2, getContextSnapshotsBySessionId2, getContextSummaryByTaskId2, getAvailableKeyIndices2, recordKeyUsage2, setApiKeyPlan2, markKeyRateLimited2, recordKeyAuthFailure2, recordKeyRateLimitWindows2, setApiKeyName2, clearKeyRateLimit2, getKeyStatuses2, getKeyCostSummary2, getUserById2, getAllUsers2, createUser2, updateUser2, deleteUser2, listInboxState2, upsertInboxState2, listFavorites2, listUserFavorites2, getFavoriteItemIdSet2, setFavorite2, setUserFavorite2, withFavoriteFlags2, listTaskTemplates2, getRootTaskChain2, listRecentSessions2, countSessions2, getBudget2, getBudgets2, upsertBudget2, deleteBudget2, getAllPricingRows2, getPricingRows2, getActivePricingRow2, insertPricingRow2, deletePricingRow2, getDailySpendForAgent2, getDailySpendGlobal2, getDailySpendForUser2, recordBudgetRefusalNotification2, getBudgetRefusalNotification2, getRecentBudgetRefusalNotifications2, hasBudgetRefusalNotificationToday2, setBudgetRefusalFollowUpTaskId2, getLiveAgentCounts2, getReadyAgentCounts2, getInstanceActivity2, getSwarmMetrics2, hasFirstCompletedTask2, getKv2, sweepExpiredKv2, sweepExpiredKvPrefix2, upsertKv2, claimKv2, deleteKv2, KvTypeCollisionError2, incrKv2, kvPrefixUpperBound2, listKv2, countKv2, createScriptRun2, recordInlineScriptRun2, getScriptRun2, getScriptRunByIdempotencyKey2, listScriptRuns2, countScriptRuns2, countActiveScriptRuns2, updateScriptRun2, updateScriptRunIfNotTerminal2, updateScriptRunIfRunning2, getRunningScriptRuns2, getScriptRunJournalStep2, upsertScriptRunJournalStep2, listScriptRunJournalSteps2, countScriptRunJournalSteps2, countScriptRunJournalAgentTaskSteps2, exports_db, init_db4 };