@vibe-lark/larkpal 0.1.86 → 0.1.87

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 (208) hide show
  1. package/dist/account-id-BM1T6029-BzQ_cMoi.mjs +1 -0
  2. package/dist/activation-context--5yu1dPF-XV0Y0pTy.mjs +1 -0
  3. package/dist/anthropic-CFZUCb1w.mjs +39 -0
  4. package/dist/assistant-visible-text-DuFWokAt-BOJV_zwc.mjs +9 -0
  5. package/dist/azure-openai-responses-BEuiMaF-.mjs +1 -0
  6. package/dist/boundary-file-read-BSd9MXPy-gnNVhPKT.mjs +1 -0
  7. package/dist/browser-lifecycle-cleanup-BdNsMhMD-BM97qA_M.mjs +1 -0
  8. package/dist/build-Bkj0hOS2.mjs +3 -0
  9. package/dist/bundled-compat-BpaDaAAu-DJtrIX6i.mjs +27 -0
  10. package/dist/bundled-dir-U738ay4K-BxbzrJOo.mjs +1 -0
  11. package/dist/call-DimWbpgJ-B4pv55RH.mjs +20 -0
  12. package/dist/channel-bootstrap.runtime-BVclcGv1-CEZ0-JP9.mjs +1 -0
  13. package/dist/channel-bootstrap.runtime-Cwcr38m2-Dt6QlQkX.mjs +1 -0
  14. package/dist/chunk-DHbaKqs-.mjs +1 -0
  15. package/dist/cli.mjs +7 -92
  16. package/dist/command-format-LSnUCVVF-Dn4h9IOh.mjs +16 -0
  17. package/dist/config-Bim2pi8a-03N-28sw.mjs +1 -0
  18. package/dist/delivery-context.shared-j5hC5qb1-BSLQG47q.mjs +1 -0
  19. package/dist/diagnostic-ClMwNnUA-BMKvPQJT.mjs +1 -0
  20. package/dist/dist-J5UB83Ws.mjs +601 -0
  21. package/dist/dist-coestTs9.mjs +5 -0
  22. package/dist/env-api-keys-Cuz5irWW.mjs +1 -0
  23. package/dist/event-stream-B7Ei41Bu.mjs +1 -0
  24. package/dist/facade-loader-DFzIYYt_-4bzFvy-b.mjs +1 -0
  25. package/dist/from-Ba69_5cR.mjs +14 -0
  26. package/dist/gateway-method-policy-C7rf0SeV-CTJcMQCE.mjs +1 -0
  27. package/dist/github-copilot-headers-BfhryVuU.mjs +1 -0
  28. package/dist/google-ABo-1guT.mjs +1 -0
  29. package/dist/google-gemini-cli-CGlN1zUA.mjs +2 -0
  30. package/dist/google-shared-C60sNhwd.mjs +301 -0
  31. package/dist/google-vertex-De0nAItu.mjs +1 -0
  32. package/dist/hash-Dw-N8Y9l.mjs +1 -0
  33. package/dist/headers-Bpsp70B9.mjs +1 -0
  34. package/dist/home-dir-C44RaPME-B5iLWwCq.mjs +1 -0
  35. package/dist/ids-BPsM98Uu-CJBJAeVC.mjs +1 -0
  36. package/dist/image-2w3cApg7-CrpUMCvm.mjs +3 -0
  37. package/dist/interactive-init-C5MFL5MW.mjs +8 -0
  38. package/dist/io-CH2g3vsv-JJtUIa_U.mjs +10 -0
  39. package/dist/jiti-loader-cache-Bat69wam-DNIteTtO.mjs +9 -0
  40. package/dist/json-file-BQRNuxmK-hRjIgOXI.mjs +1 -0
  41. package/dist/json-parse-BESd8UAM.mjs +3 -0
  42. package/dist/jws-YaZ38F_i.mjs +12 -0
  43. package/dist/lark-cli-provider-BLMxH6CN.mjs +4 -0
  44. package/dist/lark-logger-xpMKNNtY.mjs +1 -0
  45. package/dist/live-smoke-DpURW676.mjs +33 -0
  46. package/dist/load-context-mb7uvLSn-3xYwSnOZ.mjs +1 -0
  47. package/dist/loader-708jrx4Y-BbJRXNlQ.mjs +4 -0
  48. package/dist/main.mjs +153 -74571
  49. package/dist/manifest-registry-_hxKCS2K-OL8KK_o4.mjs +15 -0
  50. package/dist/mcp-server.mjs +4 -527
  51. package/dist/message-channel-Bk_YHfQg-n2Hw2Y0L.mjs +1 -0
  52. package/dist/message-channel-core-DTA--Gjh-CIh10vfo.mjs +1 -0
  53. package/dist/message.config.runtime-K-k4XOyq-F_h0Cgkl.mjs +1 -0
  54. package/dist/message.gateway.runtime-DqHOHRTQ-ge4c5p4s.mjs +1 -0
  55. package/dist/mistral-DyL3Zo1b.mjs +7 -0
  56. package/dist/model-auth-env-oyg2Hexc-DJbt9J3o.mjs +1 -0
  57. package/dist/models-config-BmpSQJQF-BL6S5qAo.mjs +1 -0
  58. package/dist/models-config.runtime-SOhLEw-f.mjs +1 -0
  59. package/dist/multipart-parser-B9dwXBqu.mjs +2 -0
  60. package/dist/oauth-25y2wc7K.mjs +75 -0
  61. package/dist/openai-C-rgGb7X.mjs +16 -0
  62. package/dist/openai-codex-responses-BbyAPsP1.mjs +7 -0
  63. package/dist/openai-completions-Bu5qvQzb.mjs +5 -0
  64. package/dist/openai-responses-pIdwQBc4.mjs +1 -0
  65. package/dist/openai-responses-shared-DqW1JSux.mjs +10 -0
  66. package/dist/paths-D6msg0S1-BO4XgM1u.mjs +1 -0
  67. package/dist/paths-D92DjaZ--DdtJ-zYp.mjs +1 -0
  68. package/dist/pi-model-discovery-Bd0TWzo8-DvSM0eWu.mjs +1 -0
  69. package/dist/pi-model-discovery-runtime-PrjWOmsV.mjs +1 -0
  70. package/dist/pi-tools.before-tool-call.runtime-Bn7uqKie-WPxU5oNX.mjs +2 -0
  71. package/dist/plugin-auto-enable-DdH3n9V8-Dr_bUXkG.mjs +1 -0
  72. package/dist/process-scoped-map-B2cWkYET-Co-i-MXA.mjs +1 -0
  73. package/dist/provider-discovery.runtime-DY0VWQ81.mjs +1 -0
  74. package/dist/provider-model-compat-CFqcq0it-BUwZENrz.mjs +1 -0
  75. package/dist/provider-runtime-C8rljsNs-BDvu6FW3.mjs +1 -0
  76. package/dist/provider-runtime-CT50mNIX-DImw7ZZu.mjs +79 -0
  77. package/dist/provider-stream-COLujAAo-Dpq1DSIk.mjs +248 -0
  78. package/dist/providers.runtime-Ba7tOlq7-B4t6ywCr.mjs +1 -0
  79. package/dist/public-surface-loader-BVl0NQAE-TfJ3izj1.mjs +1 -0
  80. package/dist/resolve-C33B7eeu-DZM_z6Wr.mjs +1 -0
  81. package/dist/runtime-Cym-fqI8-1GOIuRRQ.mjs +1 -0
  82. package/dist/runtime-channel-state-CohMybAh-BBzhl07Q.mjs +1 -0
  83. package/dist/runtime-snapshot-C54O1-gI-DxusscPf.mjs +1 -0
  84. package/dist/runtime-state-IBOIXKOx-Cw1GA1td.mjs +1 -0
  85. package/dist/runtime-web-tools-fallback.runtime-Ca-qn1mj-BsYE2gOd.mjs +1 -0
  86. package/dist/runtime-web-tools-manifest.runtime-BgxQTjmq-P6MKP9gQ.mjs +1 -0
  87. package/dist/runtime-web-tools-public-artifacts.runtime-D9qcoWIX-5VoyjouO.mjs +1 -0
  88. package/dist/session-archive.runtime-B52_5vs4-cU2tYbBz.mjs +1 -0
  89. package/dist/session-key-Cn2QoOyX-QZeYmbxd.mjs +1 -0
  90. package/dist/session-transcript-files.fs-DEeFXruQ-CXIAFSsr.mjs +1 -0
  91. package/dist/src-CCDx_C-U.mjs +3 -0
  92. package/dist/src-DACmA9V6.mjs +5 -0
  93. package/dist/subagent-announce-L5WsQatW--rMn240x.mjs +2 -0
  94. package/dist/subagent-announce.registry.runtime-DiqZyeTs-DNfNHsls.mjs +1 -0
  95. package/dist/subagent-registry-steer-runtime-DFgZFC0j-XYS1_qwl.mjs +1 -0
  96. package/dist/subagent-system-prompt-C1qnN--K-CsU4f97T.mjs +23 -0
  97. package/dist/target-parsing-loaded-DKkb6jJY-B830OA1a.mjs +12 -0
  98. package/dist/task-registry-delivery-runtime-Dd1CUkZF-B2Hj2k8C.mjs +16 -0
  99. package/dist/task-registry-delivery-runtime-ragbeVx5-Bdvo2Q5u.mjs +1 -0
  100. package/dist/thinking-Bh-7MqXz-uApNUe6g.mjs +1 -0
  101. package/dist/transcript-E_-ISOkD-VTwb782D.mjs +5 -0
  102. package/dist/transcript.runtime-BqhvZZdl-B4E0TiX5.mjs +1 -0
  103. package/dist/transform-messages-BTA3xbAI.mjs +1 -0
  104. package/dist/web-provider-public-artifacts-BlpRwIUS-DbVhDOrY.mjs +1 -0
  105. package/dist/web-search-providers.runtime--0aUtC3b-Bjh4Bmrz.mjs +1 -0
  106. package/package.json +2 -3
  107. package/dist/account-id-BM1T6029-DYjVxojW.mjs +0 -46
  108. package/dist/activation-context--5yu1dPF-Bwsn3moT.mjs +0 -172
  109. package/dist/anthropic-TH8ERTXK.mjs +0 -5962
  110. package/dist/assistant-visible-text-DuFWokAt-CsbII5KS.mjs +0 -596
  111. package/dist/azure-openai-responses-Bt_Ag9Er.mjs +0 -166
  112. package/dist/boundary-file-read-BSd9MXPy--KThL5e6.mjs +0 -594
  113. package/dist/browser-lifecycle-cleanup-BdNsMhMD-O3tnAM4i.mjs +0 -60
  114. package/dist/build-DgTrEpge.mjs +0 -3333
  115. package/dist/bundled-compat-BpaDaAAu-D7oazKjD.mjs +0 -5216
  116. package/dist/bundled-dir-U738ay4K-DXK0q_TV.mjs +0 -258
  117. package/dist/call-DimWbpgJ-ColD4W-y.mjs +0 -9993
  118. package/dist/channel-bootstrap.runtime-BVclcGv1-DJv_Z-Kr.mjs +0 -2
  119. package/dist/channel-bootstrap.runtime-Cwcr38m2-VRfVCR-i.mjs +0 -33
  120. package/dist/chunk-D6SyT4dJ.mjs +0 -36
  121. package/dist/command-format-LSnUCVVF-BQ2SMKka.mjs +0 -685
  122. package/dist/config-Bim2pi8a-BQUdfiEi.mjs +0 -9
  123. package/dist/delivery-context.shared-j5hC5qb1-CI83RXXZ.mjs +0 -72
  124. package/dist/diagnostic-ClMwNnUA-D6nUtLnb.mjs +0 -140
  125. package/dist/dist-CEGw8-2W.mjs +0 -429
  126. package/dist/dist-DD2aJ2UL.mjs +0 -125135
  127. package/dist/env-api-keys-BVvSg7T2.mjs +0 -68
  128. package/dist/event-stream-xaQWmyas.mjs +0 -15226
  129. package/dist/facade-loader-DFzIYYt_-CIr4HKtE.mjs +0 -194
  130. package/dist/from-DF7cl2wz.mjs +0 -3842
  131. package/dist/gateway-method-policy-C7rf0SeV-CJQMEYIE.mjs +0 -28
  132. package/dist/github-copilot-headers-DjqWtUoP.mjs +0 -22
  133. package/dist/google-C2pVrgBZ.mjs +0 -336
  134. package/dist/google-gemini-cli-BBxgS5Ho.mjs +0 -623
  135. package/dist/google-shared-BsWgwEk1.mjs +0 -22791
  136. package/dist/google-vertex-BsVLJrrC.mjs +0 -358
  137. package/dist/hash-DAFtW_W7.mjs +0 -16
  138. package/dist/headers-R3HdCbAE.mjs +0 -8
  139. package/dist/home-dir-C44RaPME-CBRS4HLP.mjs +0 -93
  140. package/dist/ids-BPsM98Uu-CwuxvUai.mjs +0 -77
  141. package/dist/image-2w3cApg7-CxpHvoB5.mjs +0 -207
  142. package/dist/interactive-init-BXQBalNr.mjs +0 -450
  143. package/dist/io-CH2g3vsv-BOGlLlB8.mjs +0 -26218
  144. package/dist/jiti-loader-cache-Bat69wam-D6hCxboy.mjs +0 -5049
  145. package/dist/json-file-BQRNuxmK-DhJM5NsG.mjs +0 -108
  146. package/dist/json-parse-v_HIJjjI.mjs +0 -381
  147. package/dist/jws-GFcTvvVT.mjs +0 -2291
  148. package/dist/lark-cli-provider-BARgbbmo.mjs +0 -554
  149. package/dist/lark-logger-D7_pEVQc.mjs +0 -143
  150. package/dist/live-smoke-BhkBOcH9.mjs +0 -7135
  151. package/dist/load-context-mb7uvLSn-B10MAi3I.mjs +0 -29
  152. package/dist/loader-708jrx4Y-BOswuvpe.mjs +0 -5053
  153. package/dist/manifest-registry-_hxKCS2K-CZdeyN0f.mjs +0 -3512
  154. package/dist/message-channel-Bk_YHfQg-AeNrPPpp.mjs +0 -50
  155. package/dist/message-channel-core-DTA--Gjh-CY4Tkb7N.mjs +0 -29
  156. package/dist/message.config.runtime-K-k4XOyq-DZTmXomP.mjs +0 -2
  157. package/dist/message.gateway.runtime-DqHOHRTQ-DH4ml0YF.mjs +0 -2
  158. package/dist/mistral-CaR4DiLu.mjs +0 -28657
  159. package/dist/model-auth-env-oyg2Hexc-DU_rOUU5.mjs +0 -1306
  160. package/dist/models-config-BmpSQJQF-Gfvh1n3A.mjs +0 -1282
  161. package/dist/models-config.runtime-BsU_22xk.mjs +0 -2
  162. package/dist/multipart-parser-DedmaB5g.mjs +0 -294
  163. package/dist/oauth-DOJeGfcE.mjs +0 -6392
  164. package/dist/openai-BDtIh3Ja.mjs +0 -6693
  165. package/dist/openai-codex-responses-C5EORu31.mjs +0 -664
  166. package/dist/openai-completions-CR_cS6gX.mjs +0 -669
  167. package/dist/openai-responses-oGxwZyuC.mjs +0 -184
  168. package/dist/openai-responses-shared-BixMSDZE.mjs +0 -398
  169. package/dist/paths-D6msg0S1-C2lYuisN.mjs +0 -189
  170. package/dist/paths-D92DjaZ--CTOESW2b.mjs +0 -192
  171. package/dist/pi-model-discovery-Bd0TWzo8-BFsJmeMb.mjs +0 -227
  172. package/dist/pi-model-discovery-runtime-CCCZxkd8.mjs +0 -2
  173. package/dist/pi-tools.before-tool-call.runtime-Bn7uqKie-C5ewk8kK.mjs +0 -399
  174. package/dist/plugin-auto-enable-DdH3n9V8-DsA1isaF.mjs +0 -1456
  175. package/dist/process-scoped-map-B2cWkYET-CXwUZ8CZ.mjs +0 -61
  176. package/dist/provider-discovery.runtime-BPzz1PFj.mjs +0 -58
  177. package/dist/provider-model-compat-CFqcq0it-BDDuBI3A.mjs +0 -118
  178. package/dist/provider-runtime-C8rljsNs-CIT93zoy.mjs +0 -2
  179. package/dist/provider-runtime-CT50mNIX-BwEV6GyO.mjs +0 -573
  180. package/dist/provider-stream-COLujAAo-CbJPDngm.mjs +0 -35449
  181. package/dist/providers.runtime-Ba7tOlq7-CXkhkzU9.mjs +0 -219
  182. package/dist/public-surface-loader-BVl0NQAE-C0piXtsT.mjs +0 -117
  183. package/dist/resolve-C33B7eeu-BNvYTl6k.mjs +0 -1041
  184. package/dist/runtime-Cym-fqI8-DaSDMH-a.mjs +0 -120
  185. package/dist/runtime-channel-state-CohMybAh-hXR6y5Gx.mjs +0 -19
  186. package/dist/runtime-snapshot-C54O1-gI-40cbyi7P.mjs +0 -677
  187. package/dist/runtime-state-IBOIXKOx-Bf9tcLvc.mjs +0 -10
  188. package/dist/runtime-web-tools-fallback.runtime-Ca-qn1mj-BCVImm7a.mjs +0 -39
  189. package/dist/runtime-web-tools-manifest.runtime-BgxQTjmq-Cb4nJkRT.mjs +0 -2
  190. package/dist/runtime-web-tools-public-artifacts.runtime-D9qcoWIX-BrQdXzOQ.mjs +0 -2
  191. package/dist/session-archive.runtime-B52_5vs4-BG-_IwNJ.mjs +0 -2
  192. package/dist/session-key-Cn2QoOyX-CuHbJMgR.mjs +0 -82
  193. package/dist/session-transcript-files.fs-DEeFXruQ-B1PF6nLy.mjs +0 -147
  194. package/dist/src-BgCX0MLG.mjs +0 -813
  195. package/dist/src-DYbqlAqf.mjs +0 -1177
  196. package/dist/subagent-announce-L5WsQatW-CQWI9GMd.mjs +0 -344
  197. package/dist/subagent-announce.registry.runtime-DiqZyeTs-BKuniyi3.mjs +0 -28
  198. package/dist/subagent-registry-steer-runtime-DFgZFC0j-BhBz0roy.mjs +0 -211
  199. package/dist/subagent-system-prompt-C1qnN--K-DpnTFP47.mjs +0 -3061
  200. package/dist/target-parsing-loaded-DKkb6jJY-BMD4CkpS.mjs +0 -1002
  201. package/dist/task-registry-delivery-runtime-Dd1CUkZF-C8U40a3O.mjs +0 -2950
  202. package/dist/task-registry-delivery-runtime-ragbeVx5-CNbFAkjD.mjs +0 -2
  203. package/dist/thinking-Bh-7MqXz-D3woGbO7.mjs +0 -2
  204. package/dist/transcript-E_-ISOkD-DWCfZP2p.mjs +0 -2019
  205. package/dist/transcript.runtime-BqhvZZdl-BPy42vBP.mjs +0 -2
  206. package/dist/transform-messages-DbhIzTxq.mjs +0 -207
  207. package/dist/web-provider-public-artifacts-BlpRwIUS-CGPSV4W2.mjs +0 -295
  208. package/dist/web-search-providers.runtime--0aUtC3b-DyuhC95V.mjs +0 -200
@@ -0,0 +1,16 @@
1
+ function e(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function t(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}let n=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return n=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^r()&15>>e/4).toString(16))};function r(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}const i=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};var a=class extends Error{},o=class e extends a{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`x-request-id`),this.error=n;let a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,a){if(!t||!a)return new c({message:r,cause:i(n)});let o=n?.error;return t===400?new u(t,o,r,a):t===401?new d(t,o,r,a):t===403?new f(t,o,r,a):t===404?new p(t,o,r,a):t===409?new m(t,o,r,a):t===422?new h(t,o,r,a):t===429?new g(t,o,r,a):t>=500?new _(t,o,r,a):new e(t,o,r,a)}},s=class extends o{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},c=class extends o{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},l=class extends c{constructor({message:e}={}){super({message:e??`Request timed out.`})}},u=class extends o{},d=class extends o{},f=class extends o{},p=class extends o{},m=class extends o{},h=class extends o{},g=class extends o{},_=class extends o{},v=class extends a{constructor(){super(`Could not parse response content as the length limit was reached`)}},y=class extends a{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},b=class extends Error{constructor(e){super(e)}};const ee=/^[a-z][a-z0-9+.-]*:/i,te=e=>ee.test(e);let x=e=>(x=Array.isArray,x(e)),S=x;function C(e){return typeof e==`object`?e??{}:{}}function ne(e){if(!e)return!0;for(let t in e)return!1;return!0}function re(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ie(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const ae=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new a(`${e} must be an integer`);if(t<0)throw new a(`${e} must be a positive integer`);return t},oe=e=>{try{return JSON.parse(e)}catch{return}},se=e=>new Promise(t=>setTimeout(t,e)),w=`6.26.0`,ce=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function le(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}const ue=()=>{let e=le();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":w,"X-Stainless-OS":pe(Deno.build.os),"X-Stainless-Arch":fe(Deno.build.arch),"X-Stainless-Runtime":`deno`,"X-Stainless-Runtime-Version":typeof Deno.version==`string`?Deno.version:Deno.version?.deno??`unknown`};if(typeof EdgeRuntime<`u`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":w,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":w,"X-Stainless-OS":pe(globalThis.process.platform??`unknown`),"X-Stainless-Arch":fe(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=de();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":w,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":w,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function de(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}const fe=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,pe=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`);let me;const he=()=>me??=ue();function ge(){if(typeof fetch<`u`)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function _e(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function ve(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return _e({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function ye(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function be(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}const xe=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),Se=`RFC3986`,Ce=e=>String(e),we={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:Ce};let Te=(e,t)=>(Te=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Te(e,t));const T=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),Ee=1024,De=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return`%26%23`+parseInt(e.slice(2),16)+`%3B`});let o=``;for(let e=0;e<a.length;e+=Ee){let t=a.length>=Ee?a.slice(e,e+Ee):a,n=[];for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===`RFC1738`&&(r===40||r===41)){n[n.length]=t.charAt(e);continue}if(r<128){n[n.length]=T[r];continue}if(r<2048){n[n.length]=T[192|r>>6]+T[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=T[224|r>>12]+T[128|r>>6&63]+T[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=T[240|r>>18]+T[128|r>>12&63]+T[128|r>>6&63]+T[128|r&63]}o+=n.join(``)}return o};function Oe(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function ke(e,t){if(x(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}const Ae={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},je=function(e,t){Array.prototype.push.apply(e,x(t)?t:[t])};let Me;const E={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:De,encodeValuesOnly:!1,format:Se,formatter:Ce,indices:!1,serializeDate(e){return(Me??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function Ne(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}const Pe={};function Fe(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){let v=e,y=_,b=0,ee=!1;for(;(y=y.get(Pe))!==void 0&&!ee;){let t=y.get(e);if(b+=1,t!==void 0){if(t===b)throw RangeError(`Cyclic object value`);ee=!0}y.get(Pe)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&x(v)&&(v=ke(v,function(e){return e instanceof Date?f?.(e):e})),v===null){if(a)return c&&!h?c(t,E.encoder,g,`key`,p):t;v=``}if(Ne(v)||Oe(v)){if(c){let e=h?t:c(t,E.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,E.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let te=[];if(v===void 0)return te;let S;if(n===`comma`&&x(v))h&&c&&(v=ke(v,c)),S=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(x(l))S=l;else{let e=Object.keys(v);S=u?e.sort(u):e}let C=s?String(t).replace(/\./g,`%2E`):String(t),ne=r&&x(v)&&v.length===1?C+`[]`:C;if(i&&x(v)&&v.length===0)return ne+`[]`;for(let t=0;t<S.length;++t){let y=S[t],ee=typeof y==`object`&&y.value!==void 0?y.value:v[y];if(o&&ee===null)continue;let C=d&&s?y.replace(/\./g,`%2E`):y,re=x(v)?typeof n==`function`?n(ne,C):ne:ne+(d?`.`+C:`[`+C+`]`);_.set(e,b);let ie=new WeakMap;ie.set(Pe,_),je(te,Fe(ee,re,n,r,i,a,o,s,n===`comma`&&h&&x(v)?null:c,l,u,d,f,p,m,h,g,ie))}return te}function Ie(e=E){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||E.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=Se;if(e.format!==void 0){if(!Te(we,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=we[n],i=E.filter;(typeof e.filter==`function`||x(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in Ae?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:E.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=e.allowDots===void 0?e.encodeDotInKeys?!0:E.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:E.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:E.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:E.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?E.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:E.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:E.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:E.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:E.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:E.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:E.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:E.strictNullHandling}}function Le(e,t={}){let n=e,r=Ie(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):x(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=Ae[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e=0;e<i.length;++e){let t=i[e];r.skipNulls&&n[t]===null||je(o,Fe(n[t],t,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(r.charset===`iso-8859-1`?d+=`utf8=%26%2310003%3B&`:d+=`utf8=%E2%9C%93&`),u.length>0?d+u:``}function Re(e){return Le(e,{arrayFormat:`brackets`})}function ze(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}let Be;function Ve(e){let t;return(Be??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}let He;function Ue(e){let t;return(He??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var D,O,We=class{constructor(){D.set(this,void 0),O.set(this,void 0),e(this,D,new Uint8Array,`f`),e(this,O,null,`f`)}decode(n){if(n==null)return[];let r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?Ve(n):n;e(this,D,ze([t(this,D,`f`),r]),`f`);let i=[],a;for(;(a=Ge(t(this,D,`f`),t(this,O,`f`)))!=null;){if(a.carriage&&t(this,O,`f`)==null){e(this,O,a.index,`f`);continue}if(t(this,O,`f`)!=null&&(a.index!==t(this,O,`f`)+1||a.carriage)){i.push(Ue(t(this,D,`f`).subarray(0,t(this,O,`f`)-1))),e(this,D,t(this,D,`f`).subarray(t(this,O,`f`)),`f`),e(this,O,null,`f`);continue}let n=t(this,O,`f`)===null?a.preceding:a.preceding-1,r=Ue(t(this,D,`f`).subarray(0,n));i.push(r),e(this,D,t(this,D,`f`).subarray(a.index),`f`),e(this,O,null,`f`)}return i}flush(){return t(this,D,`f`).length?this.decode(`
2
+ `):[]}};D=new WeakMap,O=new WeakMap,We.NEWLINE_CHARS=new Set([`
3
+ `,`\r`]),We.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ge(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Ke(e){for(let t=0;t<e.length-1;t++){if(e[t]===10&&e[t+1]===10||e[t]===13&&e[t+1]===13)return t+2;if(e[t]===13&&e[t+1]===10&&t+3<e.length&&e[t+2]===13&&e[t+3]===10)return t+4}return-1}const qe={off:0,error:200,warn:300,info:400,debug:500},Je=(e,t,n)=>{if(e){if(re(qe,e))return e;k(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(qe))}`)}};function Ye(){}function Xe(e,t,n){return!t||qe[e]>qe[n]?Ye:t[e].bind(t)}const Ze={error:Ye,warn:Ye,info:Ye,debug:Ye};let Qe=new WeakMap;function k(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return Ze;let r=Qe.get(t);if(r&&r[0]===n)return r[1];let i={error:Xe(`error`,t,n),warn:Xe(`warn`,t,n),info:Xe(`info`,t,n),debug:Xe(`debug`,t,n)};return Qe.set(t,[n,i]),i}const A=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`authorization`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);var $e,et=class n{constructor(t,n,r){this.iterator=t,$e.set(this,void 0),this.controller=n,e(this,$e,r,`f`)}static fromSSEResponse(e,t,i,s){let c=!1,l=i?k(i):console;async function*u(){if(c)throw new a("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");c=!0;let n=!1;try{for await(let r of tt(e,t))if(!n){if(r.data.startsWith(`[DONE]`)){n=!0;continue}if(r.event===null||!r.event.startsWith(`thread.`)){let t;try{t=JSON.parse(r.data)}catch(e){throw l.error(`Could not parse message into JSON:`,r.data),l.error(`From chunk:`,r.raw),e}if(t&&t.error)throw new o(void 0,t.error,void 0,e.headers);yield s?{event:r.event,data:t}:t}else{let e;try{e=JSON.parse(r.data)}catch(e){throw console.error(`Could not parse message into JSON:`,r.data),console.error(`From chunk:`,r.raw),e}if(r.event==`error`)throw new o(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}}n=!0}catch(e){if(r(e))return;throw e}finally{n||t.abort()}}return new n(u,t,i)}static fromReadableStream(e,t,i){let o=!1;async function*s(){let t=new We,n=ye(e);for await(let e of n)for(let n of t.decode(e))yield n;for(let e of t.flush())yield e}async function*c(){if(o)throw new a("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let e=!1;try{for await(let t of s())e||t&&(yield JSON.parse(t));e=!0}catch(e){if(r(e))return;throw e}finally{e||t.abort()}}return new n(c,t,i)}[($e=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],i=this.iterator(),a=t=>({next:()=>{if(t.length===0){let t=i.next();e.push(t),r.push(t)}return t.shift()}});return[new n(()=>a(e),this.controller,t(this,$e,`f`)),new n(()=>a(r),this.controller,t(this,$e,`f`))]}toReadableStream(){let e=this,t;return _e({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=Ve(JSON.stringify(n)+`
4
+ `);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*tt(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new a(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new a(`Attempted to iterate over a response with no body`);let n=new rt,r=new We,i=ye(e.body);for await(let e of nt(i))for(let t of r.decode(e)){let e=n.decode(t);e&&(yield e)}for(let e of r.flush()){let t=n.decode(e);t&&(yield t)}}async function*nt(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let e=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?Ve(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=Ke(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var rt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith(`\r`)&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join(`
5
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=it(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function it(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function at(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return k(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData):et.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:ot(await n.json(),n):await n.text()})();return k(e).debug(`[${r}] response parsed`,A({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function ot(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,`_request_id`,{value:t.headers.get(`x-request-id`),enumerable:!1})}var st,ct=class n extends Promise{constructor(t,n,r=at){super(e=>{e(null)}),this.responsePromise=n,this.parseResponse=r,st.set(this,void 0),e(this,st,t,`f`)}_thenUnwrap(e){return new n(t(this,st,`f`),this.responsePromise,async(t,n)=>ot(e(await this.parseResponse(t,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`x-request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(t(this,st,`f`),e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};st=new WeakMap;var lt,ut=class{constructor(t,n,r,i){lt.set(this,void 0),e(this,lt,t,`f`),this.options=i,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new a("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await t(this,lt,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(lt=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},dt=class extends ct{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await at(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},ft=class extends ut{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},j=class extends ut{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...C(this.options.query),after:t}}:null}},pt=class extends ut{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||``}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...C(this.options.query),after:e}}:null}};const mt=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function ht(e,t,n){return mt(),new File(e,t??`unknown_file`,n)}function gt(e){return(typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``).split(/[\\/]/).pop()||void 0}const _t=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,vt=async(e,t)=>wt(e.body)?{...e,body:await xt(e.body,t)}:e,M=async(e,t)=>({...e,body:await xt(e.body,t)}),yt=new WeakMap;function bt(e){let t=typeof e==`function`?e:e.fetch,n=yt.get(t);if(n)return n;let r=(async()=>{try{let e=`Response`in t?t.Response:(await t(`data:,`)).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return yt.set(t,r),r}const xt=async(e,t)=>{if(!await bt(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let n=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>Tt(n,e,t))),n},St=e=>e instanceof Blob&&`name`in e,Ct=e=>typeof e==`object`&&!!e&&(e instanceof Response||_t(e)||St(e)),wt=e=>{if(Ct(e))return!0;if(Array.isArray(e))return e.some(wt);if(e&&typeof e==`object`){for(let t in e)if(wt(e[t]))return!0}return!1},Tt=async(e,t,n)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response)e.append(t,ht([await n.blob()],gt(n)));else if(_t(n))e.append(t,ht([await new Response(ve(n)).blob()],gt(n)));else if(St(n))e.append(t,n,gt(n));else if(Array.isArray(n))await Promise.all(n.map(n=>Tt(e,t+`[]`,n)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,r])=>Tt(e,`${t}[${n}]`,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},Et=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,Dt=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&Et(e),Ot=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function kt(e,t,n){if(mt(),e=await e,Dt(e))return e instanceof File?e:ht([await e.arrayBuffer()],e.name);if(Ot(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),ht(await At(r),t,n)}let r=await At(e);if(t||=gt(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return ht(r,t,n)}async function At(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Et(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(_t(e))for await(let n of e)t.push(...await At(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${jt(e)}`)}return t}function jt(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var N=class{constructor(e){this._client=e}};function Mt(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Nt=Object.freeze(Object.create(null)),P=((e=Mt)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],o=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??Nt)??Nt)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),s=o.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=c.exec(s))!==null;)i.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new a(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
6
+ `)}\n${o}\n${t}`)}return o})(Mt);var Pt=class extends N{list(e,t={},n){return this._client.getAPIList(P`/chat/completions/${e}/messages`,j,{query:t,...n})}};function Ft(e){return e!==void 0&&`function`in e&&e.function!==void 0}function It(e){return e?.$brand===`auto-parseable-response-format`}function Lt(e){return e?.$brand===`auto-parseable-tool`}function Rt(e,t){return!t||!Ut(t)?{...e,choices:e.choices.map(e=>(Wt(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:zt(e,t)}function zt(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new v;if(e.finish_reason===`content_filter`)throw new y;return Wt(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>Vt(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?Bt(t,e.message.content):null}}});return{...e,choices:n}}function Bt(e,t){return e.response_format?.type===`json_schema`&&e.response_format?.type===`json_schema`?`$parseRaw`in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function Vt(e,t){let n=e.tools?.find(e=>Ft(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:Lt(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}function Ht(e,t){if(!e||!(`tools`in e)||!e.tools)return!1;let n=e.tools?.find(e=>Ft(e)&&e.function?.name===t.function.name);return Ft(n)&&(Lt(n)||n?.function.strict||!1)}function Ut(e){return It(e.response_format)?!0:e.tools?.some(e=>Lt(e)||e.type===`function`&&e.function.strict===!0)??!1}function Wt(e){for(let t of e||[])if(t.type!==`function`)throw new a(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function Gt(e){for(let t of e??[]){if(t.type!==`function`)throw new a(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new a(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const Kt=e=>e?.role===`assistant`,qt=e=>e?.role===`tool`;var Jt,Yt,Xt,Zt,Qt,$t,en,F,tn,nn,rn,an,on,sn=class{constructor(){Jt.add(this),this.controller=new AbortController,Yt.set(this,void 0),Xt.set(this,()=>{}),Zt.set(this,()=>{}),Qt.set(this,void 0),$t.set(this,()=>{}),en.set(this,()=>{}),F.set(this,{}),tn.set(this,!1),nn.set(this,!1),rn.set(this,!1),an.set(this,!1),e(this,Yt,new Promise((t,n)=>{e(this,Xt,t,`f`),e(this,Zt,n,`f`)}),`f`),e(this,Qt,new Promise((t,n)=>{e(this,$t,t,`f`),e(this,en,n,`f`)}),`f`),t(this,Yt,`f`).catch(()=>{}),t(this,Qt,`f`).catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit(`end`)},t(this,Jt,`m`,on).bind(this))},0)}_connected(){this.ended||(t(this,Xt,`f`).call(this),this._emit(`connect`))}get ended(){return t(this,tn,`f`)}get errored(){return t(this,nn,`f`)}get aborted(){return t(this,rn,`f`)}abort(){this.controller.abort()}on(e,n){return(t(this,F,`f`)[e]||(t(this,F,`f`)[e]=[])).push({listener:n}),this}off(e,n){let r=t(this,F,`f`)[e];if(!r)return this;let i=r.findIndex(e=>e.listener===n);return i>=0&&r.splice(i,1),this}once(e,n){return(t(this,F,`f`)[e]||(t(this,F,`f`)[e]=[])).push({listener:n,once:!0}),this}emitted(t){return new Promise((n,r)=>{e(this,an,!0,`f`),t!==`error`&&this.once(`error`,r),this.once(t,n)})}async done(){e(this,an,!0,`f`),await t(this,Qt,`f`)}_emit(n,...r){if(t(this,tn,`f`))return;n===`end`&&(e(this,tn,!0,`f`),t(this,$t,`f`).call(this));let i=t(this,F,`f`)[n];if(i&&(t(this,F,`f`)[n]=i.filter(e=>!e.once),i.forEach(({listener:e})=>e(...r))),n===`abort`){let e=r[0];!t(this,an,`f`)&&!i?.length&&Promise.reject(e),t(this,Zt,`f`).call(this,e),t(this,en,`f`).call(this,e),this._emit(`end`);return}if(n===`error`){let e=r[0];!t(this,an,`f`)&&!i?.length&&Promise.reject(e),t(this,Zt,`f`).call(this,e),t(this,en,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){}};Yt=new WeakMap,Xt=new WeakMap,Zt=new WeakMap,Qt=new WeakMap,$t=new WeakMap,en=new WeakMap,F=new WeakMap,tn=new WeakMap,nn=new WeakMap,rn=new WeakMap,an=new WeakMap,Jt=new WeakSet,on=function(t){if(e(this,nn,!0,`f`),t instanceof Error&&t.name===`AbortError`&&(t=new s),t instanceof s)return e(this,rn,!0,`f`),this._emit(`abort`,t);if(t instanceof a)return this._emit(`error`,t);if(t instanceof Error){let e=new a(t.message);return e.cause=t,this._emit(`error`,e)}return this._emit(`error`,new a(String(t)))};function cn(e){return typeof e.parse==`function`}var I,ln,un,dn,fn,pn,mn,hn,gn=class extends sn{constructor(){super(...arguments),I.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit(`chatCompletion`,e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if(`content`in e||(e.content=null),this.messages.push(e),t){if(this._emit(`message`,e),qt(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(Kt(e)&&e.tool_calls)for(let t of e.tool_calls)t.type===`function`&&this._emit(`functionToolCall`,t.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new a(`stream ended without producing a ChatCompletion`);return e}async finalContent(){return await this.done(),t(this,I,`m`,ln).call(this)}async finalMessage(){return await this.done(),t(this,I,`m`,un).call(this)}async finalFunctionToolCall(){return await this.done(),t(this,I,`m`,dn).call(this)}async finalFunctionToolCallResult(){return await this.done(),t(this,I,`m`,fn).call(this)}async totalUsage(){return await this.done(),t(this,I,`m`,pn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let n=t(this,I,`m`,un).call(this);n&&this._emit(`finalMessage`,n);let r=t(this,I,`m`,ln).call(this);r&&this._emit(`finalContent`,r);let i=t(this,I,`m`,dn).call(this);i&&this._emit(`finalFunctionToolCall`,i);let a=t(this,I,`m`,fn).call(this);a!=null&&this._emit(`finalFunctionToolCallResult`,a),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,t(this,I,`m`,pn).call(this))}async _createChatCompletion(e,n,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort())),t(this,I,`m`,mn).call(this,n);let a=await e.chat.completions.create({...n,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(zt(a,n))}async _runChatCompletion(e,t,n){for(let e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,n,r){let i=`tool`,{tool_choice:o=`auto`,stream:s,...c}=n,l=typeof o!=`string`&&o.type===`function`&&o?.function?.name,{maxChatCompletions:u=10}=r||{},d=n.tools.map(e=>{if(Lt(e)){if(!e.$callback)throw new a("Tool given to `.runTools()` that does not have an associated function");return{type:`function`,function:{function:e.$callback,name:e.function.name,description:e.function.description||``,parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),f={};for(let e of d)e.type===`function`&&(f[e.function.name||e.function.function.name]=e.function);let p=`tools`in n?d.map(e=>e.type===`function`?{type:`function`,function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(let e of n.messages)this._addMessage(e,!1);for(let n=0;n<u;++n){let n=(await this._createChatCompletion(e,{...c,tool_choice:o,tools:p,messages:[...this.messages]},r)).choices[0]?.message;if(!n)throw new a(`missing message in ChatCompletion response`);if(!n.tool_calls?.length)return;for(let e of n.tool_calls){if(e.type!==`function`)continue;let n=e.id,{name:r,arguments:a}=e.function,o=f[r];if(!o){let e=`Invalid tool_call: ${JSON.stringify(r)}. Available options are: ${Object.keys(f).map(e=>JSON.stringify(e)).join(`, `)}. Please try again`;this._addMessage({role:i,tool_call_id:n,content:e});continue}else if(l&&l!==r){let e=`Invalid tool_call: ${JSON.stringify(r)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:i,tool_call_id:n,content:e});continue}let s;try{s=cn(o)?await o.parse(a):a}catch(e){let t=e instanceof Error?e.message:String(e);this._addMessage({role:i,tool_call_id:n,content:t});continue}let c=await o.function(s,this),u=t(this,I,`m`,hn).call(this,c);if(this._addMessage({role:i,tool_call_id:n,content:u}),l)return}}}};I=new WeakSet,ln=function(){return t(this,I,`m`,un).call(this).content??null},un=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(Kt(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new a(`stream ended without producing a ChatCompletionMessage with role=assistant`)},dn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Kt(t)&&t?.tool_calls?.length)return t.tool_calls.filter(e=>e.type===`function`).at(-1)?.function}},fn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(qt(t)&&t.content!=null&&typeof t.content==`string`&&this.messages.some(e=>e.role===`assistant`&&e.tool_calls?.some(e=>e.type===`function`&&e.id===t.tool_call_id)))return t.content}},pn=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},mn=function(e){if(e.n!=null&&e.n>1)throw new a(`ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.`)},hn=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)};var _n=class e extends gn{static runTools(t,n,r){let i=new e,a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,a)),i}_addMessage(e,t=!0){super._addMessage(e,t),Kt(e)&&e.content&&this._emit(`content`,e.content)}};const L={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511};var vn=class extends Error{},yn=class extends Error{};function bn(e,t=L.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return xn(e.trim(),t)}const xn=(e,t)=>{let n=e.length,r=0,i=e=>{throw new vn(`${e} at position ${r}`)},a=e=>{throw new yn(`${e} at position ${r}`)},o=()=>(d(),r>=n&&i(`Unexpected end of input`),e[r]===`"`?s():e[r]===`{`?c():e[r]===`[`?l():e.substring(r,r+4)===`null`||L.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||L.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||L.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||L.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||L.MINUS_INFINITY&t&&1<n-r&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||L.NAN&t&&n-r<3&&`NaN`.startsWith(e.substring(r))?(r+=3,NaN):u()),s=()=>{let o=r,s=!1;for(r++;r<n&&(e[r]!==`"`||s&&e[r-1]===`\\`);)s=e[r]===`\\`?!s:!1,r++;if(e.charAt(r)==`"`)try{return JSON.parse(e.substring(o,++r-Number(s)))}catch(e){a(String(e))}else if(L.STR&t)try{return JSON.parse(e.substring(o,r-Number(s))+`"`)}catch{return JSON.parse(e.substring(o,e.lastIndexOf(`\\`))+`"`)}i(`Unterminated string literal`)},c=()=>{r++,d();let a={};try{for(;e[r]!==`}`;){if(d(),r>=n&&L.OBJ&t)return a;let i=s();d(),r++;try{let e=o();Object.defineProperty(a,i,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(L.OBJ&t)return a;throw e}d(),e[r]===`,`&&r++}}catch{if(L.OBJ&t)return a;i(`Expected '}' at end of object`)}return r++,a},l=()=>{r++;let n=[];try{for(;e[r]!==`]`;)n.push(o()),d(),e[r]===`,`&&r++}catch{if(L.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},u=()=>{if(r===0){e===`-`&&L.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(L.NUM&t)try{return e[e.length-1]===`.`?JSON.parse(e.substring(0,e.lastIndexOf(`.`))):JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}a(String(n))}}let o=r;for(e[r]===`-`&&r++;e[r]&&!`,]}`.includes(e[r]);)r++;r==n&&!(L.NUM&t)&&i(`Unterminated number literal`);try{return JSON.parse(e.substring(o,r))}catch{e.substring(o,r)===`-`&&L.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e.substring(o,e.lastIndexOf(`e`)))}catch(e){a(String(e))}}},d=()=>{for(;r<n&&`
7
+ \r `.includes(e[r]);)r++};return o()},Sn=e=>bn(e,L.ALL^L.NUM);var R,z,B,V,Cn,wn,Tn,En,Dn,On,kn,An,jn=class n extends gn{constructor(t){super(),R.add(this),z.set(this,void 0),B.set(this,void 0),V.set(this,void 0),e(this,z,t,`f`),e(this,B,[],`f`)}get currentChatCompletionSnapshot(){return t(this,V,`f`)}static fromReadableStream(e){let t=new n(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let i=new n(t);return i._run(()=>i._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createChatCompletion(e,n,r){super._createChatCompletion;let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort())),t(this,R,`m`,Cn).call(this);let a=await e.chat.completions.create({...n,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let e of a)t(this,R,`m`,Tn).call(this,e);if(a.controller.signal?.aborted)throw new s;return this._addChatCompletion(t(this,R,`m`,On).call(this))}async _fromReadableStream(e,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort())),t(this,R,`m`,Cn).call(this),this._connected();let i=et.fromReadableStream(e,this.controller),a;for await(let e of i)a&&a!==e.id&&this._addChatCompletion(t(this,R,`m`,On).call(this)),t(this,R,`m`,Tn).call(this,e),a=e.id;if(i.controller.signal?.aborted)throw new s;return this._addChatCompletion(t(this,R,`m`,On).call(this))}[(z=new WeakMap,B=new WeakMap,V=new WeakMap,R=new WeakSet,Cn=function(){this.ended||e(this,V,void 0,`f`)},wn=function(e){let n=t(this,B,`f`)[e.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},t(this,B,`f`)[e.index]=n,n)},Tn=function(e){if(this.ended)return;let n=t(this,R,`m`,An).call(this,e);this._emit(`chunk`,e,n);for(let r of e.choices){let e=n.choices[r.index];r.delta.content!=null&&e.message?.role===`assistant`&&e.message?.content&&(this._emit(`content`,r.delta.content,e.message.content),this._emit(`content.delta`,{delta:r.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),r.delta.refusal!=null&&e.message?.role===`assistant`&&e.message?.refusal&&this._emit(`refusal.delta`,{delta:r.delta.refusal,snapshot:e.message.refusal}),r.logprobs?.content!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.content.delta`,{content:r.logprobs?.content,snapshot:e.logprobs?.content??[]}),r.logprobs?.refusal!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.refusal.delta`,{refusal:r.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});let i=t(this,R,`m`,wn).call(this,e);e.finish_reason&&(t(this,R,`m`,Dn).call(this,e),i.current_tool_call_index!=null&&t(this,R,`m`,En).call(this,e,i.current_tool_call_index));for(let n of r.delta.tool_calls??[])i.current_tool_call_index!==n.index&&(t(this,R,`m`,Dn).call(this,e),i.current_tool_call_index!=null&&t(this,R,`m`,En).call(this,e,i.current_tool_call_index)),i.current_tool_call_index=n.index;for(let t of r.delta.tool_calls??[]){let n=e.message.tool_calls?.[t.index];n?.type&&(n?.type===`function`?this._emit(`tool_calls.function.arguments.delta`,{name:n.function?.name,index:t.index,arguments:n.function.arguments,parsed_arguments:n.function.parsed_arguments,arguments_delta:t.function?.arguments??``}):n?.type)}}},En=function(e,n){if(t(this,R,`m`,wn).call(this,e).done_tool_calls.has(n))return;let r=e.message.tool_calls?.[n];if(!r)throw Error(`no tool call snapshot`);if(!r.type)throw Error("tool call snapshot missing `type`");if(r.type===`function`){let e=t(this,z,`f`)?.tools?.find(e=>Ft(e)&&e.function.name===r.function.name);this._emit(`tool_calls.function.arguments.done`,{name:r.function.name,index:n,arguments:r.function.arguments,parsed_arguments:Lt(e)?e.$parseRaw(r.function.arguments):e?.function.strict?JSON.parse(r.function.arguments):null})}else r.type},Dn=function(e){let n=t(this,R,`m`,wn).call(this,e);if(e.message.content&&!n.content_done){n.content_done=!0;let r=t(this,R,`m`,kn).call(this);this._emit(`content.done`,{content:e.message.content,parsed:r?r.$parseRaw(e.message.content):null})}e.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit(`refusal.done`,{refusal:e.message.refusal})),e.logprobs?.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit(`logprobs.content.done`,{content:e.logprobs.content})),e.logprobs?.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit(`logprobs.refusal.done`,{refusal:e.logprobs.refusal}))},On=function(){if(this.ended)throw new a(`stream has ended, this shouldn't happen`);let n=t(this,V,`f`);if(!n)throw new a(`request ended without sending any chunks`);return e(this,V,void 0,`f`),e(this,B,[],`f`),Mn(n,t(this,z,`f`))},kn=function(){let e=t(this,z,`f`)?.response_format;return It(e)?e:null},An=function(n){var r,i,a,o;let s=t(this,V,`f`),{choices:c,...l}=n;s?Object.assign(s,l):s=e(this,V,{...l,choices:[]},`f`);for(let{delta:e,finish_reason:c,index:l,logprobs:u=null,...d}of n.choices){let n=s.choices[l];if(n||=s.choices[l]={finish_reason:c,index:l,message:{},logprobs:u,...d},u)if(!n.logprobs)n.logprobs=Object.assign({},u);else{let{content:e,refusal:t,...a}=u;Object.assign(n.logprobs,a),e&&((r=n.logprobs).content??(r.content=[]),n.logprobs.content.push(...e)),t&&((i=n.logprobs).refusal??(i.refusal=[]),n.logprobs.refusal.push(...t))}if(c&&(n.finish_reason=c,t(this,z,`f`)&&Ut(t(this,z,`f`)))){if(c===`length`)throw new v;if(c===`content_filter`)throw new y}if(Object.assign(n,d),!e)continue;let{content:f,refusal:p,function_call:m,role:h,tool_calls:g,..._}=e;if(Object.assign(n.message,_),p&&(n.message.refusal=(n.message.refusal||``)+p),h&&(n.message.role=h),m&&(n.message.function_call?(m.name&&(n.message.function_call.name=m.name),m.arguments&&((a=n.message.function_call).arguments??(a.arguments=``),n.message.function_call.arguments+=m.arguments)):n.message.function_call=m),f&&(n.message.content=(n.message.content||``)+f,!n.message.refusal&&t(this,R,`m`,kn).call(this)&&(n.message.parsed=Sn(n.message.content))),g){n.message.tool_calls||(n.message.tool_calls=[]);for(let{index:e,id:r,type:i,function:a,...s}of g){let c=(o=n.message.tool_calls)[e]??(o[e]={});Object.assign(c,s),r&&(c.id=r),i&&(c.type=i),a&&(c.function??={name:a.name??``,arguments:``}),a?.name&&(c.function.name=a.name),a?.arguments&&(c.function.arguments+=a.arguments,Ht(t(this,z,`f`),c)&&(c.function.parsed_arguments=Sn(c.function.arguments)))}}}return s},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`chunk`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new et(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Mn(e,t){let{id:n,choices:r,created:i,model:o,system_fingerprint:s,...c}=e;return Rt({...c,id:n,choices:r.map(({message:t,finish_reason:n,index:r,logprobs:i,...o})=>{if(!n)throw new a(`missing finish_reason for choice ${r}`);let{content:s=null,function_call:c,tool_calls:l,...u}=t,d=t.role;if(!d)throw new a(`missing role for choice ${r}`);if(c){let{arguments:e,name:l}=c;if(e==null)throw new a(`missing function_call.arguments for choice ${r}`);if(!l)throw new a(`missing function_call.name for choice ${r}`);return{...o,message:{content:s,function_call:{arguments:e,name:l},role:d,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}return l?{...o,index:r,finish_reason:n,logprobs:i,message:{...u,role:d,content:s,refusal:t.refusal??null,tool_calls:l.map((t,n)=>{let{function:i,type:o,id:s,...c}=t,{arguments:l,name:u,...d}=i||{};if(s==null)throw new a(`missing choices[${r}].tool_calls[${n}].id\n${Nn(e)}`);if(o==null)throw new a(`missing choices[${r}].tool_calls[${n}].type\n${Nn(e)}`);if(u==null)throw new a(`missing choices[${r}].tool_calls[${n}].function.name\n${Nn(e)}`);if(l==null)throw new a(`missing choices[${r}].tool_calls[${n}].function.arguments\n${Nn(e)}`);return{...c,id:s,type:o,function:{...d,name:u,arguments:l}}})}}:{...o,message:{...u,content:s,role:d,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}),created:i,model:o,object:`chat.completion`,...s?{system_fingerprint:s}:{}},t)}function Nn(e){return JSON.stringify(e)}var Pn=class e extends jn{static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static runTools(t,n,r){let i=new e(n),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,a)),i}},Fn=class extends N{constructor(){super(...arguments),this.messages=new Pt(this._client)}create(e,t){return this._client.post(`/chat/completions`,{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(P`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(P`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList(`/chat/completions`,j,{query:e,...t})}delete(e,t){return this._client.delete(P`/chat/completions/${e}`,t)}parse(e,t){return Gt(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":`chat.completions.parse`}})._thenUnwrap(t=>zt(t,e))}runTools(e,t){return e.stream?Pn.runTools(this._client,e,t):_n.runTools(this._client,e,t)}stream(e,t){return jn.createChatCompletion(this._client,e,t)}};Fn.Messages=Pt;var In=class extends N{constructor(){super(...arguments),this.completions=new Fn(this._client)}};In.Completions=Fn;const Ln=Symbol(`brand.privateNullableHeaders`);function*Rn(e){if(!e)return;if(Ln in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():S(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=S(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}const H=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of Rn(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[Ln]:!0,values:t,nulls:n}};var zn=class extends N{create(e,t){return this._client.post(`/audio/speech`,{body:e,...t,headers:H([{Accept:`application/octet-stream`},t?.headers]),__binaryResponse:!0})}},Bn=class extends N{create(e,t){return this._client.post(`/audio/transcriptions`,M({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}},Vn=class extends N{create(e,t){return this._client.post(`/audio/translations`,M({body:e,...t,__metadata:{model:e.model}},this._client))}},Hn=class extends N{constructor(){super(...arguments),this.transcriptions=new Bn(this._client),this.translations=new Vn(this._client),this.speech=new zn(this._client)}};Hn.Transcriptions=Bn,Hn.Translations=Vn,Hn.Speech=zn;var Un=class extends N{create(e,t){return this._client.post(`/batches`,{body:e,...t})}retrieve(e,t){return this._client.get(P`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList(`/batches`,j,{query:e,...t})}cancel(e,t){return this._client.post(P`/batches/${e}/cancel`,t)}},Wn=class extends N{create(e,t){return this._client.post(`/assistants`,{body:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(P`/assistants/${e}`,{...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(P`/assistants/${e}`,{body:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e={},t){return this._client.getAPIList(`/assistants`,j,{query:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}delete(e,t){return this._client.delete(P`/assistants/${e}`,{...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},Gn=class extends N{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},Kn=class extends N{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},qn=class extends N{constructor(){super(...arguments),this.sessions=new Gn(this._client),this.transcriptionSessions=new Kn(this._client)}};qn.Sessions=Gn,qn.TranscriptionSessions=Kn;var Jn=class extends N{create(e,t){return this._client.post(`/chatkit/sessions`,{body:e,...t,headers:H([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}cancel(e,t){return this._client.post(P`/chatkit/sessions/${e}/cancel`,{...t,headers:H([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}},Yn=class extends N{retrieve(e,t){return this._client.get(P`/chatkit/threads/${e}`,{...t,headers:H([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}list(e={},t){return this._client.getAPIList(`/chatkit/threads`,pt,{query:e,...t,headers:H([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}delete(e,t){return this._client.delete(P`/chatkit/threads/${e}`,{...t,headers:H([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}listItems(e,t={},n){return this._client.getAPIList(P`/chatkit/threads/${e}/items`,pt,{query:t,...n,headers:H([{"OpenAI-Beta":`chatkit_beta=v1`},n?.headers])})}},Xn=class extends N{constructor(){super(...arguments),this.sessions=new Jn(this._client),this.threads=new Yn(this._client)}};Xn.Sessions=Jn,Xn.Threads=Yn;var Zn=class extends N{create(e,t,n){return this._client.post(P`/threads/${e}/messages`,{body:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(P`/threads/${r}/messages/${e}`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(P`/threads/${r}/messages/${e}`,{body:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(P`/threads/${e}/messages`,j,{query:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t,n){let{thread_id:r}=t;return this._client.delete(P`/threads/${r}/messages/${e}`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}},Qn=class extends N{retrieve(e,t,n){let{thread_id:r,run_id:i,...a}=t;return this._client.get(P`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t,n){let{thread_id:r,...i}=t;return this._client.getAPIList(P`/threads/${r}/runs/${e}/steps`,j,{query:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}};const $n=e=>{if(typeof Buffer<`u`){let t=Buffer.from(e,`base64`);return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return Array.from(new Float32Array(r.buffer))}},U=e=>{if(globalThis.process!==void 0)return globalThis.process.env?.[e]?.trim()??void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()};var W,G,er,K,tr,q,J,nr,Y,rr,X,ir,ar,or,sr,cr,lr,ur,dr,fr,pr,mr,hr,gr=class extends sn{constructor(){super(...arguments),W.add(this),er.set(this,[]),K.set(this,{}),tr.set(this,{}),q.set(this,void 0),J.set(this,void 0),nr.set(this,void 0),Y.set(this,void 0),rr.set(this,void 0),X.set(this,void 0),ir.set(this,void 0),ar.set(this,void 0),or.set(this,void 0)}[(er=new WeakMap,K=new WeakMap,tr=new WeakMap,q=new WeakMap,J=new WeakMap,nr=new WeakMap,Y=new WeakMap,rr=new WeakMap,X=new WeakMap,ir=new WeakMap,ar=new WeakMap,or=new WeakMap,W=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new G;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort())),this._connected();let i=et.fromReadableStream(e,this.controller);for await(let e of i)t(this,W,`m`,sr).call(this,e);if(i.controller.signal?.aborted)throw new s;return this._addRun(t(this,W,`m`,cr).call(this))}toReadableStream(){return new et(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r){let i=new G;return i._run(()=>i._runToolAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createToolAssistantStream(e,n,r,i){let a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener(`abort`,()=>this.controller.abort()));let o={...r,stream:!0},c=await e.submitToolOutputs(n,o,{...i,signal:this.controller.signal});this._connected();for await(let e of c)t(this,W,`m`,sr).call(this,e);if(c.controller.signal?.aborted)throw new s;return this._addRun(t(this,W,`m`,cr).call(this))}static createThreadAssistantStream(e,t,n){let r=new G;return r._run(()=>r._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":`stream`}})),r}static createAssistantStream(e,t,n,r){let i=new G;return i._run(()=>i._runAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}currentEvent(){return t(this,ir,`f`)}currentRun(){return t(this,ar,`f`)}currentMessageSnapshot(){return t(this,q,`f`)}currentRunStepSnapshot(){return t(this,or,`f`)}async finalRunSteps(){return await this.done(),Object.values(t(this,K,`f`))}async finalMessages(){return await this.done(),Object.values(t(this,tr,`f`))}async finalRun(){if(await this.done(),!t(this,J,`f`))throw Error(`Final run was not received.`);return t(this,J,`f`)}async _createThreadAssistantStream(e,n,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort()));let a={...n,stream:!0},o=await e.createAndRun(a,{...r,signal:this.controller.signal});this._connected();for await(let e of o)t(this,W,`m`,sr).call(this,e);if(o.controller.signal?.aborted)throw new s;return this._addRun(t(this,W,`m`,cr).call(this))}async _createAssistantStream(e,n,r,i){let a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener(`abort`,()=>this.controller.abort()));let o={...r,stream:!0},c=await e.create(n,o,{...i,signal:this.controller.signal});this._connected();for await(let e of c)t(this,W,`m`,sr).call(this,e);if(c.controller.signal?.aborted)throw new s;return this._addRun(t(this,W,`m`,cr).call(this))}static accumulateDelta(e,t){for(let[n,r]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=r;continue}let t=e[n];if(t==null){e[n]=r;continue}if(n===`index`||n===`type`){e[n]=r;continue}if(typeof t==`string`&&typeof r==`string`)t+=r;else if(typeof t==`number`&&typeof r==`number`)t+=r;else if(ie(t)&&ie(r))t=this.accumulateDelta(t,r);else if(Array.isArray(t)&&Array.isArray(r)){if(t.every(e=>typeof e==`string`||typeof e==`number`)){t.push(...r);continue}for(let e of r){if(!ie(e))throw Error(`Expected array delta entry to be an object but got: ${e}`);let n=e.index;if(n==null)throw console.error(e),Error("Expected array delta entry to have an `index` property");if(typeof n!=`number`)throw Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);let r=t[n];r==null?t.push(e):t[n]=this.accumulateDelta(r,e)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${r}, accValue: ${t}`);e[n]=t}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,r){return await this._createAssistantStream(t,e,n,r)}async _runToolAssistantStream(e,t,n,r){return await this._createToolAssistantStream(t,e,n,r)}};G=gr,sr=function(n){if(!this.ended)switch(e(this,ir,n,`f`),t(this,W,`m`,dr).call(this,n),n.event){case`thread.created`:break;case`thread.run.created`:case`thread.run.queued`:case`thread.run.in_progress`:case`thread.run.requires_action`:case`thread.run.completed`:case`thread.run.incomplete`:case`thread.run.failed`:case`thread.run.cancelling`:case`thread.run.cancelled`:case`thread.run.expired`:t(this,W,`m`,hr).call(this,n);break;case`thread.run.step.created`:case`thread.run.step.in_progress`:case`thread.run.step.delta`:case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:t(this,W,`m`,ur).call(this,n);break;case`thread.message.created`:case`thread.message.in_progress`:case`thread.message.delta`:case`thread.message.completed`:case`thread.message.incomplete`:t(this,W,`m`,lr).call(this,n);break;case`error`:throw Error(`Encountered an error event in event processing - errors should be processed earlier`);default:}},cr=function(){if(this.ended)throw new a(`stream has ended, this shouldn't happen`);if(!t(this,J,`f`))throw Error(`Final run has not been received`);return t(this,J,`f`)},lr=function(n){let[r,i]=t(this,W,`m`,pr).call(this,n,t(this,q,`f`));e(this,q,r,`f`),t(this,tr,`f`)[r.id]=r;for(let e of i){let t=r.content[e.index];t?.type==`text`&&this._emit(`textCreated`,t.text)}switch(n.event){case`thread.message.created`:this._emit(`messageCreated`,n.data);break;case`thread.message.in_progress`:break;case`thread.message.delta`:if(this._emit(`messageDelta`,n.data.delta,r),n.data.delta.content)for(let i of n.data.delta.content){if(i.type==`text`&&i.text){let e=i.text,t=r.content[i.index];if(t&&t.type==`text`)this._emit(`textDelta`,e,t.text);else throw Error(`The snapshot associated with this text delta is not text or missing`)}if(i.index!=t(this,nr,`f`)){if(t(this,Y,`f`))switch(t(this,Y,`f`).type){case`text`:this._emit(`textDone`,t(this,Y,`f`).text,t(this,q,`f`));break;case`image_file`:this._emit(`imageFileDone`,t(this,Y,`f`).image_file,t(this,q,`f`));break}e(this,nr,i.index,`f`)}e(this,Y,r.content[i.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(t(this,nr,`f`)!==void 0){let e=n.data.content[t(this,nr,`f`)];if(e)switch(e.type){case`image_file`:this._emit(`imageFileDone`,e.image_file,t(this,q,`f`));break;case`text`:this._emit(`textDone`,e.text,t(this,q,`f`));break}}t(this,q,`f`)&&this._emit(`messageDone`,n.data),e(this,q,void 0,`f`)}},ur=function(n){let r=t(this,W,`m`,fr).call(this,n);switch(e(this,or,r,`f`),n.event){case`thread.run.step.created`:this._emit(`runStepCreated`,n.data);break;case`thread.run.step.delta`:let i=n.data.delta;if(i.step_details&&i.step_details.type==`tool_calls`&&i.step_details.tool_calls&&r.step_details.type==`tool_calls`)for(let n of i.step_details.tool_calls)n.index==t(this,rr,`f`)?this._emit(`toolCallDelta`,n,r.step_details.tool_calls[n.index]):(t(this,X,`f`)&&this._emit(`toolCallDone`,t(this,X,`f`)),e(this,rr,n.index,`f`),e(this,X,r.step_details.tool_calls[n.index],`f`),t(this,X,`f`)&&this._emit(`toolCallCreated`,t(this,X,`f`)));this._emit(`runStepDelta`,n.data.delta,r);break;case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:e(this,or,void 0,`f`),n.data.step_details.type==`tool_calls`&&t(this,X,`f`)&&(this._emit(`toolCallDone`,t(this,X,`f`)),e(this,X,void 0,`f`)),this._emit(`runStepDone`,n.data,r);break;case`thread.run.step.in_progress`:break}},dr=function(e){t(this,er,`f`).push(e),this._emit(`event`,e)},fr=function(e){switch(e.event){case`thread.run.step.created`:return t(this,K,`f`)[e.data.id]=e.data,e.data;case`thread.run.step.delta`:let n=t(this,K,`f`)[e.data.id];if(!n)throw Error(`Received a RunStepDelta before creation of a snapshot`);let r=e.data;if(r.delta){let i=G.accumulateDelta(n,r.delta);t(this,K,`f`)[e.data.id]=i}return t(this,K,`f`)[e.data.id];case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:case`thread.run.step.in_progress`:t(this,K,`f`)[e.data.id]=e.data;break}if(t(this,K,`f`)[e.data.id])return t(this,K,`f`)[e.data.id];throw Error(`No snapshot available`)},pr=function(e,n){let r=[];switch(e.event){case`thread.message.created`:return[e.data,r];case`thread.message.delta`:if(!n)throw Error(`Received a delta with no existing snapshot (there should be one from message creation)`);let i=e.data;if(i.delta.content)for(let e of i.delta.content)if(e.index in n.content){let r=n.content[e.index];n.content[e.index]=t(this,W,`m`,mr).call(this,e,r)}else n.content[e.index]=e,r.push(e);return[n,r];case`thread.message.in_progress`:case`thread.message.completed`:case`thread.message.incomplete`:if(n)return[n,r];throw Error(`Received thread message event with no existing snapshot`)}throw Error(`Tried to accumulate a non-message event`)},mr=function(e,t){return G.accumulateDelta(t,e)},hr=function(n){switch(e(this,ar,n.data,`f`),n.event){case`thread.run.created`:break;case`thread.run.queued`:break;case`thread.run.in_progress`:break;case`thread.run.requires_action`:case`thread.run.cancelled`:case`thread.run.failed`:case`thread.run.completed`:case`thread.run.expired`:case`thread.run.incomplete`:e(this,J,n.data,`f`),t(this,X,`f`)&&(this._emit(`toolCallDone`,t(this,X,`f`)),e(this,X,void 0,`f`));break;case`thread.run.cancelling`:break}};var _r=class extends N{constructor(){super(...arguments),this.steps=new Qn(this._client)}create(e,t,n){let{include:r,...i}=t;return this._client.post(P`/threads/${e}/runs`,{query:{include:r},body:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(P`/threads/${r}/runs/${e}`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(P`/threads/${r}/runs/${e}`,{body:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(P`/threads/${e}/runs`,j,{query:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}cancel(e,t,n){let{thread_id:r}=t;return this._client.post(P`/threads/${r}/runs/${e}/cancel`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(r.id,{thread_id:e},n)}createAndStream(e,t,n){return gr.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let r=H([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...r}}).withResponse();switch(i.status){case`queued`:case`in_progress`:case`cancelling`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await se(e);break;case`requires_action`:case`incomplete`:case`cancelled`:case`completed`:case`failed`:case`expired`:return i}}}stream(e,t,n){return gr.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:r,...i}=t;return this._client.post(P`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}async submitToolOutputsAndPoll(e,t,n){let r=await this.submitToolOutputs(e,t,n);return await this.poll(r.id,t,n)}submitToolOutputsStream(e,t,n){return gr.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};_r.Steps=Qn;var vr=class extends N{constructor(){super(...arguments),this.runs=new _r(this._client),this.messages=new Zn(this._client)}create(e={},t){return this._client.post(`/threads`,{body:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(P`/threads/${e}`,{...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(P`/threads/${e}`,{body:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t){return this._client.delete(P`/threads/${e}`,{...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}createAndRun(e,t){return this._client.post(`/threads/runs`,{body:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return gr.createThreadAssistantStream(e,this._client.beta.threads,t)}};vr.Runs=_r,vr.Messages=Zn;var yr=class extends N{constructor(){super(...arguments),this.realtime=new qn(this._client),this.chatkit=new Xn(this._client),this.assistants=new Wn(this._client),this.threads=new vr(this._client)}};yr.Realtime=qn,yr.ChatKit=Xn,yr.Assistants=Wn,yr.Threads=vr;var br=class extends N{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1})}},xr=class extends N{retrieve(e,t,n){let{container_id:r}=t;return this._client.get(P`/containers/${r}/files/${e}/content`,{...n,headers:H([{Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}},Sr=class extends N{constructor(){super(...arguments),this.content=new xr(this._client)}create(e,t,n){return this._client.post(P`/containers/${e}/files`,vt({body:t,...n},this._client))}retrieve(e,t,n){let{container_id:r}=t;return this._client.get(P`/containers/${r}/files/${e}`,n)}list(e,t={},n){return this._client.getAPIList(P`/containers/${e}/files`,j,{query:t,...n})}delete(e,t,n){let{container_id:r}=t;return this._client.delete(P`/containers/${r}/files/${e}`,{...n,headers:H([{Accept:`*/*`},n?.headers])})}};Sr.Content=xr;var Cr=class extends N{constructor(){super(...arguments),this.files=new Sr(this._client)}create(e,t){return this._client.post(`/containers`,{body:e,...t})}retrieve(e,t){return this._client.get(P`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList(`/containers`,j,{query:e,...t})}delete(e,t){return this._client.delete(P`/containers/${e}`,{...t,headers:H([{Accept:`*/*`},t?.headers])})}};Cr.Files=Sr;var wr=class extends N{create(e,t,n){let{include:r,...i}=t;return this._client.post(P`/conversations/${e}/items`,{query:{include:r},body:i,...n})}retrieve(e,t,n){let{conversation_id:r,...i}=t;return this._client.get(P`/conversations/${r}/items/${e}`,{query:i,...n})}list(e,t={},n){return this._client.getAPIList(P`/conversations/${e}/items`,pt,{query:t,...n})}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(P`/conversations/${r}/items/${e}`,n)}},Tr=class extends N{constructor(){super(...arguments),this.items=new wr(this._client)}create(e={},t){return this._client.post(`/conversations`,{body:e,...t})}retrieve(e,t){return this._client.get(P`/conversations/${e}`,t)}update(e,t,n){return this._client.post(P`/conversations/${e}`,{body:t,...n})}delete(e,t){return this._client.delete(P`/conversations/${e}`,t)}};Tr.Items=wr;var Er=class extends N{create(e,t){let n=!!e.encoding_format,r=n?e.encoding_format:`base64`;n&&k(this._client).debug(`embeddings/user defined encoding_format:`,e.encoding_format);let i=this._client.post(`/embeddings`,{body:{...e,encoding_format:r},...t});return n?i:(k(this._client).debug(`embeddings/decoding base64 embeddings from base64`),i._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{let t=e.embedding;e.embedding=$n(t)}),e)))}},Dr=class extends N{retrieve(e,t,n){let{eval_id:r,run_id:i}=t;return this._client.get(P`/evals/${r}/runs/${i}/output_items/${e}`,n)}list(e,t,n){let{eval_id:r,...i}=t;return this._client.getAPIList(P`/evals/${r}/runs/${e}/output_items`,j,{query:i,...n})}},Or=class extends N{constructor(){super(...arguments),this.outputItems=new Dr(this._client)}create(e,t,n){return this._client.post(P`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){let{eval_id:r}=t;return this._client.get(P`/evals/${r}/runs/${e}`,n)}list(e,t={},n){return this._client.getAPIList(P`/evals/${e}/runs`,j,{query:t,...n})}delete(e,t,n){let{eval_id:r}=t;return this._client.delete(P`/evals/${r}/runs/${e}`,n)}cancel(e,t,n){let{eval_id:r}=t;return this._client.post(P`/evals/${r}/runs/${e}`,n)}};Or.OutputItems=Dr;var kr=class extends N{constructor(){super(...arguments),this.runs=new Or(this._client)}create(e,t){return this._client.post(`/evals`,{body:e,...t})}retrieve(e,t){return this._client.get(P`/evals/${e}`,t)}update(e,t,n){return this._client.post(P`/evals/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList(`/evals`,j,{query:e,...t})}delete(e,t){return this._client.delete(P`/evals/${e}`,t)}};kr.Runs=Or;var Ar=class extends N{create(e,t){return this._client.post(`/files`,M({body:e,...t},this._client))}retrieve(e,t){return this._client.get(P`/files/${e}`,t)}list(e={},t){return this._client.getAPIList(`/files`,j,{query:e,...t})}delete(e,t){return this._client.delete(P`/files/${e}`,t)}content(e,t){return this._client.get(P`/files/${e}/content`,{...t,headers:H([{Accept:`application/binary`},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=1800*1e3}={}){let r=new Set([`processed`,`error`,`deleted`]),i=Date.now(),a=await this.retrieve(e);for(;!a.status||!r.has(a.status);)if(await se(t),a=await this.retrieve(e),Date.now()-i>n)throw new l({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}},jr=class extends N{},Mr=class extends N{run(e,t){return this._client.post(`/fine_tuning/alpha/graders/run`,{body:e,...t})}validate(e,t){return this._client.post(`/fine_tuning/alpha/graders/validate`,{body:e,...t})}},Nr=class extends N{constructor(){super(...arguments),this.graders=new Mr(this._client)}};Nr.Graders=Mr;var Pr=class extends N{create(e,t,n){return this._client.getAPIList(P`/fine_tuning/checkpoints/${e}/permissions`,ft,{body:t,method:`post`,...n})}retrieve(e,t={},n){return this._client.get(P`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}list(e,t={},n){return this._client.getAPIList(P`/fine_tuning/checkpoints/${e}/permissions`,pt,{query:t,...n})}delete(e,t,n){let{fine_tuned_model_checkpoint:r}=t;return this._client.delete(P`/fine_tuning/checkpoints/${r}/permissions/${e}`,n)}},Fr=class extends N{constructor(){super(...arguments),this.permissions=new Pr(this._client)}};Fr.Permissions=Pr;var Ir=class extends N{list(e,t={},n){return this._client.getAPIList(P`/fine_tuning/jobs/${e}/checkpoints`,j,{query:t,...n})}},Lr=class extends N{constructor(){super(...arguments),this.checkpoints=new Ir(this._client)}create(e,t){return this._client.post(`/fine_tuning/jobs`,{body:e,...t})}retrieve(e,t){return this._client.get(P`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList(`/fine_tuning/jobs`,j,{query:e,...t})}cancel(e,t){return this._client.post(P`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return this._client.getAPIList(P`/fine_tuning/jobs/${e}/events`,j,{query:t,...n})}pause(e,t){return this._client.post(P`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(P`/fine_tuning/jobs/${e}/resume`,t)}};Lr.Checkpoints=Ir;var Z=class extends N{constructor(){super(...arguments),this.methods=new jr(this._client),this.jobs=new Lr(this._client),this.checkpoints=new Fr(this._client),this.alpha=new Nr(this._client)}};Z.Methods=jr,Z.Jobs=Lr,Z.Checkpoints=Fr,Z.Alpha=Nr;var Rr=class extends N{},zr=class extends N{constructor(){super(...arguments),this.graderModels=new Rr(this._client)}};zr.GraderModels=Rr;var Br=class extends N{createVariation(e,t){return this._client.post(`/images/variations`,M({body:e,...t},this._client))}edit(e,t){return this._client.post(`/images/edits`,M({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post(`/images/generations`,{body:e,...t,stream:e.stream??!1})}},Vr=class extends N{retrieve(e,t){return this._client.get(P`/models/${e}`,t)}list(e){return this._client.getAPIList(`/models`,ft,e)}delete(e,t){return this._client.delete(P`/models/${e}`,t)}},Hr=class extends N{create(e,t){return this._client.post(`/moderations`,{body:e,...t})}},Ur=class extends N{accept(e,t,n){return this._client.post(P`/realtime/calls/${e}/accept`,{body:t,...n,headers:H([{Accept:`*/*`},n?.headers])})}hangup(e,t){return this._client.post(P`/realtime/calls/${e}/hangup`,{...t,headers:H([{Accept:`*/*`},t?.headers])})}refer(e,t,n){return this._client.post(P`/realtime/calls/${e}/refer`,{body:t,...n,headers:H([{Accept:`*/*`},n?.headers])})}reject(e,t={},n){return this._client.post(P`/realtime/calls/${e}/reject`,{body:t,...n,headers:H([{Accept:`*/*`},n?.headers])})}},Wr=class extends N{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t})}},Gr=class extends N{constructor(){super(...arguments),this.clientSecrets=new Wr(this._client),this.calls=new Ur(this._client)}};Gr.ClientSecrets=Wr,Gr.Calls=Ur;function Kr(e,t){return!t||!Yr(t)?{...e,output_parsed:null,output:e.output.map(e=>e.type===`function_call`?{...e,parsed_arguments:null}:e.type===`message`?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)}:qr(e,t)}function qr(e,t){let n=e.output.map(e=>{if(e.type===`function_call`)return{...e,parsed_arguments:Qr(t,e)};if(e.type===`message`){let n=e.content.map(e=>e.type===`output_text`?{...e,parsed:Jr(t,e.text)}:e);return{...e,content:n}}return e}),r=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,`output_text`)||$r(r),Object.defineProperty(r,`output_parsed`,{enumerable:!0,get(){for(let e of r.output)if(e.type===`message`){for(let t of e.content)if(t.type===`output_text`&&t.parsed!==null)return t.parsed}return null}}),r}function Jr(e,t){return e.text?.format?.type===`json_schema`?`$parseRaw`in e.text?.format?(e.text?.format).$parseRaw(t):JSON.parse(t):null}function Yr(e){return!!It(e.text?.format)}function Xr(e){return e?.$brand===`auto-parseable-tool`}function Zr(e,t){return e.find(e=>e.type===`function`&&e.name===t)}function Qr(e,t){let n=Zr(e.tools??[],t.name);return{...t,...t,parsed_arguments:Xr(n)?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null}}function $r(e){let t=[];for(let n of e.output)if(n.type===`message`)for(let e of n.content)e.type===`output_text`&&t.push(e.text);e.output_text=t.join(``)}var ei,ti,Q,ni,ri,ii,ai,oi,si=class n extends sn{constructor(t){super(),ei.add(this),ti.set(this,void 0),Q.set(this,void 0),ni.set(this,void 0),e(this,ti,t,`f`)}static createResponse(e,t,r){let i=new n(t);return i._run(()=>i._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createOrRetrieveResponse(e,n,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort())),t(this,ei,`m`,ri).call(this);let a,o=null;`response_id`in n?(a=await e.responses.retrieve(n.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),o=n.starting_after??null):a=await e.responses.create({...n,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let e of a)t(this,ei,`m`,ii).call(this,e,o);if(a.controller.signal?.aborted)throw new s;return t(this,ei,`m`,ai).call(this)}[(ti=new WeakMap,Q=new WeakMap,ni=new WeakMap,ei=new WeakSet,ri=function(){this.ended||e(this,Q,void 0,`f`)},ii=function(e,n){if(this.ended)return;let r=(e,t)=>{(n==null||t.sequence_number>n)&&this._emit(e,t)},i=t(this,ei,`m`,oi).call(this,e);switch(r(`event`,e),e.type){case`response.output_text.delta`:{let t=i.output[e.output_index];if(!t)throw new a(`missing output at index ${e.output_index}`);if(t.type===`message`){let n=t.content[e.content_index];if(!n)throw new a(`missing content at index ${e.content_index}`);if(n.type!==`output_text`)throw new a(`expected content to be 'output_text', got ${n.type}`);r(`response.output_text.delta`,{...e,snapshot:n.text})}break}case`response.function_call_arguments.delta`:{let t=i.output[e.output_index];if(!t)throw new a(`missing output at index ${e.output_index}`);t.type===`function_call`&&r(`response.function_call_arguments.delta`,{...e,snapshot:t.arguments});break}default:r(e.type,e);break}},ai=function(){if(this.ended)throw new a(`stream has ended, this shouldn't happen`);let n=t(this,Q,`f`);if(!n)throw new a(`request ended without sending any events`);e(this,Q,void 0,`f`);let r=ci(n,t(this,ti,`f`));return e(this,ni,r,`f`),r},oi=function(n){let r=t(this,Q,`f`);if(!r){if(n.type!==`response.created`)throw new a(`When snapshot hasn't been set yet, expected 'response.created' event, got ${n.type}`);return r=e(this,Q,n.response,`f`),r}switch(n.type){case`response.output_item.added`:r.output.push(n.item);break;case`response.content_part.added`:{let e=r.output[n.output_index];if(!e)throw new a(`missing output at index ${n.output_index}`);let t=e.type,i=n.part;t===`message`&&i.type!==`reasoning_text`?e.content.push(i):t===`reasoning`&&i.type===`reasoning_text`&&(e.content||=[],e.content.push(i));break}case`response.output_text.delta`:{let e=r.output[n.output_index];if(!e)throw new a(`missing output at index ${n.output_index}`);if(e.type===`message`){let t=e.content[n.content_index];if(!t)throw new a(`missing content at index ${n.content_index}`);if(t.type!==`output_text`)throw new a(`expected content to be 'output_text', got ${t.type}`);t.text+=n.delta}break}case`response.function_call_arguments.delta`:{let e=r.output[n.output_index];if(!e)throw new a(`missing output at index ${n.output_index}`);e.type===`function_call`&&(e.arguments+=n.delta);break}case`response.reasoning_text.delta`:{let e=r.output[n.output_index];if(!e)throw new a(`missing output at index ${n.output_index}`);if(e.type===`reasoning`){let t=e.content?.[n.content_index];if(!t)throw new a(`missing content at index ${n.content_index}`);if(t.type!==`reasoning_text`)throw new a(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=n.delta}break}case`response.completed`:e(this,Q,n.response,`f`);break}return r},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=t(this,ni,`f`);if(!e)throw new a(`stream ended without producing a ChatCompletion`);return e}};function ci(e,t){return Kr(e,t)}var li=class extends N{list(e,t={},n){return this._client.getAPIList(P`/responses/${e}/input_items`,j,{query:t,...n})}},ui=class extends N{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t})}},di=class extends N{constructor(){super(...arguments),this.inputItems=new li(this._client),this.inputTokens=new ui(this._client)}create(e,t){return this._client.post(`/responses`,{body:e,...t,stream:e.stream??!1})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&$r(e),e))}retrieve(e,t={},n){return this._client.get(P`/responses/${e}`,{query:t,...n,stream:t?.stream??!1})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&$r(e),e))}delete(e,t){return this._client.delete(P`/responses/${e}`,{...t,headers:H([{Accept:`*/*`},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>qr(t,e))}stream(e,t){return si.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(P`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post(`/responses/compact`,{body:e,...t})}};di.InputItems=li,di.InputTokens=ui;var fi=class extends N{retrieve(e,t){return this._client.get(P`/skills/${e}/content`,{...t,headers:H([{Accept:`application/binary`},t?.headers]),__binaryResponse:!0})}},pi=class extends N{retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(P`/skills/${r}/versions/${e}/content`,{...n,headers:H([{Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}},mi=class extends N{constructor(){super(...arguments),this.content=new pi(this._client)}create(e,t={},n){return this._client.post(P`/skills/${e}/versions`,vt({body:t,...n},this._client))}retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(P`/skills/${r}/versions/${e}`,n)}list(e,t={},n){return this._client.getAPIList(P`/skills/${e}/versions`,j,{query:t,...n})}delete(e,t,n){let{skill_id:r}=t;return this._client.delete(P`/skills/${r}/versions/${e}`,n)}};mi.Content=pi;var hi=class extends N{constructor(){super(...arguments),this.content=new fi(this._client),this.versions=new mi(this._client)}create(e={},t){return this._client.post(`/skills`,vt({body:e,...t},this._client))}retrieve(e,t){return this._client.get(P`/skills/${e}`,t)}update(e,t,n){return this._client.post(P`/skills/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList(`/skills`,j,{query:e,...t})}delete(e,t){return this._client.delete(P`/skills/${e}`,t)}};hi.Content=fi,hi.Versions=mi;var gi=class extends N{create(e,t,n){return this._client.post(P`/uploads/${e}/parts`,M({body:t,...n},this._client))}},_i=class extends N{constructor(){super(...arguments),this.parts=new gi(this._client)}create(e,t){return this._client.post(`/uploads`,{body:e,...t})}cancel(e,t){return this._client.post(P`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(P`/uploads/${e}/complete`,{body:t,...n})}};_i.Parts=gi;const vi=async e=>{let t=await Promise.allSettled(e),n=t.filter(e=>e.status===`rejected`);if(n.length){for(let e of n)console.error(e.reason);throw Error(`${n.length} promise(s) failed - see the above errors`)}let r=[];for(let e of t)e.status===`fulfilled`&&r.push(e.value);return r};var yi=class extends N{create(e,t,n){return this._client.post(P`/vector_stores/${e}/file_batches`,{body:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(P`/vector_stores/${r}/file_batches/${e}`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}cancel(e,t,n){let{vector_store_id:r}=t;return this._client.post(P`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async createAndPoll(e,t,n){let r=await this.create(e,t);return await this.poll(e,r.id,n)}listFiles(e,t,n){let{vector_store_id:r,...i}=t;return this._client.getAPIList(P`/vector_stores/${r}/file_batches/${e}/files`,j,{query:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async poll(e,t,n){let r=H([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse();switch(i.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await se(e);break;case`failed`:case`cancelled`:case`completed`:return i}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},r){if(t==null||t.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let i=r?.maxConcurrency??5,a=Math.min(i,t.length),o=this._client,s=t.values(),c=[...n];async function l(e){for(let t of e){let e=await o.files.create({file:t,purpose:`assistants`},r);c.push(e.id)}}return await vi(Array(a).fill(s).map(l)),await this.createAndPoll(e,{file_ids:c})}},bi=class extends N{create(e,t,n){return this._client.post(P`/vector_stores/${e}/files`,{body:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(P`/vector_stores/${r}/files/${e}`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{vector_store_id:r,...i}=t;return this._client.post(P`/vector_stores/${r}/files/${e}`,{body:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(P`/vector_stores/${e}/files`,j,{query:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t,n){let{vector_store_id:r}=t;return this._client.delete(P`/vector_stores/${r}/files/${e}`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(e,r.id,n)}async poll(e,t,n){let r=H([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let i=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse(),a=i.data;switch(a.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=i.response.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await se(e);break;case`failed`:case`completed`:return a}}}async upload(e,t,n){let r=await this._client.files.create({file:t,purpose:`assistants`},n);return this.create(e,{file_id:r.id},n)}async uploadAndPoll(e,t,n){let r=await this.upload(e,t,n);return await this.poll(e,r.id,n)}content(e,t,n){let{vector_store_id:r}=t;return this._client.getAPIList(P`/vector_stores/${r}/files/${e}/content`,ft,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}},xi=class extends N{constructor(){super(...arguments),this.files=new bi(this._client),this.fileBatches=new yi(this._client)}create(e,t){return this._client.post(`/vector_stores`,{body:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(P`/vector_stores/${e}`,{...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(P`/vector_stores/${e}`,{body:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e={},t){return this._client.getAPIList(`/vector_stores`,j,{query:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}delete(e,t){return this._client.delete(P`/vector_stores/${e}`,{...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}search(e,t,n){return this._client.getAPIList(P`/vector_stores/${e}/search`,ft,{body:t,method:`post`,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}};xi.Files=bi,xi.FileBatches=yi;var Si=class extends N{create(e,t){return this._client.post(`/videos`,vt({body:e,...t},this._client))}retrieve(e,t){return this._client.get(P`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList(`/videos`,pt,{query:e,...t})}delete(e,t){return this._client.delete(P`/videos/${e}`,t)}downloadContent(e,t={},n){return this._client.get(P`/videos/${e}/content`,{query:t,...n,headers:H([{Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}remix(e,t,n){return this._client.post(P`/videos/${e}/remix`,vt({body:t,...n},this._client))}},Ci,wi,Ti,Ei=class extends N{constructor(){super(...arguments),Ci.add(this)}async unwrap(e,t,n=this._client.webhookSecret,r=300){return await this.verifySignature(e,t,n,r),JSON.parse(e)}async verifySignature(e,n,r=this._client.webhookSecret,i=300){if(typeof crypto>`u`||typeof crypto.subtle.importKey!=`function`||typeof crypto.subtle.verify!=`function`)throw Error("Webhook signature verification is only supported when the `crypto` global is defined");t(this,Ci,`m`,wi).call(this,r);let a=H([n]).values,o=t(this,Ci,`m`,Ti).call(this,a,`webhook-signature`),s=t(this,Ci,`m`,Ti).call(this,a,`webhook-timestamp`),c=t(this,Ci,`m`,Ti).call(this,a,`webhook-id`),l=parseInt(s,10);if(isNaN(l))throw new b(`Invalid webhook timestamp format`);let u=Math.floor(Date.now()/1e3);if(u-l>i)throw new b(`Webhook timestamp is too old`);if(l>u+i)throw new b(`Webhook timestamp is too new`);let d=o.split(` `).map(e=>e.startsWith(`v1,`)?e.substring(3):e),f=r.startsWith(`whsec_`)?Buffer.from(r.replace(`whsec_`,``),`base64`):Buffer.from(r,`utf-8`),p=c?`${c}.${s}.${e}`:`${s}.${e}`,m=await crypto.subtle.importKey(`raw`,f,{name:`HMAC`,hash:`SHA-256`},!1,[`verify`]);for(let e of d)try{let t=Buffer.from(e,`base64`);if(await crypto.subtle.verify(`HMAC`,m,t,new TextEncoder().encode(p)))return}catch{continue}throw new b(`The given webhook signature does not match the expected signature`)}};Ci=new WeakSet,wi=function(e){if(typeof e!=`string`||e.length===0)throw Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`)},Ti=function(e,t){if(!e)throw Error(`Headers are required`);let n=e.get(t);if(n==null)throw Error(`Missing required header: ${t}`);return n};var Di,Oi,ki,Ai,$=class{constructor({baseURL:t=U(`OPENAI_BASE_URL`),apiKey:n=U(`OPENAI_API_KEY`),organization:r=U(`OPENAI_ORG_ID`)??null,project:i=U(`OPENAI_PROJECT_ID`)??null,webhookSecret:o=U(`OPENAI_WEBHOOK_SECRET`)??null,...s}={}){if(Di.add(this),ki.set(this,void 0),this.completions=new br(this),this.chat=new In(this),this.embeddings=new Er(this),this.files=new Ar(this),this.images=new Br(this),this.audio=new Hn(this),this.moderations=new Hr(this),this.models=new Vr(this),this.fineTuning=new Z(this),this.graders=new zr(this),this.vectorStores=new xi(this),this.webhooks=new Ei(this),this.beta=new yr(this),this.batches=new Un(this),this.uploads=new _i(this),this.responses=new di(this),this.realtime=new Gr(this),this.conversations=new Tr(this),this.evals=new kr(this),this.containers=new Cr(this),this.skills=new hi(this),this.videos=new Si(this),n===void 0)throw new a("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let c={apiKey:n,organization:r,project:i,webhookSecret:o,...s,baseURL:t||`https://api.openai.com/v1`};if(!c.dangerouslyAllowBrowser&&ce())throw new a(`It looks like you're running in a browser-like environment.
8
+
9
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
10
+ If you understand the risks and have appropriate mitigations in place,
11
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
12
+
13
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
14
+
15
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
16
+ `);this.baseURL=c.baseURL,this.timeout=c.timeout??Oi.DEFAULT_TIMEOUT,this.logger=c.logger??console;let l=`warn`;this.logLevel=l,this.logLevel=Je(c.logLevel,`ClientOptions.logLevel`,this)??Je(U(`OPENAI_LOG`),`process.env['OPENAI_LOG']`,this)??l,this.fetchOptions=c.fetchOptions,this.maxRetries=c.maxRetries??2,this.fetch=c.fetch??ge(),e(this,ki,xe,`f`),this._options=c,this.apiKey=typeof n==`string`?n:`Missing Key`,this.organization=r,this.project=i,this.webhookSecret=o}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return H([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Re(e)}getUserAgent(){return`${this.constructor.name}/JS ${w}`}defaultIdempotencyKey(){return`stainless-node-retry-${n()}`}makeStatusError(e,t,n,r){return o.generate(e,t,n,r)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!=`function`)return!1;let t;try{t=await e()}catch(e){throw e instanceof a?e:new a(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if(typeof t!=`string`||!t)throw new a(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,n,r){let i=!t(this,Di,`m`,Ai).call(this)&&r||this.baseURL,a=te(e)?new URL(e):new URL(i+(i.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),o=this.defaultQuery();return ne(o)||(n={...o,...n}),typeof n==`object`&&n&&!Array.isArray(n)&&(a.search=this.stringifyQuery(n)),a.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new ct(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let a=await e,o=a.maxRetries??this.maxRetries;t??=o,await this.prepareOptions(a);let{req:u,url:d,timeout:f}=await this.buildRequest(a,{retryCount:o-t});await this.prepareRequest(u,{url:d,options:a});let p=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),m=n===void 0?``:`, retryOf: ${n}`,h=Date.now();if(k(this).debug(`[${p}] sending request`,A({retryOfRequestLogID:n,method:a.method,url:d,options:a,headers:u.headers})),a.signal?.aborted)throw new s;let g=new AbortController,_=await this.fetchWithTimeout(d,u,f,g).catch(i),v=Date.now();if(_ instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(a.signal?.aborted)throw new s;let i=r(_)||/timed? ?out/i.test(String(_)+(`cause`in _?String(_.cause):``));if(t)return k(this).info(`[${p}] connection ${i?`timed out`:`failed`} - ${e}`),k(this).debug(`[${p}] connection ${i?`timed out`:`failed`} (${e})`,A({retryOfRequestLogID:n,url:d,durationMs:v-h,message:_.message})),this.retryRequest(a,t,n??p);throw k(this).info(`[${p}] connection ${i?`timed out`:`failed`} - error; no more retries left`),k(this).debug(`[${p}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,A({retryOfRequestLogID:n,url:d,durationMs:v-h,message:_.message})),i?new l:new c({cause:_})}let y=`[${p}${m}${[..._.headers.entries()].filter(([e])=>e===`x-request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${u.method} ${d} ${_.ok?`succeeded`:`failed`} with status ${_.status} in ${v-h}ms`;if(!_.ok){let e=await this.shouldRetry(_);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await be(_.body),k(this).info(`${y} - ${e}`),k(this).debug(`[${p}] response error (${e})`,A({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,durationMs:v-h})),this.retryRequest(a,t,n??p,_.headers)}let r=e?`error; no more retries left`:`error; not retryable`;k(this).info(`${y} - ${r}`);let o=await _.text().catch(e=>i(e).message),s=oe(o),c=s?void 0:o;throw k(this).debug(`[${p}] response error (${r})`,A({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,message:c,durationMs:Date.now()-h})),this.makeStatusError(_.status,s,c,_.headers)}return k(this).info(y),k(this).debug(`[${p}] response start`,A({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,durationMs:v-h})),{response:_,options:a,controller:g,requestLogID:p,retryOfRequestLogID:n,startTime:h}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new dt(this,n,e)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await se(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&ae(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n});return{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=H([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...he(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=H([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==`string`&&r.values.has(`content-type`)||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e==`object`&&(Symbol.asyncIterator in e||Symbol.iterator in e&&`next`in e&&typeof e.next==`function`)?{bodyHeaders:void 0,body:ve(e)}:typeof e==`object`&&r.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(e)}:t(this,ki,`f`).call(this,{body:e,headers:r})}};Oi=$,ki=new WeakMap,Di=new WeakSet,Ai=function(){return this.baseURL!==`https://api.openai.com/v1`},$.OpenAI=Oi,$.DEFAULT_TIMEOUT=6e5,$.OpenAIError=a,$.APIError=o,$.APIConnectionError=c,$.APIConnectionTimeoutError=l,$.APIUserAbortError=s,$.NotFoundError=p,$.ConflictError=m,$.RateLimitError=g,$.BadRequestError=u,$.AuthenticationError=d,$.InternalServerError=_,$.PermissionDeniedError=f,$.UnprocessableEntityError=h,$.InvalidWebhookSignatureError=b,$.toFile=kt,$.Completions=br,$.Chat=In,$.Embeddings=Er,$.Files=Ar,$.Images=Br,$.Audio=Hn,$.Moderations=Hr,$.Models=Vr,$.FineTuning=Z,$.Graders=zr,$.VectorStores=xi,$.Webhooks=Ei,$.Beta=yr,$.Batches=Un,$.Uploads=_i,$.Responses=di,$.Realtime=Gr,$.Conversations=Tr,$.Evals=kr,$.Containers=Cr,$.Skills=hi,$.Videos=Si;var ji=class extends ${constructor({baseURL:e=U(`OPENAI_BASE_URL`),apiKey:t=U(`AZURE_OPENAI_API_KEY`),apiVersion:n=U(`OPENAI_API_VERSION`),endpoint:r,deployment:i,azureADTokenProvider:o,dangerouslyAllowBrowser:s,...c}={}){if(!n)throw new a(`The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).`);if(typeof o==`function`&&(s=!0),!o&&!t)throw new a("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(o&&t)throw new a("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(c.defaultQuery={...c.defaultQuery,"api-version":n},!e){if(r||=process.env.AZURE_OPENAI_ENDPOINT,!r)throw new a("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${r}/openai`}else if(r)throw new a(`baseURL and endpoint are mutually exclusive`);super({apiKey:o??t,baseURL:e,...c,...s===void 0?{}:{dangerouslyAllowBrowser:s}}),this.apiVersion=``,this.apiVersion=n,this.deploymentName=i}async buildRequest(e,t={}){if(Mi.has(e.path)&&e.method===`post`&&e.body!==void 0){if(!ie(e.body))throw Error(`Expected request body to be an object`);let t=this.deploymentName||e.body.model||e.__metadata?.model;t!==void 0&&!this.baseURL.includes(`/deployments`)&&(e.path=`/deployments/${t}${e.path}`)}return super.buildRequest(e,t)}async authHeaders(e){return typeof this._options.apiKey==`string`?H([{"api-key":this.apiKey}]):super.authHeaders(e)}};const Mi=new Set([`/completions`,`/chat/completions`,`/embeddings`,`/audio/transcriptions`,`/audio/translations`,`/audio/speech`,`/images/generations`,`/batches`,`/images/edits`]);export{$ as n,ji as t};
@@ -0,0 +1,7 @@
1
+ import{t as e}from"./env-api-keys-Cuz5irWW.mjs";import{o as t,t as n}from"./event-stream-B7Ei41Bu.mjs";import{t as r}from"./headers-Bpsp70B9.mjs";import{i,r as a}from"./transform-messages-BTA3xbAI.mjs";import{n as o,r as s,t as c}from"./openai-responses-shared-DqW1JSux.mjs";let l=null;typeof process<`u`&&(process.versions?.node||process.versions?.bun)&&(e=>import(e))(`node:os`).then(e=>{l=e});const u=1e3,d=new Set([`openai`,`openai-codex`,`opencode`]),f=new Set([`completed`,`incomplete`,`failed`,`cancelled`,`queued`,`in_progress`]);function p(e,t){return e===429||e===500||e===502||e===503||e===504?!0:/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(t)}function m(e,t){return new Promise((n,r)=>{if(t?.aborted){r(Error(`Request was aborted`));return}let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(Error(`Request was aborted`))})})}const h=(t,i,a)=>{let o=new n;return(async()=>{let n={role:`assistant`,content:[],api:`openai-codex-responses`,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let s=a?.apiKey||e(t.provider)||``;if(!s)throw Error(`No API key for provider: ${t.provider}`);let c=H(s),l=_(t,i,a),d=await a?.onPayload?.(l,t);d!==void 0&&(l=d);let f=a?.sessionId||U(),h=G(t.headers,a?.headers,c,s,a?.sessionId),g=K(t.headers,a?.headers,c,s,f),v=JSON.stringify(l),y=a?.transport||`sse`;if(y!==`sse`){let e=!1;try{if(await B(C(t.baseUrl),l,g,n,o,t,()=>{e=!0},a),a?.signal?.aborted)throw Error(`Request was aborted`);o.push({type:`done`,reason:n.stopReason,message:n}),o.end();return}catch(t){if(y===`websocket`||e)throw t}}let b,x;for(let e=0;e<=3;e++){if(a?.signal?.aborted)throw Error(`Request was aborted`);try{if(b=await fetch(S(t.baseUrl),{method:`POST`,headers:h,body:v,signal:a?.signal}),await a?.onResponse?.({status:b.status,headers:r(b.headers)},t),b.ok)break;let n=await b.text();if(e<3&&p(b.status,n)){await m(u*2**e,a?.signal);continue}let i=await V(new Response(n,{status:b.status,statusText:b.statusText}));throw Error(i.friendlyMessage||i.message)}catch(t){if(t instanceof Error&&(t.name===`AbortError`||t.message===`Request was aborted`))throw Error(`Request was aborted`);if(x=t instanceof Error?t:Error(String(t)),e<3&&!x.message.includes(`usage limit`)){await m(u*2**e,a?.signal);continue}throw x}}if(!b?.ok)throw x??Error(`Failed after retries`);if(!b.body)throw Error(`No response body`);if(o.push({type:`start`,partial:n}),await w(b,n,o,t,a),a?.signal?.aborted)throw Error(`Request was aborted`);o.push({type:`done`,reason:n.stopReason,message:n}),o.end()}catch(e){for(let e of n.content)delete e.partialJson;n.stopReason=a?.signal?.aborted?`aborted`:`error`,n.errorMessage=e instanceof Error?e.message:String(e),o.push({type:`error`,reason:n.stopReason,error:n}),o.end()}})(),o},g=(n,r,o)=>{let s=o?.apiKey||e(n.provider);if(!s)throw Error(`No API key for provider: ${n.provider}`);let c=a(n,o,s),l=t(n)?o?.reasoning:i(o?.reasoning);return h(n,r,{...c,reasoningEffort:l})};function _(e,t,n){let r=c(e,t,d,{includeSystemPrompt:!1}),i={model:e.id,store:!1,stream:!0,instructions:t.systemPrompt,input:r,text:{verbosity:n?.textVerbosity||`medium`},include:[`reasoning.encrypted_content`],prompt_cache_key:n?.sessionId,tool_choice:`auto`,parallel_tool_calls:!0};return n?.temperature!==void 0&&(i.temperature=n.temperature),n?.serviceTier!==void 0&&(i.service_tier=n.serviceTier),t.tools&&(i.tools=o(t.tools,{strict:null})),n?.reasoningEffort!==void 0&&(i.reasoning={effort:v(e.id,n.reasoningEffort),summary:n.reasoningSummary??`auto`}),i}function v(e,t){let n=e.includes(`/`)?e.split(`/`).pop():e;return(n.startsWith(`gpt-5.2`)||n.startsWith(`gpt-5.3`)||n.startsWith(`gpt-5.4`))&&t===`minimal`?`low`:n===`gpt-5.1`&&t===`xhigh`?`high`:n===`gpt-5.1-codex-mini`?t===`high`||t===`xhigh`?`high`:`medium`:t}function y(e){switch(e){case`flex`:return .5;case`priority`:return 2;default:return 1}}function b(e,t){let n=y(t);n!==1&&(e.cost.input*=n,e.cost.output*=n,e.cost.cacheRead*=n,e.cost.cacheWrite*=n,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}function x(e,t){return e===`default`&&(t===`flex`||t===`priority`)?t:e??t}function S(e){let t=(e&&e.trim().length>0?e:`https://chatgpt.com/backend-api`).replace(/\/+$/,``);return t.endsWith(`/codex/responses`)?t:t.endsWith(`/codex`)?`${t}/responses`:`${t}/codex/responses`}function C(e){let t=new URL(S(e));return t.protocol===`https:`&&(t.protocol=`wss:`),t.protocol===`http:`&&(t.protocol=`ws:`),t.toString()}async function w(e,t,n,r,i){await s(T(D(e)),t,n,r,{serviceTier:i?.serviceTier,resolveServiceTier:x,applyServiceTierPricing:b})}async function*T(e){for await(let t of e){let e=typeof t.type==`string`?t.type:void 0;if(e){if(e===`error`){let e=t.code||``,n=t.message||``;throw Error(`Codex error: ${n||e||JSON.stringify(t)}`)}if(e===`response.failed`){let e=t.response?.error?.message;throw Error(e||`Codex response failed`)}if(e===`response.done`||e===`response.completed`||e===`response.incomplete`){let e=t.response,n=e&&{...e,status:E(e.status)};yield{...t,type:`response.completed`,response:n};return}yield t}}}function E(e){if(typeof e==`string`)return f.has(e)?e:void 0}async function*D(e){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,r=``;try{for(;;){let{done:e,value:i}=await t.read();if(e)break;r+=n.decode(i,{stream:!0});let a=r.indexOf(`
2
+
3
+ `);for(;a!==-1;){let e=r.slice(0,a);r=r.slice(a+2);let t=e.split(`
4
+ `).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim());if(t.length>0){let e=t.join(`
5
+ `).trim();if(e&&e!==`[DONE]`)try{yield JSON.parse(e)}catch{}}a=r.indexOf(`
6
+
7
+ `)}}}finally{try{await t.cancel()}catch{}try{t.releaseLock()}catch{}}}const O=new Map;function k(){let e=globalThis.WebSocket;return typeof e==`function`?e:null}function A(e){let t=e.readyState;return typeof t==`number`?t:void 0}function j(e){let t=A(e);return t===void 0||t===1}function M(e,t=1e3,n=`done`){try{e.close(t,n)}catch{}}function N(e,t){t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{t.busy||(M(t.socket,1e3,`idle_timeout`),O.delete(e))},3e5)}async function P(e,t,n){let i=k();if(!i)throw Error(`WebSocket transport is not available in this runtime`);let a=r(t);return delete a[`OpenAI-Beta`],new Promise((t,r)=>{let o=!1,s;try{s=new i(e,{headers:a})}catch(e){r(e instanceof Error?e:Error(String(e)));return}let c=()=>{o||(o=!0,f(),t(s))},l=e=>{let t=I(e);o||(o=!0,f(),r(t))},u=e=>{let t=L(e);o||(o=!0,f(),r(t))},d=()=>{o||(o=!0,f(),s.close(1e3,`aborted`),r(Error(`Request was aborted`)))},f=()=>{s.removeEventListener(`open`,c),s.removeEventListener(`error`,l),s.removeEventListener(`close`,u),n?.removeEventListener(`abort`,d)};s.addEventListener(`open`,c),s.addEventListener(`error`,l),s.addEventListener(`close`,u),n?.addEventListener(`abort`,d)})}async function F(e,t,n,r){if(!n){let n=await P(e,t,r);return{socket:n,release:({keep:e}={})=>{if(e===!1){M(n);return}M(n)}}}let i=O.get(n);if(i){if(i.idleTimer&&=(clearTimeout(i.idleTimer),void 0),!i.busy&&j(i.socket))return i.busy=!0,{socket:i.socket,release:({keep:e}={})=>{if(!e||!j(i.socket)){M(i.socket),O.delete(n);return}i.busy=!1,N(n,i)}};if(i.busy){let n=await P(e,t,r);return{socket:n,release:()=>{M(n)}}}j(i.socket)||(M(i.socket),O.delete(n))}let a=await P(e,t,r),o={socket:a,busy:!0};return O.set(n,o),{socket:a,release:({keep:e}={})=>{if(!e||!j(o.socket)){M(o.socket),o.idleTimer&&clearTimeout(o.idleTimer),O.get(n)===o&&O.delete(n);return}o.busy=!1,N(n,o)}}}function I(e){if(e&&typeof e==`object`&&`message`in e){let t=e.message;if(typeof t==`string`&&t.length>0)return Error(t)}return Error(`WebSocket error`)}function L(e){if(e&&typeof e==`object`){let t=`code`in e?e.code:void 0,n=`reason`in e?e.reason:void 0,r=typeof t==`number`?` ${t}`:``,i=typeof n==`string`&&n.length>0?` ${n}`:``;return Error(`WebSocket closed${r}${i}`.trim())}return Error(`WebSocket closed`)}async function R(e){if(typeof e==`string`)return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return new TextDecoder().decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}if(e&&typeof e==`object`&&`arrayBuffer`in e){let t=await e.arrayBuffer();return new TextDecoder().decode(new Uint8Array(t))}return null}async function*z(e,t){let n=[],r=null,i=!1,a=null,o=!1,s=()=>{if(!r)return;let e=r;r=null,e()},c=e=>{(async()=>{if(!e||typeof e!=`object`||!(`data`in e))return;let t=await R(e.data);if(t)try{let e=JSON.parse(t),r=typeof e.type==`string`?e.type:``;(r===`response.completed`||r===`response.done`||r===`response.incomplete`)&&(o=!0,i=!0),n.push(e),s()}catch{}})()},l=e=>{a=I(e),i=!0,s()},u=e=>{if(o){i=!0,s();return}a||=L(e),i=!0,s()},d=()=>{a=Error(`Request was aborted`),i=!0,s()};e.addEventListener(`message`,c),e.addEventListener(`error`,l),e.addEventListener(`close`,u),t?.addEventListener(`abort`,d);try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);if(n.length>0){yield n.shift();continue}if(i)break;await new Promise(e=>{r=e})}if(a)throw a;if(!o)throw Error(`WebSocket stream closed before response.completed`)}finally{e.removeEventListener(`message`,c),e.removeEventListener(`error`,l),e.removeEventListener(`close`,u),t?.removeEventListener(`abort`,d)}}async function B(e,t,n,r,i,a,o,c){let{socket:l,release:u}=await F(e,n,c?.sessionId,c?.signal),d=!0;try{l.send(JSON.stringify({type:`response.create`,...t})),o(),i.push({type:`start`,partial:r}),await s(T(z(l,c?.signal)),r,i,a,{serviceTier:c?.serviceTier,resolveServiceTier:x,applyServiceTierPricing:b}),c?.signal?.aborted&&(d=!1)}catch(e){throw d=!1,e}finally{u({keep:d})}}async function V(e){let t=await e.text(),n=t||e.statusText||`Request failed`,r;try{let i=JSON.parse(t)?.error;if(i){let t=i.code||i.type||``;if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(t)||e.status===429){let e=i.plan_type?` (${i.plan_type.toLowerCase()} plan)`:``,t=i.resets_at?Math.max(0,Math.round((i.resets_at*1e3-Date.now())/6e4)):void 0;r=`You have hit your ChatGPT usage limit${e}.${t===void 0?``:` Try again in ~${t} min.`}`.trim()}n=i.message||r||n}}catch{}return{message:n,friendlyMessage:r}}function H(e){try{let t=e.split(`.`);if(t.length!==3)throw Error(`Invalid token`);let n=JSON.parse(atob(t[1]))?.[`https://api.openai.com/auth`]?.chatgpt_account_id;if(!n)throw Error(`No account ID in token`);return n}catch{throw Error(`Failed to extract accountId from token`)}}function U(){return typeof globalThis.crypto?.randomUUID==`function`?globalThis.crypto.randomUUID():`codex_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function W(e,t,n,r){let i=new Headers(e);for(let[e,n]of Object.entries(t||{}))i.set(e,n);i.set(`Authorization`,`Bearer ${r}`),i.set(`chatgpt-account-id`,n),i.set(`originator`,`pi`);let a=l?`pi (${l.platform()} ${l.release()}; ${l.arch()})`:`pi (browser)`;return i.set(`User-Agent`,a),i}function G(e,t,n,r,i){let a=W(e,t,n,r);return a.set(`OpenAI-Beta`,`responses=experimental`),a.set(`accept`,`text/event-stream`),a.set(`content-type`,`application/json`),i&&(a.set(`session_id`,i),a.set(`x-client-request-id`,i)),a}function K(e,t,n,r,i){let a=W(e,t,n,r);return a.delete(`accept`),a.delete(`content-type`),a.delete(`OpenAI-Beta`),a.delete(`openai-beta`),a.set(`OpenAI-Beta`,`responses_websockets=2026-02-06`),a.set(`x-client-request-id`,i),a.set(`session_id`,i),a}export{h as streamOpenAICodexResponses,g as streamSimpleOpenAICodexResponses};
@@ -0,0 +1,5 @@
1
+ import{r as e}from"./chunk-DHbaKqs-.mjs";import{t}from"./env-api-keys-Cuz5irWW.mjs";import{o as n,r,t as i}from"./event-stream-B7Ei41Bu.mjs";import{n as a}from"./json-parse-BESd8UAM.mjs";import{n as o}from"./openai-C-rgGb7X.mjs";import{t as s}from"./headers-Bpsp70B9.mjs";import{a as c,i as l,r as u,t as d}from"./transform-messages-BTA3xbAI.mjs";import{n as f,t as p}from"./github-copilot-headers-BfhryVuU.mjs";var m=e({convertMessages:()=>P,streamOpenAICompletions:()=>x,streamSimpleOpenAICompletions:()=>S});function h(e){for(let t of e)if(t.role===`toolResult`||t.role===`assistant`&&t.content.some(e=>e.type===`toolCall`))return!0;return!1}function g(e){return e.type===`text`}function _(e){return e.type===`thinking`}function v(e){return e.type===`toolCall`}function y(e){return e.type===`image`}function b(e){return e||(typeof process<`u`&&process.env.PI_CACHE_RETENTION===`long`?`long`:`short`)}const x=(e,n,r)=>{let o=new i;return(async()=>{let i={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let c=r?.apiKey||t(e.provider)||``,l=z(e),u=b(r?.cacheRetention),d=u===`none`?void 0:r?.sessionId,f=C(e,n,c,r?.headers,d,l),p=w(e,n,r,l,u),m=await r?.onPayload?.(p,e);m!==void 0&&(p=m);let{data:h,response:g}=await f.chat.completions.create(p,{signal:r?.signal}).withResponse();await r?.onResponse?.({status:g.status,headers:s(g.headers)},e),o.push({type:`start`,partial:i});let _=null,v=i.content,y=()=>v.length-1,x=e=>{e&&(e.type===`text`?o.push({type:`text_end`,contentIndex:y(),content:e.text,partial:i}):e.type===`thinking`?o.push({type:`thinking_end`,contentIndex:y(),content:e.thinking,partial:i}):e.type===`toolCall`&&(e.arguments=a(e.partialArgs),delete e.partialArgs,o.push({type:`toolcall_end`,contentIndex:y(),toolCall:e,partial:i})))};for await(let t of h){if(!t||typeof t!=`object`)continue;i.responseId||=t.id,t.usage&&(i.usage=I(t.usage,e));let n=Array.isArray(t.choices)?t.choices[0]:void 0;if(n){if(!t.usage&&n.usage&&(i.usage=I(n.usage,e)),n.finish_reason){let e=L(n.finish_reason);i.stopReason=e.stopReason,e.errorMessage&&(i.errorMessage=e.errorMessage)}if(n.delta){n.delta.content!==null&&n.delta.content!==void 0&&n.delta.content.length>0&&((!_||_.type!==`text`)&&(x(_),_={type:`text`,text:``},i.content.push(_),o.push({type:`text_start`,contentIndex:y(),partial:i})),_.type===`text`&&(_.text+=n.delta.content,o.push({type:`text_delta`,contentIndex:y(),delta:n.delta.content,partial:i})));let e=[`reasoning_content`,`reasoning`,`reasoning_text`],t=null;for(let r of e)if(n.delta[r]!==null&&n.delta[r]!==void 0&&n.delta[r].length>0&&!t){t=r;break}if(t&&((!_||_.type!==`thinking`)&&(x(_),_={type:`thinking`,thinking:``,thinkingSignature:t},i.content.push(_),o.push({type:`thinking_start`,contentIndex:y(),partial:i})),_.type===`thinking`)){let e=n.delta[t];_.thinking+=e,o.push({type:`thinking_delta`,contentIndex:y(),delta:e,partial:i})}if(n?.delta?.tool_calls){for(let e of n.delta.tool_calls)if((!_||_.type!==`toolCall`||e.id&&_.id!==e.id)&&(x(_),_={type:`toolCall`,id:e.id||``,name:e.function?.name||``,arguments:{},partialArgs:``},i.content.push(_),o.push({type:`toolcall_start`,contentIndex:y(),partial:i})),_.type===`toolCall`){e.id&&(_.id=e.id),e.function?.name&&(_.name=e.function.name);let t=``;e.function?.arguments&&(t=e.function.arguments,_.partialArgs+=e.function.arguments,_.arguments=a(_.partialArgs)),o.push({type:`toolcall_delta`,contentIndex:y(),delta:t,partial:i})}}let r=n.delta.reasoning_details;if(r&&Array.isArray(r)){for(let e of r)if(e.type===`reasoning.encrypted`&&e.id&&e.data){let t=i.content.find(t=>t.type===`toolCall`&&t.id===e.id);t&&(t.thoughtSignature=JSON.stringify(e))}}}}}if(x(_),r?.signal?.aborted||i.stopReason===`aborted`)throw Error(`Request was aborted`);if(i.stopReason===`error`)throw Error(i.errorMessage||`Provider returned an error stop reason`);o.push({type:`done`,reason:i.stopReason,message:i}),o.end()}catch(e){for(let e of i.content)delete e.index,delete e.partialArgs;i.stopReason=r?.signal?.aborted?`aborted`:`error`,i.errorMessage=e instanceof Error?e.message:JSON.stringify(e);let t=e?.error?.metadata?.raw;t&&(i.errorMessage+=`\n${t}`),o.push({type:`error`,reason:i.stopReason,error:i}),o.end()}})(),o},S=(e,r,i)=>{let a=i?.apiKey||t(e.provider);if(!a)throw Error(`No API key for provider: ${e.provider}`);let o=u(e,i,a),s=n(e)?i?.reasoning:l(i?.reasoning),c=i?.toolChoice;return x(e,r,{...o,reasoningEffort:s,toolChoice:c})};function C(e,t,n,r,i,a=z(e)){if(!n){if(!process.env.OPENAI_API_KEY)throw Error(`OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.`);n=process.env.OPENAI_API_KEY}let s={...e.headers};if(e.provider===`github-copilot`){let e=f(t.messages),n=p({messages:t.messages,hasImages:e});Object.assign(s,n)}return i&&a.sendSessionAffinityHeaders&&(s.session_id=i,s[`x-client-request-id`]=i,s[`x-session-affinity`]=i),r&&Object.assign(s,r),new o({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:s})}function w(e,t,n,r=z(e),i=b(n?.cacheRetention)){let a=P(e,t,r),o=E(e,r,i),s={model:e.id,messages:a,stream:!0,prompt_cache_key:e.baseUrl.includes(`api.openai.com`)&&i!==`none`?n?.sessionId:void 0,prompt_cache_retention:e.baseUrl.includes(`api.openai.com`)&&i===`long`?`24h`:void 0};if(r.supportsUsageInStreaming!==!1&&(s.stream_options={include_usage:!0}),r.supportsStore&&(s.store=!1),n?.maxTokens&&(r.maxTokensField===`max_tokens`?s.max_tokens=n.maxTokens:s.max_completion_tokens=n.maxTokens),n?.temperature!==void 0&&(s.temperature=n.temperature),t.tools?(s.tools=F(t.tools,r),r.zaiToolStream&&(s.tool_stream=!0)):h(t.messages)&&(s.tools=[]),o&&D(a,s.tools,o),n?.toolChoice&&(s.tool_choice=n.toolChoice),r.thinkingFormat===`zai`&&e.reasoning)s.enable_thinking=!!n?.reasoningEffort;else if(r.thinkingFormat===`qwen`&&e.reasoning)s.enable_thinking=!!n?.reasoningEffort;else if(r.thinkingFormat===`qwen-chat-template`&&e.reasoning)s.chat_template_kwargs={enable_thinking:!!n?.reasoningEffort,preserve_thinking:!0};else if(r.thinkingFormat===`openrouter`&&e.reasoning){let e=s;n?.reasoningEffort?e.reasoning={effort:T(n.reasoningEffort,r.reasoningEffortMap)}:e.reasoning={effort:`none`}}else n?.reasoningEffort&&e.reasoning&&r.supportsReasoningEffort&&(s.reasoning_effort=T(n.reasoningEffort,r.reasoningEffortMap));if(e.baseUrl.includes(`openrouter.ai`)&&e.compat?.openRouterRouting&&(s.provider=e.compat.openRouterRouting),e.baseUrl.includes(`ai-gateway.vercel.sh`)&&e.compat?.vercelGatewayRouting){let t=e.compat.vercelGatewayRouting;if(t.only||t.order){let e={};t.only&&(e.only=t.only),t.order&&(e.order=t.order),s.providerOptions={gateway:e}}}return s}function T(e,t){return t[e]??e}function E(e,t,n){if(t.cacheControlFormat!==`anthropic`||n===`none`)return;let r=n===`long`&&e.baseUrl.includes(`api.anthropic.com`)?`1h`:void 0;return{type:`ephemeral`,...r?{ttl:r}:{}}}function D(e,t,n){O(e,n),A(t,n),k(e,n)}function O(e,t){for(let n of e)if(n.role===`system`||n.role===`developer`){j(n,t);return}}function k(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if((r.role===`user`||r.role===`assistant`)&&M(r,t))return}}function A(e,t){if(!e||e.length===0)return;let n=e[e.length-1];n.cache_control=t}function j(e,t){return N(e,t)}function M(e,t){return e.role===`user`||e.role===`assistant`?N(e,t):!1}function N(e,t){let n=e.content;if(typeof n==`string`)return n.length===0?!1:(e.content=[{type:`text`,text:n,cache_control:t}],!0);if(!Array.isArray(n))return!1;for(let e=n.length-1;e>=0;e--){let r=n[e];if(r?.type===`text`){let e=r;return e.cache_control=t,!0}}return!1}function P(e,t,n){let r=[],i=t=>{if(t.includes(`|`)){let[e]=t.split(`|`);return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,40)}return e.provider===`openai`&&t.length>40?t.slice(0,40):t},a=d(t.messages,e,e=>i(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:c(t.systemPrompt)})}let o=null;for(let t=0;t<a.length;t++){let i=a[t];if(n.requiresAssistantAfterToolResult&&o===`toolResult`&&i.role===`user`&&r.push({role:`assistant`,content:`I have processed the tool results.`}),i.role===`user`)if(typeof i.content==`string`)r.push({role:`user`,content:c(i.content)});else{let e=i.content.map(e=>e.type===`text`?{type:`text`,text:c(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}});if(e.length===0)continue;r.push({role:`user`,content:e})}else if(i.role===`assistant`){let e={role:`assistant`,content:n.requiresAssistantAfterToolResult?``:null},t=i.content.filter(g).filter(e=>e.text.trim().length>0).map(e=>({type:`text`,text:c(e.text)})),a=t.map(e=>e.text).join(``),o=i.content.filter(_).filter(e=>e.thinking.trim().length>0);if(o.length>0)if(n.requiresThinkingAsText)e.content=[{type:`text`,text:o.map(e=>c(e.thinking)).join(`
2
+
3
+ `)},...t];else{a.length>0&&(e.content=a);let t=o[0].thinkingSignature;t&&t.length>0&&(e[t]=o.map(e=>e.thinking).join(`
4
+ `))}else a.length>0&&(e.content=a);let s=i.content.filter(v);if(s.length>0){e.tool_calls=s.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}));let t=s.filter(e=>e.thoughtSignature).map(e=>{try{return JSON.parse(e.thoughtSignature)}catch{return null}}).filter(Boolean);t.length>0&&(e.reasoning_details=t)}let l=e.content;if(!(l!=null&&l.length>0)&&!e.tool_calls)continue;r.push(e)}else if(i.role===`toolResult`){let i=[],s=t;for(;s<a.length&&a[s].role===`toolResult`;s++){let t=a[s],o=t.content.filter(g).map(e=>e.text).join(`
5
+ `),l=t.content.some(e=>e.type===`image`),u={role:`tool`,content:c(o.length>0?o:`(see attached image)`),tool_call_id:t.toolCallId};if(n.requiresToolResultName&&t.toolName&&(u.name=t.toolName),r.push(u),l&&e.input.includes(`image`))for(let e of t.content)y(e)&&i.push({type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}})}t=s-1,i.length>0?(n.requiresAssistantAfterToolResult&&r.push({role:`assistant`,content:`I have processed the tool results.`}),r.push({role:`user`,content:[{type:`text`,text:`Attached image(s) from tool result:`},...i]}),o=`user`):o=`toolResult`;continue}o=i.role}return r}function F(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function I(e,t){let n=e.prompt_tokens||0,i=e.prompt_tokens_details?.cached_tokens||0,a=e.prompt_tokens_details?.cache_write_tokens||0,o=e.completion_tokens_details?.reasoning_tokens||0,s=a>0?Math.max(0,i-a):i,c=Math.max(0,n-s-a),l=(e.completion_tokens||0)+o,u={input:c,output:l,cacheRead:s,cacheWrite:a,totalTokens:c+l+s+a,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return r(t,u),u}function L(e){if(e===null)return{stopReason:`stop`};switch(e){case`stop`:case`end`:return{stopReason:`stop`};case`length`:return{stopReason:`length`};case`function_call`:case`tool_calls`:return{stopReason:`toolUse`};case`content_filter`:return{stopReason:`error`,errorMessage:`Provider finish_reason: content_filter`};case`network_error`:return{stopReason:`error`,errorMessage:`Provider finish_reason: network_error`};default:return{stopReason:`error`,errorMessage:`Provider finish_reason: ${e}`}}}function R(e){let t=e.provider,n=e.baseUrl,r=t===`zai`||n.includes(`api.z.ai`),i=t===`cerebras`||n.includes(`cerebras.ai`)||t===`xai`||n.includes(`api.x.ai`)||n.includes(`chutes.ai`)||n.includes(`deepseek.com`)||r||t===`opencode`||n.includes(`opencode.ai`),a=n.includes(`chutes.ai`),o=t===`xai`||n.includes(`api.x.ai`),s=t===`groq`||n.includes(`groq.com`),c=t===`openrouter`&&e.id.startsWith(`anthropic/`)?`anthropic`:void 0,l=s&&e.id===`qwen/qwen3-32b`?{minimal:`default`,low:`default`,medium:`default`,high:`default`,xhigh:`default`}:{};return{supportsStore:!i,supportsDeveloperRole:!i,supportsReasoningEffort:!o&&!r,reasoningEffortMap:l,supportsUsageInStreaming:!0,maxTokensField:a?`max_tokens`:`max_completion_tokens`,requiresToolResultName:!1,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:!1,thinkingFormat:r?`zai`:t===`openrouter`||n.includes(`openrouter.ai`)?`openrouter`:`openai`,openRouterRouting:{},vercelGatewayRouting:{},zaiToolStream:!1,supportsStrictMode:!0,cacheControlFormat:c,sendSessionAffinityHeaders:!1}}function z(e){let t=R(e);return e.compat?{supportsStore:e.compat.supportsStore??t.supportsStore,supportsDeveloperRole:e.compat.supportsDeveloperRole??t.supportsDeveloperRole,supportsReasoningEffort:e.compat.supportsReasoningEffort??t.supportsReasoningEffort,reasoningEffortMap:e.compat.reasoningEffortMap??t.reasoningEffortMap,supportsUsageInStreaming:e.compat.supportsUsageInStreaming??t.supportsUsageInStreaming,maxTokensField:e.compat.maxTokensField??t.maxTokensField,requiresToolResultName:e.compat.requiresToolResultName??t.requiresToolResultName,requiresAssistantAfterToolResult:e.compat.requiresAssistantAfterToolResult??t.requiresAssistantAfterToolResult,requiresThinkingAsText:e.compat.requiresThinkingAsText??t.requiresThinkingAsText,thinkingFormat:e.compat.thinkingFormat??t.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??t.vercelGatewayRouting,zaiToolStream:e.compat.zaiToolStream??t.zaiToolStream,supportsStrictMode:e.compat.supportsStrictMode??t.supportsStrictMode,cacheControlFormat:e.compat.cacheControlFormat??t.cacheControlFormat,sendSessionAffinityHeaders:e.compat.sendSessionAffinityHeaders??t.sendSessionAffinityHeaders}:t}export{m as n,P as t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./env-api-keys-Cuz5irWW.mjs";import{o as t,t as n}from"./event-stream-B7Ei41Bu.mjs";import{n as r}from"./openai-C-rgGb7X.mjs";import{t as i}from"./headers-Bpsp70B9.mjs";import{i as a,r as o}from"./transform-messages-BTA3xbAI.mjs";import{n as s,t as c}from"./github-copilot-headers-BfhryVuU.mjs";import{n as l,r as u,t as d}from"./openai-responses-shared-DqW1JSux.mjs";const f=new Set([`openai`,`openai-codex`,`opencode`]);function p(e){return e||(typeof process<`u`&&process.env.PI_CACHE_RETENTION===`long`?`long`:`short`)}function m(e,t){if(t===`long`&&e.includes(`api.openai.com`))return`24h`}const h=(t,r,a)=>{let o=new n;return(async()=>{let n={role:`assistant`,content:[],api:t.api,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let s=a?.apiKey||e(t.provider)||``,c=p(a?.cacheRetention)===`none`?void 0:a?.sessionId,l=_(t,r,s,a?.headers,c),d=v(t,r,a),f=await a?.onPayload?.(d,t);f!==void 0&&(d=f);let{data:m,response:h}=await l.responses.create(d,a?.signal?{signal:a.signal}:void 0).withResponse();if(await a?.onResponse?.({status:h.status,headers:i(h.headers)},t),o.push({type:`start`,partial:n}),await u(m,n,o,t,{serviceTier:a?.serviceTier,applyServiceTierPricing:b}),a?.signal?.aborted)throw Error(`Request was aborted`);if(n.stopReason===`aborted`||n.stopReason===`error`)throw Error(`An unknown error occurred`);o.push({type:`done`,reason:n.stopReason,message:n}),o.end()}catch(e){for(let e of n.content)delete e.index,delete e.partialJson;n.stopReason=a?.signal?.aborted?`aborted`:`error`,n.errorMessage=e instanceof Error?e.message:JSON.stringify(e),o.push({type:`error`,reason:n.stopReason,error:n}),o.end()}})(),o},g=(n,r,i)=>{let s=i?.apiKey||e(n.provider);if(!s)throw Error(`No API key for provider: ${n.provider}`);let c=o(n,i,s),l=t(n)?i?.reasoning:a(i?.reasoning);return h(n,r,{...c,reasoningEffort:l})};function _(e,t,n,i,a){if(!n){if(!process.env.OPENAI_API_KEY)throw Error(`OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.`);n=process.env.OPENAI_API_KEY}let o={...e.headers};if(e.provider===`github-copilot`){let e=s(t.messages),n=c({messages:t.messages,hasImages:e});Object.assign(o,n)}return a&&(o.session_id=a,o[`x-client-request-id`]=a),i&&Object.assign(o,i),new r({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:o})}function v(e,t,n){let r=d(e,t,f),i=p(n?.cacheRetention),a={model:e.id,input:r,stream:!0,prompt_cache_key:i===`none`?void 0:n?.sessionId,prompt_cache_retention:m(e.baseUrl,i),store:!1};return n?.maxTokens&&(a.max_output_tokens=n?.maxTokens),n?.temperature!==void 0&&(a.temperature=n?.temperature),n?.serviceTier!==void 0&&(a.service_tier=n.serviceTier),t.tools&&(a.tools=l(t.tools)),e.reasoning&&(n?.reasoningEffort||n?.reasoningSummary?(a.reasoning={effort:n?.reasoningEffort||`medium`,summary:n?.reasoningSummary||`auto`},a.include=[`reasoning.encrypted_content`]):e.provider!==`github-copilot`&&(a.reasoning={effort:`none`})),a}function y(e){switch(e){case`flex`:return .5;case`priority`:return 2;default:return 1}}function b(e,t){let n=y(t);n!==1&&(e.cost.input*=n,e.cost.output*=n,e.cost.cacheRead*=n,e.cost.cacheWrite*=n,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}export{h as streamOpenAIResponses,g as streamSimpleOpenAIResponses};
@@ -0,0 +1,10 @@
1
+ import{r as e}from"./event-stream-B7Ei41Bu.mjs";import{n as t}from"./json-parse-BESd8UAM.mjs";import{a as n,t as r}from"./transform-messages-BTA3xbAI.mjs";import{t as i}from"./hash-Dw-N8Y9l.mjs";function a(e,t){let n={v:1,id:e};return t&&(n.phase=t),JSON.stringify(n)}function o(e){if(e){if(e.startsWith(`{`))try{let t=JSON.parse(e);if(t.v===1&&typeof t.id==`string`)return t.phase===`commentary`||t.phase===`final_answer`?{id:t.id,phase:t.phase}:{id:t.id}}catch{}return{id:e}}}function s(e,t,a,s){let c=[],l=e=>{let t=e.replace(/[^a-zA-Z0-9_-]/g,`_`);return(t.length>64?t.slice(0,64):t).replace(/_+$/,``)},u=e=>{let t=`fc_${i(e)}`;return t.length>64?t.slice(0,64):t},d=r(t.messages,e,(t,n,r)=>{if(!a.has(e.provider)||!t.includes(`|`))return l(t);let[i,o]=t.split(`|`),s=l(i),c=r.provider!==e.provider||r.api!==e.api?u(o):l(o);return c.startsWith(`fc_`)||(c=l(`fc_${c}`)),`${s}|${c}`});if((s?.includeSystemPrompt??!0)&&t.systemPrompt){let r=e.reasoning?`developer`:`system`;c.push({role:r,content:n(t.systemPrompt)})}let f=0;for(let t of d){if(t.role===`user`)if(typeof t.content==`string`)c.push({role:`user`,content:[{type:`input_text`,text:n(t.content)}]});else{let e=t.content.map(e=>e.type===`text`?{type:`input_text`,text:n(e.text)}:{type:`input_image`,detail:`auto`,image_url:`data:${e.mimeType};base64,${e.data}`});if(e.length===0)continue;c.push({role:`user`,content:e})}else if(t.role===`assistant`){let r=[],a=t,s=a.model!==e.id&&a.provider===e.provider&&a.api===e.api;for(let e of t.content)if(e.type===`thinking`){if(e.thinkingSignature){let t=JSON.parse(e.thinkingSignature);r.push(t)}}else if(e.type===`text`){let t=e,a=o(t.textSignature),s=a?.id;s?s.length>64&&(s=`msg_${i(s)}`):s=`msg_${f}`,r.push({type:`message`,role:`assistant`,content:[{type:`output_text`,text:n(t.text),annotations:[]}],status:`completed`,id:s,phase:a?.phase})}else if(e.type===`toolCall`){let t=e,[n,i]=t.id.split(`|`),a=i;s&&a?.startsWith(`fc_`)&&(a=void 0),r.push({type:`function_call`,id:a,call_id:n,name:t.name,arguments:JSON.stringify(t.arguments)})}if(r.length===0)continue;c.push(...r)}else if(t.role===`toolResult`){let r=t.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
2
+ `),i=t.content.some(e=>e.type===`image`),a=r.length>0,[o]=t.toolCallId.split(`|`),s;if(i&&e.input.includes(`image`)){let e=[];a&&e.push({type:`input_text`,text:n(r)});for(let n of t.content)n.type===`image`&&e.push({type:`input_image`,detail:`auto`,image_url:`data:${n.mimeType};base64,${n.data}`});s=e}else s=n(a?r:`(see attached image)`);c.push({type:`function_call_output`,call_id:o,output:s})}f++}return c}function c(e,t){let n=t?.strict===void 0?!1:t.strict;return e.map(e=>({type:`function`,name:e.name,description:e.description,parameters:e.parameters,strict:n}))}async function l(n,r,i,o,s){let c=null,l=null,d=r.content,f=()=>d.length-1;for await(let d of n)if(d.type===`response.created`)r.responseId=d.response.id;else if(d.type===`response.output_item.added`){let e=d.item;e.type===`reasoning`?(c=e,l={type:`thinking`,thinking:``},r.content.push(l),i.push({type:`thinking_start`,contentIndex:f(),partial:r})):e.type===`message`?(c=e,l={type:`text`,text:``},r.content.push(l),i.push({type:`text_start`,contentIndex:f(),partial:r})):e.type===`function_call`&&(c=e,l={type:`toolCall`,id:`${e.call_id}|${e.id}`,name:e.name,arguments:{},partialJson:e.arguments||``},r.content.push(l),i.push({type:`toolcall_start`,contentIndex:f(),partial:r}))}else if(d.type===`response.reasoning_summary_part.added`)c&&c.type===`reasoning`&&(c.summary=c.summary||[],c.summary.push(d.part));else if(d.type===`response.reasoning_summary_text.delta`){if(c?.type===`reasoning`&&l?.type===`thinking`){c.summary=c.summary||[];let e=c.summary[c.summary.length-1];e&&(l.thinking+=d.delta,e.text+=d.delta,i.push({type:`thinking_delta`,contentIndex:f(),delta:d.delta,partial:r}))}}else if(d.type===`response.reasoning_summary_part.done`){if(c?.type===`reasoning`&&l?.type===`thinking`){c.summary=c.summary||[];let e=c.summary[c.summary.length-1];e&&(l.thinking+=`
3
+
4
+ `,e.text+=`
5
+
6
+ `,i.push({type:`thinking_delta`,contentIndex:f(),delta:`
7
+
8
+ `,partial:r}))}}else if(d.type===`response.content_part.added`)c?.type===`message`&&(c.content=c.content||[],(d.part.type===`output_text`||d.part.type===`refusal`)&&c.content.push(d.part));else if(d.type===`response.output_text.delta`){if(c?.type===`message`&&l?.type===`text`){if(!c.content||c.content.length===0)continue;let e=c.content[c.content.length-1];e?.type===`output_text`&&(l.text+=d.delta,e.text+=d.delta,i.push({type:`text_delta`,contentIndex:f(),delta:d.delta,partial:r}))}}else if(d.type===`response.refusal.delta`){if(c?.type===`message`&&l?.type===`text`){if(!c.content||c.content.length===0)continue;let e=c.content[c.content.length-1];e?.type===`refusal`&&(l.text+=d.delta,e.refusal+=d.delta,i.push({type:`text_delta`,contentIndex:f(),delta:d.delta,partial:r}))}}else if(d.type===`response.function_call_arguments.delta`)c?.type===`function_call`&&l?.type===`toolCall`&&(l.partialJson+=d.delta,l.arguments=t(l.partialJson),i.push({type:`toolcall_delta`,contentIndex:f(),delta:d.delta,partial:r}));else if(d.type===`response.function_call_arguments.done`){if(c?.type===`function_call`&&l?.type===`toolCall`){let e=l.partialJson;if(l.partialJson=d.arguments,l.arguments=t(l.partialJson),d.arguments.startsWith(e)){let t=d.arguments.slice(e.length);t.length>0&&i.push({type:`toolcall_delta`,contentIndex:f(),delta:t,partial:r})}}}else if(d.type===`response.output_item.done`){let e=d.item;if(e.type===`reasoning`&&l?.type===`thinking`)l.thinking=e.summary?.map(e=>e.text).join(`
9
+
10
+ `)||``,l.thinkingSignature=JSON.stringify(e),i.push({type:`thinking_end`,contentIndex:f(),content:l.thinking,partial:r}),l=null;else if(e.type===`message`&&l?.type===`text`)l.text=e.content.map(e=>e.type===`output_text`?e.text:e.refusal).join(``),l.textSignature=a(e.id,e.phase??void 0),i.push({type:`text_end`,contentIndex:f(),content:l.text,partial:r}),l=null;else if(e.type===`function_call`){let n=l?.type===`toolCall`&&l.partialJson?t(l.partialJson):t(e.arguments||`{}`),a;l?.type===`toolCall`?(l.arguments=n,delete l.partialJson,a=l):a={type:`toolCall`,id:`${e.call_id}|${e.id}`,name:e.name,arguments:n},l=null,i.push({type:`toolcall_end`,contentIndex:f(),toolCall:a,partial:r})}}else if(d.type===`response.completed`){let t=d.response;if(t?.id&&(r.responseId=t.id),t?.usage){let e=t.usage.input_tokens_details?.cached_tokens||0;r.usage={input:(t.usage.input_tokens||0)-e,output:t.usage.output_tokens||0,cacheRead:e,cacheWrite:0,totalTokens:t.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(e(o,r.usage),s?.applyServiceTierPricing){let e=s.resolveServiceTier?s.resolveServiceTier(t?.service_tier,s.serviceTier):t?.service_tier??s.serviceTier;s.applyServiceTierPricing(r.usage,e)}r.stopReason=u(t?.status),r.content.some(e=>e.type===`toolCall`)&&r.stopReason===`stop`&&(r.stopReason=`toolUse`)}else if(d.type===`error`)throw Error(`Error Code ${d.code}: ${d.message}`||`Unknown error`);else if(d.type===`response.failed`){let e=d.response?.error,t=d.response?.incomplete_details,n=e?`${e.code||`unknown`}: ${e.message||`no message`}`:t?.reason?`incomplete: ${t.reason}`:`Unknown error (no error details in response)`;throw Error(n)}}function u(e){if(!e)return`stop`;switch(e){case`completed`:return`stop`;case`incomplete`:return`length`;case`failed`:case`cancelled`:return`error`;case`in_progress`:case`queued`:return`stop`;default:throw Error(`Unhandled stop reason: ${e}`)}}export{c as n,l as r,s as t};
@@ -0,0 +1 @@
1
+ import{i as e,o as t,t as n}from"./home-dir-C44RaPME-B5iLWwCq.mjs";import{o as r}from"./paths-D92DjaZ--DdtJ-zYp.mjs";import{i}from"./session-key-Cn2QoOyX-QZeYmbxd.mjs";import a from"node:fs";import o from"node:path";import s from"node:os";const c=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(?:\.\d{3})?Z$/,l=/^sessions\.json\.bak\.\d+$/;function u(e,t){let n=`.${t}.`,r=e.lastIndexOf(n);if(r<0)return!1;let i=e.slice(r+n.length);return c.test(i)}function d(e){return l.test(e)?!0:u(e,`deleted`)||u(e,`reset`)||u(e,`bak`)}function f(e){return e===`sessions.json`||!e.endsWith(`.jsonl`)?!1:!d(e)}function p(e=Date.now()){return new Date(e).toISOString().replaceAll(`:`,`-`)}function m(e){let[t,n]=e.split(`T`);return!t||!n?e:`${t}T${n.replace(/-/g,`:`)}`}function h(e,t){let n=`.${t}.`,r=e.lastIndexOf(n);if(r<0)return null;let i=e.slice(r+n.length);if(!i||!c.test(i))return null;let a=Date.parse(m(i));return Number.isNaN(a)?null:a}function g(t,n=process.env,a=()=>e(n,s.homedir)){let c=r(n,a),l=i(t??`main`);return o.join(c,`agents`,l,`sessions`)}function _(e){return o.join(g(e),`sessions.json`)}const v=/^[a-z0-9][a-z0-9._-]{0,127}$/i;function y(e){let t=e.trim();if(!v.test(t))throw Error(`Invalid session ID: ${e}`);return t}function b(e){let t=e?.sessionsDir?.trim();return t?o.resolve(t):g(e?.agentId)}function x(e,t){let n=E(o.resolve(e))??o.resolve(e),r=E(t)??t,i=o.relative(n,r);if(!(!i||i.startsWith(`..`)||o.isAbsolute(i)))return o.resolve(n,i)}function S(e,t){let n=o.resolve(e);if(o.basename(n)!==`sessions`)return;let r=o.dirname(n),a=o.dirname(r);if(o.basename(a)!==`agents`)return;let s=o.dirname(a);return o.join(s,`agents`,i(t),`sessions`)}function C(e){let t=o.normalize(o.resolve(e)).split(o.sep).filter(Boolean),n=t.lastIndexOf(`sessions`);return n<2||t[n-2]!==`agents`?null:{parts:t,sessionsIndex:n}}function w(e){let t=C(e);if(!t)return;let{parts:n,sessionsIndex:r}=t;return n[r-1]||void 0}function T(e,n){let r=C(e);if(!r)return;let{parts:a,sessionsIndex:s}=r,c=a[s-1];if(!c)return;let l=i(c);if(l!==t(c)||l!==i(n))return;let u=a.slice(s+1);if(u.length!==1)return;let d=u[0];if(!(!d||d===`.`||d===`..`))return o.normalize(o.resolve(e))}function E(e){try{return a.realpathSync(e)}catch{return}}function D(e,t,n){let r=t.trim();if(!r)throw Error(`Session file path must not be empty`);let a=o.resolve(e),s=E(a)??a,c=o.isAbsolute(r)?E(r)??r:r,l=o.isAbsolute(c)?o.relative(s,c):c;if(l.startsWith(`..`)&&o.isAbsolute(c)){let e=e=>{let t=i(e),n=S(s,t);if(n){let e=x(n,c);if(e)return e}return x(g(t),c)},t=n?.agentId?.trim();if(t){let n=e(t);if(n)return n}let r=w(c);if(r){let t=e(r);if(t)return t;let n=T(c,r);if(n)return n}}if(!l||l.startsWith(`..`)||o.isAbsolute(l))throw Error(`Session file path must be within sessions directory`);return o.resolve(s,l)}function O(e,t,n){let r=y(e),i=typeof n==`string`?encodeURIComponent(n):typeof n==`number`?String(n):void 0;return D(t,i===void 0?`${r}.jsonl`:`${r}-topic-${i}.jsonl`)}function k(e,t,n){return O(e,g(t),n)}function A(e,t,n){let r=b(n),i=t?.sessionFile?.trim();if(i)try{return D(r,i,{agentId:n?.agentId})}catch{}return O(e,r)}function j(t,r){let a=i(r?.agentId??`main`),c=r?.env??process.env,l=()=>e(c,s.homedir);if(!t)return o.join(g(a,c,l),`sessions.json`);if(t.includes(`{agentId}`)){let r=t.replaceAll(`{agentId}`,a);return r.startsWith(`~`)?o.resolve(n(r,{home:e(c,l),env:c,homedir:l})):o.resolve(r)}return t.startsWith(`~`)?o.resolve(n(t,{home:e(c,l),env:c,homedir:l})):o.resolve(t)}export{j as a,d as c,O as i,h as l,A as n,p as o,k as r,f as s,_ as t};
@@ -0,0 +1 @@
1
+ import{i as e,r as t}from"./home-dir-C44RaPME-B5iLWwCq.mjs";import n from"node:fs";import r from"node:path";import i from"node:os";const a=new Set([`__proto__`,`prototype`,`constructor`]);function o(e){return a.has(e)}function s(e=process.env){return e.OPENCLAW_NIX_MODE===`1`}s();const c=[`.clawdbot`],l=`openclaw.json`,u=[`clawdbot.json`];function d(){return e(process.env,i.homedir)}function f(t){return()=>e(t,i.homedir)}function p(e=d){return c.map(t=>r.join(e(),t))}function m(e=d){return r.join(e(),`.openclaw`)}function h(t=process.env,r=f(t)){let i=()=>e(t,r),a=t.OPENCLAW_STATE_DIR?.trim();if(a)return g(a,t,i);let o=m(i);if(t.OPENCLAW_TEST_FAST===`1`)return o;let s=p(i);return n.existsSync(o)?o:s.find(e=>{try{return n.existsSync(e)}catch{return!1}})||o}function g(e,n=process.env,r=f(n)){return t(e,{env:n,homedir:r})}const _=h();function v(e=process.env,t=h(e,f(e))){let n=e.OPENCLAW_CONFIG_PATH?.trim();return n?g(n,e,f(e)):r.join(t,l)}function y(e=process.env,t=f(e)){return e.OPENCLAW_TEST_FAST===`1`?v(e,h(e,t)):x(e,t).find(e=>{try{return n.existsSync(e)}catch{return!1}})||v(e,h(e,t))}function b(e=process.env,t=h(e,f(e)),i=f(e)){let a=e.OPENCLAW_CONFIG_PATH?.trim();if(a)return g(a,e,i);if(e.OPENCLAW_TEST_FAST===`1`)return r.join(t,l);let o=e.OPENCLAW_STATE_DIR?.trim(),s=[r.join(t,l),...u.map(e=>r.join(t,e))].find(e=>{try{return n.existsSync(e)}catch{return!1}});if(s)return s;if(o)return r.join(t,l);let c=h(e,i);return r.resolve(t)===r.resolve(c)?y(e,i):r.join(t,l)}y();function x(t=process.env,n=f(t)){let i=()=>e(t,n),a=t.OPENCLAW_CONFIG_PATH?.trim();if(a)return[g(a,t,i)];let o=[],s=t.OPENCLAW_STATE_DIR?.trim();if(s){let e=g(s,t,i);o.push(r.join(e,l)),o.push(...u.map(t=>r.join(e,t)))}let c=[m(i),...p(i)];for(let e of c)o.push(r.join(e,l)),o.push(...u.map(t=>r.join(e,t)));return o}const S=18789;function C(e=process.env,t=h(e,f(e))){let n=e.OPENCLAW_OAUTH_DIR?.trim();return n?g(n,e,f(e)):r.join(t,`credentials`)}function w(e=process.env,t=h(e,f(e))){return r.join(C(e,t),`oauth.json`)}function T(e){let t=e?.trim();if(!t)return null;if(/^\d+$/.test(t)){let e=Number.parseInt(t,10);return Number.isFinite(e)&&e>0?e:null}let n=t.match(/^\[[^\]]+\]:(\d+)$/);if(n?.[1]){let e=Number.parseInt(n[1],10);return Number.isFinite(e)&&e>0?e:null}let r=t.indexOf(`:`),i=t.lastIndexOf(`:`);if(r<=0||r!==i)return null;let a=t.slice(r+1);if(!/^\d+$/.test(a))return null;let o=Number.parseInt(a,10);return Number.isFinite(o)&&o>0?o:null}function E(e,t=process.env){let n=t.OPENCLAW_GATEWAY_PORT?.trim(),r=T(n);if(r!==null)return r;let i=e?.gateway?.port;return typeof i==`number`&&Number.isFinite(i)&&i>0?i:S}export{w as a,E as i,_ as n,h as o,b as r,o as s,S as t};
@@ -0,0 +1 @@
1
+ import{c as e}from"./home-dir-C44RaPME-B5iLWwCq.mjs";import{s as t}from"./bundled-dir-U738ay4K-BxbzrJOo.mjs";import{l as n}from"./bundled-compat-BpaDaAAu-DJtrIX6i.mjs";import{o as r}from"./manifest-registry-_hxKCS2K-OL8KK_o4.mjs";import{r as i}from"./runtime-state-IBOIXKOx-Cw1GA1td.mjs";import{R as a,a as o,i as s,v as c}from"./provider-runtime-CT50mNIX-DImw7ZZu.mjs";import{n as l,r as u,t as d}from"./dist-J5UB83Ws.mjs";import{g as f,l as p,t as m}from"./model-auth-env-oyg2Hexc-DJbt9J3o.mjs";import{n as h}from"./provider-model-compat-CFqcq0it-BUwZENrz.mjs";import g from"node:fs";import _ from"node:path";function v(e){let t=new Set,r=[];for(let i of e){let e=i.trim(),a=n(e);!e||t.has(a)||(t.add(a),r.push(e))}return r}function y(){return v(r({cache:!0}).plugins.flatMap(e=>e.syntheticAuthRefs??[]))}function b(){let e=i()?.activeRegistry;return e?v([...(e.providers??[]).filter(e=>`resolveSyntheticAuth`in e.provider&&typeof e.provider.resolveSyntheticAuth==`function`).map(e=>e.provider.id),...(e.cliBackends??[]).filter(e=>`resolveSyntheticAuth`in e.backend&&typeof e.backend.resolveSyntheticAuth==`function`).map(e=>e.backend.id)]):y()}function x(t){if(t.type===`api_key`){let n=e(t.key)??``;return n?{type:`api_key`,key:n}:null}if(t.type===`token`){let n=e(t.token)??``;return!n||typeof t.expires==`number`&&Number.isFinite(t.expires)&&Date.now()>=t.expires?null:{type:`api_key`,key:n}}if(t.type===`oauth`){let n=e(t.access)??``,r=e(t.refresh)??``;return!n||!r||!Number.isFinite(t.expires)||t.expires<=0?null:{type:`oauth`,access:n,refresh:r,expires:t.expires}}return null}function S(e){let t={};for(let r of Object.values(e.profiles)){let e=n(r.provider??``);if(!e||t[e])continue;let i=x(r);i&&(t[e]=i)}return t}const C=l,w=d;function T(e){let t=JSON.stringify(e,null,2);return{withLock(e){let{result:n,next:r}=e(t);return typeof r==`string`&&(t=r),n}}}function E(e,n){if(!t(e)||typeof e.id!=`string`||typeof e.name!=`string`||typeof e.provider!=`string`)return e;let r=e,i=c({provider:r.provider,context:{provider:r.provider,modelId:r.id,model:r,agentDir:n}})??r,a=s({provider:r.provider,context:{provider:r.provider,modelId:r.id,model:i,agentDir:n}})??i,l=o({provider:r.provider,context:{provider:r.provider,modelId:r.id,model:a,agentDir:n}})??a;return!t(l)||typeof l.id!=`string`||typeof l.name!=`string`||typeof l.provider!=`string`||typeof l.api!=`string`?e:h(l)}function D(e,t){let n=w;return typeof n.create==`function`?n.create(e,t):new n(e,t)}function O(e,t,r,i){let a=D(e,t),o=a.getAll.bind(a),s=a.getAvailable.bind(a),c=a.find.bind(a),l=i?.providerFilter?n(i.providerFilter):``,u=e=>!l||n(e.provider)===l;return a.getAll=()=>o().filter(e=>u(e)).map(e=>E(e,r)),a.getAvailable=()=>s().filter(e=>u(e)).map(e=>E(e,r)),a.find=(e,t)=>E(c(e,t),r),a}function k(e){if(process.env.OPENCLAW_AUTH_STORE_READONLY===`1`||!g.existsSync(e))return;let n;try{n=JSON.parse(g.readFileSync(e,`utf8`))}catch{return}if(!t(n))return;let r=!1;for(let[e,i]of Object.entries(n))t(i)&&i.type===`api_key`&&(delete n[e],r=!0);if(r){if(Object.keys(n).length===0){g.rmSync(e,{force:!0});return}g.writeFileSync(e,`${JSON.stringify(n,null,2)}\n`,`utf8`),g.chmodSync(e,384)}}function A(e,t,n){let r=e;if(typeof r.inMemory==`function`)return r.inMemory(n);let i=e;if(typeof i.fromStorage==`function`){let e=u,t=typeof e==`function`?new e:T(n);return t.withLock(()=>({result:void 0,next:JSON.stringify(n,null,2)})),i.fromStorage(t)}let a=e,o=typeof a.create==`function`?a.create(t):new e(t);if(typeof o.setRuntimeApiKey==`function`)for(let[e,t]of Object.entries(n)){if(t.type===`api_key`){o.setRuntimeApiKey(e,t.key);continue}o.setRuntimeApiKey(e,t.access)}return o}function j(e,t=process.env){let n={...e};for(let e of Object.keys(p({env:t}))){if(n[e])continue;let r=m(e,t);r?.apiKey&&(n[e]={type:`api_key`,key:r.apiKey})}return n}function M(e){let t=j(S(f(e,{allowKeychainPrompt:!1})));for(let e of b()){if(t[e])continue;let n=a({provider:e,context:{config:void 0,provider:e,providerConfig:void 0}})?.apiKey?.trim();n&&(t[e]={type:`api_key`,key:n})}return t}function N(e){let t=M(e),n=_.join(e,`auth.json`);return k(n),A(C,n,t)}function P(e,t,n){return O(e,_.join(t,`models.json`),t,n)}export{P as a,k as c,N as i,w as n,E as o,j as r,M as s,C as t};
@@ -0,0 +1 @@
1
+ import{a as e,c as t,i as n,n as r,o as i,r as a,s as o,t as s}from"./pi-model-discovery-Bd0TWzo8-DvSM0eWu.mjs";export{s as AuthStorage,r as ModelRegistry,a as addEnvBackedPiCredentials,n as discoverAuthStorage,e as discoverModels,i as normalizeDiscoveredPiModel,o as resolvePiCredentialsForDiscovery,t as scrubLegacyStaticAuthJsonEntriesForDiscovery};
@@ -0,0 +1,2 @@
1
+ import{o as e}from"./bundled-dir-U738ay4K-BxbzrJOo.mjs";import{St as t}from"./bundled-compat-BpaDaAAu-DJtrIX6i.mjs";import{n,r}from"./diagnostic-ClMwNnUA-BMKvPQJT.mjs";import{createHash as i}from"node:crypto";const a=t(`agents/loop-detection`),o={enabled:!1,historySize:30,warningThreshold:10,unknownToolThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function s(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function c(e){let t=s(e?.warningThreshold,o.warningThreshold),n=s(e?.criticalThreshold,o.criticalThreshold),r=s(e?.globalCircuitBreakerThreshold,o.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??o.enabled,historySize:s(e?.historySize,o.historySize),warningThreshold:t,unknownToolThreshold:s(e?.unknownToolThreshold,o.unknownToolThreshold),criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??o.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??o.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??o.detectors.pingPong}}}function l(e,t){return`${e}:${d(t)}`}function u(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(u).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${u(t[e])}`).join(`,`)}}`}function d(e){let t=f(e);return i(`sha256`).update(t).digest(`hex`)}function f(e){try{return u(e)}catch{return e==null?`${e}`:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:e instanceof Error?`${e.name}:${e.message}`:Object.prototype.toString.call(e)}}function p(t,n){if(t===`command_status`)return!0;if(t!==`process`||!e(n))return!1;let r=n.action;return r===`poll`||r===`log`}function m(t){return!e(t)||!Array.isArray(t.content)?``:t.content.filter(t=>e(t)&&typeof t.type==`string`&&typeof t.text==`string`).map(e=>e.text).join(`
2
+ `).trim()}function h(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:u(e)}function g(e){let t=h(e).trim();if(!t)return;let n=(t.match(/unknown tool[:\s]+["']?([a-z0-9_.-]+)["']?/i)??t.match(/tool\s+["']?([a-z0-9_.-]+)["']?\s+(?:not found|is not available)/i))?.[1]?.trim();return n?n.toLowerCase():void 0}function _(t,n,r,i){if(i!==void 0){let e=g(i);return{resultHash:`error:${d(h(i))}`,unknownToolName:e}}if(!e(r))return{resultHash:r===void 0?void 0:d(r)};let a=e(r.details)?r.details:{},o=m(r);if(p(t,n)&&t===`process`&&e(n)){let e=n.action;if(e===`poll`)return{resultHash:d({action:e,status:a.status,exitCode:a.exitCode??null,exitSignal:a.exitSignal??null,aggregated:a.aggregated??null,text:o})};if(e===`log`)return{resultHash:d({action:e,status:a.status,totalLines:a.totalLines??null,totalChars:a.totalChars??null,truncated:a.truncated??null,exitCode:a.exitCode??null,exitSignal:a.exitSignal??null,text:o})}}return{resultHash:d({details:a,text:o})}}function v(e,t){let n=0,r;for(let i=e.length-1;i>=0;--i){let a=e[i];if(!a||a.toolName!==t||!a.unknownToolName)break;if(!r){r=a.unknownToolName,n=1;continue}if(a.unknownToolName!==r)break;n+=1}return{count:n,unknownToolName:r}}function y(e,t,n){let r=0,i;for(let a=e.length-1;a>=0;--a){let o=e[a];if(!(!o||o.toolName!==t||o.argsHash!==n)&&!(typeof o.resultHash!=`string`||!o.resultHash)){if(!i){i=o.resultHash,r=1;continue}if(o.resultHash!==i)break;r+=1}}return{count:r,latestResultHash:i}}function b(e,t){let n=e.at(-1);if(!n)return{count:0,noProgressEvidence:!1};let r,i;for(let t=e.length-2;t>=0;--t){let a=e[t];if(a&&a.argsHash!==n.argsHash){r=a.argsHash,i=a.toolName;break}}if(!r||!i)return{count:0,noProgressEvidence:!1};let a=0;for(let t=e.length-1;t>=0;--t){let i=e[t];if(!i)continue;let o=a%2==0?n.argsHash:r;if(i.argsHash!==o)break;a+=1}if(a<2||t!==r)return{count:0,noProgressEvidence:!1};let o=Math.max(0,e.length-a),s,c,l=!0;for(let t=o;t<e.length;t+=1){let i=e[t];if(i){if(!i.resultHash){l=!1;break}if(i.argsHash===n.argsHash){if(!s)s=i.resultHash;else if(s!==i.resultHash){l=!1;break}continue}if(i.argsHash===r){if(!c)c=i.resultHash;else if(c!==i.resultHash){l=!1;break}continue}l=!1;break}}return(!s||!c)&&(l=!1),{count:a+1,pairedToolName:n.toolName,pairedSignature:n.argsHash,noProgressEvidence:l}}function x(e,t){return[e,t].toSorted().join(`|`)}function S(e,t,n,r){let i=c(r);if(!i.enabled)return{stuck:!1};let o=e.toolCallHistory??[],s=l(t,n),u=v(o,t),d=y(o,t,s),f=d.count,m=p(t,n),h=b(o,s);if(u.count>=i.unknownToolThreshold)return{stuck:!0,level:`critical`,detector:`unknown_tool_repeat`,count:u.count,message:`CRITICAL: attempted unavailable tool ${u.unknownToolName??t} ${u.count} times. Stop retrying that missing tool and answer without it.`,warningKey:`unknown-tool:${t}:${u.unknownToolName??`unknown`}`};if(f>=i.globalCircuitBreakerThreshold)return a.error(`Global circuit breaker triggered: ${t} repeated ${f} times with no progress`),{stuck:!0,level:`critical`,detector:`global_circuit_breaker`,count:f,message:`CRITICAL: ${t} has repeated identical no-progress outcomes ${f} times. Session execution blocked by global circuit breaker to prevent runaway loops.`,warningKey:`global:${t}:${s}:${d.latestResultHash??`none`}`};if(m&&i.detectors.knownPollNoProgress&&f>=i.criticalThreshold)return a.error(`Critical polling loop detected: ${t} repeated ${f} times`),{stuck:!0,level:`critical`,detector:`known_poll_no_progress`,count:f,message:`CRITICAL: Called ${t} with identical arguments and no progress ${f} times. This appears to be a stuck polling loop. Session execution blocked to prevent resource waste.`,warningKey:`poll:${t}:${s}:${d.latestResultHash??`none`}`};if(m&&i.detectors.knownPollNoProgress&&f>=i.warningThreshold)return a.warn(`Polling loop warning: ${t} repeated ${f} times`),{stuck:!0,level:`warning`,detector:`known_poll_no_progress`,count:f,message:`WARNING: You have called ${t} ${f} times with identical arguments and no progress. Stop polling and either (1) increase wait time between checks, or (2) report the task as failed if the process is stuck.`,warningKey:`poll:${t}:${s}:${d.latestResultHash??`none`}`};let g=h.pairedSignature?`pingpong:${x(s,h.pairedSignature)}`:`pingpong:${t}:${s}`;if(i.detectors.pingPong&&h.count>=i.criticalThreshold&&h.noProgressEvidence)return a.error(`Critical ping-pong loop detected: alternating calls count=${h.count} currentTool=${t}`),{stuck:!0,level:`critical`,detector:`ping_pong`,count:h.count,message:`CRITICAL: You are alternating between repeated tool-call patterns (${h.count} consecutive calls) with no progress. This appears to be a stuck ping-pong loop. Session execution blocked to prevent resource waste.`,pairedToolName:h.pairedToolName,warningKey:g};if(i.detectors.pingPong&&h.count>=i.warningThreshold)return a.warn(`Ping-pong loop warning: alternating calls count=${h.count} currentTool=${t}`),{stuck:!0,level:`warning`,detector:`ping_pong`,count:h.count,message:`WARNING: You are alternating between repeated tool-call patterns (${h.count} consecutive calls). This looks like a ping-pong loop; stop retrying and report the task as failed.`,pairedToolName:h.pairedToolName,warningKey:g};let _=o.filter(e=>e.toolName===t&&e.argsHash===s).length;return!m&&i.detectors.genericRepeat&&_>=i.warningThreshold?(a.warn(`Loop warning: ${t} called ${_} times with identical arguments`),{stuck:!0,level:`warning`,detector:`generic_repeat`,count:_,message:`WARNING: You have called ${t} ${_} times with identical arguments. If this is not making progress, stop retrying and report the task as failed.`,warningKey:`generic:${t}:${s}`}):{stuck:!1}}function C(e,t,n,r,i){let a=c(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:l(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function w(e,t){let n=c(t.config),r=_(t.toolName,t.toolParams,t.result,t.error),i=r.resultHash;if(!i)return;e.toolCallHistory||=[];let a=l(t.toolName,t.toolParams),o=!1;for(let n=e.toolCallHistory.length-1;n>=0;--n){let s=e.toolCallHistory[n];if(s&&!(t.toolCallId&&s.toolCallId!==t.toolCallId)&&!(s.toolName!==t.toolName||s.argsHash!==a)&&s.resultHash===void 0){s.resultHash=i,s.unknownToolName=r.unknownToolName,o=!0;break}}o||e.toolCallHistory.push({toolName:t.toolName,argsHash:a,toolCallId:t.toolCallId,resultHash:i,unknownToolName:r.unknownToolName,timestamp:Date.now()}),e.toolCallHistory.length>n.historySize&&e.toolCallHistory.splice(0,e.toolCallHistory.length-n.historySize)}const T={getDiagnosticSessionState:r,logToolLoopAction:n,detectToolCallLoop:S,recordToolCall:C,recordToolCallOutcome:w};export{T as beforeToolCallRuntime};
@@ -0,0 +1 @@
1
+ import{a as e,c as t,s as n}from"./home-dir-C44RaPME-B5iLWwCq.mjs";import{o as r,s as i}from"./paths-D92DjaZ--DdtJ-zYp.mjs";import{c as a,l as o,s}from"./bundled-dir-U738ay4K-BxbzrJOo.mjs";import{i as c}from"./ids-BPsM98Uu-CJBJAeVC.mjs";import{Ft as l,Mt as u,S as d,St as f,a as ee,f as te,h as ne,l as p,m as re,o as m,r as ie,s as ae,w as h}from"./bundled-compat-BpaDaAAu-DJtrIX6i.mjs";import{M as oe,_ as se,c as ce,l as le,o as g,v as ue}from"./manifest-registry-_hxKCS2K-OL8KK_o4.mjs";import{t as de}from"./jiti-loader-cache-Bat69wam-DNIteTtO.mjs";import _ from"node:fs";import v from"node:path";import{fileURLToPath as fe}from"node:url";import pe from"node:os";function me(e){if(e!==void 0)return Array.from(new Set(e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean))).toSorted()}function he(e){return e!==void 0}function ge(e){return e===void 0?null:new Set(e)}function _e(e){return e===void 0?`__unscoped__`:JSON.stringify(e)}const ve=f(`channels`),y=new Map;function b(e,n){let r=e.channel[n];if(!r||typeof r!=`object`)return null;let i=t(r.specifier)??``,a=t(r.exportName)??``;return!i||!a?null:{specifier:i,exportName:a}}function x(e){let t=y.get(e);if(t)return t;let n=ae({origin:`bundled`}).filter(t=>!!b(t,e)),r={catalog:n,entriesById:new Map(n.map(e=>[e.pluginId,e])),checkerCache:new Map};return y.set(e,r),r}function ye(e){let t=x(e.metadataKey),n=t.checkerCache.get(e.entry.pluginId);if(n!==void 0)return n;let r=b(e.entry,e.metadataKey);if(!r)return t.checkerCache.set(e.entry.pluginId,null),null;try{let n=te({modulePath:re(e.entry.rootDir,r.specifier),rootDir:e.entry.rootDir,shouldTryNativeRequire:ne})[r.exportName];if(typeof n!=`function`)throw Error(`missing ${e.metadataKey} export ${r.exportName}`);return t.checkerCache.set(e.entry.pluginId,n),n}catch(n){let r=u(n);return ve.warn(`[channels] failed to load ${e.metadataKey} checker for ${e.entry.pluginId}: ${r}`),t.checkerCache.set(e.entry.pluginId,null),null}}function be(e){return x(e).catalog.map(e=>e.pluginId)}function S(e){let t=x(e.metadataKey).entriesById.get(e.channelId);if(!t)return!1;let n=ye({entry:t,metadataKey:e.metadataKey});return n?n({cfg:e.cfg,env:e.env}):!1}function xe(){return be(`persistedAuthState`)}function C(e){return S({metadataKey:`persistedAuthState`,channelId:e.channelId,cfg:e.cfg,env:e.env})}const Se=()=>{},Ce=()=>{},we=()=>{},Te=()=>{},Ee=()=>{},De=()=>{},Oe=()=>{},ke=()=>{},Ae=()=>{},je=()=>{},Me=()=>{},Ne=()=>{},Pe=()=>{},Fe=()=>{},Ie=()=>{},Le=()=>{},Re=()=>{},ze=()=>{},Be=()=>{},Ve=()=>{},He=()=>{},Ue=()=>{},We=()=>{},Ge=()=>{},Ke=()=>{},qe=()=>{},Je=()=>{},Ye=()=>{},Xe=()=>{},Ze=()=>{},Qe=()=>{},$e=()=>{},et=()=>{},tt=()=>{},nt=()=>{},rt=()=>{},it=()=>{},at=()=>{},ot=()=>{},st=()=>{},ct=()=>{};function w(e){let t=e.handlers??{};return{id:e.id,name:e.name,version:e.version,description:e.description,source:e.source,rootDir:e.rootDir,registrationMode:e.registrationMode,config:e.config,pluginConfig:e.pluginConfig,runtime:e.runtime,logger:e.logger,registerTool:t.registerTool??Se,registerHook:t.registerHook??Ce,registerHttpRoute:t.registerHttpRoute??we,registerChannel:t.registerChannel??Te,registerGatewayMethod:t.registerGatewayMethod??Ee,registerCli:t.registerCli??De,registerReload:t.registerReload??Oe,registerNodeHostCommand:t.registerNodeHostCommand??ke,registerSecurityAuditCollector:t.registerSecurityAuditCollector??Ae,registerService:t.registerService??je,registerCliBackend:t.registerCliBackend??Me,registerTextTransforms:t.registerTextTransforms??Ne,registerConfigMigration:t.registerConfigMigration??Pe,registerAutoEnableProbe:t.registerAutoEnableProbe??Fe,registerProvider:t.registerProvider??Ie,registerSpeechProvider:t.registerSpeechProvider??Le,registerRealtimeTranscriptionProvider:t.registerRealtimeTranscriptionProvider??Re,registerRealtimeVoiceProvider:t.registerRealtimeVoiceProvider??ze,registerMediaUnderstandingProvider:t.registerMediaUnderstandingProvider??Be,registerImageGenerationProvider:t.registerImageGenerationProvider??Ve,registerVideoGenerationProvider:t.registerVideoGenerationProvider??He,registerMusicGenerationProvider:t.registerMusicGenerationProvider??Ue,registerWebFetchProvider:t.registerWebFetchProvider??We,registerWebSearchProvider:t.registerWebSearchProvider??Ge,registerInteractiveHandler:t.registerInteractiveHandler??Ke,onConversationBindingResolved:t.onConversationBindingResolved??qe,registerCommand:t.registerCommand??Je,registerContextEngine:t.registerContextEngine??Ye,registerCompactionProvider:t.registerCompactionProvider??Xe,registerAgentHarness:t.registerAgentHarness??Ze,registerEmbeddedExtensionFactory:t.registerEmbeddedExtensionFactory??Qe,registerCodexAppServerExtensionFactory:t.registerCodexAppServerExtensionFactory??$e,registerDetachedTaskRuntime:t.registerDetachedTaskRuntime??et,registerMemoryCapability:t.registerMemoryCapability??tt,registerMemoryPromptSection:t.registerMemoryPromptSection??nt,registerMemoryPromptSupplement:t.registerMemoryPromptSupplement??rt,registerMemoryCorpusSupplement:t.registerMemoryCorpusSupplement??it,registerMemoryFlushPlan:t.registerMemoryFlushPlan??at,registerMemoryRuntime:t.registerMemoryRuntime??ot,registerMemoryEmbeddingProvider:t.registerMemoryEmbeddingProvider??st,resolvePath:e.resolvePath,on:t.on??ct}}function lt(e){return S({metadataKey:`configuredState`,channelId:e.channelId,cfg:e.cfg,env:e.env})}function ut(e,t){let n=e.channels?.[t];return s(n)?n:null}function dt(e){return s(e)?Object.keys(e).some(e=>e!==`enabled`):!1}function T(e,t,n=process.env){return dt(ut(e,t))||lt({channelId:t,cfg:e,env:n})||C({channelId:t,cfg:e,env:n})?!0:!!ee(t)?.config?.hasConfiguredState?.({cfg:e,env:n})}function ft(e){return e.setup?.providers?.map(e=>e.id)??e.providers}const E=e;function pt(e,t){let r=new Set,i=e=>{if(typeof e!=`string`)return;let t=n(e);!t||t===`auto`||t===`pi`||r.add(t)};if(i(e.agents?.defaults?.embeddedHarness?.runtime),Array.isArray(e.agents?.list))for(let t of e.agents.list)s(t)&&i(t.embeddedHarness?.runtime);return i(t.OPENCLAW_AGENT_RUNTIME),[...r].toSorted((e,t)=>e.localeCompare(t))}const mt=new Set([`defaults`,`modelByChannel`]);function ht(e){return s(e)?Object.keys(e).some(e=>e!==`enabled`):!1}function gt(e){return e.map(e=>[`${e.replace(/[^a-z0-9]+/gi,`_`).toUpperCase()}_`,e])}function _t(e){return _.existsSync(r(e,pe.homedir))}let D=null;function vt(e){return e.persistedAuthStateProbe?.listChannelIds()||D||(D=xe(),D)}function O(e){let t=e.options.persistedAuthStateProbe;return t?t.hasState(e):C(e)}function yt(e,t=process.env,n={}){return[...new Set(bt(e,t,n).map(e=>e.channelId))]}function bt(e,t=process.env,n={}){let r=[],i=new Set,a=(e,t)=>{let n=`${t}:${e}`;i.has(n)||(i.add(n),r.push({channelId:e,source:t}))},o=new Set,c=gt(m()),l=s(e.channels)?e.channels:null;if(l)for(let[e,t]of Object.entries(l))mt.has(e)||ht(t)&&(o.add(e),a(e,`config`));for(let[e,n]of Object.entries(t))if(E(n))for(let[t,n]of c)e.startsWith(t)&&(o.add(n),a(n,`env`));if(n.includePersistedAuthState!==!1&&_t(t))for(let r of vt(n))O({channelId:r,cfg:e,env:t,options:n})&&(o.add(r),a(r,`persisted-auth`));return r.filter(e=>o.has(e.channelId))}function xt(e,t,n={}){let r=gt(m());for(let[e,n]of Object.entries(t))if(E(n)&&r.some(([t])=>e.startsWith(t)))return!0;return n.includePersistedAuthState===!1||!_t(t)?!1:vt(n).some(r=>O({channelId:r,cfg:e,env:t,options:n}))}function St(e,t=process.env,n={}){let r=s(e?.channels)?e.channels:null;if(r){for(let[e,t]of Object.entries(r))if(!mt.has(e)&&ht(t))return!0}return xt(e??{},t,n)}function k(e){return!(!e.normalizedConfig.enabled||e.normalizedConfig.deny.includes(e.plugin.id)||e.normalizedConfig.entries[e.plugin.id]?.enabled===!1&&e.allowExplicitlyDisabled!==!0||e.allowRestrictiveAllowlistBypass!==!0&&e.normalizedConfig.allow.length>0&&!e.normalizedConfig.allow.includes(e.plugin.id))}function A(e){return h({id:e.plugin.id,origin:e.plugin.origin,config:e.normalizedConfig,rootConfig:e.rootConfig,enabledByDefault:e.plugin.enabledByDefault}).activated}const j=[`.js`,`.mjs`,`.cjs`,`.ts`,`.mts`,`.cts`],M=fe(import.meta.url),Ct=M.includes(`${v.sep}dist${v.sep}`)||M.includes(`${v.sep}dist-runtime${v.sep}`),wt={},Tt={info(){},warn(){},error(){}},Et=new Map,N=new Map,P=new Map;function Dt(e){return de({cache:Et,modulePath:e,importerUrl:import.meta.url})}function F(e,t){if(!e.has(t))return{hit:!1};let n=e.get(t);return e.delete(t),e.set(t,n),{hit:!0,value:n}}function I(e,t,n){for(e.has(t)&&e.delete(t),e.set(t,n);e.size>128;){let t=e.keys().next().value;if(typeof t!=`string`)break;e.delete(t)}}function L(e){let{roots:t,loadPaths:n}=ue({workspaceDir:e.workspaceDir,env:e.env});return JSON.stringify({roots:t,loadPaths:n,pluginIds:e.pluginIds?[...new Set(e.pluginIds)].toSorted():null})}function Ot(e){return JSON.stringify({provider:p(e.provider),registry:L(e)})}function kt(e){let t=Ct?j:[...j.slice(3),...j.slice(0,3)],n=e=>{for(let n of t){let t=v.join(e,`setup-api${n}`);if(_.existsSync(t))return t}return null},r=n(e);if(r)return r;let i=v.basename(e),a=[v.resolve(v.dirname(M),`..`,`..`),process.cwd()];for(let t of a){let r=v.join(t,`extensions`,i);if(r===e)continue;let a=n(r);if(a)return a}return null}function At(e){return typeof e==`function`?{register:e}:e&&typeof e==`object`&&typeof e.register==`function`?{definition:e,register:e.register.bind(e)}:{}}function R(e){let t=e.setupSource??kt(e.rootDir);if(!t)return null;let n;try{n=Dt(t)(t)}catch{return null}let r=At(n.default??n);return!r.register||r.definition?.id&&r.definition.id!==e.id?null:{setupSource:t,register:r.register}}function z(e){return w({id:e.record.id,name:e.record.name??e.record.id,version:e.record.version,description:e.record.description,source:e.setupSource,rootDir:e.record.rootDir,registrationMode:`setup-only`,config:{},runtime:wt,logger:Tt,resolvePath:e=>e,handlers:e.handlers})}function B(e){!e||typeof e.then!=`function`||Promise.resolve(e).catch(()=>void 0)}function jt(e,t){let n=p(t);return p(e.id)===n?!0:[...e.aliases??[],...e.hookAliases??[]].some(e=>p(e)===n)}function V(e){let t=e?.env??process.env,n=se({workspaceDir:e?.workspaceDir,env:t,cache:!0});return g({workspaceDir:e?.workspaceDir,env:t,cache:!0,candidates:n.candidates,diagnostics:n.diagnostics})}function Mt(e){let t=e.registry.plugins.filter(t=>e.listIds(t).some(t=>p(t)===e.normalizedId));if(t.length!==0)return t.length===1?t[0]:void 0}function Nt(e){let t=e?.env??process.env,n=L({workspaceDir:e?.workspaceDir,env:t,pluginIds:e?.pluginIds}),r=F(N,n);if(r.hit)return r.value;let i=e?.pluginIds?new Set(e.pluginIds.map(e=>e.trim()).filter(Boolean)):null;if(i&&i.size===0){let e={providers:[],cliBackends:[],configMigrations:[],autoEnableProbes:[]};return I(N,n,e),e}let a=[],o=[],s=[],c=[],l=new Set,u=new Set,d=V({workspaceDir:e?.workspaceDir,env:t});for(let e of d.plugins){if(i&&!i.has(e.id))continue;let t=R(e);if(!t)continue;let n=z({record:e,setupSource:t.setupSource,handlers:{registerProvider(t){let n=`${e.id}:${p(t.id)}`;l.has(n)||(l.add(n),a.push({pluginId:e.id,provider:t}))},registerCliBackend(t){let n=`${e.id}:${p(t.id)}`;u.has(n)||(u.add(n),o.push({pluginId:e.id,backend:t}))},registerConfigMigration(t){s.push({pluginId:e.id,migrate:t})},registerAutoEnableProbe(t){c.push({pluginId:e.id,probe:t})}}});try{let e=t.register(n);e&&typeof e.then==`function`&&B(e)}catch{continue}}let f={providers:a,cliBackends:o,configMigrations:s,autoEnableProbes:c};return I(N,n,f),f}function Pt(e){let t=Ot(e),n=F(P,t);if(n.hit)return n.value??void 0;let r=e.env??process.env,i=p(e.provider),a=Mt({registry:V({workspaceDir:e.workspaceDir,env:r}),normalizedId:i,listIds:ft});if(!a){I(P,t,null);return}let o=R(a);if(!o){I(P,t,null);return}let s,c=new Set,l=z({record:a,setupSource:o.setupSource,handlers:{registerProvider(e){let t=p(e.id);c.has(t)||(c.add(t),jt(e,i)&&(s=e))},registerConfigMigration(){},registerAutoEnableProbe(){}}});try{let e=o.register(l);e&&typeof e.then==`function`&&B(e)}catch{I(P,t,null);return}return I(P,t,s??null),s}function H(e){let t=e.env??process.env,n=[],r=new Set;for(let i of Nt({workspaceDir:e.workspaceDir,env:t,pluginIds:e.pluginIds}).autoEnableProbes){let a=i.probe({config:e.config,env:t}),o=Array.isArray(a)?a:a?[a]:[];for(let e of o){let t=e.trim();if(!t)continue;let a=`${i.pluginId}:${t}`;r.has(a)||(r.add(a),n.push({pluginId:i.pluginId,reason:t}))}}return n}function U(e,t){let n=e.plugins?.allow;return!Array.isArray(n)||n.includes(t)?e:{...e,plugins:{...e.plugins,allow:[...n,t]}}}function W(e){return g({config:e.config,workspaceDir:e.workspaceDir,env:e.env})}function G(e){return{registry:W(e),onlyPluginIdSet:ge(e.onlyPluginIds)}}function K(e,t){return e.plugins.filter(t).map(e=>e.id).toSorted((e,t)=>e.localeCompare(t))}function q(e){if(e.pluginIds.length===0)return[];let t=new Set(e.pluginIds),n=W(e),r=d(e.config?.plugins);return K(n,n=>t.has(n.id)&&e.isEligible(n,r))}function Ft(e){return ie(e)}function It(e){let{registry:t,onlyPluginIdSet:n}=G(e);return K(t,e=>e.origin===`bundled`&&e.providers.length>0&&(!n||n.has(e.id)))}function Lt(e){let{registry:t,onlyPluginIdSet:n}=G(e),r=d(e.config?.plugins);return K(t,t=>t.providers.length>0&&(!n||n.has(t.id))&&h({id:t.id,origin:t.origin,config:r,rootConfig:e.config,enabledByDefault:t.enabledByDefault}).activated)}function Rt(e){return le({contract:`externalAuthProviders`,config:e.config,workspaceDir:e.workspaceDir,env:e.env})}function zt(e){let t=e.declaredPluginIds??new Set(Rt(e)),n=W(e),r=d(e.config?.plugins);return K(n,n=>n.origin!==`bundled`&&n.providers.length>0&&!t.has(n.id)&&Ut({plugin:n,normalizedConfig:r,rootConfig:e.config}))}function Bt(e){let{registry:t,onlyPluginIdSet:n}=G(e),r=e.includeUntrustedWorkspacePlugins===!1,i=d(e.config?.plugins);return K(t,t=>t.providers.length>0&&(!n||n.has(t.id))?Vt({plugin:t,shouldFilterUntrustedWorkspacePlugins:r,normalizedConfig:i,rootConfig:e.config}):!1)}function Vt(e){return!e.shouldFilterUntrustedWorkspacePlugins||e.plugin.origin!==`workspace`?!0:k({plugin:e.plugin,normalizedConfig:e.normalizedConfig})?A({plugin:e.plugin,normalizedConfig:e.normalizedConfig,rootConfig:e.rootConfig}):!1}function Ht(e){let t=e.includeUntrustedWorkspacePlugins===!1;return q({...e,isEligible:(n,r)=>Vt({plugin:n,shouldFilterUntrustedWorkspacePlugins:t,normalizedConfig:r,rootConfig:e.config})})}function Ut(e){return k({plugin:e.plugin,normalizedConfig:e.normalizedConfig})?e.plugin.origin===`workspace`?A({plugin:e.plugin,normalizedConfig:e.normalizedConfig,rootConfig:e.rootConfig}):!0:!1}function Wt(e){return q({...e,isEligible:(t,n)=>Ut({plugin:t,normalizedConfig:n,rootConfig:e.config})})}function J(e){return e.manifestRegistry??W(e)}function Gt(e){let t=e.trim(),n=t.indexOf(`@`);return n<=0?t:t.slice(0,n).trim()}function Kt(e){let t=e.trim();if(!t)return null;let n=t.indexOf(`/`);if(n===-1){let e=Gt(t);return e?{modelId:e}:null}let r=p(t.slice(0,n)),i=Gt(t.slice(n+1));return!r||!i?null:{provider:r,modelId:i}}function qt(e,t){let n=e.modelSupport?.modelPatterns??[];for(let e of n)try{if(new RegExp(e,`u`).test(t))return`pattern`}catch{continue}let r=e.modelSupport?.modelPrefixes??[];for(let e of r)if(t.startsWith(e))return`prefix`}function Jt(e){return[...new Set(e)].toSorted((e,t)=>e.localeCompare(t))}function Yt(e,t){if(t.length===0)return;let n=Jt(t);if(n.length<=1)return n;let r=n.filter(t=>e.plugins.find(e=>e.id===t)?.origin!==`bundled`);if(r.length===1)return r;r.length}function Xt(e){let t=p(e.provider);if(!t)return;let n=J(e).plugins.filter(e=>e.providers.some(e=>p(e)===t)||e.cliBackends.some(e=>p(e)===t)).map(e=>e.id);return n.length>0?n:void 0}function Zt(e){let t=Kt(e.model);if(!t)return;if(t.provider)return Xt({provider:t.provider,config:e.config,workspaceDir:e.workspaceDir,env:e.env,manifestRegistry:e.manifestRegistry});let n=J(e);return Yt(n,n.plugins.filter(e=>qt(e,t.modelId)===`pattern`).map(e=>e.id))||Yt(n,n.plugins.filter(e=>qt(e,t.modelId)===`prefix`).map(e=>e.id))}function Qt(e){let t=J(e);return Jt(e.models.flatMap(n=>Zt({model:n,config:e.config,workspaceDir:e.workspaceDir,env:e.env,manifestRegistry:t})??[]))}function $t(e){let t=W(e),n=d(e.config?.plugins),r=K(t,t=>t.providers.length>0&&h({id:t.id,origin:t.origin,config:n,rootConfig:e.config,enabledByDefault:t.enabledByDefault}).activated),i=It(e);return[...new Set([...r,...i])].toSorted((e,t)=>e.localeCompare(t))}const en=[`OPENCLAW_PLUGIN_CATALOG_PATHS`,`OPENCLAW_MPM_CATALOG_PATHS`];function tn(e){let n=t(e)??``;return n?oe(n.split(/[;,]/g).flatMap(e=>e.split(v.delimiter))):[]}function nn(e){for(let n of en){let r=t(e[n]);if(r)return tn(r)}let n=a(e);return[v.join(n,`mpm`,`plugins.json`),v.join(n,`mpm`,`catalog.json`),v.join(n,`plugins`,`catalog.json`)]}function rn(e){let n=(()=>{if(Array.isArray(e))return e;if(!s(e))return[];let t=e.entries??e.packages??e.plugins;return Array.isArray(t)?t:[]})(),r=[];for(let e of n){if(!s(e)||!s(e.openclaw)||!s(e.openclaw.channel))continue;let n=e.openclaw.channel,i=t(n.id)??``;if(!i)continue;let a=Array.isArray(n.preferOver)?n.preferOver.filter(e=>typeof e==`string`):[];r.push({id:i,preferOver:a})}return r}function an(e,t){for(let n of nn(t)){let r=o(n,t);if(_.existsSync(r))try{let t=rn(JSON.parse(_.readFileSync(r,`utf-8`))).find(t=>t.id===e);if(t)return t.preferOver}catch{}}return[]}function on(e){let t=c(e);return t?l(t)?.preferOver??[]:[]}function sn(e,t,n){let r=e.kind===`channel-configured`?e.channelId:e.pluginId,i=n.plugins.find(t=>t.id===e.pluginId),a=i?.channelConfigs?.[r]?.preferOver;if(a?.length)return[...a];let o=i?.channelCatalogMeta;if(o?.preferOver?.length)return[...o.preferOver];let s=on(r);return s.length?[...s]:an(r,t)}function cn(e){return`${e.pluginId}:${e.kind===`channel-configured`?e.channelId:e.pluginId}`}function ln(e){let t=t=>{let n=cn(t),r=e.preferOverCache.get(n);if(r)return r;let i=sn(t,e.env,e.registry);return e.preferOverCache.set(n,i),i};for(let n of e.configured)if(n.pluginId!==e.entry.pluginId&&!(e.isPluginDenied(e.config,n.pluginId)||e.isPluginExplicitlyDisabled(e.config,n.pluginId))&&t(n).includes(e.entry.pluginId))return!0;return!1}const un={plugins:[],diagnostics:[]};function dn(e){let t=new Map;for(let n of e.plugins)for(let e of n.autoEnableWhenConfiguredProviders??[])t.has(e)||t.set(e,n.id);return Object.fromEntries(t)}function Y(e){let t=[],n=e=>{typeof e==`string`&&e.trim()&&t.push(e.trim())},r=e=>{if(!e)return;let t=e.model;if(typeof t==`string`)n(t);else if(s(t)){n(t.primary);let e=t.fallbacks;if(Array.isArray(e))for(let t of e)n(t)}let r=e.models;if(s(r))for(let e of Object.keys(r))n(e)};r(e.agents?.defaults);let i=e.agents?.list;if(Array.isArray(i))for(let e of i)s(e)&&r(e);return t}function fn(e){let t=e.trim(),n=t.indexOf(`/`);return n<=0?null:p(t.slice(0,n))}function pn(e,t){return pt(e,t).length>0}function mn(e,t){let r=n(t);return r?e.plugins.filter(e=>(e.activation?.onAgentHarnesses??[]).some(e=>n(e)===r)).map(e=>e.id).toSorted((e,t)=>e.localeCompare(t)):[]}function hn(e,t){let n=p(t),r=e.auth?.profiles;if(r&&typeof r==`object`){for(let e of Object.values(r))if(s(e)&&p(e.provider??``)===n)return!0}let i=e.models?.providers;if(i&&typeof i==`object`){for(let e of Object.keys(i))if(p(e)===n)return!0}for(let t of Y(e)){let e=fn(t);if(e&&e===n)return!0}return!1}function gn(e,t){let n=e.plugins?.entries?.[t]?.config;return s(n)&&s(n.webSearch)}function _n(e,t){let n=e.plugins?.entries?.[t]?.config;return s(n)&&s(n.webFetch)}function vn(e){if((e.contracts?.tools?.length??0)===0)return[];let t=s(e.configSchema)?e.configSchema.properties:void 0;return s(t)?Object.keys(t).filter(e=>e!==`webSearch`&&e!==`webFetch`):[]}function yn(e,t){let n=e.plugins?.entries?.[t.id]?.config;return s(n)?vn(t).some(e=>n[e]!==void 0):!1}function bn(e){return e.plugins.filter(e=>(e.providers?.length??0)>0).filter(e=>(e.contracts?.webSearchProviders?.length??0)>0)}function xn(e){return e.plugins.filter(e=>(e.contracts?.webFetchProviders?.length??0)>0)}function Sn(e){return e.plugins.filter(e=>(e.contracts?.tools?.length??0)>0)}function Cn(e,t){return ce({contract:`webFetchProviders`,value:n(e)??``,origin:`bundled`,env:t})}function wn(e){let t=new Map;for(let n of e.plugins)for(let e of n.channels??[])e&&!t.has(e)&&t.set(e,n.id);return t}function Tn(e,t){return c(e)||(t.get(e)??e)}function En(e,t){return yt(e,t).map(e=>c(e)??e)}function Dn(e){let t=e.plugins?.entries;return!!t&&typeof t==`object`&&Object.values(t).some(e=>s(e)&&s(e.config)&&s(e.config.webSearch))}function On(e){let t=e.plugins?.entries;return!!t&&typeof t==`object`&&Object.values(t).some(e=>s(e)&&s(e.config)&&s(e.config.webFetch))}function X(e){let t=e.plugins?.entries;return!!t&&typeof t==`object`&&Object.values(t).some(e=>s(e)&&s(e.config))}function Z(e,t){return Array.isArray(e)&&e.some(e=>n(e)===t)}function kn(e){return s(e)&&(Z(e.allow,`browser`)||Z(e.alsoAllow,`browser`))}function An(e){if(kn(e.tools))return!0;let t=e.agents?.list;return Array.isArray(t)?t.some(e=>s(e)&&kn(e.tools)):!1}function jn(e){let t=e.plugins?.entries;return!t||typeof t!=`object`?[]:Object.keys(t).map(e=>e.trim()).filter(Boolean)}function Mn(e){let t=new Set(jn(e));return(s(e.browser)||s(e.plugins?.entries?.browser)||An(e))&&t.add(`browser`),(s(e.acp)||s(e.plugins?.entries?.acpx))&&t.add(`acpx`),(s(e.plugins?.entries?.xai)||s(e.tools?.web)&&s(e.tools.web.x_search))&&t.add(`xai`),[...t].toSorted((e,t)=>e.localeCompare(t))}function Nn(e){let t=e.plugins?.entries;return s(e.browser)||s(e.acp)||An(e)||s(t?.browser)||s(t?.acpx)||s(t?.xai)||s(e.tools?.web)&&s(e.tools.web.x_search)?!0:X(e)}function Pn(e){let t=e.plugins?.entries;return!!t&&typeof t==`object`&&Object.keys(t).length>0}function Fn(e){return Array.isArray(e.plugins?.allow)&&e.plugins.allow.length>0&&Pn(e)}function In(e,t){return e.auth?.profiles&&Object.keys(e.auth.profiles).length>0||e.models?.providers&&Object.keys(e.models.providers).length>0||Y(e).length>0?!0:pn(e,t)}function Ln(e,t){if(Fn(e)||X(e)||In(e,t))return!0;let n=e.channels;if(!n||typeof n!=`object`)return!1;for(let e of Object.keys(n))if(!(e===`defaults`||e===`modelByChannel`)&&!c(e))return!0;return!1}function Rn(e,t){return Fn(e)||X(e)||St(e,t)||In(e,t)||Dn(e)||On(e)?!0:Nn(e)?H({config:e,env:t,pluginIds:Mn(e)}).length>0:!1}function zn(e){switch(e.kind){case`channel-configured`:return`${e.channelId} configured`;case`provider-auth-configured`:return`${e.providerId} auth configured`;case`provider-model-configured`:return`${e.modelRef} model configured`;case`agent-harness-runtime-configured`:return`${e.runtime} agent harness runtime configured`;case`web-fetch-provider-selected`:return`${e.providerId} web fetch provider selected`;case`plugin-web-search-configured`:return`${e.pluginId} web search configured`;case`plugin-web-fetch-configured`:return`${e.pluginId} web fetch configured`;case`plugin-tool-configured`:return`${e.pluginId} tool configured`;case`setup-auto-enable`:return e.reason}throw Error(`Unsupported plugin auto-enable candidate`)}function Bn(e){let t=[],r=wn(e.registry);for(let n of En(e.config,e.env)){let i=Tn(n,r);T(e.config,n,e.env)&&t.push({pluginId:i,kind:`channel-configured`,channelId:n})}for(let[n,r]of Object.entries(dn(e.registry)))hn(e.config,n)&&t.push({pluginId:r,kind:`provider-auth-configured`,providerId:n});for(let n of Y(e.config)){let r=Zt({model:n,config:e.config,env:e.env,manifestRegistry:e.registry});r?.length===1&&t.push({pluginId:r[0],kind:`provider-model-configured`,modelRef:n})}for(let n of pt(e.config,e.env)){let r=mn(e.registry,n);for(let e of r)t.push({pluginId:e,kind:`agent-harness-runtime-configured`,runtime:n})}let i=typeof e.config.tools?.web?.fetch?.provider==`string`?e.config.tools.web.fetch.provider:void 0,a=Cn(i,e.env);a&&t.push({pluginId:a,kind:`web-fetch-provider-selected`,providerId:n(i)??``});for(let n of bn(e.registry)){let r=n.id;gn(e.config,r)&&t.push({pluginId:r,kind:`plugin-web-search-configured`})}for(let n of Sn(e.registry)){let r=n.id;yn(e.config,n)&&t.push({pluginId:r,kind:`plugin-tool-configured`})}for(let n of xn(e.registry)){let r=n.id;_n(e.config,r)&&t.push({pluginId:r,kind:`plugin-web-fetch-configured`})}if(Nn(e.config))for(let n of H({config:e.config,env:e.env,pluginIds:Mn(e.config)}))t.push({pluginId:n.pluginId,kind:`setup-auto-enable`,reason:n.reason});return t}function Q(e,t){let n=c(t);if(n){let t=e.channels?.[n];if(t&&typeof t==`object`&&!Array.isArray(t)&&t.enabled===!1)return!0}return e.plugins?.entries?.[t]?.enabled===!1}function $(e,t){let n=e.plugins?.deny;return Array.isArray(n)&&n.includes(t)}function Vn(e,t){let n=e.channels?.[t];return!!n&&typeof n==`object`&&!Array.isArray(n)&&n.enabled===!0}function Hn(e,t){let n=c(t);if(n){let t=e.channels?.[n],r=t&&typeof t==`object`&&!Array.isArray(t)?t:{};return{...e,channels:{...e.channels,[n]:{...r,enabled:!0}}}}return{...e,plugins:{...e.plugins,entries:{...e.plugins?.entries,[t]:{...e.plugins?.entries?.[t],enabled:!0}}}}}function Un(e){return s(e)?e.enabled===!0||s(e.config)||s(e.hooks)||s(e.subagent)||e.apiKey!==void 0||e.env!==void 0:!1}function Wn(e,t){return c(e)?!0:t.plugins.some(t=>t.id===e)}function Gn(e){let t=e.config,n=t.plugins?.allow,r=t.plugins?.entries;if(!Array.isArray(n)||n.length===0||!r||typeof r!=`object`)return t;for(let i of Object.keys(r).toSorted((e,t)=>e.localeCompare(t))){let a=r[i];!Un(a)||$(t,i)||Q(t,i)||n.includes(i)||!Wn(i,e.manifestRegistry)||(t=U(t,i),e.changes.push(`${i} plugin config present, added to plugin allowlist.`))}return t}function Kn(e,t){let n=c(e.channelId);if(n)return l(n)?.label;let r=t.plugins.find(t=>t.id===e.pluginId);return r?.channelConfigs?.[e.channelId]?.label??r?.channelCatalogMeta?.label}function qn(e,t){if(e.kind===`channel-configured`){let n=Kn(e,t);if(n)return`${n} configured, enabled automatically.`}return`${zn(e).trim()}, enabled automatically.`}function Jn(e){return e.manifestRegistry??(Ln(e.config,e.env)?g({config:e.config,env:e.env}):un)}function Yn(e){let t=e.config??{},n=[],r=new Map;if(t.plugins?.enabled===!1)return{config:t,changes:n,autoEnabledReasons:{}};let a=new Map;for(let i of e.candidates){let o=c(i.pluginId);if($(t,i.pluginId)||Q(t,i.pluginId)||ln({config:t,entry:i,configured:e.candidates,env:e.env,registry:e.manifestRegistry,isPluginDenied:$,isPluginExplicitlyDisabled:Q,preferOverCache:a}))continue;let s=t.plugins?.allow,l=Array.isArray(s)&&!s.includes(i.pluginId);if((o==null?t.plugins?.entries?.[i.pluginId]?.enabled===!0:Vn(t,o))&&!l)continue;t=Hn(t,i.pluginId),t=U(t,i.pluginId);let u=zn(i);r.set(i.pluginId,[...r.get(i.pluginId)??[],u]),n.push(qn(i,e.manifestRegistry))}t=Gn({config:t,changes:n,manifestRegistry:e.manifestRegistry});let o=Object.create(null);for(let[e,t]of r)i(e)||(o[e]=[...t]);return{config:t,changes:n,autoEnabledReasons:o}}function Xn(e){let t=e.env??process.env,n=e.config??{};return Rn(n,t)?Bn({config:n,env:t,registry:Jn({config:n,env:t,manifestRegistry:e.manifestRegistry})}):[]}function Zn(e){let t=e.env??process.env,n=e.config??{},r=Jn({config:n,env:t,manifestRegistry:e.manifestRegistry});return Yn({config:n,candidates:e.candidates,env:t,manifestRegistry:r})}function Qn(e){let t=Xn(e);return Zn({config:e.config,candidates:t,env:e.env,manifestRegistry:e.manifestRegistry})}export{he as _,Ht as a,zt as c,Xt as d,Ft as f,ge as g,w as h,$t as i,Rt as l,T as m,Wt as n,Bt as o,Pt as p,It as r,Lt as s,Qn as t,Qt as u,me as v,_e as y};
@@ -0,0 +1 @@
1
+ import e from"node:fs";function t(e){return Number.isInteger(e)&&e>0}function n(t){if(process.platform!==`linux`)return!1;try{return e.readFileSync(`/proc/${t}/status`,`utf8`).match(/^State:\s+(\S)/m)?.[1]===`Z`}catch{return!1}}function r(e){if(!t(e))return!1;try{process.kill(e,0)}catch{return!1}return!n(e)}function i(n){if(process.platform!==`linux`||!t(n))return null;try{let t=e.readFileSync(`/proc/${n}/stat`,`utf8`),r=t.lastIndexOf(`)`);if(r<0)return null;let i=t.slice(r+1).trimStart().split(/\s+/),a=Number(i[19]);return Number.isInteger(a)&&a>=0?a:null}catch{return null}}function a(e){let t=process,n=t[e];if(n)return n;let r=new Map;return t[e]=r,r}export{i as n,r,a as t};
@@ -0,0 +1 @@
1
+ import{o as e}from"./manifest-registry-_hxKCS2K-OL8KK_o4.mjs";import{t}from"./jiti-loader-cache-Bat69wam-DNIteTtO.mjs";import{a as n}from"./loader-708jrx4Y-BbJRXNlQ.mjs";import{o as r}from"./plugin-auto-enable-DdH3n9V8-Dr_bUXkG.mjs";import{n as i}from"./providers.runtime-Ba7tOlq7-B4t6ywCr.mjs";function a(){let e=new Map;return r=>{let i=t({cache:e,modulePath:r,importerUrl:import.meta.url,jitiFilename:import.meta.url});return n({pluginId:`(direct)`,source:r},`source-loader`,()=>i(r))}}function o(e){let t=e&&typeof e==`object`&&`default`in e&&e.default!==void 0?e.default:e;if(Array.isArray(t))return t;if(t&&typeof t==`object`&&`id`in t)return[t];if(e&&typeof e==`object`&&!Array.isArray(e)){let t=e;if(Array.isArray(t.providers))return t.providers;if(t.provider)return[t.provider]}return[]}function s(t){let n=r(t),i=new Set(n),s=e(t).plugins.filter(e=>e.providerDiscoverySource&&i.has(e.id));if(s.length===0||t.requireCompleteDiscoveryEntryCoverage&&s.length<i.size)return[];let c=a(),l=[];for(let e of s)try{let t=c(e.providerDiscoverySource);l.push(...o(t).map(t=>Object.assign({},t,{pluginId:e.id})))}catch{return[]}return l}function c(e){let t=s(e);return t.length>0?t:i({...e,bundledProviderAllowlistCompat:!0})}export{c as resolvePluginDiscoveryProvidersRuntime};
@@ -0,0 +1 @@
1
+ import{d as e}from"./io-CH2g3vsv-JJtUIa_U.mjs";function t(e,...t){return e!==void 0&&t.includes(e)}const n=new Set([`jan`,`llama-cpp`,`llama.cpp`,`llamacpp`,`lm-studio`,`lmstudio`,`localai`,`sglang`,`tabby`,`tabbyapi`,`text-generation-webui`,`vllm`]);function r(...e){return e.some(e=>e!==void 0&&n.has(e.toLowerCase()))}function i(e){let{provider:n,endpointClass:i,knownProviderFamily:a,supportsNativeStreamingUsageCompat:o=!1,usesExplicitProxyLikeEndpoint:s=!1}=e,c=i===`default`,l=i!==`default`&&i!==`openai-public`,u=a===`moonshot`||a===`modelstudio`||i===`moonshot-native`||i===`modelstudio-native`,d=i===`zai-native`||c&&t(e.provider,`zai`),f=i===`cerebras-native`||i===`chutes-native`||i===`deepseek-native`||i===`mistral-public`||i===`opencode-native`||i===`xai-native`||d||c&&t(e.provider,`cerebras`,`chutes`,`deepseek`,`opencode`,`xai`),p=e.provider===`openrouter`||i===`openrouter`,m=i===`chutes-native`||i===`mistral-public`||a===`mistral`||c&&t(n,`chutes`),h=r(n,a);return{supportsStore:!f&&a!==`mistral`&&!s,supportsDeveloperRole:!f&&!u&&!l,supportsReasoningEffort:!d&&a!==`mistral`&&i!==`xai-native`&&!s,supportsUsageInStreaming:h||!f&&(!l||o),maxTokensField:m?`max_tokens`:`max_completion_tokens`,thinkingFormat:d?`zai`:p?`openrouter`:`openai`,visibleReasoningDetailTypes:p?[`response.output_text`,`response.text`]:[],supportsStrictMode:!d&&!l}}function a(e){return i(e)}function o(t){let n=e({provider:t.provider,api:`openai-completions`,baseUrl:t.baseUrl,capability:`llm`,transport:`stream`,modelId:t.id,compat:t.compat&&typeof t.compat==`object`?t.compat:void 0});return{capabilities:n,defaults:a({provider:t.provider,...n})}}function s(e){if(!(!e||typeof e!=`object`)){if(`compat`in e){let t=e.compat;return t&&typeof t==`object`?t:void 0}return e}}function c(e){let t=s(e)?.unsupportedToolSchemaKeywords??[];return new Set(t.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean))}function l(e){return e.api===`openai-completions`}function u(e){return e.api===`anthropic-messages`}function d(e){return e.replace(/\/v1\/?$/,``)}function f(e){let t=e.baseUrl??``;if(u(e)&&t){let n=d(t);if(n!==t)return{...e,baseUrl:n}}if(!l(e))return e;let n=e.compat??void 0,r=t?o(e).defaults:void 0;if(!(r&&(!r.supportsDeveloperRole||!r.supportsUsageInStreaming||!r.supportsStrictMode)))return e;let i=n?.supportsDeveloperRole===!0,a=n?.supportsUsageInStreaming!==void 0,s=n?.supportsStrictMode??r?.supportsStrictMode;return n?.supportsDeveloperRole!==void 0&&a&&n?.supportsStrictMode!==void 0?e:{...e,compat:n?{...n,supportsDeveloperRole:i||!1,...a?{}:{supportsUsageInStreaming:r?.supportsUsageInStreaming??!1},supportsStrictMode:s}:{supportsDeveloperRole:!1,supportsUsageInStreaming:r?.supportsUsageInStreaming??!1,supportsStrictMode:r?.supportsStrictMode??!1}}}export{f as n,c as r,o as t};
@@ -0,0 +1 @@
1
+ import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as f,M as p,N as m,O as h,P as g,Q as _,R as v,S as y,T as b,U as x,V as S,W as C,X as w,Y as T,Z as E,_ as D,a as O,b as k,c as A,d as j,f as M,g as N,h as P,i as F,j as I,k as L,l as R,m as z,n as B,o as V,p as H,q as U,r as W,s as G,t as K,u as q,v as J,w as Y,x as X,y as Z,z as Q}from"./provider-runtime-CT50mNIX-DImw7ZZu.mjs";export{K as __testing,B as applyProviderConfigDefaultsWithPlugin,W as applyProviderNativeStreamingUsageCompatWithPlugin,F as applyProviderResolvedModelCompatWithPlugins,O as applyProviderResolvedTransportWithPlugin,V as augmentModelCatalogWithProviderPlugins,G as buildProviderAuthDoctorHintWithPlugin,A as buildProviderMissingAuthMessageWithPlugin,R as buildProviderUnknownModelHintWithPlugin,q as classifyProviderFailoverReasonWithPlugin,j as clearProviderRuntimeHookCache,M as createProviderEmbeddingProvider,H as formatProviderAuthProfileApiKeyWithPlugin,z as inspectProviderToolSchemasWithPlugin,P as matchesProviderContextOverflowWithPlugin,N as normalizeProviderConfigWithPlugin,D as normalizeProviderModelIdWithPlugin,J as normalizeProviderResolvedModelWithPlugin,Z as normalizeProviderToolSchemasWithPlugin,k as normalizeProviderTransportWithPlugin,X as prepareProviderDynamicModel,y as prepareProviderExtraParams,r as prepareProviderRuntimeAuth,Y as refreshProviderOAuthCredentialWithPlugin,b as resetProviderRuntimeHookCacheForTest,a as resolveExternalAuthProfilesWithPlugins,i as resolveExternalOAuthProfilesWithPlugins,h as resolveProviderBinaryThinking,L as resolveProviderBuiltInModelSuppression,t as resolveProviderCacheTtlEligibility,I as resolveProviderConfigApiKeyWithPlugin,p as resolveProviderDefaultThinkingLevel,m as resolveProviderModernModelRef,g as resolveProviderReasoningOutputModeWithPlugin,o as resolveProviderReplayPolicyWithPlugin,l as resolveProviderRuntimePlugin,f as resolveProviderStreamFn,v as resolveProviderSyntheticAuthWithPlugin,Q as resolveProviderSystemPromptContribution,n as resolveProviderTextTransforms,S as resolveProviderThinkingProfile,c as resolveProviderTransportTurnStateWithPlugin,x as resolveProviderUsageAuthWithPlugin,C as resolveProviderUsageSnapshotWithPlugin,s as resolveProviderWebSocketSessionPolicyWithPlugin,d as resolveProviderXHighThinking,U as runProviderDynamicModel,u as sanitizeProviderReplayHistoryWithPlugin,T as shouldDeferProviderSyntheticProfileAuthWithPlugin,w as shouldPreferProviderRuntimeResolvedModel,E as transformProviderSystemPrompt,_ as validateProviderReplayTurnsWithPlugin,e as wrapProviderStreamFn};