@shumai-one/shumai 0.6.2 → 0.6.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.
- package/bin/{chunk-mcj1xpcc.js → chunk-01vx2chc.js} +2 -2
- package/bin/chunk-0epkrexd.js +2 -0
- package/bin/chunk-0h5239kt.js +2 -0
- package/bin/{chunk-jt0ykktx.js → chunk-0jnstdgf.js} +1 -1
- package/bin/{chunk-x03jwaga.js → chunk-0njsjy6x.js} +4 -4
- package/bin/{chunk-7naa7tpn.js → chunk-13rq2gtr.js} +2 -2
- package/bin/chunk-1aqs9sdh.js +3 -0
- package/bin/{chunk-m0q2cgfg.js → chunk-22jbsrka.js} +1 -1
- package/bin/chunk-2qknebmd.js +1 -0
- package/bin/{chunk-a411xhmm.js → chunk-2qzmh3ae.js} +4 -4
- package/bin/{chunk-2nhgdqdg.js → chunk-2tt0b8ym.js} +2 -2
- package/bin/{chunk-p3f5aevs.js → chunk-2zm7czk6.js} +1 -1
- package/bin/{chunk-p4s95471.js → chunk-396tfwdx.js} +1 -1
- package/bin/chunk-3mx4trvh.js +10 -0
- package/bin/{chunk-b5rhvzv9.js → chunk-45pb3kzz.js} +2 -2
- package/bin/{chunk-q83h0hkx.js → chunk-47fmhzwv.js} +2 -2
- package/bin/chunk-4awk4xhq.js +2 -0
- package/bin/{chunk-2cdxm1cp.js → chunk-4b2x2qba.js} +23 -23
- package/bin/{chunk-knj2s8mg.js → chunk-4rjy7ybr.js} +8 -8
- package/bin/{chunk-q8w4mbw4.js → chunk-598x693h.js} +2 -2
- package/bin/chunk-5c7ztqs7.js +1 -0
- package/bin/{chunk-2jj4j8cn.js → chunk-65dh7x4c.js} +2 -2
- package/bin/{chunk-hnkcgvcj.js → chunk-66e2vrky.js} +1 -1
- package/bin/{chunk-g22wmpk1.js → chunk-6j3beg6n.js} +2 -2
- package/bin/{chunk-cgmebxx6.js → chunk-6ke13k69.js} +1 -1
- package/bin/{chunk-7sgrtxbt.js → chunk-6rqakmg0.js} +2 -2
- package/bin/{chunk-4mws03es.js → chunk-6ty4tfmf.js} +3 -3
- package/bin/chunk-7e9ws6dh.js +129 -0
- package/bin/chunk-7mdddkfc.js +1 -0
- package/bin/{chunk-q2bew2vc.js → chunk-7q4mgd5x.js} +2 -2
- package/bin/chunk-7yv7shad.js +1 -0
- package/bin/{chunk-qwpkcp8d.js → chunk-81b8rfv7.js} +2 -2
- package/bin/{chunk-atfz7g7e.js → chunk-8a7ymmd4.js} +2 -2
- package/bin/chunk-8ac9at5y.js +2 -0
- package/bin/{chunk-gxepkvt2.js → chunk-8zcfgz9c.js} +1 -1
- package/bin/{chunk-mcw198kg.js → chunk-955kf5kc.js} +8 -8
- package/bin/{chunk-jzgbxqdg.js → chunk-978rm9a9.js} +2 -2
- package/bin/{chunk-jt02kpfc.js → chunk-9qzbrp4d.js} +2 -2
- package/bin/{chunk-tekwpkjf.js → chunk-a283dh05.js} +2 -2
- package/bin/chunk-aa2a06cc.js +1 -0
- package/bin/{chunk-8cjet7pp.js → chunk-ajr1w3vq.js} +6 -6
- package/bin/chunk-akafypge.js +218 -0
- package/bin/chunk-amk373q2.js +2 -0
- package/bin/chunk-apq2gvvp.js +4 -0
- package/bin/chunk-av2w1sez.js +2 -0
- package/bin/{chunk-5wapd171.js → chunk-b6kmj34z.js} +12 -12
- package/bin/chunk-bkzaw9p8.js +1 -0
- package/bin/{chunk-zezje74z.js → chunk-bssb9tar.js} +3 -3
- package/bin/chunk-bwvj1aqc.js +1 -0
- package/bin/chunk-by9esjn7.js +3 -0
- package/bin/chunk-bywk8mbc.js +2 -0
- package/bin/{chunk-9xhjy897.js → chunk-c61g9hfa.js} +4 -4
- package/bin/{chunk-zrszykjf.js → chunk-cdcgjh8k.js} +1 -1
- package/bin/{chunk-yk12hydf.js → chunk-d277evce.js} +4 -4
- package/bin/{chunk-55h9ze53.js → chunk-d3brvxh7.js} +2 -2
- package/bin/{chunk-9t3p4xp6.js → chunk-dcb1nzf1.js} +1 -1
- package/bin/{chunk-mzsw9var.js → chunk-dfbzatq9.js} +2 -2
- package/bin/chunk-e0bckx12.js +2 -0
- package/bin/{chunk-3ckkwdjx.js → chunk-e2p4s2pj.js} +3 -3
- package/bin/chunk-e8zzg57c.js +2 -0
- package/bin/{chunk-vp3czaeh.js → chunk-edfaqwaq.js} +2 -2
- package/bin/chunk-ehgrp0f9.js +1 -0
- package/bin/chunk-evs2aaav.js +12 -0
- package/bin/{chunk-s9ksftq2.js → chunk-f5bhcjhw.js} +1 -1
- package/bin/{chunk-ns33grgx.js → chunk-fb9dedm2.js} +2 -2
- package/bin/{chunk-srxp5jav.js → chunk-ff0mh9p3.js} +32 -32
- package/bin/chunk-fpfby5tz.js +1 -0
- package/bin/{chunk-eyjfhdp9.js → chunk-gd3b5akr.js} +2 -2
- package/bin/{chunk-1wfg56z3.js → chunk-gm1fy3hm.js} +5 -5
- package/bin/{chunk-9n1w5dw1.js → chunk-gqkjx7rz.js} +3 -3
- package/bin/{chunk-1nvd90g2.js → chunk-h7f5370s.js} +1 -1
- package/bin/chunk-hcyhsn8e.js +2 -0
- package/bin/{chunk-vcrmjtcz.js → chunk-jxm0gzmf.js} +2 -2
- package/bin/{chunk-b7bnp021.js → chunk-k3ggy3xk.js} +2 -2
- package/bin/{chunk-257dcd2f.js → chunk-k9vjs21p.js} +2 -2
- package/bin/chunk-ka40gv72.js +1 -0
- package/bin/chunk-km70p970.js +2 -0
- package/bin/{chunk-e4yscwen.js → chunk-m6v8rb39.js} +8 -8
- package/bin/chunk-m8spagwp.js +4 -0
- package/bin/{chunk-y241cxff.js → chunk-mfh7mg5b.js} +1 -1
- package/bin/chunk-n0cn0218.js +2 -0
- package/bin/chunk-n54ftsdx.js +2 -0
- package/bin/{chunk-02fvcrej.js → chunk-n7cvj15k.js} +7 -7
- package/bin/chunk-na5fh7er.js +2 -0
- package/bin/chunk-neazdbxy.js +1 -0
- package/bin/chunk-nk24qw3m.js +1 -0
- package/bin/{chunk-73yncv54.js → chunk-nsbbseff.js} +2 -2
- package/bin/chunk-nseef85h.js +1 -0
- package/bin/chunk-p35ztj2z.js +3 -0
- package/bin/chunk-pcjc9ygv.js +2 -0
- package/bin/{chunk-167z646e.js → chunk-pemmtd8q.js} +1 -1
- package/bin/{chunk-82tps5n1.js → chunk-pzrqnnpg.js} +1 -1
- package/bin/{chunk-a74g6h8a.js → chunk-q43m934j.js} +2 -2
- package/bin/{chunk-r1xer8gn.js → chunk-q57m34h0.js} +3 -3
- package/bin/chunk-q5k72jz9.js +3 -0
- package/bin/chunk-q9fsxakd.js +2 -0
- package/bin/chunk-qadpe0ct.js +2 -0
- package/bin/chunk-qeypjv4f.css +1 -0
- package/bin/chunk-qw92z3wf.js +2 -0
- package/bin/chunk-r0byfq1t.js +1 -0
- package/bin/chunk-r0q88qw3.js +2 -0
- package/bin/chunk-rjhczkh3.js +2 -0
- package/bin/{chunk-mwktrwtx.js → chunk-s0wxbybf.js} +1 -1
- package/bin/{chunk-q5vkxee3.js → chunk-s4hkcw24.js} +2 -2
- package/bin/chunk-szta50g1.js +1 -0
- package/bin/chunk-t6cb99gp.js +2 -0
- package/bin/chunk-tcr080b9.js +1 -0
- package/bin/{chunk-yq32evnn.js → chunk-v4nqx084.js} +5 -5
- package/bin/{chunk-ympbfzz4.js → chunk-v7jzc3ye.js} +1 -1
- package/bin/{chunk-9zsv6d2f.js → chunk-vbe8wred.js} +1 -1
- package/bin/{chunk-hpbn0k9n.js → chunk-vf9s8b5t.js} +2 -2
- package/bin/{chunk-m9adtgzk.js → chunk-vk3eqr65.js} +1 -1
- package/bin/{chunk-hpwv4am3.js → chunk-vm9bbk97.js} +4 -4
- package/bin/{chunk-v05rrxp5.js → chunk-w4gqg27w.js} +2 -2
- package/bin/{chunk-x8mjh387.js → chunk-w6ym7tsd.js} +4 -4
- package/bin/{chunk-hzkjgcre.js → chunk-ways29d1.js} +1 -1
- package/bin/chunk-wesg7tg9.js +1 -0
- package/bin/chunk-wmrrapwv.js +2 -0
- package/bin/chunk-wnwsjgj8.js +2 -0
- package/bin/{chunk-hw6czrya.js → chunk-wrb4xq9v.js} +1 -1
- package/bin/{chunk-v5cn90cf.js → chunk-wzrzc07t.js} +2 -2
- package/bin/chunk-xd1axsdv.js +2 -0
- package/bin/{chunk-cwat1jwx.js → chunk-xk0jmx4s.js} +2 -2
- package/bin/{chunk-g6sdezec.js → chunk-y545vfn0.js} +1 -1
- package/bin/{chunk-fatmqnp1.js → chunk-y6h885fs.js} +1 -1
- package/bin/{chunk-cz13a82m.js → chunk-yncmfr39.js} +2 -2
- package/bin/{chunk-01052ssf.js → chunk-yxnz4ypt.js} +11 -11
- package/bin/chunk-zc1asygg.js +2 -0
- package/bin/{chunk-m82tkhaa.js → chunk-zc7wzcvh.js} +7 -7
- package/bin/chunk-zdvhh8mk.js +2 -0
- package/bin/{chunk-kvhf12b4.js → chunk-zg0b902x.js} +2 -2
- package/bin/{chunk-7v7mypc6.js → chunk-zhq7a7hs.js} +2 -2
- package/bin/{chunk-f25fe9th.js → chunk-zmnvskn7.js} +11 -11
- package/bin/shumai-app.html +1 -1
- package/bin/shumai-app.js +470 -389
- package/package.json +7 -7
- package/prisma/migrations/20261102032402_add_archive_storage/migration.sql +25 -0
- package/prisma/schema.prisma +12 -6
- package/bin/chunk-0bj887zm.js +0 -2
- package/bin/chunk-1ktk6764.js +0 -10
- package/bin/chunk-26qn7fek.js +0 -2
- package/bin/chunk-2ne2b54t.js +0 -2
- package/bin/chunk-2vbeqczj.js +0 -1
- package/bin/chunk-37p6bcx2.js +0 -1
- package/bin/chunk-3knfx6dm.js +0 -1
- package/bin/chunk-3z85zxkn.js +0 -1
- package/bin/chunk-54tbfvya.js +0 -2
- package/bin/chunk-56kh5fxc.js +0 -1
- package/bin/chunk-576nj64j.js +0 -2
- package/bin/chunk-6cnqjngz.js +0 -1
- package/bin/chunk-7g46e1wy.js +0 -3
- package/bin/chunk-84x8p7v5.js +0 -1
- package/bin/chunk-88jg9dq5.js +0 -2
- package/bin/chunk-8fyg9dy4.js +0 -2
- package/bin/chunk-8gtfgkrn.js +0 -2
- package/bin/chunk-8mqbztj8.js +0 -2
- package/bin/chunk-8qdtvfx3.css +0 -1
- package/bin/chunk-8xb6yz11.js +0 -2
- package/bin/chunk-8yjsmr7g.js +0 -2
- package/bin/chunk-91rb0jpb.js +0 -2
- package/bin/chunk-96qpjght.js +0 -2
- package/bin/chunk-9f1xk1nt.js +0 -1
- package/bin/chunk-9mk9cvbk.js +0 -1
- package/bin/chunk-9nw5w8vh.js +0 -1
- package/bin/chunk-ah8fjb6f.js +0 -2
- package/bin/chunk-cf5axr8c.js +0 -1
- package/bin/chunk-dk42gf7v.js +0 -2
- package/bin/chunk-e4f56spj.js +0 -4
- package/bin/chunk-eb7mzbfm.js +0 -1
- package/bin/chunk-er14d498.js +0 -3
- package/bin/chunk-f6avg5qe.js +0 -129
- package/bin/chunk-fvx9k1dc.js +0 -2
- package/bin/chunk-gtf19jc1.js +0 -2
- package/bin/chunk-h1n7jqnw.js +0 -1
- package/bin/chunk-hfm82066.js +0 -2
- package/bin/chunk-j2s311yc.js +0 -3
- package/bin/chunk-kj6h5j5a.js +0 -4
- package/bin/chunk-km4gn6b6.js +0 -1
- package/bin/chunk-ny1kbmxt.js +0 -2
- package/bin/chunk-p3j6ydk1.js +0 -1
- package/bin/chunk-pk406dgy.js +0 -2
- package/bin/chunk-s1e4qy3q.js +0 -14
- package/bin/chunk-swtwaaqe.js +0 -1
- package/bin/chunk-tagdrg7p.js +0 -1
- package/bin/chunk-twtxnzbv.js +0 -2
- package/bin/chunk-v5mcjwxy.js +0 -2
- package/bin/chunk-vkzasgxw.js +0 -2
- package/bin/chunk-x342vzdx.js +0 -2
- package/bin/chunk-xc54vhfz.js +0 -2
- package/bin/chunk-xvkwbczx.js +0 -3
- package/bin/chunk-z1p13dnc.js +0 -2
- package/bin/chunk-zarz3sqn.js +0 -211
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{S,L,a,ee,Je,R,Ft,$t,Jg}from"./chunk-akafypge.js";import"./chunk-7e9ws6dh.js";import"./chunk-evs2aaav.js";import"./chunk-fb9dedm2.js";import"./chunk-7q4mgd5x.js";import"./chunk-d3brvxh7.js";import"./chunk-3mx4trvh.js";import"./chunk-wmrrapwv.js";import"./chunk-t6cb99gp.js";import"./chunk-xd1axsdv.js";import"./chunk-zdvhh8mk.js";import"./chunk-bssb9tar.js";import"./chunk-q57m34h0.js";import"./chunk-s4hkcw24.js";import{To}from"./chunk-e0bckx12.js";import"./chunk-vf9s8b5t.js";import{yr}from"./chunk-e8zzg57c.js";import"./chunk-av2w1sez.js";import"./chunk-km70p970.js";import"./chunk-8a7ymmd4.js";import"./chunk-k9vjs21p.js";import"./chunk-n54ftsdx.js";import"./chunk-na5fh7er.js";import"./chunk-qw92z3wf.js";import"./chunk-zg0b902x.js";import"./chunk-81b8rfv7.js";import"./chunk-wzrzc07t.js";L();function s(){let{projectId:o}=m.useParams(),{teamId:r,ensureTeamIdForProject:t}=Ft();S(()=>{t(o)},[o,t]);let{data:n}=yr(Jg(o)),e=n?.rootFolder,{data:d}=ee({queryKey:["folders",e],queryFn:()=>(async()=>await(await R.api.folders[":folderId"].$get({param:{folderId:e}})).json())(),enabled:!!e});if(!r||!e||!d)return a($t,{});return a(To,{teamId:r,projectId:o,projectName:n.name??"",assetId:"recently-deleted",rootFolderId:e})}var m=Je("/projects/$projectId/recently-deleted")({component:s});export{m as Route};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
function
|
|
3
|
-
export{
|
|
2
|
+
function io(t){if(!(t instanceof Error))return{message:u(t),messageCarriesBody:!1};let e=t,n=r(e),s=f(e),d=s===void 0||t.message.includes(s);return{status:n,body:s,message:t.message,messageCarriesBody:d}}function r(t){if(typeof t.statusCode==="number")return t.statusCode;if(typeof t.status==="number")return t.status;if(typeof t.$metadata?.httpStatusCode==="number")return t.$metadata.httpStatusCode;if(typeof t.$response?.statusCode==="number")return t.$response.statusCode;return}function f(t){let e=o(t);if(e===void 0)return;let n=e.trim();if(n.length===0)return;return c(n,4000)}function o(t){if(typeof t.body==="string")return t.body;if(i(t.error))return u(t.error);let e=t.$response?.body;if(typeof e==="string")return e;if(a(e))return;if(i(e))return u(e);return}function a(t){return typeof t==="object"&&t!==null&&"pipe"in t&&typeof t.pipe==="function"}function i(t){return typeof t==="object"&&t!==null&&Object.keys(t).length>0}function ao(t,e){if(t.messageCarriesBody||t.status===void 0||t.body===void 0)return e!==void 0&&t.status!==void 0?`${e} (${t.status}): ${t.message}`:t.message;return e!==void 0?`${e} (${t.status}): ${t.body}`:`${t.status}: ${t.body}`}function c(t,e){if(t.length<=e)return t;return`${t.slice(0,e)}... [truncated ${t.length-e} chars]`}function u(t){try{let e=JSON.stringify(t);return e===void 0?String(t):e}catch{return String(t)}}
|
|
3
|
+
export{io,ao};
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
3
|
-
`),u=o.filter((l)=>l.type==="image"),p=a.length>0;if(u.length===0||!i.input.includes("image"))return
|
|
2
|
+
import{In}from"./chunk-w6ym7tsd.js";import{yi}from"./chunk-q43m934j.js";import{lt,Vu,Ku,Qo,vc,Go}from"./chunk-jxm0gzmf.js";import{Kn}from"./chunk-978rm9a9.js";function v(i,o){let a={v:1,id:i};if(o)a.phase=o;return JSON.stringify(a)}function C(i){if(!i)return;if(i.startsWith("{"))try{let o=JSON.parse(i);if(o.v===1&&typeof o.id==="string"){if(o.phase==="commentary"||o.phase==="final_answer")return{id:o.id,phase:o.phase};return{id:o.id}}}catch{}return{id:i}}function J(i,o){let a=o.filter((l)=>l.type==="text").map((l)=>l.text).join(`
|
|
3
|
+
`),u=o.filter((l)=>l.type==="image"),p=a.length>0;if(u.length===0||!i.input.includes("image"))return lt(p?a:u.length>0?"(see attached image)":"(no tool output)");let f=[];if(p)f.push({type:"input_text",text:lt(a)});for(let l of u)f.push({type:"input_image",detail:"auto",image_url:`data:${l.mimeType};base64,${l.data}`});return f}function Ji(i,o,a,u){let p=[],f=new Set,l=(r)=>{let c=r.replace(/[^a-zA-Z0-9_-]/g,"_");return(c.length>64?c.slice(0,64):c).replace(/_+$/,"")},y=(r)=>{let c=`fc_${yi(r)}`;return c.length>64?c.slice(0,64):c},m=(r,c,t)=>{if(!a.has(i.provider))return l(r);if(!r.includes("|"))return l(r);let[e,n]=r.split("|"),s=l(e),g=t.provider!==i.provider||t.api!==i.api?y(n):l(n);if(!g.startsWith("fc_"))g=l(`fc_${g}`);return`${s}|${g}`},h=Go(o.messages,i,m);if((u?.includeSystemPrompt??!0)&&o.systemPrompt){let r=i.compat,c=i.reasoning&&r?.supportsDeveloperRole!==!1?"developer":"system";p.push({role:c,content:lt(o.systemPrompt)})}let x=0;for(let r of h){if(r.role==="user")if(typeof r.content==="string")p.push({role:"user",content:[{type:"input_text",text:lt(r.content)}]});else{let c=r.content.map((t)=>{if(t.type==="text")return{type:"input_text",text:lt(t.text)};return{type:"input_image",detail:"auto",image_url:`data:${t.mimeType};base64,${t.data}`}});if(c.length===0)continue;p.push({role:"user",content:c})}else if(r.role==="assistant"){let c=[],t=r,e=t.model!==i.id&&t.provider===i.provider&&t.api===i.api,n=0;for(let s of r.content)if(s.type==="thinking"){if(s.thinkingSignature){let d=JSON.parse(s.thinkingSignature);c.push(d)}}else if(s.type==="text"){let d=s,g=C(d.textSignature),b=n===0?`msg_pi_${x}`:`msg_pi_${x}_${n}`;n++;let _=g?.id;if(!_)_=b;else if(_.length>64)_=`msg_${yi(_)}`;c.push({type:"message",role:"assistant",content:[{type:"output_text",text:lt(d.text),annotations:[]}],status:"completed",id:_,phase:g?.phase})}else if(s.type==="toolCall"){let d=s,[g,b]=d.id.split("|"),_=u?.grammarToolInputProperties?.get(d.name),k=b;if(e&&k?.startsWith("fc_")||_===void 0&&!k?.startsWith("fc_"))k=void 0;if(_!==void 0)c.push({type:"custom_tool_call",id:k,call_id:g,name:d.name,input:lt(Vu(d.name,d.arguments,_))});else c.push({type:"function_call",id:k,call_id:g,name:d.name,arguments:JSON.stringify(d.arguments)})}if(c.length===0)continue;p.push(...c)}else if(r.role==="toolResult"){let[c]=r.toolCallId.split("|"),t=J(i,r.content);if(u?.grammarToolInputProperties?.has(r.toolName))p.push({type:"custom_tool_call_output",call_id:c,output:t});else p.push({type:"function_call_output",call_id:c,output:t});let e=[];for(let n of r.addedToolNames??[]){let s=u?.deferredTools?.get(n);if(!s||f.has(n))continue;f.add(n),e.push(s)}if(e.length>0){let n=e.map((d)=>d.name),s=`pi_tool_load_${yi(`${r.toolCallId}:${n.join(",")}`)}`;p.push({type:"tool_search_call",call_id:s,execution:"client",status:"completed",arguments:{query:n.join(" "),limit:n.length}}),p.push({type:"tool_search_output",call_id:s,execution:"client",status:"completed",tools:Yi(e,{...u?.toolOptions,deferLoading:!0})})}}x++}return p}function Yi(i,o){let a=o?.strict===void 0?!1:o.strict,u=o?.supportsStrictMode??!0,p=o?.supportsOpenAIGrammarTools??!1;return i.map((f)=>{let l=vc(f,p);if(l)return{type:"custom",name:f.name,description:f.description,format:{type:"grammar",syntax:l.format,definition:l.definition},...o?.deferLoading?{defer_loading:!0}:{}};let y=Qo(f,u),m={type:"function",name:f.name,description:f.description,parameters:f.parameters,...o?.deferLoading?{defer_loading:!0}:{}};if(u)m.strict=y??a;return m})}function T(i){let o=i.customInput?.property;if(o===void 0)return"";let a=i.arguments[o];return typeof a==="string"?a:""}function S(i,o,a){let u=i.customInput;if(!u)return;let p=Ku(u.jsonBuffer,u.property,o,a);return i.arguments={[u.property]:o},p}async function Xi(i,o,a,u,p){let f=!1,l=new Map,y=new Map,m=(t,e)=>{let n=l.get(t);return n?.type===e?n:void 0},h=(t,e)=>{if(e===void 0)return;a.push({type:"toolcall_delta",contentIndex:t.contentIndex,delta:e,partial:o})},I=(t,e)=>{if(e.type==="reasoning"){let n={type:"thinking",thinking:""};o.content.push(n);let s={type:"thinking",block:n,contentIndex:o.content.length-1};return l.set(t,s),a.push({type:"thinking_start",contentIndex:s.contentIndex,partial:o}),s}if(e.type==="message"){let n={type:"text",text:""};o.content.push(n);let s={type:"text",block:n,contentIndex:o.content.length-1};return l.set(t,s),a.push({type:"text_start",contentIndex:s.contentIndex,partial:o}),s}if(e.type==="function_call"){let n={type:"toolCall",id:`${e.call_id}|${e.id}`,name:e.name,arguments:{},partialJson:e.arguments||""};o.content.push(n);let s={type:"toolCall",block:n,contentIndex:o.content.length-1};return l.set(t,s),a.push({type:"toolcall_start",contentIndex:s.contentIndex,partial:o}),s}if(e.type==="custom_tool_call"){let n=p?.grammarToolInputProperties?.get(e.name)??"input",s=e.input||"",d={type:"toolCall",id:`${e.call_id}|${e.id}`,name:e.name,arguments:{[n]:s},customInput:{property:n,jsonBuffer:{input:"",started:!1,closed:!1}}};o.content.push(d);let g={type:"toolCall",block:d,contentIndex:o.content.length-1};return l.set(t,g),a.push({type:"toolcall_start",contentIndex:g.contentIndex,partial:o}),g}return},x=(t,e)=>l.get(t)??I(t,e),r=(t)=>{for(let e of t){if(e.type!=="reasoning"||!e.encrypted_content)continue;let n=y.get(e.id);if(!n?.thinkingSignature)continue;let s=JSON.parse(n.thinkingSignature);if(s.encrypted_content)continue;n.thinkingSignature=JSON.stringify({...s,encrypted_content:e.encrypted_content})}},c=(t)=>{if(f=!0,r(t.output??[]),t?.id)o.responseId=t.id;if(t?.usage){let e=t.usage.input_tokens_details,n=e?.cached_tokens||0,s=e?.cache_write_tokens||0;o.usage={input:Math.max(0,(t.usage.input_tokens||0)-n-s),output:t.usage.output_tokens||0,cacheRead:n,cacheWrite:s,reasoning:t.usage.output_tokens_details?.reasoning_tokens||0,totalTokens:t.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(Kn(u,o.usage),p?.applyServiceTierPricing){let e=p.resolveServiceTier?p.resolveServiceTier(t?.service_tier,p.serviceTier):t?.service_tier??p.serviceTier;p.applyServiceTierPricing(o.usage,e)}if(o.stopReason=w(t?.status),o.content.some((e)=>e.type==="toolCall")&&o.stopReason==="stop")o.stopReason="toolUse"};for await(let t of i)if(t.type==="response.created")o.responseId=t.response.id;else if(t.type==="response.output_item.added")I(t.output_index,t.item);else if(t.type==="response.reasoning_summary_text.delta"){let e=m(t.output_index,"thinking");if(!e)continue;e.block.thinking+=t.delta,a.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.reasoning_summary_part.done"){let e=m(t.output_index,"thinking");if(!e)continue;e.block.thinking+=`
|
|
4
4
|
|
|
5
5
|
`,a.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:`
|
|
6
6
|
|
|
7
|
-
`,partial:o})}else if(t.type==="response.reasoning_text.delta"){let e=m(t.output_index,"thinking");if(!e)continue;e.block.thinking+=t.delta,a.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.output_text.delta"){let e=m(t.output_index,"text");if(!e)continue;e.block.text+=t.delta,a.push({type:"text_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.refusal.delta"){let e=m(t.output_index,"text");if(!e)continue;e.block.text+=t.delta,a.push({type:"text_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.function_call_arguments.delta"){let e=m(t.output_index,"toolCall");if(!e||e.block.partialJson===void 0)continue;e.block.partialJson+=t.delta,e.block.arguments=
|
|
7
|
+
`,partial:o})}else if(t.type==="response.reasoning_text.delta"){let e=m(t.output_index,"thinking");if(!e)continue;e.block.thinking+=t.delta,a.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.output_text.delta"){let e=m(t.output_index,"text");if(!e)continue;e.block.text+=t.delta,a.push({type:"text_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.refusal.delta"){let e=m(t.output_index,"text");if(!e)continue;e.block.text+=t.delta,a.push({type:"text_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.function_call_arguments.delta"){let e=m(t.output_index,"toolCall");if(!e||e.block.partialJson===void 0)continue;e.block.partialJson+=t.delta,e.block.arguments=In(e.block.partialJson),h(e,t.delta)}else if(t.type==="response.function_call_arguments.done"){let e=m(t.output_index,"toolCall");if(!e||e.block.partialJson===void 0)continue;let n=e.block.partialJson;if(e.block.partialJson=t.arguments,e.block.arguments=In(e.block.partialJson),t.arguments.startsWith(n)){let s=t.arguments.slice(n.length);if(s.length>0)h(e,s)}}else if(t.type==="response.custom_tool_call_input.delta"){let e=m(t.output_index,"toolCall");if(!e||!e.block.customInput)continue;h(e,S(e.block,T(e.block)+t.delta,!1))}else if(t.type==="response.custom_tool_call_input.done"){let e=m(t.output_index,"toolCall");if(!e||!e.block.customInput)continue;h(e,S(e.block,t.input,!0))}else if(t.type==="response.output_item.done"){let e=t.item,n=x(t.output_index,e);if(e.type==="reasoning"&&n?.type==="thinking"){let s=e.summary?.map((g)=>g.text).join(`
|
|
8
8
|
|
|
9
9
|
`)||"",d=e.content?.map((g)=>g.text).join(`
|
|
10
10
|
|
|
11
|
-
`)||"";n.block.thinking=s||d||n.block.thinking,n.block.thinkingSignature=JSON.stringify(e),y.set(e.id,n.block),a.push({type:"thinking_end",contentIndex:n.contentIndex,content:n.block.thinking,partial:o}),l.delete(t.output_index)}else if(e.type==="message"&&n?.type==="text")n.block.text=e.content?.map((s)=>s.type==="output_text"?s.text:s.refusal).join("")||"",n.block.textSignature=v(e.id,e.phase??void 0),a.push({type:"text_end",contentIndex:n.contentIndex,content:n.block.text,partial:o}),l.delete(t.output_index);else if(e.type==="function_call"&&n?.type==="toolCall"&&n.block.partialJson!==void 0)n.block.arguments=
|
|
12
|
-
export{
|
|
11
|
+
`)||"";n.block.thinking=s||d||n.block.thinking,n.block.thinkingSignature=JSON.stringify(e),y.set(e.id,n.block),a.push({type:"thinking_end",contentIndex:n.contentIndex,content:n.block.thinking,partial:o}),l.delete(t.output_index)}else if(e.type==="message"&&n?.type==="text")n.block.text=e.content?.map((s)=>s.type==="output_text"?s.text:s.refusal).join("")||"",n.block.textSignature=v(e.id,e.phase??void 0),a.push({type:"text_end",contentIndex:n.contentIndex,content:n.block.text,partial:o}),l.delete(t.output_index);else if(e.type==="function_call"&&n?.type==="toolCall"&&n.block.partialJson!==void 0)n.block.arguments=In(e.arguments||n.block.partialJson||"{}"),delete n.block.partialJson,a.push({type:"toolcall_end",contentIndex:n.contentIndex,toolCall:n.block,partial:o}),l.delete(t.output_index);else if(e.type==="custom_tool_call"&&n?.type==="toolCall"&&n.block.customInput)h(n,S(n.block,e.input??T(n.block),!0)),delete n.block.customInput,a.push({type:"toolcall_end",contentIndex:n.contentIndex,toolCall:n.block,partial:o}),l.delete(t.output_index)}else if(t.type==="response.completed"||t.type==="response.incomplete")c(t.response);else if(t.type==="error")throw Error(`Error Code ${t.code}: ${t.message}`||"Unknown error");else if(t.type==="response.failed"){f=!0;let e=t.response?.error,n=t.response?.incomplete_details,s=e?`${e.code||"unknown"}: ${e.message||"no message"}`:n?.reason?`incomplete: ${n.reason}`:"Unknown error (no error details in response)";throw Error(s)}if(!f)throw Error("OpenAI Responses stream ended before a terminal response event")}function w(i){if(!i)return"stop";switch(i){case"completed":return"stop";case"incomplete":return"length";case"failed":case"cancelled":return"error";case"in_progress":case"queued":return"stop";default:throw Error(`Unhandled stop reason: ${i}`)}}
|
|
12
|
+
export{Ji,Yi,Xi};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{kr}from"./chunk-cwat1jwx.js";import"./chunk-x8mjh387.js";import{Oa}from"./chunk-7v7mypc6.js";import{$i,Hi,Qi}from"./chunk-1wfg56z3.js";import{Bs}from"./chunk-j2s311yc.js";import{no,oo}from"./chunk-eyjfhdp9.js";import{Hn}from"./chunk-7g46e1wy.js";import{Co,Yr}from"./chunk-vcrmjtcz.js";import{lc}from"./chunk-mcj1xpcc.js";import{vn}from"./chunk-jzgbxqdg.js";import{ja,Ju,Sc,mr}from"./chunk-v05rrxp5.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]||kr(r)||kr(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 mr;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=Co(t.tools,e.compat?.supportsOpenAIGrammarTools??!1),a=r?.cacheRetention==="none"?void 0:r?.sessionId,c=Bs(a),d=Ie(e,t,r,c,l),u=await r?.onPayload?.(d,e);if(u!==void 0)d=u;let g=c||lc(),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(Sc(s,Ju("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:Hn(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=oo(no(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=Yr(e,t,r,n),o=r?.reasoning?vn(e,r.reasoning):void 0;return De(e,t,{...s,reasoningEffort:o==="off"?void 0:o})};function Ie(e,t,r,n,s=Co(t.tools,e.compat?.supportsOpenAIGrammarTools??!1)){let o=e.compat?.supportsStrictMode??!0,i=e.compat?.supportsOpenAIGrammarTools??!1,l=Oa(t,e.compat?.supportsToolSearch??!1),a=$i(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=Hi(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 Qi(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{Mr}from"./chunk-xk0jmx4s.js";import"./chunk-w6ym7tsd.js";import{$a}from"./chunk-zhq7a7hs.js";import{Ji,Yi,Xi}from"./chunk-gm1fy3hm.js";import{Qs}from"./chunk-by9esjn7.js";import{io,ao}from"./chunk-gd3b5akr.js";import{Gn}from"./chunk-1aqs9sdh.js";import{Ro,tn}from"./chunk-jxm0gzmf.js";import{Ec}from"./chunk-01vx2chc.js";import{En}from"./chunk-978rm9a9.js";import{el,md,zc,hr}from"./chunk-w4gqg27w.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]||Mr(r)||Mr(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 hr;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=Ro(t.tools,e.compat?.supportsOpenAIGrammarTools??!1),a=r?.cacheRetention==="none"?void 0:r?.sessionId,c=Qs(a),d=Ie(e,t,r,c,l),u=await r?.onPayload?.(d,e);if(u!==void 0)d=u;let g=c||Ec(),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(zc(s,md("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:Gn(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=ao(io(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=tn(e,t,r,n),o=r?.reasoning?En(e,r.reasoning):void 0;return De(e,t,{...s,reasoningEffort:o==="off"?void 0:o})};function Ie(e,t,r,n,s=Ro(t.tools,e.compat?.supportsOpenAIGrammarTools??!1)){let o=e.compat?.supportsStrictMode??!0,i=e.compat?.supportsOpenAIGrammarTools??!1,l=$a(t,e.compat?.supportsToolSearch??!1),a=Ji(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=Yi(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 Xi(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: ${
|
|
6
|
+
`).trim();if(u&&u!=="[DONE]")try{yield JSON.parse(u)}catch(g){throw new B(`Invalid Codex SSE JSON: ${el(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=
|
|
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=el(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=Gn(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: ${el(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 Xi(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=Ji(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};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{Ti,Ds}from"./chunk-v4nqx084.js";import{Ns}from"./chunk-6ty4tfmf.js";import{Fs,Yo,Xt}from"./chunk-c61g9hfa.js";import{Jn,Er,At,Mn,gr,es,ar}from"./chunk-m6v8rb39.js";var{awsEndpointFunctions:B,emitWarningIfUnsupportedVersion:W,createDefaultUserAgentProvider:Q,NODE_APP_ID_CONFIG_OPTIONS:Y,getAwsRegionExtensionConfiguration:J,resolveAwsRegionExtensionConfiguration:X,resolveUserAgentConfig:Z,resolveHostHeaderConfig:ee,getUserAgentPlugin:te,getHostHeaderPlugin:se,getLoggerPlugin:oe,getRecursionDetectionPlugin:ne}=Xt(),{NoAuthSigner:re,getHttpAuthSchemeEndpointRuleSetPlugin:ie,DefaultIdentityProviderConfig:ae,getHttpSigningPlugin:ce}=Yo(),{normalizeProvider:b,getSmithyContext:ue,ServiceException:de,NoOpLogger:le,emitWarningIfUnsupportedVersion:pe,loadConfigsForDefaultMode:he,getDefaultExtensionConfiguration:ge,resolveDefaultRuntimeConfig:me,Client:_e,makeBuilder:Se,createAggregatedClient:fe}=Er(),{Command:cs}=Er();var{resolveDefaultsModeConfig:Ee,loadConfig:a,NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS:Pe,NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS:ve,NODE_REGION_CONFIG_OPTIONS:Re,NODE_REGION_CONFIG_FILE_OPTIONS:Ce,resolveRegionConfig:xe}=At(),{BinaryDecisionDiagram:Ie,EndpointCache:Ae,decideEndpoint:ye,customEndpointFunctions:Oe,resolveEndpointConfig:Te,getEndpointPlugin:De}=Mn(),{parseUrl:Ne,getHttpHandlerExtensionConfiguration:we,resolveHttpHandlerRuntimeConfig:ke,getContentLengthPlugin:be}=ar(),{DEFAULT_RETRY_MODE:Fe,NODE_RETRY_MODE_CONFIG_OPTIONS:$e,NODE_MAX_ATTEMPT_CONFIG_OPTIONS:qe,resolveRetryConfig:He,getRetryPlugin:Ue}=Fs(),{TypeRegistry:F,getSchemaSerdePlugin:Ge}=Jn(),{resolveAwsSdkSigV4Config:Me,AwsSdkSigV4Signer:ze,NODE_AUTH_SCHEME_PREFERENCE_OPTIONS:je}=Ds(),{toUtf8:Le,fromUtf8:Ke,toBase64:Ve,fromBase64:Be,calculateBodyLength:We}=gr(),{streamCollector:Qe,NodeHttpHandler:Ye}=Ns(),{AwsRestJsonProtocol:Je}=Ti(),{Sha256:Xe}=es(),Ze=async(e,t,s)=>({operation:ue(t).operation,region:await b(e.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()});function et(e){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"awsssoportal",region:e.region},propertiesExtractor:(t,s)=>({signingProperties:{config:t,context:s}})}}function tt(e){return{schemeId:"smithy.api#noAuth"}}var st=(e)=>{let t=[];switch(e.operation){case"GetRoleCredentials":{t.push(tt());break}default:t.push(et(e))}return t},ot=(e)=>{let t=Me(e);return Object.assign(t,{authSchemePreference:b(e.authSchemePreference??[])})},nt=(e)=>Object.assign(e,{useDualstackEndpoint:e.useDualstackEndpoint??!1,useFipsEndpoint:e.useFipsEndpoint??!1,defaultSigningName:"awsssoportal"}),rt={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},it="3.997.43",at={version:it},l="ref",c=-1,g=!0,T="isSet",q="PartitionResult",m="booleanEquals",v="getAttr",D={[l]:"Endpoint"},R={[l]:q},d={},N=[{[l]:"Region"}],w={conditions:[[T,[D]],[T,N],["aws.partition",N,q],[m,[{[l]:"UseFIPS"},g]],[m,[{[l]:"UseDualStack"},g]],[m,[{fn:v,argv:[R,"supportsDualStack"]},g]],[m,[{fn:v,argv:[R,"supportsFIPS"]},g]],["stringEquals",[{fn:v,argv:[R,"name"]},"aws-us-gov"]]],results:[[c],[c,"Invalid Configuration: FIPS and custom endpoint are not supported"],[c,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[D,d],["https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",d],[c,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://portal.sso.{Region}.amazonaws.com",d],["https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}",d],[c,"FIPS is enabled but this partition does not support FIPS"],["https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}",d],[c,"DualStack is enabled but this partition does not support DualStack"],["https://portal.sso.{Region}.{PartitionResult#dnsSuffix}",d],[c,"Invalid Configuration: Missing Region"]]},ct=2,n=1e8,ut=new Int32Array([-1,1,-1,0,13,3,1,4,n+12,2,5,n+12,3,8,6,4,7,n+11,5,n+9,n+10,4,11,9,6,10,n+8,7,n+6,n+7,5,12,n+5,6,n+4,n+5,3,n+1,14,4,n+2,n+3]),dt=Ie.from(ut,ct,w.conditions,w.results),lt=new Ae({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),pt=(e,t={})=>lt.get(e,()=>ye(dt,{endpointParams:e,logger:t.logger}));Oe.aws=B;class u extends de{constructor(e){super(e);Object.setPrototypeOf(this,u.prototype)}}class C extends u{name="InvalidRequestException";$fault="client";constructor(e){super({name:"InvalidRequestException",$fault:"client",...e});Object.setPrototypeOf(this,C.prototype)}}class x extends u{name="ResourceNotFoundException";$fault="client";constructor(e){super({name:"ResourceNotFoundException",$fault:"client",...e});Object.setPrototypeOf(this,x.prototype)}}class I extends u{name="TooManyRequestsException";$fault="client";constructor(e){super({name:"TooManyRequestsException",$fault:"client",...e});Object.setPrototypeOf(this,I.prototype)}}class A extends u{name="UnauthorizedException";$fault="client";constructor(e){super({name:"UnauthorizedException",$fault:"client",...e});Object.setPrototypeOf(this,A.prototype)}}var ht="AccessTokenType",gt="GetRoleCredentials",mt="GetRoleCredentialsRequest",_t="GetRoleCredentialsResponse",St="InvalidRequestException",ft="RoleCredentials",Et="ResourceNotFoundException",Pt="SecretAccessKeyType",vt="SessionTokenType",Rt="TooManyRequestsException",Ct="UnauthorizedException",xt="accountId",It="accessKeyId",yt="accessToken",Ot="account_id",_="client",S="error",Tt="expiration",Dt="http",f="httpError",Nt="httpHeader",k="httpQuery",E="message",wt="roleCredentials",kt="roleName",bt="role_name",H="smithy.ts.sdk.synthetic.com.amazonaws.sso",Ft="secretAccessKey",$t="sessionToken",qt="x-amz-sso_bearer_token",r="com.amazonaws.sso",U=F.for(H),Ht=[-3,H,"SSOServiceException",0,[],[]];U.registerError(Ht,u);var p=F.for(r),Ut=[-3,r,St,{[S]:_,[f]:400},[E],[0]];p.registerError(Ut,C);var Gt=[-3,r,Et,{[S]:_,[f]:404},[E],[0]];p.registerError(Gt,x);var Mt=[-3,r,Rt,{[S]:_,[f]:429},[E],[0]];p.registerError(Mt,I);var zt=[-3,r,Ct,{[S]:_,[f]:401},[E],[0]];p.registerError(zt,A);var jt=[U,p],Lt=[0,r,ht,8,0],Kt=[0,r,Pt,8,0],Vt=[0,r,vt,8,0],Bt=[3,r,mt,0,[kt,xt,yt],[[0,{[k]:bt}],[0,{[k]:Ot}],[()=>Lt,{[Nt]:qt}]],3],Wt=[3,r,_t,0,[wt],[[()=>Qt,0]]],Qt=[3,r,ft,0,[It,Ft,$t,Tt],[0,[()=>Kt,0],[()=>Vt,0],1]],Yt=[9,r,gt,{[Dt]:["GET","/federation/credentials",200]},()=>Bt,()=>Wt],Jt=(e)=>({apiVersion:"2019-06-10",base64Decoder:e?.base64Decoder??Be,base64Encoder:e?.base64Encoder??Ve,disableHostPrefix:e?.disableHostPrefix??!1,endpointProvider:e?.endpointProvider??pt,extensions:e?.extensions??[],httpAuthSchemeProvider:e?.httpAuthSchemeProvider??st,httpAuthSchemes:e?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(t)=>t.getIdentityProvider("aws.auth#sigv4"),signer:new ze},{schemeId:"smithy.api#noAuth",identityProvider:(t)=>t.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new re}],logger:e?.logger??new le,protocol:e?.protocol??Je,protocolSettings:e?.protocolSettings??{defaultNamespace:"com.amazonaws.sso",errorTypeRegistries:jt,version:"2019-06-10",serviceTarget:"SWBPortalService"},serviceId:e?.serviceId??"SSO",sha256:e?.sha256??Xe,urlParser:e?.urlParser??Ne,utf8Decoder:e?.utf8Decoder??Ke,utf8Encoder:e?.utf8Encoder??Le}),Zt=(e)=>{pe(process.version);let t=Ee(e),s=()=>t().then(he),i=Jt(e);W(process.version);let o={profile:e?.profile,logger:i.logger};return{...i,...e,runtime:"node",defaultsMode:t,authSchemePreference:e?.authSchemePreference??a(je,o),bodyLengthChecker:e?.bodyLengthChecker??We,defaultUserAgentProvider:e?.defaultUserAgentProvider??Q({serviceId:i.serviceId,clientVersion:at.version}),maxAttempts:e?.maxAttempts??a(qe,e),region:e?.region??a(Re,{...Ce,...o}),requestHandler:Ye.create(e?.requestHandler??s),retryMode:e?.retryMode??a({...$e,default:async()=>(await s()).retryMode||Fe},e),streamCollector:e?.streamCollector??Qe,useDualstackEndpoint:e?.useDualstackEndpoint??a(ve,o),useFipsEndpoint:e?.useFipsEndpoint??a(Pe,o),userAgentAppId:e?.userAgentAppId??a(Y,o)}},ts=(e)=>{let{httpAuthSchemes:t,httpAuthSchemeProvider:s,credentials:i}=e;return{setHttpAuthScheme(o){let h=t.findIndex((P)=>P.schemeId===o.schemeId);if(h===-1)t.push(o);else t.splice(h,1,o)},httpAuthSchemes(){return t},setHttpAuthSchemeProvider(o){s=o},httpAuthSchemeProvider(){return s},setCredentials(o){i=o},credentials(){return i}}},ss=(e)=>({httpAuthSchemes:e.httpAuthSchemes(),httpAuthSchemeProvider:e.httpAuthSchemeProvider(),credentials:e.credentials()}),os=(e,t)=>{let s=Object.assign(J(e),ge(e),we(e),ts(e));return t.forEach((i)=>i.configure(s)),Object.assign(e,X(s),me(s),ke(s),ss(s))};class y extends _e{config;constructor(...[e]){let t=Zt(e||{});super(t);this.initConfig=t;let s=nt(t),i=Z(s),o=He(i),h=xe(o),P=ee(h),j=Te(P),L=ot(j),K=os(L,e?.extensions||[]);this.config=K,this.middlewareStack.use(Ge(this.config)),this.middlewareStack.use(te(this.config)),this.middlewareStack.use(Ue(this.config)),this.middlewareStack.use(be(this.config)),this.middlewareStack.use(se(this.config)),this.middlewareStack.use(oe(this.config)),this.middlewareStack.use(ne(this.config)),this.middlewareStack.use(ie(this.config,{httpAuthSchemeParametersProvider:Ze,identityProviderConfigProvider:async(V)=>new ae({"aws.auth#sigv4":V.credentials})})),this.middlewareStack.use(ce(this.config))}destroy(){super.destroy()}}var ns=Se(rt,"SWBPortalService","SSOClient",De),rs={},is=(e,t,s,i)=>[];class O extends ns(rs,is,"GetRoleCredentials",Yt){}var as={GetRoleCredentialsCommand:O};class G extends y{}fe(as,G);var M=O;var z=y;export{M as GetRoleCredentialsCommand,z as SSOClient};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
function
|
|
3
|
-
export{
|
|
2
|
+
function lt(e){return e.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"")}function Vu(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 Ku(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 Qo(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 vc(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 Ro(e,n){let t=new Map;for(let r of e??[]){let o=vc(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 Pm(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 tn(e,n,t,r){return{temperature:t?.temperature,maxTokens:Pm(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 cA(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 Go(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{lt,Vu,Ku,Qo,vc,Ro,Pm,tn,cA,Go};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
function r(e){let t=e[e.length-1];return t&&t.role!=="user"?"agent":"user"}function
|
|
3
|
-
export{
|
|
2
|
+
function r(e){let t=e[e.length-1];return t&&t.role!=="user"?"agent":"user"}function Ha(e){return e.some((t)=>{if(t.role==="user"&&Array.isArray(t.content))return t.content.some((n)=>n.type==="image");if(t.role==="toolResult"&&Array.isArray(t.content))return t.content.some((n)=>n.type==="image");return!1})}function Qa(e){let t={"X-Initiator":r(e.messages),"Openai-Intent":"conversation-edits"};if(e.hasImages)t["Copilot-Vision-Request"]="true";return t}
|
|
3
|
+
export{Ha,Qa};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{
|
|
1
|
+
import{j}from"./chunk-akafypge.js";var a=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],La=j("link",a);
|
|
2
|
+
export{La};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{G,S,Q,M,w,L,W,a,g,ae,ee,X,Rt,Je,R,j,V,qe,Dn,qt,Xn,Bo,vs,Re,Ue,Ke,N,De,Ne,Fe,se,Sn,rr,fh,HA,mh,nw,ow,gh,Ah,Ge,DE,dl,cx,gx,N_,Dt,Sh,CC,jC,W_,KC,XC,eS,tS,rS,nS,Yl,ba,wa,Ph,Xl,DS,GS,bI,FI,ZI,eT,rT,nT,qp,s1,Q1,V1,rk,ok,sg,Gy,ig,zk,jk,fu,YR,uM,mo,hM,CM,TM,O0,oc,Hd,pu,Tg,kg,Rg,mu,Qd,Gd,Mg,Og,Vd,hP,gP,AP,_P,vP,to,zg,lD,cD,gu,cv,yD,vD,bD,wD,ED,Se,xe,ke,ot,Ce,re,Ie,Ft,ln,ro,So,Wd,B,Qr,Un,fe,Ve,Ye,Xe,et,tt,be,Ia,cr,Br,$t,tA}from"./chunk-akafypge.js";import{gc}from"./chunk-7e9ws6dh.js";import{of,Oa}from"./chunk-evs2aaav.js";import{Ss}from"./chunk-fb9dedm2.js";import"./chunk-7q4mgd5x.js";import"./chunk-d3brvxh7.js";import"./chunk-xd1axsdv.js";import{en}from"./chunk-s4hkcw24.js";import{yl,Cu}from"./chunk-t6cb99gp.js";import{bu,wu}from"./chunk-a283dh05.js";import{vl}from"./chunk-45pb3kzz.js";import{Su}from"./chunk-13rq2gtr.js";import{yr}from"./chunk-e8zzg57c.js";import{Tu}from"./chunk-4awk4xhq.js";import"./chunk-av2w1sez.js";import"./chunk-8a7ymmd4.js";import"./chunk-k9vjs21p.js";import"./chunk-n54ftsdx.js";import"./chunk-qw92z3wf.js";import{Ho}from"./chunk-zg0b902x.js";import"./chunk-81b8rfv7.js";import{ko}from"./chunk-8ac9at5y.js";import{zr}from"./chunk-wzrzc07t.js";L();var bt=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],it=j("folder-open",bt);var yt=[["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M9 19h6",key:"456am0"}]],lt=j("list-filter",yt);L();function Nt({ratio:t}){switch(t){case"16:9":return a("span",{className:"inline-block w-4 h-2.5 border border-current rounded-[1px] shrink-0"});case"9:16":return a("span",{className:"inline-block w-2.5 h-4 border border-current rounded-[1px] shrink-0"});case"4:3":return a("span",{className:"inline-block w-3.5 h-2.5 border border-current rounded-[1px] shrink-0"});case"3:4":return a("span",{className:"inline-block w-2.5 h-3.5 border border-current rounded-[1px] shrink-0"});case"1:1":return a("span",{className:"inline-block w-3 h-3 border border-current rounded-[1px] shrink-0"});default:return a("span",{className:"inline-block w-4 h-2.5 border border-current rounded-[1px] shrink-0"})}}function rt(){return Math.random().toString(36).substring(2,9)}function dt(){return{id:rt(),type:"text",text:"CONFIDENTIAL",x:0.5,y:0.5,size:0.05,color:"#999999",opacity:0.5,rotation:-30}}function kt(){return{id:rt(),type:"image",imageAssetKey:"",x:0.5,y:0.5,size:0.15,opacity:0.5,rotation:0}}var at=[{id:"dark",label:"Dark Slate",bg:"#1e293b",dot:"#475569"},{id:"black",label:"Black",bg:"#000000",dot:"#404040"},{id:"gray",label:"Slate Gray",bg:"#64748b",dot:"#cbd5e1"},{id:"white",label:"White",bg:"#ffffff",dot:"#94a3b8"},{id:"green",label:"Chroma Green",bg:"#059669",dot:"#047857"}],St={"16:9":1.7777777777777777,"9:16":0.5625,"4:3":1.3333333333333333,"3:4":0.75,"1:1":1};function mt({open:t,onOpenChange:b,initialConfig:f,shareId:m,teamId:y,onSaveSuccess:x}){let D=ae(),[l,v]=w([]),[d,p]=w(null),[T,A]=w(null),[k,ie]=w("16:9"),[de,ce]=w("grid"),[ge,K]=w(!1),[le,te]=w("new"),[ne,U]=w(""),[H,Y]=w(null),_=M(null),J=M(null),[Z,ve]=w({w:0,h:0}),[I,z]=w(!1),s=G((e)=>{if(J.current=e,!e)return;let i=()=>{let{clientWidth:F,clientHeight:h}=e;if(F<=0||h<=0)return;let E=St[k],Ze=F,Te=Ze/E;if(Te>h)Te=h,Ze=Te*E;ve({w:Math.round(Ze),h:Math.round(Te)})};i();let o=new ResizeObserver(i);return o.observe(e),()=>{o.disconnect(),J.current=null}},[k]),q=Ft((e)=>e.teamId),me=y||q,[Ee,ye]=w(!1),[O,he]=w({}),oe=M(null),ue=R.api.teams[":teamId"].files.$post,we=async(e,i)=>{let o=e.target.files?.[0];if(!o)return;if(o.size>1048576){if(B.error(DS()),oe.current)oe.current.value="";return}if(!me){B.error(wa());return}ye(!0);let F=URL.createObjectURL(o);he((h)=>({...h,[i]:F}));try{let h=await ue({param:{teamId:me},form:{file:o}});if(!h.ok)throw Error(wa());let E=await h.json();C(i,{imageAssetKey:E.key,imageAssetUrl:E.url})}catch(h){let E=h instanceof Error?h.message:wa();B.error(E)}finally{if(ye(!1),oe.current)oe.current.value=""}};S(()=>{if(t){if(f?.blocks&&f.blocks.length>0)v(f.blocks),p(f.blocks[0].id);else{let e=dt();v([e]),p(e.id)}A(null)}},[t,f]);let{data:P=[]}=ee({queryKey:["watermark-templates",y],queryFn:async()=>{let e=await R.api["watermark-templates"].$get({query:y?{teamId:y}:{}});if(!e.ok)return[];return await e.json()},enabled:t}),_e=R.api.shares[":shareId"].watermark.$put,{mutate:pe,isPending:Ae}=X({mutationFn:async(e)=>{let i=await _e({param:{shareId:m},json:{enabled:!0,config:e}});if(!i.ok){let o=await i.json().catch(()=>null);throw Error(o?.error||ba())}return await i.json()},onSuccess:()=>{D.invalidateQueries({queryKey:["share",m]}),D.invalidateQueries({queryKey:["shares"]}),B.success(ED()),b(!1),x?.()},onError:(e)=>{B.error(e.message||ba())}}),We=R.api["watermark-templates"].$post,{mutate:ze,isPending:Le}=X({mutationFn:async({name:e,config:i})=>{let o=await We({json:{name:e,teamId:y||void 0,config:i}});if(!o.ok)throw Error(ba());return await o.json()},onSuccess:(e)=>{D.invalidateQueries({queryKey:["watermark-templates"]}),A(e.id),K(!1),B.success(AP())},onError:()=>{B.error(ba())}}),$e=R.api["watermark-templates"][":templateId"].$put,{mutate:Me,isPending:Oe}=X({mutationFn:async({templateId:e,config:i})=>{let o=await $e({param:{templateId:e},json:{config:i}});if(!o.ok)throw Error(ba());return await o.json()},onSuccess:()=>{D.invalidateQueries({queryKey:["watermark-templates"]}),K(!1),B.success(_P())},onError:()=>{B.error(ba())}}),r=R.api["watermark-templates"][":templateId"].$delete,{mutate:c}=X({mutationFn:async(e)=>{if(!(await r({param:{templateId:e}})).ok)throw Error(Yl())},onSuccess:(e,i)=>{if(D.invalidateQueries({queryKey:["watermark-templates"]}),T===i)A(null);B.success(hP())},onError:()=>{B.error(Yl())}}),u=l.findIndex((e)=>e.id===d),n=u>=0?l[u]:null,Be=()=>{let e=dt();v((i)=>[...i,e]),p(e.id)},pt=()=>{let e=kt();v((i)=>[...i,e]),p(e.id)},nt=(e)=>{if(!e)return;v((i)=>{let o=i.filter((F)=>F.id!==e);if(d===e)p(o.length>0?o[Math.max(0,u-1)].id:null);return o})},C=(e,i)=>{v((o)=>o.map((F)=>F.id===e?{...F,...i}:F))},ft=()=>{if(l.length===0)return;let e=(u-1+l.length)%l.length;p(l[e].id)},gt=()=>{if(l.length===0)return;let e=(u+1)%l.length;p(l[e].id)},xt=(e,i)=>{e.stopPropagation(),p(i),z(!0)},Qe=G((e)=>{if(!I||!d||!_.current)return;let i=_.current.getBoundingClientRect(),o=(e.clientX-i.left)/i.width,F=(e.clientY-i.top)/i.height,h=Math.max(0,Math.min(1,Math.round(o*100)/100)),E=Math.max(0,Math.min(1,Math.round(F*100)/100));C(d,{x:h,y:E})},[I,d]),He=G(()=>{z(!1)},[]);S(()=>{if(I)window.addEventListener("mousemove",Qe),window.addEventListener("mouseup",He);return()=>{window.removeEventListener("mousemove",Qe),window.removeEventListener("mouseup",He)}},[I,Qe,He]),S(()=>{let e=(i)=>{if(!t||!d)return;let o=i.target?.tagName?.toLowerCase();if(o==="input"||o==="textarea"||o==="select")return;if(i.key==="Delete"||i.key==="Backspace")i.preventDefault(),nt(d)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[t,d,u]);let vt=(e)=>{if(e.config?.blocks&&e.config.blocks.length>0){let i=e.config.blocks.map((o)=>({...o,id:rt()}));v(i),p(i[0].id),A(e.id)}},ht=()=>{if(l.length===0){B.error(V1());return}pe({blocks:l})},wt=()=>{if(le==="new"){if(!ne.trim()){B.error(W_());return}ze({name:ne.trim(),config:{blocks:l}})}else{let e=H||T;if(!e){B.error(O0());return}Me({templateId:e,config:{blocks:l}})}};return g(W,{children:[a(Se,{open:t,onOpenChange:b,children:g(xe,{showCloseButton:!1,className:"sm:max-w-[1400px] max-w-[95vw] w-[95vw] h-[88vh] flex flex-col p-0 gap-0 overflow-hidden",onPointerDownOutside:(e)=>e.preventDefault(),children:[g("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border bg-card",children:[a("div",{className:"flex items-center gap-3",children:a(Ce,{className:"text-base font-semibold",children:vD()})}),g("div",{className:"flex items-center gap-2",children:[g(De,{modal:!1,children:[a(Ne,{asChild:!0,children:g(N,{variant:"outline",size:"sm",className:"gap-2 text-xs",children:[a(it,{className:"h-4 w-4 text-muted-foreground"}),bD()]})}),g(Fe,{align:"end",className:"w-56",children:[a(Sn,{className:"text-xs font-semibold text-muted-foreground",children:nT()}),P.length===0?a("div",{className:"px-2 py-1.5 text-xs text-muted-foreground italic",children:Q1()}):P.map((e)=>g(se,{onClick:()=>vt(e),className:"flex items-center justify-between text-xs cursor-pointer",children:[a("span",{className:"truncate flex-1",children:e.name}),T===e.id&&a(qe,{className:"h-3.5 w-3.5 text-primary ml-2 flex-shrink-0"}),a(N,{variant:"ghost",size:"icon",className:"h-5 w-5 hover:bg-destructive/10 hover:text-destructive ml-1",onClick:(i)=>{i.stopPropagation(),c(e.id)},children:a(Ue,{className:"h-3 w-3"})})]},e.id)),a(rr,{}),g(se,{onClick:()=>{te("new"),U(""),K(!0)},className:"text-xs gap-2 cursor-pointer",children:[a(Re,{className:"h-3.5 w-3.5 text-primary"}),N_()]}),P.length>0&&g(se,{onClick:()=>{te("overwrite"),Y(T||P[0].id),K(!0)},className:"text-xs gap-2 cursor-pointer",children:[a(vl,{className:"h-3.5 w-3.5 text-muted-foreground"}),Gy()]})]})]}),a(N,{variant:"outline",size:"sm",className:"text-xs",onClick:()=>b(!1),children:Ge()}),g(N,{size:"sm",className:"text-xs bg-primary hover:bg-primary/90 text-primary-foreground gap-1.5",disabled:Ae,onClick:ht,children:[a(vl,{className:"h-3.5 w-3.5"}),hM()]})]})]}),g("div",{className:"flex-1 flex overflow-hidden",children:[g("div",{className:"w-[65%] flex flex-col p-4 bg-muted/20 border-r border-border overflow-hidden select-none",children:[g("div",{className:"flex items-center justify-between mb-3",children:[a("div",{className:"flex items-center gap-1 bg-muted/60 p-1 rounded-md border border-border/60",children:["16:9","9:16","4:3","3:4","1:1"].map((e)=>g(N,{variant:k===e?"secondary":"ghost",size:"sm",className:Pe("h-7 px-2.5 text-xs gap-1.5 font-mono transition-all",k===e?"bg-background shadow-xs font-semibold text-foreground border border-border/50":"text-muted-foreground hover:text-foreground"),onClick:()=>ie(e),children:[a(Nt,{ratio:e}),a("span",{children:e})]},e))}),a("div",{className:"flex items-center gap-1.5 bg-background border border-border/60 rounded-md p-1",children:at.map((e)=>a("button",{type:"button",onClick:()=>ce(e.id),style:{backgroundColor:e.bg},className:Pe("w-5 h-5 rounded-full border border-border/80 transition-all cursor-pointer relative",de===e.id?"ring-2 ring-primary ring-offset-1 scale-110":"hover:scale-105 opacity-80 hover:opacity-100"),title:e.label},e.id))})]}),a("div",{ref:s,className:"flex-1 flex items-center justify-center overflow-hidden",children:(()=>{let e=at.find((o)=>o.id===de)||at[0],i=Z.w>0&&Z.h>0;return a("div",{ref:_,onClick:()=>p(null),style:{backgroundColor:e.bg,backgroundImage:`radial-gradient(${e.dot} 1px, transparent 1px)`,backgroundSize:"16px 16px",...i?{width:Z.w,height:Z.h}:{}},className:Pe("relative rounded-lg border border-border overflow-hidden shadow-inner transition-all",k==="16:9"&&"aspect-[16/9] w-full max-h-full",k==="9:16"&&"aspect-[9/16] h-full max-w-full",k==="4:3"&&"aspect-[4/3] w-full max-h-full",k==="3:4"&&"aspect-[3/4] h-full max-w-full",k==="1:1"&&"aspect-square h-full max-w-full"),children:l.map((o)=>{let F=o.id===d,h=o.size*(Z.w||640);return a("div",{onMouseDown:(E)=>xt(E,o.id),onClick:(E)=>{E.stopPropagation(),p(o.id)},style:{left:`${o.x*100}%`,top:`${o.y*100}%`,transform:`translate(-50%, -50%) rotate(${o.rotation}deg)`,opacity:o.opacity},className:Pe("absolute cursor-move select-none transition-shadow rounded p-1.5 flex items-center justify-center",F?"ring-2 ring-primary ring-offset-2 ring-offset-background/80 bg-primary/10":"hover:ring-1 hover:ring-muted-foreground/50"),children:o.type==="text"?a("span",{style:{fontSize:`${h}px`,color:o.color,lineHeight:1,whiteSpace:"nowrap",fontWeight:700,textShadow:"0 1px 3px rgba(0,0,0,0.5)"},children:o.text||"Text"}):a("div",{style:{width:`${h}px`,height:`${h}px`},className:"bg-primary/20 border border-primary/40 rounded flex items-center justify-center p-1 overflow-hidden",children:O[o.id]||o.imageAssetUrl?a("img",{src:O[o.id]||o.imageAssetUrl,alt:"Watermark logo",className:"w-full h-full object-contain pointer-events-none"}):a(Xn,{className:"h-1/2 w-1/2 opacity-70 text-primary"})})},o.id)})})})()})]}),g("div",{className:"w-[35%] flex flex-col bg-card overflow-hidden border-l border-border",children:[a("div",{className:"p-4 border-b border-border bg-muted/10 flex items-center justify-between",children:g("div",{className:"flex items-center gap-2",children:[a(Bo,{className:"h-4 w-4 text-muted-foreground"}),a("span",{className:"text-xs font-semibold",children:cv()})]})}),g("div",{className:"p-3 border-b border-border bg-background flex items-center justify-between gap-2",children:[g("div",{className:"flex items-center gap-1",children:[a(N,{variant:"outline",size:"icon",className:"h-7 w-7",disabled:l.length<=1,onClick:ft,children:a(Dn,{className:"h-4 w-4"})}),g(De,{modal:!1,children:[a(Ne,{asChild:!0,children:a(N,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs font-mono",children:l.length===0?"0 / 0":`${u+1} / ${l.length}`})}),a(Fe,{align:"start",className:"w-48",children:l.map((e,i)=>g(se,{onClick:()=>p(e.id),className:"text-xs flex items-center justify-between cursor-pointer",children:[g("span",{className:"flex items-center gap-2 truncate",children:[e.type==="text"?a(gc,{className:"h-3.5 w-3.5 text-muted-foreground"}):a(Xn,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.type==="text"?e.text||"Text":e.imageAssetKey||"Image"]}),g("span",{className:"text-[10px] font-mono text-muted-foreground ml-2",children:["#",i+1]})]},e.id))})]}),a(N,{variant:"outline",size:"icon",className:"h-7 w-7",disabled:l.length<=1,onClick:gt,children:a(qt,{className:"h-4 w-4"})})]}),g("div",{className:"flex items-center gap-1",children:[n&&a(N,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive hover:bg-destructive/10",title:Dt(),onClick:()=>nt(n.id),children:a(Ue,{className:"h-4 w-4"})}),g(De,{modal:!1,children:[a(Ne,{asChild:!0,children:g(N,{size:"sm",className:"h-7 text-xs gap-1",children:[a(Re,{className:"h-3.5 w-3.5"}),fh()]})}),g(Fe,{align:"end",children:[g(se,{onClick:Be,className:"text-xs gap-2 cursor-pointer",children:[a(gc,{className:"h-3.5 w-3.5"}),mh()]}),g(se,{onClick:pt,className:"text-xs gap-2 cursor-pointer",children:[a(Xn,{className:"h-3.5 w-3.5"}),HA()]})]})]})]})]}),a(Ie,{className:"flex-1 min-h-0 p-4",children:n?g("div",{className:"space-y-5 text-xs",children:[g("div",{className:"flex items-center justify-between pb-2 border-b border-border",children:[g("span",{className:"font-semibold text-muted-foreground flex items-center gap-1.5",children:[n.type==="text"?a(gc,{className:"h-4 w-4 text-primary"}):a(Xn,{className:"h-4 w-4 text-primary"}),n.type==="text"?mh():HA()]}),g("span",{className:"text-[10px] font-mono text-muted-foreground",children:["ID: ",n.id.slice(0,6)]})]}),n.type==="text"&&g("div",{className:"space-y-2",children:[a(fe,{className:"text-xs",children:vP()}),a(re,{type:"text",value:n.text,onChange:(e)=>C(n.id,{text:e.target.value}),className:"text-xs h-8"})]}),n.type==="image"&&g("div",{className:"space-y-2",children:[g("div",{className:"flex items-center justify-between",children:[a(fe,{className:"text-xs",children:FI()}),n.imageAssetKey&&g("button",{type:"button",onClick:()=>C(n.id,{imageAssetKey:"",imageAssetUrl:void 0}),className:"text-xs text-muted-foreground hover:text-destructive flex items-center gap-1 font-medium transition-colors cursor-pointer",children:[a(Ke,{className:"w-3.5 h-3.5"}),fu?fu():"Remove"]})]}),a("input",{type:"file",ref:oe,className:"hidden",accept:"image/*",onChange:(e)=>we(e,n.id)}),g("div",{onClick:()=>oe.current?.click(),className:"relative aspect-square w-full rounded-xl border border-dashed border-border flex items-center justify-center cursor-pointer overflow-hidden group shadow-inner bg-muted/20 hover:border-primary/50 hover:bg-muted/40 transition-all p-2",children:[Ee&&a("div",{className:"absolute inset-0 bg-background/70 backdrop-blur-xs flex flex-col items-center justify-center gap-2 z-20",children:g("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-background border rounded-full shadow-lg",children:[a(V,{className:"w-4 h-4 animate-spin text-primary"}),a("span",{className:"text-xs font-semibold",children:gu()})]})}),O[n.id]||n.imageAssetUrl?g(W,{children:[a("img",{src:O[n.id]||n.imageAssetUrl,alt:"Uploaded logo preview",className:"max-w-full max-h-full object-contain transition-transform duration-300 group-hover:scale-105"}),g("div",{className:"absolute inset-0 bg-black/45 opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex flex-col items-center justify-center gap-1 text-white z-10",children:[a(Ho,{className:"w-5 h-5 transform translate-y-1 group-hover:translate-y-0 transition-transform duration-300"}),a("span",{className:"text-xs font-semibold",children:zg()})]})]}):g("div",{className:"flex flex-col items-center gap-1.5 text-center p-3",children:[a("div",{className:"p-2 rounded-full bg-background border shadow-xs group-hover:scale-110 transition-transform duration-300",children:a(Ho,{className:"w-4 h-4 text-muted-foreground"})}),g("div",{children:[a("p",{className:"text-xs font-medium text-foreground",children:lD()}),a("p",{className:"text-[10px] text-muted-foreground mt-0.5 max-w-[150px] mx-auto leading-normal",children:cD()})]})]})]})]}),g("div",{className:"space-y-2",children:[g("div",{className:"flex items-center justify-between",children:[a(fe,{className:"text-xs",children:n.type==="text"?GS():ZI()}),g("span",{className:"font-mono text-[11px] text-muted-foreground",children:[Math.round(n.size*100),"%"]})]}),g("div",{className:"flex items-center gap-3",children:[a(Ss,{min:n.type==="text"?0.01:0.02,max:n.type==="text"?0.12:0.5,step:0.005,value:[n.size],onValueChange:([e])=>C(n.id,{size:e}),className:"flex-1"}),a(re,{type:"number",min:1,max:100,value:Math.round(n.size*100),onChange:(e)=>C(n.id,{size:Math.min(1,Math.max(0.001,Number(e.target.value)/100))}),className:"w-16 h-7 text-xs font-mono text-right"})]})]}),n.type==="text"&&g("div",{className:"space-y-2",children:[g("div",{className:"flex items-center justify-between",children:[a(fe,{className:"text-xs",children:DE()}),a("span",{className:"font-mono text-[11px] text-muted-foreground uppercase",children:n.color})]}),g("div",{className:"flex items-center gap-2",children:[a("input",{type:"color",value:n.color,onChange:(e)=>C(n.id,{color:e.target.value}),className:"w-8 h-8 rounded border border-border cursor-pointer bg-transparent p-0"}),a(re,{type:"text",value:n.color,onChange:(e)=>C(n.id,{color:e.target.value}),className:"flex-1 h-8 text-xs font-mono"})]}),a("div",{className:"flex items-center gap-1.5 pt-1",children:["#FFFFFF","#000000","#999999","#EF4444","#3B82F6","#10B981","#F59E0B"].map((e)=>a("button",{type:"button",onClick:()=>C(n.id,{color:e}),style:{backgroundColor:e},className:"w-5 h-5 rounded-full border border-border hover:scale-110 transition-transform"},e))})]}),g("div",{className:"space-y-2",children:[g("div",{className:"flex items-center justify-between",children:[a(fe,{className:"text-xs",children:rk()}),g("span",{className:"font-mono text-[11px] text-muted-foreground",children:[Math.round(n.opacity*100),"%"]})]}),a(Ss,{min:0,max:1,step:0.01,value:[n.opacity],onValueChange:([e])=>C(n.id,{opacity:e})})]}),g("div",{className:"space-y-2",children:[g("div",{className:"flex items-center justify-between",children:[a(fe,{className:"text-xs",children:uM()}),g("span",{className:"font-mono text-[11px] text-muted-foreground",children:[n.rotation,"°"]})]}),a(Ss,{min:-180,max:180,step:1,value:[n.rotation],onValueChange:([e])=>C(n.id,{rotation:e})}),a("div",{className:"flex items-center gap-1.5 pt-1",children:[-45,-30,0,30,45].map((e)=>g(N,{variant:"outline",size:"sm",className:"h-6 text-[10px] flex-1 px-1 font-mono",onClick:()=>C(n.id,{rotation:e}),children:[e,"°"]},e))})]}),g("div",{className:"space-y-2",children:[g("div",{className:"flex items-center justify-between",children:[a(fe,{className:"text-xs",children:zk()}),g("span",{className:"font-mono text-[11px] text-muted-foreground",children:[Math.round(n.x*100),"%"]})]}),a(Ss,{min:0,max:1,step:0.01,value:[n.x],onValueChange:([e])=>C(n.id,{x:e})})]}),g("div",{className:"space-y-2",children:[g("div",{className:"flex items-center justify-between",children:[a(fe,{className:"text-xs",children:jk()}),g("span",{className:"font-mono text-[11px] text-muted-foreground",children:[Math.round(n.y*100),"%"]})]}),a(Ss,{min:0,max:1,step:0.01,value:[n.y],onValueChange:([e])=>C(n.id,{y:e})})]})]}):g("div",{className:"py-12 text-center text-xs text-muted-foreground space-y-3",children:[a("p",{children:TM()}),g(N,{size:"sm",variant:"outline",onClick:Be,children:[a(Re,{className:"h-3.5 w-3.5 mr-1"}),mh()]})]})})]})]})]})}),a(Se,{open:ge,onOpenChange:K,children:g(xe,{className:"max-w-md",children:[a(ke,{children:a(Ce,{className:"text-sm font-semibold",children:le==="new"?N_():Gy()})}),a("div",{className:"py-3 space-y-4 text-xs",children:le==="new"?g("div",{className:"space-y-2",children:[a(fe,{children:gP()}),a(re,{type:"text",value:ne,onChange:(e)=>U(e.target.value),placeholder:W_(),className:"text-xs"})]}):g("div",{className:"space-y-2",children:[a(fe,{children:O0()}),a("select",{value:H||"",onChange:(e)=>Y(e.target.value),className:"w-full h-9 rounded-md border border-input bg-background px-3 text-xs",children:P.map((e)=>a("option",{value:e.id,children:e.name},e.id))})]})}),g(ot,{children:[a(N,{variant:"outline",size:"sm",className:"text-xs",onClick:()=>K(!1),children:Ge()}),a(N,{size:"sm",className:"text-xs",disabled:Le||Oe,onClick:wt,children:dl()})]})]})})]})}function Pe(...t){return t.filter(Boolean).join(" ")}L();function ut({shareLink:t,viewMode:b,onViewModeChange:f,defaultSortOrder:m,onSortOrderChange:y}){let x=ae(),[D,l]=w(t.password||""),[v,d]=w(t.expireAt?new Date(t.expireAt):void 0),[p,T]=w(!1);S(()=>{l(t.password||"")},[t.password]);let[A,k]=w(t.hasPassword),[ie,de]=w(!!t.expireAt),{data:ce,refetch:ge}=ee({queryKey:["share-watermark",t.id],queryFn:async()=>{let s=await R.api.shares[":shareId"].watermark.$get({param:{shareId:t.id}});if(!s.ok)return null;return await s.json()},refetchInterval:(s)=>(s.state.data?.watermarkStatus||t.watermarkStatus)==="processing"?3000:!1}),K=R.api.shares[":shareId"].watermark.$put,{mutate:le}=X({mutationFn:async()=>{let s=await K({param:{shareId:t.id},json:{enabled:!1}});if(!s.ok)throw Error(ba());return await s.json()},onSuccess:()=>{x.invalidateQueries({queryKey:["shares",t.projectId]}),x.invalidateQueries({queryKey:["share",t.id]}),x.invalidateQueries({queryKey:["share-watermark",t.id]}),B.success(yD())}}),te=ce?.watermarkStatus??t.watermarkStatus??(t.watermarkConfigId?"ready":"disabled"),ne=ce?.watermarkConfig?.config??t.watermarkConfig?.config??null,U=ne!==null&&te!=="disabled",{data:H}=ee({queryKey:["fields",t.projectId],queryFn:async()=>{let s=await R.api.projects[":projectId"].fields.$get({param:{projectId:t.projectId}});if(!s.ok)throw Error(XC());return await s.json()},enabled:!!t.projectId}),Y=R.api.shares[":shareId"].$put,{mutate:_}=X({mutationFn:async(s)=>{let q=await Y({param:{shareId:t.id},json:s});if(!q.ok)throw Error(ba());return await q.json()},onSuccess:()=>{x.invalidateQueries({queryKey:["shares",t.projectId]}),x.invalidateQueries({queryKey:["share",t.id]}),B.success(oc())}}),J=`${window.location.origin}/share/${t.id}`,Z=async(s)=>{if(await ko(s))B.success(cx())},ve=(s)=>{let q=t.fieldVisibility||{},me={...q,[s]:!q[s]};_({fieldVisibility:me})},I="index",z="asc";if(m){let s=m.split(":");I=s[0],z=s[1]||"asc"}return g("div",{className:"flex flex-col h-full bg-background border-l border-border",children:[a("div",{className:"flex-1 overflow-y-auto",children:g("div",{className:"p-4 space-y-6",children:[g("div",{className:"space-y-4",children:[g("div",{className:"flex items-center justify-between",children:[a("h3",{className:"text-sm font-medium",children:eT()}),a(Ve,{checked:!t.isDisabled,onCheckedChange:(s)=>_({isDisabled:!s})})]}),g("div",{className:"relative w-full",children:[a(re,{value:J,readOnly:!0,className:"pr-10 bg-muted/50 text-xs"}),a(N,{variant:"ghost",size:"icon",className:"absolute right-0 top-0 h-full",onClick:()=>Z(J),children:a(zr,{className:"h-4 w-4"})})]})]}),g("div",{className:"space-y-1",children:[a(je,{title:CM(),icon:a(wu,{className:"h-4 w-4"}),children:g("div",{className:"p-3 space-y-4 pt-2",children:[g("div",{className:"space-y-2",children:[g("div",{className:"flex items-center justify-between",children:[a(fe,{className:"text-xs",children:ig()}),a(Ve,{checked:A,onCheckedChange:(s)=>{if(k(s),!s)_({password:null})}})]}),A&&g("div",{className:"flex gap-2 animate-in fade-in slide-in-from-top-1 duration-200",children:[a(re,{type:"text",value:D,onChange:(s)=>l(s.target.value),placeholder:jC(),className:"text-xs"}),a(N,{size:"sm",onClick:()=>_({password:D}),children:mo()})]})]}),g("div",{className:"space-y-2",children:[g("div",{className:"flex items-center justify-between",children:[a(fe,{className:"text-xs",children:KC()}),a(Ve,{checked:ie,onCheckedChange:(s)=>{if(de(s),!s)d(void 0),_({expireAt:null})}})]}),ie&&a("div",{className:"animate-in fade-in slide-in-from-top-1 duration-200",children:a(Ia,{value:v,onChange:(s)=>{d(s),_({expireAt:s?s.toISOString():null})},className:"text-xs"})})]}),g("div",{className:"space-y-2",children:[g("div",{className:"flex items-center justify-between",children:[a(fe,{className:"text-xs",children:nw()}),a(Ve,{checked:t.allowDownload,onCheckedChange:(s)=>_({allowDownload:s})})]}),a("p",{className:"text-xs text-muted-foreground",children:ow()})]}),g("div",{className:"space-y-2 pt-2 border-t border-border/50",children:[g("div",{className:"flex items-center justify-between",children:[a(fe,{className:"text-xs",children:cv()}),a(Ve,{checked:U,disabled:te==="processing",onCheckedChange:(s)=>{if(!s)le();else T(!0)}})]}),U&&te==="processing"&&g("div",{className:"flex items-center gap-2 text-xs text-amber-600 dark:text-amber-400 font-medium py-1 animate-pulse",children:[a(V,{className:"h-3.5 w-3.5 animate-spin"}),a("span",{children:wD()})]}),U&&te!=="processing"&&a(N,{variant:"outline",size:"sm",className:"w-full text-xs gap-1.5 mt-1",onClick:()=>T(!0),children:CC()})]})]})}),a(je,{title:gh(),icon:a(bu,{className:"h-4 w-4"}),children:g("div",{className:"p-3 space-y-3 pt-2 flex gap-2",children:[g(N,{variant:b==="card"?"secondary":"outline",size:"sm",className:"flex-1 gap-2 text-xs",onClick:()=>f("card"),children:[a(Bo,{className:"h-4 w-4"}),bI()]}),g(N,{variant:b==="list"?"secondary":"outline",size:"sm",className:"flex-1 gap-2 text-xs",onClick:()=>f("list"),children:[a(vs,{className:"h-4 w-4"}),rT()]})]})}),a(je,{title:Xl(),icon:a(lt,{className:"h-4 w-4"}),children:a("div",{className:"p-3 space-y-3 pt-2",children:H?.map((s)=>g("div",{className:"flex items-center justify-between",children:[a(fe,{className:"text-xs",children:s.config?.name}),a(Ve,{checked:t.fieldVisibility?.[s.id]??!1,onCheckedChange:()=>ve(s.id)})]},s.id))})}),a(je,{title:pu(),icon:a(Tu,{className:"h-4 w-4"}),children:g("div",{className:"p-3 space-y-4 pt-2",children:[g("div",{className:"space-y-2",children:[a(fe,{className:"text-xs text-muted-foreground",children:Ph()}),g(Ye,{value:I,onValueChange:(s)=>{if(s==="index")y(null);else y(`${s}:${z}`)},children:[a(et,{className:"w-full text-xs h-9",children:a(Xe,{})}),g(tt,{children:[a(be,{value:"index",children:Tg()}),a(be,{value:"name",children:mu()}),a(be,{value:"createdAt",children:kg()}),a(be,{value:"size",children:Mg()})]})]})]}),g("div",{className:"space-y-2",children:[a(fe,{className:"text-xs text-muted-foreground",children:sg()}),g(N,{variant:"outline",className:"w-full justify-between font-normal text-xs h-9",disabled:I==="index",onClick:()=>{y(`${I}:${z==="asc"?"desc":"asc"}`)},children:[a("span",{children:I==="name"?z==="asc"?Hd():Vd():I==="createdAt"?z==="asc"?Gd():Qd():I==="size"?z==="asc"?Og():Rg():z==="asc"?Ah():Sh()}),a(of,{className:"h-4 w-4 opacity-50"})]})]})]})})]})]})}),g("div",{className:"p-4 border-t border-border space-y-2",children:[g(N,{variant:"outline",className:"w-full justify-center",onClick:()=>window.open(J,"_blank"),children:[a(Su,{className:"h-4 w-4 mr-2"}),ok()]}),g(N,{className:"w-full justify-center bg-blue-600 hover:bg-blue-700 text-white",onClick:()=>Z(J),children:[a(zr,{className:"h-4 w-4 mr-2"}),gx()]})]}),a(mt,{open:p,onOpenChange:T,initialConfig:ne,shareId:t.id,onSaveSuccess:()=>{ge(),x.invalidateQueries({queryKey:["share",t.id]}),x.invalidateQueries({queryKey:["shares",t.projectId]})}})]})}function je({title:t,icon:b,children:f}){let[m,y]=w(!1);return g("div",{className:"border-b border-border last:border-0",children:[g("button",{onClick:()=>y(!m),className:"w-full flex items-center justify-between py-3 px-2 hover:bg-muted/50 transition-colors",children:[g("div",{className:"flex items-center gap-3",children:[b,a("span",{className:"text-sm font-medium",children:t})]}),a(qt,{className:_t("h-4 w-4 transition-transform",m&&"rotate-90")})]}),m&&f&&a("div",{className:"animate-in fade-in slide-in-from-top-1 duration-200",children:f})]})}function _t(...t){return t.filter(Boolean).join(" ")}function st({teamId:t,projectId:b,projectName:f,shareId:m,rootFolderId:y}){let x=ae(),{fetchMetadata:D}=Br();S(()=>{if(t)D(t)},[t,D]);let{data:l}=ee({queryKey:["share",m],queryFn:async()=>{let r=await R.api.shares[":shareId"].$get({param:{shareId:m}});if(!r.ok)throw Error(rS());return await r.json()}}),v=l?.rootFolderId,[d,p]=w(null),[T,A]=w([]);S(()=>{if(v)p(v),A([]),P(new Set)},[v,m]);let k=Un((r)=>r.setProjectState),ie=Un((r)=>r.clearProjectState),de=(r)=>{if(r===d)return;if(r===v)p(v),A([]);else{let c=T.findIndex((u)=>u.id===r);if(c!==-1)p(r),A(T.slice(c+1))}P(new Set)},[ce,ge]=w(240),[K,le]=w(360),{shareConfigLeftSidebarCollapsed:te,shareConfigRightSidebarCollapsed:ne}=cr(),U=l?.defaultSortOrder||null,H,Y;if(U){let r=U.split(":");H=r[0],Y=r[1]}let _=l?.viewMode??"card",{data:J,fetchNextPage:Z,hasNextPage:ve,isFetchingNextPage:I,isLoading:z}=Rt({queryKey:["folder-children",t,d,"folder",H,Y],queryFn:async({pageParam:r})=>{let c=await R.api.folders[":folderId"].children.$get({param:{folderId:d},query:{assetType:"folder",after:r,sort:H,order:Y}});if(!c.ok)throw Error(tS());return await c.json()},enabled:!!d,initialPageParam:"",getNextPageParam:(r)=>r.pageInfo?.cursor||void 0}),{data:s,fetchNextPage:q,hasNextPage:me,isFetchingNextPage:Ee,isLoading:ye}=Rt({queryKey:["folder-children",t,d,"file",H,Y],queryFn:async({pageParam:r})=>{let c=await R.api.folders[":folderId"].children.$get({param:{folderId:d},query:{assetType:"file",after:r,sort:H,order:Y}});if(!c.ok)throw Error(eS());return await c.json()},enabled:!!d,initialPageParam:"",getNextPageParam:(r)=>r.pageInfo?.cursor||void 0}),O=Q(()=>J?.pages.flatMap((r)=>r.data??[])??[],[J]),he=Q(()=>s?.pages.flatMap((r)=>r.data??[])??[],[s]);S(()=>{if(l)k({teamId:t,projectId:b,projectName:f,ancestorFolders:T,currentAsset:{name:d===v?l.name:O.find((r)=>r.id===d)?.name||l.name,type:"folder"},isRootFolder:!1,shareId:m,onFolderClick:de});return()=>ie()},[t,b,f,T,d,v,l,m,O,k,ie]);let[oe,ue]=w(null),[we,P]=w(new Set),_e=()=>{P(new Set),ue(null)},{dragState:pe,handleDragStart:Ae,handleDragEnd:We}=Cu({teamId:t,projectId:b,assetId:d||"",folders:O,files:he,selectedIds:we,onClearSelection:_e}),ze=R.api.shares[":shareId"].assets[":assetId"].$delete,{mutate:Le}=X({mutationFn:async(r)=>{if(!(await ze({param:{shareId:m,assetId:r}})).ok)throw Error(nS())},onSuccess:()=>{x.invalidateQueries({queryKey:["folder-children",t,d]}),B.success(YR())}}),$e=R.api.shares[":shareId"].$put,{mutate:Me}=X({mutationFn:async(r)=>{let c=await $e({param:{shareId:m},json:r});if(!c.ok)throw Error(ba());return await c.json()},onSuccess:()=>{x.invalidateQueries({queryKey:["share",m]}),B.success(oc())}}),Oe=(r)=>{if(r.type==="folder"||r.targetType==="folder"){let c=d===v?l?.name||"":O.find((u)=>u.id===d)?.name||to();A((u)=>[{id:d,name:c},...u]),p(r.id),P(new Set)}};if(!l)return a("div",{children:qp()});return g(So,{modifiers:[yl.configure({anchor:{x:0,y:0}})],sensors:[ro.configure({activationConstraints:[new ln.Distance({value:10})]})],onDragStart:Ae,onDragEnd:We,children:[a("div",{className:"flex flex-1 flex-col bg-background min-h-0",children:g("div",{className:"flex flex-1 overflow-hidden relative",children:[!te&&g(W,{children:[a("div",{className:"bg-background",style:{width:ce},children:a(Qr,{teamId:t,projectId:b,projectName:f,rootFolderId:y,dragState:pe})}),a(en,{onResize:(r)=>ge((c)=>Math.max(180,Math.min(400,c+r)))})]}),a(Oa,{teamId:t,projectId:b,assetId:d||"",folders:O,files:he,selectedItem:oe,selectedIds:we,onItemSelect:(r,c)=>{if(c.metaKey||c.ctrlKey){let u=new Set(we);if(u.has(r.id)){if(u.delete(r.id),P(u),oe?.id===r.id){let n=[...O,...he].find((Be)=>u.has(Be.id));ue(n||null)}}else u.add(r.id),P(u),ue(r)}else P(new Set([r.id])),ue(r)},onItemDoubleClick:Oe,onSaveField:()=>{},displayStyle:_,onClearSelection:_e,fetchNextFoldersPage:Z,hasNextFoldersPage:ve,isFetchingNextFoldersPage:I,fetchNextFilesPage:q,hasNextFilesPage:me,isFetchingNextFilesPage:Ee,isLoading:z||ye,filterConditions:[],onFilterChange:()=>{},dragState:pe,isShareView:!0,onRemoveFromShare:(r)=>{r.forEach((c)=>Le(c.id))},fieldVisibility:l.fieldVisibility}),!ne&&g(W,{children:[a(en,{onResize:(r)=>le((c)=>Math.max(240,Math.min(600,c-r)))}),a("div",{style:{width:K},className:"flex-shrink-0 h-full",children:a(ut,{shareLink:l,viewMode:_,onViewModeChange:(r)=>Me({viewMode:r}),defaultSortOrder:U,onSortOrderChange:(r)=>Me({defaultSortOrder:r})})})]})]})}),a(Wd,{children:pe?.isActive?a("div",{className:"flex items-center gap-2 rounded-md bg-popover px-3 py-2 text-sm font-medium shadow-md",children:s1({count:pe.itemCount})}):null})]})}L();function It(){let{projectId:t,shareId:b}=Ct.useParams(),{teamId:f,ensureTeamIdForProject:m}=Ft();S(()=>{m(t)},[t,m]);let{data:y}=yr(tA(t)),x=y?.rootFolder,{data:D}=ee({queryKey:["folders",x],queryFn:async()=>{let l=await R.api.folders[":folderId"].$get({param:{folderId:x}});if(!l.ok)throw Error("Failed to fetch folder");return await l.json()},enabled:!!x});if(!f||!x||!D)return a($t,{});return a(st,{teamId:f,projectId:t,projectName:y.name??"",shareId:b,rootFolderId:x})}var Ct=Je("/projects/$projectId/shares/$shareId")({component:It});export{Ct as Route};
|