@bkm016/basalt 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/chunk-09vr609h.js +2 -0
  2. package/chunk-0qqb6v41.js +3753 -0
  3. package/{chunk-1egbcp85.js → chunk-0yytz0r1.js} +7 -7
  4. package/{chunk-rjdhaasf.js → chunk-1aspj1hn.js} +2 -2
  5. package/chunk-1b7gbe8g.js +10 -0
  6. package/{chunk-665jzf2w.js → chunk-1v7st27a.js} +11 -11
  7. package/{chunk-5fdgy0q2.js → chunk-2bb01ddq.js} +10 -10
  8. package/{chunk-kjr81mrd.js → chunk-2wkaw73s.js} +3 -3
  9. package/{chunk-xhk54h2q.js → chunk-3m7qwfm3.js} +4 -4
  10. package/{chunk-0tdv0t5q.js → chunk-44ek81ad.js} +2 -2
  11. package/{chunk-wc5j0hfw.js → chunk-45cz26ap.js} +2 -2
  12. package/{chunk-0rya8cxe.js → chunk-6e49xsf5.js} +2 -2
  13. package/{chunk-bj14jshr.js → chunk-6qertm2t.js} +2 -2
  14. package/chunk-8dxzqwq3.js +2 -0
  15. package/chunk-9mmz6wt3.js +2 -0
  16. package/{chunk-3jz9g8ab.js → chunk-a3tqx584.js} +3 -3
  17. package/{chunk-y9xe9ct2.js → chunk-a8nyk4k9.js} +1 -1
  18. package/{chunk-qffb7een.js → chunk-bhqyxyap.js} +2 -2
  19. package/chunk-bpw6q7g0.js +3 -0
  20. package/{chunk-tnrqkc7b.js → chunk-cv5wsd9m.js} +1 -1
  21. package/{chunk-5wp4egky.js → chunk-dhm42y04.js} +2 -2
  22. package/{chunk-913tfr9c.js → chunk-exnn1867.js} +1 -1
  23. package/{chunk-7yw8aa5j.js → chunk-f7egr55n.js} +4 -4
  24. package/{chunk-kgdrjqsy.js → chunk-g2t6t8fk.js} +2 -2
  25. package/{chunk-qbf8x2ft.js → chunk-h6sw8fbt.js} +1 -1
  26. package/chunk-jhd54p1b.js +3 -0
  27. package/{chunk-x9982ek7.js → chunk-kf8hq21a.js} +2 -2
  28. package/{chunk-zt1wvkyf.js → chunk-kfq8wyd3.js} +1 -1
  29. package/chunk-nt2gntad.js +2 -0
  30. package/{chunk-wd9zxhza.js → chunk-pmc3y1z8.js} +1 -1
  31. package/{chunk-3p7q2pyp.js → chunk-pvncysbb.js} +1 -1
  32. package/chunk-q8zx3kt6.js +2 -0
  33. package/{chunk-sf13azm4.js → chunk-qczbfccb.js} +3 -3
  34. package/chunk-qx0m82rw.js +2 -0
  35. package/chunk-ry0z4ev6.js +2 -0
  36. package/{chunk-g2k3yhgh.js → chunk-s37s3k24.js} +3 -3
  37. package/{chunk-y8ced1jm.js → chunk-sh74qzvt.js} +1 -1
  38. package/{chunk-9y69ywyg.js → chunk-szat3vp4.js} +2 -2
  39. package/chunk-tvm4zmgj.js +3 -0
  40. package/{chunk-8wjgbd9k.js → chunk-vgvq3q12.js} +2 -2
  41. package/{chunk-d913kpyw.js → chunk-vv7fp27r.js} +2 -2
  42. package/{chunk-97kjn55j.js → chunk-wjd9fr23.js} +1 -1
  43. package/{chunk-6gyhajhx.js → chunk-x3dnb9sz.js} +2 -2
  44. package/chunk-xysny0ve.js +3 -0
  45. package/{chunk-qcwnkr5y.js → chunk-yskm0hsy.js} +1 -1
  46. package/{chunk-sytpmbfp.js → chunk-zef13k3h.js} +36 -36
  47. package/cli.js +89 -0
  48. package/compiled.js +12 -3762
  49. package/package.json +4 -3
  50. package/ui-test-worker.js +31 -31
  51. package/web/{chunk-rkesqprv.js → chunk-05w4fyzc.js} +1 -1
  52. package/web/{chunk-ev1g5cqw.js → chunk-0vt9fg48.js} +1 -1
  53. package/web/{chunk-55kw67nv.js → chunk-22a4ety5.js} +1 -1
  54. package/web/{chunk-hryhthxr.js → chunk-2m12wyrb.js} +1 -1
  55. package/web/{chunk-svmhj9hd.js → chunk-2msj52w6.js} +1 -1
  56. package/web/{chunk-rsn8j7xv.js → chunk-2ps6mepk.js} +1 -1
  57. package/web/chunk-2pver6r4.js +1 -0
  58. package/web/{chunk-1t760bg0.js → chunk-2scce33n.js} +1 -1
  59. package/web/chunk-37ajk6zg.js +2 -0
  60. package/web/{chunk-haphmhz8.js → chunk-3ee04tmm.js} +1 -1
  61. package/web/{chunk-c85wxnpw.js → chunk-3jhyzmnf.js} +1 -1
  62. package/web/{chunk-pz934t6t.js → chunk-45fzdcgz.js} +1 -1
  63. package/web/{chunk-ea9swkkt.js → chunk-4ks96e4r.js} +1 -1
  64. package/web/{chunk-0k0hvh59.js → chunk-4v8en1yw.js} +1 -1
  65. package/web/chunk-4wkm9fda.js +1 -0
  66. package/web/{chunk-zk2f7x5e.js → chunk-5vw9rs4r.js} +1 -1
  67. package/web/{chunk-mq92vqb1.js → chunk-70qwwwak.js} +1 -1
  68. package/web/{chunk-4b5mt5pd.js → chunk-8p4tc9f4.js} +1 -1
  69. package/web/{chunk-3pm4645m.js → chunk-90kp4pnz.js} +1 -1
  70. package/web/{chunk-ytpwz01r.js → chunk-9an7cjd9.js} +1 -1
  71. package/web/{chunk-29e1trsq.js → chunk-9dxjafp2.js} +1 -1
  72. package/web/{chunk-ykxpb3wv.js → chunk-9p12mgs6.js} +1 -1
  73. package/web/{chunk-sc63gh9d.js → chunk-9yakxvjb.js} +1 -1
  74. package/web/{chunk-fdkp6tzq.js → chunk-a1z5qx1r.js} +1 -1
  75. package/web/{chunk-v6v831tc.js → chunk-a3verqw9.js} +1 -1
  76. package/web/{chunk-vqjs551t.js → chunk-a5x2zveg.js} +1 -1
  77. package/web/chunk-amzgyy1k.js +1 -0
  78. package/web/{chunk-e5rmr47n.js → chunk-b1pe46zz.js} +1 -1
  79. package/web/{chunk-1v3d60pp.js → chunk-b4wbk7vc.js} +1 -1
  80. package/web/{chunk-3bqh2dkw.js → chunk-bc78qf1m.js} +1 -1
  81. package/web/{chunk-tfyxp2qs.js → chunk-bgnnrpna.js} +1 -1
  82. package/web/{chunk-vadqkz3x.js → chunk-bj90t5gh.js} +1 -1
  83. package/web/{chunk-mdsgekpk.js → chunk-bjkc94mv.js} +1 -1
  84. package/web/{chunk-3cfabjey.js → chunk-ca682sm6.js} +1 -1
  85. package/web/chunk-cff5hcm8.js +8 -0
  86. package/web/{chunk-942prjb6.js → chunk-dt462hk9.js} +1 -1
  87. package/web/{chunk-bwyw10wx.js → chunk-dzwxgqgm.js} +1 -1
  88. package/web/{chunk-bhe4jzha.js → chunk-e32y85kx.js} +1 -1
  89. package/web/{chunk-v47rhg7b.js → chunk-e53wfgb8.js} +1 -1
  90. package/web/{chunk-ezyvv4ab.js → chunk-e6jxqbv7.js} +1 -1
  91. package/web/chunk-esp1mmgr.js +1 -0
  92. package/web/chunk-ew3cgdtd.js +1 -0
  93. package/web/{chunk-svdzmaxb.js → chunk-f26smjjf.js} +1 -1
  94. package/web/{chunk-jvhmna7z.js → chunk-fk0dh93x.js} +1 -1
  95. package/web/{chunk-3pf33xsm.js → chunk-fm2ybfj5.js} +1 -1
  96. package/web/{chunk-6r912gfj.js → chunk-fscafg24.js} +1 -1
  97. package/web/{chunk-canbct9d.js → chunk-fz06t6km.js} +1 -1
  98. package/web/{chunk-rz6wwdd5.js → chunk-g4azyef7.js} +1 -1
  99. package/web/chunk-gjq1pxw3.js +1 -0
  100. package/web/{chunk-0xck277j.js → chunk-gqw3f02j.js} +1 -1
  101. package/web/chunk-h5ejbf6e.js +1 -0
  102. package/web/{chunk-kbtbbarw.js → chunk-hev4hq89.js} +1 -1
  103. package/web/chunk-jjh5jvva.js +1 -0
  104. package/web/{chunk-a3xt6840.js → chunk-jrcyc9s9.js} +1 -1
  105. package/web/{chunk-4y2td14d.js → chunk-jwzd9tzk.js} +1 -1
  106. package/web/chunk-k5btcvbg.js +1 -0
  107. package/web/{chunk-z1jtv4c0.js → chunk-kdyjnwdx.js} +1 -1
  108. package/web/chunk-kpvgecwy.js +1 -0
  109. package/web/chunk-kq40ss39.js +1 -0
  110. package/web/{chunk-ghxe4gam.js → chunk-p3b9crsa.js} +1 -1
  111. package/web/{chunk-zakv2xdf.js → chunk-pf2ab8p8.js} +1 -1
  112. package/web/{chunk-d4d3mnak.js → chunk-q0p5xqe1.js} +1 -1
  113. package/web/{chunk-5hex8g0y.js → chunk-q5ke7a33.js} +1 -1
  114. package/web/chunk-q7dsnvpf.js +1 -0
  115. package/web/{chunk-vfqe8298.js → chunk-qd8bxxdj.js} +1 -1
  116. package/web/{chunk-3ahpr030.js → chunk-qefasa1j.js} +1 -1
  117. package/web/{chunk-x9q4kh67.js → chunk-qh7265qw.js} +1 -1
  118. package/web/{chunk-hejz98gw.js → chunk-qnaqf0cr.js} +1 -1
  119. package/web/chunk-rg426vkf.js +1 -0
  120. package/web/{chunk-s8vapqgr.js → chunk-rpmpttbk.js} +1 -1
  121. package/web/chunk-scpwc9ev.js +1 -0
  122. package/web/{chunk-b5brnfv9.js → chunk-ss1bcb0n.js} +1 -1
  123. package/web/chunk-ssy07dd2.js +1 -0
  124. package/web/{chunk-gxn0bey7.js → chunk-taynqrgq.js} +2 -2
  125. package/web/chunk-tgpbhzn9.js +1 -0
  126. package/web/{chunk-ejd43q75.js → chunk-tmvakq7n.js} +2 -2
  127. package/web/{chunk-nerx2q12.js → chunk-tqmwd9qp.js} +1 -1
  128. package/web/{chunk-n5fn9khr.js → chunk-v28fx2nd.js} +1 -1
  129. package/web/{chunk-32ezm0ry.js → chunk-vt40e1kp.js} +39 -39
  130. package/web/chunk-w53rba6g.js +1 -0
  131. package/web/chunk-w86n42dy.js +1 -0
  132. package/web/{chunk-ktqt87qw.js → chunk-w880psmw.js} +1 -1
  133. package/web/{chunk-p8y0hjx9.js → chunk-wptv8atc.js} +1 -1
  134. package/web/{chunk-g9qv15hq.js → chunk-xbty0rv7.js} +1 -1
  135. package/web/{chunk-7f0m2yrd.js → chunk-xjxv8dg8.js} +1 -1
  136. package/web/{chunk-x3zwjkwg.js → chunk-xrxne80b.js} +1 -1
  137. package/web/{chunk-jtwhjp20.js → chunk-y0m8hrwz.js} +2 -2
  138. package/web/{chunk-6atq9qtt.js → chunk-y49fhfda.js} +1 -1
  139. package/web/{chunk-1x8fn8w9.js → chunk-yd46jhqv.js} +1 -1
  140. package/web/{chunk-ngpq43vn.js → chunk-z7dcbxws.js} +1 -1
  141. package/web/chunk-zde7mj43.js +1 -0
  142. package/web/index.html +1 -1
  143. package/worker.js +1 -1
  144. package/chunk-1fv27j4b.js +0 -3
  145. package/chunk-356q8e0y.js +0 -10
  146. package/chunk-b9bg5fhd.js +0 -2
  147. package/chunk-j2x0g1vg.js +0 -2
  148. package/chunk-k0t23cmx.js +0 -2
  149. package/chunk-m38ber71.js +0 -2
  150. package/chunk-rad3dm0q.js +0 -2
  151. package/chunk-tjpvayr1.js +0 -2
  152. package/chunk-ve7qx8wm.js +0 -3
  153. package/chunk-yb1jxgnk.js +0 -2
  154. package/web/chunk-00mq7bhx.js +0 -1
  155. package/web/chunk-0atfn8jf.js +0 -1
  156. package/web/chunk-310yey4q.js +0 -1
  157. package/web/chunk-3hvgs5aw.js +0 -1
  158. package/web/chunk-3kh6zefg.js +0 -1
  159. package/web/chunk-401v5ht6.js +0 -8
  160. package/web/chunk-5r5kv4gh.js +0 -1
  161. package/web/chunk-95q1bwxn.js +0 -1
  162. package/web/chunk-9s7c178f.js +0 -1
  163. package/web/chunk-benmmqt2.js +0 -1
  164. package/web/chunk-bgqdcnke.js +0 -1
  165. package/web/chunk-eqegxtdt.js +0 -1
  166. package/web/chunk-gmfp7fg4.js +0 -1
  167. package/web/chunk-gxay64d5.js +0 -1
  168. package/web/chunk-jg6nzn6q.js +0 -1
  169. package/web/chunk-kx2xk3bb.js +0 -1
  170. package/web/chunk-vfqdy860.js +0 -1
  171. package/web/chunk-x59p8sg2.js +0 -1
  172. package/web/chunk-y7z144e3.js +0 -1
  173. package/web/chunk-ydgqrfvw.js +0 -2
  174. package/web/chunk-yj1a2d37.js +0 -1
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{N,H}from"./chunk-sf13azm4.js";class p extends Error{}var D=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function y(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function b(e){if(!y(e))return!1;let n=typeof e.type==="string"?[e.type]:Array.isArray(e.type)?e.type:[];return n.includes("object")||n.includes("array")||e.properties!==void 0||e.items!==void 0}function k(e){if(!y(e))return!1;if(e.type==="null"||Array.isArray(e.type)&&e.type.includes("null"))return!0;if(e.const===null||Array.isArray(e.enum)&&e.enum.includes(null))return!0;return Array.isArray(e.anyOf)&&e.anyOf.some((n)=>k(n))}function w(e,n){if(!y(e))throw new p("boolean schemas are unsupported");for(let a of D)if(e[a]!==void 0)throw new p(`${a} schemas are unsupported`);if(n){for(let[a,l]of Object.entries(e))if(n(a,l))throw new p(`${a}: ${JSON.stringify(l)} is unsupported`)}if(e.anyOf!==void 0){if(!Array.isArray(e.anyOf)||e.anyOf.length===0)throw new p("anyOf must contain at least one schema");for(let a of e.anyOf){if(b(a))throw new p("object and array unions are unsupported");w(a,n)}}if(e.items!==void 0){if(Array.isArray(e.items))throw new p("tuple schemas are unsupported");w(e.items,n)}let t=e.type==="object";if(e.properties!==void 0&&!t)throw new p("properties require type object");if(!t)return;if(e.additionalProperties!==void 0&&e.additionalProperties!==!1)throw new p("schema-valued or true additionalProperties is unsupported");if(e.properties!==void 0&&!y(e.properties))throw new p("object properties must be a schema map");if(e.required!==void 0&&(!Array.isArray(e.required)||e.required.some((a)=>typeof a!=="string")))throw new p("object required must be a string array");let r=e.properties??{},i=Object.keys(r),o=new Set(Array.isArray(e.required)?e.required:[]);if([...o].some((a)=>!i.includes(a)))throw new p("required contains an unknown property");for(let[a,l]of Object.entries(r))if(w(l,n),!o.has(a)&&!k(l))r[a]={anyOf:[l,{type:"null"}]};e.required=i,e.additionalProperties=!1}function C(e,n){let t=structuredClone(e);if(!y(t))throw new p("root schema must have type object");if(w(t,n),t.type!=="object")throw new p("root schema must have type object");return t}function de(e,n){return n===!0?C(e.parameters):e.parameters}function Mr(e,n,t){let r=n[t];if(typeof r!=="string")throw Error(`Grammar tool call "${e}" requires argument "${t}" to be a string.`);return r}function Lr(e,n,t,r){if(e.closed){if(r&&t===e.input)return;throw Error(`grammar tool input for property "${n}" changed after it was closed`)}if(!t.startsWith(e.input))throw Error(`grammar tool input for property "${n}" changed non-monotonically`);let i=t.slice(e.input.length);if(!r&&i.length===0)return;let o="";if(!e.started)o+=`{${JSON.stringify(n)}:"`,e.started=!0;if(o+=JSON.stringify(i).slice(1,-1),e.input=t,r)o+='"}',e.closed=!0;return o}function G(e){let n=e.parameters;if(n.type!=="object")throw Error("grammar constrained sampling requires an object parameter schema");if(!Array.isArray(n.required)||n.required.length!==1||typeof n.required[0]!=="string")throw Error("grammar constrained sampling requires exactly one required string property");let t=n.required[0];if(!n.properties?.[t])throw Error(`grammar constrained sampling requires a properties entry for ${t}`);if(n.properties[t]?.type!=="string")throw Error(`grammar constrained sampling property ${t} must have type string`);return t}function ce(e,n,t){let r=e.constrainedSampling;if(!r||r.type!=="json_schema")return;if(n)try{return C(e.parameters,t),!0}catch(i){if(!(i instanceof p))throw i;if(r.strict!=="require")return;throw Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but ${i.message}.`)}if(r.strict==="require")throw Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`);return}function Xt(e,n){let t=e.constrainedSampling;if(!t||t.type!=="grammar")return;if(!n)return;let r=t.variants.openai_lark,i=t.variants.openai_regex,o=typeof r==="string"&&r.trim().length>0,a=typeof i==="string"&&i.trim().length>0;if(!o&&!a)throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:o?"lark":"regex",definition:o?r:i,inputProperty:G(e)}}catch(l){let d=l instanceof Error?l.message:String(l);throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: ${d}.`)}}function Ee(e,n){let t=new Map;for(let r of e??[]){let i=Xt(r,n);if(i)t.set(r.name,i.inputProperty)}return t}var M=3.5,B=4800;function v(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}function P(e){try{return JSON.stringify(e)??"undefined"}catch{return"[unserializable]"}}function W(e){if(typeof e==="string")return e.length;let n=0;for(let t of e)n+=t.type==="text"?t.text.length:B;return n}function S(e){return Math.ceil(e.length/M)}function E(e){return Math.ceil(W(e)/M)}function R(e){let n=0;if(e.role==="system")return S(N(e))+_(e.toolsAdded)+_(e.toolsRemoved);if(e.role==="user")return E(e.content);if(e.role==="toolResult")return E(e.content);for(let t of e.content)if(t.type==="text")n+=t.text.length;else if(t.type==="thinking")n+=t.thinking.length;else n+=t.name.length+P(t.arguments).length;return Math.ceil(n/M)}function F(e){let n=Number.NEGATIVE_INFINITY,t;for(let r=0;r<e.length;r++){let i=e[r];if(i.role==="assistant"){let o=i;if(o.timestamp>=n&&o.stopReason!=="aborted"&&o.stopReason!=="error"&&v(o.usage)>0)t={usage:o.usage,index:r}}n=Math.max(n,i.timestamp)}return t}function q(e){let n="messages"in e?e.messages:e,t=F(n);if(t){let i=v(t.usage),o=0;for(let a=t.index+1;a<n.length;a++)o+=R(n[a]);return{tokens:i+o,usageTokens:i,trailingTokens:o,lastUsageIndex:t.index}}let r=0;for(let i of n)r+=R(i);return{tokens:r,usageTokens:0,trailingTokens:r,lastUsageIndex:null}}function _(e){if(!e||e.length===0)return 0;return S(P(e))}var z=4096,j=1;function Jt(e,n,t){if(e.contextWindow<=0)return Math.max(j,t);let r=e.contextWindow-q(n).tokens-z;return Math.min(t,Math.max(j,r))}function ct(e,n,t){let r=H(e,n),i=e.samplingParamsByThinkingLevel?.[r];return e.samplingParams||i||t?{...e.samplingParams,...i,...t}:void 0}function V(e,n,t,r){let i=ct(e,t?.reasoning??"off",t?.samplingParams);return{temperature:t?.temperature,samplingParams:i,maxTokens:Jt(e,n,t?.maxTokens??e.maxTokens),signal:t?.signal,telemetryContext:t?.telemetryContext,apiKey:r||t?.apiKey,fetch:t?.fetch,transport:t?.transport,cacheRetention:t?.cacheRetention,sessionId:t?.sessionId,headers:t?.headers,onPayload:t?.onPayload,onResponse:t?.onResponse,onProviderStreamEvent:t?.onProviderStreamEvent,timeoutMs:t?.timeoutMs,websocketConnectTimeoutMs:t?.websocketConnectTimeoutMs,maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,metadata:t?.metadata,env:t?.env}}var K=1024,Y={minimal:1024,low:2048,medium:8192,high:16384};function Ao(e){return e==="xhigh"||e==="max"?"high":e}function Eo(e,n){let t={...Y,...n},r=Ao(e);return t[r]}function _o(e,n){return Math.min(e,Math.max(0,n-K))}function Or(e,n,t,r){let i=Eo(t,r),o=e===void 0?n:Math.min(e+i,n);if(o<=i)i=_o(i,o);return{maxTokens:o,thinkingBudget:i}}function L(e,n){let t=[],r=!1;for(let i of e){if(i.type==="image"){if(!r)t.push({type:"text",text:n});r=!0;continue}t.push(i),r=i.text===n}return t}function X(e,n){if(n.input.includes("image"))return e;return e.map((t)=>{if(t.role==="user"&&Array.isArray(t.content))return{...t,content:L(t.content,"(image omitted: model does not support images)")};if(t.role==="toolResult")return{...t,content:L(t.content,"(tool image omitted: model does not support images)")};return t})}function me(e,n,t){let r=new Map,i=e.map((s)=>s.content==null?{...s,content:[]}:s),a=X(i,n).map((s)=>{if(s.role==="system"||s.role==="user")return s;if(s.role==="toolResult"){let u=r.get(s.toolCallId);if(u&&u!==s.toolCallId)return{...s,toolCallId:u};return s}if(s.role==="assistant"){let u=s,c=u.provider===n.provider&&u.api===n.api&&u.model===n.id,x=u.content.flatMap((f)=>{if(f.type==="thinking"){if(f.redacted)return c?f:[];if(c&&f.thinkingSignature)return f;if(!f.thinking||f.thinking.trim()==="")return[];if(c)return f;return{type:"text",text:f.thinking}}if(f.type==="text"){if(c)return f;return{type:"text",text:f.text}}if(f.type==="toolCall"){let g=f,m=g;if(!c&&g.thoughtSignature)m={...g},delete m.thoughtSignature;if(!c&&t){let I=t(g.id,n,u);if(I!==g.id)r.set(g.id,I),m={...m,id:I}}return m}return f});return{...u,content:x}}return s}),l=[],d=[],h=new Set,A=[],O=()=>{if(d.length>0){for(let s of d)if(!h.has(s.id))l.push({role:"toolResult",toolCallId:s.id,toolName:s.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});d=[],h=new Set}l.push(...A),A.length=0};for(let s=0;s<a.length;s++){let u=a[s];if(u.role==="assistant"){O();let c=u;if(c.stopReason==="error"||c.stopReason==="aborted")continue;let x=c.content.filter((f)=>f.type==="toolCall");if(x.length>0)d=x,h=new Set;l.push(u)}else if(u.role==="toolResult")h.add(u.toolCallId),l.push(u);else if(u.role==="system")if(d.length>0)A.push(u);else l.push(u);else if(u.role==="user")O(),l.push(u);else l.push(u)}return O(),l}function J(){if(typeof process>"u"||!(process.versions?.node||process.versions?.bun))return null;return process.getBuiltinModule?.("node:os")??null}var T=J();function ee(){return T?`pi (${T.platform()} ${T.release()}; ${T.arch()})`:"pi (browser)"}
3
- export{de,Mr,Lr,ce,Xt,Ee,Jt,ct,V,Ao,Eo,_o,Or,me,ee};
2
+ import{N,H}from"./chunk-qczbfccb.js";class p extends Error{}var L=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function y(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function D(e){if(!y(e))return!1;let n=typeof e.type==="string"?[e.type]:Array.isArray(e.type)?e.type:[];return n.includes("object")||n.includes("array")||e.properties!==void 0||e.items!==void 0}function M(e){if(!y(e))return!1;if(e.type==="null"||Array.isArray(e.type)&&e.type.includes("null"))return!0;if(e.const===null||Array.isArray(e.enum)&&e.enum.includes(null))return!0;return Array.isArray(e.anyOf)&&e.anyOf.some((n)=>M(n))}function w(e,n){if(!y(e))throw new p("boolean schemas are unsupported");for(let a of L)if(e[a]!==void 0)throw new p(`${a} schemas are unsupported`);if(n){for(let[a,l]of Object.entries(e))if(n(a,l))throw new p(`${a}: ${JSON.stringify(l)} is unsupported`)}if(e.anyOf!==void 0){if(!Array.isArray(e.anyOf)||e.anyOf.length===0)throw new p("anyOf must contain at least one schema");for(let a of e.anyOf){if(D(a))throw new p("object and array unions are unsupported");w(a,n)}}if(e.items!==void 0){if(Array.isArray(e.items))throw new p("tuple schemas are unsupported");w(e.items,n)}let t=e.type==="object";if(e.properties!==void 0&&!t)throw new p("properties require type object");if(!t)return;if(e.additionalProperties!==void 0&&e.additionalProperties!==!1)throw new p("schema-valued or true additionalProperties is unsupported");if(e.properties!==void 0&&!y(e.properties))throw new p("object properties must be a schema map");if(e.required!==void 0&&(!Array.isArray(e.required)||e.required.some((a)=>typeof a!=="string")))throw new p("object required must be a string array");let r=e.properties??{},i=Object.keys(r),o=new Set(Array.isArray(e.required)?e.required:[]);if([...o].some((a)=>!i.includes(a)))throw new p("required contains an unknown property");for(let[a,l]of Object.entries(r))if(w(l,n),!o.has(a)&&!M(l))r[a]={anyOf:[l,{type:"null"}]};e.required=i,e.additionalProperties=!1}function k(e,n){let t=structuredClone(e);if(!y(t))throw new p("root schema must have type object");if(w(t,n),t.type!=="object")throw new p("root schema must have type object");return t}function de(e,n){return n===!0?k(e.parameters):e.parameters}function Mr(e,n,t){let r=n[t];if(typeof r!=="string")throw Error(`Grammar tool call "${e}" requires argument "${t}" to be a string.`);return r}function Lr(e,n,t,r){if(e.closed){if(r&&t===e.input)return;throw Error(`grammar tool input for property "${n}" changed after it was closed`)}if(!t.startsWith(e.input))throw Error(`grammar tool input for property "${n}" changed non-monotonically`);let i=t.slice(e.input.length);if(!r&&i.length===0)return;let o="";if(!e.started)o+=`{${JSON.stringify(n)}:"`,e.started=!0;if(o+=JSON.stringify(i).slice(1,-1),e.input=t,r)o+='"}',e.closed=!0;return o}function G(e){let n=e.parameters;if(n.type!=="object")throw Error("grammar constrained sampling requires an object parameter schema");if(!Array.isArray(n.required)||n.required.length!==1||typeof n.required[0]!=="string")throw Error("grammar constrained sampling requires exactly one required string property");let t=n.required[0];if(!n.properties?.[t])throw Error(`grammar constrained sampling requires a properties entry for ${t}`);if(n.properties[t]?.type!=="string")throw Error(`grammar constrained sampling property ${t} must have type string`);return t}function ce(e,n,t){let r=e.constrainedSampling;if(!r||r.type!=="json_schema")return;if(n)try{return k(e.parameters,t),!0}catch(i){if(!(i instanceof p))throw i;if(r.strict!=="require")return;throw Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but ${i.message}.`)}if(r.strict==="require")throw Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`);return}function Jt(e,n){let t=e.constrainedSampling;if(!t||t.type!=="grammar")return;if(!n)return;let r=t.variants.openai_lark,i=t.variants.openai_regex,o=typeof r==="string"&&r.trim().length>0,a=typeof i==="string"&&i.trim().length>0;if(!o&&!a)throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:o?"lark":"regex",definition:o?r:i,inputProperty:G(e)}}catch(l){let d=l instanceof Error?l.message:String(l);throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: ${d}.`)}}function Ee(e,n){let t=new Map;for(let r of e??[]){let i=Jt(r,n);if(i)t.set(r.name,i.inputProperty)}return t}var O=3.5,b=4800;function _(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}function P(e){try{return JSON.stringify(e)??"undefined"}catch{return"[unserializable]"}}function W(e){if(typeof e==="string")return e.length;let n=0;for(let t of e)n+=t.type==="text"?t.text.length:b;return n}function v(e){return Math.ceil(e.length/O)}function C(e){return Math.ceil(W(e)/O)}function E(e){let n=0;if(e.role==="system")return v(N(e))+R(e.toolsAdded)+R(e.toolsRemoved);if(e.role==="user")return C(e.content);if(e.role==="toolResult")return C(e.content);for(let t of e.content)if(t.type==="text")n+=t.text.length;else if(t.type==="thinking")n+=t.thinking.length;else n+=t.name.length+P(t.arguments).length;return Math.ceil(n/O)}function B(e){let n=Number.NEGATIVE_INFINITY,t;for(let r=0;r<e.length;r++){let i=e[r];if(i.role==="assistant"){let o=i;if(o.timestamp>=n&&o.stopReason!=="aborted"&&o.stopReason!=="error"&&_(o.usage)>0)t={usage:o.usage,index:r}}n=Math.max(n,i.timestamp)}return t}function S(e){let n="messages"in e?e.messages:e,t=B(n);if(t){let i=_(t.usage),o=0;for(let a=t.index+1;a<n.length;a++)o+=E(n[a]);return{tokens:i+o,usageTokens:i,trailingTokens:o,lastUsageIndex:t.index}}let r=0;for(let i of n)r+=E(i);return{tokens:r,usageTokens:0,trailingTokens:r,lastUsageIndex:null}}function R(e){if(!e||e.length===0)return 0;return v(P(e))}var F=4096,q=1;function Zt(e,n,t){if(e.contextWindow<=0)return Math.max(q,t);let r=e.contextWindow-S(n).tokens-F;return Math.min(t,Math.max(q,r))}function ct(e,n,t){let r=H(e,n),i=e.samplingParamsByThinkingLevel?.[r];return e.samplingParams||i||t?{...e.samplingParams,...i,...t}:void 0}function V(e,n,t,r){let i=ct(e,t?.reasoning??"off",t?.samplingParams);return{temperature:t?.temperature,samplingParams:i,maxTokens:Zt(e,n,t?.maxTokens??e.maxTokens),signal:t?.signal,telemetryContext:t?.telemetryContext,apiKey:r||t?.apiKey,fetch:t?.fetch,transport:t?.transport,cacheRetention:t?.cacheRetention,sessionId:t?.sessionId,headers:t?.headers,onPayload:t?.onPayload,onResponse:t?.onResponse,onProviderStreamEvent:t?.onProviderStreamEvent,timeoutMs:t?.timeoutMs,websocketConnectTimeoutMs:t?.websocketConnectTimeoutMs,maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,metadata:t?.metadata,env:t?.env}}var z=1024,K={minimal:1024,low:2048,medium:8192,high:16384};function Ao(e){return e==="xhigh"||e==="max"?"high":e}function Eo(e,n){let t={...K,...n},r=Ao(e);return t[r]}function _o(e,n){return Math.min(e,Math.max(0,n-z))}function Or(e,n,t,r){let i=Eo(t,r),o=e===void 0?n:Math.min(e+i,n);if(o<=i)i=_o(i,o);return{maxTokens:o,thinkingBudget:i}}function j(e,n){let t=[],r=!1;for(let i of e){if(i.type==="image"){if(!r)t.push({type:"text",text:n});r=!0;continue}t.push(i),r=i.text===n}return t}function Y(e,n){if(n.input.includes("image"))return e;return e.map((t)=>{if(t.role==="user"&&Array.isArray(t.content))return{...t,content:j(t.content,"(image omitted: model does not support images)")};if(t.role==="toolResult")return{...t,content:j(t.content,"(tool image omitted: model does not support images)")};return t})}function me(e,n,t){let r=new Map,i=e.map((s)=>s.content==null?{...s,content:[]}:s),a=Y(i,n).map((s)=>{if(s.role==="system"||s.role==="user")return s;if(s.role==="toolResult"){let u=r.get(s.toolCallId);if(u&&u!==s.toolCallId)return{...s,toolCallId:u};return s}if(s.role==="assistant"){let u=s,c=u.provider===n.provider&&u.api===n.api&&u.model===n.id,x=u.content.flatMap((f)=>{if(f.type==="thinking"){if(f.redacted)return c?f:[];if(c&&f.thinkingSignature)return f;if(!f.thinking||f.thinking.trim()==="")return[];if(c)return f;return{type:"text",text:f.thinking}}if(f.type==="text"){if(c)return f;return{type:"text",text:f.text}}if(f.type==="toolCall"){let m=f,g=m;if(!c&&m.thoughtSignature)g={...m},delete g.thoughtSignature;if(!c&&t){let I=t(m.id,n,u);if(I!==m.id)r.set(m.id,I),g={...g,id:I}}return g}return f});return{...u,content:x}}return s}),l=[],d=[],h=new Set,T=[],A=()=>{if(d.length>0){for(let s of d)if(!h.has(s.id))l.push({role:"toolResult",toolCallId:s.id,toolName:s.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});d=[],h=new Set}l.push(...T),T.length=0};for(let s=0;s<a.length;s++){let u=a[s];if(u.role==="assistant"){A();let c=u;if(c.stopReason==="error"||c.stopReason==="aborted")continue;let x=c.content.filter((f)=>f.type==="toolCall");if(x.length>0)d=x,h=new Set;l.push(u)}else if(u.role==="toolResult")h.add(u.toolCallId),l.push(u);else if(u.role==="system")if(d.length>0)T.push(u);else l.push(u);else if(u.role==="user")A(),l.push(u);else l.push(u)}return A(),l}
3
+ export{de,Mr,Lr,ce,Jt,Ee,Zt,ct,V,Ao,Eo,_o,Or,me};
@@ -0,0 +1,10 @@
1
+ // @bun
2
+ import"./chunk-hat3s3pr.js";import"./chunk-c25s4w6a.js";import{xr}from"./chunk-v9fea96h.js";import{at,Je,lt}from"./chunk-s37s3k24.js";import{Ge}from"./chunk-bpw6q7g0.js";import{ee}from"./chunk-tvm4zmgj.js";import{Cr}from"./chunk-6qertm2t.js";import{q,j}from"./chunk-y69ewdn2.js";import{Ee,V}from"./chunk-1aspj1hn.js";import{z}from"./chunk-dakrpbe6.js";import{$n,Gr}from"./chunk-szat3vp4.js";import{N,ht,ue,re,ge,ye,H}from"./chunk-qczbfccb.js";import{M,Ve,qt,Te}from"./chunk-6e49xsf5.js";var ve="https://chatgpt.com/backend-api",Re="https://api.openai.com/auth",Ce=0,te=1000,xe=60000,Oe=15000,Ae=3,fe=new Set(["openai","openai-codex","opencode"]),Me=1009,We="websocket_connection_limit_reached",Le="previous_response_not_found",De=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function ne(e){if(e.stopReason==="pending")throw Error("Codex stream ended without a stop reason");if(e.stopReason==="error"||e.stopReason==="aborted")throw Error(e.errorMessage||"An unknown error occurred")}function Ne(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}function qe(e,r){if(e===429&&Ne(r))return!1;if(e===429||e===500||e===502||e===503||e===504)return!0;return/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(r)}function Be(e){let r=e.get("retry-after-ms");if(r!==null){let s=Number(r);if(Number.isFinite(s))return Math.max(0,s)}let t=e.get("retry-after");if(!t)return;let n=Number(t);if(Number.isFinite(n))return Math.max(0,n*1000);let o=Date.parse(t);if(!Number.isNaN(o))return Math.max(0,o-Date.now());return}class Y extends Error{}function Pe(e,r){let t=r?.maxRetryDelayMs??xe;if(t>0&&e>t)throw new Y(`Server requested ${Math.ceil(e/1000)}s retry delay (max: ${Math.ceil(t/1000)}s)`);return e}function se(e,r){return new Promise((t,n)=>{if(r?.aborted){n(Error("Request was aborted"));return}let o=setTimeout(t,e);r?.addEventListener("abort",()=>{clearTimeout(o),n(Error("Request was aborted"))})})}function oe(e){if(e===void 0)return;if(!Number.isFinite(e)||e<0)throw Error(`Invalid timeoutMs: ${String(e)}`);return Math.floor(e)}function Ie(){if(typeof process>"u"||!(process.versions?.node||process.versions?.bun))return null;return process.getBuiltinModule?.("node:zlib")??null}function Fe(e){let r=Ie();if(!r||typeof r.zstdCompressSync!=="function")return null;try{let t=r.zstdCompressSync(e,{params:{[r.constants.ZSTD_c_compressionLevel]:Ae}});return new Uint8Array(t)}catch{return null}}var Ue=(e,r,t)=>{let n=new M,o=re(r,e.compat?.supportsMidConvoSystemMessages);return(async()=>{let s={role:"assistant",content:[],api:"openai-codex-responses",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:"pending",timestamp:Date.now()};try{let i=t?.apiKey;if(!i)throw Error(`No API key for provider: ${e.provider}`);let u=_t(i),a=Ee(ge(o.messages),e.compat?.supportsOpenAIGrammarTools??!1),d=t?.cacheRetention==="none"?void 0:t?.sessionId,p=Ge(d),c=$e(e,o,t,p,a),l=await t?.onPayload?.(c,e);if(l!==void 0)c=l;let f=p||Gr(),m=kt(e.headers,t?.headers,u,i,p),b=Tt(e.headers,t?.headers,u,i,f),h=JSON.stringify(c),E=oe(t?.timeoutMs),w=oe(t?.websocketConnectTimeoutMs),v=t?.transport||"auto",T=!1,y=v!=="sse"&&be(d);if(y)ie(d);if(v!=="sse"&&!y){let S=!1,k=!1,O=!1;while(!0){S=!1;try{if(await St(He(e.baseUrl),c,b,s,n,e,()=>{if(S=!0,!T)T=!0,n.push({type:"start",partial:s})},E,w,d,u,a,t),t?.signal?.aborted)throw Error("Request was aborted");ne(s),n.push({type:"done",reason:s.stopReason,message:s}),n.end();return}catch(R){let B=t?.signal?.aborted,P=!S&&Xe(R),W=Ye(R);if(!B&&W&&!O){O=!0;continue}if(!B&&P&&!k){k=!0;continue}if(B||je(R)&&!P)throw R;if(Te(s,qt("provider_transport_failure",R,{configuredTransport:v,...S?{}:{fallbackTransport:"sse"},eventsEmitted:S,phase:S?"after_message_stream_start":"before_message_stream_start",requestBytes:new TextEncoder().encode(h).byteLength})),ot(d,R),S)throw R;ie(d);break}}}let x=Fe(h);if(x)m.set("content-encoding","zstd");let A=x??h,_,D,K=t?.maxRetries??Ce;for(let S=0;S<=K;S++){if(t?.signal?.aborted)throw Error("Request was aborted");try{let k=E!==void 0&&E>0?AbortSignal.timeout(E):void 0,O=xr([t?.signal,k]);try{_=await(t?.fetch??globalThis.fetch)(pe(e.baseUrl),{method:"POST",headers:m,body:A,signal:O.signal})}catch(W){if(k?.aborted&&!t?.signal?.aborted)throw Error(`Codex SSE response headers timed out after ${E}ms`);throw W}finally{O.cleanup()}if(await t?.onResponse?.({status:_.status,headers:z(_.headers)},e),_.ok)break;let R=await _.text();if(S<K&&qe(_.status,R)){let W=Be(_.headers),ke=W===void 0?te*2**S:Pe(W,t);await se(ke,t?.signal);continue}let B=new Response(R,{status:_.status,statusText:_.statusText}),P=await Et(B);throw Error(P.friendlyMessage||P.message)}catch(k){if(k instanceof Error){if(k.name==="AbortError"||k.message==="Request was aborted")throw Error("Request was aborted")}if(D=k instanceof Error?k:Error(String(k)),S<K&&!(D instanceof Y)&&!D.message.includes("usage limit")){let O=te*2**S;await se(O,t?.signal);continue}throw D}}if(!_?.ok)throw D??Error("Failed after retries");if(!_.body)throw Error("No response body");if(!T)T=!0,n.push({type:"start",partial:s});if(await Ke(_,s,n,e,a,t),t?.signal?.aborted)throw Error("Request was aborted");ne(s),n.push({type:"done",reason:s.stopReason,message:s}),n.end()}catch(i){for(let u of s.content)delete u.partialJson,delete u.customInput;s.stopReason=t?.signal?.aborted?"aborted":"error",s.errorMessage=j(q(i)),n.push({type:"error",reason:s.stopReason,error:s}),n.end()}})(),n},$t=(e,r,t)=>{let n=t?.apiKey;if(!n)throw Error(`No API key for provider: ${e.provider}`);let o={...V(e,r,t,n),toolChoice:t?.toolChoice},s=t?.reasoning?H(e,t.reasoning):void 0;return Ue(e,r,{...o,reasoningEffort:s==="off"?void 0:s})};function $e(e,r,t,n,o=Ee(ge(r.messages),e.compat?.supportsOpenAIGrammarTools??!1)){let s=e.compat?.supportsStrictMode??!0,i=e.compat?.supportsOpenAIGrammarTools??!1,u=e.compat?.supportsAdditionalTools??!1,a=e.compat?.supportsToolSearch??!1,d=ye(r.messages,u||a),p=at(e,r,fe,{includeSystemPrompt:!1,grammarToolInputProperties:o,supportsMidConvoSystemMessages:e.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools:u,supportsToolSearch:a,toolOptions:{strict:null,supportsStrictMode:s,supportsOpenAIGrammarTools:i}}),c=ue(r.messages),l=c?N(c):"",f={model:e.id,store:!1,stream:!0,instructions:l||"You are a helpful assistant.",input:p,text:{verbosity:t?.textVerbosity||"low"},include:["reasoning.encrypted_content"],prompt_cache_key:n,tool_choice:t?.toolChoice??"auto",parallel_tool_calls:!0};if(t?.temperature!==void 0)f.temperature=t.temperature;if(t?.serviceTier!==void 0)f.service_tier=t.serviceTier;if(d.requestTools.length>0)f.tools=Je(d.requestTools,{strict:null,supportsStrictMode:s,supportsOpenAIGrammarTools:i});if(t?.reasoningEffort!==void 0){let m=t.reasoningEffort==="none"?e.thinkingLevelMap?.off===void 0?"none":e.thinkingLevelMap.off:e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;if(m!==null)f.reasoning={effort:m,summary:t.reasoningSummary??"auto"}}else if(e.reasoning&&e.thinkingLevelMap?.off!==null)f.reasoning={effort:e.thinkingLevelMap?.off??"none"};return f}function ze(e,r){switch(r){case"flex":return 0.5;case"priority":return e.id==="gpt-5.5"?2.5:2;default:return 1}}function le(e,r,t){let n=ze(t,r);if(n===1)return;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 de(e,r){if(e==="default"&&(r==="flex"||r==="priority"))return r;return e??r}function pe(e){let t=(e&&e.trim().length>0?e:ve).replace(/\/+$/,"");if(t.endsWith("/codex/responses"))return t;if(t.endsWith("/codex"))return`${t}/responses`;return`${t}/codex/responses`}function He(e){let r=new URL(pe(e));if(r.protocol==="https:")r.protocol="wss:";if(r.protocol==="http:")r.protocol="ws:";return r.toString()}async function Ke(e,r,t,n,o,s){await lt(me(et(e,s?.signal),r,n,s?.onProviderStreamEvent),r,t,n,{serviceTier:s?.serviceTier,grammarToolInputProperties:o,resolveServiceTier:de,applyServiceTierPricing:(i,u)=>le(i,u,n)})}class L extends Error{code;payload;constructor(e,r){super(e);this.name="CodexApiError",this.code=r?.code,this.payload=r?.payload,this.cause=r?.cause}}class J extends Error{payload;constructor(e,r){super(e);this.name="CodexProtocolError",this.payload=r?.payload,this.cause=r?.cause}}class Z extends Error{constructor(e){super(Ve(e));this.name="ProviderStreamEventCallbackError",this.cause=e}}function je(e){return e instanceof L||e instanceof J||e instanceof Z}function Xe(e){return e instanceof L&&e.code===We}function Ye(e){return e instanceof L&&e.code===Le}function Ze(e){let r=e.error&&typeof e.error==="object"?e.error:void 0;return{code:typeof e.code==="string"?e.code:typeof r?.code==="string"?r.code:void 0,message:typeof e.message==="string"?e.message:typeof r?.message==="string"?r.message:void 0}}async function*me(e,r,t,n){for await(let o of e){try{await n?.(o,t)}catch(i){throw new Z(i)}let s=typeof o.type==="string"?o.type:void 0;if(!s)continue;if(s==="error"){let{code:i,message:u}=Ze(o);throw new L(`Codex error: ${u||i||JSON.stringify(o)}`,{code:i,payload:o})}if(s==="response.failed"){let i=o.response,u=i?.error?.code,a=i?.error?.message;throw new L(a||"Codex response failed",{code:u,payload:o})}if(s==="response.done"||s==="response.completed"||s==="response.incomplete"){let i=o.response;if(typeof i?.end_turn==="boolean")r.endTurn=i.end_turn;let u=i?{...i,status:Qe(i.status)}:i;yield{...o,type:"response.completed",response:u};return}yield o}}function Qe(e){if(typeof e!=="string")return;return De.has(e)?e:void 0}async function*et(e,r){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,o="",s=()=>{t.cancel().catch(()=>{})};r?.addEventListener("abort",s,{once:!0});try{while(!0){if(r?.aborted)throw Error("Request was aborted");let{done:i,value:u}=await t.read();if(r?.aborted)throw Error("Request was aborted");if(o+=i?n.decode():n.decode(u,{stream:!0}),i&&o.trim())o+=`
3
+
4
+ `;let a=o.indexOf(`
5
+
6
+ `);while(a!==-1){let d=o.slice(0,a);o=o.slice(a+2);let p=d.split(`
7
+ `).filter((c)=>c.startsWith("data:")).map((c)=>c.slice(5).trim());if(p.length>0){let c=p.join(`
8
+ `).trim();if(c&&c!=="[DONE]")try{yield JSON.parse(c)}catch(l){throw new J(`Invalid Codex SSE JSON: ${Ve(l)}`,{cause:l,payload:c})}}a=o.indexOf(`
9
+
10
+ `)}if(i)break}}finally{r?.removeEventListener("abort",s);try{await t.cancel()}catch{}try{t.releaseLock()}catch{}}}var tt="responses_websockets=2026-02-06",rt=300000,nt=3300000,g=new Map,I=new Map,U=new Set;function Q(e){let r=I.get(e);if(!r)r={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},I.set(e,r);return r}function zt(e){let r=I.get(e);return r?{...r}:void 0}function Jt(e){if(e){I.delete(e),U.delete(e);return}I.clear(),U.clear()}function st(e){let r=(t)=>{if(t.idleTimer)clearTimeout(t.idleTimer);C(t.socket,1000,"debug_close")};if(e){for(let t of g.get(e)?.values()??[])r(t);g.delete(e);return}for(let t of g.values())for(let n of t.values())r(n);g.clear()}$n(st);function be(e){return e?U.has(e):!1}function ie(e){if(!e)return;let r=Q(e);r.sseFallbacks++,r.websocketFallbackActive=be(e)}function ot(e,r){if(!e)return;U.add(e);let t=Q(e);t.websocketFailures++,t.lastWebSocketError=Ve(r),t.websocketFallbackActive=!0}var G=null;async function it(e){if(!e&&G)return G;if(typeof process<"u"&&process.versions?.bun){let t=class extends WebSocket{constructor(n,o){let s={};if(Array.isArray(o)||typeof o==="string")s={protocols:o};else s={...o};let i=Cr(n.toString().replace(/^wss:/,"https:").replace(/^ws:/,"http:"),e);super(n,{...s,...i?{proxy:i.toString()}:{}})}};if(!e)G=t;return t}let r=globalThis.WebSocket;if(typeof r!=="function")return null;return r}class he extends Error{code;reason;wasClean;constructor(e,r){super(e);this.name="WebSocketCloseError",this.code=r?.code,this.reason=r?.reason,this.wasClean=r?.wasClean}}function ct(e){let r=e.readyState;return typeof r==="number"?r:void 0}function F(e){let r=ct(e);return r===void 0||r===1}function ut(e){return Date.now()-e.createdAt>=nt}function C(e,r=1000,t="done"){try{e.close(r,t)}catch{}}function ae(e,r,t){if(t.idleTimer)clearTimeout(t.idleTimer);t.idleTimer=setTimeout(()=>{if(t.busy)return;C(t.socket,1000,"idle_timeout");let n=g.get(e);if(n?.get(r)===t)n.delete(r);if(n?.size===0)g.delete(e)},rt)}async function X(e,r,t,n=Oe,o){let s=await it(o);if(!s)throw Error("WebSocket transport is not available in this runtime");let i=z(r);return delete i["OpenAI-Beta"],new Promise((u,a)=>{let d=!1,p,c;try{c=new s(e,{headers:i})}catch(w){a(w instanceof Error?w:Error(String(w)));return}let l=()=>{if(p)clearTimeout(p),p=void 0;c.removeEventListener("open",m),c.removeEventListener("error",b),c.removeEventListener("close",h),t?.removeEventListener("abort",E)},f=(w,v)=>{if(d)return;if(d=!0,l(),v)C(c,1000,v);a(w)},m=()=>{if(d)return;d=!0,l(),u(c)},b=(w)=>{f(we(w))},h=(w)=>{f(Se(w))},E=()=>{f(Error("Request was aborted"),"aborted")};if(c.addEventListener("open",m),c.addEventListener("error",b),c.addEventListener("close",h),t?.addEventListener("abort",E),n>0)p=setTimeout(()=>{f(Error(`WebSocket connect timeout after ${n}ms`),"connect_timeout")},n);if(t?.aborted)E()})}async function ft(e,r,t,n,o,s,i){if(!t){let c=await X(e,r,o,s,i);return{socket:c,reused:!1,release:()=>C(c)}}let u=g.get(t),a=u?.get(n);if(a){if(a.idleTimer)clearTimeout(a.idleTimer),a.idleTimer=void 0;if(!a.busy&&ut(a)){if(C(a.socket,1000,"connection_age_limit"),u?.delete(n),u?.size===0)g.delete(t)}else if(!a.busy&&F(a.socket))return a.busy=!0,{socket:a.socket,entry:a,reused:!0,release:({keep:c}={})=>{if(!c||!F(a.socket)){C(a.socket);let l=g.get(t);if(l?.get(n)===a)l.delete(n);if(l?.size===0)g.delete(t);return}a.busy=!1,ae(t,n,a)}};if(a.busy){let c=await X(e,r,o,s,i);return{socket:c,reused:!1,release:()=>{C(c)}}}if(!F(a.socket)){if(C(a.socket),u?.delete(n),u?.size===0)g.delete(t)}}let d=await X(e,r,o,s,i),p={socket:d,busy:!0,createdAt:Date.now()};if(u=g.get(t),!u)u=new Map,g.set(t,u);return u.set(n,p),{socket:d,entry:p,reused:!1,release:({keep:c}={})=>{if(!c||!F(p.socket)){if(C(p.socket),p.idleTimer)clearTimeout(p.idleTimer);let l=g.get(t);if(l?.get(n)===p)l.delete(n);if(l?.size===0)g.delete(t);return}p.busy=!1,ae(t,n,p)}}}function we(e){if(e&&typeof e==="object"){let r="message"in e?e.message:void 0;if(typeof r==="string"&&r.length>0)return Error(r);let t="error"in e?e.error:void 0;if(t instanceof Error&&t.message.length>0)return t;if(t&&typeof t==="object"&&"message"in t){let n=t.message;if(typeof n==="string"&&n.length>0)return Error(n)}}return Error("WebSocket error")}function Se(e){if(e&&typeof e==="object"){let r="code"in e?e.code:void 0,t="reason"in e?e.reason:void 0,n="wasClean"in e?e.wasClean:void 0,o=typeof r==="number"?` ${r}`:"",s=typeof t==="string"&&t.length>0?` ${t}`:"";if(!s&&r===Me)s=" message too big";return new he(`WebSocket closed${o}${s}`.trim(),{code:typeof r==="number"?r:void 0,reason:typeof t==="string"&&t.length>0?t:void 0,wasClean:typeof n==="boolean"?n:void 0})}return Error("WebSocket closed")}async function dt(e){if(typeof e==="string")return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){let r=e;return new TextDecoder().decode(new Uint8Array(r.buffer,r.byteOffset,r.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*pt(e,r,t){let n=[],o=null,s=!1,i=null,u=!1,a=()=>{if(!o)return;let f=o;o=null,f()},d=(f)=>{(async()=>{let m=null;try{if(!f||typeof f!=="object"||!("data"in f))return;if(m=await dt(f.data),!m)return;let b=JSON.parse(m),h=typeof b.type==="string"?b.type:"";if(h==="response.completed"||h==="response.done"||h==="response.incomplete")u=!0,s=!0;n.push(b),a()}catch(b){i=new J(`Invalid Codex WebSocket JSON: ${Ve(b)}`,{cause:b,payload:m}),s=!0,a()}})()},p=(f)=>{i=we(f),s=!0,a()},c=(f)=>{if(u){s=!0,a();return}if(!i)i=Se(f);s=!0,a()},l=()=>{i=Error("Request was aborted"),s=!0,a()};e.addEventListener("message",d),e.addEventListener("error",p),e.addEventListener("close",c),r?.addEventListener("abort",l);try{while(!0){if(r?.aborted)throw Error("Request was aborted");if(n.length>0){yield n.shift();continue}if(s)break;let f;await new Promise((m,b)=>{if(o=m,t!==void 0&&t>0)f=setTimeout(()=>{let h=Error(`WebSocket idle timeout after ${t}ms`);i=h,s=!0,o=null,C(e,1000,"idle_timeout"),b(h)},t)}).finally(()=>{if(f)clearTimeout(f)})}if(i)throw i;if(!u)throw Error("WebSocket stream closed before response.completed")}finally{e.removeEventListener("message",d),e.removeEventListener("error",p),e.removeEventListener("close",c),r?.removeEventListener("abort",l)}}function ce(e){let{input:r,previous_response_id:t,...n}=e;return n}function mt(e,r){return JSON.stringify(e??[])===JSON.stringify(r??[])}function yt(e,r){return JSON.stringify(ce(e))===JSON.stringify(ce(r))}function bt(e,r){if(!yt(e,r.lastRequestBody))return;let t=e.input??[],n=[...r.lastRequestBody.input??[],...r.lastResponseItems];if(t.length<n.length)return;let o=t.slice(0,n.length);if(!mt(o,n))return;return t.slice(n.length)}function wt(e,r){let t=e.continuation;if(!t)return r;let n=bt(r,t);if(!n||!t.lastResponseId)return e.continuation=void 0,r;return{...r,previous_response_id:t.lastResponseId,input:n}}async function*gt(e,r){let t=!1;for await(let n of e){if(!t)t=!0,r();yield n}}async function St(e,r,t,n,o,s,i,u,a,d,p,c,l){let{socket:f,entry:m,reused:b,release:h}=await ft(e,t,d,p,l?.signal,a,l?.env),E=!0,w=l?.transport==="websocket-cached"||l?.transport==="auto",v=r,T=w&&m?wt(m,v):v,y=d?Q(d):void 0;if(y){if(y.requests++,b)y.connectionsReused++;else y.connectionsCreated++;if(w)y.cachedContextRequests++;if(T.store===!0)y.storeTrueRequests++;if(y.lastInputItems=T.input?.length??0,T.previous_response_id)y.deltaRequests++,y.lastDeltaInputItems=T.input?.length??0,y.lastPreviousResponseId=T.previous_response_id;else y.fullContextRequests++,y.lastDeltaInputItems=void 0,y.lastPreviousResponseId=void 0}try{if(f.send(JSON.stringify({type:"response.create",...T})),await lt(gt(me(pt(f,l?.signal,u),n,s,l?.onProviderStreamEvent),i),n,o,s,{serviceTier:l?.serviceTier,grammarToolInputProperties:c,resolveServiceTier:de,applyServiceTierPricing:(x,A)=>le(x,A,s)}),l?.signal?.aborted)E=!1;else if(w&&m&&n.responseId){let x=at(s,ht({messages:[n]}),fe,{includeSystemPrompt:!1,grammarToolInputProperties:c}).filter((A)=>A.type!=="function_call_output"&&A.type!=="custom_tool_call_output");m.continuation={lastRequestBody:v,lastResponseId:n.responseId,lastResponseItems:x}}}catch(x){if(m)m.continuation=void 0;throw E=!1,x}finally{h({keep:E})}}async function Et(e){let r=await e.text(),t=r||e.statusText||"Request failed",n;try{let s=JSON.parse(r)?.error;if(s){let i=s.code||s.type||"";if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(i)||e.status===429){let u=s.plan_type?` (${s.plan_type.toLowerCase()} plan)`:"",a=s.resets_at?Math.max(0,Math.round((s.resets_at*1000-Date.now())/60000)):void 0,d=a!==void 0?` Try again in ~${a} min.`:"";n=`You have hit your ChatGPT usage limit${u}.${d}`.trim()}t=s.message||n||t}}catch{}return{message:t,friendlyMessage:n}}function _t(e){try{let r=e.split(".");if(r.length!==3)throw Error("Invalid token");let n=JSON.parse(atob(r[1]))?.[Re]?.chatgpt_account_id;if(!n)throw Error("No account ID in token");return n}catch{throw Error("Failed to extract accountId from token")}}function _e(e,r,t,n){let o=new Headers({originator:"pi","User-Agent":ee()});for(let[s,i]of Object.entries(e||{}))o.set(s,i);for(let[s,i]of Object.entries(r||{}))if(i===null)o.delete(s);else o.set(s,i);return o.set("Authorization",`Bearer ${n}`),o.set("chatgpt-account-id",t),o}function kt(e,r,t,n,o){let s=_e(e,r,t,n);if(s.set("OpenAI-Beta","responses=experimental"),s.set("accept","text/event-stream"),s.set("content-type","application/json"),o)s.set("session-id",o),s.set("x-client-request-id",o);return s}function Tt(e,r,t,n,o){let s=_e(e,r,t,n);return s.delete("accept"),s.delete("content-type"),s.delete("OpenAI-Beta"),s.delete("openai-beta"),s.set("OpenAI-Beta",tt),s.set("x-client-request-id",o),s.set("session-id",o),s}export{st as closeOpenAICodexWebSocketSessions,zt as getOpenAICodexWebSocketDebugStats,Jt as resetOpenAICodexWebSocketDebugStats,Ue as stream,$t as streamSimple};