@shumai-one/shumai 0.4.3 → 0.4.4

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 (168) hide show
  1. package/bin/chunk-071x515q.js +4 -0
  2. package/bin/chunk-0cmx7k4c.js +1 -0
  3. package/bin/{chunk-cqb415s6.js → chunk-0qaq0sp8.js} +2 -2
  4. package/bin/chunk-0qjfahk9.js +2 -0
  5. package/bin/{chunk-9t1ne8xr.js → chunk-0zv3bks2.js} +2 -2
  6. package/bin/chunk-16xax8kk.js +1 -0
  7. package/bin/chunk-1gvscz88.js +5 -0
  8. package/bin/{chunk-6gg1ymer.js → chunk-1j27fzy1.js} +2 -2
  9. package/bin/chunk-1t167cvj.js +11 -0
  10. package/bin/{chunk-pb1zf0vb.js → chunk-1xh34aew.js} +2 -2
  11. package/bin/{chunk-zmv8cg4s.js → chunk-1zwajpwf.js} +3 -3
  12. package/bin/chunk-2w5xqhjm.js +1 -0
  13. package/bin/{chunk-f3ehv01n.js → chunk-3tedzb2j.js} +26 -26
  14. package/bin/{chunk-zehyn6vd.js → chunk-3ttrhqy3.js} +2 -2
  15. package/bin/chunk-3zkasqb8.js +1 -0
  16. package/bin/chunk-453ykvaw.js +2 -0
  17. package/bin/{chunk-3cyrcgm5.js → chunk-4991gz3y.js} +9 -9
  18. package/bin/chunk-4hkkdm2q.js +2 -0
  19. package/bin/chunk-4mjywsj8.js +3 -0
  20. package/bin/{chunk-cnxwmycy.js → chunk-4v41a1r9.js} +3 -3
  21. package/bin/{chunk-87zxtf66.js → chunk-4wy87hwd.js} +2 -2
  22. package/bin/{chunk-sfx2588q.js → chunk-579e4wv4.js} +2 -2
  23. package/bin/{chunk-1yacmegc.js → chunk-5adsx8x4.js} +2 -2
  24. package/bin/{chunk-b235azv4.js → chunk-5hg6kcfz.js} +13 -13
  25. package/bin/{chunk-rbj4fad9.js → chunk-5nm2jvg5.js} +13 -13
  26. package/bin/chunk-5tcdwep5.js +11 -0
  27. package/bin/chunk-5vzrpz50.js +2 -0
  28. package/bin/chunk-6ghcj4a9.js +3 -0
  29. package/bin/{chunk-b9yrw9et.js → chunk-77fmkpdz.js} +4 -4
  30. package/bin/chunk-7bcxj1jd.js +2 -0
  31. package/bin/{chunk-qf24e71w.js → chunk-7gmdnsdg.js} +1 -1
  32. package/bin/{chunk-fxswt9hc.js → chunk-7jtmwt5a.js} +2 -2
  33. package/bin/chunk-7kjgvxqa.js +2 -0
  34. package/bin/{chunk-bay038pj.js → chunk-7pw1550a.js} +2 -2
  35. package/bin/chunk-7rhz2gze.js +211 -0
  36. package/bin/chunk-837fky18.js +3 -0
  37. package/bin/chunk-84as6x83.js +1 -0
  38. package/bin/chunk-8e28hcny.js +2 -0
  39. package/bin/{chunk-k7hss0bd.js → chunk-914bp49r.js} +3 -3
  40. package/bin/chunk-97f2af6d.js +12 -0
  41. package/bin/{chunk-4r81ghg8.js → chunk-98715kc3.js} +2 -2
  42. package/bin/chunk-9ccw540k.js +2 -0
  43. package/bin/{chunk-ag6p3mbf.js → chunk-9t8n2des.js} +2 -2
  44. package/bin/chunk-9ybt6vbm.js +1 -0
  45. package/bin/{chunk-f15qyp41.js → chunk-a6gx7f5q.js} +1 -1
  46. package/bin/chunk-avwgktxb.js +2 -0
  47. package/bin/chunk-bkr5zm4h.js +2 -0
  48. package/bin/{chunk-2yxj593j.js → chunk-cbgq517y.js} +2 -2
  49. package/bin/chunk-d27mm390.js +1 -0
  50. package/bin/{chunk-185qefn1.js → chunk-dj92fss9.js} +2 -2
  51. package/bin/{chunk-v9w25rp2.js → chunk-dqxeztfa.js} +2 -2
  52. package/bin/chunk-drepsbb4.js +2 -0
  53. package/bin/chunk-f6svp4dp.js +2 -0
  54. package/bin/{chunk-q2bvyv39.js → chunk-fahk9h62.js} +2 -2
  55. package/bin/{chunk-v9b3w8q5.js → chunk-fb40xxz3.js} +2 -2
  56. package/bin/chunk-fnmwksnb.js +3 -0
  57. package/bin/chunk-fpc4p0j8.js +3 -0
  58. package/bin/{chunk-aqbrzx9z.js → chunk-fsyzs0tf.js} +1 -1
  59. package/bin/{chunk-e2mvmq2m.js → chunk-fxecgp5k.js} +1 -1
  60. package/bin/{chunk-wfzqnpc1.js → chunk-g3fpmyyn.js} +2 -2
  61. package/bin/{chunk-ehc9adfz.js → chunk-gc5sbfa5.js} +2 -2
  62. package/bin/chunk-gdm6yfqq.js +2 -0
  63. package/bin/{chunk-ea79xnn3.js → chunk-gk2q9a3f.js} +2 -2
  64. package/bin/{chunk-jje8nj8h.js → chunk-gt4csat6.js} +2 -2
  65. package/bin/chunk-gye8gabk.js +2 -0
  66. package/bin/{chunk-wry2hvrq.js → chunk-hk5rc6cd.js} +2 -2
  67. package/bin/{chunk-zqv0zhfb.js → chunk-hm0dkzed.js} +2 -2
  68. package/bin/chunk-hmpwg5za.js +16 -0
  69. package/bin/{chunk-rpywcvg1.js → chunk-j1tkmcae.js} +2 -2
  70. package/bin/chunk-j2bvj2yn.js +2 -0
  71. package/bin/chunk-jffktpqg.js +1 -0
  72. package/bin/chunk-jgs8an3h.js +18 -0
  73. package/bin/{chunk-8fmy5jtp.js → chunk-jmpb5633.js} +1 -1
  74. package/bin/{chunk-xp59apdb.js → chunk-jrjnqx78.js} +1 -1
  75. package/bin/chunk-k2k9vjq6.js +1 -0
  76. package/bin/{chunk-32pcmaqm.js → chunk-kpgfqkp0.js} +2 -2
  77. package/bin/{chunk-twdxayky.js → chunk-ks8xzc95.js} +2 -2
  78. package/bin/{chunk-qwqvt9v6.js → chunk-kswvyqq1.js} +2 -2
  79. package/bin/{chunk-gk3eqd50.js → chunk-m9pr03kn.js} +2 -2
  80. package/bin/chunk-mfn9qjm4.js +2 -0
  81. package/bin/{chunk-e99dv20z.js → chunk-msfw3jmc.js} +2 -2
  82. package/bin/chunk-mz0yjra0.js +5 -0
  83. package/bin/chunk-nbdw8fen.js +1 -0
  84. package/bin/{chunk-cak32x57.js → chunk-nkdk229f.js} +1 -1
  85. package/bin/chunk-nr20tvnw.js +3 -0
  86. package/bin/{chunk-ck8azecb.js → chunk-pazjhrnf.js} +5 -5
  87. package/bin/chunk-q806pqeh.js +1 -0
  88. package/bin/{chunk-abt0azmv.js → chunk-qka4mkmj.js} +2 -2
  89. package/bin/{chunk-0e4wawpq.js → chunk-qsr1a0rp.js} +1 -1
  90. package/bin/chunk-rchsme43.js +3 -0
  91. package/bin/{chunk-tf28796q.js → chunk-reyxk4bw.js} +1 -1
  92. package/bin/{chunk-av1a8fqp.js → chunk-rhvv1vvk.js} +2 -2
  93. package/bin/{chunk-a32vreya.js → chunk-rq0n0vcc.js} +2 -2
  94. package/bin/chunk-rqf7999q.js +42 -0
  95. package/bin/chunk-rssgmj7x.js +2 -0
  96. package/bin/chunk-ryzz5fht.js +2 -0
  97. package/bin/chunk-s2fnfyn9.js +2 -0
  98. package/bin/{chunk-83e12sjg.js → chunk-s2k4qntr.js} +2 -2
  99. package/bin/{chunk-c007p0t8.js → chunk-snhsjs4x.js} +56 -56
  100. package/bin/{chunk-j8fxp8ej.js → chunk-t2hy6tj9.js} +1 -1
  101. package/bin/chunk-t7nsgg5k.js +4 -0
  102. package/bin/chunk-tm7f32c7.js +14 -0
  103. package/bin/{chunk-2291ehh5.js → chunk-trveq4wg.js} +2 -2
  104. package/bin/chunk-vap4k11j.js +20 -0
  105. package/bin/chunk-vm5fx7td.js +3 -0
  106. package/bin/chunk-vy8gntez.js +1 -0
  107. package/bin/{chunk-awfwk64v.js → chunk-vyzptrea.js} +2 -2
  108. package/bin/{chunk-hfh0c082.js → chunk-w4ghe71n.js} +1 -1
  109. package/bin/chunk-wdsf44hs.js +2 -0
  110. package/bin/chunk-wjyaezs7.js +2 -0
  111. package/bin/{chunk-3a13dcs1.js → chunk-wndm3px3.js} +1 -1
  112. package/bin/chunk-x5jwwvs0.js +1 -0
  113. package/bin/chunk-x92cq59c.js +1 -0
  114. package/bin/{chunk-vgn5zcpv.js → chunk-xa18z1py.js} +2 -2
  115. package/bin/{chunk-4v5n0ayb.js → chunk-xarsrs08.js} +1 -1
  116. package/bin/{chunk-66hsjnw6.js → chunk-xx337zcw.js} +2 -2
  117. package/bin/chunk-xz6713tj.js +2 -0
  118. package/bin/chunk-yfnem6se.js +2 -0
  119. package/bin/{chunk-m7m9d4fb.js → chunk-ytdwk2fq.js} +2 -2
  120. package/bin/{chunk-jy006gcv.js → chunk-ze20rm02.js} +4 -4
  121. package/bin/chunk-zw86wnwe.js +7 -0
  122. package/bin/{chunk-h3tbf521.js → chunk-zxk7q0zk.js} +1 -1
  123. package/bin/shumai-app.html +1 -1
  124. package/bin/shumai-app.js +773 -776
  125. package/package.json +7 -7
  126. package/prisma/migrations/20260907021754_add_asset_upload_id/migration.sql +2 -0
  127. package/prisma/schema.prisma +1 -0
  128. package/bin/chunk-1kw2mbqb.js +0 -1
  129. package/bin/chunk-1wm6ptdx.js +0 -1
  130. package/bin/chunk-2520aq8j.js +0 -2
  131. package/bin/chunk-29zdp63z.js +0 -3
  132. package/bin/chunk-3swpwb9v.js +0 -1
  133. package/bin/chunk-3wmcx2bv.js +0 -2
  134. package/bin/chunk-5a8nt4me.js +0 -1
  135. package/bin/chunk-6bhn1p8v.js +0 -211
  136. package/bin/chunk-70c3xrgd.js +0 -2
  137. package/bin/chunk-7esm0hqb.js +0 -2
  138. package/bin/chunk-7fst8kdw.js +0 -12
  139. package/bin/chunk-8zqgaxvv.js +0 -1
  140. package/bin/chunk-a3dmtt2j.js +0 -1
  141. package/bin/chunk-ce8m4zeg.js +0 -3
  142. package/bin/chunk-e7mqtkzn.js +0 -2
  143. package/bin/chunk-ejbvfj4r.js +0 -1
  144. package/bin/chunk-ekfem7kf.js +0 -1
  145. package/bin/chunk-etwkk0xh.js +0 -1
  146. package/bin/chunk-evrdd32b.js +0 -2
  147. package/bin/chunk-fm6p03ad.js +0 -2
  148. package/bin/chunk-fyha3r13.js +0 -2
  149. package/bin/chunk-g0vs7k2x.js +0 -1
  150. package/bin/chunk-g84z2w7v.js +0 -16
  151. package/bin/chunk-h837fyed.js +0 -2
  152. package/bin/chunk-j20e0qsw.js +0 -7
  153. package/bin/chunk-n1jwdb0a.js +0 -1
  154. package/bin/chunk-p5gf1zdm.js +0 -4
  155. package/bin/chunk-pfgxggaj.js +0 -11
  156. package/bin/chunk-q16490pv.js +0 -2
  157. package/bin/chunk-qh81zhg1.js +0 -1
  158. package/bin/chunk-qwp3kwbz.js +0 -2
  159. package/bin/chunk-qydeqgyj.js +0 -5
  160. package/bin/chunk-r7dty1tg.js +0 -2
  161. package/bin/chunk-rhdxwebf.js +0 -2
  162. package/bin/chunk-rhh716z0.js +0 -42
  163. package/bin/chunk-rza4ae5z.js +0 -3
  164. package/bin/chunk-sk4e6rb1.js +0 -1
  165. package/bin/chunk-t2n1dbgx.js +0 -4
  166. package/bin/chunk-x8f4defx.js +0 -3
  167. package/bin/chunk-z3gkt8w1.js +0 -3
  168. package/bin/chunk-zh6fqq44.js +0 -1
@@ -1,2 +1,2 @@
1
- import{T}from"./chunk-6bhn1p8v.js";var t=[["path",{d:"M13 5h8",key:"a7qcls"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 19h8",key:"c3s6r1"}],["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["rect",{x:"3",y:"4",width:"6",height:"6",rx:"1",key:"cif1o7"}]],bi=T("list-todo",t);
2
- export{bi};
1
+ import{T}from"./chunk-7rhz2gze.js";var t=[["path",{d:"M13 5h8",key:"a7qcls"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 19h8",key:"c3s6r1"}],["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["rect",{x:"3",y:"4",width:"6",height:"6",rx:"1",key:"cif1o7"}]],Li=T("list-todo",t);
2
+ export{Li};
@@ -1,8 +1,8 @@
1
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(`
2
+ import{ar}from"./chunk-579e4wv4.js";import"./chunk-mz0yjra0.js";import{Ra}from"./chunk-xa18z1py.js";import{$s,Gs,Qs}from"./chunk-pazjhrnf.js";import{es}from"./chunk-837fky18.js";import{mn,hn}from"./chunk-4wy87hwd.js";import{$n,Cr}from"./chunk-hm0dkzed.js";import{on}from"./chunk-rchsme43.js";import{Vi}from"./chunk-7jtmwt5a.js";import{qr}from"./chunk-trveq4wg.js";import{Za,hc,Xi,Yt}from"./chunk-nr20tvnw.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]||ar(r)||ar(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 Yt;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=$n(t.tools,e.compat?.supportsOpenAIGrammarTools??!1),a=r?.cacheRetention==="none"?void 0:r?.sessionId,c=es(a),d=Ie(e,t,r,c,l),u=await r?.onPayload?.(d,e);if(u!==void 0)d=u;let g=c||Vi(),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(Xi(s,hc("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:on(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=hn(mn(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=Cr(e,t,r,n),o=r?.reasoning?qr(e,r.reasoning):void 0;return De(e,t,{...s,reasoningEffort:o==="off"?void 0:o})};function Ie(e,t,r,n,s=$n(t.tools,e.compat?.supportsOpenAIGrammarTools??!1)){let o=e.compat?.supportsStrictMode??!0,i=e.compat?.supportsOpenAIGrammarTools??!1,l=Ra(t,e.compat?.supportsToolSearch??!1),a=$s(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=Gs(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 Qs(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
3
 
4
4
  `);while(a!==-1){let c=s.slice(0,a);s=s.slice(a+2);let d=c.split(`
5
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(`
6
+ `).trim();if(u&&u!=="[DONE]")try{yield JSON.parse(u)}catch(g){throw new B(`Invalid Codex SSE JSON: ${Za(g)}`,{cause:g,payload:u})}}a=s.indexOf(`
7
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};
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=Za(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=on(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: ${Za(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 Qs(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=$s(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 @@
1
+ import{D,N,h,O,w,u,Vn,C,B,t,o,K,Ou,Du,mr,vc,za,yo,qt,Vo,Lu,Zu,Bu,Uu,xc,Fu,Z,U,ut,Fe,A,T,br,L,wt,be,hr,Ut,De,E,dt,he,Y,It,vr,Lt,se,sr,S,Ee,Ie,Te,sA,aA,ay,uy,dy,hf,Zy,Fm,ke,Wa,$m,$0,Pc,Km,Ps,ls,ih,lh,Ub,Fb,bh,vw,vv,xv,tx,Qf,Vf,hx,Ix,jh,Zc,bS,ig,FS,jS,np,HS,QS,cg,KS,WS,ug,YS,XS,Cd,Ed,Id,wl,cp,iC,lC,cC,uC,Td,Os,IC,FC,qC,oE,uE,fE,pE,mE,hE,Mg,gE,Nd,XE,nI,gI,jg,cn,Rp,UI,FI,jc,Je,Xe,et,tt,rt,nt,ot,st,H,Mt,R,Cn,Zp,we,gt,At,yt,Il,Nr,Gd,Ct,Nt,Ot,Ht,Rt}from"./chunk-7rhz2gze.js";import{Eo,pr}from"./chunk-gc5sbfa5.js";import{Ul}from"./chunk-914bp49r.js";import{Fs,Uo,jl,ci,zi,Ca,ql}from"./chunk-dqxeztfa.js";import{Tn,Mn,Rn,_r,bt,mt}from"./chunk-xx337zcw.js";import"./chunk-5adsx8x4.js";import"./chunk-j2bvj2yn.js";import{Hn,oo}from"./chunk-cbgq517y.js";C();function te(a,e){let s=new Set(e);return a.filter((i)=>!s.has(i))}var ae=class extends yo{#r;#e;#o;#a;#t;#s;#i;#n;#l;#d=[];constructor(a,e,s){super();this.#r=a,this.#a=s,this.#o=[],this.#t=[],this.#e=[],this.setQueries(e)}onSubscribe(){if(this.listeners.size===1)this.#t.forEach((a)=>{a.subscribe((e)=>{this.#p(a,e)})})}onUnsubscribe(){if(!this.listeners.size)this.destroy()}destroy(){this.listeners=new Set,this.#t.forEach((a)=>{a.destroy()})}setQueries(a,e){this.#o=a,this.#a=e,qt.batch(()=>{let s=this.#t,i=this.#u(this.#o);i.forEach((c)=>c.observer.setOptions(c.defaultedQueryOptions));let m=i.map((c)=>c.observer),r=m.map((c)=>c.getCurrentResult()),p=s.length!==m.length,f=m.some((c,x)=>c!==s[x]),g=p||f,v=g?!0:r.some((c,x)=>{let y=this.#e[x];return!y||!za(c,y)});if(!g&&!v)return;if(g)this.#d=i,this.#t=m;if(this.#e=r,!this.hasListeners())return;if(g)te(s,m).forEach((c)=>{c.destroy()}),te(m,s).forEach((c)=>{c.subscribe((x)=>{this.#p(c,x)})});this.#f()})}getCurrentResult(){return this.#e}getQueries(){return this.#t.map((a)=>a.getCurrentQuery())}getObservers(){return this.#t}getOptimisticResult(a,e){let s=this.#u(a),i=s.map((r)=>r.observer.getOptimisticResult(r.defaultedQueryOptions)),m=s.map((r)=>r.defaultedQueryOptions.queryHash);return[i,(r)=>this.#c(r??i,e,m),()=>this.#m(i,s)]}#m(a,e){let s=new Set;return e.map((i,m)=>{let r=a[m];return!i.defaultedQueryOptions.notifyOnChangeProps?i.observer.trackResult(r,(p)=>{if(!s.has(p))s.add(p),e.forEach((f)=>{f.observer.trackProp(p)})}):r})}#c(a,e,s){if(e){let i=this.#l,m=s!==void 0&&i!==void 0&&(i.length!==s.length||s.some((r,p)=>r!==i[p]));if(this.#e!==this.#n||m||e!==this.#i){if(this.#i=e,this.#n=this.#e,s!==void 0)this.#l=s;this.#s=vc(this.#s,e(a))}return this.#s}return a}#g(){return!this.#a?.combine||this.#t.some((a,e)=>a.options.suspense&&this.#e[e]?.data===void 0)}#u(a){let e=new Map;this.#t.forEach((i)=>{let m=i.options.queryHash;if(!m)return;let r=e.get(m);if(r)r.push(i);else e.set(m,[i])});let s=[];return a.forEach((i)=>{let m=this.#r.defaultQueryOptions(i),r=e.get(m.queryHash)?.shift()??new Vo(this.#r,m);s.push({defaultedQueryOptions:m,observer:r})}),s}#p(a,e){let s=this.#t.indexOf(a);if(s!==-1)this.#e=this.#e.slice(),this.#e[s]=e,this.#f()}#f(){if(this.hasListeners()){let a=this.#g(),e=this.#s,s=a?e:this.#c(this.#m(this.#e,this.#d),this.#a?.combine);if(a||e!==s)qt.batch(()=>{this.listeners.forEach((i)=>{i(this.#e)})})}}};C();function re({queries:a,...e},s){let i=K(s),m=Ou(),r=Du(),p=e.subscribed!==!1,f=O(()=>a.map((d)=>{let b=i.defaultQueryOptions(d);return b._optimisticResults=m?"isRestoring":p?"optimistic":void 0,b}),[a,i,m,p]);f.forEach((d)=>{Uu(d);let b=i.getQueryCache().get(d.queryHash);Lu(d,r,b)}),Zu(r);let[g]=u(()=>new ae(i,f,e)),[v,c,x]=g.getOptimisticResult(f,e.combine),y=!m&&p;Vn(N((d)=>y?g.subscribe(qt.batchCalls(d)):mr,[g,y]),()=>g.getCurrentResult(),()=>g.getCurrentResult()),h(()=>{g.setQueries(f,e)},[f,e,g]);let n=v.some((d,b)=>xc(f[b],d))?v.flatMap((d,b)=>{let k=f[b];if(k&&xc(k,d)){let Q=new Vo(i,k);return Fu(k,Q,r)}return[]}):[];if(n.length>0)throw Promise.all(n);let _=v.find((d,b)=>{let k=f[b];return k&&Bu({result:d,errorResetBoundary:r,throwOnError:k.throwOnError,query:i.getQueryCache().get(k.queryHash),suspense:k.suspense})});if(_)throw _.error;return c(x())}C();C();var ve=Object.defineProperty,M=(a,e)=>ve(a,"name",{value:e,configurable:!0}),W="Collapsible",[Ne,Bt]=dt(W),[ye,X]=Ne(W),Ce=D(M(function(e,s){let{__scopeCollapsible:i,open:m,defaultOpen:r,disabled:p,onOpenChange:f,...g}=e,[v,c]=Lt({prop:m,defaultProp:r??!1,onChange:f,caller:W});return t(ye,{scope:i,disabled:p,contentId:vr(),open:v,onOpenToggle:N(()=>c((x)=>!x),[c]),children:t(se.div,{"data-state":z(v),"data-disabled":p?"":void 0,...g,ref:s})})},"Collapsible")),_e="CollapsibleTrigger",Re=D(M(function(e,s){let{__scopeCollapsible:i,...m}=e,r=X(_e,i);return t(se.button,{type:"button","aria-controls":r.open?r.contentId:void 0,"aria-expanded":r.open||!1,"data-state":z(r.open),"data-disabled":r.disabled?"":void 0,disabled:r.disabled,...m,ref:s,onClick:Y(e.onClick,r.onOpenToggle)})},"CollapsibleTrigger")),oe="CollapsibleContent",Ae=D(M(function(e,s){let{forceMount:i,...m}=e,r=X(oe,e.__scopeCollapsible);return t(sr,{present:i||r.open,children:({present:p})=>t(qe,{...m,ref:s,present:p})})},"CollapsibleContent")),qe=D(M(function(e,s){let{__scopeCollapsible:i,present:m,children:r,...p}=e,f=X(oe,i),[g,v]=u(m),c=w(null),x=he(s,c),y=w(0),n=y.current,_=w(0),d=_.current,b=f.open||g,k=w(b),Q=w(void 0);return h(()=>{let I=requestAnimationFrame(()=>k.current=!1);return()=>cancelAnimationFrame(I)},[]),It(()=>{let I=c.current;if(I){Q.current=Q.current||{transitionDuration:I.style.transitionDuration,animationName:I.style.animationName},I.style.transitionDuration="0s",I.style.animationName="none";let j=I.getBoundingClientRect();if(y.current=j.height,_.current=j.width,!k.current)I.style.transitionDuration=Q.current.transitionDuration,I.style.animationName=Q.current.animationName;v(m)}},[f.open,m]),t(se.div,{"data-state":z(f.open),"data-disabled":f.disabled?"":void 0,id:f.contentId,hidden:!b,...p,ref:x,style:{["--radix-collapsible-content-height"]:n?`${n}px`:void 0,["--radix-collapsible-content-width"]:d?`${d}px`:void 0,...e.style},children:b&&r})},"CollapsibleContentImpl"));function z(a){return a?"open":"closed"}M(z,"getState");var Pe=Ce;var He=[["path",{d:"M5 21v-6",key:"1hz6c0"}],["path",{d:"M12 21V3",key:"1lcnhd"}],["path",{d:"M19 21V9",key:"unv183"}]],ie=T("chart-no-axes-column",He);var Oe=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]],J=T("funnel",Oe);var Qe=[["path",{d:"M16 10a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 14.286V4a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z",key:"1n2ejm"}],["path",{d:"M20 9a2 2 0 0 1 2 2v10.286a.71.71 0 0 1-1.212.502l-2.202-2.202A2 2 0 0 0 17.172 19H10a2 2 0 0 1-2-2v-1",key:"1qfcsi"}]],F=T("messages-square",Qe);function ne({teamId:a}){let[e,s]=u("team"),[i,m]=u("1h"),{data:r,isLoading:p}=Z({queryKey:["teams",a,"ai-usage",i,"team"],queryFn:async()=>{let d=await A.api.teams[":teamId"]["ai-usage"].$get({param:{teamId:a},query:{timeframe:i}});if(!d.ok)throw Error("Failed to fetch team AI usage");return await d.json()},enabled:!!a&&e==="team"}),{data:f,isLoading:g}=Z({queryKey:["teams",a,"members"],queryFn:async()=>{let d=await A.api.teams[":teamId"].members.$get({param:{teamId:a},query:{}});if(!d.ok)throw Error("Failed to fetch team members");return await d.json()},enabled:!!a&&e==="members"}),v=re({queries:(f||[]).map((d)=>({queryKey:["teams",a,"ai-usage",i,d.id],queryFn:async()=>{let b=await A.api.teams[":teamId"]["ai-usage"].$get({param:{teamId:a},query:{timeframe:i,userId:d.id}});if(!b.ok)throw Error(`Failed to fetch AI usage for member ${d.id}`);return await b.json()},enabled:!!a&&e==="members"}))}),c=g||v.some((d)=>d.isLoading),x=(d)=>{if(!d)return"U";let b=d.split(" ");if(b.length>1)return`${b[0][0]}${b[b.length-1][0]}`.toUpperCase();return d.substring(0,2).toUpperCase()},y=(d)=>{if(!d)return"";switch(d.toLowerCase()){case"owner":return Zc();case"editor":return Ps();case"reviewer":return Os();default:return d}},n=(d)=>(d??0).toLocaleString(),_=(d)=>`$${(d??0).toFixed(6)}`;return o(Ct,{className:"border-border/60 shadow-sm",children:[o(Nt,{className:"flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between pb-6",children:[o("div",{children:[t(Ot,{className:"text-xl font-semibold tracking-tight",children:uy()}),t(Ht,{className:"text-sm text-muted-foreground mt-1",children:dy()})]}),o("div",{className:"flex flex-wrap items-center gap-3",children:[o(Eo,{type:"single",value:e,onValueChange:(d)=>{if(d)s(d)},className:"border rounded-lg p-1 bg-muted/30",children:[t(pr,{value:"team",className:"px-3 py-1.5 text-xs font-medium",children:nI()}),t(pr,{value:"members",className:"px-3 py-1.5 text-xs font-medium",children:xv()})]}),o(Eo,{type:"single",value:i,onValueChange:(d)=>{if(d)m(d)},className:"border rounded-lg p-1 bg-muted/30",children:[t(pr,{value:"1h",className:"px-2.5 py-1.5 text-xs font-medium",children:"1h"}),t(pr,{value:"24h",className:"px-2.5 py-1.5 text-xs font-medium",children:"24h"}),t(pr,{value:"7d",className:"px-2.5 py-1.5 text-xs font-medium",children:"7d"}),t(pr,{value:"30d",className:"px-2.5 py-1.5 text-xs font-medium",children:"30d"})]})]})]}),t(Rt,{children:e==="team"?p?t("div",{className:"flex h-48 items-center justify-center",children:t(L,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):t("div",{className:"rounded-md border",children:o(Tn,{children:[t(Mn,{children:o(_r,{children:[t(bt,{children:Nd()}),t(bt,{className:"text-right",children:bh()}),t(bt,{className:"text-right",children:jh()}),t(bt,{className:"text-right",children:Fm()}),t(bt,{className:"text-right",children:jg()}),t(bt,{className:"text-right",children:$m()})]})}),t(Rn,{children:o(_r,{children:[t(mt,{className:"font-medium",children:Nd()}),t(mt,{className:"text-right",children:n(r?.team?.inputTokens)}),t(mt,{className:"text-right",children:n(r?.team?.outputTokens)}),t(mt,{className:"text-right",children:n(r?.team?.cacheReadTokens)}),t(mt,{className:"text-right font-medium",children:n(r?.team?.totalTokens)}),t(mt,{className:"text-right font-medium",children:_(r?.team?.cost)})]})})]})}):c?t("div",{className:"flex h-48 items-center justify-center",children:t(L,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):t("div",{className:"rounded-md border",children:o(Tn,{children:[t(Mn,{children:o(_r,{children:[t(bt,{children:vv()}),t(bt,{children:IC()}),t(bt,{className:"text-right",children:bh()}),t(bt,{className:"text-right",children:jh()}),t(bt,{className:"text-right",children:Fm()}),t(bt,{className:"text-right",children:jg()}),t(bt,{className:"text-right",children:$m()})]})}),t(Rn,{children:(f||[]).map((d,b)=>{let k=v[b]?.data?.member;return o(_r,{children:[t(mt,{children:o("div",{className:"flex items-center gap-3",children:[o(Ee,{className:"h-8 w-8 rounded-full",children:[d.image&&t(Ie,{src:d.image,alt:d.name,className:"object-cover"}),t(Te,{className:"bg-primary/20 text-xs",children:x(d.name)})]}),o("div",{className:"flex flex-col",children:[t("span",{className:"text-sm font-medium leading-none",children:d.name}),t("span",{className:"text-xs text-muted-foreground mt-0.5",children:d.email})]})]})}),t(mt,{className:"text-xs text-muted-foreground",children:y(d.role)}),t(mt,{className:"text-right",children:n(k?.inputTokens)}),t(mt,{className:"text-right",children:n(k?.outputTokens)}),t(mt,{className:"text-right",children:n(k?.cacheReadTokens)}),t(mt,{className:"text-right font-medium",children:n(k?.totalTokens)}),t(mt,{className:"text-right font-medium",children:_(k?.cost)})]},d.id)})})]})})})]})}C();function le({teamId:a}){let[e,s]=u(null),{ref:i,inView:m}=Mt(),{data:r,isLoading:p,isError:f,fetchNextPage:g,hasNextPage:v,isFetchingNextPage:c}=ut({queryKey:["teams",a,"agent-sessions"],queryFn:async({pageParam:n})=>{let _=await A.api.teams[":teamId"]["agent-sessions"].$get({param:{teamId:a},query:{first:"20",after:n?String(n):void 0}});if(!_.ok)throw Error("Failed to fetch agent sessions");return await _.json()},initialPageParam:"",getNextPageParam:(n)=>n.pageInfo.cursor||void 0,enabled:!!a});h(()=>{if(m&&v&&!c)g()},[m,v,c,g]);let x=r?.pages.flatMap((n)=>n.data).filter((n)=>n.id!=="pending")||[],y=(n)=>{switch(n){case"comment":return t(we,{variant:"outline",className:"bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-500/20",children:mE()});case"chat":return t(we,{variant:"outline",className:"bg-violet-500/10 text-violet-600 dark:text-violet-400 border-violet-500/20",children:pE()});case"naming":return t(we,{variant:"outline",className:"bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/20",children:hE()});default:return t(we,{variant:"outline",className:"bg-muted text-muted-foreground border-border",children:n})}};return o("div",{className:"space-y-6",children:[o(Ct,{className:"border border-border/50 shadow-xs",children:[t(Nt,{className:"pb-4",children:t("div",{className:"flex items-center justify-between",children:o("div",{children:[o(Ot,{className:"text-xl font-bold flex items-center gap-2",children:[t(F,{className:"w-5 h-5 text-violet-500"}),Mg()]}),t(Ht,{className:"mt-1 text-sm text-muted-foreground",children:gE()})]})})}),t(Rt,{children:p?t("div",{className:"flex h-64 items-center justify-center",children:t(L,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):f?t("div",{className:"flex h-64 items-center justify-center text-destructive",children:"Failed to load agent sessions."}):x.length===0?o("div",{className:"flex flex-col items-center justify-center py-12 text-center text-muted-foreground",children:[t(F,{className:"w-10 h-10 text-muted-foreground/40 mb-3"}),t("p",{className:"text-base font-medium",children:hx()})]}):o("div",{className:"rounded-md border border-border/50 overflow-hidden",children:[o(Tn,{children:[t(Mn,{className:"bg-muted/40",children:o(_r,{children:[t(bt,{children:uE()}),t(bt,{children:Pc()}),t(bt,{children:fE()}),t(bt,{className:"text-right",children:$0()})]})}),t(Rn,{children:x.map((n)=>o(_r,{onClick:()=>s(n.id),className:"cursor-pointer hover:bg-muted/50 transition-colors",children:[t(mt,{className:"font-medium",children:o("div",{className:"flex flex-col",children:[t("span",{className:"text-sm font-semibold text-foreground",children:n.name||Rp()}),t("span",{className:"text-xs font-mono text-muted-foreground/70",children:n.id})]})}),t(mt,{children:o("div",{className:"flex items-center gap-2",children:[o(Ee,{className:"h-6 w-6",children:[t(Ie,{src:n.creator?.image||void 0}),t(Te,{className:"text-[10px]",children:n.creator?.name?.[0]?.toUpperCase()||"?"})]}),t("span",{className:"text-sm text-foreground/90",children:n.creator?.name||"System / Agent"})]})}),t(mt,{children:y(n.type)}),t(mt,{className:"text-right text-xs text-muted-foreground",children:Cn(n.createdAt)})]},n.id))})]}),t("div",{ref:i,className:"py-4 flex justify-center",children:c&&t(L,{className:"h-6 w-6 animate-spin text-muted-foreground"})})]})})]}),t(Ul,{sessionId:e,open:!!e,onOpenChange:(n)=>{if(!n)s(null)}})]})}C();function de({...a}){return t(Pe,{"data-slot":"collapsible",...a})}function me({...a}){return t(Re,{"data-slot":"collapsible-trigger",...a})}function ce({...a}){return t(Ae,{"data-slot":"collapsible-content",...a})}function ee(a){switch(a.toLowerCase()){case"owner":return Zc();case"editor":return Ps();case"reviewer":return Os();default:return a}}function Le(a,e){if(typeof a==="object"&&a!==null&&"message"in a){let s=a.message;if(typeof s==="string")return s}return e}function Be({rule:a}){let e=a.resourceData??{};if(a.resource==="agent_mcp_call_count")return t("span",{children:lC({value:String(e.id??"")})});if(a.resource==="agent_bash_call_count")return t("span",{children:iC({value:String(e.match??"*")})});if(a.resource==="agent_tool_call_count")return t("span",{children:cC({value:String(e.name??e.toolName??"*")})});return null}function Me({rule:a}){if(a.scopeMode==="all_members")return o(we,{variant:"secondary",className:"gap-1 text-xs",children:[t(oo,{className:"h-3 w-3"}),o("span",{children:[Cd(),a.role?` (${ee(a.role)})`:` (${wl()})`]})]});if(a.scopeMode==="each_member")return o(we,{variant:"secondary",className:"gap-1 text-xs",children:[t(Hn,{className:"h-3 w-3"}),o("span",{children:[Ed(),a.role?` (${ee(a.role)})`:` (${wl()})`]})]});return o(we,{variant:"secondary",className:"gap-1 text-xs",children:[t(ci,{className:"h-3 w-3"}),o("span",{children:[Id()," (",a.userIds?.length||0,")"]})]})}function je({teamId:a,rule:e,record:s}){let i=K(),[m,r]=u(!1),[p,f]=u(()=>new Date),g=zi[e.resource],v=e.scopeMode==="all_members",c=s.percent>=100,x=v?e.role?`${XS()}: ${ee(e.role)}`:uC():s.user?.name||s.userId||cn();h(()=>{if(!s.isWindowActive||!s.periodEnd)return;let n=window.setInterval(()=>f(new Date),60000);return()=>window.clearInterval(n)},[s.isWindowActive,s.periodEnd]);let y=U({mutationFn:async()=>{let n=await A.api.teams[":teamId"].quotas[":id"].records.reset.$post({param:{teamId:a,id:e.id},json:{userId:s.userId??null}});if(!n.ok){let _=await n.json().catch(()=>null);throw Error(Le(_,lh()))}return await n.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["teams",a,"quotas",e.id,"records"]}),i.invalidateQueries({queryKey:["teams",a,"quotas"]}),r(!1),R.success(WS())},onError:(n)=>{let _=n instanceof Error?n.message:lh();r(!1),R.error(_)}});return o(B,{children:[o("div",{className:"space-y-3 rounded-xl border border-border/70 bg-card p-4 text-card-foreground shadow-2xs",children:[o("div",{className:"flex items-center justify-between gap-3",children:[o("div",{className:"flex min-w-0 items-center gap-3",children:[v?t("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-primary/10 text-primary",children:t(oo,{className:"h-5 w-5"})}):o(Ee,{className:"h-9 w-9 shrink-0 border border-border/50",children:[t(Ie,{src:s.user?.image||void 0}),t(Te,{className:"text-xs font-semibold",children:s.user?.name?.[0]?.toUpperCase()||"U"})]}),o("div",{className:"min-w-0",children:[t("div",{className:"truncate text-sm font-semibold text-foreground",children:x}),!v&&s.user?.email&&t("div",{className:"truncate text-xs text-muted-foreground",children:s.user.email})]})]}),o("div",{className:"flex shrink-0 items-center gap-2",children:[s.isWindowActive&&s.periodEnd?o(we,{variant:"outline",className:"hidden gap-1 border-primary/30 bg-primary/5 text-xs text-primary sm:flex",children:[t(hr,{className:"h-3 w-3"}),t("span",{children:cg({time:Zp(s.periodEnd,p)})})]}):o(we,{variant:"secondary",className:"hidden gap-1 text-xs text-muted-foreground sm:flex",children:[t(br,{className:"h-3 w-3 text-primary"}),t("span",{children:ig()})]}),o(S,{type:"button",variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>r(!0),disabled:y.isPending,children:[y.isPending?t(L,{className:"h-3.5 w-3.5 animate-spin"}):t(Fs,{className:"h-3.5 w-3.5"}),ug()]})]})]}),o("div",{className:"space-y-1.5 pt-1",children:[t(Gd,{value:Math.min(100,Math.max(0,s.percent)),className:"h-2"}),o("div",{className:"flex items-center justify-between gap-2 text-xs font-medium",children:[o("span",{className:c?"font-bold text-destructive":"text-foreground",children:[Ca(e.resource,s.consumed)," /"," ",Ca(e.resource,e.limit)," ",g?.unit]}),o("span",{className:c?"font-bold text-destructive":"text-muted-foreground",children:[s.percent,"%"]})]})]}),o("div",{className:"flex items-center justify-between gap-2 text-xs text-muted-foreground sm:hidden",children:[s.isWindowActive&&s.periodEnd?o("span",{className:"flex items-center gap-1 text-primary",children:[t(hr,{className:"h-3 w-3"}),cg({time:Zp(s.periodEnd,p)})]}):o("span",{className:"flex items-center gap-1",children:[t(br,{className:"h-3 w-3 text-primary"}),ig()]}),o("span",{children:[KS(),": ",Ca(e.resource,s.remaining)," ",g?.unit]})]})]}),t(Je,{open:m,onOpenChange:r,children:o(Xe,{children:[o(et,{children:[t(rt,{children:ug()}),t(nt,{children:YS({target:x})})]}),o(tt,{children:[t(st,{disabled:y.isPending,children:ke()}),o(ot,{onClick:(n)=>{n.preventDefault(),y.mutate()},disabled:y.isPending,children:[y.isPending&&t(L,{className:"mr-2 h-4 w-4 animate-spin"}),Wa()]})]})]})})]})}function Ue({teamId:a,rule:e}){let[s,i]=u(!1),[m,r]=u(""),p=zi[e.resource],f=p?.icon||Uo,{data:g,isLoading:v,isError:c}=Z({queryKey:["teams",a,"quotas",e.id,"records"],queryFn:async()=>{let n=await A.api.teams[":teamId"].quotas[":id"].records.$get({param:{teamId:a,id:e.id}});if(!n.ok)throw Error(ih());return await n.json()},enabled:s,refetchInterval:s?1e4:!1}),x=g?.records??[],y=x.filter((n)=>{if(!m.trim())return!0;let _=m.toLowerCase();return n.user?.name.toLowerCase().includes(_)||n.user?.email.toLowerCase().includes(_)});return o(de,{open:s,onOpenChange:i,className:"rounded-xl border border-border/70",children:[t(me,{asChild:!0,children:o("button",{type:"button","aria-label":s?FS():HS(),className:"flex w-full items-center justify-between gap-4 p-4 text-left transition-colors hover:bg-muted/40",children:[o("div",{className:"flex min-w-0 items-start gap-3",children:[t("div",{className:"mt-0.5 rounded-lg bg-primary/10 p-2 text-primary",children:t(f,{className:"h-5 w-5"})}),o("div",{className:"min-w-0",children:[o("div",{className:"flex flex-wrap items-center gap-2",children:[t("span",{className:"font-semibold text-foreground",children:p?.label()||e.resource}),!e.enabled&&t(we,{variant:"secondary",children:np()})]}),o("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground",children:[t(Me,{rule:e}),o(we,{variant:"outline",className:"gap-1 text-xs",children:[t(hr,{className:"h-3 w-3"}),Ca(e.resource,e.limit)," ",p?.unit," /"," ",ql(e.period)]}),t(Be,{rule:e})]})]})]}),t(be,{className:`h-5 w-5 shrink-0 text-muted-foreground transition-transform ${s?"rotate-180":""}`})]})}),t(ce,{children:o("div",{className:"space-y-3 border-t border-border/60 bg-muted/10 p-4",children:[e.scopeMode!=="all_members"&&x.length>3&&o("div",{className:"relative",children:[t(Ut,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),t(H,{value:m,onChange:(n)=>r(n.target.value),placeholder:cp(),className:"h-9 pl-9 text-sm"})]}),v?t("div",{className:"flex justify-center py-10",children:t(L,{className:"h-7 w-7 animate-spin text-primary"})}):c?t("div",{className:"py-8 text-center text-sm text-destructive",children:ih()}):y.length===0?t("div",{className:"py-8 text-center text-sm text-muted-foreground",children:QS()}):y.map((n,_)=>t(je,{teamId:a,rule:e,record:n},n.id||n.userId||`record-${_}`))]})})]})}function ue({teamId:a}){let{data:e,isLoading:s,isError:i}=Z({queryKey:["teams",a,"quotas"],queryFn:async()=>{let r=await A.api.teams[":teamId"].quotas.$get({param:{teamId:a}});if(!r.ok)throw Error(ls());return await r.json()},enabled:!!a}),m=e?.rules??[];return o(Ct,{className:"border-border/60 shadow-sm",children:[o(Nt,{children:[o(Ot,{className:"flex items-center gap-2 text-xl font-semibold tracking-tight",children:[t(Uo,{className:"h-5 w-5 text-primary"}),Td()]}),t(Ht,{children:jS()})]}),t(Rt,{children:s?t("div",{className:"flex h-48 items-center justify-center",children:t(L,{className:"h-7 w-7 animate-spin text-muted-foreground"})}):i?t("div",{className:"py-10 text-center text-sm text-destructive",children:ls()}):m.length===0?o("div",{className:"flex flex-col items-center justify-center rounded-xl border-2 border-dashed border-border py-12 text-center",children:[t(Uo,{className:"mb-3 h-10 w-10 text-muted-foreground/50"}),t("p",{className:"text-base font-medium text-foreground",children:Vf()}),t("p",{className:"mt-1 max-w-md text-sm text-muted-foreground",children:Qf()})]}):t("div",{className:"space-y-3",children:m.map((r)=>t(Ue,{teamId:a,rule:r},r.id))})})]})}C();var $e=Object.values(Il);function pe({teamId:a}){let[e,s]=u([]),[i,m]=u([]),[r,p]=u(""),{ref:f,inView:g}=Mt(),{data:v}=Z({queryKey:["teams",a,"members"],queryFn:async()=>{let l=await A.api.teams[":teamId"].members.$get({param:{teamId:a},query:{}});if(!l.ok)return[];return await l.json()},enabled:!!a}),c=v||[],{data:x,isLoading:y,isError:n,fetchNextPage:_,hasNextPage:d,isFetchingNextPage:b}=ut({queryKey:["teams",a,"audit-logs",e,i,r],queryFn:async({pageParam:l})=>{let q=await A.api.teams[":teamId"]["audit-logs"].$get({param:{teamId:a},query:{first:"20",after:l?String(l):void 0,actions:e.length>0?e:void 0,userIds:i.length>0?i:void 0,itemId:r.trim()||void 0}});if(!q.ok)throw Error("Failed to fetch audit logs");return await q.json()},initialPageParam:"",getNextPageParam:(l)=>l.pageInfo.endCursor||void 0,enabled:!!a});h(()=>{if(g&&d&&!b)_()},[g,d,b,_]);let k=x?.pages.flatMap((l)=>l.nodes)||[],Q=x?.pages[0]?.total??0,I=(l)=>{s((q)=>q.includes(l)?q.filter((P)=>P!==l):[...q,l])},j=(l)=>{m((q)=>q.includes(l)?q.filter((P)=>P!==l):[...q,l])},fe=(l)=>{if(l.includes("delete")||l.includes("remove")||l.includes("revoke"))return t(we,{variant:"outline",className:"bg-destructive/10 text-destructive border-destructive/20 font-mono text-xs",children:l});if(l.includes("create")||l.includes("add"))return t(we,{variant:"outline",className:"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20 font-mono text-xs",children:l});if(l.includes("update")||l.includes("reparent")||l.includes("copy"))return t(we,{variant:"outline",className:"bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-500/20 font-mono text-xs",children:l});return t(we,{variant:"outline",className:"bg-muted text-muted-foreground border-border font-mono text-xs",children:l})},ge=new Map(c.map((l)=>[l.userId||l.id,l]));return t("div",{className:"space-y-6",children:o(Ct,{className:"border border-border/50 shadow-xs",children:[o(Nt,{className:"pb-4",children:[o("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-4",children:[o("div",{children:[o(Ot,{className:"text-xl font-bold flex items-center gap-2",children:[t(Fs,{className:"h-5 w-5 text-primary"}),hf()]}),t(Ht,{className:"mt-1",children:Zy()})]}),Q>0&&o(we,{variant:"secondary",className:"w-fit text-xs font-normal",children:[Q," ",hf()]})]}),o("div",{className:"mt-4 flex flex-wrap items-center gap-3 pt-4 border-t border-border/40",children:[o(gt,{children:[t(At,{asChild:!0,children:o(S,{variant:"outline",size:"sm",className:"h-9 gap-2 text-xs border-dashed",children:[t(J,{className:"h-3.5 w-3.5"}),Ub(),e.length>0&&t(we,{variant:"secondary",className:"ml-1 px-1.5 py-0 text-[10px]",children:e.length})]})}),o(yt,{className:"w-64 p-2",align:"start",children:[t("div",{className:"text-xs font-semibold text-muted-foreground px-2 py-1 mb-1",children:qC()}),t("div",{className:"max-h-60 overflow-y-auto space-y-1 pr-1",children:$e.map((l)=>o("label",{className:"flex items-center gap-2 px-2 py-1.5 hover:bg-accent rounded-md cursor-pointer text-xs",children:[t(Nr,{checked:e.includes(l),onCheckedChange:()=>I(l)}),t("span",{className:"font-mono",children:l})]},l))}),e.length>0&&t(S,{variant:"ghost",size:"sm",className:"w-full mt-2 h-7 text-xs text-muted-foreground hover:text-foreground",onClick:()=>s([]),children:"Clear Actions"})]})]}),o(gt,{children:[t(At,{asChild:!0,children:o(S,{variant:"outline",size:"sm",className:"h-9 gap-2 text-xs border-dashed",children:[t(J,{className:"h-3.5 w-3.5"}),Fb(),i.length>0&&t(we,{variant:"secondary",className:"ml-1 px-1.5 py-0 text-[10px]",children:i.length})]})}),o(yt,{className:"w-64 p-2",align:"start",children:[t("div",{className:"text-xs font-semibold text-muted-foreground px-2 py-1 mb-1",children:oE()}),t("div",{className:"max-h-60 overflow-y-auto space-y-1 pr-1",children:c.map((l)=>{let q=l.userId||l.user?.id||l.id,P=l.user?.name||l.name||q,V=l.user?.image||l.image;return o("label",{className:"flex items-center gap-2 px-2 py-1.5 hover:bg-accent rounded-md cursor-pointer text-xs",children:[t(Nr,{checked:i.includes(q),onCheckedChange:()=>j(q)}),o(Ee,{className:"h-5 w-5",children:[t(Ie,{src:V||void 0}),t(Te,{className:"text-[10px]",children:P.slice(0,2).toUpperCase()})]}),t("span",{className:"truncate",children:P})]},q)})}),i.length>0&&t(S,{variant:"ghost",size:"sm",className:"w-full mt-2 h-7 text-xs text-muted-foreground hover:text-foreground",onClick:()=>m([]),children:"Clear Users"})]})]}),o("div",{className:"relative flex-1 min-w-[200px] max-w-xs",children:[t(Ut,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),t(H,{type:"text",placeholder:FC(),value:r,onChange:(l)=>p(l.target.value),className:"pl-8 pr-8 h-9 text-xs"}),r&&t("button",{onClick:()=>p(""),className:"absolute right-2.5 top-2.5 text-muted-foreground hover:text-foreground",children:t(De,{className:"h-4 w-4"})})]}),(e.length>0||i.length>0||r)&&t(S,{variant:"ghost",size:"sm",className:"h-9 px-2 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{s([]),m([]),p("")},children:"Clear all"})]})]}),o(Rt,{className:"p-0",children:[y?t("div",{className:"flex h-64 items-center justify-center",children:t(L,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):n?t("div",{className:"p-8 text-center text-sm text-destructive",children:"Failed to load audit logs."}):k.length===0?t("div",{className:"p-12 text-center text-sm text-muted-foreground",children:tx()}):o(Tn,{children:[t(Mn,{children:o(_r,{className:"hover:bg-transparent border-b border-border/50",children:[t(bt,{className:"w-[180px] text-xs font-semibold",children:aA()}),t(bt,{className:"w-[200px] text-xs font-semibold",children:FI()}),t(bt,{className:"text-xs font-semibold",children:vw()}),t(bt,{className:"text-xs font-semibold",children:bS()}),t(bt,{className:"w-[160px] text-right text-xs font-semibold",children:gI()})]})}),t(Rn,{children:k.map((l)=>{let q=l.userId?ge.get(l.userId):null,P=q?.user?.name||q?.name||l.userId||"System",V=q?.user?.image||q?.image;return o(_r,{className:"hover:bg-muted/40 transition-colors",children:[t(mt,{className:"py-3 font-medium",children:fe(l.action)}),t(mt,{className:"py-3",children:o("div",{className:"flex items-center gap-2",children:[o(Ee,{className:"h-6 w-6",children:[t(Ie,{src:V||void 0}),t(Te,{className:"text-[10px]",children:P.slice(0,2).toUpperCase()})]}),t("span",{className:"text-xs font-medium text-foreground truncate max-w-[160px]",children:l.agent?jc({user:P,agent:l.agent.name}):P}),l.agent&&t(wt,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"})]})}),t(mt,{className:"py-3 text-xs font-mono text-muted-foreground",children:l.itemId||"-"}),t(mt,{className:"py-3 text-xs font-mono text-muted-foreground",children:l.projectId||"-"}),t(mt,{className:"py-3 text-right text-xs text-muted-foreground",children:Cn(l.createdAt)})]},l.id)})})]}),t("div",{ref:f,className:"py-4 flex justify-center",children:b&&t(L,{className:"h-6 w-6 animate-spin text-muted-foreground"})})]})]})})}function ze(){let{teamId:a}=Ge.useParams(),[e,s]=u("audit-logs"),{data:i,isLoading:m}=Z({queryKey:["teams",a,"me"],queryFn:async()=>{let r=await A.api.teams[":teamId"].me.$get({param:{teamId:a}});if(!r.ok)throw Error("Failed to fetch me");return await r.json()},enabled:!!a});if(m)return t("div",{className:"flex h-screen items-center justify-center",children:t(L,{className:"h-8 w-8 animate-spin text-muted-foreground"})});if(i?.role?.toLowerCase()!=="owner")return o("div",{className:"flex h-full flex-col items-center justify-center p-8 text-center",children:[t(jl,{className:"h-12 w-12 text-destructive mb-4"}),t("h2",{className:"text-xl font-bold tracking-tight mb-2",children:sA()}),t("p",{className:"text-sm text-muted-foreground max-w-md",children:Ix()})]});return t("div",{className:"h-full bg-background font-sans selection:bg-primary/20 transition-colors duration-300",children:o("div",{className:"flex flex-col md:flex-row h-full",children:[t("div",{className:"w-full h-full md:w-72 bg-sidebar border-b md:border-b-0 md:border-r border-sidebar-border z-10 md:left-16 overflow-y-auto transition-colors duration-300",children:o("nav",{className:"p-4 space-y-1 mt-4",children:[t("div",{className:"mb-2 px-4 text-xs font-semibold text-sidebar-foreground/60 uppercase tracking-wider",children:Km()}),t("div",{className:"mt-4 mb-2 px-4 text-xs font-semibold text-sidebar-foreground/60 uppercase tracking-wider pt-4 border-t border-sidebar-border",children:XE()}),o("button",{onClick:()=>s("audit-logs"),className:E("w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all",e==="audit-logs"?"bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border":"text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"),children:[t(Fs,{className:"w-5 h-5"}),hf(),e==="audit-logs"&&t("div",{className:"ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary"})]}),o("button",{onClick:()=>s("quotas"),className:E("w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all",e==="quotas"?"bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border":"text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"),children:[t(Uo,{className:"w-5 h-5"}),Td(),e==="quotas"&&t("div",{className:"ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary"})]}),t("div",{className:"mt-4 mb-2 px-4 text-xs font-semibold text-sidebar-foreground/60 uppercase tracking-wider pt-4 border-t border-sidebar-border",children:ay()}),o("button",{onClick:()=>s("ai-usage"),className:E("w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all",e==="ai-usage"?"bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border":"text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"),children:[t(ie,{className:"w-5 h-5"}),UI(),e==="ai-usage"&&t("div",{className:"ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary"})]}),o("button",{onClick:()=>s("ai-sessions"),className:E("w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all",e==="ai-sessions"?"bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border":"text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"),children:[t(F,{className:"w-5 h-5"}),Mg(),e==="ai-sessions"&&t("div",{className:"ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary"})]})]})}),t("div",{className:"flex-1 overflow-y-auto p-4 md:p-8",children:o("div",{className:"max-w-6xl mx-auto space-y-8",children:[e==="audit-logs"&&t(pe,{teamId:a}),e==="ai-usage"&&t(ne,{teamId:a}),e==="ai-sessions"&&t(le,{teamId:a}),e==="quotas"&&t(ue,{teamId:a})]})})]})})}var Ge=Fe("/teams/$teamId/dashboard")({component:ze});export{Ge as Route};