@desplega.ai/agent-swarm 2.14.0 → 2.14.2

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 (411) hide show
  1. package/dist/acp-adapter-q1vz4hh2.js +17 -0
  2. package/dist/{acp-targets-23exz4z4.js → acp-targets-d44eerh4.js} +10 -10
  3. package/dist/{actions-zcr25x27.js → actions-z4k4bvss.js} +28 -28
  4. package/dist/{agent-fs-provision-7fa9e12e.js → agent-fs-provision-aan1cgpx.js} +4 -4
  5. package/dist/{amp-adapter-s7ytmv6b.js → amp-adapter-wac3py0p.js} +3 -3
  6. package/dist/{anthropic-messages-vdd1zmha.js → anthropic-messages-njt2r5m4.js} +28 -27
  7. package/dist/{app-5d3sz1hy.js → app-wax6qz5e.js} +10 -10
  8. package/dist/{approval-notifications-7qgkzkzx.js → approval-notifications-6fvkhnma.js} +11 -11
  9. package/dist/{assistant-p2yvhc3j.js → assistant-e8fe08zx.js} +29 -29
  10. package/dist/{azure-openai-responses-jeaas6x0.js → azure-openai-responses-6ewf9rwp.js} +6 -6
  11. package/dist/{boot-args-schema-ry6cb0p7.js → boot-args-schema-rv97cmnt.js} +1 -1
  12. package/dist/{boot-reembed-c9643ms3.js → boot-reembed-bcn7frk9.js} +1 -1
  13. package/dist/{boot-reembed-2hkm3vz2.js → boot-reembed-xakrdy6y.js} +1 -1
  14. package/dist/{boot-scrub-sweep-3ycxr51t.js → boot-scrub-sweep-20t8akhf.js} +2 -2
  15. package/dist/{boot-seeds-2hzvvzg0.js → boot-seeds-48rr6r29.js} +4 -4
  16. package/dist/{boxd-9py3x0jb.js → boxd-tjpxwecx.js} +3 -3
  17. package/dist/{claude-adapter-dnkww93e.js → claude-adapter-0wzwntrj.js} +12 -13
  18. package/dist/{claude-managed-adapter-yk0cr5x6.js → claude-managed-adapter-4xcgt46w.js} +4 -4
  19. package/dist/{claude-managed-setup-4byxpp47.js → claude-managed-setup-91cyktw7.js} +7 -7
  20. package/dist/{claude-sdk-session-4wf3dbvs.js → claude-sdk-session-ngj4dce5.js} +11144 -12464
  21. package/dist/{cli-gcyws2bp.js → cli-021hrewp.js} +2 -2
  22. package/dist/{cli-wvgg7r4j.js → cli-08gfvs58.js} +2 -2
  23. package/dist/{cli-2zjxake1.js → cli-0kyjrbaa.js} +4 -4
  24. package/dist/{cli-rp1n2xpd.js → cli-0nvqg1hb.js} +1 -1
  25. package/dist/{cli-vxmmttmt.js → cli-0nz04gqv.js} +50 -50
  26. package/dist/{cli-vr4eyq6p.js → cli-0rrft7s3.js} +538 -410
  27. package/dist/{cli-mw1tmn3x.js → cli-1d9q7qrn.js} +7 -7
  28. package/dist/{cli-84xn7bgz.js → cli-1t5vhrpv.js} +1 -1
  29. package/dist/{cli-hzhv7yac.js → cli-1zbj28py.js} +1 -1
  30. package/dist/{cli-z8t4485r.js → cli-2ja7eadd.js} +2 -2
  31. package/dist/{cli-r04ve9xw.js → cli-2r62jy9s.js} +1 -1
  32. package/dist/{cli-9fwznq4p.js → cli-3ffzr65w.js} +7 -7
  33. package/dist/{cli-2ckwgs7q.js → cli-3kdgm393.js} +5 -5
  34. package/dist/{cli-jwnac23b.js → cli-3vc518cw.js} +1 -1
  35. package/dist/{cli-6p8p2e6r.js → cli-5188hq0a.js} +1286 -31
  36. package/dist/{cli-zcghfsdg.js → cli-53gt8wfv.js} +1 -1
  37. package/dist/{cli-930zbczq.js → cli-5njmmmer.js} +3 -3
  38. package/dist/{cli-dw9rtjm3.js → cli-5rw7nt99.js} +3061 -727
  39. package/dist/{cli-6c61yjwy.js → cli-5xx353cy.js} +7554 -1534
  40. package/dist/{cli-2ap1the6.js → cli-65k149j5.js} +2 -2
  41. package/dist/{cli-v41kn3cd.js → cli-6prwz0zn.js} +4427 -5566
  42. package/dist/{cli-yd7e590v.js → cli-6zpn5hmp.js} +12 -12
  43. package/dist/{cli-ty3gha1p.js → cli-7b9bwrfg.js} +2 -2
  44. package/dist/{cli-2414h5r9.js → cli-7dpdq7yh.js} +11428 -1914
  45. package/dist/{cli-r9d2tya0.js → cli-7qkbab03.js} +5 -5
  46. package/dist/{cli-7ca8hczj.js → cli-7svwhw1a.js} +1 -1
  47. package/dist/cli-7wwewkf4.js +37 -0
  48. package/dist/{cli-ejnhs815.js → cli-83hynhes.js} +17 -13
  49. package/dist/{cli-rs1rzwp4.js → cli-8crn0510.js} +1 -1
  50. package/dist/{cli-f2rwt43y.js → cli-8ee7xt75.js} +13 -13
  51. package/dist/{cli-9j47sgzy.js → cli-8ef94zm2.js} +2 -2
  52. package/dist/{cli-9fvk9mv8.js → cli-8gr1bg9t.js} +1 -1
  53. package/dist/{cli-b0m3bg0f.js → cli-9j1qcs0b.js} +1 -1
  54. package/dist/{cli-ad00h1st.js → cli-9mvfvggt.js} +7 -7
  55. package/dist/{cli-xh5fpmg8.js → cli-9txap41q.js} +101 -18
  56. package/dist/{cli-24wervhz.js → cli-aktk3qt6.js} +3 -3
  57. package/dist/{cli-6ajyhxh7.js → cli-an8bpy60.js} +2 -2
  58. package/dist/{cli-meydjstb.js → cli-azptj8xe.js} +5591 -69
  59. package/dist/cli-c0rt16vk.js +15 -0
  60. package/dist/{cli-w4bvtxet.js → cli-c6vhcknq.js} +7 -7
  61. package/dist/{cli-2savn6mm.js → cli-cczffwak.js} +7 -7
  62. package/dist/{cli-ze1ndjs4.js → cli-cgmka83w.js} +3 -3
  63. package/dist/{cli-kc7vd07m.js → cli-d13qgcct.js} +3699 -1733
  64. package/dist/{cli-k3facve0.js → cli-d5nvy1jy.js} +1 -1
  65. package/dist/{cli-edxfzgah.js → cli-dev6f0px.js} +4 -4
  66. package/dist/{cli-0e914dp9.js → cli-dzhht0vq.js} +3 -3
  67. package/dist/{cli-m0ea8ggd.js → cli-e13kbyq0.js} +2 -2
  68. package/dist/{cli-73rmgm45.js → cli-e2k0ej0d.js} +2 -2
  69. package/dist/cli-ek8b88kv.js +9740 -0
  70. package/dist/{cli-0k7ppk9k.js → cli-ertcjw6z.js} +281 -46
  71. package/dist/{cli-qrwjk4xy.js → cli-f3ta4e67.js} +5 -5
  72. package/dist/{cli-1nfabrt4.js → cli-f4xv7s0t.js} +7 -7
  73. package/dist/{cli-phe2vcw5.js → cli-fdam1t9b.js} +171 -104
  74. package/dist/{cli-gc6b94tj.js → cli-fe8he9cy.js} +2 -2
  75. package/dist/{cli-spfz393q.js → cli-feh37wgs.js} +598 -219
  76. package/dist/{cli-ebqx630g.js → cli-fjzjtqna.js} +35 -18
  77. package/dist/{cli-37p61fcg.js → cli-fs9t2m2k.js} +18 -20
  78. package/dist/{cli-7w1fs01q.js → cli-g03x26q6.js} +2 -2
  79. package/dist/{cli-879txsac.js → cli-gnkzh8ed.js} +4 -4
  80. package/dist/{cli-v4z5v3jd.js → cli-gy0r7gb8.js} +514 -337
  81. package/dist/{cli-s4pccby1.js → cli-h0edykd1.js} +1 -1
  82. package/dist/{cli-pq0kv31y.js → cli-h364asjc.js} +9 -9
  83. package/dist/{cli-69szn7w7.js → cli-h3xcfp4c.js} +93 -54
  84. package/dist/{cli-jcnc5ret.js → cli-h8k5801a.js} +73 -27
  85. package/dist/{cli-6yy4fepf.js → cli-h96yp7xv.js} +4 -4
  86. package/dist/{cli-q5n3deaf.js → cli-hab0bvrh.js} +1 -1
  87. package/dist/{cli-g6a696c0.js → cli-j3wqt73b.js} +4 -4
  88. package/dist/{cli-wym6rxgt.js → cli-jfgaz10x.js} +10 -15
  89. package/dist/{cli-shyhb4t5.js → cli-jrhvywah.js} +53 -52
  90. package/dist/{cli-qkbevqer.js → cli-jrxt5j0n.js} +3 -3
  91. package/dist/{cli-7b7rxz22.js → cli-jw7n9pct.js} +5 -2
  92. package/dist/{cli-8vbxjzk0.js → cli-k9kfck3s.js} +3 -3
  93. package/dist/{cli-yjb3cddd.js → cli-kkwq5b12.js} +1 -1
  94. package/dist/{cli-39t9d248.js → cli-kz8rar0g.js} +1 -1
  95. package/dist/{cli-rzbsh6bw.js → cli-n15fhd43.js} +1 -1
  96. package/dist/{cli-1jx0srjt.js → cli-nc842kc9.js} +1921 -80
  97. package/dist/{cli-9j1t3kf6.js → cli-nmj4phcg.js} +2 -2
  98. package/dist/{cli-t9pzz2eq.js → cli-ntmjzyte.js} +4 -1
  99. package/dist/{cli-adzmmcvf.js → cli-praaw1wh.js} +2 -2
  100. package/dist/{cli-f9g96z28.js → cli-q44p4869.js} +11 -11
  101. package/dist/{cli-fww016hh.js → cli-q58qt9dw.js} +1711 -7287
  102. package/dist/{cli-njvpngc6.js → cli-qqz5z36e.js} +3 -3
  103. package/dist/{cli-096aftq6.js → cli-r7rpy2xz.js} +7 -7
  104. package/dist/cli-rcqgr0hs.js +30 -0
  105. package/dist/{cli-ph95yejc.js → cli-rjc464jg.js} +2 -2
  106. package/dist/{cli-md4tn21h.js → cli-rw3m83j4.js} +40 -26
  107. package/dist/cli-rwcj6wt3.js +1291 -0
  108. package/dist/{cli-srq69pn1.js → cli-ryn4y478.js} +1 -1
  109. package/dist/{cli-jgq9xptq.js → cli-s48k2rzx.js} +4 -4
  110. package/dist/{cli-cbg0j1yt.js → cli-s90wcbk9.js} +3 -3
  111. package/dist/{cli-2ayk9gn8.js → cli-svcy72s5.js} +2 -2
  112. package/dist/{cli-4dyzzkfb.js → cli-swtwbg85.js} +944 -170
  113. package/dist/{cli-mv8ft7b0.js → cli-t1bqpzgz.js} +3 -3
  114. package/dist/{cli-tc165vrb.js → cli-t5jbjq61.js} +4 -3
  115. package/dist/{cli-enavhq6r.js → cli-tbrjvrrg.js} +1 -1
  116. package/dist/{cli-mz7ycqn8.js → cli-td2h8zej.js} +6 -6
  117. package/dist/{cli-9t7syepg.js → cli-ttatvwn6.js} +1 -1
  118. package/dist/{cli-ayxxkk3p.js → cli-txxcf9s1.js} +8 -8
  119. package/dist/{cli-q4z9s6zs.js → cli-v7az4d1g.js} +2 -2
  120. package/dist/cli-vqt44168.js +14 -0
  121. package/dist/{cli-q457ga28.js → cli-vs9h3vw2.js} +14 -14
  122. package/dist/{cli-snxhtehz.js → cli-w2fg8kjc.js} +7 -8
  123. package/dist/{cli-wd7b5hgc.js → cli-w81s97bn.js} +1 -1
  124. package/dist/{cli-bqfx72e6.js → cli-wkzrknpt.js} +1 -1
  125. package/dist/{cli-cg1q8ymp.js → cli-wqpvfq2m.js} +1 -1
  126. package/dist/{cli-kg63yp1r.js → cli-wz7qj1jy.js} +19 -19
  127. package/dist/{cli-3wsabyt0.js → cli-x5t54ytt.js} +2 -2
  128. package/dist/{cli-r495stwd.js → cli-xd6ntv7x.js} +2 -2
  129. package/dist/{cli-wvbaq052.js → cli-xphbv66z.js} +10 -3
  130. package/dist/{cli-a49frv85.js → cli-xxgqn93n.js} +3753 -1186
  131. package/dist/{cli-91amj3md.js → cli-z209g721.js} +111 -87
  132. package/dist/{cli-3mhdmcd4.js → cli-z5andw8k.js} +1 -1
  133. package/dist/{cli-7g5qj2ca.js → cli-zcb64xzv.js} +1 -1
  134. package/dist/{cli-0h6m6z5g.js → cli-zr2sc5tr.js} +1 -1
  135. package/dist/{cli-krk8y8c7.js → cli-zrm0610v.js} +1833 -518
  136. package/dist/cli.js +73 -73
  137. package/dist/{cloudflare-workers-ai-system-one-w3m0fbf8.js → cloudflare-workers-ai-system-one-kb0tq22h.js} +2 -2
  138. package/dist/{codex-adapter-eq61radw.js → codex-adapter-0c1ynrmt.js} +9 -9
  139. package/dist/{codex-hook-8nmepvz6.js → codex-hook-w5nmtrn2.js} +2 -2
  140. package/dist/{codex-login-vbd9707w.js → codex-login-67qarfcg.js} +1 -1
  141. package/dist/{codex-session-runner-rfx355h4.js → codex-session-runner-z4t9z7yy.js} +10 -10
  142. package/dist/{commands-d1z0sx62.js → commands-h0jxqdhk.js} +3 -3
  143. package/dist/{controller-9hz6d8x3.js → controller-4ygy66hv.js} +4 -4
  144. package/dist/{controllers-connect-tz07d2xr.js → controllers-connect-ynbvv8pv.js} +28 -28
  145. package/dist/core-mj9fzrcm.js +41 -0
  146. package/dist/{cursor-adapter-ef22ze3j.js → cursor-adapter-9e4d6658.js} +2 -2
  147. package/dist/{db-gd81d68c.js → db-bg0hxjq1.js} +3 -3
  148. package/dist/{db-vrckks6q.js → db-q12gmpns.js} +2 -2
  149. package/dist/{devin-adapter-kdt6a2bh.js → devin-adapter-tn1twrha.js} +1 -1
  150. package/dist/{devtools-qxfgbsqz.js → devtools-t8my9az6.js} +1 -1
  151. package/dist/{dispatcher-76as8w2t.js → dispatcher-v5dbfscq.js} +24 -24
  152. package/dist/{docker-51ta7jsh.js → docker-6007r2fj.js} +2 -2
  153. package/dist/{dsh-adapter-ypfvcdyz.js → dsh-adapter-z3fneea1.js} +2 -2
  154. package/dist/{e2b-05kn3kpq.js → e2b-k3kb8b52.js} +4 -4
  155. package/dist/{e2b-dm9r8hpy.js → e2b-p269awh6.js} +5 -5
  156. package/dist/{easter-egg-3d-sg21j15g.js → easter-egg-3d-y49v5z90.js} +1 -1
  157. package/dist/{embedding-space-zsdw37bb.js → embedding-space-mjt5ksq0.js} +5 -5
  158. package/dist/{embeddings-p4e3e1m6.js → embeddings-td9hgnc5.js} +1 -1
  159. package/dist/emscripten-module-Q67P5WYC-3sde6cre.js +2458 -0
  160. package/dist/{event-bus-tvf2grf4.js → event-bus-pawddp92.js} +1 -1
  161. package/dist/{execute-nztd0af0.js → execute-z8nc8bba.js} +1 -1
  162. package/dist/{external-channel-717yzn4d.js → external-channel-pjenc2ag.js} +2 -2
  163. package/dist/ffi-cbfmmtqk.js +85 -0
  164. package/dist/fx-adapter-pjeztp0n.js +20 -0
  165. package/dist/getMachineId-bsd-hjs2tbdp.js +36 -0
  166. package/dist/getMachineId-darwin-kzbvr8s3.js +40 -0
  167. package/dist/getMachineId-linux-embmcq2c.js +26 -0
  168. package/dist/getMachineId-unsupported-jvznc6d4.js +20 -0
  169. package/dist/getMachineId-win-qr8z0b13.js +36 -0
  170. package/dist/{google-generative-ai-sw77egmr.js → google-generative-ai-tf3w7557.js} +11 -16
  171. package/dist/{google-vertex-rrw93g8h.js → google-vertex-9pj87bd8.js} +15 -17
  172. package/dist/grok-adapter-davbhx8t.js +20 -0
  173. package/dist/handlers-rf130hnp.js +39 -0
  174. package/dist/heartbeat-9hmvqxk0.js +49 -0
  175. package/dist/hook-0b1jqs2t.js +21 -0
  176. package/dist/{hook-ctz0xmp3.js → hook-1n0sjv8p.js} +10 -11
  177. package/dist/{http-zregegrx.js → http-vykejyjx.js} +432 -170
  178. package/dist/{index-7dgxveck.js → index-07d66kdm.js} +3 -3
  179. package/dist/index-0hgjxqz8.js +10584 -0
  180. package/dist/{index-rz8ve510.js → index-0nt39qwy.js} +2 -2
  181. package/dist/{index-ym9fgxad.js → index-2xbxq71g.js} +2 -2
  182. package/dist/{index-42jq9yy3.js → index-3j8hffkb.js} +12327 -7450
  183. package/dist/index-8w09aggw.js +43 -0
  184. package/dist/{index-5kx15d19.js → index-b3wy4jzs.js} +1 -1
  185. package/dist/{index-kzdqn3dd.js → index-dt9vr7tb.js} +3143 -760
  186. package/dist/{index-maddg9ys.js → index-ezfas4jj.js} +5858 -15337
  187. package/dist/index-g2jntx15.js +38 -0
  188. package/dist/{index-x9qf8dg7.js → index-j6sqtb83.js} +105 -75
  189. package/dist/{index-m6g8q65g.js → index-na0tczq0.js} +9268 -10220
  190. package/dist/{index-whysn1wf.js → index-p9dkwhwe.js} +1 -1
  191. package/dist/{index-126v2d0t.js → index-pe2etczf.js} +6 -2918
  192. package/dist/{index-mtnbhe12.js → index-q60mhcpd.js} +23631 -19921
  193. package/dist/index-qffex5k4.js +41 -0
  194. package/dist/index-qrp11tp9.js +4 -0
  195. package/dist/{index-kdmkfjt7.js → index-ryyrg0d8.js} +3426 -2333
  196. package/dist/{index-t17p395x.js → index-sf06w57a.js} +13 -13
  197. package/dist/{index-evay0xyk.js → index-vybnwd5v.js} +1 -1
  198. package/dist/{index-fdym6ryb.js → index-wsf1f5pe.js} +28 -28
  199. package/dist/{k8s-ejkk0aw7.js → k8s-mr1r12th.js} +2 -2
  200. package/dist/{keepalive-zdqay870.js → keepalive-86z0tzzf.js} +4 -4
  201. package/dist/lead-edmwagkn.js +81 -0
  202. package/dist/{llama-cpp-classify-yvb8vh7w.js → llama-cpp-classify-wd7htn1x.js} +2 -2
  203. package/dist/{maintenance-t5ndg11m.js → maintenance-19h6tfwz.js} +1 -1
  204. package/dist/{mistral-conversations-w4bncwbt.js → mistral-conversations-txjmc64f.js} +7 -7
  205. package/dist/module-ES6BEMUI-44w9s1dx.js +1210 -0
  206. package/dist/{multipart-parser-xevcstye.js → multipart-parser-xqbgwrav.js} +1 -1
  207. package/dist/{node-0as4n1ef.js → node-q4628t0b.js} +1 -1
  208. package/dist/{oauth-refresh-sweep-y9zyd7t6.js → oauth-refresh-sweep-6nmyrv32.js} +3 -3
  209. package/dist/{object-webhooks-mkca91s0.js → object-webhooks-2kynmdf8.js} +7 -7
  210. package/dist/{onboard-ss995244.js → onboard-zbpm96mn.js} +7 -7
  211. package/dist/{openai-codex-responses-70g39cgz.js → openai-codex-responses-6ckhys6r.js} +35 -29
  212. package/dist/{openai-completions-cv3hp4h5.js → openai-completions-c9dsq9jh.js} +15 -15
  213. package/dist/{openai-decisions-fyq1p9f9.js → openai-decisions-9vzvv10c.js} +2 -2
  214. package/dist/{openai-responses-trsvnks6.js → openai-responses-bhfmt9sa.js} +6 -6
  215. package/dist/{opencode-adapter-mwpz0278.js → opencode-adapter-fyqcbdra.js} +8 -8
  216. package/dist/{openrouter-images-0jj12a2q.js → openrouter-images-hkk5p580.js} +3 -3
  217. package/dist/otel-impl-txa20w1h.js +11178 -0
  218. package/dist/{pending-2sxh1t6j.js → pending-4rxawq8y.js} +25 -25
  219. package/dist/{pi-messages-zk3g4esn.js → pi-messages-py3f96p7.js} +5 -5
  220. package/dist/{pi-mono-adapter-sfb7zy43.js → pi-mono-adapter-rnsed1xa.js} +24 -27
  221. package/dist/{pricing-refresh-h79bg4cf.js → pricing-refresh-4314hwtw.js} +2 -2
  222. package/dist/{rbac-roles-ckq0czp4.js → rbac-roles-fztcm8ky.js} +2 -2
  223. package/dist/{rbac-roles-jg2e260w.js → rbac-roles-msqt7a3k.js} +3 -3
  224. package/dist/{render-v2-ymbshmn0.js → render-v2-w49wtecg.js} +10 -10
  225. package/dist/{resume-jdhnt4jk.js → resume-gwgtp4m3.js} +13 -13
  226. package/dist/{runtime-y28jhhnf.js → runtime-kkebz8yq.js} +1 -1
  227. package/dist/{session-access-k4ta5hvp.js → session-access-kjb19m2w.js} +5 -5
  228. package/dist/{session-source-backfill-528j4s8j.js → session-source-backfill-805p4wqr.js} +3 -3
  229. package/dist/{setup-d6pj82fr.js → setup-q8y168c8.js} +3 -3
  230. package/dist/thread-buffer-yqbffd0t.js +40 -0
  231. package/dist/{token-util-pjgekqxr.js → token-util-hnzceyn9.js} +1 -1
  232. package/dist/{token-pgr2w4s3.js → token-xnc02n6w.js} +21 -14
  233. package/dist/{tree-visibility-kjxv3nxk.js → tree-visibility-qj323994.js} +2 -2
  234. package/dist/{typesafe-system-one-qkvkgrcz.js → typesafe-system-one-avrdb4zm.js} +2 -2
  235. package/dist/{user-merge-jobs-rabbncf6.js → user-merge-jobs-qfp40f2s.js} +3 -3
  236. package/dist/{virtual-modules-22k51txd.js → virtual-modules-nzxegw0a.js} +7 -7
  237. package/dist/{work-objects-xtjbar3r.js → work-objects-hs089w60.js} +26 -26
  238. package/dist/{worker-follow-up-fg48vk6d.js → worker-follow-up-zwgg20sr.js} +24 -24
  239. package/dist/worker-kg4g7rnx.js +81 -0
  240. package/dist/{x-vfsqypht.js → x-k29vmskt.js} +2 -2
  241. package/openapi.json +59 -3
  242. package/package.json +53 -52
  243. package/plugin/commands/create-pr.md +5 -2
  244. package/plugin/pi-skills/create-pr/SKILL.md +5 -2
  245. package/src/apps/sync.ts +7 -2
  246. package/src/be/db/model-profiles.ts +103 -12
  247. package/src/be/db/tasks/read.ts +5 -0
  248. package/src/be/db/workflow-runs.ts +12 -8
  249. package/src/be/db.ts +18 -5
  250. package/src/be/migrations/367_workflow_run_principal.sql +5 -0
  251. package/src/be/model-group-resolution.ts +134 -0
  252. package/src/be/model-tier-resolution.ts +120 -17
  253. package/src/be/model-validation.ts +9 -1
  254. package/src/be/runtime-pools/routing.ts +22 -8
  255. package/src/be/scripts/extract-schema.ts +7 -0
  256. package/src/be/swarm-config-guard.ts +20 -7
  257. package/src/be/task-auto-title-listener.ts +2 -2
  258. package/src/commands/onboard/agent-fs-version.ts +1 -1
  259. package/src/extensions/contract-types.generated.ts +1 -1
  260. package/src/extensions/post-bridge.ts +27 -28
  261. package/src/http/active-sessions.ts +7 -0
  262. package/src/http/agents.ts +7 -0
  263. package/src/http/api-keys.ts +7 -0
  264. package/src/http/approval-requests.ts +4 -0
  265. package/src/http/budgets.ts +2 -0
  266. package/src/http/codex-oauth-keep-warm.ts +6 -2
  267. package/src/http/config.ts +1 -0
  268. package/src/http/context.ts +4 -0
  269. package/src/http/db-query.ts +11 -2
  270. package/src/http/events.ts +2 -0
  271. package/src/http/fs.ts +1 -0
  272. package/src/http/integrations.ts +4 -0
  273. package/src/http/mcp-bridge.ts +1 -0
  274. package/src/http/memory.ts +3 -0
  275. package/src/http/metrics.ts +16 -0
  276. package/src/http/oauth-locks.ts +8 -0
  277. package/src/http/operator-actor.ts +3 -8
  278. package/src/http/page-proxy.ts +16 -0
  279. package/src/http/pages.ts +9 -0
  280. package/src/http/poll.ts +21 -1
  281. package/src/http/pricing.ts +2 -0
  282. package/src/http/prompt-templates.ts +34 -0
  283. package/src/http/repos.ts +3 -1
  284. package/src/http/schedules.ts +33 -3
  285. package/src/http/script-runs.ts +24 -0
  286. package/src/http/scripts.ts +1 -0
  287. package/src/http/session-data.ts +2 -0
  288. package/src/http/status.ts +1 -0
  289. package/src/http/tasks.ts +28 -1
  290. package/src/http/trackers/jira.ts +2 -0
  291. package/src/http/trackers/linear.ts +4 -0
  292. package/src/http/users.ts +18 -0
  293. package/src/http/webhooks.ts +12 -0
  294. package/src/http/workflow-events.ts +26 -6
  295. package/src/http/workflows.ts +40 -0
  296. package/src/http/x.ts +4 -0
  297. package/src/linear/app.ts +3 -2
  298. package/src/linear/client.ts +5 -1
  299. package/src/linear/host.ts +40 -0
  300. package/src/linear/oauth.ts +3 -2
  301. package/src/linear/sync.ts +4 -3
  302. package/src/otel-impl.ts +8 -5
  303. package/src/prompts/base-prompt.ts +10 -6
  304. package/src/prompts/session-templates.ts +3 -3
  305. package/src/providers/acp-targets.ts +1 -1
  306. package/src/providers/amp-adapter.ts +11 -9
  307. package/src/providers/cursor-adapter.ts +1 -1
  308. package/src/rbac/legacy-policy.ts +2 -0
  309. package/src/rbac/permissions.ts +5 -0
  310. package/src/realtime/browser.generated.txt +1 -1
  311. package/src/scheduler/schedule-task.ts +1 -0
  312. package/src/scripts-runtime/quickjs-compat.ts +44 -10
  313. package/src/scripts-runtime/types/swarm-extension.d.ts +2 -0
  314. package/src/slack/config.ts +4 -0
  315. package/src/slack/render-v2.ts +52 -24
  316. package/src/slack/responses.ts +2 -1
  317. package/src/slack/reviewed-deliverables.ts +251 -0
  318. package/src/tasks/follow-up-gate.ts +142 -38
  319. package/src/tasks/worker-follow-up.ts +126 -37
  320. package/src/tests/amp-adapter.test.ts +57 -9
  321. package/src/tests/base-prompt.test.ts +36 -2
  322. package/src/tests/check-pr-body.test.ts +408 -93
  323. package/src/tests/compose-dev-object-store.test.ts +13 -0
  324. package/src/tests/compose-example-object-store.test.ts +67 -0
  325. package/src/tests/db-query.test.ts +8 -4
  326. package/src/tests/db-retention-defaults.test.ts +28 -3
  327. package/src/tests/e2b-dispatch.test.ts +7 -1
  328. package/src/tests/entrypoint-repo-autoclone-args.test.ts +10 -0
  329. package/src/tests/follow-up-gate-shadow.test.ts +268 -10
  330. package/src/tests/linear-outbound-sync.test.ts +59 -25
  331. package/src/tests/operator-actor-keyless.test.ts +103 -0
  332. package/src/tests/otel-event-loop-and-logs.test.ts +1 -1
  333. package/src/tests/profile-tier-alias.test.ts +9 -3
  334. package/src/tests/quickjs-compat.test.ts +40 -4
  335. package/src/tests/rbac-route-verbs-e2e.test.ts +142 -0
  336. package/src/tests/runner-repo-clone-args.test.ts +15 -6
  337. package/src/tests/script-connections.test.ts +2 -0
  338. package/src/tests/slack-render-v2.test.ts +52 -8
  339. package/src/tests/workflow-definition-pinning.test.ts +2 -0
  340. package/src/tests/workflow-hitl-routing.test.ts +67 -5
  341. package/src/tests/workflow-replay.test.ts +13 -1
  342. package/src/tests/workflow-system-one-extraction.test.ts +21 -0
  343. package/src/tests/workflow-wait-filter.test.ts +7 -7
  344. package/src/tests/worktree-reaper.test.ts +15 -4
  345. package/src/tests/x402-client.test.ts +82 -0
  346. package/src/tools/memory-rate.ts +2 -2
  347. package/src/tools/prompt-templates/delete.ts +22 -1
  348. package/src/tools/prompt-templates/set.ts +15 -1
  349. package/src/tools/schedules/create-schedule.ts +20 -3
  350. package/src/tools/schedules/patch-schedule.ts +30 -4
  351. package/src/tools/schedules/update-schedule.ts +30 -4
  352. package/src/tools/send-task.ts +17 -3
  353. package/src/tools/slack-post.ts +7 -2
  354. package/src/tools/slack-reply.ts +6 -2
  355. package/src/tools/task-action.ts +16 -3
  356. package/src/tools/utils.ts +1 -1
  357. package/src/types.ts +10 -0
  358. package/src/utils/amp-models.ts +20 -4
  359. package/src/utils/constants.ts +5 -4
  360. package/src/utils/secret-scrubber.ts +6 -4
  361. package/src/utils/task-citations.ts +11 -0
  362. package/src/workflows/engine.ts +41 -8
  363. package/src/workflows/executors/agent-task.ts +13 -2
  364. package/src/workflows/executors/code-match.ts +11 -31
  365. package/src/workflows/executors/script.ts +13 -0
  366. package/src/workflows/executors/sub-workflow.ts +5 -7
  367. package/src/workflows/executors/swarm-script.ts +4 -5
  368. package/src/workflows/executors/system-one-extraction.ts +9 -6
  369. package/src/workflows/executors/wait.ts +1 -1
  370. package/src/workflows/foreach-driver.ts +5 -1
  371. package/src/workflows/model-validation.ts +13 -1
  372. package/src/workflows/predicate-sandbox.ts +171 -0
  373. package/src/workflows/resume.ts +21 -4
  374. package/src/workflows/retry-poller.ts +1 -1
  375. package/src/workflows/run-principal.ts +51 -0
  376. package/src/workflows/wait-filter.ts +14 -192
  377. package/src/x402/client.ts +38 -17
  378. package/templates/skills/code-quality/content.md +1 -1
  379. package/templates/skills/heartbeat-runbook/content.md +1 -0
  380. package/templates/skills/pages/content.md +36 -12
  381. package/templates/skills/slack-interaction/content.md +4 -0
  382. package/templates/skills/swarm-docs/content.md +47 -41
  383. package/templates/skills/swarm-scripts/SKILL.md +1 -1
  384. package/templates/skills/swarm-scripts/content.md +1 -1
  385. package/dist/acp-adapter-99n6z9ky.js +0 -17
  386. package/dist/cli-5ss6qqt9.js +0 -45
  387. package/dist/cli-dzzh58sy.js +0 -6996
  388. package/dist/cli-e8trbfx1.js +0 -15
  389. package/dist/cli-j9ccfveb.js +0 -1849
  390. package/dist/cli-mna6pmfx.js +0 -1485
  391. package/dist/cli-r8ddn0hf.js +0 -25583
  392. package/dist/core-dynsv289.js +0 -41
  393. package/dist/fx-adapter-9k0hptnz.js +0 -20
  394. package/dist/getMachineId-bsd-637a7rbk.js +0 -36
  395. package/dist/getMachineId-darwin-9vytrcnn.js +0 -36
  396. package/dist/getMachineId-linux-mkzsvyyz.js +0 -29
  397. package/dist/getMachineId-unsupported-4cfs2n11.js +0 -19
  398. package/dist/getMachineId-win-154s3qma.js +0 -38
  399. package/dist/grok-adapter-skdj2pce.js +0 -20
  400. package/dist/handlers-5btjqkz6.js +0 -39
  401. package/dist/heartbeat-vfb1gy84.js +0 -49
  402. package/dist/hook-eh52p7yd.js +0 -22
  403. package/dist/index-7w8p6em0.js +0 -41
  404. package/dist/index-t56y945n.js +0 -4
  405. package/dist/index-vfemrwwk.js +0 -10002
  406. package/dist/index-vz4semsx.js +0 -38
  407. package/dist/index-y3s0xp2v.js +0 -43
  408. package/dist/lead-6cscw8a5.js +0 -82
  409. package/dist/otel-impl-6n6vva3x.js +0 -28205
  410. package/dist/thread-buffer-9w6x5zec.js +0 -40
  411. package/dist/worker-g4aj93dt.js +0 -82
@@ -1,9 +1,15 @@
1
+ import {
2
+ resolveGitHubHost,
3
+ getGitHubLinkConfig,
4
+ getGitHubHostForSql,
5
+ init_github_host
6
+ } from "./cli-9ttx00s3.js";
1
7
  import {
2
8
  ampPinProviderError,
3
9
  ampPinCatalogError,
4
10
  ampModelError,
5
11
  init_amp_models
6
- } from "./cli-wvbaq052.js";
12
+ } from "./cli-xphbv66z.js";
7
13
  import {
8
14
  ALL_TOOLS,
9
15
  init_tool_config
@@ -14,7 +20,7 @@ import {
14
20
  applyProviderQuotaReport,
15
21
  scrubProviderQuotaReport,
16
22
  init_provider_account_telemetry
17
- } from "./cli-cg1q8ymp.js";
23
+ } from "./cli-wqpvfq2m.js";
18
24
  import {
19
25
  CODEX_AUTH_FAILURE_BENCH_THRESHOLD,
20
26
  CODEX_AUTH_FAILURE_BENCH_MS,
@@ -22,12 +28,6 @@ import {
22
28
  codexAuthBenchMarkerKey,
23
29
  init_codex_auth_failure
24
30
  } from "./cli-fw2w0kva.js";
25
- import {
26
- resolveGitHubHost,
27
- getGitHubLinkConfig,
28
- getGitHubHostForSql,
29
- init_github_host
30
- } from "./cli-9ttx00s3.js";
31
31
  import {
32
32
  init_templates4,
33
33
  generateDefaultClaudeMd2,
@@ -42,15 +42,15 @@ import {
42
42
  init_identity_field_budget,
43
43
  contentSha256,
44
44
  init_profile_sync
45
- } from "./cli-wym6rxgt.js";
46
- import {
47
- isSlackConfigured,
48
- init_config5
49
- } from "./cli-t9pzz2eq.js";
45
+ } from "./cli-jfgaz10x.js";
50
46
  import {
51
47
  isSteeringEnabled2,
52
48
  init_steering_enabled
53
49
  } from "./cli-4sydckyj.js";
50
+ import {
51
+ isSlackConfigured,
52
+ init_config5
53
+ } from "./cli-ntmjzyte.js";
54
54
  import {
55
55
  kindForModelString,
56
56
  init_models2
@@ -74,7 +74,11 @@ import {
74
74
  splitCredentialPool,
75
75
  selectCredential,
76
76
  init_credentials2
77
- } from "./cli-wd7b5hgc.js";
77
+ } from "./cli-w81s97bn.js";
78
+ import {
79
+ getOpenRouterAttributionHeaders,
80
+ init_openrouter_base_url
81
+ } from "./cli-dfyv0jdy.js";
78
82
  import {
79
83
  registerTemplate,
80
84
  getAllTemplateDefinitions,
@@ -82,11 +86,7 @@ import {
82
86
  configureDbResolver,
83
87
  init_resolver,
84
88
  init_session_templates
85
- } from "./cli-24wervhz.js";
86
- import {
87
- getOpenRouterAttributionHeaders,
88
- init_openrouter_base_url
89
- } from "./cli-dfyv0jdy.js";
89
+ } from "./cli-aktk3qt6.js";
90
90
  import {
91
91
  normalizeAssetKey,
92
92
  defaultAssetKey,
@@ -127,12 +127,12 @@ import {
127
127
  SUPERSEDED_WORKFLOW_TASK_REASON,
128
128
  PageThemeTokensSchema,
129
129
  init_types5
130
- } from "./cli-tc165vrb.js";
130
+ } from "./cli-t5jbjq61.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";
@@ -160,7 +160,7 @@ import {
160
160
  import {
161
161
  init_package,
162
162
  package_default
163
- } from "./cli-shyhb4t5.js";
163
+ } from "./cli-jrhvywah.js";
164
164
  import {
165
165
  getNodeEnv,
166
166
  isDevOrTestNodeEnv,
@@ -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-msqt7a3k.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-6fvkhnma.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();
@@ -7020,6 +7020,7 @@ var init_legacy_policy = __esm(() => {
7020
7020
  "page.delete.any": leadOrResourceOwner,
7021
7021
  "design-system.write": anyAuthenticated,
7022
7022
  "page.launch": anyAuthenticated,
7023
+ "prompt-template.write": humanOrLeadOrResourceOwner,
7023
7024
  "objects.read": operatorOrUser,
7024
7025
  "objects.write": operatorOrUser,
7025
7026
  "app.manage": anyAuthenticated,
@@ -7423,6 +7424,10 @@ var init_permissions = __esm(() => {
7423
7424
  description: "Open a public or authed page: mint its page-session cookie.",
7424
7425
  namespace: "page"
7425
7426
  },
7427
+ "prompt-template.write": {
7428
+ description: "Create, change, reset or delete a prompt template override: any as lead, operator, or user; an agent-scope override only for the caller's own agent.",
7429
+ namespace: "prompt-template"
7430
+ },
7426
7431
  "objects.read": {
7427
7432
  description: "Read a board or sheet on the swarm's shared agent-fs drive through the object routes.",
7428
7433
  namespace: "objects"
@@ -8806,7 +8811,7 @@ async function applyCliSupport(resolution, harness, cliVersion) {
8806
8811
  return { ...resolution, resolvedModel: fallback, modelSource };
8807
8812
  }
8808
8813
  async function resolveClaimProfile(name, source, harness) {
8809
- const isTask = source === "profile:task";
8814
+ const isTask = source === "profile:task" || source === "profile:group";
8810
8815
  const profile = await getModelProfileByName(name);
8811
8816
  if (!profile) {
8812
8817
  return isTask ? { modelUnsupported: `[model-profile-missing] Model profile "${name}" no longer exists.` } : null;
@@ -8848,18 +8853,40 @@ async function resolveClaimProfile(name, source, harness) {
8848
8853
  resolution
8849
8854
  };
8850
8855
  }
8851
- async function resolveTierAlias(resolved, task, harness) {
8856
+ async function resolveTierAlias(resolved, task, agentId, harness, includeRepoSecrets) {
8852
8857
  const tier = parseModelTier(task.modelTier);
8853
8858
  if (!resolved || "harnessMismatch" in resolved || !tier || !harness)
8854
8859
  return null;
8855
- const name = `${harness}-${tier}`;
8860
+ const seeded = `${harness}-${tier}`;
8856
8861
  if (resolved.modelSource === "worker-env" || resolved.modelSource === "tier-config") {
8857
- console.log(`[model-tier] deprecated: ${resolved.modelSource} override for ${name}; edit profile ${name} instead`);
8862
+ console.log(`[model-tier] deprecated: ${resolved.modelSource} override for ${seeded}; edit profile ${seeded} instead`);
8858
8863
  return null;
8859
8864
  }
8860
8865
  if (resolved.modelSource !== "tier-default")
8861
8866
  return null;
8862
- const picked = await resolveClaimProfile(name, "profile:tier-alias", harness);
8867
+ const group = await resolveGroupForAgent(tier, agentId, {
8868
+ vcsRepo: task.vcsRepo,
8869
+ includeRepoSecrets
8870
+ });
8871
+ let name = seeded;
8872
+ let picked = null;
8873
+ if (group.kind === "resolved") {
8874
+ picked = await resolveClaimProfile(group.member, "profile:tier-alias", harness);
8875
+ if (picked && "profile" in picked) {
8876
+ name = group.member;
8877
+ const untouched = group.onHarness.length === 1 && group.onHarness[0] === seeded;
8878
+ if (!untouched) {
8879
+ picked = { ...picked, resolution: { ...picked.resolution, modelSource: "profile:group" } };
8880
+ }
8881
+ if (group.member !== seeded) {
8882
+ await logGroupResolution(task.id, agentId, tier, group.member, group.skipped);
8883
+ }
8884
+ }
8885
+ }
8886
+ if (!picked || !("profile" in picked)) {
8887
+ picked = await resolveClaimProfile(seeded, "profile:tier-alias", harness);
8888
+ name = seeded;
8889
+ }
8863
8890
  if (!picked || !("profile" in picked))
8864
8891
  return picked;
8865
8892
  if (isHarnessModelJudged(harness) && harnessModelMismatch(picked.resolution.resolvedModel, harness, (await loadResolutionCatalog()).catalog)) {
@@ -8868,14 +8895,41 @@ async function resolveTierAlias(resolved, task, harness) {
8868
8895
  }
8869
8896
  return picked;
8870
8897
  }
8898
+ async function logGroupResolution(taskId, agentId, group, member, skipped) {
8899
+ await createLogEntry2({
8900
+ eventType: "task_model_group_resolved",
8901
+ taskId,
8902
+ agentId,
8903
+ newValue: member,
8904
+ metadata: { group, member, skipped }
8905
+ });
8906
+ }
8907
+ async function resolveClaimGroup(group, task, agentId, harness, includeRepoSecrets) {
8908
+ const resolution = await resolveGroupForAgent(group, agentId, {
8909
+ vcsRepo: task.vcsRepo,
8910
+ includeRepoSecrets
8911
+ });
8912
+ if (resolution.kind === "missing") {
8913
+ return { modelUnsupported: `[model-group-missing] Model group "${group}" no longer exists.` };
8914
+ }
8915
+ if (resolution.kind === "none") {
8916
+ return { modelUnsupported: groupUnavailableMessage(group, harness, resolution.skipped) };
8917
+ }
8918
+ if (resolution.skipped.length > 0) {
8919
+ console.log(`[model-group] task ${task.id}: ${group} → ${resolution.member} (skipped: ${formatGroupSkips(resolution.skipped)})`);
8920
+ }
8921
+ await logGroupResolution(task.id, agentId, group, resolution.member, resolution.skipped);
8922
+ return await resolveClaimProfile(resolution.member, "profile:group", harness);
8923
+ }
8871
8924
  async function recordClaimModelResolution(task, agent, { includeRepoSecrets = true } = {}) {
8872
8925
  const harnessProvider = agent.harnessProvider ?? agent.provider ?? null;
8873
8926
  if (!task.model?.trim()) {
8874
8927
  const taskProfile = task.profile?.trim();
8875
- const agentDefault = taskProfile || parseModelTier(task.modelTier) ? null : await getAgentDefaultProfileName(agent.id);
8928
+ const taskGroup = taskProfile ? undefined : task.modelGroup?.trim();
8929
+ const agentDefault = taskProfile || taskGroup || parseModelTier(task.modelTier) ? null : await getAgentDefaultProfileName(agent.id);
8876
8930
  const repoKeys = agentDefault ? await repoModelOverrideKeys(task.vcsRepo, { includeSecrets: includeRepoSecrets }) : new Set;
8877
8931
  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;
8932
+ 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
8933
  if (picked && "modelUnsupported" in picked)
8880
8934
  return { modelUnsupported: picked.modelUnsupported };
8881
8935
  if (picked) {
@@ -8904,7 +8958,7 @@ async function recordClaimModelResolution(task, agent, { includeRepoSecrets = tr
8904
8958
  harnessProvider,
8905
8959
  workerOverrides: await getAgentModelTierOverrides(agent.id)
8906
8960
  });
8907
- const alias = await resolveTierAlias(resolvedTier, task, harnessProvider);
8961
+ const alias = await resolveTierAlias(resolvedTier, task, agent.id, harnessProvider, includeRepoSecrets);
8908
8962
  if (alias && "modelUnsupported" in alias)
8909
8963
  return { modelUnsupported: alias.modelUnsupported };
8910
8964
  if (alias) {
@@ -8952,6 +9006,7 @@ var init_model_tier_resolution = __esm(() => {
8952
9006
  init_model_profiles();
8953
9007
  init_harness_model_support();
8954
9008
  init_model_catalog_store();
9009
+ init_model_group_resolution();
8955
9010
  init_model_tier_keys();
8956
9011
  init_modelsdev_cache();
8957
9012
  init_model_tier_keys();
@@ -9003,6 +9058,9 @@ async function poolTaskRunsOnHarness(task, harness) {
9003
9058
  const profile = await getModelProfileByName(profileName);
9004
9059
  return !profile || !harness || profile.harness === harness;
9005
9060
  }
9061
+ const groupName = task?.modelGroup?.trim();
9062
+ if (groupName)
9063
+ return await groupHasMemberOnHarness(groupName, harness);
9006
9064
  const model = taskModelPin(task ?? {})?.trim();
9007
9065
  if (!model)
9008
9066
  return true;
@@ -9088,6 +9146,7 @@ var init_model_validation2 = __esm(() => {
9088
9146
  init_db4();
9089
9147
  init_model_profiles();
9090
9148
  init_model_catalog_store();
9149
+ init_model_group_resolution();
9091
9150
  init_model_tier_resolution();
9092
9151
  FREE_FORM_HARNESSES = new Set(["acp", "devin", "dsh", "cursor"]);
9093
9152
  CONTEXT_SUFFIX_RE = /\[1m\]$/i;
@@ -9298,6 +9357,76 @@ var init_model_profile_check = __esm(() => {
9298
9357
  STATE_RANK = { pass: 0, unverified: 1, warn: 2, fail: 3 };
9299
9358
  });
9300
9359
 
9360
+ // src/be/model-group-resolution.ts
9361
+ async function modelGroupMemberHarnesses(group) {
9362
+ const rows = await getDbClient2().query(`SELECT m.profileName AS profile, p.harness AS harness
9363
+ FROM model_groups g
9364
+ LEFT JOIN model_group_members m ON m.groupId = g.id
9365
+ LEFT JOIN model_profiles p ON p.name = m.profileName
9366
+ WHERE g.name = ?
9367
+ ORDER BY m.position`, [group.trim()]);
9368
+ if (rows.length === 0)
9369
+ return null;
9370
+ return rows.flatMap((row) => row.profile && row.harness ? [{ profile: row.profile, harness: row.harness }] : []);
9371
+ }
9372
+ function firstFailingCheck(result) {
9373
+ const row = result.profiles[0]?.checks.find((check) => check.state === "fail");
9374
+ if (!row)
9375
+ return "failed the profile check";
9376
+ return row.detail ? `${row.check}: ${row.detail}` : row.check;
9377
+ }
9378
+ async function resolveGroupForAgent(group, agentId, options = {}) {
9379
+ const members = await modelGroupMemberHarnesses(group);
9380
+ if (!members)
9381
+ return { kind: "missing" };
9382
+ const agent = await getAgentById2(agentId);
9383
+ const harness = agent?.harnessProvider ?? agent?.provider ?? null;
9384
+ const skipped = [];
9385
+ const from = options.startAfter ? members.findIndex((member) => member.profile === options.startAfter) + 1 : 0;
9386
+ for (let index = from;index < members.length; index++) {
9387
+ const member = members[index];
9388
+ if (options.skip?.has(member.profile))
9389
+ continue;
9390
+ if (member.harness !== harness) {
9391
+ if (options.sameHarnessOnly)
9392
+ continue;
9393
+ skipped.push({ profile: member.profile, reason: `harness: runs on ${member.harness}` });
9394
+ continue;
9395
+ }
9396
+ const result = await checkProfileForAgent(agentId, member.profile, {
9397
+ vcsRepo: options.vcsRepo,
9398
+ includeRepoSecrets: options.includeRepoSecrets,
9399
+ fallbacks: false
9400
+ });
9401
+ if (result?.ok) {
9402
+ const onHarness = members.filter((m) => m.harness === harness).map((m) => m.profile);
9403
+ return { kind: "resolved", member: member.profile, index, skipped, onHarness };
9404
+ }
9405
+ skipped.push({
9406
+ profile: member.profile,
9407
+ reason: result ? firstFailingCheck(result) : "not found"
9408
+ });
9409
+ }
9410
+ return { kind: "none", skipped };
9411
+ }
9412
+ function formatGroupSkips(skipped) {
9413
+ return skipped.map((skip) => `${skip.profile} (${skip.reason})`).join(", ");
9414
+ }
9415
+ function groupUnavailableMessage(group, harness, skipped) {
9416
+ const where = harness ? `this ${harness} agent` : "this agent";
9417
+ return `[model-group-unavailable] no member of "${group}" runs on ${where}${skipped.length > 0 ? `: ${formatGroupSkips(skipped)}` : ""}`;
9418
+ }
9419
+ async function groupHasMemberOnHarness(group, harness) {
9420
+ if (!harness)
9421
+ return true;
9422
+ const members = await modelGroupMemberHarnesses(group);
9423
+ return !members || members.some((member) => member.harness === harness);
9424
+ }
9425
+ var init_model_group_resolution = __esm(() => {
9426
+ init_db4();
9427
+ init_model_profile_check();
9428
+ });
9429
+
9301
9430
  // src/utils/provider-metadata.ts
9302
9431
  function parseProviderMeta(rawProvider, rawMeta) {
9303
9432
  if (!rawMeta || !rawProvider)
@@ -9615,6 +9744,7 @@ function rowToAgentTask(row) {
9615
9744
  resolvedEffort: ReasoningEffortSchema.safeParse(row.resolvedEffort).success ? row.resolvedEffort : undefined,
9616
9745
  profile: row.profile ?? undefined,
9617
9746
  resolvedProfile: row.resolvedProfile ?? undefined,
9747
+ modelGroup: row.modelGroup ?? undefined,
9618
9748
  fallbackHops: parseFallbackHops(row.fallbackHops),
9619
9749
  scheduleId: row.scheduleId ?? undefined,
9620
9750
  workflowRunId: row.workflowRunId ?? undefined,
@@ -9677,6 +9807,7 @@ function rowToAgentTaskSummary(row) {
9677
9807
  resolvedEffort: ReasoningEffortSchema.safeParse(row.resolvedEffort).success ? row.resolvedEffort : undefined,
9678
9808
  profile: row.profile ?? undefined,
9679
9809
  resolvedProfile: row.resolvedProfile ?? undefined,
9810
+ modelGroup: row.modelGroup ?? undefined,
9680
9811
  provider: row.provider ?? undefined,
9681
9812
  requestedByUserId: row.requestedByUserId ?? undefined,
9682
9813
  progress: row.progress ?? undefined,
@@ -10653,6 +10784,7 @@ var init_read = __esm(() => {
10653
10784
  agent_tasks.scheduleId, agent_tasks.model, agent_tasks.modelTier,
10654
10785
  agent_tasks.resolvedModel, agent_tasks.modelSource, agent_tasks.modelAlias, agent_tasks.effort,
10655
10786
  agent_tasks.resolvedEffort, agent_tasks.profile, agent_tasks.resolvedProfile,
10787
+ agent_tasks.modelGroup,
10656
10788
  agent_tasks.provider, agent_tasks.requestedByUserId, agent_tasks.progress,
10657
10789
  agent_tasks.createdAt, agent_tasks.lastUpdatedAt, agent_tasks.finishedAt,
10658
10790
  agent_tasks.statusKind, agent_tasks.peakContextPercent`,
@@ -10892,6 +11024,9 @@ async function repoModelOverrideKeys(vcsRepo, { includeSecrets = true } = {}) {
10892
11024
  return new Set(rows.map((row) => row.key));
10893
11025
  }
10894
11026
  async function taskProfileError(check) {
11027
+ const group = check.modelGroup?.trim();
11028
+ if (group)
11029
+ return await taskModelGroupError({ ...check, modelGroup: group });
10895
11030
  const name = check.profile?.trim();
10896
11031
  if (!name)
10897
11032
  return null;
@@ -10912,9 +11047,46 @@ async function taskProfileError(check) {
10912
11047
  return null;
10913
11048
  return formatProfileCheckFailures(result);
10914
11049
  }
11050
+ async function taskModelGroupError(check) {
11051
+ if (check.model?.trim() || check.modelTier?.trim() || check.profile?.trim()) {
11052
+ return "Pass `modelGroup`, or `model`/`modelTier`/`profile`, not both.";
11053
+ }
11054
+ if (!check.agentId) {
11055
+ return await modelGroupMemberHarnesses(check.modelGroup) ? null : unknownModelGroupMessage(check.modelGroup);
11056
+ }
11057
+ const resolution = await resolveGroupForAgent(check.modelGroup, check.agentId, {
11058
+ vcsRepo: check.vcsRepo
11059
+ });
11060
+ if (resolution.kind === "missing")
11061
+ return unknownModelGroupMessage(check.modelGroup);
11062
+ if (resolution.kind === "resolved")
11063
+ return null;
11064
+ const agent = await getAgentById2(check.agentId);
11065
+ return groupUnavailableMessage(check.modelGroup, agent?.harnessProvider ?? agent?.provider, resolution.skipped);
11066
+ }
11067
+ function unknownModelGroupMessage(name) {
11068
+ return `Unknown model group "${name}". List groups with GET /api/model-groups.`;
11069
+ }
11070
+ function modelGroupRefError(error) {
11071
+ const message = error instanceof Error ? error.message : "";
11072
+ return message.includes("model-group-missing:");
11073
+ }
10915
11074
  async function scheduleProfileUpdate(existing, patch) {
10916
11075
  const profile = patch.profile === undefined ? undefined : patch.profile?.trim() || null;
11076
+ const modelGroup = patch.modelGroup === undefined ? undefined : patch.modelGroup?.trim() || null;
10917
11077
  const agentId = patch.targetAgentId !== undefined ? patch.targetAgentId : existing.targetAgentId;
11078
+ if (modelGroup) {
11079
+ const error = await taskProfileError({
11080
+ modelGroup,
11081
+ profile,
11082
+ model: patch.model,
11083
+ modelTier: patch.modelTier,
11084
+ agentId
11085
+ });
11086
+ if (error)
11087
+ return { error };
11088
+ return { fields: { modelGroup, profile: null, model: null, modelTier: null } };
11089
+ }
10918
11090
  if (profile) {
10919
11091
  const error = await taskProfileError({
10920
11092
  profile,
@@ -10924,18 +11096,24 @@ async function scheduleProfileUpdate(existing, patch) {
10924
11096
  });
10925
11097
  if (error)
10926
11098
  return { error };
10927
- return { fields: { profile, model: null, modelTier: null } };
11099
+ return { fields: { profile, modelGroup: null, model: null, modelTier: null } };
10928
11100
  }
10929
- if (patch.model?.trim() || patch.modelTier?.trim() || profile === null) {
10930
- return { fields: { profile: null } };
11101
+ if (patch.model?.trim() || patch.modelTier?.trim()) {
11102
+ return { fields: { profile: null, modelGroup: null } };
10931
11103
  }
11104
+ const cleared = {
11105
+ ...profile === null ? { profile: null } : {},
11106
+ ...modelGroup === null ? { modelGroup: null } : {}
11107
+ };
10932
11108
  const agentChanged = patch.targetAgentId !== undefined && patch.targetAgentId !== existing.targetAgentId;
10933
- if (agentChanged && existing.profile) {
10934
- const error = await taskProfileError({ profile: existing.profile, agentId });
11109
+ if (agentChanged) {
11110
+ const keptProfile = profile === null ? null : existing.profile;
11111
+ const keptGroup = modelGroup === null ? null : existing.modelGroup;
11112
+ const error = keptGroup ? await taskProfileError({ modelGroup: keptGroup, agentId }) : keptProfile ? await taskProfileError({ profile: keptProfile, agentId }) : null;
10935
11113
  if (error)
10936
11114
  return { error };
10937
11115
  }
10938
- return { fields: {} };
11116
+ return { fields: cleared };
10939
11117
  }
10940
11118
  function effectiveOverride(row) {
10941
11119
  if (!row)
@@ -10954,7 +11132,9 @@ var MODEL_PROFILE_CONFIG_KEY = "MODEL_PROFILE", unreadableAllowlists, TASK_HOLDS
10954
11132
  WHERE j.value = model_profiles.name AND o.name <> model_profiles.name)`, MAX_MODEL_PROFILE_FALLBACKS = 10;
10955
11133
  var init_model_profiles = __esm(() => {
10956
11134
  init_types5();
11135
+ init_model_group_resolution();
10957
11136
  init_model_profile_check();
11137
+ init_agents();
10958
11138
  init_runtime2();
10959
11139
  init_read();
10960
11140
  unreadableAllowlists = new WeakSet;
@@ -12581,7 +12761,7 @@ async function completeTask2(id, output, options) {
12581
12761
  });
12582
12762
  } catch {}
12583
12763
  getDbClient2().afterCommit(() => {
12584
- import("./event-bus-tvf2grf4.js").then(({ workflowEventBus }) => {
12764
+ import("./event-bus-pawddp92.js").then(({ workflowEventBus }) => {
12585
12765
  workflowEventBus.emit("task.completed", {
12586
12766
  taskId: id,
12587
12767
  previousStatus: oldTask.status,
@@ -12638,7 +12818,7 @@ async function failTask2(id, reason, opts = {}) {
12638
12818
  });
12639
12819
  } catch {}
12640
12820
  getDbClient2().afterCommit(() => {
12641
- import("./event-bus-tvf2grf4.js").then(({ workflowEventBus }) => {
12821
+ import("./event-bus-pawddp92.js").then(({ workflowEventBus }) => {
12642
12822
  workflowEventBus.emit("task.failed", {
12643
12823
  taskId: id,
12644
12824
  previousStatus: oldTask.status,
@@ -12721,7 +12901,7 @@ async function cancelTask2(id, reason, options = {}) {
12721
12901
  });
12722
12902
  } catch {}
12723
12903
  getDbClient2().afterCommit(() => {
12724
- import("./event-bus-tvf2grf4.js").then(({ workflowEventBus }) => {
12904
+ import("./event-bus-pawddp92.js").then(({ workflowEventBus }) => {
12725
12905
  workflowEventBus.emit("task.cancelled", {
12726
12906
  taskId: id,
12727
12907
  previousStatus: oldTask.status,
@@ -12734,7 +12914,7 @@ async function cancelTask2(id, reason, options = {}) {
12734
12914
  if (row.source === "schedule" && row.taskType === "deferred" && row.parentTaskId) {
12735
12915
  getDbClient2().afterCommit(async () => {
12736
12916
  try {
12737
- const { createWorkerTaskFollowUp } = await import("./worker-follow-up-fg48vk6d.js");
12917
+ const { createWorkerTaskFollowUp } = await import("./worker-follow-up-zwgg20sr.js");
12738
12918
  await createWorkerTaskFollowUp({
12739
12919
  task: rowToAgentTask(row),
12740
12920
  status: "failed",
@@ -12783,7 +12963,7 @@ async function skipTask2(id, reason, opts = {}) {
12783
12963
  });
12784
12964
  } catch {}
12785
12965
  getDbClient2().afterCommit(() => {
12786
- import("./event-bus-tvf2grf4.js").then(({ workflowEventBus }) => {
12966
+ import("./event-bus-pawddp92.js").then(({ workflowEventBus }) => {
12787
12967
  workflowEventBus.emit("task.skipped", {
12788
12968
  taskId: id,
12789
12969
  failureReason: skipReason,
@@ -12842,7 +13022,7 @@ async function supersedeTask2(id, args) {
12842
13022
  });
12843
13023
  } catch {}
12844
13024
  getDbClient2().afterCommit(() => {
12845
- import("./event-bus-tvf2grf4.js").then(({ workflowEventBus }) => {
13025
+ import("./event-bus-pawddp92.js").then(({ workflowEventBus }) => {
12846
13026
  workflowEventBus.emit("task.superseded", {
12847
13027
  taskId: id,
12848
13028
  reason: args.reason,
@@ -13078,7 +13258,7 @@ async function updateTaskProgress2(id, progress) {
13078
13258
  });
13079
13259
  } catch {}
13080
13260
  getDbClient2().afterCommit(() => {
13081
- import("./event-bus-tvf2grf4.js").then(({ workflowEventBus }) => {
13261
+ import("./event-bus-pawddp92.js").then(({ workflowEventBus }) => {
13082
13262
  workflowEventBus.emit("task.progress", {
13083
13263
  taskId: id,
13084
13264
  progress: scrubbedProgress,
@@ -13403,9 +13583,8 @@ function rowToWorkflowRunStep(row, view = "replay") {
13403
13583
  target: `the output of step ${row.id} (node ${row.nodeId})`
13404
13584
  });
13405
13585
  }
13406
- async function getWorkflowRunTriggeredByAgentId(runId) {
13407
- const row = await getDbClient2().get("SELECT triggeredByAgentId FROM workflow_runs WHERE id = ?", [runId]);
13408
- return row?.triggeredByAgentId ?? null;
13586
+ async function getWorkflowRunPrincipalRow(runId) {
13587
+ return await getDbClient2().get("SELECT principal, triggeredByAgentId FROM workflow_runs WHERE id = ?", [runId]) ?? null;
13409
13588
  }
13410
13589
  async function getWorkflowRunSummary(id) {
13411
13590
  const row = await getDbClient2().get(`SELECT ${WORKFLOW_RUN_SUMMARY_COLUMNS} FROM workflow_runs WHERE id = ?`, [id]);
@@ -13665,7 +13844,7 @@ function emitRunFinished(runId, workflowId, status) {
13665
13844
  }
13666
13845
  function emitBusEventAfterCommit(event, payload) {
13667
13846
  getDbClient2().afterCommit(() => {
13668
- import("./event-bus-tvf2grf4.js").then(({ workflowEventBus }) => {
13847
+ import("./event-bus-pawddp92.js").then(({ workflowEventBus }) => {
13669
13848
  workflowEventBus.emit(event, payload);
13670
13849
  }).catch((err) => console.error(`[db] ${event} event not emitted:`, scrubSecrets(err instanceof Error ? err.message : String(err))));
13671
13850
  });
@@ -14325,6 +14504,16 @@ function booleanValidators(keys) {
14325
14504
  }
14326
14505
  ]));
14327
14506
  }
14507
+ function scheduleIdsValidator(key) {
14508
+ const message = `Invalid ${key} (must be comma-separated schedule UUIDs)`;
14509
+ return {
14510
+ [key]: (value) => {
14511
+ if (typeof value !== "string")
14512
+ return message;
14513
+ return parseFollowUpGateScheduleIds(value).every(isFollowUpGateScheduleId) ? null : message;
14514
+ }
14515
+ };
14516
+ }
14328
14517
  function enumValidator(key, options) {
14329
14518
  const listed = options.filter(Boolean).join(", ");
14330
14519
  const message = `Invalid ${key} value (must be one of: ${listed}${options.includes("") ? ", or empty" : ""})`;
@@ -14499,6 +14688,8 @@ var init_swarm_config_guard = __esm(() => {
14499
14688
  "CLOUDFLARE_API_BASE_URL",
14500
14689
  "GITHUB_URL",
14501
14690
  "GITHUB_API_URL",
14691
+ "LINEAR_URL",
14692
+ "LINEAR_API_URL",
14502
14693
  "GITHUB_APP_INSTALLATION_ID",
14503
14694
  "GITHUB_APP_REPO_OWNERS",
14504
14695
  "OPENCODE_SDK_PATH",
@@ -14514,7 +14705,8 @@ var init_swarm_config_guard = __esm(() => {
14514
14705
  "NODE_PATH",
14515
14706
  "BUN_OPTIONS",
14516
14707
  "GCONV_PATH",
14517
- "GLIBC_TUNABLES"
14708
+ "GLIBC_TUNABLES",
14709
+ "CLAUDE_BINARY"
14518
14710
  ]);
14519
14711
  API_PROCESS_CONTROL_ENV_PREFIXES = ["LD_", "DYLD_", "BASH_", "BUN_INSPECT"];
14520
14712
  API_ONLY_CONFIG_KEYS = new Set([
@@ -14652,13 +14844,9 @@ var init_swarm_config_guard = __esm(() => {
14652
14844
  ...enumValidator("MODEL_WINDOW_EXHAUSTED_POLICY", ["fail", "fallback"]),
14653
14845
  ...enumValidator("CREDENTIAL_SELECTION_STRATEGY", [...CREDENTIAL_SELECTION_STRATEGIES]),
14654
14846
  ...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
- },
14847
+ ...enumValidator("FOLLOW_UP_GATE_MODE", ["off", "shadow", "enforce"]),
14848
+ ...scheduleIdsValidator("FOLLOW_UP_GATE_SCHEDULE_IDS"),
14849
+ ...scheduleIdsValidator("FOLLOW_UP_GATE_ENFORCE_SCHEDULE_IDS"),
14662
14850
  ...enumValidator("SYSTEM_ONE_DEFAULT_PROVIDER", [...SYSTEM_ONE_DEFAULT_PROVIDER_OPTIONS]),
14663
14851
  ...enumValidator("SYSTEM_ONE_EXTRACT_DEFAULT_PROVIDER", [
14664
14852
  ...SYSTEM_ONE_EXTRACT_DEFAULT_PROVIDER_OPTIONS
@@ -14720,6 +14908,7 @@ var init_swarm_config_guard = __esm(() => {
14720
14908
  "CHAT_SDK_ENABLED",
14721
14909
  "SLACK_RENDER_V2",
14722
14910
  "SLACK_RENDER_V2_TASK_TREE_ENABLED",
14911
+ "SLACK_REPLY_FOOTER_ENABLED",
14723
14912
  "SLACK_RENDER_V2_DELEGATION",
14724
14913
  "SLACK_BLOCK_EXTERNAL_CHANNELS",
14725
14914
  "GITHUB_DISABLE",
@@ -15650,7 +15839,7 @@ var sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
15650
15839
  var init_sleep = () => {};
15651
15840
 
15652
15841
  // node_modules/openai/version.mjs
15653
- var VERSION = "6.40.0";
15842
+ var VERSION = "6.49.0";
15654
15843
  var init_version = () => {};
15655
15844
 
15656
15845
  // node_modules/openai/internal/detect-platform.mjs
@@ -16338,7 +16527,7 @@ var levelNumbers, parseLogLevel = (maybeLevel, sourceName, client) => {
16338
16527
  if (details.headers) {
16339
16528
  details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [
16340
16529
  name,
16341
- name.toLowerCase() === "authorization" || name.toLowerCase() === "api-key" || name.toLowerCase() === "x-api-key" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value
16530
+ 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
16531
  ]));
16343
16532
  }
16344
16533
  if ("retryOfRequestLogID" in details) {
@@ -16540,14 +16729,45 @@ var init_streaming = __esm(() => {
16540
16729
  let consumed = false;
16541
16730
  async function* iterLines() {
16542
16731
  const lineDecoder = new LineDecoder;
16543
- const iter = ReadableStreamToAsyncIterable(readableStream);
16544
- for await (const chunk of iter) {
16545
- for (const line of lineDecoder.decode(chunk)) {
16732
+ const reader = readableStream.getReader();
16733
+ let closed = false;
16734
+ let cancelPromise;
16735
+ const cancel = () => {
16736
+ cancelPromise ?? (cancelPromise = reader.cancel());
16737
+ cancelPromise.catch(() => {});
16738
+ };
16739
+ controller.signal.addEventListener("abort", cancel, { once: true });
16740
+ try {
16741
+ if (controller.signal.aborted) {
16742
+ cancel();
16743
+ return;
16744
+ }
16745
+ while (true) {
16746
+ const { value: chunk, done } = await reader.read();
16747
+ if (done) {
16748
+ closed = true;
16749
+ break;
16750
+ }
16751
+ if (controller.signal.aborted)
16752
+ return;
16753
+ for (const line of lineDecoder.decode(chunk)) {
16754
+ if (controller.signal.aborted)
16755
+ return;
16756
+ yield line;
16757
+ }
16758
+ }
16759
+ if (controller.signal.aborted)
16760
+ return;
16761
+ for (const line of lineDecoder.flush()) {
16762
+ if (controller.signal.aborted)
16763
+ return;
16546
16764
  yield line;
16547
16765
  }
16548
- }
16549
- for (const line of lineDecoder.flush()) {
16550
- yield line;
16766
+ } finally {
16767
+ controller.signal.removeEventListener("abort", cancel);
16768
+ if (!closed)
16769
+ cancel();
16770
+ reader.releaseLock();
16551
16771
  }
16552
16772
  }
16553
16773
  async function* iterator() {
@@ -16565,7 +16785,7 @@ var init_streaming = __esm(() => {
16565
16785
  }
16566
16786
  done = true;
16567
16787
  } catch (e) {
16568
- if (isAbortError(e))
16788
+ if (controller.signal.aborted || isAbortError(e))
16569
16789
  return;
16570
16790
  throw e;
16571
16791
  } finally {
@@ -16945,13 +17165,17 @@ class WorkloadIdentityAuth {
16945
17165
  throw APIError.generate(response.status, body, `Token exchange failed with status ${response.status}`, response.headers);
16946
17166
  }
16947
17167
  const tokenResponse = await response.json();
16948
- const expiresIn = tokenResponse.expires_in || 3600;
17168
+ if (typeof tokenResponse !== "object" || tokenResponse === null || !("access_token" in tokenResponse) || typeof tokenResponse.access_token !== "string" || tokenResponse.access_token.trim().length === 0) {
17169
+ throw new OpenAIError("Token exchange response missing 'access_token' field");
17170
+ }
17171
+ const accessToken = tokenResponse.access_token;
17172
+ const expiresIn = tokenResponse.expires_in ?? 3600;
16949
17173
  const expiresAt = Date.now() + expiresIn * 1000;
16950
17174
  this.cachedToken = {
16951
- token: tokenResponse.access_token,
17175
+ token: accessToken,
16952
17176
  expiresAt
16953
17177
  };
16954
- return tokenResponse.access_token;
17178
+ return accessToken;
16955
17179
  }
16956
17180
  isTokenExpired(cachedToken) {
16957
17181
  return Date.now() >= cachedToken.expiresAt;
@@ -16976,7 +17200,88 @@ var init_workload_identity_auth = __esm(() => {
16976
17200
  };
16977
17201
  });
16978
17202
 
17203
+ // node_modules/openai/internal/headers.mjs
17204
+ function* iterateHeaders(headers) {
17205
+ if (!headers)
17206
+ return;
17207
+ if (brand_privateNullableHeaders in headers) {
17208
+ const { values, nulls } = headers;
17209
+ yield* values.entries();
17210
+ for (const name of nulls) {
17211
+ yield [name, null];
17212
+ }
17213
+ return;
17214
+ }
17215
+ let shouldClear = false;
17216
+ let iter;
17217
+ if (headers instanceof Headers) {
17218
+ iter = headers.entries();
17219
+ } else if (isReadonlyArray(headers)) {
17220
+ iter = headers;
17221
+ } else {
17222
+ shouldClear = true;
17223
+ iter = Object.entries(headers ?? {});
17224
+ }
17225
+ for (let row of iter) {
17226
+ const name = row[0];
17227
+ if (typeof name !== "string")
17228
+ throw new TypeError("expected header name to be a string");
17229
+ const values = isReadonlyArray(row[1]) ? row[1] : [row[1]];
17230
+ let didClear = false;
17231
+ for (const value of values) {
17232
+ if (value === undefined)
17233
+ continue;
17234
+ if (shouldClear && !didClear) {
17235
+ didClear = true;
17236
+ yield [name, null];
17237
+ }
17238
+ yield [name, value];
17239
+ }
17240
+ }
17241
+ }
17242
+ var brand_privateNullableHeaders, httpTokenHeaderName, buildHeaders = (newHeaders) => {
17243
+ const targetHeaders = new Headers;
17244
+ const nullHeaders = new Set;
17245
+ for (const headers of newHeaders) {
17246
+ const seenHeaders = new Set;
17247
+ for (const [name, value] of iterateHeaders(headers)) {
17248
+ if (!httpTokenHeaderName.test(name)) {
17249
+ throw new TypeError(`Header name must be a valid HTTP token ["${name}"]`);
17250
+ }
17251
+ const lowerName = name.toLowerCase();
17252
+ if (!seenHeaders.has(lowerName)) {
17253
+ targetHeaders.delete(lowerName);
17254
+ seenHeaders.add(lowerName);
17255
+ }
17256
+ if (value === null) {
17257
+ targetHeaders.delete(lowerName);
17258
+ nullHeaders.add(lowerName);
17259
+ } else {
17260
+ targetHeaders.append(lowerName, value);
17261
+ nullHeaders.delete(lowerName);
17262
+ }
17263
+ }
17264
+ }
17265
+ return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders };
17266
+ };
17267
+ var init_headers = __esm(() => {
17268
+ init_values();
17269
+ brand_privateNullableHeaders = /* @__PURE__ */ Symbol("brand.privateNullableHeaders");
17270
+ httpTokenHeaderName = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
17271
+ });
17272
+
16979
17273
  // node_modules/openai/internal/uploads.mjs
17274
+ function toStreamingFile(data, name, options) {
17275
+ if (!name) {
17276
+ throw new TypeError("toStreamingFile requires a non-empty file name");
17277
+ }
17278
+ return {
17279
+ [brand_privateStreamingFile]: true,
17280
+ data,
17281
+ name,
17282
+ ...options?.type ? { type: options.type } : {}
17283
+ };
17284
+ }
16980
17285
  function makeFile(fileBits, fileName, options) {
16981
17286
  checkFileSupport();
16982
17287
  return new File(fileBits, fileName ?? "unknown_file", options);
@@ -17004,7 +17309,108 @@ function supportsFormData(fetchObject) {
17004
17309
  supportsFormDataMap.set(fetch2, promise);
17005
17310
  return promise;
17006
17311
  }
17007
- var checkFileSupport = () => {
17312
+ async function* iterateMultipartBody(body, boundary) {
17313
+ for await (const { key, value } of iterateFormEntries(body)) {
17314
+ yield encodeUTF8(`--${boundary}\r
17315
+ `);
17316
+ if (isUploadable(value)) {
17317
+ const filename = getStreamingFileName(value);
17318
+ const type = getStreamingFileType(value);
17319
+ yield encodeUTF8(`Content-Disposition: form-data; name="${escapeHeaderValue(key)}"; filename="${escapeHeaderValue(filename)}"\r
17320
+ ` + `Content-Type: ${type}\r
17321
+ \r
17322
+ `);
17323
+ yield* iterateBytes(getStreamingFileData(value));
17324
+ } else {
17325
+ yield encodeUTF8(`Content-Disposition: form-data; name="${escapeHeaderValue(key)}"\r
17326
+ \r
17327
+ ${String(value)}`);
17328
+ }
17329
+ yield encodeUTF8(`\r
17330
+ `);
17331
+ }
17332
+ yield encodeUTF8(`--${boundary}--\r
17333
+ `);
17334
+ }
17335
+ async function* iterateFormEntries(body) {
17336
+ if (!body || typeof body !== "object")
17337
+ return;
17338
+ for (const [key, value] of Object.entries(body)) {
17339
+ yield* iterateFormValue(key, value);
17340
+ }
17341
+ }
17342
+ async function* iterateFormValue(key, value) {
17343
+ if (value === undefined)
17344
+ return;
17345
+ if (value == null) {
17346
+ throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
17347
+ }
17348
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || isUploadable(value)) {
17349
+ yield { key, value };
17350
+ } else if (Array.isArray(value)) {
17351
+ for (const entry of value) {
17352
+ yield* iterateFormValue(key + "[]", entry);
17353
+ }
17354
+ } else if (typeof value === "object") {
17355
+ for (const [name, prop] of Object.entries(value)) {
17356
+ yield* iterateFormValue(`${key}[${name}]`, prop);
17357
+ }
17358
+ } else {
17359
+ throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
17360
+ }
17361
+ }
17362
+ function getStreamingFileName(value) {
17363
+ return isStreamingFile(value) ? value.name : getName(value) ?? "unknown_file";
17364
+ }
17365
+ function getStreamingFileType(value) {
17366
+ if (isStreamingFile(value))
17367
+ return value.type || "application/octet-stream";
17368
+ if (isNamedBlob(value) && value.type)
17369
+ return value.type;
17370
+ if (value instanceof Response)
17371
+ return value.headers.get("content-type") || "application/octet-stream";
17372
+ return "application/octet-stream";
17373
+ }
17374
+ function getStreamingFileData(value) {
17375
+ if (isStreamingFile(value))
17376
+ return value.data;
17377
+ return value;
17378
+ }
17379
+ async function* iterateBytes(value) {
17380
+ if (typeof value === "string") {
17381
+ yield encodeUTF8(value);
17382
+ } else if (ArrayBuffer.isView(value)) {
17383
+ yield new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
17384
+ } else if (value instanceof ArrayBuffer) {
17385
+ yield new Uint8Array(value);
17386
+ } else if (value instanceof Response) {
17387
+ if (value.body) {
17388
+ yield* iterateBytes(value.body);
17389
+ } else {
17390
+ yield* iterateBytes(await value.blob());
17391
+ }
17392
+ } else if (value instanceof Blob) {
17393
+ if (typeof value.stream === "function") {
17394
+ yield* iterateBytes(value.stream());
17395
+ } else {
17396
+ yield new Uint8Array(await value.arrayBuffer());
17397
+ }
17398
+ } else if (isReadableStream(value)) {
17399
+ for await (const chunk of ReadableStreamToAsyncIterable(value)) {
17400
+ yield* iterateBytes(chunk);
17401
+ }
17402
+ } else if (isAsyncIterable(value)) {
17403
+ for await (const chunk of value) {
17404
+ yield* iterateBytes(chunk);
17405
+ }
17406
+ } else {
17407
+ throw new TypeError(`Invalid streaming file chunk: ${String(value)}`);
17408
+ }
17409
+ }
17410
+ function escapeHeaderValue(value) {
17411
+ return value.replace(/["\\\r\n]/g, (character) => encodeURIComponent(character));
17412
+ }
17413
+ var brand_privateStreamingFile, checkFileSupport = () => {
17008
17414
  if (typeof File === "undefined") {
17009
17415
  const { process: process2 } = globalThis;
17010
17416
  const isOldNode = typeof process2?.versions?.node === "string" && parseInt(process2.versions.node.split(".")) < 20;
@@ -17013,8 +17419,14 @@ var checkFileSupport = () => {
17013
17419
  }, isAsyncIterable = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function", maybeMultipartFormRequestOptions = async (opts, fetch2) => {
17014
17420
  if (!hasUploadableValue(opts.body))
17015
17421
  return opts;
17422
+ if (hasStreamingUploadableValue(opts.body)) {
17423
+ return createStreamingFormRequestOptions(opts);
17424
+ }
17016
17425
  return { ...opts, body: await createForm(opts.body, fetch2) };
17017
17426
  }, multipartFormRequestOptions = async (opts, fetch2) => {
17427
+ if (hasStreamingUploadableValue(opts.body)) {
17428
+ return createStreamingFormRequestOptions(opts);
17429
+ }
17018
17430
  return { ...opts, body: await createForm(opts.body, fetch2) };
17019
17431
  }, supportsFormDataMap, createForm = async (body, fetch2) => {
17020
17432
  if (!await supportsFormData(fetch2)) {
@@ -17023,7 +17435,19 @@ var checkFileSupport = () => {
17023
17435
  const form = new FormData;
17024
17436
  await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));
17025
17437
  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) => {
17438
+ }, 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) => {
17439
+ if (isStreamingFile(value) || isAsyncIterable(value) || isReadableStream(value))
17440
+ return true;
17441
+ if (Array.isArray(value))
17442
+ return value.some(hasStreamingUploadableValue);
17443
+ if (value && typeof value === "object" && !isNamedBlob(value) && !(value instanceof Response)) {
17444
+ for (const k in value) {
17445
+ if (hasStreamingUploadableValue(value[k]))
17446
+ return true;
17447
+ }
17448
+ }
17449
+ return false;
17450
+ }, hasUploadableValue = (value) => {
17027
17451
  if (isUploadable(value))
17028
17452
  return true;
17029
17453
  if (Array.isArray(value))
@@ -17035,6 +17459,14 @@ var checkFileSupport = () => {
17035
17459
  }
17036
17460
  }
17037
17461
  return false;
17462
+ }, createStreamingFormRequestOptions = (opts) => {
17463
+ const boundary = `openai-${Math.random().toString(36).slice(2)}`;
17464
+ const body = ReadableStreamFrom(iterateMultipartBody(opts.body, boundary));
17465
+ return {
17466
+ ...opts,
17467
+ body,
17468
+ headers: buildHeaders([{ "content-type": `multipart/form-data; boundary=${boundary}` }, opts.headers])
17469
+ };
17038
17470
  }, addFormValue = async (form, key, value) => {
17039
17471
  if (value === undefined)
17040
17472
  return;
@@ -17058,7 +17490,10 @@ var checkFileSupport = () => {
17058
17490
  }
17059
17491
  };
17060
17492
  var init_uploads = __esm(() => {
17493
+ init_headers();
17061
17494
  init_shims();
17495
+ init_bytes();
17496
+ brand_privateStreamingFile = /* @__PURE__ */ Symbol("brand.privateStreamingFile");
17062
17497
  supportsFormDataMap = /* @__PURE__ */ new WeakMap;
17063
17498
  });
17064
17499
 
@@ -17117,6 +17552,7 @@ var init_to_file = __esm(() => {
17117
17552
 
17118
17553
  // node_modules/openai/core/uploads.mjs
17119
17554
  var init_uploads2 = __esm(() => {
17555
+ init_uploads();
17120
17556
  init_to_file();
17121
17557
  });
17122
17558
 
@@ -17334,6 +17770,7 @@ class EventStream {
17334
17770
  _EventStream_resolveEndPromise.set(this, () => {});
17335
17771
  _EventStream_rejectEndPromise.set(this, () => {});
17336
17772
  _EventStream_listeners.set(this, {});
17773
+ _EventStream_abortListeners.set(this, []);
17337
17774
  _EventStream_ended.set(this, false);
17338
17775
  _EventStream_errored.set(this, false);
17339
17776
  _EventStream_aborted.set(this, false);
@@ -17351,8 +17788,13 @@ class EventStream {
17351
17788
  }
17352
17789
  _run(executor) {
17353
17790
  setTimeout(() => {
17354
- executor().then(() => {
17355
- this._emitFinal();
17791
+ Promise.resolve().then(executor).then(() => {
17792
+ try {
17793
+ this._emitFinal();
17794
+ } catch (error) {
17795
+ __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_handleError).call(this, error);
17796
+ return;
17797
+ }
17356
17798
  this._emit("end");
17357
17799
  }, __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_handleError).bind(this));
17358
17800
  }, 0);
@@ -17375,6 +17817,17 @@ class EventStream {
17375
17817
  abort() {
17376
17818
  this.controller.abort();
17377
17819
  }
17820
+ _listenForAbort(signal) {
17821
+ if (!signal || this.ended)
17822
+ return;
17823
+ if (signal.aborted) {
17824
+ this.controller.abort();
17825
+ return;
17826
+ }
17827
+ const listener = () => this.controller.abort();
17828
+ signal.addEventListener("abort", listener, { once: true });
17829
+ __classPrivateFieldGet(this, _EventStream_abortListeners, "f").push({ signal, listener });
17830
+ }
17378
17831
  on(event, listener) {
17379
17832
  const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = []);
17380
17833
  listeners.push({ listener });
@@ -17402,6 +17855,90 @@ class EventStream {
17402
17855
  this.once(event, resolve);
17403
17856
  });
17404
17857
  }
17858
+ events(event) {
17859
+ const pushQueue = [];
17860
+ const readQueue = [];
17861
+ let ended = this.ended;
17862
+ let failure;
17863
+ let failureDelivered = false;
17864
+ const doneResult = () => ({ value: undefined, done: true });
17865
+ const finishReaders = () => {
17866
+ while (readQueue.length) {
17867
+ readQueue.shift().resolve(doneResult());
17868
+ }
17869
+ };
17870
+ const rejectReader = () => {
17871
+ if (!failure || failureDelivered || !readQueue.length)
17872
+ return;
17873
+ failureDelivered = true;
17874
+ readQueue.shift().reject(failure);
17875
+ };
17876
+ const cleanup = () => {
17877
+ this.off(event, onEvent);
17878
+ this.off("end", onEnd);
17879
+ if (event !== "error")
17880
+ this.off("error", onFailure);
17881
+ if (event !== "abort")
17882
+ this.off("abort", onFailure);
17883
+ };
17884
+ const onEvent = (...args) => {
17885
+ if (ended)
17886
+ return;
17887
+ const reader = readQueue.shift();
17888
+ if (reader) {
17889
+ reader.resolve({ value: args, done: false });
17890
+ } else {
17891
+ pushQueue.push(args);
17892
+ }
17893
+ };
17894
+ const onFailure = (error) => {
17895
+ failure = error;
17896
+ if (!pushQueue.length)
17897
+ rejectReader();
17898
+ };
17899
+ const onEnd = () => {
17900
+ ended = true;
17901
+ cleanup();
17902
+ if (!pushQueue.length) {
17903
+ rejectReader();
17904
+ finishReaders();
17905
+ }
17906
+ };
17907
+ if (!ended) {
17908
+ this.on(event, onEvent);
17909
+ this.on("end", onEnd);
17910
+ if (event !== "error")
17911
+ this.on("error", onFailure);
17912
+ if (event !== "abort")
17913
+ this.on("abort", onFailure);
17914
+ }
17915
+ return {
17916
+ next: () => {
17917
+ const value = pushQueue.shift();
17918
+ if (value)
17919
+ return Promise.resolve({ value, done: false });
17920
+ if (failure && !failureDelivered) {
17921
+ failureDelivered = true;
17922
+ return Promise.reject(failure);
17923
+ }
17924
+ if (ended)
17925
+ return Promise.resolve(doneResult());
17926
+ return new Promise((resolve, reject) => {
17927
+ readQueue.push({ resolve, reject });
17928
+ });
17929
+ },
17930
+ return: () => {
17931
+ ended = true;
17932
+ pushQueue.length = 0;
17933
+ cleanup();
17934
+ finishReaders();
17935
+ return Promise.resolve(doneResult());
17936
+ },
17937
+ [Symbol.asyncIterator]() {
17938
+ return this;
17939
+ }
17940
+ };
17941
+ }
17405
17942
  async done() {
17406
17943
  __classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f");
17407
17944
  await __classPrivateFieldGet(this, _EventStream_endPromise, "f");
@@ -17411,6 +17948,7 @@ class EventStream {
17411
17948
  return;
17412
17949
  }
17413
17950
  if (event === "end") {
17951
+ __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_removeAbortListeners).call(this);
17414
17952
  __classPrivateFieldSet(this, _EventStream_ended, true, "f");
17415
17953
  __classPrivateFieldGet(this, _EventStream_resolveEndPromise, "f").call(this);
17416
17954
  }
@@ -17441,11 +17979,15 @@ class EventStream {
17441
17979
  }
17442
17980
  _emitFinal() {}
17443
17981
  }
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;
17982
+ 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
17983
  var init_EventStream = __esm(() => {
17446
17984
  init_tslib();
17447
17985
  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) {
17986
+ _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() {
17987
+ for (const { signal, listener } of __classPrivateFieldGet(this, _EventStream_abortListeners, "f").splice(0)) {
17988
+ signal.removeEventListener("abort", listener);
17989
+ }
17990
+ }, _EventStream_handleError = function _EventStream_handleError(error) {
17449
17991
  __classPrivateFieldSet(this, _EventStream_errored, true, "f");
17450
17992
  if (error instanceof Error && error.name === "AbortError") {
17451
17993
  error = new APIUserAbortError;
@@ -17473,10 +18015,58 @@ function isRunnableFunctionWithParse(fn) {
17473
18015
  var init_RunnableFunction = () => {};
17474
18016
 
17475
18017
  // node_modules/openai/lib/AbstractChatCompletionRunner.mjs
18018
+ function normalizeToolCallIds(chatCompletion) {
18019
+ for (const choice of chatCompletion.choices) {
18020
+ for (const toolCall of choice.message.tool_calls ?? []) {
18021
+ if (!toolCall.id) {
18022
+ toolCall.id = `call_${uuid4()}`;
18023
+ }
18024
+ }
18025
+ }
18026
+ }
18027
+ function toRequestMessage(message) {
18028
+ if (!isAssistantMessage(message))
18029
+ return message;
18030
+ const requestMessage = { role: "assistant" };
18031
+ if (message.audio != null)
18032
+ requestMessage.audio = { id: message.audio.id };
18033
+ if (message.content !== undefined)
18034
+ requestMessage.content = message.content;
18035
+ if (message.function_call != null)
18036
+ requestMessage.function_call = message.function_call;
18037
+ if (message.name !== undefined)
18038
+ requestMessage.name = message.name;
18039
+ if (message.refusal != null)
18040
+ requestMessage.refusal = message.refusal;
18041
+ if (message.tool_calls !== undefined) {
18042
+ requestMessage.tool_calls = message.tool_calls.map((toolCall) => {
18043
+ if (toolCall.type === "custom") {
18044
+ return {
18045
+ id: toolCall.id,
18046
+ type: toolCall.type,
18047
+ custom: {
18048
+ input: toolCall.custom.input,
18049
+ name: toolCall.custom.name
18050
+ }
18051
+ };
18052
+ }
18053
+ return {
18054
+ id: toolCall.id,
18055
+ type: toolCall.type,
18056
+ function: {
18057
+ arguments: toolCall.function.arguments,
18058
+ name: toolCall.function.name
18059
+ }
18060
+ };
18061
+ });
18062
+ }
18063
+ return requestMessage;
18064
+ }
17476
18065
  var _AbstractChatCompletionRunner_instances, _AbstractChatCompletionRunner_getFinalContent, _AbstractChatCompletionRunner_getFinalMessage, _AbstractChatCompletionRunner_getFinalFunctionToolCall, _AbstractChatCompletionRunner_getFinalFunctionToolCallResult, _AbstractChatCompletionRunner_calculateTotalUsage, _AbstractChatCompletionRunner_validateParams, _AbstractChatCompletionRunner_stringifyFunctionCallResult, DEFAULT_MAX_CHAT_COMPLETIONS = 10, AbstractChatCompletionRunner;
17477
18066
  var init_AbstractChatCompletionRunner = __esm(() => {
17478
18067
  init_tslib();
17479
18068
  init_error2();
18069
+ init_uuid();
17480
18070
  init_parser();
17481
18071
  init_chatCompletionUtils();
17482
18072
  init_EventStream();
@@ -17489,6 +18079,7 @@ var init_AbstractChatCompletionRunner = __esm(() => {
17489
18079
  this.messages = [];
17490
18080
  }
17491
18081
  _addChatCompletion(chatCompletion) {
18082
+ normalizeToolCallIds(chatCompletion);
17492
18083
  this._chatCompletions.push(chatCompletion);
17493
18084
  this._emit("chatCompletion", chatCompletion);
17494
18085
  const message = chatCompletion.choices[0]?.message;
@@ -17564,12 +18155,7 @@ var init_AbstractChatCompletionRunner = __esm(() => {
17564
18155
  }
17565
18156
  }
17566
18157
  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
- }
18158
+ this._listenForAbort(options?.signal);
17573
18159
  __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params);
17574
18160
  const chatCompletion = await client.chat.completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal });
17575
18161
  this._connected();
@@ -17581,11 +18167,12 @@ var init_AbstractChatCompletionRunner = __esm(() => {
17581
18167
  }
17582
18168
  return await this._createChatCompletion(client, params, options);
17583
18169
  }
17584
- async _runTools(client, params, options) {
18170
+ async _runTools(client, params, runner, options) {
17585
18171
  const role = "tool";
17586
- const { tool_choice = "auto", stream, ...restParams } = params;
18172
+ const { tool_choice = "auto", stream, toolContext: inputToolContext, ...restParams } = params;
18173
+ const toolContext = inputToolContext;
17587
18174
  const singleFunctionToCall = typeof tool_choice !== "string" && tool_choice.type === "function" && tool_choice?.function?.name;
17588
- const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {};
18175
+ const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS, afterCompletion } = options || {};
17589
18176
  const inputTools = params.tools.map((tool) => {
17590
18177
  if (isAutoParsableTool(tool)) {
17591
18178
  if (!tool.$callback) {
@@ -17623,50 +18210,74 @@ var init_AbstractChatCompletionRunner = __esm(() => {
17623
18210
  for (const message of params.messages) {
17624
18211
  this._addMessage(message, false);
17625
18212
  }
18213
+ const runToolCall = async (toolCall) => {
18214
+ if (toolCall.type !== "function")
18215
+ return { message: undefined, functionCalled: false };
18216
+ const tool_call_id = toolCall.id;
18217
+ const { name, arguments: args } = toolCall.function;
18218
+ const fn = functionsByName[name];
18219
+ if (!fn) {
18220
+ const content = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys(functionsByName).map((name) => JSON.stringify(name)).join(", ")}. Please try again`;
18221
+ return { message: { role, tool_call_id, content }, functionCalled: false };
18222
+ }
18223
+ if (singleFunctionToCall && singleFunctionToCall !== name) {
18224
+ const content = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`;
18225
+ return { message: { role, tool_call_id, content }, functionCalled: false };
18226
+ }
18227
+ let rawContent;
18228
+ if (isRunnableFunctionWithParse(fn)) {
18229
+ let parsed;
18230
+ try {
18231
+ parsed = await fn.parse(args);
18232
+ } catch (error) {
18233
+ const content = error instanceof Error ? error.message : String(error);
18234
+ return { message: { role, tool_call_id, content }, functionCalled: false };
18235
+ }
18236
+ rawContent = await fn.function(parsed, runner, toolContext);
18237
+ } else {
18238
+ rawContent = await fn.function(args, runner, toolContext);
18239
+ }
18240
+ const content = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);
18241
+ return { message: { role, tool_call_id, content }, functionCalled: true };
18242
+ };
17626
18243
  for (let i = 0;i < maxChatCompletions; ++i) {
17627
18244
  const chatCompletion = await this._createChatCompletion(client, {
17628
18245
  ...restParams,
17629
18246
  tool_choice,
17630
18247
  tools,
17631
- messages: [...this.messages]
18248
+ messages: this.messages.map(toRequestMessage)
17632
18249
  }, options);
17633
18250
  const message = chatCompletion.choices[0]?.message;
17634
18251
  if (!message) {
17635
18252
  throw new OpenAIError(`missing message in ChatCompletion response`);
17636
18253
  }
17637
18254
  if (!message.tool_calls?.length) {
18255
+ await afterCompletion?.(chatCompletion, runner);
17638
18256
  return;
17639
18257
  }
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;
18258
+ if (singleFunctionToCall || params.parallel_tool_calls === false) {
18259
+ for (const toolCall of message.tool_calls) {
18260
+ const result = await runToolCall(toolCall);
18261
+ if (result.message)
18262
+ this._addMessage(result.message);
18263
+ if (singleFunctionToCall && result.functionCalled) {
18264
+ await afterCompletion?.(chatCompletion, runner);
18265
+ return;
18266
+ }
17654
18267
  }
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;
18268
+ } else {
18269
+ const results = await Promise.allSettled(message.tool_calls.map(runToolCall));
18270
+ for (const result of results) {
18271
+ if (result.status === "rejected")
18272
+ throw result.reason;
17662
18273
  }
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;
18274
+ for (const result of results) {
18275
+ if (result.status === "fulfilled" && result.value.message) {
18276
+ this._addMessage(result.value.message);
18277
+ }
17668
18278
  }
17669
18279
  }
18280
+ await afterCompletion?.(chatCompletion, runner);
17670
18281
  }
17671
18282
  return;
17672
18283
  }
@@ -17691,7 +18302,12 @@ var init_AbstractChatCompletionRunner = __esm(() => {
17691
18302
  for (let i = this.messages.length - 1;i >= 0; i--) {
17692
18303
  const message = this.messages[i];
17693
18304
  if (isAssistantMessage(message) && message?.tool_calls?.length) {
17694
- return message.tool_calls.filter((x) => x.type === "function").at(-1)?.function;
18305
+ for (let j = message.tool_calls.length - 1;j >= 0; j--) {
18306
+ const toolCall = message.tool_calls[j];
18307
+ if (toolCall?.type === "function") {
18308
+ return toolCall.function;
18309
+ }
18310
+ }
17695
18311
  }
17696
18312
  }
17697
18313
  return;
@@ -17738,7 +18354,7 @@ var init_ChatCompletionRunner = __esm(() => {
17738
18354
  ...options,
17739
18355
  headers: { ...options?.headers, "X-Stainless-Helper-Method": "runTools" }
17740
18356
  };
17741
- runner._run(() => runner._runTools(client, params, opts));
18357
+ runner._run(() => runner._runTools(client, params, runner, opts));
17742
18358
  return runner;
17743
18359
  }
17744
18360
  _addMessage(message, emit = true) {
@@ -17960,16 +18576,41 @@ var init_streaming2 = __esm(() => {
17960
18576
  });
17961
18577
 
17962
18578
  // node_modules/openai/lib/ChatCompletionStream.mjs
17963
- function finalizeChatCompletion(snapshot, params) {
18579
+ function makeChatCompletionReadableStreamMessageChunk(chunk, message, toolCallIds) {
18580
+ const payload = {
18581
+ type: "message",
18582
+ message,
18583
+ ...toolCallIds ? { tool_call_ids: toolCallIds } : {}
18584
+ };
18585
+ return {
18586
+ id: chunk.id,
18587
+ choices: [],
18588
+ created: chunk.created,
18589
+ model: chunk.model,
18590
+ object: `${CHAT_COMPLETION_READABLE_STREAM_MESSAGE_PREFIX}${JSON.stringify(payload)}`
18591
+ };
18592
+ }
18593
+ function isChatCompletionReadableStreamMessage(item) {
18594
+ 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);
18595
+ }
18596
+ function getChatCompletionReadableStreamMessage(item) {
18597
+ if ("type" in item) {
18598
+ return item;
18599
+ }
18600
+ return JSON.parse(item.object.slice(CHAT_COMPLETION_READABLE_STREAM_MESSAGE_PREFIX.length));
18601
+ }
18602
+ function finalizeChatCompletion(snapshot, params, audioDoneChoiceIndexes) {
17964
18603
  const { id, choices, created, model, system_fingerprint, ...rest } = snapshot;
17965
18604
  const completion = {
17966
18605
  ...rest,
17967
18606
  id,
17968
18607
  choices: choices.map(({ message, finish_reason, index, logprobs, ...choiceRest }) => {
17969
- if (!finish_reason) {
18608
+ const { content = null, function_call, tool_calls, audio, ...messageRest } = message;
18609
+ const finishReason = finish_reason ?? (audioDoneChoiceIndexes.has(index) && isCompleteAudio(audio) ? "stop" : null);
18610
+ if (!finishReason) {
17970
18611
  throw new OpenAIError(`missing finish_reason for choice ${index}`);
17971
18612
  }
17972
- const { content = null, function_call, tool_calls, ...messageRest } = message;
18613
+ const audioResponse = audio ? { audio } : {};
17973
18614
  const role = message.role;
17974
18615
  if (!role) {
17975
18616
  throw new OpenAIError(`missing role for choice ${index}`);
@@ -17985,12 +18626,13 @@ function finalizeChatCompletion(snapshot, params) {
17985
18626
  return {
17986
18627
  ...choiceRest,
17987
18628
  message: {
18629
+ ...audioResponse,
17988
18630
  content,
17989
18631
  function_call: { arguments: args, name },
17990
18632
  role,
17991
18633
  refusal: message.refusal ?? null
17992
18634
  },
17993
- finish_reason,
18635
+ finish_reason: finishReason,
17994
18636
  index,
17995
18637
  logprobs
17996
18638
  };
@@ -17999,20 +18641,17 @@ function finalizeChatCompletion(snapshot, params) {
17999
18641
  return {
18000
18642
  ...choiceRest,
18001
18643
  index,
18002
- finish_reason,
18644
+ finish_reason: finishReason,
18003
18645
  logprobs,
18004
18646
  message: {
18005
18647
  ...messageRest,
18648
+ ...audioResponse,
18006
18649
  role,
18007
18650
  content,
18008
18651
  refusal: message.refusal ?? null,
18009
18652
  tool_calls: tool_calls.map((tool_call, i) => {
18010
18653
  const { function: fn, type, id, ...toolRest } = tool_call;
18011
18654
  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
18655
  if (type == null) {
18017
18656
  throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].type
18018
18657
  ${str2(snapshot)}`);
@@ -18025,15 +18664,20 @@ ${str2(snapshot)}`);
18025
18664
  throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.arguments
18026
18665
  ${str2(snapshot)}`);
18027
18666
  }
18028
- return { ...toolRest, id, type, function: { ...fnRest, name, arguments: args } };
18667
+ return {
18668
+ ...toolRest,
18669
+ id: id || `call_${uuid4()}`,
18670
+ type,
18671
+ function: { ...fnRest, name, arguments: args }
18672
+ };
18029
18673
  })
18030
18674
  }
18031
18675
  };
18032
18676
  }
18033
18677
  return {
18034
18678
  ...choiceRest,
18035
- message: { ...messageRest, content, role, refusal: message.refusal ?? null },
18036
- finish_reason,
18679
+ message: { ...messageRest, ...audioResponse, content, role, refusal: message.refusal ?? null },
18680
+ finish_reason: finishReason,
18037
18681
  index,
18038
18682
  logprobs
18039
18683
  };
@@ -18045,6 +18689,9 @@ ${str2(snapshot)}`);
18045
18689
  };
18046
18690
  return maybeParseChatCompletion(completion, params);
18047
18691
  }
18692
+ function isCompleteAudio(audio) {
18693
+ return audio?.id != null && audio.data != null && audio.transcript != null && audio.expires_at != null;
18694
+ }
18048
18695
  function str2(x) {
18049
18696
  return JSON.stringify(x);
18050
18697
  }
@@ -18052,11 +18699,12 @@ function assertIsEmpty(obj) {
18052
18699
  return;
18053
18700
  }
18054
18701
  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;
18702
+ 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
18703
  var init_ChatCompletionStream = __esm(() => {
18057
18704
  init_tslib();
18058
18705
  init_parser2();
18059
18706
  init_error2();
18707
+ init_uuid();
18060
18708
  init_parser();
18061
18709
  init_streaming2();
18062
18710
  init_AbstractChatCompletionRunner();
@@ -18065,9 +18713,11 @@ var init_ChatCompletionStream = __esm(() => {
18065
18713
  super();
18066
18714
  _ChatCompletionStream_instances.add(this);
18067
18715
  _ChatCompletionStream_params.set(this, undefined);
18716
+ _ChatCompletionStream_audioDoneChoiceIndexes.set(this, undefined);
18068
18717
  _ChatCompletionStream_choiceEventStates.set(this, undefined);
18069
18718
  _ChatCompletionStream_currentChatCompletionSnapshot.set(this, undefined);
18070
18719
  __classPrivateFieldSet(this, _ChatCompletionStream_params, params, "f");
18720
+ __classPrivateFieldSet(this, _ChatCompletionStream_audioDoneChoiceIndexes, new Set, "f");
18071
18721
  __classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f");
18072
18722
  }
18073
18723
  get currentChatCompletionSnapshot() {
@@ -18085,12 +18735,7 @@ var init_ChatCompletionStream = __esm(() => {
18085
18735
  }
18086
18736
  async _createChatCompletion(client, params, options) {
18087
18737
  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
- }
18738
+ this._listenForAbort(options?.signal);
18094
18739
  __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
18095
18740
  const stream = await client.chat.completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal });
18096
18741
  this._connected();
@@ -18103,31 +18748,52 @@ var init_ChatCompletionStream = __esm(() => {
18103
18748
  return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
18104
18749
  }
18105
18750
  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
- }
18751
+ this._listenForAbort(options?.signal);
18112
18752
  __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
18113
18753
  this._connected();
18114
18754
  const stream = Stream.fromReadableStream(readableStream, this.controller);
18115
18755
  let chatId;
18116
- for await (const chunk of stream) {
18117
- if (chatId && chatId !== chunk.id) {
18756
+ for await (const item of stream) {
18757
+ if (isChatCompletionReadableStreamMessage(item)) {
18758
+ const message = getChatCompletionReadableStreamMessage(item);
18759
+ if (__classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f")) {
18760
+ const toolCalls = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f").choices[0]?.message.tool_calls;
18761
+ for (const [index, id] of message.tool_call_ids?.entries() ?? []) {
18762
+ const toolCall = toolCalls?.[index];
18763
+ if (toolCall && id) {
18764
+ toolCall.id = id;
18765
+ }
18766
+ }
18767
+ this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
18768
+ chatId = undefined;
18769
+ }
18770
+ this._addMessage(message.message);
18771
+ continue;
18772
+ }
18773
+ const chunk = item;
18774
+ if (chatId && chunk.id && chatId !== chunk.id) {
18118
18775
  this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
18119
18776
  }
18120
18777
  __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
18121
- chatId = chunk.id;
18778
+ if (chunk.id)
18779
+ chatId = chunk.id;
18122
18780
  }
18123
18781
  if (stream.controller.signal?.aborted) {
18124
18782
  throw new APIUserAbortError;
18125
18783
  }
18126
- return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
18784
+ if (__classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f")) {
18785
+ return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
18786
+ }
18787
+ const lastChatCompletion = this._chatCompletions[this._chatCompletions.length - 1];
18788
+ if (lastChatCompletion) {
18789
+ return lastChatCompletion;
18790
+ }
18791
+ throw new OpenAIError(`request ended without sending any chunks`);
18127
18792
  }
18128
- [(_ChatCompletionStream_params = new WeakMap, _ChatCompletionStream_choiceEventStates = new WeakMap, _ChatCompletionStream_currentChatCompletionSnapshot = new WeakMap, _ChatCompletionStream_instances = new WeakSet, _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest2() {
18793
+ [(_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
18794
  if (this.ended)
18130
18795
  return;
18796
+ __classPrivateFieldSet(this, _ChatCompletionStream_audioDoneChoiceIndexes, new Set, "f");
18131
18797
  __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f");
18132
18798
  }, _ChatCompletionStream_getChoiceEventState = function _ChatCompletionStream_getChoiceEventState2(choice) {
18133
18799
  let state = __classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index];
@@ -18151,17 +18817,18 @@ var init_ChatCompletionStream = __esm(() => {
18151
18817
  this._emit("chunk", chunk, completion);
18152
18818
  for (const choice of chunk.choices) {
18153
18819
  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);
18820
+ const { delta } = choice;
18821
+ if (delta?.content != null && choiceSnapshot.message?.role === "assistant" && choiceSnapshot.message?.content) {
18822
+ this._emit("content", delta.content, choiceSnapshot.message.content);
18156
18823
  this._emit("content.delta", {
18157
- delta: choice.delta.content,
18824
+ delta: delta.content,
18158
18825
  snapshot: choiceSnapshot.message.content,
18159
18826
  parsed: choiceSnapshot.message.parsed
18160
18827
  });
18161
18828
  }
18162
- if (choice.delta.refusal != null && choiceSnapshot.message?.role === "assistant" && choiceSnapshot.message?.refusal) {
18829
+ if (delta?.refusal != null && choiceSnapshot.message?.role === "assistant" && choiceSnapshot.message?.refusal) {
18163
18830
  this._emit("refusal.delta", {
18164
- delta: choice.delta.refusal,
18831
+ delta: delta.refusal,
18165
18832
  snapshot: choiceSnapshot.message.refusal
18166
18833
  });
18167
18834
  }
@@ -18184,7 +18851,7 @@ var init_ChatCompletionStream = __esm(() => {
18184
18851
  __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);
18185
18852
  }
18186
18853
  }
18187
- for (const toolCall of choice.delta.tool_calls ?? []) {
18854
+ for (const toolCall of delta?.tool_calls ?? []) {
18188
18855
  if (state.current_tool_call_index !== toolCall.index) {
18189
18856
  __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
18190
18857
  if (state.current_tool_call_index != null) {
@@ -18193,7 +18860,7 @@ var init_ChatCompletionStream = __esm(() => {
18193
18860
  }
18194
18861
  state.current_tool_call_index = toolCall.index;
18195
18862
  }
18196
- for (const toolCallDelta of choice.delta.tool_calls ?? []) {
18863
+ for (const toolCallDelta of delta?.tool_calls ?? []) {
18197
18864
  const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallDelta.index];
18198
18865
  if (!toolCallSnapshot?.type) {
18199
18866
  continue;
@@ -18264,9 +18931,11 @@ var init_ChatCompletionStream = __esm(() => {
18264
18931
  if (!snapshot) {
18265
18932
  throw new OpenAIError(`request ended without sending any chunks`);
18266
18933
  }
18934
+ const audioDoneChoiceIndexes = __classPrivateFieldGet(this, _ChatCompletionStream_audioDoneChoiceIndexes, "f");
18935
+ __classPrivateFieldSet(this, _ChatCompletionStream_audioDoneChoiceIndexes, new Set, "f");
18267
18936
  __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f");
18268
18937
  __classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f");
18269
- return finalizeChatCompletion(snapshot, __classPrivateFieldGet(this, _ChatCompletionStream_params, "f"));
18938
+ return finalizeChatCompletion(snapshot, __classPrivateFieldGet(this, _ChatCompletionStream_params, "f"), audioDoneChoiceIndexes);
18270
18939
  }, _ChatCompletionStream_getAutoParseableResponseFormat = function _ChatCompletionStream_getAutoParseableResponseFormat2() {
18271
18940
  const responseFormat = __classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.response_format;
18272
18941
  if (isAutoParsableResponseFormat(responseFormat)) {
@@ -18274,7 +18943,7 @@ var init_ChatCompletionStream = __esm(() => {
18274
18943
  }
18275
18944
  return null;
18276
18945
  }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion2(chunk) {
18277
- var _a, _b, _c, _d;
18946
+ var _a, _b, _c, _d, _e;
18278
18947
  let snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
18279
18948
  const { choices, ...rest } = chunk;
18280
18949
  if (!snapshot) {
@@ -18282,7 +18951,7 @@ var init_ChatCompletionStream = __esm(() => {
18282
18951
  ...rest,
18283
18952
  choices: []
18284
18953
  }, "f");
18285
- } else {
18954
+ } else if (chunk.id) {
18286
18955
  Object.assign(snapshot, rest);
18287
18956
  }
18288
18957
  for (const { delta, finish_reason, index, logprobs = null, ...other } of chunk.choices) {
@@ -18321,14 +18990,30 @@ var init_ChatCompletionStream = __esm(() => {
18321
18990
  Object.assign(choice, other);
18322
18991
  if (!delta)
18323
18992
  continue;
18324
- const { content, refusal, function_call, role, tool_calls, ...rest } = delta;
18993
+ __classPrivateFieldGet(this, _ChatCompletionStream_audioDoneChoiceIndexes, "f").delete(index);
18994
+ const { audio, content, refusal, function_call, role, tool_calls, ...rest } = delta;
18325
18995
  assertIsEmpty(rest);
18326
18996
  Object.assign(choice.message, rest);
18997
+ 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) {
18998
+ __classPrivateFieldGet(this, _ChatCompletionStream_audioDoneChoiceIndexes, "f").add(index);
18999
+ }
18327
19000
  if (refusal) {
18328
19001
  choice.message.refusal = (choice.message.refusal || "") + refusal;
18329
19002
  }
18330
19003
  if (role)
18331
19004
  choice.message.role = role;
19005
+ if (audio) {
19006
+ const audioSnapshot = (_c = choice.message).audio ?? (_c.audio = {});
19007
+ if (audio.id != null)
19008
+ audioSnapshot.id = audio.id;
19009
+ if (audio.data != null)
19010
+ audioSnapshot.data = (audioSnapshot.data ?? "") + audio.data;
19011
+ if (audio.transcript != null) {
19012
+ audioSnapshot.transcript = (audioSnapshot.transcript ?? "") + audio.transcript;
19013
+ }
19014
+ if (audio.expires_at != null)
19015
+ audioSnapshot.expires_at = audio.expires_at;
19016
+ }
18332
19017
  if (function_call) {
18333
19018
  if (!choice.message.function_call) {
18334
19019
  choice.message.function_call = function_call;
@@ -18336,7 +19021,7 @@ var init_ChatCompletionStream = __esm(() => {
18336
19021
  if (function_call.name)
18337
19022
  choice.message.function_call.name = function_call.name;
18338
19023
  if (function_call.arguments) {
18339
- (_c = choice.message.function_call).arguments ?? (_c.arguments = "");
19024
+ (_d = choice.message.function_call).arguments ?? (_d.arguments = "");
18340
19025
  choice.message.function_call.arguments += function_call.arguments;
18341
19026
  }
18342
19027
  }
@@ -18344,14 +19029,14 @@ var init_ChatCompletionStream = __esm(() => {
18344
19029
  if (content) {
18345
19030
  choice.message.content = (choice.message.content || "") + content;
18346
19031
  if (!choice.message.refusal && __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) {
18347
- choice.message.parsed = partialParse(choice.message.content);
19032
+ choice.message.parsed = choice.message.content.trim() ? partialParse(choice.message.content) : null;
18348
19033
  }
18349
19034
  }
18350
19035
  if (tool_calls) {
18351
19036
  if (!choice.message.tool_calls)
18352
19037
  choice.message.tool_calls = [];
18353
19038
  for (const { index, id, type, function: fn, ...rest } of tool_calls) {
18354
- const tool_call = (_d = choice.message.tool_calls)[index] ?? (_d[index] = {});
19039
+ const tool_call = (_e = choice.message.tool_calls)[index] ?? (_e[index] = {});
18355
19040
  Object.assign(tool_call, rest);
18356
19041
  if (id)
18357
19042
  tool_call.id = id;
@@ -18432,19 +19117,95 @@ var init_ChatCompletionStream = __esm(() => {
18432
19117
  var ChatCompletionStreamingRunner;
18433
19118
  var init_ChatCompletionStreamingRunner = __esm(() => {
18434
19119
  init_ChatCompletionStream();
19120
+ init_error2();
19121
+ init_streaming2();
19122
+ init_chatCompletionUtils();
18435
19123
  ChatCompletionStreamingRunner = class ChatCompletionStreamingRunner extends ChatCompletionStream {
18436
19124
  static fromReadableStream(stream) {
18437
19125
  const runner = new ChatCompletionStreamingRunner(null);
18438
19126
  runner._run(() => runner._fromReadableStream(stream));
18439
19127
  return runner;
18440
19128
  }
19129
+ toReadableStream() {
19130
+ const pushQueue = [];
19131
+ const readQueue = [];
19132
+ let done = false;
19133
+ let lastChunk;
19134
+ let toolCallIds;
19135
+ const pushEvent = (event) => {
19136
+ const reader = readQueue.shift();
19137
+ if (reader) {
19138
+ reader.resolve(event);
19139
+ } else {
19140
+ pushQueue.push(event);
19141
+ }
19142
+ };
19143
+ this.on("chunk", (chunk) => {
19144
+ lastChunk = chunk;
19145
+ pushEvent(chunk);
19146
+ });
19147
+ this.on("message", (message) => {
19148
+ if (isAssistantMessage(message)) {
19149
+ toolCallIds = message.tool_calls?.map((toolCall) => toolCall.id);
19150
+ return;
19151
+ }
19152
+ if (isToolMessage(message)) {
19153
+ if (!lastChunk) {
19154
+ throw new OpenAIError("cannot serialize a tool message before receiving any chunks");
19155
+ }
19156
+ pushEvent(makeChatCompletionReadableStreamMessageChunk(lastChunk, message, toolCallIds));
19157
+ }
19158
+ });
19159
+ this.on("end", () => {
19160
+ done = true;
19161
+ for (const reader of readQueue) {
19162
+ reader.resolve(undefined);
19163
+ }
19164
+ readQueue.length = 0;
19165
+ });
19166
+ this.on("abort", (err) => {
19167
+ done = true;
19168
+ for (const reader of readQueue) {
19169
+ reader.reject(err);
19170
+ }
19171
+ readQueue.length = 0;
19172
+ });
19173
+ this.on("error", (err) => {
19174
+ done = true;
19175
+ for (const reader of readQueue) {
19176
+ reader.reject(err);
19177
+ }
19178
+ readQueue.length = 0;
19179
+ });
19180
+ const iterator = () => ({
19181
+ next: async () => {
19182
+ if (!pushQueue.length) {
19183
+ if (done) {
19184
+ return { value: undefined, done: true };
19185
+ }
19186
+ return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((event) => event ? { value: event, done: false } : { value: undefined, done: true });
19187
+ }
19188
+ const event = pushQueue.shift();
19189
+ if (!event) {
19190
+ return { value: undefined, done: true };
19191
+ }
19192
+ return { value: event, done: false };
19193
+ },
19194
+ return: async () => {
19195
+ this.abort();
19196
+ return { value: undefined, done: true };
19197
+ }
19198
+ });
19199
+ const stream = new Stream(iterator, this.controller);
19200
+ return stream.toReadableStream();
19201
+ }
18441
19202
  static runTools(client, params, options) {
18442
19203
  const runner = new ChatCompletionStreamingRunner(params);
18443
19204
  const opts = {
18444
19205
  ...options,
18445
19206
  headers: { ...options?.headers, "X-Stainless-Helper-Method": "runTools" }
18446
19207
  };
18447
- runner._run(() => runner._runTools(client, params, opts));
19208
+ runner._run(() => runner._runTools(client, params, runner, opts));
18448
19209
  return runner;
18449
19210
  }
18450
19211
  };
@@ -18776,6 +19537,12 @@ var init_spend_alerts = __esm(() => {
18776
19537
  __security: { adminAPIKeyAuth: true }
18777
19538
  });
18778
19539
  }
19540
+ retrieve(alertID, options) {
19541
+ return this._client.get(path3`/organization/spend_alerts/${alertID}`, {
19542
+ ...options,
19543
+ __security: { adminAPIKeyAuth: true }
19544
+ });
19545
+ }
18779
19546
  update(alertID, body, options) {
18780
19547
  return this._client.post(path3`/organization/spend_alerts/${alertID}`, {
18781
19548
  body,
@@ -18795,6 +19562,33 @@ var init_spend_alerts = __esm(() => {
18795
19562
  };
18796
19563
  });
18797
19564
 
19565
+ // node_modules/openai/resources/admin/organization/spend-limit.mjs
19566
+ var SpendLimit;
19567
+ var init_spend_limit = __esm(() => {
19568
+ init_resource();
19569
+ SpendLimit = class SpendLimit extends APIResource {
19570
+ retrieve(options) {
19571
+ return this._client.get("/organization/spend_limit", {
19572
+ ...options,
19573
+ __security: { adminAPIKeyAuth: true }
19574
+ });
19575
+ }
19576
+ update(body, options) {
19577
+ return this._client.post("/organization/spend_limit", {
19578
+ body,
19579
+ ...options,
19580
+ __security: { adminAPIKeyAuth: true }
19581
+ });
19582
+ }
19583
+ delete(options) {
19584
+ return this._client.delete("/organization/spend_limit", {
19585
+ ...options,
19586
+ __security: { adminAPIKeyAuth: true }
19587
+ });
19588
+ }
19589
+ };
19590
+ });
19591
+
18798
19592
  // node_modules/openai/resources/admin/organization/usage.mjs
18799
19593
  var Usage;
18800
19594
  var init_usage = __esm(() => {
@@ -19187,13 +19981,180 @@ var init_roles3 = __esm(() => {
19187
19981
  };
19188
19982
  });
19189
19983
 
19190
- // node_modules/openai/resources/admin/organization/projects/service-accounts.mjs
19984
+ // node_modules/openai/resources/admin/organization/projects/spend-alerts.mjs
19985
+ var SpendAlerts2;
19986
+ var init_spend_alerts2 = __esm(() => {
19987
+ init_resource();
19988
+ init_pagination();
19989
+ init_path();
19990
+ SpendAlerts2 = class SpendAlerts2 extends APIResource {
19991
+ create(projectID, body, options) {
19992
+ return this._client.post(path3`/organization/projects/${projectID}/spend_alerts`, {
19993
+ body,
19994
+ ...options,
19995
+ __security: { adminAPIKeyAuth: true }
19996
+ });
19997
+ }
19998
+ retrieve(alertID, params, options) {
19999
+ const { project_id } = params;
20000
+ return this._client.get(path3`/organization/projects/${project_id}/spend_alerts/${alertID}`, {
20001
+ ...options,
20002
+ __security: { adminAPIKeyAuth: true }
20003
+ });
20004
+ }
20005
+ update(alertID, params, options) {
20006
+ const { project_id, ...body } = params;
20007
+ return this._client.post(path3`/organization/projects/${project_id}/spend_alerts/${alertID}`, {
20008
+ body,
20009
+ ...options,
20010
+ __security: { adminAPIKeyAuth: true }
20011
+ });
20012
+ }
20013
+ list(projectID, query = {}, options) {
20014
+ return this._client.getAPIList(path3`/organization/projects/${projectID}/spend_alerts`, ConversationCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
20015
+ }
20016
+ delete(alertID, params, options) {
20017
+ const { project_id } = params;
20018
+ return this._client.delete(path3`/organization/projects/${project_id}/spend_alerts/${alertID}`, {
20019
+ ...options,
20020
+ __security: { adminAPIKeyAuth: true }
20021
+ });
20022
+ }
20023
+ };
20024
+ });
20025
+
20026
+ // node_modules/openai/resources/admin/organization/projects/spend-limit.mjs
20027
+ var SpendLimit2;
20028
+ var init_spend_limit2 = __esm(() => {
20029
+ init_resource();
20030
+ init_path();
20031
+ SpendLimit2 = class SpendLimit2 extends APIResource {
20032
+ retrieve(projectID, options) {
20033
+ return this._client.get(path3`/organization/projects/${projectID}/spend_limit`, {
20034
+ ...options,
20035
+ __security: { adminAPIKeyAuth: true }
20036
+ });
20037
+ }
20038
+ update(projectID, body, options) {
20039
+ return this._client.post(path3`/organization/projects/${projectID}/spend_limit`, {
20040
+ body,
20041
+ ...options,
20042
+ __security: { adminAPIKeyAuth: true }
20043
+ });
20044
+ }
20045
+ delete(projectID, options) {
20046
+ return this._client.delete(path3`/organization/projects/${projectID}/spend_limit`, {
20047
+ ...options,
20048
+ __security: { adminAPIKeyAuth: true }
20049
+ });
20050
+ }
20051
+ };
20052
+ });
20053
+
20054
+ // node_modules/openai/resources/admin/organization/projects/groups/roles.mjs
20055
+ var Roles4;
20056
+ var init_roles4 = __esm(() => {
20057
+ init_resource();
20058
+ init_pagination();
20059
+ init_path();
20060
+ Roles4 = class Roles4 extends APIResource {
20061
+ create(groupID, params, options) {
20062
+ const { project_id, ...body } = params;
20063
+ return this._client.post(path3`/projects/${project_id}/groups/${groupID}/roles`, {
20064
+ body,
20065
+ ...options,
20066
+ __security: { adminAPIKeyAuth: true }
20067
+ });
20068
+ }
20069
+ retrieve(roleID, params, options) {
20070
+ const { project_id, group_id } = params;
20071
+ return this._client.get(path3`/projects/${project_id}/groups/${group_id}/roles/${roleID}`, {
20072
+ ...options,
20073
+ __security: { adminAPIKeyAuth: true }
20074
+ });
20075
+ }
20076
+ list(groupID, params, options) {
20077
+ const { project_id, ...query } = params;
20078
+ return this._client.getAPIList(path3`/projects/${project_id}/groups/${groupID}/roles`, NextCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
20079
+ }
20080
+ delete(roleID, params, options) {
20081
+ const { project_id, group_id } = params;
20082
+ return this._client.delete(path3`/projects/${project_id}/groups/${group_id}/roles/${roleID}`, {
20083
+ ...options,
20084
+ __security: { adminAPIKeyAuth: true }
20085
+ });
20086
+ }
20087
+ };
20088
+ });
20089
+
20090
+ // node_modules/openai/resources/admin/organization/projects/groups/groups.mjs
20091
+ var Groups2;
20092
+ var init_groups2 = __esm(() => {
20093
+ init_resource();
20094
+ init_roles4();
20095
+ init_roles4();
20096
+ init_pagination();
20097
+ init_path();
20098
+ Groups2 = class Groups2 extends APIResource {
20099
+ constructor() {
20100
+ super(...arguments);
20101
+ this.roles = new Roles4(this._client);
20102
+ }
20103
+ create(projectID, body, options) {
20104
+ return this._client.post(path3`/organization/projects/${projectID}/groups`, {
20105
+ body,
20106
+ ...options,
20107
+ __security: { adminAPIKeyAuth: true }
20108
+ });
20109
+ }
20110
+ retrieve(groupID, params, options) {
20111
+ const { project_id, ...query } = params;
20112
+ return this._client.get(path3`/organization/projects/${project_id}/groups/${groupID}`, {
20113
+ query,
20114
+ ...options,
20115
+ __security: { adminAPIKeyAuth: true }
20116
+ });
20117
+ }
20118
+ list(projectID, query = {}, options) {
20119
+ return this._client.getAPIList(path3`/organization/projects/${projectID}/groups`, NextCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
20120
+ }
20121
+ delete(groupID, params, options) {
20122
+ const { project_id } = params;
20123
+ return this._client.delete(path3`/organization/projects/${project_id}/groups/${groupID}`, {
20124
+ ...options,
20125
+ __security: { adminAPIKeyAuth: true }
20126
+ });
20127
+ }
20128
+ };
20129
+ Groups2.Roles = Roles4;
20130
+ });
20131
+
20132
+ // node_modules/openai/resources/admin/organization/projects/service-accounts/api-keys.mjs
20133
+ var APIKeys2;
20134
+ var init_api_keys3 = __esm(() => {
20135
+ init_resource();
20136
+ init_path();
20137
+ APIKeys2 = class APIKeys2 extends APIResource {
20138
+ create(serviceAccountID, params, options) {
20139
+ const { project_id, ...body } = params;
20140
+ return this._client.post(path3`/organization/projects/${project_id}/service_accounts/${serviceAccountID}/api_keys`, { body, ...options, __security: { adminAPIKeyAuth: true } });
20141
+ }
20142
+ };
20143
+ });
20144
+
20145
+ // node_modules/openai/resources/admin/organization/projects/service-accounts/service-accounts.mjs
19191
20146
  var ServiceAccounts;
19192
20147
  var init_service_accounts = __esm(() => {
19193
20148
  init_resource();
20149
+ init_api_keys3();
20150
+ init_api_keys3();
19194
20151
  init_pagination();
19195
20152
  init_path();
19196
20153
  ServiceAccounts = class ServiceAccounts extends APIResource {
20154
+ constructor() {
20155
+ super(...arguments);
20156
+ this.apiKeys = new APIKeys2(this._client);
20157
+ }
19197
20158
  create(projectID, body, options) {
19198
20159
  return this._client.post(path3`/organization/projects/${projectID}/service_accounts`, {
19199
20160
  body,
@@ -19220,119 +20181,7 @@ var init_service_accounts = __esm(() => {
19220
20181
  return this._client.delete(path3`/organization/projects/${project_id}/service_accounts/${serviceAccountID}`, { ...options, __security: { adminAPIKeyAuth: true } });
19221
20182
  }
19222
20183
  };
19223
- });
19224
-
19225
- // node_modules/openai/resources/admin/organization/projects/spend-alerts.mjs
19226
- var SpendAlerts2;
19227
- var init_spend_alerts2 = __esm(() => {
19228
- init_resource();
19229
- init_pagination();
19230
- 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,
19235
- ...options,
19236
- __security: { adminAPIKeyAuth: true }
19237
- });
19238
- }
19239
- update(alertID, params, options) {
19240
- const { project_id, ...body } = params;
19241
- return this._client.post(path3`/organization/projects/${project_id}/spend_alerts/${alertID}`, {
19242
- body,
19243
- ...options,
19244
- __security: { adminAPIKeyAuth: true }
19245
- });
19246
- }
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}`, {
19253
- ...options,
19254
- __security: { adminAPIKeyAuth: true }
19255
- });
19256
- }
19257
- };
19258
- });
19259
-
19260
- // node_modules/openai/resources/admin/organization/projects/groups/roles.mjs
19261
- var Roles4;
19262
- var init_roles4 = __esm(() => {
19263
- init_resource();
19264
- init_pagination();
19265
- init_path();
19266
- Roles4 = class Roles4 extends APIResource {
19267
- create(groupID, params, options) {
19268
- const { project_id, ...body } = params;
19269
- return this._client.post(path3`/projects/${project_id}/groups/${groupID}/roles`, {
19270
- body,
19271
- ...options,
19272
- __security: { adminAPIKeyAuth: true }
19273
- });
19274
- }
19275
- retrieve(roleID, params, options) {
19276
- const { project_id, group_id } = params;
19277
- return this._client.get(path3`/projects/${project_id}/groups/${group_id}/roles/${roleID}`, {
19278
- ...options,
19279
- __security: { adminAPIKeyAuth: true }
19280
- });
19281
- }
19282
- list(groupID, params, options) {
19283
- const { project_id, ...query } = params;
19284
- return this._client.getAPIList(path3`/projects/${project_id}/groups/${groupID}/roles`, NextCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
19285
- }
19286
- delete(roleID, params, options) {
19287
- const { project_id, group_id } = params;
19288
- return this._client.delete(path3`/projects/${project_id}/groups/${group_id}/roles/${roleID}`, {
19289
- ...options,
19290
- __security: { adminAPIKeyAuth: true }
19291
- });
19292
- }
19293
- };
19294
- });
19295
-
19296
- // node_modules/openai/resources/admin/organization/projects/groups/groups.mjs
19297
- var Groups2;
19298
- var init_groups2 = __esm(() => {
19299
- init_resource();
19300
- init_roles4();
19301
- init_roles4();
19302
- init_pagination();
19303
- init_path();
19304
- Groups2 = class Groups2 extends APIResource {
19305
- constructor() {
19306
- super(...arguments);
19307
- this.roles = new Roles4(this._client);
19308
- }
19309
- create(projectID, body, options) {
19310
- return this._client.post(path3`/organization/projects/${projectID}/groups`, {
19311
- body,
19312
- ...options,
19313
- __security: { adminAPIKeyAuth: true }
19314
- });
19315
- }
19316
- retrieve(groupID, params, options) {
19317
- const { project_id, ...query } = params;
19318
- return this._client.get(path3`/organization/projects/${project_id}/groups/${groupID}`, {
19319
- query,
19320
- ...options,
19321
- __security: { adminAPIKeyAuth: true }
19322
- });
19323
- }
19324
- list(projectID, query = {}, options) {
19325
- return this._client.getAPIList(path3`/organization/projects/${projectID}/groups`, NextCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
19326
- }
19327
- delete(groupID, params, options) {
19328
- const { project_id } = params;
19329
- return this._client.delete(path3`/organization/projects/${project_id}/groups/${groupID}`, {
19330
- ...options,
19331
- __security: { adminAPIKeyAuth: true }
19332
- });
19333
- }
19334
- };
19335
- Groups2.Roles = Roles4;
20184
+ ServiceAccounts.APIKeys = APIKeys2;
19336
20185
  });
19337
20186
 
19338
20187
  // node_modules/openai/resources/admin/organization/projects/users/roles.mjs
@@ -19438,12 +20287,14 @@ var init_projects = __esm(() => {
19438
20287
  init_rate_limits();
19439
20288
  init_roles3();
19440
20289
  init_roles3();
19441
- init_service_accounts();
19442
- init_service_accounts();
19443
20290
  init_spend_alerts2();
19444
20291
  init_spend_alerts2();
20292
+ init_spend_limit2();
20293
+ init_spend_limit2();
19445
20294
  init_groups2();
19446
20295
  init_groups2();
20296
+ init_service_accounts();
20297
+ init_service_accounts();
19447
20298
  init_users2();
19448
20299
  init_users2();
19449
20300
  init_pagination();
@@ -19460,6 +20311,7 @@ var init_projects = __esm(() => {
19460
20311
  this.groups = new Groups2(this._client);
19461
20312
  this.roles = new Roles3(this._client);
19462
20313
  this.dataRetention = new DataRetention2(this._client);
20314
+ this.spendLimit = new SpendLimit2(this._client);
19463
20315
  this.spendAlerts = new SpendAlerts2(this._client);
19464
20316
  this.certificates = new Certificates2(this._client);
19465
20317
  }
@@ -19506,6 +20358,7 @@ var init_projects = __esm(() => {
19506
20358
  Projects.Groups = Groups2;
19507
20359
  Projects.Roles = Roles3;
19508
20360
  Projects.DataRetention = DataRetention2;
20361
+ Projects.SpendLimit = SpendLimit2;
19509
20362
  Projects.SpendAlerts = SpendAlerts2;
19510
20363
  Projects.Certificates = Certificates2;
19511
20364
  });
@@ -19605,6 +20458,8 @@ var init_organization = __esm(() => {
19605
20458
  init_roles();
19606
20459
  init_spend_alerts();
19607
20460
  init_spend_alerts();
20461
+ init_spend_limit();
20462
+ init_spend_limit();
19608
20463
  init_usage();
19609
20464
  init_usage();
19610
20465
  init_groups();
@@ -19624,6 +20479,7 @@ var init_organization = __esm(() => {
19624
20479
  this.groups = new Groups(this._client);
19625
20480
  this.roles = new Roles(this._client);
19626
20481
  this.dataRetention = new DataRetention(this._client);
20482
+ this.spendLimit = new SpendLimit(this._client);
19627
20483
  this.spendAlerts = new SpendAlerts(this._client);
19628
20484
  this.certificates = new Certificates(this._client);
19629
20485
  this.projects = new Projects(this._client);
@@ -19637,6 +20493,7 @@ var init_organization = __esm(() => {
19637
20493
  Organization.Groups = Groups;
19638
20494
  Organization.Roles = Roles;
19639
20495
  Organization.DataRetention = DataRetention;
20496
+ Organization.SpendLimit = SpendLimit;
19640
20497
  Organization.SpendAlerts = SpendAlerts;
19641
20498
  Organization.Certificates = Certificates;
19642
20499
  Organization.Projects = Projects;
@@ -19657,72 +20514,6 @@ var init_admin = __esm(() => {
19657
20514
  Admin.Organization = Organization;
19658
20515
  });
19659
20516
 
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
20517
  // node_modules/openai/resources/audio/speech.mjs
19727
20518
  var Speech;
19728
20519
  var init_speech = __esm(() => {
@@ -20010,6 +20801,131 @@ var init_chatkit = __esm(() => {
20010
20801
  ChatKit.Threads = Threads;
20011
20802
  });
20012
20803
 
20804
+ // node_modules/openai/resources/beta/responses/input-items.mjs
20805
+ var InputItems;
20806
+ var init_input_items = __esm(() => {
20807
+ init_resource();
20808
+ init_pagination();
20809
+ init_headers();
20810
+ init_path();
20811
+ InputItems = class InputItems extends APIResource {
20812
+ list(responseID, params = {}, options) {
20813
+ const { betas, ...query } = params ?? {};
20814
+ return this._client.getAPIList(path3`/responses/${responseID}/input_items?beta=true`, CursorPage, {
20815
+ query,
20816
+ ...options,
20817
+ headers: buildHeaders([
20818
+ { ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : undefined },
20819
+ options?.headers
20820
+ ]),
20821
+ __security: { bearerAuth: true }
20822
+ });
20823
+ }
20824
+ };
20825
+ });
20826
+
20827
+ // node_modules/openai/resources/beta/responses/input-tokens.mjs
20828
+ var InputTokens;
20829
+ var init_input_tokens = __esm(() => {
20830
+ init_resource();
20831
+ init_headers();
20832
+ InputTokens = class InputTokens extends APIResource {
20833
+ count(params = {}, options) {
20834
+ const { betas, ...body } = params ?? {};
20835
+ return this._client.post("/responses/input_tokens?beta=true", {
20836
+ body,
20837
+ ...options,
20838
+ headers: buildHeaders([
20839
+ { ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : undefined },
20840
+ options?.headers
20841
+ ]),
20842
+ __security: { bearerAuth: true }
20843
+ });
20844
+ }
20845
+ };
20846
+ });
20847
+
20848
+ // node_modules/openai/resources/beta/responses/responses.mjs
20849
+ var Responses;
20850
+ var init_responses = __esm(() => {
20851
+ init_resource();
20852
+ init_input_items();
20853
+ init_input_items();
20854
+ init_input_tokens();
20855
+ init_input_tokens();
20856
+ init_headers();
20857
+ init_path();
20858
+ Responses = class Responses extends APIResource {
20859
+ constructor() {
20860
+ super(...arguments);
20861
+ this.inputItems = new InputItems(this._client);
20862
+ this.inputTokens = new InputTokens(this._client);
20863
+ }
20864
+ create(params, options) {
20865
+ const { betas, ...body } = params;
20866
+ return this._client.post("/responses?beta=true", {
20867
+ body,
20868
+ ...options,
20869
+ headers: buildHeaders([
20870
+ { ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : undefined },
20871
+ options?.headers
20872
+ ]),
20873
+ stream: params.stream ?? false,
20874
+ __security: { bearerAuth: true }
20875
+ });
20876
+ }
20877
+ retrieve(responseID, params = {}, options) {
20878
+ const { betas, ...query } = params ?? {};
20879
+ return this._client.get(path3`/responses/${responseID}?beta=true`, {
20880
+ query,
20881
+ ...options,
20882
+ headers: buildHeaders([
20883
+ { ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : undefined },
20884
+ options?.headers
20885
+ ]),
20886
+ stream: params?.stream ?? false,
20887
+ __security: { bearerAuth: true }
20888
+ });
20889
+ }
20890
+ delete(responseID, params = {}, options) {
20891
+ const { betas } = params ?? {};
20892
+ return this._client.delete(path3`/responses/${responseID}?beta=true`, {
20893
+ ...options,
20894
+ headers: buildHeaders([
20895
+ { Accept: "*/*", ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : undefined },
20896
+ options?.headers
20897
+ ]),
20898
+ __security: { bearerAuth: true }
20899
+ });
20900
+ }
20901
+ cancel(responseID, params = {}, options) {
20902
+ const { betas } = params ?? {};
20903
+ return this._client.post(path3`/responses/${responseID}/cancel?beta=true`, {
20904
+ ...options,
20905
+ headers: buildHeaders([
20906
+ { ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : undefined },
20907
+ options?.headers
20908
+ ]),
20909
+ __security: { bearerAuth: true }
20910
+ });
20911
+ }
20912
+ compact(params, options) {
20913
+ const { betas, ...body } = params;
20914
+ return this._client.post("/responses/compact?beta=true", {
20915
+ body,
20916
+ ...options,
20917
+ headers: buildHeaders([
20918
+ { ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : undefined },
20919
+ options?.headers
20920
+ ]),
20921
+ __security: { bearerAuth: true }
20922
+ });
20923
+ }
20924
+ };
20925
+ Responses.InputItems = InputItems;
20926
+ Responses.InputTokens = InputTokens;
20927
+ });
20928
+
20013
20929
  // node_modules/openai/resources/beta/threads/messages.mjs
20014
20930
  var Messages2;
20015
20931
  var init_messages2 = __esm(() => {
@@ -20165,11 +21081,12 @@ var init_AssistantStream = __esm(() => {
20165
21081
  const readQueue = [];
20166
21082
  let done = false;
20167
21083
  this.on("event", (event) => {
21084
+ const eventCopy = structuredClone(event);
20168
21085
  const reader = readQueue.shift();
20169
21086
  if (reader) {
20170
- reader.resolve(event);
21087
+ reader.resolve(eventCopy);
20171
21088
  } else {
20172
- pushQueue.push(event);
21089
+ pushQueue.push(eventCopy);
20173
21090
  }
20174
21091
  });
20175
21092
  this.on("end", () => {
@@ -20216,12 +21133,7 @@ var init_AssistantStream = __esm(() => {
20216
21133
  return runner;
20217
21134
  }
20218
21135
  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
- }
21136
+ this._listenForAbort(options?.signal);
20225
21137
  this._connected();
20226
21138
  const stream = Stream.fromReadableStream(readableStream, this.controller);
20227
21139
  for await (const event of stream) {
@@ -20245,12 +21157,7 @@ var init_AssistantStream = __esm(() => {
20245
21157
  return runner;
20246
21158
  }
20247
21159
  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
- }
21160
+ this._listenForAbort(options?.signal);
20254
21161
  const body = { ...params, stream: true };
20255
21162
  const stream = await run.submitToolOutputs(runId, body, {
20256
21163
  ...options,
@@ -20308,12 +21215,7 @@ var init_AssistantStream = __esm(() => {
20308
21215
  return __classPrivateFieldGet(this, _AssistantStream_finalRun, "f");
20309
21216
  }
20310
21217
  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
- }
21218
+ this._listenForAbort(options?.signal);
20317
21219
  const body = { ...params, stream: true };
20318
21220
  const stream = await thread.createAndRun(body, { ...options, signal: this.controller.signal });
20319
21221
  this._connected();
@@ -20326,12 +21228,7 @@ var init_AssistantStream = __esm(() => {
20326
21228
  return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
20327
21229
  }
20328
21230
  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
- }
21231
+ this._listenForAbort(options?.signal);
20335
21232
  const body = { ...params, stream: true };
20336
21233
  const stream = await run.create(threadId, body, { ...options, signal: this.controller.signal });
20337
21234
  this._connected();
@@ -20383,7 +21280,7 @@ var init_AssistantStream = __esm(() => {
20383
21280
  }
20384
21281
  const accEntry = accValue[index];
20385
21282
  if (accEntry == null) {
20386
- accValue.push(deltaEntry);
21283
+ accValue[index] = deltaEntry;
20387
21284
  } else {
20388
21285
  accValue[index] = this.accumulateDelta(accEntry, deltaEntry);
20389
21286
  }
@@ -20870,18 +21767,22 @@ var init_beta = __esm(() => {
20870
21767
  init_realtime();
20871
21768
  init_chatkit();
20872
21769
  init_chatkit();
21770
+ init_responses();
21771
+ init_responses();
20873
21772
  init_threads2();
20874
21773
  init_threads2();
20875
21774
  Beta = class Beta extends APIResource {
20876
21775
  constructor() {
20877
21776
  super(...arguments);
20878
21777
  this.realtime = new Realtime(this._client);
21778
+ this.responses = new Responses(this._client);
20879
21779
  this.chatkit = new ChatKit(this._client);
20880
21780
  this.assistants = new Assistants(this._client);
20881
21781
  this.threads = new Threads2(this._client);
20882
21782
  }
20883
21783
  };
20884
21784
  Beta.Realtime = Realtime;
21785
+ Beta.Responses = Responses;
20885
21786
  Beta.ChatKit = ChatKit;
20886
21787
  Beta.Assistants = Assistants;
20887
21788
  Beta.Threads = Threads2;
@@ -21616,7 +22517,7 @@ var init_realtime2 = __esm(() => {
21616
22517
  // node_modules/openai/lib/ResponsesParser.mjs
21617
22518
  function maybeParseResponse(response, params) {
21618
22519
  if (!params || !hasAutoParseableInput2(params)) {
21619
- return {
22520
+ const parsed = {
21620
22521
  ...response,
21621
22522
  output_parsed: null,
21622
22523
  output: response.output.map((item) => {
@@ -21639,23 +22540,25 @@ function maybeParseResponse(response, params) {
21639
22540
  }
21640
22541
  })
21641
22542
  };
22543
+ if (needsOutputText(response, parsed)) {
22544
+ addOutputText(parsed);
22545
+ }
22546
+ return parsed;
21642
22547
  }
21643
22548
  return parseResponse(response, params);
21644
22549
  }
21645
22550
  function parseResponse(response, params) {
22551
+ const shouldParse = !response.status || response.status === "completed";
21646
22552
  const output = response.output.map((item) => {
21647
22553
  if (item.type === "function_call") {
21648
- return {
21649
- ...item,
21650
- parsed_arguments: parseToolCall2(params, item)
21651
- };
22554
+ return shouldParse ? parseToolCall2(params, item) : { ...item, parsed_arguments: null };
21652
22555
  }
21653
22556
  if (item.type === "message") {
21654
22557
  const content = item.content.map((content) => {
21655
22558
  if (content.type === "output_text") {
21656
22559
  return {
21657
22560
  ...content,
21658
- parsed: parseTextFormat(params, content.text)
22561
+ parsed: shouldParse ? parseTextFormat(params, content.text) : null
21659
22562
  };
21660
22563
  }
21661
22564
  return content;
@@ -21668,7 +22571,7 @@ function parseResponse(response, params) {
21668
22571
  return item;
21669
22572
  });
21670
22573
  const parsed = Object.assign({}, response, { output });
21671
- if (!Object.getOwnPropertyDescriptor(response, "output_text")) {
22574
+ if (needsOutputText(response, parsed)) {
21672
22575
  addOutputText(parsed);
21673
22576
  }
21674
22577
  Object.defineProperty(parsed, "output_parsed", {
@@ -21703,7 +22606,7 @@ function hasAutoParseableInput2(params) {
21703
22606
  if (isAutoParsableResponseFormat(params.text?.format)) {
21704
22607
  return true;
21705
22608
  }
21706
- return false;
22609
+ return Array.isArray(params.tools) && params.tools.some((tool) => isAutoParsableTool2(tool) || tool.type === "function" && tool.strict === true);
21707
22610
  }
21708
22611
  function isAutoParsableTool2(tool) {
21709
22612
  return tool?.["$brand"] === "auto-parseable-tool";
@@ -21719,6 +22622,9 @@ function parseToolCall2(params, toolCall) {
21719
22622
  parsed_arguments: isAutoParsableTool2(inputTool) ? inputTool.$parseRaw(toolCall.arguments) : inputTool?.strict ? JSON.parse(toolCall.arguments) : null
21720
22623
  };
21721
22624
  }
22625
+ function needsOutputText(response, target) {
22626
+ return !Object.getOwnPropertyDescriptor(response, "output_text") || target.output_text == null;
22627
+ }
21722
22628
  function addOutputText(rsp) {
21723
22629
  const texts = [];
21724
22630
  for (const output of rsp.output) {
@@ -21738,16 +22644,411 @@ var init_ResponsesParser = __esm(() => {
21738
22644
  init_parser();
21739
22645
  });
21740
22646
 
22647
+ // node_modules/openai/lib/responses/ResponseAccumulator.mjs
22648
+ function accumulateResponse(event, snapshot) {
22649
+ if (!snapshot) {
22650
+ if (event.type !== "response.created") {
22651
+ throw new OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${event.type}`);
22652
+ }
22653
+ return cloneResponse(event.response);
22654
+ }
22655
+ switch (event.type) {
22656
+ case "response.output_item.added": {
22657
+ snapshot.output.push(structuredClone(event.item));
22658
+ if (event.item.type === "message") {
22659
+ addOutputText(snapshot);
22660
+ }
22661
+ break;
22662
+ }
22663
+ case "response.output_item.done": {
22664
+ getOutput(snapshot, event.output_index);
22665
+ snapshot.output[event.output_index] = structuredClone(event.item);
22666
+ if (event.item.type === "message") {
22667
+ addOutputText(snapshot);
22668
+ }
22669
+ break;
22670
+ }
22671
+ case "response.content_part.added": {
22672
+ const output = getOutput(snapshot, event.output_index);
22673
+ const type = output.type;
22674
+ const part = event.part;
22675
+ if (type === "message" && part.type !== "reasoning_text") {
22676
+ output.content.push(structuredClone(part));
22677
+ if (part.type === "output_text") {
22678
+ addOutputText(snapshot);
22679
+ }
22680
+ } else if (type === "reasoning" && part.type === "reasoning_text") {
22681
+ if (!output.content) {
22682
+ output.content = [];
22683
+ }
22684
+ output.content.push(structuredClone(part));
22685
+ }
22686
+ break;
22687
+ }
22688
+ case "response.content_part.done": {
22689
+ const output = getOutput(snapshot, event.output_index);
22690
+ const part = event.part;
22691
+ if (output.type === "message" && part.type !== "reasoning_text") {
22692
+ getContent(output.content, event.content_index);
22693
+ output.content[event.content_index] = structuredClone(part);
22694
+ if (part.type === "output_text") {
22695
+ addOutputText(snapshot);
22696
+ }
22697
+ } else if (output.type === "reasoning" && part.type === "reasoning_text") {
22698
+ const content = output.content;
22699
+ if (!content) {
22700
+ throw new OpenAIError(`missing content at index ${event.content_index}`);
22701
+ }
22702
+ getContent(content, event.content_index);
22703
+ content[event.content_index] = structuredClone(part);
22704
+ }
22705
+ break;
22706
+ }
22707
+ case "response.output_text.delta": {
22708
+ const output = getOutput(snapshot, event.output_index);
22709
+ if (output.type === "message") {
22710
+ const content = getContent(output.content, event.content_index);
22711
+ if (content.type !== "output_text") {
22712
+ throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
22713
+ }
22714
+ content.text += event.delta;
22715
+ snapshot.output_text += event.delta;
22716
+ }
22717
+ break;
22718
+ }
22719
+ case "response.output_text.done": {
22720
+ const output = getOutput(snapshot, event.output_index);
22721
+ if (output.type === "message") {
22722
+ const content = getContent(output.content, event.content_index);
22723
+ if (content.type !== "output_text") {
22724
+ throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
22725
+ }
22726
+ content.text = event.text;
22727
+ addOutputText(snapshot);
22728
+ }
22729
+ break;
22730
+ }
22731
+ case "response.output_text.annotation.added": {
22732
+ const output = getOutput(snapshot, event.output_index);
22733
+ if (output.type === "message") {
22734
+ const content = getContent(output.content, event.content_index);
22735
+ if (content.type !== "output_text") {
22736
+ throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
22737
+ }
22738
+ content.annotations[event.annotation_index] = structuredClone(event.annotation);
22739
+ }
22740
+ break;
22741
+ }
22742
+ case "response.refusal.delta": {
22743
+ const output = getOutput(snapshot, event.output_index);
22744
+ if (output.type === "message") {
22745
+ const content = getContent(output.content, event.content_index);
22746
+ if (content.type !== "refusal") {
22747
+ throw new OpenAIError(`expected content to be 'refusal', got ${content.type}`);
22748
+ }
22749
+ content.refusal += event.delta;
22750
+ }
22751
+ break;
22752
+ }
22753
+ case "response.refusal.done": {
22754
+ const output = getOutput(snapshot, event.output_index);
22755
+ if (output.type === "message") {
22756
+ const content = getContent(output.content, event.content_index);
22757
+ if (content.type !== "refusal") {
22758
+ throw new OpenAIError(`expected content to be 'refusal', got ${content.type}`);
22759
+ }
22760
+ content.refusal = event.refusal;
22761
+ }
22762
+ break;
22763
+ }
22764
+ case "response.function_call_arguments.delta": {
22765
+ const output = getOutput(snapshot, event.output_index);
22766
+ if (output.type === "function_call") {
22767
+ output.arguments += event.delta;
22768
+ }
22769
+ break;
22770
+ }
22771
+ case "response.function_call_arguments.done": {
22772
+ const output = getOutput(snapshot, event.output_index);
22773
+ if (output.type === "function_call") {
22774
+ output.arguments = event.arguments;
22775
+ }
22776
+ break;
22777
+ }
22778
+ case "response.reasoning_text.delta": {
22779
+ const output = getOutput(snapshot, event.output_index);
22780
+ if (output.type === "reasoning") {
22781
+ if (!output.content) {
22782
+ throw new OpenAIError(`missing content at index ${event.content_index}`);
22783
+ }
22784
+ const content = getContent(output.content, event.content_index);
22785
+ if (content.type !== "reasoning_text") {
22786
+ throw new OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`);
22787
+ }
22788
+ content.text += event.delta;
22789
+ }
22790
+ break;
22791
+ }
22792
+ case "response.reasoning_text.done": {
22793
+ const output = getOutput(snapshot, event.output_index);
22794
+ if (output.type === "reasoning") {
22795
+ if (!output.content) {
22796
+ throw new OpenAIError(`missing content at index ${event.content_index}`);
22797
+ }
22798
+ const content = getContent(output.content, event.content_index);
22799
+ if (content.type !== "reasoning_text") {
22800
+ throw new OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`);
22801
+ }
22802
+ content.text = event.text;
22803
+ }
22804
+ break;
22805
+ }
22806
+ case "response.reasoning_summary_part.added": {
22807
+ const output = getOutput(snapshot, event.output_index);
22808
+ if (output.type === "reasoning") {
22809
+ output.summary.push(structuredClone(event.part));
22810
+ }
22811
+ break;
22812
+ }
22813
+ case "response.reasoning_summary_part.done": {
22814
+ const output = getOutput(snapshot, event.output_index);
22815
+ if (output.type === "reasoning") {
22816
+ getContent(output.summary, event.summary_index);
22817
+ output.summary[event.summary_index] = structuredClone(event.part);
22818
+ }
22819
+ break;
22820
+ }
22821
+ case "response.reasoning_summary_text.delta": {
22822
+ const output = getOutput(snapshot, event.output_index);
22823
+ if (output.type === "reasoning") {
22824
+ const part = getContent(output.summary, event.summary_index);
22825
+ part.text += event.delta;
22826
+ }
22827
+ break;
22828
+ }
22829
+ case "response.reasoning_summary_text.done": {
22830
+ const output = getOutput(snapshot, event.output_index);
22831
+ if (output.type === "reasoning") {
22832
+ const part = getContent(output.summary, event.summary_index);
22833
+ part.text = event.text;
22834
+ }
22835
+ break;
22836
+ }
22837
+ case "response.custom_tool_call_input.delta": {
22838
+ const output = getOutput(snapshot, event.output_index);
22839
+ if (output.type === "custom_tool_call") {
22840
+ output.input += event.delta;
22841
+ }
22842
+ break;
22843
+ }
22844
+ case "response.custom_tool_call_input.done": {
22845
+ const output = getOutput(snapshot, event.output_index);
22846
+ if (output.type === "custom_tool_call") {
22847
+ output.input = event.input;
22848
+ }
22849
+ break;
22850
+ }
22851
+ case "response.mcp_call_arguments.delta": {
22852
+ const output = getOutput(snapshot, event.output_index);
22853
+ if (output.type === "mcp_call") {
22854
+ output.arguments += event.delta;
22855
+ }
22856
+ break;
22857
+ }
22858
+ case "response.mcp_call_arguments.done": {
22859
+ const output = getOutput(snapshot, event.output_index);
22860
+ if (output.type === "mcp_call") {
22861
+ output.arguments = event.arguments;
22862
+ }
22863
+ break;
22864
+ }
22865
+ case "response.code_interpreter_call_code.delta": {
22866
+ const output = getOutput(snapshot, event.output_index);
22867
+ if (output.type === "code_interpreter_call") {
22868
+ output.code = (output.code ?? "") + event.delta;
22869
+ }
22870
+ break;
22871
+ }
22872
+ case "response.code_interpreter_call_code.done": {
22873
+ const output = getOutput(snapshot, event.output_index);
22874
+ if (output.type === "code_interpreter_call") {
22875
+ output.code = event.code;
22876
+ }
22877
+ break;
22878
+ }
22879
+ case "response.code_interpreter_call.in_progress": {
22880
+ const output = getOutput(snapshot, event.output_index);
22881
+ if (output.type === "code_interpreter_call") {
22882
+ output.status = "in_progress";
22883
+ }
22884
+ break;
22885
+ }
22886
+ case "response.code_interpreter_call.interpreting": {
22887
+ const output = getOutput(snapshot, event.output_index);
22888
+ if (output.type === "code_interpreter_call") {
22889
+ output.status = "interpreting";
22890
+ }
22891
+ break;
22892
+ }
22893
+ case "response.code_interpreter_call.completed": {
22894
+ const output = getOutput(snapshot, event.output_index);
22895
+ if (output.type === "code_interpreter_call") {
22896
+ output.status = "completed";
22897
+ }
22898
+ break;
22899
+ }
22900
+ case "response.file_search_call.in_progress": {
22901
+ const output = getOutput(snapshot, event.output_index);
22902
+ if (output.type === "file_search_call") {
22903
+ output.status = "in_progress";
22904
+ }
22905
+ break;
22906
+ }
22907
+ case "response.file_search_call.searching": {
22908
+ const output = getOutput(snapshot, event.output_index);
22909
+ if (output.type === "file_search_call") {
22910
+ output.status = "searching";
22911
+ }
22912
+ break;
22913
+ }
22914
+ case "response.file_search_call.completed": {
22915
+ const output = getOutput(snapshot, event.output_index);
22916
+ if (output.type === "file_search_call") {
22917
+ output.status = "completed";
22918
+ }
22919
+ break;
22920
+ }
22921
+ case "response.web_search_call.in_progress": {
22922
+ const output = getOutput(snapshot, event.output_index);
22923
+ if (output.type === "web_search_call") {
22924
+ output.status = "in_progress";
22925
+ }
22926
+ break;
22927
+ }
22928
+ case "response.web_search_call.searching": {
22929
+ const output = getOutput(snapshot, event.output_index);
22930
+ if (output.type === "web_search_call") {
22931
+ output.status = "searching";
22932
+ }
22933
+ break;
22934
+ }
22935
+ case "response.web_search_call.completed": {
22936
+ const output = getOutput(snapshot, event.output_index);
22937
+ if (output.type === "web_search_call") {
22938
+ output.status = "completed";
22939
+ }
22940
+ break;
22941
+ }
22942
+ case "response.image_generation_call.in_progress": {
22943
+ const output = getOutput(snapshot, event.output_index);
22944
+ if (output.type === "image_generation_call") {
22945
+ output.status = "in_progress";
22946
+ }
22947
+ break;
22948
+ }
22949
+ case "response.image_generation_call.generating": {
22950
+ const output = getOutput(snapshot, event.output_index);
22951
+ if (output.type === "image_generation_call") {
22952
+ output.status = "generating";
22953
+ }
22954
+ break;
22955
+ }
22956
+ case "response.image_generation_call.completed": {
22957
+ const output = getOutput(snapshot, event.output_index);
22958
+ if (output.type === "image_generation_call") {
22959
+ output.status = "completed";
22960
+ }
22961
+ break;
22962
+ }
22963
+ case "response.mcp_call.in_progress": {
22964
+ const output = getOutput(snapshot, event.output_index);
22965
+ if (output.type === "mcp_call") {
22966
+ output.status = "in_progress";
22967
+ }
22968
+ break;
22969
+ }
22970
+ case "response.mcp_call.completed": {
22971
+ const output = getOutput(snapshot, event.output_index);
22972
+ if (output.type === "mcp_call") {
22973
+ output.status = "completed";
22974
+ }
22975
+ break;
22976
+ }
22977
+ case "response.mcp_call.failed": {
22978
+ const output = getOutput(snapshot, event.output_index);
22979
+ if (output.type === "mcp_call") {
22980
+ output.status = "failed";
22981
+ }
22982
+ break;
22983
+ }
22984
+ case "response.created":
22985
+ case "response.queued":
22986
+ case "response.in_progress":
22987
+ case "response.completed":
22988
+ case "response.failed":
22989
+ case "response.incomplete": {
22990
+ snapshot = cloneResponse(event.response);
22991
+ break;
22992
+ }
22993
+ case "response.audio.delta":
22994
+ case "response.audio.done":
22995
+ case "response.audio.transcript.delta":
22996
+ case "response.audio.transcript.done":
22997
+ case "response.image_generation_call.partial_image":
22998
+ case "response.mcp_list_tools.in_progress":
22999
+ case "response.mcp_list_tools.completed":
23000
+ case "response.mcp_list_tools.failed":
23001
+ case "keepalive":
23002
+ case "error": {
23003
+ break;
23004
+ }
23005
+ default: {
23006
+ assertNever3(event);
23007
+ }
23008
+ }
23009
+ return snapshot;
23010
+ }
23011
+ function cloneResponse(response) {
23012
+ const snapshot = structuredClone(response);
23013
+ if (!Object.getOwnPropertyDescriptor(snapshot, "output_text") || snapshot.output_text == null) {
23014
+ addOutputText(snapshot);
23015
+ }
23016
+ return snapshot;
23017
+ }
23018
+ function getOutput(snapshot, outputIndex) {
23019
+ const output = snapshot.output[outputIndex];
23020
+ if (!output) {
23021
+ throw new OpenAIError(`missing output at index ${outputIndex}`);
23022
+ }
23023
+ return output;
23024
+ }
23025
+ function getContent(content, contentIndex) {
23026
+ const part = content[contentIndex];
23027
+ if (!part) {
23028
+ throw new OpenAIError(`missing content at index ${contentIndex}`);
23029
+ }
23030
+ return part;
23031
+ }
23032
+ function assertNever3(value) {
23033
+ throw new OpenAIError(`Unhandled response stream event: ${JSON.stringify(value)}`);
23034
+ }
23035
+ var init_ResponseAccumulator = __esm(() => {
23036
+ init_error2();
23037
+ init_ResponsesParser();
23038
+ });
23039
+
21741
23040
  // node_modules/openai/lib/responses/ResponseStream.mjs
21742
23041
  function finalizeResponse(snapshot, params) {
21743
23042
  return maybeParseResponse(snapshot, params);
21744
23043
  }
21745
- var _ResponseStream_instances, _ResponseStream_params, _ResponseStream_currentResponseSnapshot, _ResponseStream_finalResponse, _ResponseStream_beginRequest, _ResponseStream_addEvent, _ResponseStream_endRequest, _ResponseStream_accumulateResponse, ResponseStream;
23044
+ var _ResponseStream_instances, _ResponseStream_params, _ResponseStream_currentResponseSnapshot, _ResponseStream_finalResponse, _ResponseStream_beginRequest, _ResponseStream_addEvent, _ResponseStream_endRequest, ResponseStream;
21746
23045
  var init_ResponseStream = __esm(() => {
21747
23046
  init_tslib();
21748
23047
  init_error2();
21749
23048
  init_EventStream();
23049
+ init_ResponseAccumulator();
21750
23050
  init_ResponsesParser();
23051
+ init_streaming2();
21751
23052
  ResponseStream = class ResponseStream extends EventStream {
21752
23053
  constructor(params) {
21753
23054
  super();
@@ -21765,13 +23066,13 @@ var init_ResponseStream = __esm(() => {
21765
23066
  }));
21766
23067
  return runner;
21767
23068
  }
23069
+ static fromReadableStream(stream) {
23070
+ const runner = new ResponseStream(null);
23071
+ runner._run(() => runner._fromReadableStream(stream));
23072
+ return runner;
23073
+ }
21768
23074
  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
- }
23075
+ this._listenForAbort(options?.signal);
21775
23076
  __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_beginRequest).call(this);
21776
23077
  let stream;
21777
23078
  let starting_after = null;
@@ -21790,6 +23091,19 @@ var init_ResponseStream = __esm(() => {
21790
23091
  }
21791
23092
  return __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_endRequest).call(this);
21792
23093
  }
23094
+ async _fromReadableStream(readableStream, options) {
23095
+ this._listenForAbort(options?.signal);
23096
+ __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_beginRequest).call(this);
23097
+ this._connected();
23098
+ const stream = Stream.fromReadableStream(readableStream, this.controller);
23099
+ for await (const event of stream) {
23100
+ __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_addEvent).call(this, event, null);
23101
+ }
23102
+ if (stream.controller.signal?.aborted) {
23103
+ throw new APIUserAbortError;
23104
+ }
23105
+ return __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_endRequest).call(this);
23106
+ }
21793
23107
  [(_ResponseStream_params = new WeakMap, _ResponseStream_currentResponseSnapshot = new WeakMap, _ResponseStream_finalResponse = new WeakMap, _ResponseStream_instances = new WeakSet, _ResponseStream_beginRequest = function _ResponseStream_beginRequest2() {
21794
23108
  if (this.ended)
21795
23109
  return;
@@ -21802,7 +23116,8 @@ var init_ResponseStream = __esm(() => {
21802
23116
  this._emit(name, event);
21803
23117
  }
21804
23118
  };
21805
- const response = __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_accumulateResponse).call(this, event);
23119
+ const response = accumulateResponse(event, __classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f"));
23120
+ __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, response, "f");
21806
23121
  maybeEmit("event", event);
21807
23122
  switch (event.type) {
21808
23123
  case "response.output_text.delta": {
@@ -21854,87 +23169,6 @@ var init_ResponseStream = __esm(() => {
21854
23169
  const parsedResponse = finalizeResponse(snapshot, __classPrivateFieldGet(this, _ResponseStream_params, "f"));
21855
23170
  __classPrivateFieldSet(this, _ResponseStream_finalResponse, parsedResponse, "f");
21856
23171
  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
23172
  }, Symbol.asyncIterator)]() {
21939
23173
  const pushQueue = [];
21940
23174
  const readQueue = [];
@@ -21996,12 +23230,12 @@ var init_ResponseStream = __esm(() => {
21996
23230
  });
21997
23231
 
21998
23232
  // node_modules/openai/resources/responses/input-items.mjs
21999
- var InputItems;
22000
- var init_input_items = __esm(() => {
23233
+ var InputItems2;
23234
+ var init_input_items2 = __esm(() => {
22001
23235
  init_resource();
22002
23236
  init_pagination();
22003
23237
  init_path();
22004
- InputItems = class InputItems extends APIResource {
23238
+ InputItems2 = class InputItems2 extends APIResource {
22005
23239
  list(responseID, query = {}, options) {
22006
23240
  return this._client.getAPIList(path3`/responses/${responseID}/input_items`, CursorPage, { query, ...options, __security: { bearerAuth: true } });
22007
23241
  }
@@ -22009,10 +23243,10 @@ var init_input_items = __esm(() => {
22009
23243
  });
22010
23244
 
22011
23245
  // node_modules/openai/resources/responses/input-tokens.mjs
22012
- var InputTokens;
22013
- var init_input_tokens = __esm(() => {
23246
+ var InputTokens2;
23247
+ var init_input_tokens2 = __esm(() => {
22014
23248
  init_resource();
22015
- InputTokens = class InputTokens extends APIResource {
23249
+ InputTokens2 = class InputTokens2 extends APIResource {
22016
23250
  count(body = {}, options) {
22017
23251
  return this._client.post("/responses/input_tokens", {
22018
23252
  body,
@@ -22024,22 +23258,22 @@ var init_input_tokens = __esm(() => {
22024
23258
  });
22025
23259
 
22026
23260
  // node_modules/openai/resources/responses/responses.mjs
22027
- var Responses;
22028
- var init_responses = __esm(() => {
23261
+ var Responses2;
23262
+ var init_responses2 = __esm(() => {
22029
23263
  init_ResponsesParser();
22030
23264
  init_ResponseStream();
22031
23265
  init_resource();
22032
- init_input_items();
22033
- init_input_items();
22034
- init_input_tokens();
22035
- init_input_tokens();
23266
+ init_input_items2();
23267
+ init_input_items2();
23268
+ init_input_tokens2();
23269
+ init_input_tokens2();
22036
23270
  init_headers();
22037
23271
  init_path();
22038
- Responses = class Responses extends APIResource {
23272
+ Responses2 = class Responses2 extends APIResource {
22039
23273
  constructor() {
22040
23274
  super(...arguments);
22041
- this.inputItems = new InputItems(this._client);
22042
- this.inputTokens = new InputTokens(this._client);
23275
+ this.inputItems = new InputItems2(this._client);
23276
+ this.inputTokens = new InputTokens2(this._client);
22043
23277
  }
22044
23278
  create(body, options) {
22045
23279
  return this._client.post("/responses", {
@@ -22090,8 +23324,8 @@ var init_responses = __esm(() => {
22090
23324
  return this._client.post("/responses/compact", { body, ...options, __security: { bearerAuth: true } });
22091
23325
  }
22092
23326
  };
22093
- Responses.InputItems = InputItems;
22094
- Responses.InputTokens = InputTokens;
23327
+ Responses2.InputItems = InputItems2;
23328
+ Responses2.InputTokens = InputTokens2;
22095
23329
  });
22096
23330
 
22097
23331
  // node_modules/openai/resources/skills/content.mjs
@@ -22720,7 +23954,7 @@ var init_resources = __esm(() => {
22720
23954
  init_models();
22721
23955
  init_moderations();
22722
23956
  init_realtime2();
22723
- init_responses();
23957
+ init_responses2();
22724
23958
  init_skills();
22725
23959
  init_uploads3();
22726
23960
  init_vector_stores();
@@ -22730,9 +23964,28 @@ var init_resources = __esm(() => {
22730
23964
  init_shared();
22731
23965
  });
22732
23966
 
23967
+ // node_modules/openai/internal/provider.mjs
23968
+ function configureProvider(provider) {
23969
+ const definition = providerDefinitions.get(provider);
23970
+ if (!definition) {
23971
+ throw new Error("Invalid provider. Providers must be created with createProvider().");
23972
+ }
23973
+ return definition.configure();
23974
+ }
23975
+ var providerDefinitionsKey, providerGlobal, existingProviderDefinitions, providerDefinitions;
23976
+ var init_provider = __esm(() => {
23977
+ providerDefinitionsKey = Symbol.for("openai.node.providerDefinitions.v1");
23978
+ providerGlobal = globalThis;
23979
+ existingProviderDefinitions = providerGlobal[providerDefinitionsKey];
23980
+ providerDefinitions = existingProviderDefinitions ?? new WeakMap;
23981
+ if (!existingProviderDefinitions) {
23982
+ Object.defineProperty(providerGlobal, providerDefinitionsKey, { value: providerDefinitions });
23983
+ }
23984
+ });
23985
+
22733
23986
  // node_modules/openai/client.mjs
22734
23987
  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 } = {}) {
23988
+ constructor(clientOptions = {}) {
22736
23989
  _OpenAI_instances.add(this);
22737
23990
  _OpenAI_encoder.set(this, undefined);
22738
23991
  this.completions = new Completions2(this);
@@ -22751,13 +24004,22 @@ class OpenAI2 {
22751
24004
  this.batches = new Batches(this);
22752
24005
  this.uploads = new Uploads(this);
22753
24006
  this.admin = new Admin(this);
22754
- this.responses = new Responses(this);
24007
+ this.responses = new Responses2(this);
22755
24008
  this.realtime = new Realtime2(this);
22756
24009
  this.conversations = new Conversations(this);
22757
24010
  this.evals = new Evals(this);
22758
24011
  this.containers = new Containers(this);
22759
24012
  this.skills = new Skills(this);
22760
24013
  this.videos = new Videos(this);
24014
+ const provider = clientOptions.provider;
24015
+ if (provider) {
24016
+ const conflictingOptions = ["apiKey", "adminAPIKey", "workloadIdentity", "baseURL"].filter((key) => clientOptions[key] != null);
24017
+ if (conflictingOptions.length) {
24018
+ 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.`);
24019
+ }
24020
+ }
24021
+ 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;
24022
+ const providerRuntime = provider ? configureProvider(provider) : undefined;
22761
24023
  const options = {
22762
24024
  apiKey,
22763
24025
  adminAPIKey,
@@ -22765,13 +24027,14 @@ class OpenAI2 {
22765
24027
  project,
22766
24028
  webhookSecret,
22767
24029
  workloadIdentity,
24030
+ provider,
22768
24031
  ...opts,
22769
- baseURL: baseURL || `https://api.openai.com/v1`
24032
+ baseURL: providerRuntime?.baseURL ?? (baseURL || `https://api.openai.com/v1`)
22770
24033
  };
22771
24034
  if (apiKey && workloadIdentity) {
22772
24035
  throw new OpenAIError("The `apiKey` and `workloadIdentity` options are mutually exclusive");
22773
24036
  }
22774
- if (!apiKey && !adminAPIKey && !workloadIdentity) {
24037
+ if (!providerRuntime && !apiKey && !adminAPIKey && !workloadIdentity) {
22775
24038
  throw new OpenAIError("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");
22776
24039
  }
22777
24040
  if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) {
@@ -22796,7 +24059,7 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
22796
24059
  this.maxRetries = options.maxRetries ?? 2;
22797
24060
  this.fetch = options.fetch ?? getDefaultFetch();
22798
24061
  __classPrivateFieldSet(this, _OpenAI_encoder, FallbackEncoder, "f");
22799
- const customHeadersEnv = readEnv("OPENAI_CUSTOM_HEADERS");
24062
+ const customHeadersEnv = provider ? undefined : readEnv("OPENAI_CUSTOM_HEADERS");
22800
24063
  if (customHeadersEnv) {
22801
24064
  const parsed = {};
22802
24065
  for (const line of customHeadersEnv.split(`
@@ -22809,6 +24072,7 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
22809
24072
  options.defaultHeaders = buildHeaders([parsed, options.defaultHeaders]);
22810
24073
  }
22811
24074
  this._options = options;
24075
+ this._provider = providerRuntime;
22812
24076
  if (workloadIdentity) {
22813
24077
  this._workloadIdentityAuth = new WorkloadIdentityAuth(workloadIdentity, this.fetch);
22814
24078
  }
@@ -22819,7 +24083,9 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
22819
24083
  this.webhookSecret = webhookSecret;
22820
24084
  }
22821
24085
  withOptions(options) {
22822
- const client = new this.constructor({
24086
+ const inheritedProvider = this._options.provider;
24087
+ const provider = options.provider ?? inheritedProvider;
24088
+ const inheritedOptions = {
22823
24089
  ...this._options,
22824
24090
  baseURL: this.baseURL,
22825
24091
  maxRetries: this.maxRetries,
@@ -22833,8 +24099,23 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
22833
24099
  workloadIdentity: this._options.workloadIdentity,
22834
24100
  organization: this.organization,
22835
24101
  project: this.project,
22836
- webhookSecret: this.webhookSecret,
22837
- ...options
24102
+ webhookSecret: this.webhookSecret
24103
+ };
24104
+ if (provider) {
24105
+ delete inheritedOptions.apiKey;
24106
+ delete inheritedOptions.adminAPIKey;
24107
+ delete inheritedOptions.workloadIdentity;
24108
+ delete inheritedOptions.baseURL;
24109
+ if (provider !== inheritedProvider) {
24110
+ delete inheritedOptions.organization;
24111
+ delete inheritedOptions.project;
24112
+ delete inheritedOptions.defaultHeaders;
24113
+ }
24114
+ }
24115
+ const client = new this.constructor({
24116
+ ...inheritedOptions,
24117
+ ...options,
24118
+ provider
22838
24119
  });
22839
24120
  return client;
22840
24121
  }
@@ -22893,6 +24174,8 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
22893
24174
  return APIError.generate(status, error, message, headers);
22894
24175
  }
22895
24176
  async _callApiKey() {
24177
+ if (this._provider)
24178
+ return false;
22896
24179
  const apiKey = this._options.apiKey;
22897
24180
  if (typeof apiKey !== "function")
22898
24181
  return false;
@@ -22924,6 +24207,8 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
22924
24207
  return url.toString();
22925
24208
  }
22926
24209
  async prepareOptions(options) {
24210
+ if (this._provider)
24211
+ return;
22927
24212
  const security = options.__security ?? { bearerAuth: true };
22928
24213
  if (security.bearerAuth) {
22929
24214
  await this._callApiKey();
@@ -22963,7 +24248,9 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
22963
24248
  const { req, url, timeout } = await this.buildRequest(options, {
22964
24249
  retryCount: maxRetries - retriesRemaining
22965
24250
  });
24251
+ const hasStreamingBody = options.__metadata?.["hasStreamingBody"] === true;
22966
24252
  await this.prepareRequest(req, { url, options });
24253
+ await this._provider?.prepareRequest?.(req, { url, options });
22967
24254
  const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0");
22968
24255
  const retryLogStr = retryOfRequestLogID === undefined ? "" : `, retryOf: ${retryOfRequestLogID}`;
22969
24256
  const startTime = Date.now();
@@ -22987,7 +24274,7 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
22987
24274
  throw new APIUserAbortError;
22988
24275
  }
22989
24276
  const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
22990
- if (retriesRemaining) {
24277
+ if (retriesRemaining && !hasStreamingBody) {
22991
24278
  loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`);
22992
24279
  loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({
22993
24280
  retryOfRequestLogID,
@@ -22997,8 +24284,9 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
22997
24284
  }));
22998
24285
  return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
22999
24286
  }
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({
24287
+ const terminalMessage = hasStreamingBody ? "error; streaming body cannot be retried" : "error; no more retries left";
24288
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${terminalMessage}`);
24289
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${terminalMessage})`, formatRequestDetails({
23002
24290
  retryOfRequestLogID,
23003
24291
  url,
23004
24292
  durationMs: headersTime - startTime,
@@ -23030,7 +24318,7 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
23030
24318
  }, retriesRemaining, retryOfRequestLogID ?? requestLogID);
23031
24319
  }
23032
24320
  const shouldRetry = await this.shouldRetry(response);
23033
- if (retriesRemaining && shouldRetry) {
24321
+ if (retriesRemaining && shouldRetry && !hasStreamingBody) {
23034
24322
  const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
23035
24323
  await CancelReadableStream(response.body);
23036
24324
  loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
@@ -23043,7 +24331,7 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
23043
24331
  }));
23044
24332
  return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
23045
24333
  }
23046
- const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
24334
+ const retryMessage = shouldRetry ? hasStreamingBody ? `error; streaming body cannot be retried` : `error; no more retries left` : `error; not retryable`;
23047
24335
  loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
23048
24336
  const errText = await response.text().catch((err) => castToError(err).message);
23049
24337
  const errJSON = safeJSON(errText);
@@ -23206,19 +24494,25 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
23206
24494
  "OpenAI-Organization": this.organization,
23207
24495
  "OpenAI-Project": this.project
23208
24496
  },
23209
- await this.authHeaders(options, options.__security ?? { bearerAuth: true }),
24497
+ this._provider ? undefined : await this.authHeaders(options, options.__security ?? { bearerAuth: true }),
23210
24498
  this._options.defaultHeaders,
23211
24499
  bodyHeaders,
23212
24500
  options.headers
23213
24501
  ]);
23214
- this.validateHeaders(headers, options.__security ?? { bearerAuth: true });
24502
+ if (!this._provider) {
24503
+ this.validateHeaders(headers, options.__security ?? { bearerAuth: true });
24504
+ }
23215
24505
  return headers.values;
23216
24506
  }
23217
24507
  _makeAbort(controller) {
23218
24508
  return () => controller.abort();
23219
24509
  }
23220
- buildBody({ options: { body, headers: rawHeaders } }) {
24510
+ buildBody({ options }) {
24511
+ const { body, headers: rawHeaders } = options;
23221
24512
  if (!body) {
24513
+ if (body === undefined && "body" in options) {
24514
+ return { ...__classPrivateFieldGet(this, _OpenAI_encoder, "f").call(this, { body, headers: buildHeaders([rawHeaders]) }), isStreamingBody: false };
24515
+ }
23222
24516
  return { bodyHeaders: undefined, body: undefined, isStreamingBody: false };
23223
24517
  }
23224
24518
  const headers = buildHeaders([rawHeaders]);
@@ -23297,18 +24591,19 @@ var init_client = __esm(() => {
23297
24591
  init_fine_tuning();
23298
24592
  init_graders2();
23299
24593
  init_realtime2();
23300
- init_responses();
24594
+ init_responses2();
23301
24595
  init_skills();
23302
24596
  init_uploads3();
23303
24597
  init_vector_stores();
23304
24598
  init_webhooks();
23305
24599
  init_detect_platform();
23306
24600
  init_headers();
24601
+ init_provider();
23307
24602
  init_env();
23308
24603
  init_log();
23309
24604
  init_values();
23310
24605
  _a2 = OpenAI2, _OpenAI_encoder = new WeakMap, _OpenAI_instances = new WeakSet, _OpenAI_baseURLOverridden = function _OpenAI_baseURLOverridden() {
23311
- return this.baseURL !== "https://api.openai.com/v1";
24606
+ return this._provider !== undefined || this.baseURL !== "https://api.openai.com/v1";
23312
24607
  };
23313
24608
  OpenAI2.OpenAI = _a2;
23314
24609
  OpenAI2.DEFAULT_TIMEOUT = 600000;
@@ -23327,6 +24622,7 @@ var init_client = __esm(() => {
23327
24622
  OpenAI2.UnprocessableEntityError = UnprocessableEntityError;
23328
24623
  OpenAI2.InvalidWebhookSignatureError = InvalidWebhookSignatureError;
23329
24624
  OpenAI2.toFile = toFile;
24625
+ OpenAI2.toStreamingFile = toStreamingFile;
23330
24626
  OpenAI2.Completions = Completions2;
23331
24627
  OpenAI2.Chat = Chat;
23332
24628
  OpenAI2.Embeddings = Embeddings;
@@ -23343,7 +24639,7 @@ var init_client = __esm(() => {
23343
24639
  OpenAI2.Batches = Batches;
23344
24640
  OpenAI2.Uploads = Uploads;
23345
24641
  OpenAI2.Admin = Admin;
23346
- OpenAI2.Responses = Responses;
24642
+ OpenAI2.Responses = Responses2;
23347
24643
  OpenAI2.Realtime = Realtime2;
23348
24644
  OpenAI2.Conversations = Conversations;
23349
24645
  OpenAI2.Evals = Evals;
@@ -23372,6 +24668,16 @@ var init_azure = __esm(() => {
23372
24668
  ]);
23373
24669
  });
23374
24670
 
24671
+ // node_modules/openai/bedrock.mjs
24672
+ var init_bedrock = __esm(() => {
24673
+ init_error2();
24674
+ init_client();
24675
+ init_headers();
24676
+ init_utils2();
24677
+ init_ResponsesParser();
24678
+ init_resources();
24679
+ });
24680
+
23375
24681
  // node_modules/openai/index.mjs
23376
24682
  var init_openai2 = __esm(() => {
23377
24683
  init_client();
@@ -23381,6 +24687,7 @@ var init_openai2 = __esm(() => {
23381
24687
  init_pagination();
23382
24688
  init_error();
23383
24689
  init_azure();
24690
+ init_bedrock();
23384
24691
  });
23385
24692
 
23386
24693
  // node_modules/oauth4webapi/build/index.js
@@ -23436,7 +24743,7 @@ var USER_AGENT, ERR_INVALID_ARG_VALUE = "ERR_INVALID_ARG_VALUE", ERR_INVALID_ARG
23436
24743
  var init_build = __esm(() => {
23437
24744
  if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
23438
24745
  const NAME = "oauth4webapi";
23439
- const VERSION = "v3.8.5";
24746
+ const VERSION = "v3.8.8";
23440
24747
  USER_AGENT = `${NAME}/${VERSION}`;
23441
24748
  }
23442
24749
  allowInsecureRequests = Symbol();
@@ -23895,7 +25202,7 @@ function noteEmbeddingSuccess() {
23895
25202
  const report = (what) => (err) => {
23896
25203
  console.error(`[memory] ${what} backfill after embeddings recovered failed:`, err.message);
23897
25204
  };
23898
- backfill2 = import("./embedding-space-zsdw37bb.js").then(({ runEmbeddingMaintenance }) => runEmbeddingMaintenance({ backfill: true })).catch(report("Embedding")).finally(() => {
25205
+ backfill2 = import("./embedding-space-mjt5ksq0.js").then(({ runEmbeddingMaintenance }) => runEmbeddingMaintenance({ backfill: true })).catch(report("Embedding")).finally(() => {
23899
25206
  backfill2 = null;
23900
25207
  });
23901
25208
  }
@@ -26489,7 +27796,7 @@ async function loadSecretRegistry() {
26489
27796
  result.failed += 1;
26490
27797
  }
26491
27798
  try {
26492
- const { loadRuntimeControllerSecrets } = await import("./db-gd81d68c.js");
27799
+ const { loadRuntimeControllerSecrets } = await import("./db-bg0hxjq1.js");
26493
27800
  const loaded = await loadRuntimeControllerSecrets();
26494
27801
  result.runtimeController = loaded.count;
26495
27802
  result.failed += loaded.failed;
@@ -26650,7 +27957,7 @@ async function requestSteering(args) {
26650
27957
  }
26651
27958
  const requestedMode = args.mode ?? "queue";
26652
27959
  const onUnsupported = args.onUnsupported ?? "degrade";
26653
- const { dispatchPre, extensionIdForAgent } = await import("./dispatcher-76as8w2t.js");
27960
+ const { dispatchPre, extensionIdForAgent } = await import("./dispatcher-v5dbfscq.js");
26654
27961
  const preSteer = await dispatchPre("pre.task.steer", {
26655
27962
  task,
26656
27963
  message: args.message,
@@ -28800,10 +30107,10 @@ async function createTaskExtended2(task, options) {
28800
30107
  vcsProvider, vcsRepo, vcsEventType, vcsNumber, vcsCommentId, vcsAuthor, vcsUrl,
28801
30108
  vcsInstallationId, vcsNodeId,
28802
30109
  agentmailInboxId, agentmailMessageId, agentmailThreadId,
28803
- mentionMessageId, mentionChannelId, dir, parentTaskId, dispatchedByTaskId, model, modelTier, effort, profile, fallbackHops, scheduleId,
30110
+ mentionMessageId, mentionChannelId, dir, parentTaskId, dispatchedByTaskId, model, modelTier, effort, profile, modelGroup, fallbackHops, scheduleId,
28804
30111
  workflowRunId, workflowRunStepId, outputSchema, followUpConfig, requestedByUserId, requestedByUserIdInherited, contextKey, routingAffinity, swarmVersion, createdAt, lastUpdatedAt, created_by, updated_by, isHumanFree,
28805
30112
  sourceStepId, sourceScriptRunId
28806
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`, [
30113
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`, [
28807
30114
  id,
28808
30115
  insertKey,
28809
30116
  options?.agentId ?? null,
@@ -28846,6 +30153,7 @@ async function createTaskExtended2(task, options) {
28846
30153
  options?.modelTier ?? null,
28847
30154
  options?.effort ?? null,
28848
30155
  options?.profile?.trim() || null,
30156
+ options?.modelGroup?.trim() || null,
28849
30157
  options?.fallbackHops?.length ? JSON.stringify(options.fallbackHops) : null,
28850
30158
  options?.scheduleId ?? null,
28851
30159
  options?.workflowRunId ?? null,
@@ -28914,7 +30222,7 @@ async function createTaskExtended2(task, options) {
28914
30222
  priority: row.priority
28915
30223
  }, (task) => task !== null, row.requestedByUserId);
28916
30224
  getDbClient2().afterCommit(() => {
28917
- import("./event-bus-tvf2grf4.js").then(({ workflowEventBus }) => {
30225
+ import("./event-bus-pawddp92.js").then(({ workflowEventBus }) => {
28918
30226
  workflowEventBus.emit("task.created", {
28919
30227
  taskId: row.id,
28920
30228
  task: row.task,
@@ -28996,7 +30304,7 @@ async function releaseTask2(taskId, wakeSnapshot) {
28996
30304
  } catch {}
28997
30305
  if (isRuntimePoolsEnabled() && !wakeSnapshot)
28998
30306
  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))));
30307
+ import("./event-bus-pawddp92.js").then(({ workflowEventBus }) => workflowEventBus.emit("task.unassigned", { taskId })).catch((error) => console.error("[db] Routing event failed:", scrubSecrets(String(error))));
29000
30308
  });
29001
30309
  }
29002
30310
  return row ? rowToAgentTask(row) : null;
@@ -29066,7 +30374,7 @@ async function rejectTask2(taskId, agentId, reason) {
29066
30374
  } catch {}
29067
30375
  if (isRuntimePoolsEnabled())
29068
30376
  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))));
30377
+ import("./event-bus-pawddp92.js").then(({ workflowEventBus }) => workflowEventBus.emit("task.unassigned", { taskId })).catch((error) => console.error("[db] Routing event failed:", scrubSecrets(String(error))));
29070
30378
  });
29071
30379
  }
29072
30380
  return row ? rowToAgentTask(row) : null;
@@ -30450,6 +31758,7 @@ function rowToScheduledTask(row) {
30450
31758
  model: row.model ?? undefined,
30451
31759
  modelTier: parseModelTier(row.modelTier) ?? undefined,
30452
31760
  profile: row.profile ?? undefined,
31761
+ modelGroup: row.modelGroup ?? undefined,
30453
31762
  scheduleType: row.scheduleType,
30454
31763
  targetType: row.targetType,
30455
31764
  workflowId: row.workflowId ?? undefined,
@@ -30540,11 +31849,11 @@ async function createScheduledTask2(data) {
30540
31849
  id, "key", name, description, cronExpression, intervalMs, taskTemplate,
30541
31850
  taskType, tags, priority, targetAgentId, enabled, nextRunAt,
30542
31851
  createdByAgentId, parentTaskId, requestedDelayMs, requestedRunAt,
30543
- timezone, model, modelTier, profile, scheduleType,
31852
+ timezone, model, modelTier, profile, modelGroup, scheduleType,
30544
31853
  targetType, workflowId, scriptName, scriptArgs, params, requiredParams, requires,
30545
31854
  createdAt, lastUpdatedAt,
30546
31855
  created_by, updated_by, updatedByAgentId
30547
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`, [
31856
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`, [
30548
31857
  id,
30549
31858
  normalizeAssetKey(data.key ?? defaultAssetKey("schedule", id)),
30550
31859
  data.name,
@@ -30566,6 +31875,7 @@ async function createScheduledTask2(data) {
30566
31875
  data.model ?? null,
30567
31876
  data.modelTier ?? null,
30568
31877
  data.profile ?? null,
31878
+ data.modelGroup ?? null,
30569
31879
  data.scheduleType ?? "recurring",
30570
31880
  data.targetType ?? "agent-task",
30571
31881
  data.workflowId ?? null,
@@ -30667,6 +31977,10 @@ async function updateScheduledTask2(id, data) {
30667
31977
  updates.push("profile = ?");
30668
31978
  params.push(data.profile);
30669
31979
  }
31980
+ if (data.modelGroup !== undefined) {
31981
+ updates.push("modelGroup = ?");
31982
+ params.push(data.modelGroup);
31983
+ }
30670
31984
  if (data.scheduleType !== undefined) {
30671
31985
  updates.push("scheduleType = ?");
30672
31986
  params.push(data.scheduleType);
@@ -30729,7 +32043,7 @@ async function deleteScheduledTask2(id) {
30729
32043
  const parent = await getTaskById2(deferred.parentTaskId);
30730
32044
  if (!parent?.deferredAt)
30731
32045
  return;
30732
- const { createWorkerTaskFollowUp } = await import("./worker-follow-up-fg48vk6d.js");
32046
+ const { createWorkerTaskFollowUp } = await import("./worker-follow-up-zwgg20sr.js");
30733
32047
  await createWorkerTaskFollowUp({
30734
32048
  task: parent,
30735
32049
  status: "failed",
@@ -31500,7 +32814,7 @@ async function getWorkflowsByScheduleId2(scheduleId) {
31500
32814
  }
31501
32815
  async function createWorkflowRun2(data) {
31502
32816
  const now = new Date().toISOString();
31503
- const row = await getDbClient2().get(`INSERT INTO workflow_runs (id, workflowId, triggerType, startedAt, triggerData, created_by, parentStepId, parentStepAttempt, triggeredByAgentId, definitionHash, sourceStepId) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`, [
32817
+ const row = await getDbClient2().get(`INSERT INTO workflow_runs (id, workflowId, triggerType, startedAt, triggerData, created_by, parentStepId, parentStepAttempt, triggeredByAgentId, definitionHash, sourceStepId, principal) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`, [
31504
32818
  data.id,
31505
32819
  data.workflowId,
31506
32820
  data.triggerType ?? "manual",
@@ -31511,7 +32825,8 @@ async function createWorkflowRun2(data) {
31511
32825
  data.parentStepAttempt ?? 0,
31512
32826
  data.triggeredByAgentId ?? null,
31513
32827
  data.definitionHash ?? null,
31514
- data.parentStepId || data.triggerType !== "api" && (data.triggerType ?? "manual") !== "manual" ? null : getCurrentRunProvenance()?.sourceStepId ?? null
32828
+ data.parentStepId || data.triggerType !== "api" && (data.triggerType ?? "manual") !== "manual" ? null : getCurrentRunProvenance()?.sourceStepId ?? null,
32829
+ data.principal ?? null
31515
32830
  ]);
31516
32831
  if (!row)
31517
32832
  throw new Error("Failed to create workflow run");
@@ -35102,7 +36417,7 @@ var init_db4 = __esm(() => {
35102
36417
  configureAgentDependencies({
35103
36418
  createLogEntry: (entry) => createLogEntry2(entry),
35104
36419
  installSystemDefaultSkillsForAgent: (agentId) => installSystemDefaultSkillsForAgent2(agentId),
35105
- resolvePendingImportAssignments: async (agent) => (await import("./pending-2sxh1t6j.js")).resolvePendingImportAssignments(agent)
36420
+ resolvePendingImportAssignments: async (agent) => (await import("./pending-4rxawq8y.js")).resolvePendingImportAssignments(agent)
35106
36421
  });
35107
36422
  configureTaskWriteDependencies({
35108
36423
  createLogEntry: (...args) => createLogEntry2(...args),
@@ -35152,4 +36467,4 @@ var init_db4 = __esm(() => {
35152
36467
  };
35153
36468
  });
35154
36469
 
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 };
36470
+ 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, getWorkflowRunPrincipalRow, 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 };