@shumai-one/shumai 0.4.2 → 0.4.3

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 (250) hide show
  1. package/bin/{chunk-adekdctx.css → chunk-0ccg9ddn.css} +1 -1
  2. package/bin/chunk-0e4wawpq.js +2 -0
  3. package/bin/chunk-185qefn1.js +2 -0
  4. package/bin/chunk-1kw2mbqb.js +1 -0
  5. package/bin/chunk-1wm6ptdx.js +1 -0
  6. package/bin/chunk-1yacmegc.js +2 -0
  7. package/bin/chunk-2291ehh5.js +3 -0
  8. package/bin/chunk-2520aq8j.js +2 -0
  9. package/bin/chunk-29zdp63z.js +3 -0
  10. package/bin/chunk-2yxj593j.js +2 -0
  11. package/bin/chunk-32pcmaqm.js +3 -0
  12. package/bin/chunk-3a13dcs1.js +1 -0
  13. package/bin/chunk-3cyrcgm5.js +13 -0
  14. package/bin/chunk-3swpwb9v.js +1 -0
  15. package/bin/chunk-3wmcx2bv.js +2 -0
  16. package/bin/chunk-4r81ghg8.js +2 -0
  17. package/bin/chunk-4v5n0ayb.js +2 -0
  18. package/bin/chunk-5a8nt4me.js +1 -0
  19. package/bin/chunk-66hsjnw6.js +2 -0
  20. package/bin/chunk-6bhn1p8v.js +211 -0
  21. package/bin/chunk-6gg1ymer.js +2 -0
  22. package/bin/chunk-70c3xrgd.js +2 -0
  23. package/bin/chunk-7esm0hqb.js +2 -0
  24. package/bin/chunk-7fst8kdw.js +12 -0
  25. package/bin/chunk-83e12sjg.js +3 -0
  26. package/bin/chunk-87zxtf66.js +3 -0
  27. package/bin/chunk-8fmy5jtp.js +2 -0
  28. package/bin/chunk-8zqgaxvv.js +1 -0
  29. package/bin/chunk-9t1ne8xr.js +2 -0
  30. package/bin/chunk-a32vreya.js +2 -0
  31. package/bin/chunk-a3dmtt2j.js +1 -0
  32. package/bin/chunk-abt0azmv.js +2 -0
  33. package/bin/chunk-ag6p3mbf.js +2 -0
  34. package/bin/chunk-aqbrzx9z.js +1 -0
  35. package/bin/chunk-av1a8fqp.js +3 -0
  36. package/bin/chunk-awfwk64v.js +2 -0
  37. package/bin/chunk-b235azv4.js +45 -0
  38. package/bin/chunk-b9yrw9et.js +10 -0
  39. package/bin/chunk-bay038pj.js +2 -0
  40. package/bin/chunk-c007p0t8.js +299 -0
  41. package/bin/chunk-cak32x57.js +2 -0
  42. package/bin/chunk-ce8m4zeg.js +3 -0
  43. package/bin/chunk-ck8azecb.js +12 -0
  44. package/bin/chunk-cnxwmycy.js +6 -0
  45. package/bin/chunk-cqb415s6.js +5 -0
  46. package/bin/chunk-e2mvmq2m.js +1 -0
  47. package/bin/chunk-e7mqtkzn.js +2 -0
  48. package/bin/chunk-e99dv20z.js +3 -0
  49. package/bin/chunk-ea79xnn3.js +2 -0
  50. package/bin/chunk-ehc9adfz.js +2 -0
  51. package/bin/chunk-ejbvfj4r.js +1 -0
  52. package/bin/chunk-ekfem7kf.js +1 -0
  53. package/bin/chunk-etwkk0xh.js +1 -0
  54. package/bin/chunk-evrdd32b.js +2 -0
  55. package/bin/chunk-f15qyp41.js +1 -0
  56. package/bin/chunk-f3ehv01n.js +54 -0
  57. package/bin/chunk-fm6p03ad.js +2 -0
  58. package/bin/chunk-fxswt9hc.js +3 -0
  59. package/bin/chunk-fyha3r13.js +2 -0
  60. package/bin/chunk-g0vs7k2x.js +1 -0
  61. package/bin/chunk-g84z2w7v.js +16 -0
  62. package/bin/chunk-gk3eqd50.js +2 -0
  63. package/bin/chunk-h3tbf521.js +2 -0
  64. package/bin/chunk-h837fyed.js +2 -0
  65. package/bin/chunk-hfh0c082.js +2 -0
  66. package/bin/chunk-j20e0qsw.js +7 -0
  67. package/bin/chunk-j8fxp8ej.js +2 -0
  68. package/bin/chunk-jje8nj8h.js +3 -0
  69. package/bin/chunk-jy006gcv.js +7 -0
  70. package/bin/chunk-k7hss0bd.js +4 -0
  71. package/bin/chunk-m7m9d4fb.js +2 -0
  72. package/bin/chunk-n1jwdb0a.js +1 -0
  73. package/bin/chunk-p5gf1zdm.js +4 -0
  74. package/bin/chunk-pb1zf0vb.js +2 -0
  75. package/bin/chunk-pfgxggaj.js +11 -0
  76. package/bin/chunk-q16490pv.js +2 -0
  77. package/bin/chunk-q2bvyv39.js +8 -0
  78. package/bin/chunk-qf24e71w.js +2 -0
  79. package/bin/chunk-qh81zhg1.js +1 -0
  80. package/bin/chunk-qwp3kwbz.js +2 -0
  81. package/bin/chunk-qwqvt9v6.js +2 -0
  82. package/bin/chunk-qydeqgyj.js +5 -0
  83. package/bin/chunk-r7dty1tg.js +2 -0
  84. package/bin/chunk-rbj4fad9.js +32 -0
  85. package/bin/chunk-rhdxwebf.js +2 -0
  86. package/bin/chunk-rhh716z0.js +42 -0
  87. package/bin/chunk-rpywcvg1.js +3 -0
  88. package/bin/chunk-rza4ae5z.js +3 -0
  89. package/bin/chunk-sfx2588q.js +3 -0
  90. package/bin/chunk-sk4e6rb1.js +1 -0
  91. package/bin/chunk-t2n1dbgx.js +4 -0
  92. package/bin/chunk-tf28796q.js +2 -0
  93. package/bin/chunk-twdxayky.js +3 -0
  94. package/bin/chunk-v9b3w8q5.js +3 -0
  95. package/bin/chunk-v9w25rp2.js +2 -0
  96. package/bin/chunk-vgn5zcpv.js +3 -0
  97. package/bin/chunk-wfzqnpc1.js +3 -0
  98. package/bin/chunk-wry2hvrq.js +24 -0
  99. package/bin/chunk-x8f4defx.js +3 -0
  100. package/bin/chunk-xp59apdb.js +2 -0
  101. package/bin/chunk-xtf3c29c.css +1 -0
  102. package/bin/chunk-z3gkt8w1.js +3 -0
  103. package/bin/chunk-zehyn6vd.js +2 -0
  104. package/bin/chunk-zh6fqq44.js +1 -0
  105. package/bin/chunk-zmv8cg4s.js +8 -0
  106. package/bin/chunk-zqv0zhfb.js +3 -0
  107. package/bin/{pdf.worker.min-szxdj13d.mjs → pdf.worker.min-vf48er29.mjs} +14423 -13889
  108. package/bin/shumai-app.html +1 -1
  109. package/bin/shumai-app.js +626 -460
  110. package/package.json +18 -18
  111. package/prisma/migrations/20260904022457_add_agent_id_to_assets_and_audit_logs/migration.sql +17 -0
  112. package/prisma/migrations/20260906081230_default_denied_tools_delete_asset/migration.sql +15 -0
  113. package/prisma/schema.prisma +9 -0
  114. package/bin/chunk-07h4b77v.js +0 -2
  115. package/bin/chunk-0t4n4d5w.js +0 -4
  116. package/bin/chunk-1611z9jg.js +0 -2
  117. package/bin/chunk-1phqxp6z.js +0 -3
  118. package/bin/chunk-23hckrrz.js +0 -2
  119. package/bin/chunk-30z44j1g.js +0 -2
  120. package/bin/chunk-3j463k1g.js +0 -1
  121. package/bin/chunk-4181tdds.js +0 -14
  122. package/bin/chunk-480jtqng.js +0 -4
  123. package/bin/chunk-4c3g146q.js +0 -2
  124. package/bin/chunk-4ca0zt5e.js +0 -1
  125. package/bin/chunk-4d9bgmf2.js +0 -2
  126. package/bin/chunk-4ev56fss.js +0 -9
  127. package/bin/chunk-4gk52tjq.js +0 -45
  128. package/bin/chunk-4mdqkj4d.js +0 -1
  129. package/bin/chunk-4r91fggc.js +0 -2
  130. package/bin/chunk-50fb1x3w.js +0 -1
  131. package/bin/chunk-59gj1njz.js +0 -1
  132. package/bin/chunk-5pr0t7fb.js +0 -2
  133. package/bin/chunk-5vewxmz7.js +0 -3
  134. package/bin/chunk-62zx96pe.js +0 -2
  135. package/bin/chunk-63y0eb07.js +0 -2
  136. package/bin/chunk-6d5xrgfx.js +0 -2
  137. package/bin/chunk-6gbtz5bf.js +0 -67
  138. package/bin/chunk-6gjg5egq.js +0 -3
  139. package/bin/chunk-6m4jz9s1.js +0 -44
  140. package/bin/chunk-6s4x525w.js +0 -2
  141. package/bin/chunk-6w2wmvqs.js +0 -3
  142. package/bin/chunk-77d23vcn.js +0 -2
  143. package/bin/chunk-77m5p188.js +0 -2
  144. package/bin/chunk-7bvx087f.js +0 -1
  145. package/bin/chunk-7pfjfrjg.js +0 -5
  146. package/bin/chunk-7q10s127.js +0 -4
  147. package/bin/chunk-7thx8ctx.js +0 -3
  148. package/bin/chunk-8t4s91gh.js +0 -2
  149. package/bin/chunk-98ey5p2e.js +0 -3
  150. package/bin/chunk-9amndcyh.js +0 -6
  151. package/bin/chunk-9bk23g9x.js +0 -1
  152. package/bin/chunk-9mkcfy43.js +0 -1
  153. package/bin/chunk-9t3nsq5n.js +0 -2
  154. package/bin/chunk-9tjq99ds.js +0 -2
  155. package/bin/chunk-9wm9rwh1.js +0 -2
  156. package/bin/chunk-ab16fyg4.js +0 -4
  157. package/bin/chunk-arv0g2av.js +0 -1
  158. package/bin/chunk-aytj4zxg.js +0 -3
  159. package/bin/chunk-b1ypjqgp.js +0 -2
  160. package/bin/chunk-bdjv0ykq.js +0 -2
  161. package/bin/chunk-c1k86mfa.js +0 -10
  162. package/bin/chunk-caa96dgd.js +0 -2
  163. package/bin/chunk-ce4v2yjy.js +0 -1
  164. package/bin/chunk-cqh60y54.js +0 -3
  165. package/bin/chunk-cvq7zgw7.js +0 -1
  166. package/bin/chunk-d9mjbtp2.js +0 -2
  167. package/bin/chunk-dn7sbjws.js +0 -3
  168. package/bin/chunk-dxyq9h8n.js +0 -3
  169. package/bin/chunk-e3cabksx.js +0 -3
  170. package/bin/chunk-egcrbj94.js +0 -2
  171. package/bin/chunk-ev17v1mv.js +0 -2
  172. package/bin/chunk-evtpwg71.js +0 -2
  173. package/bin/chunk-f3e0nsv2.js +0 -2
  174. package/bin/chunk-f40gjqpq.js +0 -2
  175. package/bin/chunk-fe7822ak.js +0 -299
  176. package/bin/chunk-g8tkhw9j.js +0 -2
  177. package/bin/chunk-g9r0p4t8.js +0 -2
  178. package/bin/chunk-gbjyh9ms.js +0 -1
  179. package/bin/chunk-gtbsb39v.js +0 -3
  180. package/bin/chunk-gytz1q13.js +0 -13
  181. package/bin/chunk-h0fxysxs.js +0 -7
  182. package/bin/chunk-h8bdvsqt.js +0 -2
  183. package/bin/chunk-hag024w8.js +0 -2
  184. package/bin/chunk-hc6w5nw4.js +0 -7
  185. package/bin/chunk-j69dqc48.js +0 -2
  186. package/bin/chunk-jbtw1zym.js +0 -8
  187. package/bin/chunk-jc1vb7rj.js +0 -5
  188. package/bin/chunk-jdv78w9r.js +0 -2
  189. package/bin/chunk-jjs70y9v.js +0 -3
  190. package/bin/chunk-jmdar2gz.js +0 -2
  191. package/bin/chunk-jvwz10n4.js +0 -2
  192. package/bin/chunk-k47md1g4.js +0 -2
  193. package/bin/chunk-k4v0brcb.js +0 -2
  194. package/bin/chunk-k6n7c07e.js +0 -1
  195. package/bin/chunk-kk2cstsg.js +0 -2
  196. package/bin/chunk-knz4h56q.js +0 -12
  197. package/bin/chunk-kqqtt6bd.js +0 -3
  198. package/bin/chunk-kvyp1t4j.js +0 -7
  199. package/bin/chunk-kxskpgsq.js +0 -5
  200. package/bin/chunk-m6srbjcs.js +0 -2
  201. package/bin/chunk-mcc1scxs.js +0 -12
  202. package/bin/chunk-mq83a0kk.js +0 -2
  203. package/bin/chunk-mxm8g4q0.js +0 -1
  204. package/bin/chunk-nhpgdqq5.js +0 -2
  205. package/bin/chunk-nne496aa.js +0 -2
  206. package/bin/chunk-nqpb0r9h.js +0 -11
  207. package/bin/chunk-ns0zww9g.js +0 -2
  208. package/bin/chunk-ps4xfp23.js +0 -2
  209. package/bin/chunk-pz2ec6xt.js +0 -2
  210. package/bin/chunk-q163k309.js +0 -2
  211. package/bin/chunk-q1da61ps.js +0 -1
  212. package/bin/chunk-qrf0ady6.js +0 -68
  213. package/bin/chunk-qy28f25e.js +0 -2
  214. package/bin/chunk-r7s4ypw1.js +0 -2
  215. package/bin/chunk-ran23vm9.js +0 -1
  216. package/bin/chunk-rfvdc4n0.js +0 -2
  217. package/bin/chunk-rgthkvgx.js +0 -3
  218. package/bin/chunk-s39n3yw3.js +0 -2
  219. package/bin/chunk-s7wdd0g7.js +0 -8
  220. package/bin/chunk-s88ha5kx.js +0 -3
  221. package/bin/chunk-sf91bt9m.js +0 -2
  222. package/bin/chunk-sjwbjf9j.js +0 -2
  223. package/bin/chunk-t62076pv.js +0 -1
  224. package/bin/chunk-tbbwss3v.js +0 -3
  225. package/bin/chunk-tjcc7a6y.js +0 -24
  226. package/bin/chunk-tp6ab26e.js +0 -2
  227. package/bin/chunk-v2wxk9p5.js +0 -4
  228. package/bin/chunk-vbk6y4hk.js +0 -2
  229. package/bin/chunk-vfgfg5fk.js +0 -2
  230. package/bin/chunk-vm6c3xx9.js +0 -2
  231. package/bin/chunk-vsx96mt6.js +0 -3
  232. package/bin/chunk-wbyw1shz.js +0 -6
  233. package/bin/chunk-whh2vh50.css +0 -1
  234. package/bin/chunk-wjkcq65s.js +0 -2
  235. package/bin/chunk-wkefwkfp.js +0 -41
  236. package/bin/chunk-x7bsnk1e.js +0 -2
  237. package/bin/chunk-xbhw6bpz.js +0 -3
  238. package/bin/chunk-xg5yrcj5.js +0 -2
  239. package/bin/chunk-xg9xscqz.js +0 -1
  240. package/bin/chunk-xw2gpcsh.js +0 -3
  241. package/bin/chunk-ycq8ank7.js +0 -2
  242. package/bin/chunk-yp9hvkc5.js +0 -73
  243. package/bin/chunk-ytypyfkc.js +0 -65
  244. package/bin/chunk-z1kjmf60.js +0 -2
  245. package/bin/chunk-z36bx86r.js +0 -2
  246. package/bin/chunk-z7hdnecp.js +0 -3
  247. package/bin/chunk-zeby1cq7.js +0 -2
  248. package/bin/chunk-zs5e8z1w.js +0 -1
  249. package/bin/chunk-zxnyefg5.js +0 -2
  250. /package/bin/{chunk-24ke0th1.css → chunk-kegybs91.css} +0 -0
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ function Go(_){if(_===void 0)return;let n=Array.from(_);if(n.length<=64)return _;return n.slice(0,64).join("")}
3
+ export{Go};
@@ -0,0 +1,2 @@
1
+ import{T}from"./chunk-6bhn1p8v.js";var a=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],js=T("save",a);
2
+ export{js};
@@ -0,0 +1 @@
1
+ import{h,C,t,L,Ue,A,st,yt,yp}from"./chunk-6bhn1p8v.js";import"./chunk-3wmcx2bv.js";import"./chunk-j20e0qsw.js";import"./chunk-ehc9adfz.js";import"./chunk-b9yrw9et.js";import"./chunk-6gg1ymer.js";import"./chunk-bay038pj.js";import"./chunk-7esm0hqb.js";import"./chunk-q16490pv.js";import"./chunk-k7hss0bd.js";import"./chunk-c007p0t8.js";import"./chunk-cqb415s6.js";import{Zn}from"./chunk-185qefn1.js";import{Wt}from"./chunk-rhdxwebf.js";import"./chunk-4r81ghg8.js";import"./chunk-gk3eqd50.js";import"./chunk-ag6p3mbf.js";import"./chunk-9t1ne8xr.js";import"./chunk-m7m9d4fb.js";import"./chunk-1yacmegc.js";import"./chunk-r7dty1tg.js";import"./chunk-2yxj593j.js";import"./chunk-ea79xnn3.js";C();function i(){let{projectId:o}=l.useParams(),{teamId:r,ensureTeamIdForProject:a}=st();h(()=>{a(o)},[o,a]);let{data:s}=Wt(yp(o)),e=s?.rootFolder,{data:n}=L({queryKey:["folders",e],queryFn:()=>(async()=>await(await A.api.folders[":folderId"].$get({param:{folderId:e}})).json())(),enabled:!!e});if(!r||!e||!n)return t(yt,{});return t(Zn,{teamId:r,projectId:o,projectName:s.name??"",assetId:"recents",rootFolderId:e})}var l=Ue("/projects/$projectId/recents")({component:i});export{l as Route};
@@ -0,0 +1,8 @@
1
+ // @bun
2
+ import{nr}from"./chunk-sfx2588q.js";import"./chunk-qydeqgyj.js";import{Zi}from"./chunk-fxswt9hc.js";import{vs}from"./chunk-vgn5zcpv.js";import{Ua,za,Fa}from"./chunk-ck8azecb.js";import{Go}from"./chunk-z3gkt8w1.js";import{cn,un}from"./chunk-87zxtf66.js";import{zn,xr}from"./chunk-zqv0zhfb.js";import{Xr}from"./chunk-29zdp63z.js";import{Ur}from"./chunk-2291ehh5.js";import{Vt,Cs,tc,zi}from"./chunk-x8f4defx.js";var z=new Set;function X(e){return z.add(e),()=>{z.delete(e)}}function j(e){let t=e.filter((o)=>o!==void 0);if(t.length===0)return{cleanup:()=>{}};if(t.length===1)return{signal:t[0],cleanup:()=>{}};let r=new AbortController,n=[],s=(o)=>{if(!r.signal.aborted)r.abort(o.reason)};for(let o of t){if(o.aborted){s(o);break}let i=()=>s(o);o.addEventListener("abort",i,{once:!0}),n.push({signal:o,listener:i})}return{signal:r.signal,cleanup:()=>{for(let{signal:o,listener:i}of n)o.removeEventListener("abort",i)}}}var me={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function F(e,t){let r=e.toLowerCase(),n=e.toUpperCase();return t?.[r]||t?.[n]||nr(r)||nr(n)||""}function ye(e){if(e instanceof URL)return e;try{return new URL(e)}catch{return}}function be(e,t,r){let n=F("no_proxy",r).toLowerCase();if(!n)return!0;if(n==="*")return!1;return n.split(/[,\s]/).every((s)=>{if(!s)return!0;let o=s.match(/^(.+):(\d+)$/),i=o?o[1]:s,l=o?Number.parseInt(o[2],10):0;if(l&&l!==t)return!0;if(!/^[.*]/.test(i))return e!==i;if(i.startsWith("*"))i=i.slice(1);return!e.endsWith(i)})}function he(e,t){let r=ye(e);if(!r?.protocol||!r.host)return"";let n=r.protocol.split(":",1)[0],s=r.host.replace(/:\d*$/,""),o=Number.parseInt(r.port,10)||me[n]||0;if(!be(s,o,t))return"";let i=F(`${n}_proxy`,t)||F("all_proxy",t);if(i&&!i.includes("://"))i=`${n}://${i}`;return i}var we="Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL.";function V(e,t){let r=he(e,t);if(!r)return;let n;try{n=new URL(r)}catch(s){throw Error(`Invalid proxy URL ${JSON.stringify(r)}: ${s instanceof Error?s.message:String(s)}`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw Error(`${we} Got ${n.protocol}`);return n}function ge(){if(typeof process>"u"||!(process.versions?.node||process.versions?.bun))return null;return process.getBuiltinModule?.("node:os")??null}var D=ge(),Se="https://chatgpt.com/backend-api",Ee="https://api.openai.com/auth",_e=0,Y=1000,ke=60000,Te=15000,Re=3,ne=new Set(["openai","openai-codex","opencode"]),xe=1009,ve="websocket_connection_limit_reached",Ce="previous_response_not_found",Oe=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function Ae(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}function Le(e,t){if(e===429&&Ae(t))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(t)}function We(e){let t=e.get("retry-after-ms");if(t!==null){let o=Number(t);if(Number.isFinite(o))return Math.max(0,o)}let r=e.get("retry-after");if(!r)return;let n=Number(r);if(Number.isFinite(n))return Math.max(0,n*1000);let s=Date.parse(r);if(!Number.isNaN(s))return Math.max(0,s-Date.now());return}class K extends Error{}function Ne(e,t){let r=t?.maxRetryDelayMs??ke;if(r>0&&e>r)throw new K(`Server requested ${Math.ceil(e/1000)}s retry delay (max: ${Math.ceil(r/1000)}s)`);return e}function Z(e,t){return new Promise((r,n)=>{if(t?.aborted){n(Error("Request was aborted"));return}let s=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(s),n(Error("Request was aborted"))})})}function Q(e){if(e===void 0)return;if(!Number.isFinite(e)||e<0)throw Error(`Invalid timeoutMs: ${String(e)}`);return Math.floor(e)}function Pe(){if(typeof process>"u"||!(process.versions?.node||process.versions?.bun))return null;return process.getBuiltinModule?.("node:zlib")??null}function Me(e){let t=Pe();if(!t||typeof t.zstdCompressSync!=="function")return null;try{let r=t.zstdCompressSync(e,{params:{[t.constants.ZSTD_c_compressionLevel]:Re}});return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}catch{return null}}var De=(e,t,r)=>{let n=new Vt;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:"stop",timestamp:Date.now()};try{let o=r?.apiKey;if(!o)throw Error(`No API key for provider: ${e.provider}`);let i=ft(o),l=zn(t.tools,e.compat?.supportsOpenAIGrammarTools??!1),a=r?.cacheRetention==="none"?void 0:r?.sessionId,c=Go(a),d=Ie(e,t,r,c,l),u=await r?.onPayload?.(d,e);if(u!==void 0)d=u;let g=c||Zi(),f=dt(e.headers,r?.headers,i,o,c),S=pt(e.headers,r?.headers,i,o,g),m=JSON.stringify(d),p=Q(r?.timeoutMs),x=Q(r?.websocketConnectTimeoutMs),y=r?.transport||"auto",h=!1,b=y!=="sse"&&ce(a);if(b)ee(a);if(y!=="sse"&&!b){let w=!1,_=!1,C=!1;while(!0){w=!1;try{if(await ut(Be(e.baseUrl),d,S,s,n,e,()=>{if(w=!0,!h)h=!0,n.push({type:"start",partial:s})},p,x,a,l,r),r?.signal?.aborted)throw Error("Request was aborted");n.push({type:"done",reason:s.stopReason,message:s}),n.end();return}catch(T){let N=r?.signal?.aborted,P=!w&&Fe(T),A=Je(T);if(!N&&A&&!C){C=!0;continue}if(!N&&P&&!_){_=!0;continue}if(N||$e(T)&&!P)throw T;if(zi(s,tc("provider_transport_failure",T,{configuredTransport:y,fallbackTransport:w?void 0:"sse",eventsEmitted:w,phase:w?"after_message_stream_start":"before_message_stream_start",requestBytes:new TextEncoder().encode(m).byteLength})),Ye(a,T),w)throw T;ee(a);break}}}let v=Me(m);if(v)f.set("content-encoding","zstd");let O=v??m,E,W,U=r?.maxRetries??_e;for(let w=0;w<=U;w++){if(r?.signal?.aborted)throw Error("Request was aborted");try{let _=p!==void 0&&p>0?AbortSignal.timeout(p):void 0,C=j([r?.signal,_]);try{E=await fetch(ie(e.baseUrl),{method:"POST",headers:f,body:O,signal:C.signal})}catch(A){if(_?.aborted&&!r?.signal?.aborted)throw Error(`Codex SSE response headers timed out after ${p}ms`);throw A}finally{C.cleanup()}if(await r?.onResponse?.({status:E.status,headers:Xr(E.headers)},e),E.ok)break;let T=await E.text();if(w<U&&Le(E.status,T)){let A=We(E.headers),pe=A===void 0?Y*2**w:Ne(A,r);await Z(pe,r?.signal);continue}let N=new Response(T,{status:E.status,statusText:E.statusText}),P=await lt(N);throw Error(P.friendlyMessage||P.message)}catch(_){if(_ instanceof Error){if(_.name==="AbortError"||_.message==="Request was aborted")throw Error("Request was aborted")}if(W=_ instanceof Error?_:Error(String(_)),w<U&&!(W instanceof K)&&!W.message.includes("usage limit")){let C=Y*2**w;await Z(C,r?.signal);continue}throw W}}if(!E?.ok)throw W??Error("Failed after retries");if(!E.body)throw Error("No response body");if(!h)h=!0,n.push({type:"start",partial:s});if(await Ue(E,s,n,e,l,r),r?.signal?.aborted)throw Error("Request was aborted");n.push({type:"done",reason:s.stopReason,message:s}),n.end()}catch(o){for(let i of s.content)delete i.partialJson,delete i.customInput;s.stopReason=r?.signal?.aborted?"aborted":"error",s.errorMessage=un(cn(o)),n.push({type:"error",reason:s.stopReason,error:s}),n.end()}})(),n},Wt=(e,t,r)=>{let n=r?.apiKey;if(!n)throw Error(`No API key for provider: ${e.provider}`);let s=xr(e,t,r,n),o=r?.reasoning?Ur(e,r.reasoning):void 0;return De(e,t,{...s,reasoningEffort:o==="off"?void 0:o})};function Ie(e,t,r,n,s=zn(t.tools,e.compat?.supportsOpenAIGrammarTools??!1)){let o=e.compat?.supportsStrictMode??!0,i=e.compat?.supportsOpenAIGrammarTools??!1,l=vs(t,e.compat?.supportsToolSearch??!1),a=Ua(e,t,ne,{includeSystemPrompt:!1,grammarToolInputProperties:s,deferredTools:l.deferred,toolOptions:{strict:null,supportsStrictMode:o,supportsOpenAIGrammarTools:i}}),c={model:e.id,store:!1,stream:!0,instructions:t.systemPrompt||"You are a helpful assistant.",input:a,text:{verbosity:r?.textVerbosity||"low"},include:["reasoning.encrypted_content"],prompt_cache_key:n,tool_choice:r?.toolChoice??"auto",parallel_tool_calls:!0};if(r?.temperature!==void 0)c.temperature=r.temperature;if(r?.serviceTier!==void 0)c.service_tier=r.serviceTier;if(l.immediate.length>0)c.tools=za(l.immediate,{strict:null,supportsStrictMode:o,supportsOpenAIGrammarTools:i});if(r?.reasoningEffort!==void 0){let d=r.reasoningEffort==="none"?e.thinkingLevelMap?.off??"none":e.thinkingLevelMap?.[r.reasoningEffort]??r.reasoningEffort;if(d!==null)c.reasoning={effort:d,summary:r.reasoningSummary??"auto"}}return c}function qe(e,t){switch(t){case"flex":return 0.5;case"priority":return e.id==="gpt-5.5"?2.5:2;default:return 1}}function oe(e,t,r){let n=qe(r,t);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 se(e,t){if(e==="default"&&(t==="flex"||t==="priority"))return t;return e??t}function ie(e){let r=(e&&e.trim().length>0?e:Se).replace(/\/+$/,"");if(r.endsWith("/codex/responses"))return r;if(r.endsWith("/codex"))return`${r}/responses`;return`${r}/codex/responses`}function Be(e){let t=new URL(ie(e));if(t.protocol==="https:")t.protocol="wss:";if(t.protocol==="http:")t.protocol="ws:";return t.toString()}async function Ue(e,t,r,n,s,o){await Fa(ae(Ge(e,o?.signal)),t,r,n,{serviceTier:o?.serviceTier,grammarToolInputProperties:s,resolveServiceTier:se,applyServiceTierPricing:(i,l)=>oe(i,l,n)})}class L extends Error{code;payload;constructor(e,t){super(e);this.name="CodexApiError",this.code=t?.code,this.payload=t?.payload,this.cause=t?.cause}}class B extends Error{payload;constructor(e,t){super(e);this.name="CodexProtocolError",this.payload=t?.payload,this.cause=t?.cause}}function $e(e){return e instanceof L||e instanceof B}function Fe(e){return e instanceof L&&e.code===ve}function Je(e){return e instanceof L&&e.code===Ce}function He(e){let t=e.error&&typeof e.error==="object"?e.error:void 0;return{code:typeof e.code==="string"?e.code:typeof t?.code==="string"?t.code:void 0,message:typeof e.message==="string"?e.message:typeof t?.message==="string"?t.message:void 0}}async function*ae(e){for await(let t of e){let r=typeof t.type==="string"?t.type:void 0;if(!r)continue;if(r==="error"){let{code:n,message:s}=He(t);throw new L(`Codex error: ${s||n||JSON.stringify(t)}`,{code:n,payload:t})}if(r==="response.failed"){let n=t.response,s=n?.error?.code,o=n?.error?.message;throw new L(o||"Codex response failed",{code:s,payload:t})}if(r==="response.done"||r==="response.completed"||r==="response.incomplete"){let n=t.response,s=n?{...n,status:Ke(n.status)}:n;yield{...t,type:"response.completed",response:s};return}yield t}}function Ke(e){if(typeof e!=="string")return;return Oe.has(e)?e:void 0}async function*Ge(e,t){if(!e.body)return;let r=e.body.getReader(),n=new TextDecoder,s="",o=()=>{r.cancel().catch(()=>{})};t?.addEventListener("abort",o,{once:!0});try{while(!0){if(t?.aborted)throw Error("Request was aborted");let{done:i,value:l}=await r.read();if(t?.aborted)throw Error("Request was aborted");if(i)break;s+=n.decode(l,{stream:!0});let a=s.indexOf(`
3
+
4
+ `);while(a!==-1){let c=s.slice(0,a);s=s.slice(a+2);let d=c.split(`
5
+ `).filter((u)=>u.startsWith("data:")).map((u)=>u.slice(5).trim());if(d.length>0){let u=d.join(`
6
+ `).trim();if(u&&u!=="[DONE]")try{yield JSON.parse(u)}catch(g){throw new B(`Invalid Codex SSE JSON: ${Cs(g)}`,{cause:g,payload:u})}}a=s.indexOf(`
7
+
8
+ `)}}}finally{t?.removeEventListener("abort",o);try{await r.cancel()}catch{}try{r.releaseLock()}catch{}}}var ze="responses_websockets=2026-02-06",Xe=300000,je=3300000,k=new Map,M=new Map,q=new Set;function G(e){let t=M.get(e);if(!t)t={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},M.set(e,t);return t}function Nt(e){let t=M.get(e);return t?{...t}:void 0}function Pt(e){if(e){M.delete(e),q.delete(e);return}M.clear(),q.clear()}function Ve(e){let t=(r)=>{if(r.idleTimer)clearTimeout(r.idleTimer);R(r.socket,1000,"debug_close")};if(e){let r=k.get(e);if(r)t(r);k.delete(e);return}for(let r of k.values())t(r);k.clear()}X(Ve);function ce(e){return e?q.has(e):!1}function ee(e){if(!e)return;let t=G(e);t.sseFallbacks++,t.websocketFallbackActive=ce(e)}function Ye(e,t){if(!e)return;q.add(e);let r=G(e);r.websocketFailures++,r.lastWebSocketError=Cs(t),r.websocketFallbackActive=!0}var J=null;async function Ze(e){if(!e&&J)return J;if(typeof process<"u"&&process.versions?.bun){let r=class extends WebSocket{constructor(n,s){let o={};if(Array.isArray(s)||typeof s==="string")o={protocols:s};else o={...s};let i=V(n.toString().replace(/^wss:/,"https:").replace(/^ws:/,"http:"),e);super(n,{...o,...i?{proxy:i.toString()}:{}})}};if(!e)J=r;return r}let t=globalThis.WebSocket;if(typeof t!=="function")return null;return t}class ue extends Error{code;reason;wasClean;constructor(e,t){super(e);this.name="WebSocketCloseError",this.code=t?.code,this.reason=t?.reason,this.wasClean=t?.wasClean}}function Qe(e){let t=e.readyState;return typeof t==="number"?t:void 0}function I(e){let t=Qe(e);return t===void 0||t===1}function et(e){return Date.now()-e.createdAt>=je}function R(e,t=1000,r="done"){try{e.close(t,r)}catch{}}function te(e,t){if(t.idleTimer)clearTimeout(t.idleTimer);t.idleTimer=setTimeout(()=>{if(t.busy)return;R(t.socket,1000,"idle_timeout"),k.delete(e)},Xe)}async function H(e,t,r,n=Te,s){let o=await Ze(s);if(!o)throw Error("WebSocket transport is not available in this runtime");let i=Xr(t);return delete i["OpenAI-Beta"],new Promise((l,a)=>{let c=!1,d,u;try{u=new o(e,{headers:i})}catch(y){a(y instanceof Error?y:Error(String(y)));return}let g=()=>{if(d)clearTimeout(d),d=void 0;u.removeEventListener("open",S),u.removeEventListener("error",m),u.removeEventListener("close",p),r?.removeEventListener("abort",x)},f=(y,h)=>{if(c)return;if(c=!0,g(),h)R(u,1000,h);a(y)},S=()=>{if(c)return;c=!0,g(),l(u)},m=(y)=>{f(le(y))},p=(y)=>{f(fe(y))},x=()=>{f(Error("Request was aborted"),"aborted")};if(u.addEventListener("open",S),u.addEventListener("error",m),u.addEventListener("close",p),r?.addEventListener("abort",x),n>0)d=setTimeout(()=>{f(Error(`WebSocket connect timeout after ${n}ms`),"connect_timeout")},n);if(r?.aborted)x()})}async function tt(e,t,r,n,s,o){if(!r){let c=await H(e,t,n,s,o);return{socket:c,reused:!1,release:()=>R(c)}}let i=k.get(r);if(i){if(i.idleTimer)clearTimeout(i.idleTimer),i.idleTimer=void 0;if(!i.busy&&et(i))R(i.socket,1000,"connection_age_limit"),k.delete(r);else if(!i.busy&&I(i.socket))return i.busy=!0,{socket:i.socket,entry:i,reused:!0,release:({keep:c}={})=>{if(!c||!I(i.socket)){R(i.socket),k.delete(r);return}i.busy=!1,te(r,i)}};if(i.busy){let c=await H(e,t,n,s,o);return{socket:c,reused:!1,release:()=>{R(c)}}}if(!I(i.socket))R(i.socket),k.delete(r)}let l=await H(e,t,n,s,o),a={socket:l,busy:!0,createdAt:Date.now()};return k.set(r,a),{socket:l,entry:a,reused:!1,release:({keep:c}={})=>{if(!c||!I(a.socket)){if(R(a.socket),a.idleTimer)clearTimeout(a.idleTimer);if(k.get(r)===a)k.delete(r);return}a.busy=!1,te(r,a)}}}function le(e){if(e&&typeof e==="object"){let t="message"in e?e.message:void 0;if(typeof t==="string"&&t.length>0)return Error(t);let r="error"in e?e.error:void 0;if(r instanceof Error&&r.message.length>0)return r;if(r&&typeof r==="object"&&"message"in r){let n=r.message;if(typeof n==="string"&&n.length>0)return Error(n)}}return Error("WebSocket error")}function fe(e){if(e&&typeof e==="object"){let t="code"in e?e.code:void 0,r="reason"in e?e.reason:void 0,n="wasClean"in e?e.wasClean:void 0,s=typeof t==="number"?` ${t}`:"",o=typeof r==="string"&&r.length>0?` ${r}`:"";if(!o&&t===xe)o=" message too big";return new ue(`WebSocket closed${s}${o}`.trim(),{code:typeof t==="number"?t:void 0,reason:typeof r==="string"&&r.length>0?r:void 0,wasClean:typeof n==="boolean"?n:void 0})}return Error("WebSocket closed")}async function rt(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 r=await e.arrayBuffer();return new TextDecoder().decode(new Uint8Array(r))}return null}async function*nt(e,t,r){let n=[],s=null,o=!1,i=null,l=!1,a=()=>{if(!s)return;let f=s;s=null,f()},c=(f)=>{(async()=>{let S=null;try{if(!f||typeof f!=="object"||!("data"in f))return;if(S=await rt(f.data),!S)return;let m=JSON.parse(S),p=typeof m.type==="string"?m.type:"";if(p==="response.completed"||p==="response.done"||p==="response.incomplete")l=!0,o=!0;n.push(m),a()}catch(m){i=new B(`Invalid Codex WebSocket JSON: ${Cs(m)}`,{cause:m,payload:S}),o=!0,a()}})()},d=(f)=>{i=le(f),o=!0,a()},u=(f)=>{if(l){o=!0,a();return}if(!i)i=fe(f);o=!0,a()},g=()=>{i=Error("Request was aborted"),o=!0,a()};e.addEventListener("message",c),e.addEventListener("error",d),e.addEventListener("close",u),t?.addEventListener("abort",g);try{while(!0){if(t?.aborted)throw Error("Request was aborted");if(n.length>0){yield n.shift();continue}if(o)break;let f;await new Promise((S,m)=>{if(s=S,r!==void 0&&r>0)f=setTimeout(()=>{let p=Error(`WebSocket idle timeout after ${r}ms`);i=p,o=!0,s=null,R(e,1000,"idle_timeout"),m(p)},r)}).finally(()=>{if(f)clearTimeout(f)})}if(i)throw i;if(!l)throw Error("WebSocket stream closed before response.completed")}finally{e.removeEventListener("message",c),e.removeEventListener("error",d),e.removeEventListener("close",u),t?.removeEventListener("abort",g)}}function re(e){let{input:t,previous_response_id:r,...n}=e;return n}function ot(e,t){return JSON.stringify(e??[])===JSON.stringify(t??[])}function st(e,t){return JSON.stringify(re(e))===JSON.stringify(re(t))}function it(e,t){if(!st(e,t.lastRequestBody))return;let r=e.input??[],n=[...t.lastRequestBody.input??[],...t.lastResponseItems];if(r.length<n.length)return;let s=r.slice(0,n.length);if(!ot(s,n))return;return r.slice(n.length)}function at(e,t){let r=e.continuation;if(!r)return t;let n=it(t,r);if(!n||!r.lastResponseId)return e.continuation=void 0,t;return{...t,previous_response_id:r.lastResponseId,input:n}}async function*ct(e,t){let r=!1;for await(let n of e){if(!r)r=!0,t();yield n}}async function ut(e,t,r,n,s,o,i,l,a,c,d,u){let{socket:g,entry:f,reused:S,release:m}=await tt(e,r,c,u?.signal,a,u?.env),p=!0,x=u?.transport==="websocket-cached"||u?.transport==="auto",y=t,h=x&&f?at(f,y):y,b=c?G(c):void 0;if(b){if(b.requests++,S)b.connectionsReused++;else b.connectionsCreated++;if(x)b.cachedContextRequests++;if(h.store===!0)b.storeTrueRequests++;if(b.lastInputItems=h.input?.length??0,h.previous_response_id)b.deltaRequests++,b.lastDeltaInputItems=h.input?.length??0,b.lastPreviousResponseId=h.previous_response_id;else b.fullContextRequests++,b.lastDeltaInputItems=void 0,b.lastPreviousResponseId=void 0}try{if(g.send(JSON.stringify({type:"response.create",...h})),await Fa(ct(ae(nt(g,u?.signal,l)),i),n,s,o,{serviceTier:u?.serviceTier,grammarToolInputProperties:d,resolveServiceTier:se,applyServiceTierPricing:(v,O)=>oe(v,O,o)}),u?.signal?.aborted)p=!1;else if(x&&f&&n.responseId){let v=Ua(o,{messages:[n]},ne,{includeSystemPrompt:!1,grammarToolInputProperties:d}).filter((O)=>O.type!=="function_call_output"&&O.type!=="custom_tool_call_output");f.continuation={lastRequestBody:y,lastResponseId:n.responseId,lastResponseItems:v}}}catch(v){if(f)f.continuation=void 0;throw p=!1,v}finally{m({keep:p})}}async function lt(e){let t=await e.text(),r=t||e.statusText||"Request failed",n;try{let o=JSON.parse(t)?.error;if(o){let i=o.code||o.type||"";if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(i)||e.status===429){let l=o.plan_type?` (${o.plan_type.toLowerCase()} plan)`:"",a=o.resets_at?Math.max(0,Math.round((o.resets_at*1000-Date.now())/60000)):void 0,c=a!==void 0?` Try again in ~${a} min.`:"";n=`You have hit your ChatGPT usage limit${l}.${c}`.trim()}r=o.message||n||r}}catch{}return{message:r,friendlyMessage:n}}function ft(e){try{let t=e.split(".");if(t.length!==3)throw Error("Invalid token");let n=JSON.parse(atob(t[1]))?.[Ee]?.chatgpt_account_id;if(!n)throw Error("No account ID in token");return n}catch{throw Error("Failed to extract accountId from token")}}function de(e,t,r,n){let s=new Headers(e);for(let[i,l]of Object.entries(t||{}))if(l===null)s.delete(i);else s.set(i,l);s.set("Authorization",`Bearer ${n}`),s.set("chatgpt-account-id",r),s.set("originator","pi");let o=D?`pi (${D.platform()} ${D.release()}; ${D.arch()})`:"pi (browser)";return s.set("User-Agent",o),s}function dt(e,t,r,n,s){let o=de(e,t,r,n);if(o.set("OpenAI-Beta","responses=experimental"),o.set("accept","text/event-stream"),o.set("content-type","application/json"),s)o.set("session-id",s),o.set("x-client-request-id",s);return o}function pt(e,t,r,n,s){let o=de(e,t,r,n);return o.delete("accept"),o.delete("content-type"),o.delete("OpenAI-Beta"),o.delete("openai-beta"),o.set("OpenAI-Beta",ze),o.set("x-client-request-id",s),o.set("session-id",s),o}export{Ve as closeOpenAICodexWebSocketSessions,Nt as getOpenAICodexWebSocketDebugStats,Pt as resetOpenAICodexWebSocketDebugStats,De as stream,Wt as streamSimple};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ function Fe(e){return e.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"")}function Jl(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 Xl(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 o=t.slice(e.input.length);if(!r&&o.length===0)return;let i="";if(!e.started)i+=`{${JSON.stringify(n)}:"`,e.started=!0;if(i+=JSON.stringify(o).slice(1,-1),e.input=t,r)i+='"}',e.closed=!0;return i}function C(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 oo(e,n){let t=e.constrainedSampling;if(!t||t.type!=="json_schema")return;if(n)return!0;if(t.strict==="require")throw Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`);return}function Ui(e,n){let t=e.constrainedSampling;if(!t||t.type!=="grammar")return;if(!n)return;let r=t.variants.openai_lark,o=t.variants.openai_regex,i=typeof r==="string"&&r.trim().length>0,d=typeof o==="string"&&o.trim().length>0;if(!i&&!d)throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:i?"lark":"regex",definition:i?r:o,inputProperty:C(e)}}catch(l){let c=l instanceof Error?l.message:String(l);throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: ${c}.`)}}function zn(e,n){let t=new Map;for(let r of e??[]){let o=Ui(r,n);if(o)t.set(r.name,o.inputProperty)}return t}function R(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}function S(e){try{return JSON.stringify(e)??"undefined"}catch{return"[unserializable]"}}function N(e){if(typeof e==="string")return e.length;let n=0;for(let t of e)n+=t.type==="text"?t.text.length:4800;return n}function k(e){return Math.ceil(e.length/4)}function y(e){return Math.ceil(N(e)/4)}function I(e){let n=0;if(e.role==="user")return y(e.content);if(e.role==="toolResult")return y(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+S(t.arguments).length;return Math.ceil(n/4)}function O(e){let n=Number.NEGATIVE_INFINITY,t;for(let r=0;r<e.length;r++){let o=e[r];if(o.role==="assistant"){let i=o;if(i.timestamp>=n&&i.stopReason!=="aborted"&&i.stopReason!=="error"&&R(i.usage)>0)t={usage:i.usage,index:r}}n=Math.max(n,o.timestamp)}return t}function E(e){let n=O(e);if(n){let r=R(n.usage),o=0;for(let i=n.index+1;i<e.length;i++)o+=I(e[i]);return{tokens:r+o,usageTokens:r,trailingTokens:o,lastUsageIndex:n.index}}let t=0;for(let r of e)t+=I(r);return{tokens:t,usageTokens:0,trailingTokens:t,lastUsageIndex:null}}function M(e){if(!e||e.length===0)return 0;return k(S(e))}function D(e){return Array.isArray(e)}function w(e){if(D(e))return E(e);let n=E(e.messages);if(n.lastUsageIndex!==null){let r=new Set(e.messages.slice(n.lastUsageIndex+1).filter((i)=>i.role==="toolResult").flatMap((i)=>i.addedToolNames??[])),o=M(e.tools?.filter((i)=>r.has(i.name)));return{tokens:n.tokens+o,usageTokens:n.usageTokens,trailingTokens:n.trailingTokens+o,lastUsageIndex:n.lastUsageIndex}}let t=(e.systemPrompt?k(e.systemPrompt):0)+M(e.tools);return{tokens:n.tokens+t,usageTokens:n.usageTokens,trailingTokens:n.trailingTokens+t,lastUsageIndex:n.lastUsageIndex}}var P=4096,_=1;function Fd(e,n,t){if(e.contextWindow<=0)return Math.max(_,t);let r=e.contextWindow-w(n).tokens-P;return Math.min(t,Math.max(_,r))}function xr(e,n,t,r){return{temperature:t?.temperature,maxTokens:Fd(e,n,t?.maxTokens??e.maxTokens),signal:t?.signal,apiKey:r||t?.apiKey,transport:t?.transport,cacheRetention:t?.cacheRetention,sessionId:t?.sessionId,headers:t?.headers,onPayload:t?.onPayload,onResponse:t?.onResponse,timeoutMs:t?.timeoutMs,websocketConnectTimeoutMs:t?.websocketConnectTimeoutMs,maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,metadata:t?.metadata,env:t?.env}}function v(e){return e==="xhigh"||e==="max"?"high":e}function Bp(e,n,t,r){let i={...{minimal:1024,low:2048,medium:8192,high:16384},...r},d=1024,l=v(t),c=i[l],f=e===void 0?n:Math.min(e+c,n);if(f<=c)c=Math.max(0,f-1024);return{maxTokens:f,thinkingBudget:c}}function A(e,n){let t=[],r=!1;for(let o of e){if(o.type==="image"){if(!r)t.push({type:"text",text:n});r=!0;continue}t.push(o),r=o.text===n}return t}function F(e,n){if(n.input.includes("image"))return e;return e.map((t)=>{if(t.role==="user"&&Array.isArray(t.content))return{...t,content:A(t.content,"(image omitted: model does not support images)")};if(t.role==="toolResult")return{...t,content:A(t.content,"(tool image omitted: model does not support images)")};return t})}function ao(e,n,t){let r=new Map,o=e.map((a)=>a.content==null?{...a,content:[]}:a),d=F(o,n).map((a)=>{if(a.role==="user")return a;if(a.role==="toolResult"){let s=r.get(a.toolCallId);if(s&&s!==a.toolCallId)return{...a,toolCallId:s};return a}if(a.role==="assistant"){let s=a,p=s.provider===n.provider&&s.api===n.api&&s.model===n.id,h=s.content.flatMap((u)=>{if(u.type==="thinking"){if(u.redacted)return p?u:[];if(p&&u.thinkingSignature)return u;if(!u.thinking||u.thinking.trim()==="")return[];if(p)return u;return{type:"text",text:u.thinking}}if(u.type==="text"){if(p)return u;return{type:"text",text:u.text}}if(u.type==="toolCall"){let m=u,g=m;if(!p&&m.thoughtSignature)g={...m},delete g.thoughtSignature;if(!p&&t){let x=t(m.id,n,s);if(x!==m.id)r.set(m.id,x),g={...g,id:x}}return g}return u});return{...s,content:h}}return a}),l=[],c=[],f=new Set,T=()=>{if(c.length>0){for(let a of c)if(!f.has(a.id))l.push({role:"toolResult",toolCallId:a.id,toolName:a.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});c=[],f=new Set}};for(let a=0;a<d.length;a++){let s=d[a];if(s.role==="assistant"){T();let p=s;if(p.stopReason==="error"||p.stopReason==="aborted")continue;let h=p.content.filter((u)=>u.type==="toolCall");if(h.length>0)c=h,f=new Set;l.push(s)}else if(s.role==="toolResult")f.add(s.toolCallId),l.push(s);else if(s.role==="user")T(),l.push(s);else l.push(s)}return T(),l}
3
+ export{Fe,Jl,Xl,oo,Ui,zn,Fd,xr,Bp,ao};