@opentiny/next-remoter 0.4.1 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -38,11 +38,11 @@ ${B}`,A++;break;case"id":g=B.includes("\0")?void 0:B;break;case"retry":/^\d+$/.t
38
38
 
39
39
  Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const E of this.seen.entries()){const A=E[1];if(r===E[0]){m(E);continue}if(c.external){const T=c.external.registry.get(E[0])?.id;if(r!==E[0]&&T){m(E);continue}}if(this.metadataRegistry.get(E[0])?.id){m(E);continue}if(A.cycle){m(E);continue}if(A.count>1&&c.reused==="ref"){m(E);continue}}const x=(E,A)=>{const D=this.seen.get(E),T=D.def??D.schema,S={...T};if(D.ref===null)return;const P=D.ref;if(D.ref=null,P){x(P,A);const M=this.seen.get(P).schema;M.$ref&&A.target==="draft-7"?(T.allOf=T.allOf??[],T.allOf.push(M)):(Object.assign(T,M),Object.assign(T,S))}D.isParent||this.override({zodSchema:E,jsonSchema:T,path:D.path??[]})};for(const E of[...this.seen.entries()].reverse())x(E[0],{target:this.target});const v={};if(this.target==="draft-2020-12"?v.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?v.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),c.external?.uri){const E=c.external.registry.get(r)?.id;if(!E)throw new Error("Schema is missing an `id` property");v.$id=c.external.uri(E)}Object.assign(v,d.def);const g=c.external?.defs??{};for(const E of this.seen.entries()){const A=E[1];A.def&&A.defId&&(g[A.defId]=A.def)}c.external||Object.keys(g).length>0&&(this.target==="draft-2020-12"?v.$defs=g:v.definitions=g);try{return JSON.parse(JSON.stringify(v))}catch{throw new Error("Error converting schema to JSON.")}}}function Uf(t,r){if(t instanceof yc){const c=new Zs(r),d={};for(const x of t._idmap.entries()){const[v,g]=x;c.process(g)}const f={},m={registry:t,uri:r?.uri,defs:d};for(const x of t._idmap.entries()){const[v,g]=x;f[v]=c.emit(g,{...r,external:m})}if(Object.keys(d).length>0){const x=c.target==="draft-2020-12"?"$defs":"definitions";f.__shared={[x]:d}}return{schemas:f}}const i=new Zs(r);return i.process(t),i.emit(t,r)}function Lt(t,r){const i=r??{seen:new Set};if(i.seen.has(t))return!1;i.seen.add(t);const d=t._zod.def;switch(d.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Lt(d.element,i);case"object":{for(const f in d.shape)if(Lt(d.shape[f],i))return!0;return!1}case"union":{for(const f of d.options)if(Lt(f,i))return!0;return!1}case"intersection":return Lt(d.left,i)||Lt(d.right,i);case"tuple":{for(const f of d.items)if(Lt(f,i))return!0;return!!(d.rest&&Lt(d.rest,i))}case"record":return Lt(d.keyType,i)||Lt(d.valueType,i);case"map":return Lt(d.keyType,i)||Lt(d.valueType,i);case"set":return Lt(d.valueType,i);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Lt(d.innerType,i);case"lazy":return Lt(d.getter(),i);case"default":return Lt(d.innerType,i);case"prefault":return Lt(d.innerType,i);case"custom":return!1;case"transform":return!0;case"pipe":return Lt(d.in,i)||Lt(d.out,i);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${d.type}`)}const zf=oe("ZodISODateTime",(t,r)=>{a0.init(t,r),It.init(t,r)});function Vf(t){return mf(zf,t)}const Zf=oe("ZodISODate",(t,r)=>{l0.init(t,r),It.init(t,r)});function $f(t){return gf(Zf,t)}const jf=oe("ZodISOTime",(t,r)=>{c0.init(t,r),It.init(t,r)});function Hf(t){return xf(jf,t)}const Wf=oe("ZodISODuration",(t,r)=>{u0.init(t,r),It.init(t,r)});function Gf(t){return yf(Wf,t)}const qf=(t,r)=>{ic.init(t,r),t.name="ZodError",Object.defineProperties(t,{format:{value:i=>r1(t,i)},flatten:{value:i=>n1(t,i)},addIssue:{value:i=>t.issues.push(i)},addIssues:{value:i=>t.issues.push(...i)},isEmpty:{get(){return t.issues.length===0}}})},Uo=oe("ZodError",qf,{Parent:Error}),Xf=o1(Uo),Yf=i1(Uo),Kf=ac(Uo),vc=lc(Uo),_t=oe("ZodType",(t,r)=>(ht.init(t,r),t.def=r,Object.defineProperty(t,"_def",{value:r}),t.check=(...i)=>t.clone({...r,checks:[...r.checks??[],...i.map(c=>typeof c=="function"?{_zod:{check:c,def:{check:"custom"},onattach:[]}}:c)]}),t.clone=(i,c)=>gr(t,i,c),t.brand=()=>t,t.register=((i,c)=>(i.add(t,c),t)),t.parse=(i,c)=>Xf(t,i,c,{callee:t.parse}),t.safeParse=(i,c)=>Kf(t,i,c),t.parseAsync=async(i,c)=>Yf(t,i,c,{callee:t.parseAsync}),t.safeParseAsync=async(i,c)=>vc(t,i,c),t.spa=t.safeParseAsync,t.refine=(i,c)=>t.check(Wh(i,c)),t.superRefine=i=>t.check(Gh(i)),t.overwrite=i=>t.check(so(i)),t.optional=()=>Hs(t),t.nullable=()=>Ws(t),t.nullish=()=>Hs(Ws(t)),t.nonoptional=i=>Lh(t,i),t.array=()=>ue(t),t.or=i=>st([t,i]),t.and=i=>Sh(t,i),t.transform=i=>Gs(t,kh(i)),t.default=i=>Dh(t,i),t.prefault=i=>Bh(t,i),t.catch=i=>Uh(t,i),t.pipe=i=>Gs(t,i),t.readonly=()=>Zh(t),t.describe=i=>{const c=t.clone();return Gr.add(c,{description:i}),c},Object.defineProperty(t,"description",{get(){return Gr.get(t)?.description},configurable:!0}),t.meta=(...i)=>{if(i.length===0)return Gr.get(t);const c=t.clone();return Gr.add(c,i[0]),c},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Cc=oe("_ZodString",(t,r)=>{ji.init(t,r),_t.init(t,r);const i=t._zod.bag;t.format=i.format??null,t.minLength=i.minimum??null,t.maxLength=i.maximum??null,t.regex=(...c)=>t.check(Sf(...c)),t.includes=(...c)=>t.check(Of(...c)),t.startsWith=(...c)=>t.check(kf(...c)),t.endsWith=(...c)=>t.check(Rf(...c)),t.min=(...c)=>t.check(Mo(...c)),t.max=(...c)=>t.check(wc(...c)),t.length=(...c)=>t.check(_c(...c)),t.nonempty=(...c)=>t.check(Mo(1,...c)),t.lowercase=c=>t.check(Tf(c)),t.uppercase=c=>t.check(Nf(c)),t.trim=()=>t.check(Df()),t.normalize=(...c)=>t.check(Mf(...c)),t.toLowerCase=()=>t.check(Pf()),t.toUpperCase=()=>t.check(Bf())}),Jf=oe("ZodString",(t,r)=>{ji.init(t,r),Cc.init(t,r),t.email=i=>t.check(G0(Qf,i)),t.url=i=>t.check(J0(eh,i)),t.jwt=i=>t.check(pf(mh,i)),t.emoji=i=>t.check(Q0(th,i)),t.guid=i=>t.check(Fs($s,i)),t.uuid=i=>t.check(q0(Co,i)),t.uuidv4=i=>t.check(X0(Co,i)),t.uuidv6=i=>t.check(Y0(Co,i)),t.uuidv7=i=>t.check(K0(Co,i)),t.nanoid=i=>t.check(ef(nh,i)),t.guid=i=>t.check(Fs($s,i)),t.cuid=i=>t.check(tf(rh,i)),t.cuid2=i=>t.check(nf(oh,i)),t.ulid=i=>t.check(rf(ih,i)),t.base64=i=>t.check(df(fh,i)),t.base64url=i=>t.check(ff(hh,i)),t.xid=i=>t.check(of(sh,i)),t.ksuid=i=>t.check(sf(ah,i)),t.ipv4=i=>t.check(af(lh,i)),t.ipv6=i=>t.check(lf(ch,i)),t.cidrv4=i=>t.check(cf(uh,i)),t.cidrv6=i=>t.check(uf(dh,i)),t.e164=i=>t.check(hf(ph,i)),t.datetime=i=>t.check(Vf(i)),t.date=i=>t.check($f(i)),t.time=i=>t.check(Hf(i)),t.duration=i=>t.check(Gf(i))});function w(t){return W0(Jf,t)}const It=oe("ZodStringFormat",(t,r)=>{bt.init(t,r),Cc.init(t,r)}),Qf=oe("ZodEmail",(t,r)=>{J1.init(t,r),It.init(t,r)}),$s=oe("ZodGUID",(t,r)=>{Y1.init(t,r),It.init(t,r)}),Co=oe("ZodUUID",(t,r)=>{K1.init(t,r),It.init(t,r)}),eh=oe("ZodURL",(t,r)=>{Q1.init(t,r),It.init(t,r)}),th=oe("ZodEmoji",(t,r)=>{e0.init(t,r),It.init(t,r)}),nh=oe("ZodNanoID",(t,r)=>{t0.init(t,r),It.init(t,r)}),rh=oe("ZodCUID",(t,r)=>{n0.init(t,r),It.init(t,r)}),oh=oe("ZodCUID2",(t,r)=>{r0.init(t,r),It.init(t,r)}),ih=oe("ZodULID",(t,r)=>{o0.init(t,r),It.init(t,r)}),sh=oe("ZodXID",(t,r)=>{i0.init(t,r),It.init(t,r)}),ah=oe("ZodKSUID",(t,r)=>{s0.init(t,r),It.init(t,r)}),lh=oe("ZodIPv4",(t,r)=>{d0.init(t,r),It.init(t,r)}),ch=oe("ZodIPv6",(t,r)=>{f0.init(t,r),It.init(t,r)}),uh=oe("ZodCIDRv4",(t,r)=>{h0.init(t,r),It.init(t,r)}),dh=oe("ZodCIDRv6",(t,r)=>{p0.init(t,r),It.init(t,r)}),fh=oe("ZodBase64",(t,r)=>{m0.init(t,r),It.init(t,r)}),hh=oe("ZodBase64URL",(t,r)=>{x0.init(t,r),It.init(t,r)}),ph=oe("ZodE164",(t,r)=>{y0.init(t,r),It.init(t,r)}),mh=oe("ZodJWT",(t,r)=>{_0.init(t,r),It.init(t,r)}),Hi=oe("ZodNumber",(t,r)=>{gc.init(t,r),_t.init(t,r),t.gt=(c,d)=>t.check(zs(c,d)),t.gte=(c,d)=>t.check(ui(c,d)),t.min=(c,d)=>t.check(ui(c,d)),t.lt=(c,d)=>t.check(Us(c,d)),t.lte=(c,d)=>t.check(ci(c,d)),t.max=(c,d)=>t.check(ci(c,d)),t.int=c=>t.check(js(c)),t.safe=c=>t.check(js(c)),t.positive=c=>t.check(zs(0,c)),t.nonnegative=c=>t.check(ui(0,c)),t.negative=c=>t.check(Us(0,c)),t.nonpositive=c=>t.check(ci(0,c)),t.multipleOf=(c,d)=>t.check(Vs(c,d)),t.step=(c,d)=>t.check(Vs(c,d)),t.finite=()=>t;const i=t._zod.bag;t.minValue=Math.max(i.minimum??Number.NEGATIVE_INFINITY,i.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(i.maximum??Number.POSITIVE_INFINITY,i.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(i.format??"").includes("int")||Number.isSafeInteger(i.multipleOf??.5),t.isFinite=!0,t.format=i.format??null});function j(t){return wf(Hi,t)}const gh=oe("ZodNumberFormat",(t,r)=>{v0.init(t,r),Hi.init(t,r)});function js(t){return vf(gh,t)}const xh=oe("ZodBoolean",(t,r)=>{C0.init(t,r),_t.init(t,r)});function Mt(t){return Cf(xh,t)}const yh=oe("ZodNull",(t,r)=>{b0.init(t,r),_t.init(t,r)});function bc(t){return bf(yh,t)}const wh=oe("ZodAny",(t,r)=>{A0.init(t,r),_t.init(t,r)});function xr(){return Af(wh)}const _h=oe("ZodUnknown",(t,r)=>{E0.init(t,r),_t.init(t,r)});function Cn(){return Ef(_h)}const vh=oe("ZodNever",(t,r)=>{I0.init(t,r),_t.init(t,r)});function Ch(t){return If(vh,t)}const bh=oe("ZodArray",(t,r)=>{S0.init(t,r),_t.init(t,r),t.element=r.element,t.min=(i,c)=>t.check(Mo(i,c)),t.nonempty=i=>t.check(Mo(1,i)),t.max=(i,c)=>t.check(wc(i,c)),t.length=(i,c)=>t.check(_c(i,c)),t.unwrap=()=>t.element});function ue(t,r){return Lf(bh,t,r)}const Ah=oe("ZodObject",(t,r)=>{T0.init(t,r),_t.init(t,r),lt(t,"shape",()=>r.shape),t.keyof=()=>Ae(Object.keys(t._zod.def.shape)),t.catchall=i=>t.clone({...t._zod.def,catchall:i}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Cn()}),t.loose=()=>t.clone({...t._zod.def,catchall:Cn()}),t.strict=()=>t.clone({...t._zod.def,catchall:Ch()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=i=>Jd(t,i),t.merge=i=>Qd(t,i),t.pick=i=>Yd(t,i),t.omit=i=>Kd(t,i),t.partial=(...i)=>e1(Ec,t,i[0]),t.required=(...i)=>t1(Ic,t,i[0])});function N(t,r){const i={type:"object",get shape(){return Zi(this,"shape",{...t}),this.shape},...Ie(r)};return new Ah(i)}const Ac=oe("ZodUnion",(t,r)=>{xc.init(t,r),_t.init(t,r),t.options=r.options});function st(t,r){return new Ac({type:"union",options:t,...Ie(r)})}const Eh=oe("ZodDiscriminatedUnion",(t,r)=>{Ac.init(t,r),N0.init(t,r)});function mt(t,r,i){return new Eh({type:"union",options:r,discriminator:t,...Ie(i)})}const Ih=oe("ZodIntersection",(t,r)=>{O0.init(t,r),_t.init(t,r)});function Sh(t,r){return new Ih({type:"intersection",left:t,right:r})}const Th=oe("ZodRecord",(t,r)=>{k0.init(t,r),_t.init(t,r),t.keyType=r.keyType,t.valueType=r.valueType});function wt(t,r,i){return new Th({type:"record",keyType:t,valueType:r,...Ie(i)})}const Ai=oe("ZodEnum",(t,r)=>{R0.init(t,r),_t.init(t,r),t.enum=r.entries,t.options=Object.values(r.entries);const i=new Set(Object.keys(r.entries));t.extract=(c,d)=>{const f={};for(const m of c)if(i.has(m))f[m]=r.entries[m];else throw new Error(`Key ${m} not found in enum`);return new Ai({...r,checks:[],...Ie(d),entries:f})},t.exclude=(c,d)=>{const f={...r.entries};for(const m of c)if(i.has(m))delete f[m];else throw new Error(`Key ${m} not found in enum`);return new Ai({...r,checks:[],...Ie(d),entries:f})}});function Ae(t,r){const i=Array.isArray(t)?Object.fromEntries(t.map(c=>[c,c])):t;return new Ai({type:"enum",entries:i,...Ie(r)})}const Nh=oe("ZodLiteral",(t,r)=>{M0.init(t,r),_t.init(t,r),t.values=new Set(r.values),Object.defineProperty(t,"value",{get(){if(r.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return r.values[0]}})});function Y(t,r){return new Nh({type:"literal",values:Array.isArray(t)?t:[t],...Ie(r)})}const Oh=oe("ZodTransform",(t,r)=>{D0.init(t,r),_t.init(t,r),t._zod.parse=(i,c)=>{i.addIssue=f=>{if(typeof f=="string")i.issues.push(eo(f,i.value,r));else{const m=f;m.fatal&&(m.continue=!1),m.code??(m.code="custom"),m.input??(m.input=i.value),m.inst??(m.inst=t),m.continue??(m.continue=!0),i.issues.push(eo(m))}};const d=r.transform(i.value,i);return d instanceof Promise?d.then(f=>(i.value=f,i)):(i.value=d,i)}});function kh(t){return new Oh({type:"transform",transform:t})}const Ec=oe("ZodOptional",(t,r)=>{P0.init(t,r),_t.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Hs(t){return new Ec({type:"optional",innerType:t})}const Rh=oe("ZodNullable",(t,r)=>{B0.init(t,r),_t.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Ws(t){return new Rh({type:"nullable",innerType:t})}const Mh=oe("ZodDefault",(t,r)=>{L0.init(t,r),_t.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Dh(t,r){return new Mh({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():r}})}const Ph=oe("ZodPrefault",(t,r)=>{F0.init(t,r),_t.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Bh(t,r){return new Ph({type:"prefault",innerType:t,get defaultValue(){return typeof r=="function"?r():r}})}const Ic=oe("ZodNonOptional",(t,r)=>{U0.init(t,r),_t.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Lh(t,r){return new Ic({type:"nonoptional",innerType:t,...Ie(r)})}const Fh=oe("ZodCatch",(t,r)=>{z0.init(t,r),_t.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Uh(t,r){return new Fh({type:"catch",innerType:t,catchValue:typeof r=="function"?r:()=>r})}const zh=oe("ZodPipe",(t,r)=>{V0.init(t,r),_t.init(t,r),t.in=r.in,t.out=r.out});function Gs(t,r){return new zh({type:"pipe",in:t,out:r})}const Vh=oe("ZodReadonly",(t,r)=>{Z0.init(t,r),_t.init(t,r)});function Zh(t){return new Vh({type:"readonly",innerType:t})}const $h=oe("ZodLazy",(t,r)=>{$0.init(t,r),_t.init(t,r),t.unwrap=()=>t._zod.def.getter()});function Wi(t){return new $h({type:"lazy",getter:t})}const jh=oe("ZodCustom",(t,r)=>{j0.init(t,r),_t.init(t,r)});function Hh(t){const r=new on({check:"custom"});return r._zod.check=t,r}function Wh(t,r={}){return Ff(jh,t,r)}function Gh(t){const r=Hh(i=>(i.addIssue=c=>{if(typeof c=="string")i.issues.push(eo(c,i.value,r._zod.def));else{const d=c;d.fatal&&(d.continue=!1),d.code??(d.code="custom"),d.input??(d.input=i.value),d.inst??(d.inst=r),d.continue??(d.continue=!r._zod.def.abort),i.issues.push(eo(d))}},t(i.value,i)));return r}function qh(t){return _f(Hi,t)}var je;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(je||(je={}));function qs(...t){return t.reduce((r,i)=>({...r,...i??{}}),{})}function zo(t){return Object.fromEntries([...t.headers])}var Xh=({prefix:t,size:r=16,alphabet:i="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:c="-"}={})=>{const d=()=>{const f=i.length,m=new Array(r);for(let x=0;x<r;x++)m[x]=i[Math.random()*f|0];return m.join("")};if(t==null)return d;if(i.includes(c))throw new Dl({argument:"separator",message:`The separator "${c}" must not be part of the alphabet "${i}".`});return()=>`${t}${c}${d()}`},bo=Xh();function Ei(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var Yh=["fetch failed","failed to fetch"];function Kh({error:t,url:r,requestBodyValues:i}){if(Ei(t))return t;if(t instanceof TypeError&&Yh.includes(t.message.toLowerCase())){const c=t.cause;if(c!=null)return new Vn({message:`Cannot connect to API: ${c.message}`,cause:c,url:r,requestBodyValues:i,isRetryable:!0})}return t}function Jh(t=globalThis){var r,i,c;return t.window?"runtime/browser":(r=t.navigator)!=null&&r.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(c=(i=t.process)==null?void 0:i.versions)!=null&&c.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function Qh(t){if(t==null)return{};const r={};if(t instanceof Headers)t.forEach((i,c)=>{r[c.toLowerCase()]=i});else{Array.isArray(t)||(t=Object.entries(t));for(const[i,c]of t)c!=null&&(r[i.toLowerCase()]=c)}return r}function Sc(t,...r){const i=new Headers(Qh(t)),c=i.get("user-agent")||"";return i.set("user-agent",[c,...r].filter(Boolean).join(" ")),Object.fromEntries(i.entries())}var ep="3.0.18";function tp({apiKey:t,environmentVariableName:r,apiKeyParameterName:i="apiKey",description:c}){if(typeof t=="string")return t;if(t!=null)throw new wo({message:`${c} API key must be a string.`});if(typeof process>"u")throw new wo({message:`${c} API key is missing. Pass it using the '${i}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[r],t==null)throw new wo({message:`${c} API key is missing. Pass it using the '${i}' parameter or the ${r} environment variable.`});if(typeof t!="string")throw new wo({message:`${c} API key must be a string. The value of the ${r} environment variable is not a string.`});return t}var np=/"__proto__"\s*:/,rp=/"constructor"\s*:/;function Xs(t){const r=JSON.parse(t);return r===null||typeof r!="object"||np.test(t)===!1&&rp.test(t)===!1?r:op(r)}function op(t){let r=[t];for(;r.length;){const i=r;r=[];for(const c of i){if(Object.prototype.hasOwnProperty.call(c,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(c,"constructor")&&Object.prototype.hasOwnProperty.call(c.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const d in c){const f=c[d];f&&typeof f=="object"&&r.push(f)}}}return t}function Gi(t){const{stackTraceLimit:r}=Error;try{Error.stackTraceLimit=0}catch{return Xs(t)}try{return Xs(t)}finally{Error.stackTraceLimit=r}}var Ii=Symbol.for("vercel.ai.validator");function ip(t){return{[Ii]:!0,validate:t}}function sp(t){return typeof t=="object"&&t!==null&&Ii in t&&t[Ii]===!0&&"validate"in t}function ap(t){return sp(t)?t:typeof t=="function"?t():lp(t)}function lp(t){return ip(async r=>{const i=await t["~standard"].validate(r);return i.issues==null?{success:!0,value:i.value}:{success:!1,error:new Jr({value:r,cause:i.issues})}})}async function cp({value:t,schema:r}){const i=await to({value:t,schema:r});if(!i.success)throw Jr.wrap({value:t,cause:i.error});return i.value}async function to({value:t,schema:r}){const i=ap(r);try{if(i.validate==null)return{success:!0,value:t,rawValue:t};const c=await i.validate(t);return c.success?{success:!0,value:c.value,rawValue:t}:{success:!1,error:Jr.wrap({value:t,cause:c.error}),rawValue:t}}catch(c){return{success:!1,error:Jr.wrap({value:t,cause:c}),rawValue:t}}}async function up({text:t,schema:r}){try{const i=Gi(t);return r==null?i:cp({value:i,schema:r})}catch(i){throw Oo.isInstance(i)||Jr.isInstance(i)?i:new Oo({text:t,cause:i})}}async function Tc({text:t,schema:r}){try{const i=Gi(t);return r==null?{success:!0,value:i,rawValue:i}:await to({value:i,schema:r})}catch(i){return{success:!1,error:Oo.isInstance(i)?i:new Oo({text:t,cause:i}),rawValue:void 0}}}function Ys(t){try{return Gi(t),!0}catch{return!1}}function dp({stream:t,schema:r}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new ec).pipeThrough(new TransformStream({async transform({data:i},c){i!=="[DONE]"&&c.enqueue(await Tc({text:i,schema:r}))}}))}async function Ks({provider:t,providerOptions:r,schema:i}){if(r?.[t]==null)return;const c=await to({value:r[t],schema:i});if(!c.success)throw new Dl({argument:"providerOptions",message:`invalid ${t} provider options`,cause:c.error});return c.value}var fp=()=>globalThis.fetch,Js=async({url:t,headers:r,body:i,failedResponseHandler:c,successfulResponseHandler:d,abortSignal:f,fetch:m})=>hp({url:t,headers:{"Content-Type":"application/json",...r},body:{content:JSON.stringify(i),values:i},failedResponseHandler:c,successfulResponseHandler:d,abortSignal:f,fetch:m}),hp=async({url:t,headers:r={},body:i,successfulResponseHandler:c,failedResponseHandler:d,abortSignal:f,fetch:m=fp()})=>{try{const x=await m(t,{method:"POST",headers:Sc(r,`ai-sdk/provider-utils/${ep}`,Jh()),body:i.content,signal:f}),v=zo(x);if(!x.ok){let g;try{g=await d({response:x,url:t,requestBodyValues:i.values})}catch(E){throw Ei(E)||Vn.isInstance(E)?E:new Vn({message:"Failed to process error response",cause:E,statusCode:x.status,url:t,responseHeaders:v,requestBodyValues:i.values})}throw g.value}try{return await c({response:x,url:t,requestBodyValues:i.values})}catch(g){throw g instanceof Error&&(Ei(g)||Vn.isInstance(g))?g:new Vn({message:"Failed to process successful response",cause:g,statusCode:x.status,url:t,responseHeaders:v,requestBodyValues:i.values})}}catch(x){throw Kh({error:x,url:t,requestBodyValues:i.values})}},pp=({errorSchema:t,errorToMessage:r,isRetryable:i})=>async({response:c,url:d,requestBodyValues:f})=>{const m=await c.text(),x=zo(c);if(m.trim()==="")return{responseHeaders:x,value:new Vn({message:c.statusText,url:d,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,isRetryable:i?.(c)})};try{const v=await up({text:m,schema:t});return{responseHeaders:x,value:new Vn({message:r(v),url:d,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,data:v,isRetryable:i?.(c,v)})}}catch{return{responseHeaders:x,value:new Vn({message:c.statusText,url:d,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,isRetryable:i?.(c)})}}},mp=t=>async({response:r})=>{const i=zo(r);if(r.body==null)throw new Md({});return{responseHeaders:i,value:dp({stream:r.body,schema:t})}},gp=t=>async({response:r,url:i,requestBodyValues:c})=>{const d=await r.text(),f=await Tc({text:d,schema:t}),m=zo(r);if(!f.success)throw new Vn({message:"Invalid JSON response",cause:f.error,statusCode:r.status,responseHeaders:m,responseBody:d,url:i,requestBodyValues:c});return{responseHeaders:m,value:f.value,rawValue:f.rawValue}};new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var{btoa:xp}=globalThis;function yp(t){let r="";for(let i=0;i<t.length;i++)r+=String.fromCodePoint(t[i]);return xp(r)}function wp(t){return t instanceof Uint8Array?yp(t):t}function _p(t){return t?.replace(/\/$/,"")}function $r(t){var r,i;return(i=(r=t?.providerOptions)==null?void 0:r.openaiCompatible)!=null?i:{}}function vp(t){const r=[];for(const{role:i,content:c,...d}of t){const f=$r({...d});switch(i){case"system":{r.push({role:"system",content:c,...f});break}case"user":{if(c.length===1&&c[0].type==="text"){r.push({role:"user",content:c[0].text,...$r(c[0])});break}r.push({role:"user",content:c.map(m=>{const x=$r(m);switch(m.type){case"text":return{type:"text",text:m.text,...x};case"file":if(m.mediaType.startsWith("image/")){const v=m.mediaType==="image/*"?"image/jpeg":m.mediaType;return{type:"image_url",image_url:{url:m.data instanceof URL?m.data.toString():`data:${v};base64,${wp(m.data)}`},...x}}else throw new Ql({functionality:`file part media type ${m.mediaType}`})}}),...f});break}case"assistant":{let m="";const x=[];for(const v of c){const g=$r(v);switch(v.type){case"text":{m+=v.text;break}case"tool-call":{x.push({id:v.toolCallId,type:"function",function:{name:v.toolName,arguments:JSON.stringify(v.input)},...g});break}}}r.push({role:"assistant",content:m,tool_calls:x.length>0?x:void 0,...f});break}case"tool":{for(const m of c){const x=m.output;let v;switch(x.type){case"text":case"error-text":v=x.value;break;case"content":case"json":case"error-json":v=JSON.stringify(x.value);break}const g=$r(m);r.push({role:"tool",tool_call_id:m.toolCallId,content:v,...g})}break}default:{const m=i;throw new Error(`Unsupported role: ${m}`)}}}return r}function Qs({id:t,model:r,created:i}){return{id:t??void 0,modelId:r??void 0,timestamp:i!=null?new Date(i*1e3):void 0}}function ea(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var di=N({user:w().optional(),reasoningEffort:w().optional(),textVerbosity:w().optional()}),Cp=N({error:N({message:w(),type:w().nullish(),param:xr().nullish(),code:st([w(),j()]).nullish()})}),bp={errorSchema:Cp,errorToMessage:t=>t.error.message};function Ap({tools:t,toolChoice:r}){t=t?.length?t:void 0;const i=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i};const c=[];for(const f of t)f.type==="provider-defined"?i.push({type:"unsupported-tool",tool:f}):c.push({type:"function",function:{name:f.name,description:f.description,parameters:f.inputSchema}});if(r==null)return{tools:c,toolChoice:void 0,toolWarnings:i};const d=r.type;switch(d){case"auto":case"none":case"required":return{tools:c,toolChoice:d,toolWarnings:i};case"tool":return{tools:c,toolChoice:{type:"function",function:{name:r.toolName}},toolWarnings:i};default:{const f=d;throw new Ql({functionality:`tool choice type: ${f}`})}}}var Ep=class{constructor(t,r){this.specificationVersion="v2";var i,c;this.modelId=t,this.config=r;const d=(i=r.errorStructure)!=null?i:bp;this.chunkSchema=Sp(d.errorSchema),this.failedResponseHandler=pp(d),this.supportsStructuredOutputs=(c=r.supportsStructuredOutputs)!=null?c:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,r,i;return(i=(r=(t=this.config).supportedUrls)==null?void 0:r.call(t))!=null?i:{}}async getArgs({prompt:t,maxOutputTokens:r,temperature:i,topP:c,topK:d,frequencyPenalty:f,presencePenalty:m,providerOptions:x,stopSequences:v,responseFormat:g,seed:E,toolChoice:A,tools:D}){var T,S,P,M;const ee=[],$=Object.assign((T=await Ks({provider:"openai-compatible",providerOptions:x,schema:di}))!=null?T:{},(S=await Ks({provider:this.providerOptionsName,providerOptions:x,schema:di}))!=null?S:{});d!=null&&ee.push({type:"unsupported-setting",setting:"topK"}),g?.type==="json"&&g.schema!=null&&!this.supportsStructuredOutputs&&ee.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:F,toolChoice:re,toolWarnings:Z}=Ap({tools:D,toolChoice:A});return{args:{model:this.modelId,user:$.user,max_tokens:r,temperature:i,top_p:c,frequency_penalty:f,presence_penalty:m,response_format:g?.type==="json"?this.supportsStructuredOutputs===!0&&g.schema!=null?{type:"json_schema",json_schema:{schema:g.schema,name:(P=g.name)!=null?P:"response",description:g.description}}:{type:"json_object"}:void 0,stop:v,seed:E,...Object.fromEntries(Object.entries((M=x?.[this.providerOptionsName])!=null?M:{}).filter(([B])=>!Object.keys(di.shape).includes(B))),reasoning_effort:$.reasoningEffort,verbosity:$.textVerbosity,messages:vp(t),tools:F,tool_choice:re},warnings:[...ee,...Z]}}async doGenerate(t){var r,i,c,d,f,m,x,v,g,E,A,D,T,S,P,M,ee;const{args:$,warnings:F}=await this.getArgs({...t}),re=JSON.stringify($),{responseHeaders:Z,value:B,rawValue:L}=await Js({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:qs(this.config.headers(),t.headers),body:$,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:gp(Ip),abortSignal:t.abortSignal,fetch:this.config.fetch}),W=B.choices[0],z=[],we=W.message.content;we!=null&&we.length>0&&z.push({type:"text",text:we});const G=(r=W.message.reasoning_content)!=null?r:W.message.reasoning;if(G!=null&&G.length>0&&z.push({type:"reasoning",text:G}),W.message.tool_calls!=null)for(const te of W.message.tool_calls)z.push({type:"tool-call",toolCallId:(i=te.id)!=null?i:bo(),toolName:te.function.name,input:te.function.arguments});const me={[this.providerOptionsName]:{},...await((d=(c=this.config.metadataExtractor)==null?void 0:c.extractMetadata)==null?void 0:d.call(c,{parsedBody:L}))},fe=(f=B.usage)==null?void 0:f.completion_tokens_details;return fe?.accepted_prediction_tokens!=null&&(me[this.providerOptionsName].acceptedPredictionTokens=fe?.accepted_prediction_tokens),fe?.rejected_prediction_tokens!=null&&(me[this.providerOptionsName].rejectedPredictionTokens=fe?.rejected_prediction_tokens),{content:z,finishReason:ea(W.finish_reason),usage:{inputTokens:(x=(m=B.usage)==null?void 0:m.prompt_tokens)!=null?x:void 0,outputTokens:(g=(v=B.usage)==null?void 0:v.completion_tokens)!=null?g:void 0,totalTokens:(A=(E=B.usage)==null?void 0:E.total_tokens)!=null?A:void 0,reasoningTokens:(S=(T=(D=B.usage)==null?void 0:D.completion_tokens_details)==null?void 0:T.reasoning_tokens)!=null?S:void 0,cachedInputTokens:(ee=(M=(P=B.usage)==null?void 0:P.prompt_tokens_details)==null?void 0:M.cached_tokens)!=null?ee:void 0},providerMetadata:me,request:{body:re},response:{...Qs(B),headers:Z,body:L},warnings:F}}async doStream(t){var r;const{args:i,warnings:c}=await this.getArgs({...t}),d={...i,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},f=(r=this.config.metadataExtractor)==null?void 0:r.createStreamExtractor(),{responseHeaders:m,value:x}=await Js({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:qs(this.config.headers(),t.headers),body:d,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:mp(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch}),v=[];let g="unknown";const E={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let A=!0;const D=this.providerOptionsName;let T=!1,S=!1;return{stream:x.pipeThrough(new TransformStream({start(P){P.enqueue({type:"stream-start",warnings:c})},transform(P,M){var ee,$,F,re,Z,B,L,W,z,we,G,me,fe;if(t.includeRawChunks&&M.enqueue({type:"raw",rawValue:P.rawValue}),!P.success){g="error",M.enqueue({type:"error",error:P.error});return}const te=P.value;if(f?.processChunk(P.rawValue),"error"in te){g="error",M.enqueue({type:"error",error:te.error.message});return}if(A&&(A=!1,M.enqueue({type:"response-metadata",...Qs(te)})),te.usage!=null){const{prompt_tokens:Te,completion_tokens:Je,total_tokens:xe,prompt_tokens_details:$e,completion_tokens_details:Ue}=te.usage;E.promptTokens=Te??void 0,E.completionTokens=Je??void 0,E.totalTokens=xe??void 0,Ue?.reasoning_tokens!=null&&(E.completionTokensDetails.reasoningTokens=Ue?.reasoning_tokens),Ue?.accepted_prediction_tokens!=null&&(E.completionTokensDetails.acceptedPredictionTokens=Ue?.accepted_prediction_tokens),Ue?.rejected_prediction_tokens!=null&&(E.completionTokensDetails.rejectedPredictionTokens=Ue?.rejected_prediction_tokens),$e?.cached_tokens!=null&&(E.promptTokensDetails.cachedTokens=$e?.cached_tokens)}const q=te.choices[0];if(q?.finish_reason!=null&&(g=ea(q.finish_reason)),q?.delta==null)return;const ke=q.delta,le=(ee=ke.reasoning_content)!=null?ee:ke.reasoning;if(le&&(T||(M.enqueue({type:"reasoning-start",id:"reasoning-0"}),T=!0),M.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:le})),ke.content&&(S||(M.enqueue({type:"text-start",id:"txt-0"}),S=!0),M.enqueue({type:"text-delta",id:"txt-0",delta:ke.content})),ke.tool_calls!=null)for(const Te of ke.tool_calls){const Je=Te.index;if(v[Je]==null){if(Te.id==null)throw new bs({data:Te,message:"Expected 'id' to be a string."});if((($=Te.function)==null?void 0:$.name)==null)throw new bs({data:Te,message:"Expected 'function.name' to be a string."});M.enqueue({type:"tool-input-start",id:Te.id,toolName:Te.function.name}),v[Je]={id:Te.id,type:"function",function:{name:Te.function.name,arguments:(F=Te.function.arguments)!=null?F:""},hasFinished:!1};const $e=v[Je];((re=$e.function)==null?void 0:re.name)!=null&&((Z=$e.function)==null?void 0:Z.arguments)!=null&&($e.function.arguments.length>0&&M.enqueue({type:"tool-input-delta",id:$e.id,delta:$e.function.arguments}),Ys($e.function.arguments)&&(M.enqueue({type:"tool-input-end",id:$e.id}),M.enqueue({type:"tool-call",toolCallId:(B=$e.id)!=null?B:bo(),toolName:$e.function.name,input:$e.function.arguments}),$e.hasFinished=!0));continue}const xe=v[Je];xe.hasFinished||(((L=Te.function)==null?void 0:L.arguments)!=null&&(xe.function.arguments+=(z=(W=Te.function)==null?void 0:W.arguments)!=null?z:""),M.enqueue({type:"tool-input-delta",id:xe.id,delta:(we=Te.function.arguments)!=null?we:""}),((G=xe.function)==null?void 0:G.name)!=null&&((me=xe.function)==null?void 0:me.arguments)!=null&&Ys(xe.function.arguments)&&(M.enqueue({type:"tool-input-end",id:xe.id}),M.enqueue({type:"tool-call",toolCallId:(fe=xe.id)!=null?fe:bo(),toolName:xe.function.name,input:xe.function.arguments}),xe.hasFinished=!0))}},flush(P){var M,ee,$,F,re,Z;T&&P.enqueue({type:"reasoning-end",id:"reasoning-0"}),S&&P.enqueue({type:"text-end",id:"txt-0"});for(const L of v.filter(W=>!W.hasFinished))P.enqueue({type:"tool-input-end",id:L.id}),P.enqueue({type:"tool-call",toolCallId:(M=L.id)!=null?M:bo(),toolName:L.function.name,input:L.function.arguments});const B={[D]:{},...f?.buildMetadata()};E.completionTokensDetails.acceptedPredictionTokens!=null&&(B[D].acceptedPredictionTokens=E.completionTokensDetails.acceptedPredictionTokens),E.completionTokensDetails.rejectedPredictionTokens!=null&&(B[D].rejectedPredictionTokens=E.completionTokensDetails.rejectedPredictionTokens),P.enqueue({type:"finish",finishReason:g,usage:{inputTokens:(ee=E.promptTokens)!=null?ee:void 0,outputTokens:($=E.completionTokens)!=null?$:void 0,totalTokens:(F=E.totalTokens)!=null?F:void 0,reasoningTokens:(re=E.completionTokensDetails.reasoningTokens)!=null?re:void 0,cachedInputTokens:(Z=E.promptTokensDetails.cachedTokens)!=null?Z:void 0},providerMetadata:B})}})),request:{body:d},response:{headers:m}}}},Nc=N({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:N({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:N({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish(),Ip=N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(N({message:N({role:Y("assistant").nullish(),content:w().nullish(),reasoning_content:w().nullish(),reasoning:w().nullish(),tool_calls:ue(N({id:w().nullish(),function:N({name:w(),arguments:w()})})).nullish()}),finish_reason:w().nullish()})),usage:Nc}),Sp=t=>st([N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(N({delta:N({role:Ae(["assistant"]).nullish(),content:w().nullish(),reasoning_content:w().nullish(),reasoning:w().nullish(),tool_calls:ue(N({index:j(),id:w().nullish(),function:N({name:w().nullish(),arguments:w().nullish()})})).nullish()}).nullish(),finish_reason:w().nullish()})),usage:Nc}),t]);N({echo:Mt().optional(),logitBias:wt(w(),j()).optional(),suffix:w().optional(),user:w().optional()});var Tp=N({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()});N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(N({text:w(),finish_reason:w()})),usage:Tp.nullish()});N({dimensions:j().optional(),user:w().optional()});N({data:ue(N({embedding:ue(j())})),usage:N({prompt_tokens:j()}).nullish(),providerMetadata:wt(w(),wt(w(),xr())).optional()});N({data:ue(N({b64_json:w()}))});var ta=t=>{var r,i;return t==null?void 0:{deepseek:{promptCacheHitTokens:(r=t.prompt_cache_hit_tokens)!=null?r:NaN,promptCacheMissTokens:(i=t.prompt_cache_miss_tokens)!=null?i:NaN}}},Np={extractMetadata:async({parsedBody:t})=>{const r=await to({value:t,schema:Op});return!r.success||r.value.usage==null?void 0:ta(r.value.usage)},createStreamExtractor:()=>{let t;return{processChunk:async r=>{var i,c;const d=await to({value:r,schema:kp});d.success&&((c=(i=d.value.choices)==null?void 0:i[0])==null?void 0:c.finish_reason)==="stop"&&d.value.usage&&(t=d.value.usage)},buildMetadata:()=>ta(t)}}},Oc=N({prompt_cache_hit_tokens:j().nullish(),prompt_cache_miss_tokens:j().nullish()}),Op=N({usage:Oc.nullish()}),kp=N({choices:ue(N({finish_reason:w().nullish()})).nullish(),usage:Oc.nullish()}),Rp="1.0.30";function kc(t={}){var r;const i=_p((r=t.baseURL)!=null?r:"https://api.deepseek.com/v1"),c=()=>Sc({Authorization:`Bearer ${tp({apiKey:t.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...t.headers},`ai-sdk/deepseek/${Rp}`);class d extends Ep{addJsonInstruction(v){var g;if(((g=v.responseFormat)==null?void 0:g.type)!=="json")return v;const D=[...Array.isArray(v.prompt)?v.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...v,prompt:D}}async doGenerate(v){return super.doGenerate(this.addJsonInstruction(v))}async doStream(v){return super.doStream(this.addJsonInstruction(v))}}const f=x=>new d(x,{provider:"deepseek.chat",url:({path:v})=>`${i}${v}`,headers:c,fetch:t.fetch,metadataExtractor:Np}),m=x=>f(x);return m.languageModel=f,m.chat=f,m.textEmbeddingModel=x=>{throw new As({modelId:x,modelType:"textEmbeddingModel"})},m.imageModel=x=>{throw new As({modelId:x,modelType:"imageModel"})},m}kc();var Rc="vercel.ai.error",Mp=Symbol.for(Rc),na,ra,kt=class Mc extends(ra=Error,na=Mp,ra){constructor({name:r,message:i,cause:c}){super(i),this[na]=!0,this.name=r,this.cause=c}static isInstance(r){return Mc.hasMarker(r,Rc)}static hasMarker(r,i){const c=Symbol.for(i);return r!=null&&typeof r=="object"&&c in r&&typeof r[c]=="boolean"&&r[c]===!0}},Dc="AI_APICallError",Pc=`vercel.ai.error.${Dc}`,Dp=Symbol.for(Pc),oa,ia,Kt=class extends(ia=kt,oa=Dp,ia){constructor({message:t,url:r,requestBodyValues:i,statusCode:c,responseHeaders:d,responseBody:f,cause:m,isRetryable:x=c!=null&&(c===408||c===409||c===429||c>=500),data:v}){super({name:Dc,message:t,cause:m}),this[oa]=!0,this.url=r,this.requestBodyValues=i,this.statusCode=c,this.responseHeaders=d,this.responseBody=f,this.isRetryable=x,this.data=v}static isInstance(t){return kt.hasMarker(t,Pc)}},Bc="AI_EmptyResponseBodyError",Lc=`vercel.ai.error.${Bc}`,Pp=Symbol.for(Lc),sa,aa,Bp=class extends(aa=kt,sa=Pp,aa){constructor({message:t="Empty response body"}={}){super({name:Bc,message:t}),this[sa]=!0}static isInstance(t){return kt.hasMarker(t,Lc)}};function Fc(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var Uc="AI_InvalidArgumentError",zc=`vercel.ai.error.${Uc}`,Lp=Symbol.for(zc),la,ca,Vc=class extends(ca=kt,la=Lp,ca){constructor({message:t,cause:r,argument:i}){super({name:Uc,message:t,cause:r}),this[la]=!0,this.argument=i}static isInstance(t){return kt.hasMarker(t,zc)}},Zc="AI_InvalidPromptError",$c=`vercel.ai.error.${Zc}`,Fp=Symbol.for($c),ua,da,Up=class extends(da=kt,ua=Fp,da){constructor({prompt:t,message:r,cause:i}){super({name:Zc,message:`Invalid prompt: ${r}`,cause:i}),this[ua]=!0,this.prompt=t}static isInstance(t){return kt.hasMarker(t,$c)}},jc="AI_InvalidResponseDataError",Hc=`vercel.ai.error.${jc}`,zp=Symbol.for(Hc),fa,ha,fi=class extends(ha=kt,fa=zp,ha){constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:jc,message:r}),this[fa]=!0,this.data=t}static isInstance(t){return kt.hasMarker(t,Hc)}},Wc="AI_JSONParseError",Gc=`vercel.ai.error.${Wc}`,Vp=Symbol.for(Gc),pa,ma,Do=class extends(ma=kt,pa=Vp,ma){constructor({text:t,cause:r}){super({name:Wc,message:`JSON parsing failed: Text: ${t}.
40
40
  Error message: ${Fc(r)}`,cause:r}),this[pa]=!0,this.text=t}static isInstance(t){return kt.hasMarker(t,Gc)}},qc="AI_LoadAPIKeyError",Xc=`vercel.ai.error.${qc}`,Zp=Symbol.for(Xc),ga,xa,Ao=class extends(xa=kt,ga=Zp,xa){constructor({message:t}){super({name:qc,message:t}),this[ga]=!0}static isInstance(t){return kt.hasMarker(t,Xc)}},Yc="AI_TooManyEmbeddingValuesForCallError",Kc=`vercel.ai.error.${Yc}`,$p=Symbol.for(Kc),ya,wa,jp=class extends(wa=kt,ya=$p,wa){constructor(t){super({name:Yc,message:`Too many values for a single embedding call. The ${t.provider} model "${t.modelId}" can only embed up to ${t.maxEmbeddingsPerCall} values per call, but ${t.values.length} values were provided.`}),this[ya]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return kt.hasMarker(t,Kc)}},Jc="AI_TypeValidationError",Qc=`vercel.ai.error.${Jc}`,Hp=Symbol.for(Qc),_a,va,no=class Si extends(va=kt,_a=Hp,va){constructor({value:r,cause:i,context:c}){let d="Type validation failed";if(c?.field&&(d+=` for ${c.field}`),c?.entityName||c?.entityId){d+=" (";const f=[];c.entityName&&f.push(c.entityName),c.entityId&&f.push(`id: "${c.entityId}"`),d+=f.join(", "),d+=")"}super({name:Jc,message:`${d}: Value: ${JSON.stringify(r)}.
41
- Error message: ${Fc(i)}`,cause:i}),this[_a]=!0,this.value=r,this.context=c}static isInstance(r){return kt.hasMarker(r,Qc)}static wrap({value:r,cause:i,context:c}){var d,f,m;return Si.isInstance(i)&&i.value===r&&((d=i.context)==null?void 0:d.field)===c?.field&&((f=i.context)==null?void 0:f.entityName)===c?.entityName&&((m=i.context)==null?void 0:m.entityId)===c?.entityId?i:new Si({value:r,cause:i,context:c})}},eu="AI_UnsupportedFunctionalityError",tu=`vercel.ai.error.${eu}`,Wp=Symbol.for(tu),Ca,ba,Mn=class extends(ba=kt,Ca=Wp,ba){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:eu,message:r}),this[Ca]=!0,this.functionality=t}static isInstance(t){return kt.hasMarker(t,tu)}};function bn(...t){return t.reduce((r,i)=>({...r,...i??{}}),{})}function Gp({tools:t=[],providerToolNames:r,resolveProviderToolName:i}){var c;const d={},f={};for(const m of t)if(m.type==="provider"){const x=(c=i?.(m))!=null?c:m.id in r?r[m.id]:void 0;if(x==null)continue;d[m.name]=x,f[x]=m.name}return{toProviderToolName:m=>{var x;return(x=d[m])!=null?x:m},toCustomToolName:m=>{var x;return(x=f[m])!=null?x:m}}}var qp=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((t,r)=>{this.status.type==="resolved"?t(this.status.value):this.status.type==="rejected"&&r(this.status.error),this._resolve=t,this._reject=r}),this._promise)}resolve(t){var r;this.status={type:"resolved",value:t},this._promise&&((r=this._resolve)==null||r.call(this,t))}reject(t){var r;this.status={type:"rejected",error:t},this._promise&&((r=this._reject)==null||r.call(this,t))}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function ao(t){return Object.fromEntries([...t.headers])}var{btoa:Xp,atob:Yp}=globalThis;function qi(t){const r=t.replace(/-/g,"+").replace(/_/g,"/"),i=Yp(r);return Uint8Array.from(i,c=>c.codePointAt(0))}function Kp(t){let r="";for(let i=0;i<t.length;i++)r+=String.fromCodePoint(t[i]);return Xp(r)}function kr(t){return t instanceof Uint8Array?Kp(t):t}function Jp(t,r={}){const{useArrayBrackets:i=!0}=r,c=new FormData;for(const[d,f]of Object.entries(t))if(f!=null){if(Array.isArray(f)){if(f.length===1){c.append(d,f[0]);continue}const m=i?`${d}[]`:d;for(const x of f)c.append(m,x);continue}c.append(d,f)}return c}async function Xi(t){var r;try{await((r=t.body)==null?void 0:r.cancel())}catch{}}var nu="AI_DownloadError",ru=`vercel.ai.error.${nu}`,Qp=Symbol.for(ru),Aa,Ea,cn=class extends(Ea=kt,Aa=Qp,Ea){constructor({url:t,statusCode:r,statusText:i,cause:c,message:d=c==null?`Failed to download ${t}: ${r} ${i}`:`Failed to download ${t}: ${c}`}){super({name:nu,message:d,cause:c}),this[Aa]=!0,this.url=t,this.statusCode=r,this.statusText=i}static isInstance(t){return kt.hasMarker(t,ru)}};function em(t=globalThis){return t.window!=null}function tm(t){let r;try{r=new URL(t)}catch{throw new cn({url:t,message:`Invalid URL: ${t}`})}if(r.protocol==="data:")return;if(r.protocol!=="http:"&&r.protocol!=="https:")throw new cn({url:t,message:`URL scheme must be http, https, or data, got ${r.protocol}`});const i=r.hostname.toLowerCase().replace(/\.+$/,"");if(!i)throw new cn({url:t,message:"URL must have a hostname"});if(i==="localhost"||i.endsWith(".local")||i.endsWith(".localhost"))throw new cn({url:t,message:`URL with hostname ${i} is not allowed`});if(i.startsWith("[")&&i.endsWith("]")){const c=i.slice(1,-1);if(rm(c))throw new cn({url:t,message:`URL with IPv6 address ${i} is not allowed`});return}if(ou(i)){if(iu(i))throw new cn({url:t,message:`URL with IP address ${i} is not allowed`});return}}function ou(t){const r=t.split(".");return r.length!==4?!1:r.every(i=>{const c=Number(i);return Number.isInteger(c)&&c>=0&&c<=255&&String(c)===i})}function iu(t){const r=t.split(".").map(Number),[i,c,d]=r;return i===0||i===10||i===100&&c>=64&&c<=127||i===127||i===169&&c===254||i===172&&c>=16&&c<=31||i===192&&c===0&&d===0||i===192&&c===168||i===198&&(c===18||c===19)||i>=240}function nm(t){let r=t.toLowerCase();const i=r.indexOf("%");i!==-1&&(r=r.slice(0,i));const c=r.split("::");if(c.length>2)return null;const d=m=>{if(m==="")return[];const x=[],v=m.split(":");for(let g=0;g<v.length;g++){const E=v[g];if(E.includes(".")){if(g!==v.length-1||!ou(E))return null;const[A,D,T,S]=E.split(".").map(Number);x.push(A<<8|D,T<<8|S);continue}if(!/^[0-9a-f]{1,4}$/.test(E))return null;x.push(parseInt(E,16))}return x},f=d(c[0]);if(f===null)return null;if(c.length===2){const m=d(c[1]);if(m===null)return null;const x=8-f.length-m.length;return x<0?null:[...f,...new Array(x).fill(0),...m]}return f.length===8?f:null}function rm(t){const r=nm(t);if(r===null)return!0;const i=d=>r.slice(0,d).every(f=>f===0);if(i(7)&&(r[7]===0||r[7]===1)||(r[0]&65024)===64512||(r[0]&65472)===65152||(r[0]&65472)===65216||(r[0]&65280)===65280)return!0;if(i(6)||i(5)&&r[5]===65535||i(4)&&r[4]===65535&&r[5]===0||r[0]===100&&r[1]===65435&&r[2]===0&&r[3]===0&&r[4]===0&&r[5]===0||r[0]===100&&r[1]===65435&&r[2]===1){const d=r[6]>>8&255,f=r[6]&255,m=r[7]>>8&255,x=r[7]&255;return iu(`${d}.${f}.${m}.${x}`)}return!1}var om=10;async function im({url:t,headers:r,abortSignal:i,maxRedirects:c=om}){const d={signal:i};r!==void 0&&(d.headers=r);let f=t;for(let m=0;m<=c;m++){tm(f);const x=await fetch(f,{...d,redirect:"manual"});if(x.type==="opaqueredirect"){if(!em())throw new cn({url:t,message:`Redirect from ${f} could not be validated and was blocked`});return await fetch(f,{...d,redirect:"follow"})}const v=x.headers.get("location");if(x.status>=300&&x.status<400&&v){await Xi(x),f=new URL(v,f).toString();continue}return x}throw new cn({url:t,message:`Too many redirects (max ${c})`})}var su=2*1024*1024*1024;async function au({response:t,url:r,maxBytes:i=su}){const c=t.headers.get("content-length");if(c!=null){const E=parseInt(c,10);if(!isNaN(E)&&E>i)throw await Xi(t),new cn({url:r,message:`Download of ${r} exceeded maximum size of ${i} bytes (Content-Length: ${E}).`})}const d=t.body;if(d==null)return new Uint8Array(0);const f=d.getReader(),m=[];let x=0;try{for(;;){const{done:E,value:A}=await f.read();if(E)break;if(x+=A.length,x>i)throw new cn({url:r,message:`Download of ${r} exceeded maximum size of ${i} bytes.`});m.push(A)}}finally{try{await f.cancel()}finally{f.releaseLock()}}const v=new Uint8Array(x);let g=0;for(const E of m)v.set(E,g),g+=E.length;return v}async function lu(t,r){var i,c;try{const d=await im({url:t,abortSignal:r?.abortSignal});if(!d.ok)throw await Xi(d),new cn({url:t,statusCode:d.status,statusText:d.statusText});const f=await au({response:d,url:t,maxBytes:(i=r?.maxBytes)!=null?i:su}),m=(c=d.headers.get("content-type"))!=null?c:void 0;return new Blob([f],m?{type:m}:void 0)}catch(d){throw cn.isInstance(d)?d:new cn({url:t,cause:d})}}var sm=({prefix:t,size:r=16,alphabet:i="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:c="-"}={})=>{const d=()=>{const f=i.length,m=new Array(r);for(let x=0;x<r;x++)m[x]=i[Math.random()*f|0];return m.join("")};if(t==null)return d;if(i.includes(c))throw new Vc({argument:"separator",message:`The separator "${c}" must not be part of the alphabet "${i}".`});return()=>`${t}${c}${d()}`},rn=sm();function Ti(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var am=["fetch failed","failed to fetch"],lm=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function cm(t){if(!(t instanceof Error))return!1;const r=t.code;return!!(typeof r=="string"&&lm.includes(r))}function um({error:t,url:r,requestBodyValues:i}){if(Ti(t))return t;if(t instanceof TypeError&&am.includes(t.message.toLowerCase())){const c=t.cause;if(c!=null)return new Kt({message:`Cannot connect to API: ${c.message}`,cause:c,url:r,requestBodyValues:i,isRetryable:!0})}return cm(t)?new Kt({message:`Cannot connect to API: ${t.message}`,cause:t,url:r,requestBodyValues:i,isRetryable:!0}):t}function dm(t=globalThis){var r,i,c;return t.window?"runtime/browser":(r=t.navigator)!=null&&r.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(c=(i=t.process)==null?void 0:i.versions)!=null&&c.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function fm(t){if(t==null)return{};const r={};if(t instanceof Headers)t.forEach((i,c)=>{r[c.toLowerCase()]=i});else{Array.isArray(t)||(t=Object.entries(t));for(const[i,c]of t)c!=null&&(r[i.toLowerCase()]=c)}return r}function cu(t,...r){const i=new Headers(fm(t)),c=i.get("user-agent")||"";return i.set("user-agent",[c,...r].filter(Boolean).join(" ")),Object.fromEntries(i.entries())}var hm="4.0.38";function Ia(t){return t!=null}function pm({apiKey:t,environmentVariableName:r,apiKeyParameterName:i="apiKey",description:c}){if(typeof t=="string")return t;if(t!=null)throw new Ao({message:`${c} API key must be a string.`});if(typeof process>"u")throw new Ao({message:`${c} API key is missing. Pass it using the '${i}' parameter. Environment variables are not supported in this environment.`});if(t=process.env[r],t==null)throw new Ao({message:`${c} API key is missing. Pass it using the '${i}' parameter or the ${r} environment variable.`});if(typeof t!="string")throw new Ao({message:`${c} API key must be a string. The value of the ${r} environment variable is not a string.`});return t}function mm({settingValue:t,environmentVariableName:r}){if(typeof t=="string")return t;if(!(t!=null||typeof process>"u")&&(t=process.env[r],!(t==null||typeof t!="string")))return t}function gm(t){var r;const[i,c=""]=t.toLowerCase().split("/");return(r={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[c])!=null?r:c}var xm=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,ym=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function Sa(t){const r=JSON.parse(t);return r===null||typeof r!="object"||xm.test(t)===!1&&ym.test(t)===!1?r:wm(r)}function wm(t){let r=[t];for(;r.length;){const i=r;r=[];for(const c of i){if(Object.prototype.hasOwnProperty.call(c,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(c,"constructor")&&c.constructor!==null&&typeof c.constructor=="object"&&Object.prototype.hasOwnProperty.call(c.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const d in c){const f=c[d];f&&typeof f=="object"&&r.push(f)}}}return t}function uu(t){const{stackTraceLimit:r}=Error;try{Error.stackTraceLimit=0}catch{return Sa(t)}try{return Sa(t)}finally{Error.stackTraceLimit=r}}function Yi(t){if(t.type==="object"||Array.isArray(t.type)&&t.type.includes("object")){t.additionalProperties=!1;const{properties:i}=t;if(i!=null)for(const c of Object.keys(i))i[c]=dr(i[c])}t.items!=null&&(t.items=Array.isArray(t.items)?t.items.map(dr):dr(t.items)),t.anyOf!=null&&(t.anyOf=t.anyOf.map(dr)),t.allOf!=null&&(t.allOf=t.allOf.map(dr)),t.oneOf!=null&&(t.oneOf=t.oneOf.map(dr));const{definitions:r}=t;if(r!=null)for(const i of Object.keys(r))r[i]=dr(r[i]);return t}function dr(t){return typeof t=="boolean"?t:Yi(t)}var _m=Symbol("Let zodToJsonSchema decide on which parser to use"),Ta={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},vm=t=>typeof t=="string"?{...Ta,name:t}:{...Ta,...t};function fn(){return{}}function Cm(t,r){var i,c,d;const f={type:"array"};return(i=t.type)!=null&&i._def&&((d=(c=t.type)==null?void 0:c._def)==null?void 0:d.typeName)!==je.ZodAny&&(f.items=ct(t.type._def,{...r,currentPath:[...r.currentPath,"items"]})),t.minLength&&(f.minItems=t.minLength.value),t.maxLength&&(f.maxItems=t.maxLength.value),t.exactLength&&(f.minItems=t.exactLength.value,f.maxItems=t.exactLength.value),f}function bm(t){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const i of t.checks)switch(i.kind){case"min":i.inclusive?r.minimum=i.value:r.exclusiveMinimum=i.value;break;case"max":i.inclusive?r.maximum=i.value:r.exclusiveMaximum=i.value;break;case"multipleOf":r.multipleOf=i.value;break}return r}function Am(){return{type:"boolean"}}function du(t,r){return ct(t.type._def,r)}var Em=(t,r)=>ct(t.innerType._def,r);function fu(t,r,i){const c=i??r.dateStrategy;if(Array.isArray(c))return{anyOf:c.map((d,f)=>fu(t,r,d))};switch(c){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Im(t)}}var Im=t=>{const r={type:"integer",format:"unix-time"};for(const i of t.checks)switch(i.kind){case"min":r.minimum=i.value;break;case"max":r.maximum=i.value;break}return r};function Sm(t,r){return{...ct(t.innerType._def,r),default:t.defaultValue()}}function Tm(t,r){return r.effectStrategy==="input"?ct(t.schema._def,r):fn()}function Nm(t){return{type:"string",enum:Array.from(t.values)}}var Om=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function km(t,r){const i=[ct(t.left._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),ct(t.right._def,{...r,currentPath:[...r.currentPath,"allOf","1"]})].filter(d=>!!d),c=[];return i.forEach(d=>{if(Om(d))c.push(...d.allOf);else{let f=d;if("additionalProperties"in d&&d.additionalProperties===!1){const{additionalProperties:m,...x}=d;f=x}c.push(f)}}),c.length?{allOf:c}:void 0}function Rm(t){const r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:{type:r==="bigint"?"integer":r,const:t.value}}var hi=void 0,wn={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(hi===void 0&&(hi=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),hi),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function hu(t,r){const i={type:"string"};if(t.checks)for(const c of t.checks)switch(c.kind){case"min":i.minLength=typeof i.minLength=="number"?Math.max(i.minLength,c.value):c.value;break;case"max":i.maxLength=typeof i.maxLength=="number"?Math.min(i.maxLength,c.value):c.value;break;case"email":switch(r.emailStrategy){case"format:email":_n(i,"email",c.message,r);break;case"format:idn-email":_n(i,"idn-email",c.message,r);break;case"pattern:zod":Yt(i,wn.email,c.message,r);break}break;case"url":_n(i,"uri",c.message,r);break;case"uuid":_n(i,"uuid",c.message,r);break;case"regex":Yt(i,c.regex,c.message,r);break;case"cuid":Yt(i,wn.cuid,c.message,r);break;case"cuid2":Yt(i,wn.cuid2,c.message,r);break;case"startsWith":Yt(i,RegExp(`^${pi(c.value,r)}`),c.message,r);break;case"endsWith":Yt(i,RegExp(`${pi(c.value,r)}$`),c.message,r);break;case"datetime":_n(i,"date-time",c.message,r);break;case"date":_n(i,"date",c.message,r);break;case"time":_n(i,"time",c.message,r);break;case"duration":_n(i,"duration",c.message,r);break;case"length":i.minLength=typeof i.minLength=="number"?Math.max(i.minLength,c.value):c.value,i.maxLength=typeof i.maxLength=="number"?Math.min(i.maxLength,c.value):c.value;break;case"includes":{Yt(i,RegExp(pi(c.value,r)),c.message,r);break}case"ip":{c.version!=="v6"&&_n(i,"ipv4",c.message,r),c.version!=="v4"&&_n(i,"ipv6",c.message,r);break}case"base64url":Yt(i,wn.base64url,c.message,r);break;case"jwt":Yt(i,wn.jwt,c.message,r);break;case"cidr":{c.version!=="v6"&&Yt(i,wn.ipv4Cidr,c.message,r),c.version!=="v4"&&Yt(i,wn.ipv6Cidr,c.message,r);break}case"emoji":Yt(i,wn.emoji(),c.message,r);break;case"ulid":{Yt(i,wn.ulid,c.message,r);break}case"base64":{switch(r.base64Strategy){case"format:binary":{_n(i,"binary",c.message,r);break}case"contentEncoding:base64":{i.contentEncoding="base64";break}case"pattern:zod":{Yt(i,wn.base64,c.message,r);break}}break}case"nanoid":Yt(i,wn.nanoid,c.message,r)}return i}function pi(t,r){return r.patternStrategy==="escape"?Dm(t):t}var Mm=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Dm(t){let r="";for(let i=0;i<t.length;i++)Mm.has(t[i])||(r+="\\"),r+=t[i];return r}function _n(t,r,i,c){var d;t.format||(d=t.anyOf)!=null&&d.some(f=>f.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:r,...i&&c.errorMessages&&{errorMessage:{format:i}}})):t.format=r}function Yt(t,r,i,c){var d;t.pattern||(d=t.allOf)!=null&&d.some(f=>f.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:Na(r,c),...i&&c.errorMessages&&{errorMessage:{pattern:i}}})):t.pattern=Na(r,c)}function Na(t,r){var i;if(!r.applyRegexFlags||!t.flags)return t.source;const c={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},d=c.i?t.source.toLowerCase():t.source;let f="",m=!1,x=!1,v=!1;for(let g=0;g<d.length;g++){if(m){f+=d[g],m=!1;continue}if(c.i){if(x){if(d[g].match(/[a-z]/)){v?(f+=d[g],f+=`${d[g-2]}-${d[g]}`.toUpperCase(),v=!1):d[g+1]==="-"&&((i=d[g+2])!=null&&i.match(/[a-z]/))?(f+=d[g],v=!0):f+=`${d[g]}${d[g].toUpperCase()}`;continue}}else if(d[g].match(/[a-z]/)){f+=`[${d[g]}${d[g].toUpperCase()}]`;continue}}if(c.m){if(d[g]==="^"){f+=`(^|(?<=[\r
41
+ Error message: ${Fc(i)}`,cause:i}),this[_a]=!0,this.value=r,this.context=c}static isInstance(r){return kt.hasMarker(r,Qc)}static wrap({value:r,cause:i,context:c}){var d,f,m;return Si.isInstance(i)&&i.value===r&&((d=i.context)==null?void 0:d.field)===c?.field&&((f=i.context)==null?void 0:f.entityName)===c?.entityName&&((m=i.context)==null?void 0:m.entityId)===c?.entityId?i:new Si({value:r,cause:i,context:c})}},eu="AI_UnsupportedFunctionalityError",tu=`vercel.ai.error.${eu}`,Wp=Symbol.for(tu),Ca,ba,Mn=class extends(ba=kt,Ca=Wp,ba){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:eu,message:r}),this[Ca]=!0,this.functionality=t}static isInstance(t){return kt.hasMarker(t,tu)}};function bn(...t){return t.reduce((r,i)=>({...r,...i??{}}),{})}function Gp({tools:t=[],providerToolNames:r,resolveProviderToolName:i}){var c;const d={},f={};for(const m of t)if(m.type==="provider"){const x=(c=i?.(m))!=null?c:m.id in r?r[m.id]:void 0;if(x==null)continue;d[m.name]=x,f[x]=m.name}return{toProviderToolName:m=>{var x;return(x=d[m])!=null?x:m},toCustomToolName:m=>{var x;return(x=f[m])!=null?x:m}}}var qp=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((t,r)=>{this.status.type==="resolved"?t(this.status.value):this.status.type==="rejected"&&r(this.status.error),this._resolve=t,this._reject=r}),this._promise)}resolve(t){var r;this.status={type:"resolved",value:t},this._promise&&((r=this._resolve)==null||r.call(this,t))}reject(t){var r;this.status={type:"rejected",error:t},this._promise&&((r=this._reject)==null||r.call(this,t))}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function ao(t){return Object.fromEntries([...t.headers])}var{btoa:Xp,atob:Yp}=globalThis;function qi(t){const r=t.replace(/-/g,"+").replace(/_/g,"/"),i=Yp(r);return Uint8Array.from(i,c=>c.codePointAt(0))}function Kp(t){let r="";for(let i=0;i<t.length;i++)r+=String.fromCodePoint(t[i]);return Xp(r)}function kr(t){return t instanceof Uint8Array?Kp(t):t}function Jp(t,r={}){const{useArrayBrackets:i=!0}=r,c=new FormData;for(const[d,f]of Object.entries(t))if(f!=null){if(Array.isArray(f)){if(f.length===1){c.append(d,f[0]);continue}const m=i?`${d}[]`:d;for(const x of f)c.append(m,x);continue}c.append(d,f)}return c}async function Xi(t){var r;try{await((r=t.body)==null?void 0:r.cancel())}catch{}}var nu="AI_DownloadError",ru=`vercel.ai.error.${nu}`,Qp=Symbol.for(ru),Aa,Ea,cn=class extends(Ea=kt,Aa=Qp,Ea){constructor({url:t,statusCode:r,statusText:i,cause:c,message:d=c==null?`Failed to download ${t}: ${r} ${i}`:`Failed to download ${t}: ${c}`}){super({name:nu,message:d,cause:c}),this[Aa]=!0,this.url=t,this.statusCode=r,this.statusText=i}static isInstance(t){return kt.hasMarker(t,ru)}};function em(t=globalThis){return t.window!=null}function tm(t){let r;try{r=new URL(t)}catch{throw new cn({url:t,message:`Invalid URL: ${t}`})}if(r.protocol==="data:")return;if(r.protocol!=="http:"&&r.protocol!=="https:")throw new cn({url:t,message:`URL scheme must be http, https, or data, got ${r.protocol}`});const i=r.hostname.toLowerCase().replace(/\.+$/,"");if(!i)throw new cn({url:t,message:"URL must have a hostname"});if(i==="localhost"||i.endsWith(".local")||i.endsWith(".localhost"))throw new cn({url:t,message:`URL with hostname ${i} is not allowed`});if(i.startsWith("[")&&i.endsWith("]")){const c=i.slice(1,-1);if(rm(c))throw new cn({url:t,message:`URL with IPv6 address ${i} is not allowed`});return}if(ou(i)){if(iu(i))throw new cn({url:t,message:`URL with IP address ${i} is not allowed`});return}}function ou(t){const r=t.split(".");return r.length!==4?!1:r.every(i=>{const c=Number(i);return Number.isInteger(c)&&c>=0&&c<=255&&String(c)===i})}function iu(t){const r=t.split(".").map(Number),[i,c,d]=r;return i===0||i===10||i===100&&c>=64&&c<=127||i===127||i===169&&c===254||i===172&&c>=16&&c<=31||i===192&&c===0&&d===0||i===192&&c===168||i===198&&(c===18||c===19)||i>=240}function nm(t){let r=t.toLowerCase();const i=r.indexOf("%");i!==-1&&(r=r.slice(0,i));const c=r.split("::");if(c.length>2)return null;const d=m=>{if(m==="")return[];const x=[],v=m.split(":");for(let g=0;g<v.length;g++){const E=v[g];if(E.includes(".")){if(g!==v.length-1||!ou(E))return null;const[A,D,T,S]=E.split(".").map(Number);x.push(A<<8|D,T<<8|S);continue}if(!/^[0-9a-f]{1,4}$/.test(E))return null;x.push(parseInt(E,16))}return x},f=d(c[0]);if(f===null)return null;if(c.length===2){const m=d(c[1]);if(m===null)return null;const x=8-f.length-m.length;return x<0?null:[...f,...new Array(x).fill(0),...m]}return f.length===8?f:null}function rm(t){const r=nm(t);if(r===null)return!0;const i=d=>r.slice(0,d).every(f=>f===0);if(i(7)&&(r[7]===0||r[7]===1)||(r[0]&65024)===64512||(r[0]&65472)===65152||(r[0]&65472)===65216||(r[0]&65280)===65280)return!0;if(i(6)||i(5)&&r[5]===65535||i(4)&&r[4]===65535&&r[5]===0||r[0]===100&&r[1]===65435&&r[2]===0&&r[3]===0&&r[4]===0&&r[5]===0||r[0]===100&&r[1]===65435&&r[2]===1){const d=r[6]>>8&255,f=r[6]&255,m=r[7]>>8&255,x=r[7]&255;return iu(`${d}.${f}.${m}.${x}`)}return!1}var om=10;async function im({url:t,headers:r,abortSignal:i,maxRedirects:c=om}){const d={signal:i};r!==void 0&&(d.headers=r);let f=t;for(let m=0;m<=c;m++){tm(f);const x=await fetch(f,{...d,redirect:"manual"});if(x.type==="opaqueredirect"){if(!em())throw new cn({url:t,message:`Redirect from ${f} could not be validated and was blocked`});return await fetch(f,{...d,redirect:"follow"})}const v=x.headers.get("location");if(x.status>=300&&x.status<400&&v){await Xi(x),f=new URL(v,f).toString();continue}return x}throw new cn({url:t,message:`Too many redirects (max ${c})`})}var su=2*1024*1024*1024;async function au({response:t,url:r,maxBytes:i=su}){const c=t.headers.get("content-length");if(c!=null){const E=parseInt(c,10);if(!isNaN(E)&&E>i)throw await Xi(t),new cn({url:r,message:`Download of ${r} exceeded maximum size of ${i} bytes (Content-Length: ${E}).`})}const d=t.body;if(d==null)return new Uint8Array(0);const f=d.getReader(),m=[];let x=0;try{for(;;){const{done:E,value:A}=await f.read();if(E)break;if(x+=A.length,x>i)throw new cn({url:r,message:`Download of ${r} exceeded maximum size of ${i} bytes.`});m.push(A)}}finally{try{await f.cancel()}finally{f.releaseLock()}}const v=new Uint8Array(x);let g=0;for(const E of m)v.set(E,g),g+=E.length;return v}async function lu(t,r){var i,c;try{const d=await im({url:t,abortSignal:r?.abortSignal});if(!d.ok)throw await Xi(d),new cn({url:t,statusCode:d.status,statusText:d.statusText});const f=await au({response:d,url:t,maxBytes:(i=r?.maxBytes)!=null?i:su}),m=(c=d.headers.get("content-type"))!=null?c:void 0;return new Blob([f],m?{type:m}:void 0)}catch(d){throw cn.isInstance(d)?d:new cn({url:t,cause:d})}}var sm=({prefix:t,size:r=16,alphabet:i="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:c="-"}={})=>{const d=()=>{const f=i.length,m=new Array(r);for(let x=0;x<r;x++)m[x]=i[Math.random()*f|0];return m.join("")};if(t==null)return d;if(i.includes(c))throw new Vc({argument:"separator",message:`The separator "${c}" must not be part of the alphabet "${i}".`});return()=>`${t}${c}${d()}`},rn=sm();function Ti(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var am=["fetch failed","failed to fetch"],lm=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function cm(t){if(!(t instanceof Error))return!1;const r=t.code;return!!(typeof r=="string"&&lm.includes(r))}function um({error:t,url:r,requestBodyValues:i}){if(Ti(t))return t;if(t instanceof TypeError&&am.includes(t.message.toLowerCase())){const c=t.cause;if(c!=null)return new Kt({message:`Cannot connect to API: ${c.message}`,cause:c,url:r,requestBodyValues:i,isRetryable:!0})}return cm(t)?new Kt({message:`Cannot connect to API: ${t.message}`,cause:t,url:r,requestBodyValues:i,isRetryable:!0}):t}function dm(t=globalThis){var r,i,c;return t.window?"runtime/browser":(r=t.navigator)!=null&&r.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(c=(i=t.process)==null?void 0:i.versions)!=null&&c.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function fm(t){if(t==null)return{};const r={};if(t instanceof Headers)t.forEach((i,c)=>{r[c.toLowerCase()]=i});else{Array.isArray(t)||(t=Object.entries(t));for(const[i,c]of t)c!=null&&(r[i.toLowerCase()]=c)}return r}function cu(t,...r){const i=new Headers(fm(t)),c=i.get("user-agent")||"";return i.set("user-agent",[c,...r].filter(Boolean).join(" ")),Object.fromEntries(i.entries())}var hm="4.0.40";function Ia(t){return t!=null}function pm({apiKey:t,environmentVariableName:r,apiKeyParameterName:i="apiKey",description:c}){if(typeof t=="string")return t;if(t!=null)throw new Ao({message:`${c} API key must be a string.`});if(typeof process>"u")throw new Ao({message:`${c} API key is missing. Pass it using the '${i}' parameter. Environment variables are not supported in this environment.`});if(t=process.env[r],t==null)throw new Ao({message:`${c} API key is missing. Pass it using the '${i}' parameter or the ${r} environment variable.`});if(typeof t!="string")throw new Ao({message:`${c} API key must be a string. The value of the ${r} environment variable is not a string.`});return t}function mm({settingValue:t,environmentVariableName:r}){if(typeof t=="string")return t;if(!(t!=null||typeof process>"u")&&(t=process.env[r],!(t==null||typeof t!="string")))return t}function gm(t){var r;const[i,c=""]=t.toLowerCase().split("/");return(r={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[c])!=null?r:c}var xm=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,ym=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function Sa(t){const r=JSON.parse(t);return r===null||typeof r!="object"||xm.test(t)===!1&&ym.test(t)===!1?r:wm(r)}function wm(t){let r=[t];for(;r.length;){const i=r;r=[];for(const c of i){if(Object.prototype.hasOwnProperty.call(c,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(c,"constructor")&&c.constructor!==null&&typeof c.constructor=="object"&&Object.prototype.hasOwnProperty.call(c.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const d in c){const f=c[d];f&&typeof f=="object"&&r.push(f)}}}return t}function uu(t){const{stackTraceLimit:r}=Error;try{Error.stackTraceLimit=0}catch{return Sa(t)}try{return Sa(t)}finally{Error.stackTraceLimit=r}}function Yi(t){if(t.type==="object"||Array.isArray(t.type)&&t.type.includes("object")){t.additionalProperties=!1;const{properties:i}=t;if(i!=null)for(const c of Object.keys(i))i[c]=dr(i[c])}t.items!=null&&(t.items=Array.isArray(t.items)?t.items.map(dr):dr(t.items)),t.anyOf!=null&&(t.anyOf=t.anyOf.map(dr)),t.allOf!=null&&(t.allOf=t.allOf.map(dr)),t.oneOf!=null&&(t.oneOf=t.oneOf.map(dr));const{definitions:r}=t;if(r!=null)for(const i of Object.keys(r))r[i]=dr(r[i]);return t}function dr(t){return typeof t=="boolean"?t:Yi(t)}var _m=Symbol("Let zodToJsonSchema decide on which parser to use"),Ta={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},vm=t=>typeof t=="string"?{...Ta,name:t}:{...Ta,...t};function fn(){return{}}function Cm(t,r){var i,c,d;const f={type:"array"};return(i=t.type)!=null&&i._def&&((d=(c=t.type)==null?void 0:c._def)==null?void 0:d.typeName)!==je.ZodAny&&(f.items=ct(t.type._def,{...r,currentPath:[...r.currentPath,"items"]})),t.minLength&&(f.minItems=t.minLength.value),t.maxLength&&(f.maxItems=t.maxLength.value),t.exactLength&&(f.minItems=t.exactLength.value,f.maxItems=t.exactLength.value),f}function bm(t){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const i of t.checks)switch(i.kind){case"min":i.inclusive?r.minimum=i.value:r.exclusiveMinimum=i.value;break;case"max":i.inclusive?r.maximum=i.value:r.exclusiveMaximum=i.value;break;case"multipleOf":r.multipleOf=i.value;break}return r}function Am(){return{type:"boolean"}}function du(t,r){return ct(t.type._def,r)}var Em=(t,r)=>ct(t.innerType._def,r);function fu(t,r,i){const c=i??r.dateStrategy;if(Array.isArray(c))return{anyOf:c.map((d,f)=>fu(t,r,d))};switch(c){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Im(t)}}var Im=t=>{const r={type:"integer",format:"unix-time"};for(const i of t.checks)switch(i.kind){case"min":r.minimum=i.value;break;case"max":r.maximum=i.value;break}return r};function Sm(t,r){return{...ct(t.innerType._def,r),default:t.defaultValue()}}function Tm(t,r){return r.effectStrategy==="input"?ct(t.schema._def,r):fn()}function Nm(t){return{type:"string",enum:Array.from(t.values)}}var Om=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function km(t,r){const i=[ct(t.left._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),ct(t.right._def,{...r,currentPath:[...r.currentPath,"allOf","1"]})].filter(d=>!!d),c=[];return i.forEach(d=>{if(Om(d))c.push(...d.allOf);else{let f=d;if("additionalProperties"in d&&d.additionalProperties===!1){const{additionalProperties:m,...x}=d;f=x}c.push(f)}}),c.length?{allOf:c}:void 0}function Rm(t){const r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:{type:r==="bigint"?"integer":r,const:t.value}}var hi=void 0,wn={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(hi===void 0&&(hi=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),hi),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function hu(t,r){const i={type:"string"};if(t.checks)for(const c of t.checks)switch(c.kind){case"min":i.minLength=typeof i.minLength=="number"?Math.max(i.minLength,c.value):c.value;break;case"max":i.maxLength=typeof i.maxLength=="number"?Math.min(i.maxLength,c.value):c.value;break;case"email":switch(r.emailStrategy){case"format:email":_n(i,"email",c.message,r);break;case"format:idn-email":_n(i,"idn-email",c.message,r);break;case"pattern:zod":Yt(i,wn.email,c.message,r);break}break;case"url":_n(i,"uri",c.message,r);break;case"uuid":_n(i,"uuid",c.message,r);break;case"regex":Yt(i,c.regex,c.message,r);break;case"cuid":Yt(i,wn.cuid,c.message,r);break;case"cuid2":Yt(i,wn.cuid2,c.message,r);break;case"startsWith":Yt(i,RegExp(`^${pi(c.value,r)}`),c.message,r);break;case"endsWith":Yt(i,RegExp(`${pi(c.value,r)}$`),c.message,r);break;case"datetime":_n(i,"date-time",c.message,r);break;case"date":_n(i,"date",c.message,r);break;case"time":_n(i,"time",c.message,r);break;case"duration":_n(i,"duration",c.message,r);break;case"length":i.minLength=typeof i.minLength=="number"?Math.max(i.minLength,c.value):c.value,i.maxLength=typeof i.maxLength=="number"?Math.min(i.maxLength,c.value):c.value;break;case"includes":{Yt(i,RegExp(pi(c.value,r)),c.message,r);break}case"ip":{c.version!=="v6"&&_n(i,"ipv4",c.message,r),c.version!=="v4"&&_n(i,"ipv6",c.message,r);break}case"base64url":Yt(i,wn.base64url,c.message,r);break;case"jwt":Yt(i,wn.jwt,c.message,r);break;case"cidr":{c.version!=="v6"&&Yt(i,wn.ipv4Cidr,c.message,r),c.version!=="v4"&&Yt(i,wn.ipv6Cidr,c.message,r);break}case"emoji":Yt(i,wn.emoji(),c.message,r);break;case"ulid":{Yt(i,wn.ulid,c.message,r);break}case"base64":{switch(r.base64Strategy){case"format:binary":{_n(i,"binary",c.message,r);break}case"contentEncoding:base64":{i.contentEncoding="base64";break}case"pattern:zod":{Yt(i,wn.base64,c.message,r);break}}break}case"nanoid":Yt(i,wn.nanoid,c.message,r)}return i}function pi(t,r){return r.patternStrategy==="escape"?Dm(t):t}var Mm=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Dm(t){let r="";for(let i=0;i<t.length;i++)Mm.has(t[i])||(r+="\\"),r+=t[i];return r}function _n(t,r,i,c){var d;t.format||(d=t.anyOf)!=null&&d.some(f=>f.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:r,...i&&c.errorMessages&&{errorMessage:{format:i}}})):t.format=r}function Yt(t,r,i,c){var d;t.pattern||(d=t.allOf)!=null&&d.some(f=>f.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:Na(r,c),...i&&c.errorMessages&&{errorMessage:{pattern:i}}})):t.pattern=Na(r,c)}function Na(t,r){var i;if(!r.applyRegexFlags||!t.flags)return t.source;const c={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},d=c.i?t.source.toLowerCase():t.source;let f="",m=!1,x=!1,v=!1;for(let g=0;g<d.length;g++){if(m){f+=d[g],m=!1;continue}if(c.i){if(x){if(d[g].match(/[a-z]/)){v?(f+=d[g],f+=`${d[g-2]}-${d[g]}`.toUpperCase(),v=!1):d[g+1]==="-"&&((i=d[g+2])!=null&&i.match(/[a-z]/))?(f+=d[g],v=!0):f+=`${d[g]}${d[g].toUpperCase()}`;continue}}else if(d[g].match(/[a-z]/)){f+=`[${d[g]}${d[g].toUpperCase()}]`;continue}}if(c.m){if(d[g]==="^"){f+=`(^|(?<=[\r
42
42
  ]))`;continue}else if(d[g]==="$"){f+=`($|(?=[\r
43
43
  ]))`;continue}}if(c.s&&d[g]==="."){f+=x?`${d[g]}\r
44
44
  `:`[${d[g]}\r
45
- ]`;continue}f+=d[g],d[g]==="\\"?m=!0:x&&d[g]==="]"?x=!1:!x&&d[g]==="["&&(x=!0)}try{new RegExp(f)}catch{return console.warn(`Could not convert regex pattern at ${r.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return f}function pu(t,r){var i,c,d,f,m,x;const v={type:"object",additionalProperties:(i=ct(t.valueType._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]}))!=null?i:r.allowedAdditionalProperties};if(((c=t.keyType)==null?void 0:c._def.typeName)===je.ZodString&&((d=t.keyType._def.checks)!=null&&d.length)){const{type:g,...E}=hu(t.keyType._def,r);return{...v,propertyNames:E}}else{if(((f=t.keyType)==null?void 0:f._def.typeName)===je.ZodEnum)return{...v,propertyNames:{enum:t.keyType._def.values}};if(((m=t.keyType)==null?void 0:m._def.typeName)===je.ZodBranded&&t.keyType._def.type._def.typeName===je.ZodString&&((x=t.keyType._def.type._def.checks)!=null&&x.length)){const{type:g,...E}=du(t.keyType._def,r);return{...v,propertyNames:E}}}return v}function Pm(t,r){if(r.mapStrategy==="record")return pu(t,r);const i=ct(t.keyType._def,{...r,currentPath:[...r.currentPath,"items","items","0"]})||fn(),c=ct(t.valueType._def,{...r,currentPath:[...r.currentPath,"items","items","1"]})||fn();return{type:"array",maxItems:125,items:{type:"array",items:[i,c],minItems:2,maxItems:2}}}function Bm(t){const r=t.values,c=Object.keys(t.values).filter(f=>typeof r[r[f]]!="number").map(f=>r[f]),d=Array.from(new Set(c.map(f=>typeof f)));return{type:d.length===1?d[0]==="string"?"string":"number":["string","number"],enum:c}}function Lm(){return{not:fn()}}function Fm(){return{type:"null"}}var Ni={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Um(t,r){const i=t.options instanceof Map?Array.from(t.options.values()):t.options;if(i.every(c=>c._def.typeName in Ni&&(!c._def.checks||!c._def.checks.length))){const c=i.reduce((d,f)=>{const m=Ni[f._def.typeName];return m&&!d.includes(m)?[...d,m]:d},[]);return{type:c.length>1?c:c[0]}}else if(i.every(c=>c._def.typeName==="ZodLiteral"&&!c.description)){const c=i.reduce((d,f)=>{const m=typeof f._def.value;switch(m){case"string":case"number":case"boolean":return[...d,m];case"bigint":return[...d,"integer"];case"object":if(f._def.value===null)return[...d,"null"];case"symbol":case"undefined":case"function":default:return d}},[]);if(c.length===i.length){const d=c.filter((f,m,x)=>x.indexOf(f)===m);return{type:d.length>1?d:d[0],enum:i.reduce((f,m)=>f.includes(m._def.value)?f:[...f,m._def.value],[])}}}else if(i.every(c=>c._def.typeName==="ZodEnum"))return{type:"string",enum:i.reduce((c,d)=>[...c,...d._def.values.filter(f=>!c.includes(f))],[])};return zm(t,r)}var zm=(t,r)=>{const i=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((c,d)=>ct(c._def,{...r,currentPath:[...r.currentPath,"anyOf",`${d}`]})).filter(c=>!!c&&(!r.strictUnions||typeof c=="object"&&Object.keys(c).length>0));return i.length?{anyOf:i}:void 0};function Vm(t,r){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[Ni[t.innerType._def.typeName],"null"]};const i=ct(t.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","0"]});return i&&{anyOf:[i,{type:"null"}]}}function Zm(t){const r={type:"number"};if(!t.checks)return r;for(const i of t.checks)switch(i.kind){case"int":r.type="integer";break;case"min":i.inclusive?r.minimum=i.value:r.exclusiveMinimum=i.value;break;case"max":i.inclusive?r.maximum=i.value:r.exclusiveMaximum=i.value;break;case"multipleOf":r.multipleOf=i.value;break}return r}function $m(t,r){const i={type:"object",properties:{}},c=[],d=t.shape();for(const m in d){let x=d[m];if(x===void 0||x._def===void 0)continue;const v=Hm(x),g=ct(x._def,{...r,currentPath:[...r.currentPath,"properties",m],propertyPath:[...r.currentPath,"properties",m]});g!==void 0&&(i.properties[m]=g,v||c.push(m))}c.length&&(i.required=c);const f=jm(t,r);return f!==void 0&&(i.additionalProperties=f),i}function jm(t,r){if(t.catchall._def.typeName!=="ZodNever")return ct(t.catchall._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return r.allowedAdditionalProperties;case"strict":return r.rejectedAdditionalProperties;case"strip":return r.removeAdditionalStrategy==="strict"?r.allowedAdditionalProperties:r.rejectedAdditionalProperties}}function Hm(t){try{return t.isOptional()}catch{return!0}}var Wm=(t,r)=>{var i;if(r.currentPath.toString()===((i=r.propertyPath)==null?void 0:i.toString()))return ct(t.innerType._def,r);const c=ct(t.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","1"]});return c?{anyOf:[{not:fn()},c]}:fn()},Gm=(t,r)=>{if(r.pipeStrategy==="input")return ct(t.in._def,r);if(r.pipeStrategy==="output")return ct(t.out._def,r);const i=ct(t.in._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),c=ct(t.out._def,{...r,currentPath:[...r.currentPath,"allOf",i?"1":"0"]});return{allOf:[i,c].filter(d=>d!==void 0)}};function qm(t,r){return ct(t.type._def,r)}function Xm(t,r){const c={type:"array",uniqueItems:!0,items:ct(t.valueType._def,{...r,currentPath:[...r.currentPath,"items"]})};return t.minSize&&(c.minItems=t.minSize.value),t.maxSize&&(c.maxItems=t.maxSize.value),c}function Ym(t,r){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((i,c)=>ct(i._def,{...r,currentPath:[...r.currentPath,"items",`${c}`]})).reduce((i,c)=>c===void 0?i:[...i,c],[]),additionalItems:ct(t.rest._def,{...r,currentPath:[...r.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((i,c)=>ct(i._def,{...r,currentPath:[...r.currentPath,"items",`${c}`]})).reduce((i,c)=>c===void 0?i:[...i,c],[])}}function Km(){return{not:fn()}}function Jm(){return fn()}var Qm=(t,r)=>ct(t.innerType._def,r),eg=(t,r,i)=>{switch(r){case je.ZodString:return hu(t,i);case je.ZodNumber:return Zm(t);case je.ZodObject:return $m(t,i);case je.ZodBigInt:return bm(t);case je.ZodBoolean:return Am();case je.ZodDate:return fu(t,i);case je.ZodUndefined:return Km();case je.ZodNull:return Fm();case je.ZodArray:return Cm(t,i);case je.ZodUnion:case je.ZodDiscriminatedUnion:return Um(t,i);case je.ZodIntersection:return km(t,i);case je.ZodTuple:return Ym(t,i);case je.ZodRecord:return pu(t,i);case je.ZodLiteral:return Rm(t);case je.ZodEnum:return Nm(t);case je.ZodNativeEnum:return Bm(t);case je.ZodNullable:return Vm(t,i);case je.ZodOptional:return Wm(t,i);case je.ZodMap:return Pm(t,i);case je.ZodSet:return Xm(t,i);case je.ZodLazy:return()=>t.getter()._def;case je.ZodPromise:return qm(t,i);case je.ZodNaN:case je.ZodNever:return Lm();case je.ZodEffects:return Tm(t,i);case je.ZodAny:return fn();case je.ZodUnknown:return Jm();case je.ZodDefault:return Sm(t,i);case je.ZodBranded:return du(t,i);case je.ZodReadonly:return Qm(t,i);case je.ZodCatch:return Em(t,i);case je.ZodPipeline:return Gm(t,i);case je.ZodFunction:case je.ZodVoid:case je.ZodSymbol:return;default:return(c=>{})()}},tg=(t,r)=>{let i=0;for(;i<t.length&&i<r.length&&t[i]===r[i];i++);return[(t.length-i).toString(),...r.slice(i)].join("/")};function ct(t,r,i=!1){var c;const d=r.seen.get(t);if(r.override){const v=(c=r.override)==null?void 0:c.call(r,t,r,d,i);if(v!==_m)return v}if(d&&!i){const v=ng(d,r);if(v!==void 0)return v}const f={def:t,path:r.currentPath,jsonSchema:void 0};r.seen.set(t,f);const m=eg(t,t.typeName,r),x=typeof m=="function"?ct(m(),r):m;if(x&&rg(t,r,x),r.postProcess){const v=r.postProcess(x,t,r);return f.jsonSchema=x,v}return f.jsonSchema=x,x}var ng=(t,r)=>{switch(r.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:tg(r.currentPath,t.path)};case"none":case"seen":return t.path.length<r.currentPath.length&&t.path.every((i,c)=>r.currentPath[c]===i)?(console.warn(`Recursive reference detected at ${r.currentPath.join("/")}! Defaulting to any`),fn()):r.$refStrategy==="seen"?fn():void 0}},rg=(t,r,i)=>(t.description&&(i.description=t.description),i),og=t=>{const r=vm(t),i=r.name!==void 0?[...r.basePath,r.definitionPath,r.name]:r.basePath;return{...r,currentPath:i,propertyPath:void 0,seen:new Map(Object.entries(r.definitions).map(([c,d])=>[d._def,{def:d._def,path:[...r.basePath,r.definitionPath,c],jsonSchema:void 0}]))}},ig=(t,r)=>{var i;const c=og(r);let d=typeof r=="object"&&r.definitions?Object.entries(r.definitions).reduce((g,[E,A])=>{var D;return{...g,[E]:(D=ct(A._def,{...c,currentPath:[...c.basePath,c.definitionPath,E]},!0))!=null?D:fn()}},{}):void 0;const f=typeof r=="string"?r:r?.nameStrategy==="title"?void 0:r?.name,m=(i=ct(t._def,f===void 0?c:{...c,currentPath:[...c.basePath,c.definitionPath,f]},!1))!=null?i:fn(),x=typeof r=="object"&&r.name!==void 0&&r.nameStrategy==="title"?r.name:void 0;x!==void 0&&(m.title=x);const v=f===void 0?d?{...m,[c.definitionPath]:d}:m:{$ref:[...c.$refStrategy==="relative"?[]:c.basePath,c.definitionPath,f].join("/"),[c.definitionPath]:{...d,[f]:m}};return v.$schema="http://json-schema.org/draft-07/schema#",v},Oi=Symbol.for("vercel.ai.schema");function Fe(t){let r;return()=>(r==null&&(r=t()),r)}function Vo(t,{validate:r}={}){return{[Oi]:!0,_type:void 0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:r}}function sg(t){return typeof t=="object"&&t!==null&&Oi in t&&t[Oi]===!0&&"jsonSchema"in t&&"validate"in t}function ag(t){return t==null?Vo({type:"object",properties:{},additionalProperties:!1}):sg(t)?t:"~standard"in t?t["~standard"].vendor==="zod"?Le(t):lg(t):t()}function lg(t){return Vo(()=>Yi(t["~standard"].jsonSchema.input({target:"draft-07"})),{validate:async r=>{const i=await t["~standard"].validate(r);return"value"in i?{success:!0,value:i.value}:{success:!1,error:new no({value:r,cause:i.issues})}}})}function cg(t,r){var i;const c=(i=void 0)!=null?i:!1;return Vo(()=>ig(t,{$refStrategy:c?"root":"none"}),{validate:async d=>{const f=await t.safeParseAsync(d);return f.success?{success:!0,value:f.data}:{success:!1,error:f.error}}})}function ug(t,r){var i;const c=(i=void 0)!=null?i:!1;return Vo(()=>Yi(Uf(t,{target:"draft-7",io:"input",reused:c?"ref":"inline"})),{validate:async d=>{const f=await vc(t,d);return f.success?{success:!0,value:f.data}:{success:!1,error:f.error}}})}function dg(t){return"_zod"in t}function Le(t,r){return dg(t)?ug(t):cg(t)}async function Dt({value:t,schema:r,context:i}){const c=await Ki({value:t,schema:r,context:i});if(!c.success)throw no.wrap({value:t,cause:c.error,context:i});return c.value}async function Ki({value:t,schema:r,context:i}){const c=ag(r);try{if(c.validate==null)return{success:!0,value:t,rawValue:t};const d=await c.validate(t);return d.success?{success:!0,value:d.value,rawValue:t}:{success:!1,error:no.wrap({value:t,cause:d.error,context:i}),rawValue:t}}catch(d){return{success:!1,error:no.wrap({value:t,cause:d,context:i}),rawValue:t}}}async function mu({text:t,schema:r}){try{const i=uu(t);return r==null?i:Dt({value:i,schema:r})}catch(i){throw Do.isInstance(i)||no.isInstance(i)?i:new Do({text:t,cause:i})}}async function gu({text:t,schema:r}){try{const i=uu(t);return r==null?{success:!0,value:i,rawValue:i}:await Ki({value:i,schema:r})}catch(i){return{success:!1,error:Do.isInstance(i)?i:new Do({text:t,cause:i}),rawValue:void 0}}}function fg({stream:t,schema:r}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new ec).pipeThrough(new TransformStream({async transform({data:i},c){i!=="[DONE]"&&c.enqueue(await gu({text:i,schema:r}))}}))}async function An({provider:t,providerOptions:r,schema:i}){if(r?.[t]==null)return;const c=await Ki({value:r[t],schema:i});if(!c.success)throw new Vc({argument:"providerOptions",message:`invalid ${t} provider options`,cause:c.error});return c.value}var hg=()=>globalThis.fetch,Zn=async({url:t,headers:r,body:i,failedResponseHandler:c,successfulResponseHandler:d,abortSignal:f,fetch:m})=>yu({url:t,headers:{"Content-Type":"application/json",...r},body:{content:JSON.stringify(i),values:i},failedResponseHandler:c,successfulResponseHandler:d,abortSignal:f,fetch:m}),xu=async({url:t,headers:r,formData:i,failedResponseHandler:c,successfulResponseHandler:d,abortSignal:f,fetch:m})=>yu({url:t,headers:r,body:{content:i,values:Object.fromEntries(i.entries())},failedResponseHandler:c,successfulResponseHandler:d,abortSignal:f,fetch:m}),yu=async({url:t,headers:r={},body:i,successfulResponseHandler:c,failedResponseHandler:d,abortSignal:f,fetch:m=hg()})=>{try{const x=await m(t,{method:"POST",headers:cu(r,`ai-sdk/provider-utils/${hm}`,dm()),body:i.content,signal:f}),v=ao(x);if(!x.ok){let g;try{g=await d({response:x,url:t,requestBodyValues:i.values})}catch(E){throw Ti(E)||Kt.isInstance(E)?E:new Kt({message:"Failed to process error response",cause:E,statusCode:x.status,url:t,responseHeaders:v,requestBodyValues:i.values})}throw g.value}try{return await c({response:x,url:t,requestBodyValues:i.values})}catch(g){throw g instanceof Error&&(Ti(g)||Kt.isInstance(g))?g:new Kt({message:"Failed to process successful response",cause:g,statusCode:x.status,url:t,responseHeaders:v,requestBodyValues:i.values})}}catch(x){throw um({error:x,url:t,requestBodyValues:i.values})}};function pg({id:t,inputSchema:r}){return({execute:i,outputSchema:c,needsApproval:d,toModelOutput:f,onInputStart:m,onInputDelta:x,onInputAvailable:v,...g})=>({type:"provider",id:t,args:g,inputSchema:r,outputSchema:c,execute:i,needsApproval:d,toModelOutput:f,onInputStart:m,onInputDelta:x,onInputAvailable:v})}function Dn({id:t,inputSchema:r,outputSchema:i,supportsDeferredResults:c}){return({execute:d,needsApproval:f,toModelOutput:m,onInputStart:x,onInputDelta:v,onInputAvailable:g,...E})=>({type:"provider",id:t,args:E,inputSchema:r,outputSchema:i,execute:d,needsApproval:f,toModelOutput:m,onInputStart:x,onInputDelta:v,onInputAvailable:g,supportsDeferredResults:c})}var mg=new TextDecoder;async function wu({response:t,url:r}){return mg.decode(await au({response:t,url:r}))}var gg=({errorSchema:t,errorToMessage:r,isRetryable:i})=>async({response:c,url:d,requestBodyValues:f})=>{const m=await wu({response:c,url:d}),x=ao(c);if(m.trim()==="")return{responseHeaders:x,value:new Kt({message:c.statusText,url:d,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,isRetryable:i?.(c)})};try{const v=await mu({text:m,schema:t});return{responseHeaders:x,value:new Kt({message:r(v),url:d,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,data:v,isRetryable:i?.(c,v)})}}catch{return{responseHeaders:x,value:new Kt({message:c.statusText,url:d,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,isRetryable:i?.(c)})}}},Ji=t=>async({response:r})=>{const i=ao(r);if(r.body==null)throw new Bp({});return{responseHeaders:i,value:fg({stream:r.body,schema:t})}},mr=t=>async({response:r,url:i,requestBodyValues:c})=>{const d=await wu({response:r,url:i}),f=await gu({text:d,schema:t}),m=ao(r);if(!f.success)throw new Kt({message:"Invalid JSON response",cause:f.error,statusCode:r.status,responseHeaders:m,responseBody:d,url:i,requestBodyValues:c});return{responseHeaders:m,value:f.value,rawValue:f.rawValue}},xg=()=>async({response:t,url:r,requestBodyValues:i})=>{const c=ao(t);if(!t.body)throw new Kt({message:"Response body is empty",url:r,requestBodyValues:i,statusCode:t.status,responseHeaders:c,responseBody:void 0});try{const d=await t.arrayBuffer();return{responseHeaders:c,value:new Uint8Array(d)}}catch(d){throw new Kt({message:"Failed to read response as array buffer",url:r,requestBodyValues:i,statusCode:t.status,responseHeaders:c,responseBody:void 0,cause:d})}};function yg(t){return t?.replace(/\/$/,"")}var Qi=N({error:N({message:w(),type:w().nullish(),param:xr().nullish(),code:st([w(),j()]).nullish()})}),En=gg({errorSchema:Qi,errorToMessage:t=>t.error.message});function _u(t){const r=t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat"),i=t.startsWith("gpt-4")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-nano")&&!t.startsWith("gpt-5-chat")&&!t.startsWith("gpt-5.4-nano")||t.startsWith("o3")||t.startsWith("o4-mini"),c=t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat"),d=t.startsWith("gpt-5.1")||t.startsWith("gpt-5.2")||t.startsWith("gpt-5.3")||t.startsWith("gpt-5.4")||t.startsWith("gpt-5.5")||t.startsWith("gpt-5.6");return{supportsFlexProcessing:r,supportsPriorityProcessing:i,isReasoningModel:c,systemMessageMode:c?"developer":"system",supportsNonReasoningParameters:d}}async function es({stream:t,getError:r,isOutputChunk:i,url:c,requestBodyValues:d,responseHeaders:f}){const[m,x]=t.tee(),v=m.getReader();try{for(;;){const g=await v.read();if(g.done)return x;const E=g.value;if(!E.success)return x;const A=r(E.value);if(A!=null)throw x.cancel().catch(()=>{}),wg({frame:A,url:c,requestBodyValues:d,responseHeaders:f});if(i(E.value))return x}}finally{v.cancel().catch(()=>{}),v.releaseLock()}}function wg({frame:t,url:r,requestBodyValues:i,responseHeaders:c}){var d;const f=_g(t);return new Kt({message:(d=f?.message)!=null?d:"OpenAI stream failed before any output was generated",url:r,requestBodyValues:i,statusCode:f==null?500:vg(f),responseHeaders:c,responseBody:JSON.stringify(t),data:t})}function _g(t){var r;const i=jr(t);if(i==null)return;if(i.type==="response.failed"){const d=jr(i.response),f=jr(d?.error);return typeof f?.message=="string"?{message:f.message,code:Oa(f.code),type:"response.failed",frame:t}:void 0}const c=(r=jr(i.error))!=null?r:i;return typeof c.message=="string"&&(jr(i.error)!=null||typeof c.type=="string"||"code"in c||"param"in c)?{message:c.message,code:Oa(c.code),type:typeof c.type=="string"?c.type:void 0,frame:t}:void 0}function vg(t){if(typeof t.code=="number"&&ka(t.code))return t.code;if(typeof t.code=="string"&&/^\d{3}$/.test(t.code)){const i=Number(t.code);if(ka(i))return i}const r=[t.code,t.type].filter(i=>typeof i=="string"||typeof i=="number").join(" ").toLowerCase();return["insufficient_quota","rate_limit"].some(i=>r.includes(i))?429:r.includes("authentication")?401:r.includes("permission")?403:r.includes("not_found")?404:["invalid","bad_request","context_length"].some(i=>r.includes(i))?400:r.includes("overload")?503:r.includes("timeout")?504:500}function jr(t){return typeof t=="object"&&t!=null?t:void 0}function Oa(t){return typeof t=="string"||typeof t=="number"?t:void 0}function ka(t){return Number.isInteger(t)&&t>=400&&t<=599}function Ra(t){var r,i,c,d,f,m,x,v;if(t==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const g=(r=t.prompt_tokens)!=null?r:0,E=(i=t.completion_tokens)!=null?i:0,A=(d=(c=t.prompt_tokens_details)==null?void 0:c.cached_tokens)!=null?d:0,D=(m=(f=t.prompt_tokens_details)==null?void 0:f.cache_write_tokens)!=null?m:void 0,T=(v=(x=t.completion_tokens_details)==null?void 0:x.reasoning_tokens)!=null?v:0;return{inputTokens:{total:g,noCache:g-A-(D??0),cacheRead:A,cacheWrite:D},outputTokens:{total:E,text:E-T,reasoning:T},raw:t}}function Cg(t){return JSON.stringify(t===void 0?{}:t)}function Un(t){var r;return(r=t?.openai)==null?void 0:r.promptCacheBreakpoint}function bg({prompt:t,systemMessageMode:r="system"}){var i,c;const d=[],f=[];for(const{role:m,content:x,providerOptions:v}of t)switch(m){case"system":{switch(r){case"system":{const g=Un(v);d.push({role:"system",content:g==null?x:[{type:"text",text:x,prompt_cache_breakpoint:g}]});break}case"developer":{const g=Un(v);d.push({role:"developer",content:g==null?x:[{type:"text",text:x,prompt_cache_breakpoint:g}]});break}case"remove":{f.push({type:"other",message:"system messages are removed for this model"});break}default:{const g=r;throw new Error(`Unsupported system message mode: ${g}`)}}break}case"user":{if(x.length===1&&x[0].type==="text"&&Un(x[0].providerOptions)==null){d.push({role:"user",content:x[0].text});break}d.push({role:"user",content:x.map((g,E)=>{var A,D,T;switch(g.type){case"text":{const S=Un(g.providerOptions);return{type:"text",text:g.text,...S!=null&&{prompt_cache_breakpoint:S}}}case"file":{const S=Un(g.providerOptions);if(g.mediaType.startsWith("image/")){const P=g.mediaType==="image/*"?"image/jpeg":g.mediaType;return{type:"image_url",image_url:{url:g.data instanceof URL?g.data.toString():`data:${P};base64,${kr(g.data)}`,detail:(D=(A=g.providerOptions)==null?void 0:A.openai)==null?void 0:D.imageDetail},...S!=null&&{prompt_cache_breakpoint:S}}}else if(g.mediaType.startsWith("audio/")){if(g.data instanceof URL)throw new Mn({functionality:"audio file parts with URLs"});switch(g.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:kr(g.data),format:"wav"},...S!=null&&{prompt_cache_breakpoint:S}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:kr(g.data),format:"mp3"},...S!=null&&{prompt_cache_breakpoint:S}};default:throw new Mn({functionality:`audio content parts with media type ${g.mediaType}`})}}else if(g.mediaType==="application/pdf"){if(g.data instanceof URL)throw new Mn({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof g.data=="string"&&g.data.startsWith("file-")?{file_id:g.data}:{filename:(T=g.filename)!=null?T:`part-${E}.pdf`,file_data:`data:application/pdf;base64,${kr(g.data)}`},...S!=null&&{prompt_cache_breakpoint:S}}}else throw new Mn({functionality:`file part media type ${g.mediaType}`})}}})});break}case"assistant":{let g="";const E=[];let A=!1;const D=[];for(const T of x)switch(T.type){case"text":{const S=Un(T.providerOptions);g+=T.text,E.push({type:"text",text:T.text,...S!=null&&{prompt_cache_breakpoint:S}}),A||(A=S!=null);break}case"tool-call":{D.push({id:T.toolCallId,type:"function",function:{name:T.toolName,arguments:Cg(T.input)}});break}}d.push({role:"assistant",content:A?E:D.length>0?g||null:g,tool_calls:D.length>0?D:void 0});break}case"tool":{for(const g of x){if(g.type==="tool-approval-response")continue;const E=g.output,A=(i=E.type==="content"?E.value.map(T=>Un(T.providerOptions)).find(T=>T!=null):Un(E.providerOptions))!=null?i:Un(g.providerOptions);let D;switch(E.type){case"text":case"error-text":D=E.value;break;case"execution-denied":D=(c=E.reason)!=null?c:"Tool call execution denied.";break;case"content":case"json":case"error-json":D=JSON.stringify(E.value);break}d.push({role:"tool",tool_call_id:g.toolCallId,content:A==null?D:[{type:"text",text:D,prompt_cache_breakpoint:A}]})}break}default:{const g=m;throw new Error(`Unsupported role: ${g}`)}}return{messages:d,warnings:f}}function mi({id:t,model:r,created:i}){return{id:t??void 0,modelId:r??void 0,timestamp:i?new Date(i*1e3):void 0}}function Ma(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var Ag=Fe(()=>Le(N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(N({message:N({role:Y("assistant").nullish(),content:w().nullish(),tool_calls:ue(N({id:w().nullish(),type:Y("function"),function:N({name:w(),arguments:w()})})).nullish(),annotations:ue(N({type:Y("url_citation"),url_citation:N({start_index:j(),end_index:j(),url:w(),title:w()})})).nullish()}),index:j(),logprobs:N({content:ue(N({token:w(),logprob:j(),top_logprobs:ue(N({token:w(),logprob:j()}))})).nullish()}).nullish(),finish_reason:w().nullish()})),usage:N({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:N({cached_tokens:j().nullish(),cache_write_tokens:j().nullish()}).nullish(),completion_tokens_details:N({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish()}))),Eg=Fe(()=>Le(st([N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(N({delta:N({role:Ae(["assistant"]).nullish(),content:w().nullish(),tool_calls:ue(N({index:j(),id:w().nullish(),type:Y("function").nullish(),function:N({name:w().nullish(),arguments:w().nullish()})})).nullish(),annotations:ue(N({type:Y("url_citation"),url_citation:N({start_index:j(),end_index:j(),url:w(),title:w()})})).nullish()}).nullish(),logprobs:N({content:ue(N({token:w(),logprob:j(),top_logprobs:ue(N({token:w(),logprob:j()}))})).nullish()}).nullish(),finish_reason:w().nullish(),index:j()})),usage:N({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:N({cached_tokens:j().nullish(),cache_write_tokens:j().nullish()}).nullish(),completion_tokens_details:N({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish()}),Qi]))),Ig=Fe(()=>Le(N({logitBias:wt(qh(),j()).optional(),logprobs:st([Mt(),j()]).optional(),parallelToolCalls:Mt().optional(),user:w().optional(),reasoningEffort:Ae(["none","minimal","low","medium","high","xhigh","max"]).optional(),maxCompletionTokens:j().optional(),store:Mt().optional(),metadata:wt(w().max(64),w().max(512)).optional(),prediction:wt(w(),xr()).optional(),serviceTier:Ae(["auto","flex","priority","default"]).optional(),strictJsonSchema:Mt().optional(),textVerbosity:Ae(["low","medium","high"]).optional(),promptCacheKey:w().optional(),promptCacheOptions:N({mode:Ae(["implicit","explicit"]).optional(),ttl:Y("30m").optional()}).optional(),promptCacheRetention:Ae(["in_memory","24h"]).optional(),safetyIdentifier:w().optional(),systemMessageMode:Ae(["system","developer","remove"]).optional(),forceReasoning:Mt().optional()})));function Sg({tools:t,toolChoice:r}){t=t?.length?t:void 0;const i=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i};const c=[];for(const f of t)switch(f.type){case"function":c.push({type:"function",function:{name:f.name,description:f.description,parameters:f.inputSchema,...f.strict!=null?{strict:f.strict}:{}}});break;default:i.push({type:"unsupported",feature:`tool type: ${f.type}`});break}if(r==null)return{tools:c,toolChoice:void 0,toolWarnings:i};const d=r.type;switch(d){case"auto":case"none":case"required":return{tools:c,toolChoice:d,toolWarnings:i};case"tool":return{tools:c,toolChoice:{type:"function",function:{name:r.toolName}},toolWarnings:i};default:{const f=d;throw new Mn({functionality:`tool choice type: ${f}`})}}}var Tg=class{constructor(t,r){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=t,this.config=r}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:r,temperature:i,topP:c,topK:d,frequencyPenalty:f,presencePenalty:m,stopSequences:x,responseFormat:v,seed:g,tools:E,toolChoice:A,providerOptions:D}){var T,S,P,M,ee;const $=[],F=(T=await An({provider:"openai",providerOptions:D,schema:Ig}))!=null?T:{},re=_u(this.modelId),Z=(S=F.forceReasoning)!=null?S:re.isReasoningModel;d!=null&&$.push({type:"unsupported",feature:"topK"});const{messages:B,warnings:L}=bg({prompt:t,systemMessageMode:(P=F.systemMessageMode)!=null?P:Z?"developer":re.systemMessageMode});$.push(...L);const W=(M=F.strictJsonSchema)!=null?M:!0,z={model:this.modelId,logit_bias:F.logitBias,logprobs:F.logprobs===!0||typeof F.logprobs=="number"?!0:void 0,top_logprobs:typeof F.logprobs=="number"?F.logprobs:typeof F.logprobs=="boolean"&&F.logprobs?0:void 0,user:F.user,parallel_tool_calls:F.parallelToolCalls,max_tokens:r,temperature:i,top_p:c,frequency_penalty:f,presence_penalty:m,response_format:v?.type==="json"?v.schema!=null?{type:"json_schema",json_schema:{schema:v.schema,strict:W,name:(ee=v.name)!=null?ee:"response",description:v.description}}:{type:"json_object"}:void 0,stop:x,seed:g,verbosity:F.textVerbosity,max_completion_tokens:F.maxCompletionTokens,store:F.store,metadata:F.metadata,prediction:F.prediction,reasoning_effort:F.reasoningEffort,service_tier:F.serviceTier,prompt_cache_key:F.promptCacheKey,prompt_cache_options:F.promptCacheOptions,prompt_cache_retention:F.promptCacheRetention,safety_identifier:F.safetyIdentifier,messages:B};Z?((F.reasoningEffort!=="none"||!re.supportsNonReasoningParameters)&&(z.temperature!=null&&(z.temperature=void 0,$.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),z.top_p!=null&&(z.top_p=void 0,$.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),z.logprobs!=null&&(z.logprobs=void 0,$.push({type:"other",message:"logprobs is not supported for reasoning models"}))),z.frequency_penalty!=null&&(z.frequency_penalty=void 0,$.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),z.presence_penalty!=null&&(z.presence_penalty=void 0,$.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),z.logit_bias!=null&&(z.logit_bias=void 0,$.push({type:"other",message:"logitBias is not supported for reasoning models"})),z.top_logprobs!=null&&(z.top_logprobs=void 0,$.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),z.max_tokens!=null&&(z.max_completion_tokens==null&&(z.max_completion_tokens=z.max_tokens),z.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&z.temperature!=null&&(z.temperature=void 0,$.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),F.serviceTier==="flex"&&!re.supportsFlexProcessing&&($.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),z.service_tier=void 0),F.serviceTier==="priority"&&!re.supportsPriorityProcessing&&($.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),z.service_tier=void 0);const{tools:we,toolChoice:G,toolWarnings:me}=Sg({tools:E,toolChoice:A});return{args:{...z,tools:we,tool_choice:G},warnings:[...$,...me]}}async doGenerate(t){var r,i,c,d,f,m,x;const{args:v,warnings:g}=await this.getArgs(t),{responseHeaders:E,value:A,rawValue:D}=await Zn({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:bn(this.config.headers(),t.headers),body:v,failedResponseHandler:En,successfulResponseHandler:mr(Ag),abortSignal:t.abortSignal,fetch:this.config.fetch}),T=A.choices[0],S=[],P=T.message.content;P!=null&&P.length>0&&S.push({type:"text",text:P});for(const $ of(r=T.message.tool_calls)!=null?r:[])S.push({type:"tool-call",toolCallId:(i=$.id)!=null?i:rn(),toolName:$.function.name,input:$.function.arguments});for(const $ of(c=T.message.annotations)!=null?c:[])S.push({type:"source",sourceType:"url",id:rn(),url:$.url_citation.url,title:$.url_citation.title});const M=(d=A.usage)==null?void 0:d.completion_tokens_details;(f=A.usage)==null||f.prompt_tokens_details;const ee={openai:{}};return M?.accepted_prediction_tokens!=null&&(ee.openai.acceptedPredictionTokens=M?.accepted_prediction_tokens),M?.rejected_prediction_tokens!=null&&(ee.openai.rejectedPredictionTokens=M?.rejected_prediction_tokens),((m=T.logprobs)==null?void 0:m.content)!=null&&(ee.openai.logprobs=T.logprobs.content),{content:S,finishReason:{unified:Ma(T.finish_reason),raw:(x=T.finish_reason)!=null?x:void 0},usage:Ra(A.usage),request:{body:v},response:{...mi(A),headers:E,body:D},warnings:g,providerMetadata:ee}}async doStream(t){const{args:r,warnings:i}=await this.getArgs(t),c={...r,stream:!0,stream_options:{include_usage:!0}},d=this.config.url({path:"/chat/completions",modelId:this.modelId}),{responseHeaders:f,value:m}=await Zn({url:d,headers:bn(this.config.headers(),t.headers),body:c,failedResponseHandler:En,successfulResponseHandler:Ji(Eg),abortSignal:t.abortSignal,fetch:this.config.fetch}),x=await es({stream:m,getError:P=>"error"in P?P.error:void 0,isOutputChunk:Ng,url:d,requestBodyValues:c,responseHeaders:f}),v=[];let g={unified:"other",raw:void 0},E,A=!1,D=!1;const T={openai:{}};return{stream:x.pipeThrough(new TransformStream({start(P){P.enqueue({type:"stream-start",warnings:i})},transform(P,M){var ee,$,F,re,Z,B,L,W,z,we,G,me,fe;if(t.includeRawChunks&&M.enqueue({type:"raw",rawValue:P.rawValue}),!P.success){g={unified:"error",raw:void 0},M.enqueue({type:"error",error:P.error});return}const te=P.value;if("error"in te){g={unified:"error",raw:void 0},M.enqueue({type:"error",error:te.error});return}if(!A){const le=mi(te);Object.values(le).some(Boolean)&&(A=!0,M.enqueue({type:"response-metadata",...mi(te)}))}te.usage!=null&&(E=te.usage,((ee=te.usage.completion_tokens_details)==null?void 0:ee.accepted_prediction_tokens)!=null&&(T.openai.acceptedPredictionTokens=($=te.usage.completion_tokens_details)==null?void 0:$.accepted_prediction_tokens),((F=te.usage.completion_tokens_details)==null?void 0:F.rejected_prediction_tokens)!=null&&(T.openai.rejectedPredictionTokens=(re=te.usage.completion_tokens_details)==null?void 0:re.rejected_prediction_tokens));const q=te.choices[0];if(q?.finish_reason!=null&&(g={unified:Ma(q.finish_reason),raw:q.finish_reason}),((Z=q?.logprobs)==null?void 0:Z.content)!=null&&(T.openai.logprobs=q.logprobs.content),q?.delta==null)return;const ke=q.delta;if(ke.content!=null&&(D||(M.enqueue({type:"text-start",id:"0"}),D=!0),M.enqueue({type:"text-delta",id:"0",delta:ke.content})),ke.tool_calls!=null)for(const le of ke.tool_calls){const Te=le.index;if(v[Te]==null){if(le.type!=null&&le.type!=="function")throw new fi({data:le,message:"Expected 'function' type."});if(le.id==null)throw new fi({data:le,message:"Expected 'id' to be a string."});if(((B=le.function)==null?void 0:B.name)==null)throw new fi({data:le,message:"Expected 'function.name' to be a string."});M.enqueue({type:"tool-input-start",id:le.id,toolName:le.function.name}),v[Te]={id:le.id,type:"function",function:{name:le.function.name,arguments:(L=le.function.arguments)!=null?L:""},hasFinished:!1};const xe=v[Te];((W=xe.function)==null?void 0:W.name)!=null&&((z=xe.function)==null?void 0:z.arguments)!=null&&xe.function.arguments.length>0&&M.enqueue({type:"tool-input-delta",id:xe.id,delta:xe.function.arguments});continue}const Je=v[Te];Je.hasFinished||(((we=le.function)==null?void 0:we.arguments)!=null&&(Je.function.arguments+=(me=(G=le.function)==null?void 0:G.arguments)!=null?me:""),M.enqueue({type:"tool-input-delta",id:Je.id,delta:(fe=le.function.arguments)!=null?fe:""}))}if(ke.annotations!=null)for(const le of ke.annotations)M.enqueue({type:"source",sourceType:"url",id:rn(),url:le.url_citation.url,title:le.url_citation.title})},flush(P){var M;D&&P.enqueue({type:"text-end",id:"0"});for(const ee of v)ee.hasFinished||(P.enqueue({type:"tool-input-end",id:ee.id}),P.enqueue({type:"tool-call",toolCallId:(M=ee.id)!=null?M:rn(),toolName:ee.function.name,input:ee.function.arguments}),ee.hasFinished=!0);P.enqueue({type:"finish",finishReason:g,usage:Ra(E),...T!=null?{providerMetadata:T}:{}})}})),request:{body:c},response:{headers:f}}}};function Ng(t){return"error"in t?!1:t.choices.some(r=>{const i=r.delta;return i?.content!=null&&i.content.length>0||i?.tool_calls!=null&&i.tool_calls.length>0||i?.annotations!=null&&i.annotations.length>0})}function Da(t){var r,i,c,d;if(t==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const f=(r=t.prompt_tokens)!=null?r:0,m=(i=t.completion_tokens)!=null?i:0;return{inputTokens:{total:(c=t.prompt_tokens)!=null?c:void 0,noCache:f,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:(d=t.completion_tokens)!=null?d:void 0,text:m,reasoning:void 0},raw:t}}function Og({prompt:t,user:r="user",assistant:i="assistant"}){let c="";t[0].role==="system"&&(c+=`${t[0].content}
45
+ ]`;continue}f+=d[g],d[g]==="\\"?m=!0:x&&d[g]==="]"?x=!1:!x&&d[g]==="["&&(x=!0)}try{new RegExp(f)}catch{return console.warn(`Could not convert regex pattern at ${r.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return f}function pu(t,r){var i,c,d,f,m,x;const v={type:"object",additionalProperties:(i=ct(t.valueType._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]}))!=null?i:r.allowedAdditionalProperties};if(((c=t.keyType)==null?void 0:c._def.typeName)===je.ZodString&&((d=t.keyType._def.checks)!=null&&d.length)){const{type:g,...E}=hu(t.keyType._def,r);return{...v,propertyNames:E}}else{if(((f=t.keyType)==null?void 0:f._def.typeName)===je.ZodEnum)return{...v,propertyNames:{enum:t.keyType._def.values}};if(((m=t.keyType)==null?void 0:m._def.typeName)===je.ZodBranded&&t.keyType._def.type._def.typeName===je.ZodString&&((x=t.keyType._def.type._def.checks)!=null&&x.length)){const{type:g,...E}=du(t.keyType._def,r);return{...v,propertyNames:E}}}return v}function Pm(t,r){if(r.mapStrategy==="record")return pu(t,r);const i=ct(t.keyType._def,{...r,currentPath:[...r.currentPath,"items","items","0"]})||fn(),c=ct(t.valueType._def,{...r,currentPath:[...r.currentPath,"items","items","1"]})||fn();return{type:"array",maxItems:125,items:{type:"array",items:[i,c],minItems:2,maxItems:2}}}function Bm(t){const r=t.values,c=Object.keys(t.values).filter(f=>typeof r[r[f]]!="number").map(f=>r[f]),d=Array.from(new Set(c.map(f=>typeof f)));return{type:d.length===1?d[0]==="string"?"string":"number":["string","number"],enum:c}}function Lm(){return{not:fn()}}function Fm(){return{type:"null"}}var Ni={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Um(t,r){const i=t.options instanceof Map?Array.from(t.options.values()):t.options;if(i.every(c=>c._def.typeName in Ni&&(!c._def.checks||!c._def.checks.length))){const c=i.reduce((d,f)=>{const m=Ni[f._def.typeName];return m&&!d.includes(m)?[...d,m]:d},[]);return{type:c.length>1?c:c[0]}}else if(i.every(c=>c._def.typeName==="ZodLiteral"&&!c.description)){const c=i.reduce((d,f)=>{const m=typeof f._def.value;switch(m){case"string":case"number":case"boolean":return[...d,m];case"bigint":return[...d,"integer"];case"object":if(f._def.value===null)return[...d,"null"];case"symbol":case"undefined":case"function":default:return d}},[]);if(c.length===i.length){const d=c.filter((f,m,x)=>x.indexOf(f)===m);return{type:d.length>1?d:d[0],enum:i.reduce((f,m)=>f.includes(m._def.value)?f:[...f,m._def.value],[])}}}else if(i.every(c=>c._def.typeName==="ZodEnum"))return{type:"string",enum:i.reduce((c,d)=>[...c,...d._def.values.filter(f=>!c.includes(f))],[])};return zm(t,r)}var zm=(t,r)=>{const i=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((c,d)=>ct(c._def,{...r,currentPath:[...r.currentPath,"anyOf",`${d}`]})).filter(c=>!!c&&(!r.strictUnions||typeof c=="object"&&Object.keys(c).length>0));return i.length?{anyOf:i}:void 0};function Vm(t,r){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[Ni[t.innerType._def.typeName],"null"]};const i=ct(t.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","0"]});return i&&{anyOf:[i,{type:"null"}]}}function Zm(t){const r={type:"number"};if(!t.checks)return r;for(const i of t.checks)switch(i.kind){case"int":r.type="integer";break;case"min":i.inclusive?r.minimum=i.value:r.exclusiveMinimum=i.value;break;case"max":i.inclusive?r.maximum=i.value:r.exclusiveMaximum=i.value;break;case"multipleOf":r.multipleOf=i.value;break}return r}function $m(t,r){const i={type:"object",properties:{}},c=[],d=t.shape();for(const m in d){let x=d[m];if(x===void 0||x._def===void 0)continue;const v=Hm(x),g=ct(x._def,{...r,currentPath:[...r.currentPath,"properties",m],propertyPath:[...r.currentPath,"properties",m]});g!==void 0&&(i.properties[m]=g,v||c.push(m))}c.length&&(i.required=c);const f=jm(t,r);return f!==void 0&&(i.additionalProperties=f),i}function jm(t,r){if(t.catchall._def.typeName!=="ZodNever")return ct(t.catchall._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return r.allowedAdditionalProperties;case"strict":return r.rejectedAdditionalProperties;case"strip":return r.removeAdditionalStrategy==="strict"?r.allowedAdditionalProperties:r.rejectedAdditionalProperties}}function Hm(t){try{return t.isOptional()}catch{return!0}}var Wm=(t,r)=>{var i;if(r.currentPath.toString()===((i=r.propertyPath)==null?void 0:i.toString()))return ct(t.innerType._def,r);const c=ct(t.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","1"]});return c?{anyOf:[{not:fn()},c]}:fn()},Gm=(t,r)=>{if(r.pipeStrategy==="input")return ct(t.in._def,r);if(r.pipeStrategy==="output")return ct(t.out._def,r);const i=ct(t.in._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),c=ct(t.out._def,{...r,currentPath:[...r.currentPath,"allOf",i?"1":"0"]});return{allOf:[i,c].filter(d=>d!==void 0)}};function qm(t,r){return ct(t.type._def,r)}function Xm(t,r){const c={type:"array",uniqueItems:!0,items:ct(t.valueType._def,{...r,currentPath:[...r.currentPath,"items"]})};return t.minSize&&(c.minItems=t.minSize.value),t.maxSize&&(c.maxItems=t.maxSize.value),c}function Ym(t,r){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((i,c)=>ct(i._def,{...r,currentPath:[...r.currentPath,"items",`${c}`]})).reduce((i,c)=>c===void 0?i:[...i,c],[]),additionalItems:ct(t.rest._def,{...r,currentPath:[...r.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((i,c)=>ct(i._def,{...r,currentPath:[...r.currentPath,"items",`${c}`]})).reduce((i,c)=>c===void 0?i:[...i,c],[])}}function Km(){return{not:fn()}}function Jm(){return fn()}var Qm=(t,r)=>ct(t.innerType._def,r),eg=(t,r,i)=>{switch(r){case je.ZodString:return hu(t,i);case je.ZodNumber:return Zm(t);case je.ZodObject:return $m(t,i);case je.ZodBigInt:return bm(t);case je.ZodBoolean:return Am();case je.ZodDate:return fu(t,i);case je.ZodUndefined:return Km();case je.ZodNull:return Fm();case je.ZodArray:return Cm(t,i);case je.ZodUnion:case je.ZodDiscriminatedUnion:return Um(t,i);case je.ZodIntersection:return km(t,i);case je.ZodTuple:return Ym(t,i);case je.ZodRecord:return pu(t,i);case je.ZodLiteral:return Rm(t);case je.ZodEnum:return Nm(t);case je.ZodNativeEnum:return Bm(t);case je.ZodNullable:return Vm(t,i);case je.ZodOptional:return Wm(t,i);case je.ZodMap:return Pm(t,i);case je.ZodSet:return Xm(t,i);case je.ZodLazy:return()=>t.getter()._def;case je.ZodPromise:return qm(t,i);case je.ZodNaN:case je.ZodNever:return Lm();case je.ZodEffects:return Tm(t,i);case je.ZodAny:return fn();case je.ZodUnknown:return Jm();case je.ZodDefault:return Sm(t,i);case je.ZodBranded:return du(t,i);case je.ZodReadonly:return Qm(t,i);case je.ZodCatch:return Em(t,i);case je.ZodPipeline:return Gm(t,i);case je.ZodFunction:case je.ZodVoid:case je.ZodSymbol:return;default:return(c=>{})()}},tg=(t,r)=>{let i=0;for(;i<t.length&&i<r.length&&t[i]===r[i];i++);return[(t.length-i).toString(),...r.slice(i)].join("/")};function ct(t,r,i=!1){var c;const d=r.seen.get(t);if(r.override){const v=(c=r.override)==null?void 0:c.call(r,t,r,d,i);if(v!==_m)return v}if(d&&!i){const v=ng(d,r);if(v!==void 0)return v}const f={def:t,path:r.currentPath,jsonSchema:void 0};r.seen.set(t,f);const m=eg(t,t.typeName,r),x=typeof m=="function"?ct(m(),r):m;if(x&&rg(t,r,x),r.postProcess){const v=r.postProcess(x,t,r);return f.jsonSchema=x,v}return f.jsonSchema=x,x}var ng=(t,r)=>{switch(r.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:tg(r.currentPath,t.path)};case"none":case"seen":return t.path.length<r.currentPath.length&&t.path.every((i,c)=>r.currentPath[c]===i)?(console.warn(`Recursive reference detected at ${r.currentPath.join("/")}! Defaulting to any`),fn()):r.$refStrategy==="seen"?fn():void 0}},rg=(t,r,i)=>(t.description&&(i.description=t.description),i),og=t=>{const r=vm(t),i=r.name!==void 0?[...r.basePath,r.definitionPath,r.name]:r.basePath;return{...r,currentPath:i,propertyPath:void 0,seen:new Map(Object.entries(r.definitions).map(([c,d])=>[d._def,{def:d._def,path:[...r.basePath,r.definitionPath,c],jsonSchema:void 0}]))}},ig=(t,r)=>{var i;const c=og(r);let d=typeof r=="object"&&r.definitions?Object.entries(r.definitions).reduce((g,[E,A])=>{var D;return{...g,[E]:(D=ct(A._def,{...c,currentPath:[...c.basePath,c.definitionPath,E]},!0))!=null?D:fn()}},{}):void 0;const f=typeof r=="string"?r:r?.nameStrategy==="title"?void 0:r?.name,m=(i=ct(t._def,f===void 0?c:{...c,currentPath:[...c.basePath,c.definitionPath,f]},!1))!=null?i:fn(),x=typeof r=="object"&&r.name!==void 0&&r.nameStrategy==="title"?r.name:void 0;x!==void 0&&(m.title=x);const v=f===void 0?d?{...m,[c.definitionPath]:d}:m:{$ref:[...c.$refStrategy==="relative"?[]:c.basePath,c.definitionPath,f].join("/"),[c.definitionPath]:{...d,[f]:m}};return v.$schema="http://json-schema.org/draft-07/schema#",v},Oi=Symbol.for("vercel.ai.schema");function Fe(t){let r;return()=>(r==null&&(r=t()),r)}function Vo(t,{validate:r}={}){return{[Oi]:!0,_type:void 0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:r}}function sg(t){return typeof t=="object"&&t!==null&&Oi in t&&t[Oi]===!0&&"jsonSchema"in t&&"validate"in t}function ag(t){return t==null?Vo({type:"object",properties:{},additionalProperties:!1}):sg(t)?t:"~standard"in t?t["~standard"].vendor==="zod"?Le(t):lg(t):t()}function lg(t){return Vo(()=>{if(!cg(t))throw new Error(`Standard schema vendor '${t["~standard"].vendor}' does not support JSON Schema conversion.`);return Yi(t["~standard"].jsonSchema.input({target:"draft-07"}))},{validate:async r=>{const i=await t["~standard"].validate(r);return"value"in i?{success:!0,value:i.value}:{success:!1,error:new no({value:r,cause:i.issues})}}})}function cg(t){return t["~standard"].jsonSchema!=null}function ug(t,r){var i;const c=(i=void 0)!=null?i:!1;return Vo(()=>ig(t,{$refStrategy:c?"root":"none"}),{validate:async d=>{const f=await t.safeParseAsync(d);return f.success?{success:!0,value:f.data}:{success:!1,error:f.error}}})}function dg(t,r){var i;const c=(i=void 0)!=null?i:!1;return Vo(()=>Yi(Uf(t,{target:"draft-7",io:"input",reused:c?"ref":"inline"})),{validate:async d=>{const f=await vc(t,d);return f.success?{success:!0,value:f.data}:{success:!1,error:f.error}}})}function fg(t){return"_zod"in t}function Le(t,r){return fg(t)?dg(t):ug(t)}async function Dt({value:t,schema:r,context:i}){const c=await Ki({value:t,schema:r,context:i});if(!c.success)throw no.wrap({value:t,cause:c.error,context:i});return c.value}async function Ki({value:t,schema:r,context:i}){const c=ag(r);try{if(c.validate==null)return{success:!0,value:t,rawValue:t};const d=await c.validate(t);return d.success?{success:!0,value:d.value,rawValue:t}:{success:!1,error:no.wrap({value:t,cause:d.error,context:i}),rawValue:t}}catch(d){return{success:!1,error:no.wrap({value:t,cause:d,context:i}),rawValue:t}}}async function mu({text:t,schema:r}){try{const i=uu(t);return r==null?i:Dt({value:i,schema:r})}catch(i){throw Do.isInstance(i)||no.isInstance(i)?i:new Do({text:t,cause:i})}}async function gu({text:t,schema:r}){try{const i=uu(t);return r==null?{success:!0,value:i,rawValue:i}:await Ki({value:i,schema:r})}catch(i){return{success:!1,error:Do.isInstance(i)?i:new Do({text:t,cause:i}),rawValue:void 0}}}function hg({stream:t,schema:r}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new ec).pipeThrough(new TransformStream({async transform({data:i},c){i!=="[DONE]"&&c.enqueue(await gu({text:i,schema:r}))}}))}async function An({provider:t,providerOptions:r,schema:i}){if(r?.[t]==null)return;const c=await Ki({value:r[t],schema:i});if(!c.success)throw new Vc({argument:"providerOptions",message:`invalid ${t} provider options`,cause:c.error});return c.value}var pg=()=>globalThis.fetch,Zn=async({url:t,headers:r,body:i,failedResponseHandler:c,successfulResponseHandler:d,abortSignal:f,fetch:m})=>yu({url:t,headers:{"Content-Type":"application/json",...r},body:{content:JSON.stringify(i),values:i},failedResponseHandler:c,successfulResponseHandler:d,abortSignal:f,fetch:m}),xu=async({url:t,headers:r,formData:i,failedResponseHandler:c,successfulResponseHandler:d,abortSignal:f,fetch:m})=>yu({url:t,headers:r,body:{content:i,values:Object.fromEntries(i.entries())},failedResponseHandler:c,successfulResponseHandler:d,abortSignal:f,fetch:m}),yu=async({url:t,headers:r={},body:i,successfulResponseHandler:c,failedResponseHandler:d,abortSignal:f,fetch:m=pg()})=>{try{const x=await m(t,{method:"POST",headers:cu(r,`ai-sdk/provider-utils/${hm}`,dm()),body:i.content,signal:f}),v=ao(x);if(!x.ok){let g;try{g=await d({response:x,url:t,requestBodyValues:i.values})}catch(E){throw Ti(E)||Kt.isInstance(E)?E:new Kt({message:"Failed to process error response",cause:E,statusCode:x.status,url:t,responseHeaders:v,requestBodyValues:i.values})}throw g.value}try{return await c({response:x,url:t,requestBodyValues:i.values})}catch(g){throw g instanceof Error&&(Ti(g)||Kt.isInstance(g))?g:new Kt({message:"Failed to process successful response",cause:g,statusCode:x.status,url:t,responseHeaders:v,requestBodyValues:i.values})}}catch(x){throw um({error:x,url:t,requestBodyValues:i.values})}};function mg({id:t,inputSchema:r}){return({execute:i,outputSchema:c,needsApproval:d,toModelOutput:f,onInputStart:m,onInputDelta:x,onInputAvailable:v,...g})=>({type:"provider",id:t,args:g,inputSchema:r,outputSchema:c,execute:i,needsApproval:d,toModelOutput:f,onInputStart:m,onInputDelta:x,onInputAvailable:v})}function Dn({id:t,inputSchema:r,outputSchema:i,supportsDeferredResults:c}){return({execute:d,needsApproval:f,toModelOutput:m,onInputStart:x,onInputDelta:v,onInputAvailable:g,...E})=>({type:"provider",id:t,args:E,inputSchema:r,outputSchema:i,execute:d,needsApproval:f,toModelOutput:m,onInputStart:x,onInputDelta:v,onInputAvailable:g,supportsDeferredResults:c})}var gg=new TextDecoder;async function wu({response:t,url:r}){return gg.decode(await au({response:t,url:r}))}var xg=({errorSchema:t,errorToMessage:r,isRetryable:i})=>async({response:c,url:d,requestBodyValues:f})=>{const m=await wu({response:c,url:d}),x=ao(c);if(m.trim()==="")return{responseHeaders:x,value:new Kt({message:c.statusText,url:d,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,isRetryable:i?.(c)})};try{const v=await mu({text:m,schema:t});return{responseHeaders:x,value:new Kt({message:r(v),url:d,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,data:v,isRetryable:i?.(c,v)})}}catch{return{responseHeaders:x,value:new Kt({message:c.statusText,url:d,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,isRetryable:i?.(c)})}}},Ji=t=>async({response:r})=>{const i=ao(r);if(r.body==null)throw new Bp({});return{responseHeaders:i,value:hg({stream:r.body,schema:t})}},mr=t=>async({response:r,url:i,requestBodyValues:c})=>{const d=await wu({response:r,url:i}),f=await gu({text:d,schema:t}),m=ao(r);if(!f.success)throw new Kt({message:"Invalid JSON response",cause:f.error,statusCode:r.status,responseHeaders:m,responseBody:d,url:i,requestBodyValues:c});return{responseHeaders:m,value:f.value,rawValue:f.rawValue}},yg=()=>async({response:t,url:r,requestBodyValues:i})=>{const c=ao(t);if(!t.body)throw new Kt({message:"Response body is empty",url:r,requestBodyValues:i,statusCode:t.status,responseHeaders:c,responseBody:void 0});try{const d=await t.arrayBuffer();return{responseHeaders:c,value:new Uint8Array(d)}}catch(d){throw new Kt({message:"Failed to read response as array buffer",url:r,requestBodyValues:i,statusCode:t.status,responseHeaders:c,responseBody:void 0,cause:d})}};function wg(t){return t?.replace(/\/$/,"")}var Qi=N({error:N({message:w(),type:w().nullish(),param:xr().nullish(),code:st([w(),j()]).nullish()})}),En=xg({errorSchema:Qi,errorToMessage:t=>t.error.message});function _u(t){const r=t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat"),i=t.startsWith("gpt-4")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-nano")&&!t.startsWith("gpt-5-chat")&&!t.startsWith("gpt-5.4-nano")||t.startsWith("o3")||t.startsWith("o4-mini"),c=t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat"),d=t.startsWith("gpt-5.1")||t.startsWith("gpt-5.2")||t.startsWith("gpt-5.3")||t.startsWith("gpt-5.4")||t.startsWith("gpt-5.5")||t.startsWith("gpt-5.6");return{supportsFlexProcessing:r,supportsPriorityProcessing:i,isReasoningModel:c,systemMessageMode:c?"developer":"system",supportsNonReasoningParameters:d}}async function es({stream:t,getError:r,isOutputChunk:i,url:c,requestBodyValues:d,responseHeaders:f}){const[m,x]=t.tee(),v=m.getReader();try{for(;;){const g=await v.read();if(g.done)return x;const E=g.value;if(!E.success)return x;const A=r(E.value);if(A!=null)throw x.cancel().catch(()=>{}),_g({frame:A,url:c,requestBodyValues:d,responseHeaders:f});if(i(E.value))return x}}finally{v.cancel().catch(()=>{}),v.releaseLock()}}function _g({frame:t,url:r,requestBodyValues:i,responseHeaders:c}){var d;const f=vg(t);return new Kt({message:(d=f?.message)!=null?d:"OpenAI stream failed before any output was generated",url:r,requestBodyValues:i,statusCode:f==null?500:Cg(f),responseHeaders:c,responseBody:JSON.stringify(t),data:t})}function vg(t){var r;const i=jr(t);if(i==null)return;if(i.type==="response.failed"){const d=jr(i.response),f=jr(d?.error);return typeof f?.message=="string"?{message:f.message,code:Oa(f.code),type:"response.failed",frame:t}:void 0}const c=(r=jr(i.error))!=null?r:i;return typeof c.message=="string"&&(jr(i.error)!=null||typeof c.type=="string"||"code"in c||"param"in c)?{message:c.message,code:Oa(c.code),type:typeof c.type=="string"?c.type:void 0,frame:t}:void 0}function Cg(t){if(typeof t.code=="number"&&ka(t.code))return t.code;if(typeof t.code=="string"&&/^\d{3}$/.test(t.code)){const i=Number(t.code);if(ka(i))return i}const r=[t.code,t.type].filter(i=>typeof i=="string"||typeof i=="number").join(" ").toLowerCase();return["insufficient_quota","rate_limit"].some(i=>r.includes(i))?429:r.includes("authentication")?401:r.includes("permission")?403:r.includes("not_found")?404:["invalid","bad_request","context_length"].some(i=>r.includes(i))?400:r.includes("overload")?503:r.includes("timeout")?504:500}function jr(t){return typeof t=="object"&&t!=null?t:void 0}function Oa(t){return typeof t=="string"||typeof t=="number"?t:void 0}function ka(t){return Number.isInteger(t)&&t>=400&&t<=599}function Ra(t){var r,i,c,d,f,m,x,v;if(t==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const g=(r=t.prompt_tokens)!=null?r:0,E=(i=t.completion_tokens)!=null?i:0,A=(d=(c=t.prompt_tokens_details)==null?void 0:c.cached_tokens)!=null?d:0,D=(m=(f=t.prompt_tokens_details)==null?void 0:f.cache_write_tokens)!=null?m:void 0,T=(v=(x=t.completion_tokens_details)==null?void 0:x.reasoning_tokens)!=null?v:0;return{inputTokens:{total:g,noCache:g-A-(D??0),cacheRead:A,cacheWrite:D},outputTokens:{total:E,text:E-T,reasoning:T},raw:t}}function bg(t){return JSON.stringify(t===void 0?{}:t)}function Un(t){var r;return(r=t?.openai)==null?void 0:r.promptCacheBreakpoint}function Ag({prompt:t,systemMessageMode:r="system"}){var i,c;const d=[],f=[];for(const{role:m,content:x,providerOptions:v}of t)switch(m){case"system":{switch(r){case"system":{const g=Un(v);d.push({role:"system",content:g==null?x:[{type:"text",text:x,prompt_cache_breakpoint:g}]});break}case"developer":{const g=Un(v);d.push({role:"developer",content:g==null?x:[{type:"text",text:x,prompt_cache_breakpoint:g}]});break}case"remove":{f.push({type:"other",message:"system messages are removed for this model"});break}default:{const g=r;throw new Error(`Unsupported system message mode: ${g}`)}}break}case"user":{if(x.length===1&&x[0].type==="text"&&Un(x[0].providerOptions)==null){d.push({role:"user",content:x[0].text});break}d.push({role:"user",content:x.map((g,E)=>{var A,D,T;switch(g.type){case"text":{const S=Un(g.providerOptions);return{type:"text",text:g.text,...S!=null&&{prompt_cache_breakpoint:S}}}case"file":{const S=Un(g.providerOptions);if(g.mediaType.startsWith("image/")){const P=g.mediaType==="image/*"?"image/jpeg":g.mediaType;return{type:"image_url",image_url:{url:g.data instanceof URL?g.data.toString():`data:${P};base64,${kr(g.data)}`,detail:(D=(A=g.providerOptions)==null?void 0:A.openai)==null?void 0:D.imageDetail},...S!=null&&{prompt_cache_breakpoint:S}}}else if(g.mediaType.startsWith("audio/")){if(g.data instanceof URL)throw new Mn({functionality:"audio file parts with URLs"});switch(g.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:kr(g.data),format:"wav"},...S!=null&&{prompt_cache_breakpoint:S}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:kr(g.data),format:"mp3"},...S!=null&&{prompt_cache_breakpoint:S}};default:throw new Mn({functionality:`audio content parts with media type ${g.mediaType}`})}}else if(g.mediaType==="application/pdf"){if(g.data instanceof URL)throw new Mn({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof g.data=="string"&&g.data.startsWith("file-")?{file_id:g.data}:{filename:(T=g.filename)!=null?T:`part-${E}.pdf`,file_data:`data:application/pdf;base64,${kr(g.data)}`},...S!=null&&{prompt_cache_breakpoint:S}}}else throw new Mn({functionality:`file part media type ${g.mediaType}`})}}})});break}case"assistant":{let g="";const E=[];let A=!1;const D=[];for(const T of x)switch(T.type){case"text":{const S=Un(T.providerOptions);g+=T.text,E.push({type:"text",text:T.text,...S!=null&&{prompt_cache_breakpoint:S}}),A||(A=S!=null);break}case"tool-call":{D.push({id:T.toolCallId,type:"function",function:{name:T.toolName,arguments:bg(T.input)}});break}}d.push({role:"assistant",content:A?E:D.length>0?g||null:g,tool_calls:D.length>0?D:void 0});break}case"tool":{for(const g of x){if(g.type==="tool-approval-response")continue;const E=g.output,A=(i=E.type==="content"?E.value.map(T=>Un(T.providerOptions)).find(T=>T!=null):Un(E.providerOptions))!=null?i:Un(g.providerOptions);let D;switch(E.type){case"text":case"error-text":D=E.value;break;case"execution-denied":D=(c=E.reason)!=null?c:"Tool call execution denied.";break;case"content":case"json":case"error-json":D=JSON.stringify(E.value);break}d.push({role:"tool",tool_call_id:g.toolCallId,content:A==null?D:[{type:"text",text:D,prompt_cache_breakpoint:A}]})}break}default:{const g=m;throw new Error(`Unsupported role: ${g}`)}}return{messages:d,warnings:f}}function mi({id:t,model:r,created:i}){return{id:t??void 0,modelId:r??void 0,timestamp:i?new Date(i*1e3):void 0}}function Ma(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var Eg=Fe(()=>Le(N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(N({message:N({role:Y("assistant").nullish(),content:w().nullish(),tool_calls:ue(N({id:w().nullish(),type:Y("function"),function:N({name:w(),arguments:w()})})).nullish(),annotations:ue(N({type:Y("url_citation"),url_citation:N({start_index:j(),end_index:j(),url:w(),title:w()})})).nullish()}),index:j(),logprobs:N({content:ue(N({token:w(),logprob:j(),top_logprobs:ue(N({token:w(),logprob:j()}))})).nullish()}).nullish(),finish_reason:w().nullish()})),usage:N({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:N({cached_tokens:j().nullish(),cache_write_tokens:j().nullish()}).nullish(),completion_tokens_details:N({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish()}))),Ig=Fe(()=>Le(st([N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(N({delta:N({role:Ae(["assistant"]).nullish(),content:w().nullish(),tool_calls:ue(N({index:j(),id:w().nullish(),type:Y("function").nullish(),function:N({name:w().nullish(),arguments:w().nullish()})})).nullish(),annotations:ue(N({type:Y("url_citation"),url_citation:N({start_index:j(),end_index:j(),url:w(),title:w()})})).nullish()}).nullish(),logprobs:N({content:ue(N({token:w(),logprob:j(),top_logprobs:ue(N({token:w(),logprob:j()}))})).nullish()}).nullish(),finish_reason:w().nullish(),index:j()})),usage:N({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:N({cached_tokens:j().nullish(),cache_write_tokens:j().nullish()}).nullish(),completion_tokens_details:N({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish()}),Qi]))),Sg=Fe(()=>Le(N({logitBias:wt(qh(),j()).optional(),logprobs:st([Mt(),j()]).optional(),parallelToolCalls:Mt().optional(),user:w().optional(),reasoningEffort:Ae(["none","minimal","low","medium","high","xhigh","max"]).optional(),maxCompletionTokens:j().optional(),store:Mt().optional(),metadata:wt(w().max(64),w().max(512)).optional(),prediction:wt(w(),xr()).optional(),serviceTier:Ae(["auto","flex","priority","default"]).optional(),strictJsonSchema:Mt().optional(),textVerbosity:Ae(["low","medium","high"]).optional(),promptCacheKey:w().optional(),promptCacheOptions:N({mode:Ae(["implicit","explicit"]).optional(),ttl:Y("30m").optional()}).optional(),promptCacheRetention:Ae(["in_memory","24h"]).optional(),safetyIdentifier:w().optional(),systemMessageMode:Ae(["system","developer","remove"]).optional(),forceReasoning:Mt().optional()})));function Tg({tools:t,toolChoice:r}){t=t?.length?t:void 0;const i=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i};const c=[];for(const f of t)switch(f.type){case"function":c.push({type:"function",function:{name:f.name,description:f.description,parameters:f.inputSchema,...f.strict!=null?{strict:f.strict}:{}}});break;default:i.push({type:"unsupported",feature:`tool type: ${f.type}`});break}if(r==null)return{tools:c,toolChoice:void 0,toolWarnings:i};const d=r.type;switch(d){case"auto":case"none":case"required":return{tools:c,toolChoice:d,toolWarnings:i};case"tool":return{tools:c,toolChoice:{type:"function",function:{name:r.toolName}},toolWarnings:i};default:{const f=d;throw new Mn({functionality:`tool choice type: ${f}`})}}}var Ng=class{constructor(t,r){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=t,this.config=r}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:r,temperature:i,topP:c,topK:d,frequencyPenalty:f,presencePenalty:m,stopSequences:x,responseFormat:v,seed:g,tools:E,toolChoice:A,providerOptions:D}){var T,S,P,M,ee;const $=[],F=(T=await An({provider:"openai",providerOptions:D,schema:Sg}))!=null?T:{},re=_u(this.modelId),Z=(S=F.forceReasoning)!=null?S:re.isReasoningModel;d!=null&&$.push({type:"unsupported",feature:"topK"});const{messages:B,warnings:L}=Ag({prompt:t,systemMessageMode:(P=F.systemMessageMode)!=null?P:Z?"developer":re.systemMessageMode});$.push(...L);const W=(M=F.strictJsonSchema)!=null?M:!0,z={model:this.modelId,logit_bias:F.logitBias,logprobs:F.logprobs===!0||typeof F.logprobs=="number"?!0:void 0,top_logprobs:typeof F.logprobs=="number"?F.logprobs:typeof F.logprobs=="boolean"&&F.logprobs?0:void 0,user:F.user,parallel_tool_calls:F.parallelToolCalls,max_tokens:r,temperature:i,top_p:c,frequency_penalty:f,presence_penalty:m,response_format:v?.type==="json"?v.schema!=null?{type:"json_schema",json_schema:{schema:v.schema,strict:W,name:(ee=v.name)!=null?ee:"response",description:v.description}}:{type:"json_object"}:void 0,stop:x,seed:g,verbosity:F.textVerbosity,max_completion_tokens:F.maxCompletionTokens,store:F.store,metadata:F.metadata,prediction:F.prediction,reasoning_effort:F.reasoningEffort,service_tier:F.serviceTier,prompt_cache_key:F.promptCacheKey,prompt_cache_options:F.promptCacheOptions,prompt_cache_retention:F.promptCacheRetention,safety_identifier:F.safetyIdentifier,messages:B};Z?((F.reasoningEffort!=="none"||!re.supportsNonReasoningParameters)&&(z.temperature!=null&&(z.temperature=void 0,$.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),z.top_p!=null&&(z.top_p=void 0,$.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),z.logprobs!=null&&(z.logprobs=void 0,$.push({type:"other",message:"logprobs is not supported for reasoning models"}))),z.frequency_penalty!=null&&(z.frequency_penalty=void 0,$.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),z.presence_penalty!=null&&(z.presence_penalty=void 0,$.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),z.logit_bias!=null&&(z.logit_bias=void 0,$.push({type:"other",message:"logitBias is not supported for reasoning models"})),z.top_logprobs!=null&&(z.top_logprobs=void 0,$.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),z.max_tokens!=null&&(z.max_completion_tokens==null&&(z.max_completion_tokens=z.max_tokens),z.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&z.temperature!=null&&(z.temperature=void 0,$.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),F.serviceTier==="flex"&&!re.supportsFlexProcessing&&($.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),z.service_tier=void 0),F.serviceTier==="priority"&&!re.supportsPriorityProcessing&&($.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),z.service_tier=void 0);const{tools:we,toolChoice:G,toolWarnings:me}=Tg({tools:E,toolChoice:A});return{args:{...z,tools:we,tool_choice:G},warnings:[...$,...me]}}async doGenerate(t){var r,i,c,d,f,m,x;const{args:v,warnings:g}=await this.getArgs(t),{responseHeaders:E,value:A,rawValue:D}=await Zn({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:bn(this.config.headers(),t.headers),body:v,failedResponseHandler:En,successfulResponseHandler:mr(Eg),abortSignal:t.abortSignal,fetch:this.config.fetch}),T=A.choices[0],S=[],P=T.message.content;P!=null&&P.length>0&&S.push({type:"text",text:P});for(const $ of(r=T.message.tool_calls)!=null?r:[])S.push({type:"tool-call",toolCallId:(i=$.id)!=null?i:rn(),toolName:$.function.name,input:$.function.arguments});for(const $ of(c=T.message.annotations)!=null?c:[])S.push({type:"source",sourceType:"url",id:rn(),url:$.url_citation.url,title:$.url_citation.title});const M=(d=A.usage)==null?void 0:d.completion_tokens_details;(f=A.usage)==null||f.prompt_tokens_details;const ee={openai:{}};return M?.accepted_prediction_tokens!=null&&(ee.openai.acceptedPredictionTokens=M?.accepted_prediction_tokens),M?.rejected_prediction_tokens!=null&&(ee.openai.rejectedPredictionTokens=M?.rejected_prediction_tokens),((m=T.logprobs)==null?void 0:m.content)!=null&&(ee.openai.logprobs=T.logprobs.content),{content:S,finishReason:{unified:Ma(T.finish_reason),raw:(x=T.finish_reason)!=null?x:void 0},usage:Ra(A.usage),request:{body:v},response:{...mi(A),headers:E,body:D},warnings:g,providerMetadata:ee}}async doStream(t){const{args:r,warnings:i}=await this.getArgs(t),c={...r,stream:!0,stream_options:{include_usage:!0}},d=this.config.url({path:"/chat/completions",modelId:this.modelId}),{responseHeaders:f,value:m}=await Zn({url:d,headers:bn(this.config.headers(),t.headers),body:c,failedResponseHandler:En,successfulResponseHandler:Ji(Ig),abortSignal:t.abortSignal,fetch:this.config.fetch}),x=await es({stream:m,getError:P=>"error"in P?P.error:void 0,isOutputChunk:Og,url:d,requestBodyValues:c,responseHeaders:f}),v=[];let g={unified:"other",raw:void 0},E,A=!1,D=!1;const T={openai:{}};return{stream:x.pipeThrough(new TransformStream({start(P){P.enqueue({type:"stream-start",warnings:i})},transform(P,M){var ee,$,F,re,Z,B,L,W,z,we,G,me,fe;if(t.includeRawChunks&&M.enqueue({type:"raw",rawValue:P.rawValue}),!P.success){g={unified:"error",raw:void 0},M.enqueue({type:"error",error:P.error});return}const te=P.value;if("error"in te){g={unified:"error",raw:void 0},M.enqueue({type:"error",error:te.error});return}if(!A){const le=mi(te);Object.values(le).some(Boolean)&&(A=!0,M.enqueue({type:"response-metadata",...mi(te)}))}te.usage!=null&&(E=te.usage,((ee=te.usage.completion_tokens_details)==null?void 0:ee.accepted_prediction_tokens)!=null&&(T.openai.acceptedPredictionTokens=($=te.usage.completion_tokens_details)==null?void 0:$.accepted_prediction_tokens),((F=te.usage.completion_tokens_details)==null?void 0:F.rejected_prediction_tokens)!=null&&(T.openai.rejectedPredictionTokens=(re=te.usage.completion_tokens_details)==null?void 0:re.rejected_prediction_tokens));const q=te.choices[0];if(q?.finish_reason!=null&&(g={unified:Ma(q.finish_reason),raw:q.finish_reason}),((Z=q?.logprobs)==null?void 0:Z.content)!=null&&(T.openai.logprobs=q.logprobs.content),q?.delta==null)return;const ke=q.delta;if(ke.content!=null&&(D||(M.enqueue({type:"text-start",id:"0"}),D=!0),M.enqueue({type:"text-delta",id:"0",delta:ke.content})),ke.tool_calls!=null)for(const le of ke.tool_calls){const Te=le.index;if(v[Te]==null){if(le.type!=null&&le.type!=="function")throw new fi({data:le,message:"Expected 'function' type."});if(le.id==null)throw new fi({data:le,message:"Expected 'id' to be a string."});if(((B=le.function)==null?void 0:B.name)==null)throw new fi({data:le,message:"Expected 'function.name' to be a string."});M.enqueue({type:"tool-input-start",id:le.id,toolName:le.function.name}),v[Te]={id:le.id,type:"function",function:{name:le.function.name,arguments:(L=le.function.arguments)!=null?L:""},hasFinished:!1};const xe=v[Te];((W=xe.function)==null?void 0:W.name)!=null&&((z=xe.function)==null?void 0:z.arguments)!=null&&xe.function.arguments.length>0&&M.enqueue({type:"tool-input-delta",id:xe.id,delta:xe.function.arguments});continue}const Je=v[Te];Je.hasFinished||(((we=le.function)==null?void 0:we.arguments)!=null&&(Je.function.arguments+=(me=(G=le.function)==null?void 0:G.arguments)!=null?me:""),M.enqueue({type:"tool-input-delta",id:Je.id,delta:(fe=le.function.arguments)!=null?fe:""}))}if(ke.annotations!=null)for(const le of ke.annotations)M.enqueue({type:"source",sourceType:"url",id:rn(),url:le.url_citation.url,title:le.url_citation.title})},flush(P){var M;D&&P.enqueue({type:"text-end",id:"0"});for(const ee of v)ee.hasFinished||(P.enqueue({type:"tool-input-end",id:ee.id}),P.enqueue({type:"tool-call",toolCallId:(M=ee.id)!=null?M:rn(),toolName:ee.function.name,input:ee.function.arguments}),ee.hasFinished=!0);P.enqueue({type:"finish",finishReason:g,usage:Ra(E),...T!=null?{providerMetadata:T}:{}})}})),request:{body:c},response:{headers:f}}}};function Og(t){return"error"in t?!1:t.choices.some(r=>{const i=r.delta;return i?.content!=null&&i.content.length>0||i?.tool_calls!=null&&i.tool_calls.length>0||i?.annotations!=null&&i.annotations.length>0})}function Da(t){var r,i,c,d;if(t==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const f=(r=t.prompt_tokens)!=null?r:0,m=(i=t.completion_tokens)!=null?i:0;return{inputTokens:{total:(c=t.prompt_tokens)!=null?c:void 0,noCache:f,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:(d=t.completion_tokens)!=null?d:void 0,text:m,reasoning:void 0},raw:t}}function kg({prompt:t,user:r="user",assistant:i="assistant"}){let c="";t[0].role==="system"&&(c+=`${t[0].content}
46
46
 
47
47
  `,t=t.slice(1));for(const{role:d,content:f}of t)switch(d){case"system":throw new Up({message:"Unexpected system message in prompt: ${content}",prompt:t});case"user":{const m=f.map(x=>{switch(x.type){case"text":return x.text}}).filter(Boolean).join("");c+=`${r}:
48
48
  ${m}
@@ -52,14 +52,14 @@ ${m}
52
52
 
53
53
  `;break}case"tool":throw new Mn({functionality:"tool messages"});default:{const m=d;throw new Error(`Unsupported role: ${m}`)}}return c+=`${i}:
54
54
  `,{prompt:c,stopSequences:[`
55
- ${r}:`]}}function Pa({id:t,model:r,created:i}){return{id:t??void 0,modelId:r??void 0,timestamp:i!=null?new Date(i*1e3):void 0}}function Ba(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var kg=Fe(()=>Le(N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(N({text:w(),finish_reason:w(),logprobs:N({tokens:ue(w()),token_logprobs:ue(j()),top_logprobs:ue(wt(w(),j())).nullish()}).nullish()})),usage:N({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}))),Rg=Fe(()=>Le(st([N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(N({text:w(),finish_reason:w().nullish(),index:j(),logprobs:N({tokens:ue(w()),token_logprobs:ue(j()),top_logprobs:ue(wt(w(),j())).nullish()}).nullish()})),usage:N({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}),Qi]))),La=Fe(()=>Le(N({echo:Mt().optional(),logitBias:wt(w(),j()).optional(),suffix:w().optional(),user:w().optional(),logprobs:st([Mt(),j()]).optional()}))),Mg=class{constructor(t,r){this.specificationVersion="v3",this.supportedUrls={},this.modelId=t,this.config=r}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:r,temperature:i,topP:c,topK:d,frequencyPenalty:f,presencePenalty:m,stopSequences:x,responseFormat:v,tools:g,toolChoice:E,seed:A,providerOptions:D}){const T=[],S={...await An({provider:"openai",providerOptions:D,schema:La}),...await An({provider:this.providerOptionsName,providerOptions:D,schema:La})};d!=null&&T.push({type:"unsupported",feature:"topK"}),g?.length&&T.push({type:"unsupported",feature:"tools"}),E!=null&&T.push({type:"unsupported",feature:"toolChoice"}),v!=null&&v.type!=="text"&&T.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:P,stopSequences:M}=Og({prompt:t}),ee=[...M??[],...x??[]];return{args:{model:this.modelId,echo:S.echo,logit_bias:S.logitBias,logprobs:S?.logprobs===!0?0:S?.logprobs===!1?void 0:S?.logprobs,suffix:S.suffix,user:S.user,max_tokens:r,temperature:i,top_p:c,frequency_penalty:f,presence_penalty:m,seed:A,prompt:P,stop:ee.length>0?ee:void 0},warnings:T}}async doGenerate(t){var r;const{args:i,warnings:c}=await this.getArgs(t),{responseHeaders:d,value:f,rawValue:m}=await Zn({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:bn(this.config.headers(),t.headers),body:i,failedResponseHandler:En,successfulResponseHandler:mr(kg),abortSignal:t.abortSignal,fetch:this.config.fetch}),x=f.choices[0],v={openai:{}};return x.logprobs!=null&&(v.openai.logprobs=x.logprobs),{content:[{type:"text",text:x.text}],usage:Da(f.usage),finishReason:{unified:Ba(x.finish_reason),raw:(r=x.finish_reason)!=null?r:void 0},request:{body:i},response:{...Pa(f),headers:d,body:m},providerMetadata:v,warnings:c}}async doStream(t){const{args:r,warnings:i}=await this.getArgs(t),c={...r,stream:!0,stream_options:{include_usage:!0}},d=this.config.url({path:"/completions",modelId:this.modelId}),{responseHeaders:f,value:m}=await Zn({url:d,headers:bn(this.config.headers(),t.headers),body:c,failedResponseHandler:En,successfulResponseHandler:Ji(Rg),abortSignal:t.abortSignal,fetch:this.config.fetch}),x=await es({stream:m,getError:T=>"error"in T?T.error:void 0,isOutputChunk:Dg,url:d,requestBodyValues:c,responseHeaders:f});let v={unified:"other",raw:void 0};const g={openai:{}};let E,A=!0;return{stream:x.pipeThrough(new TransformStream({start(T){T.enqueue({type:"stream-start",warnings:i})},transform(T,S){if(t.includeRawChunks&&S.enqueue({type:"raw",rawValue:T.rawValue}),!T.success){v={unified:"error",raw:void 0},S.enqueue({type:"error",error:T.error});return}const P=T.value;if("error"in P){v={unified:"error",raw:void 0},S.enqueue({type:"error",error:P.error});return}A&&(A=!1,S.enqueue({type:"response-metadata",...Pa(P)}),S.enqueue({type:"text-start",id:"0"})),P.usage!=null&&(E=P.usage);const M=P.choices[0];M?.finish_reason!=null&&(v={unified:Ba(M.finish_reason),raw:M.finish_reason}),M?.logprobs!=null&&(g.openai.logprobs=M.logprobs),M?.text!=null&&M.text.length>0&&S.enqueue({type:"text-delta",id:"0",delta:M.text})},flush(T){A||T.enqueue({type:"text-end",id:"0"}),T.enqueue({type:"finish",finishReason:v,providerMetadata:g,usage:Da(E)})}})),request:{body:c},response:{headers:f}}}};function Dg(t){return!("error"in t)&&t.choices.some(r=>r.text.length>0)}var Pg=Fe(()=>Le(N({dimensions:j().optional(),user:w().optional()}))),Bg=Fe(()=>Le(N({data:ue(N({embedding:ue(j())})),usage:N({prompt_tokens:j()}).nullish()}))),Lg=class{constructor(t,r){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=r}get provider(){return this.config.provider}async doEmbed({values:t,headers:r,abortSignal:i,providerOptions:c}){var d;if(t.length>this.maxEmbeddingsPerCall)throw new jp({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const f=(d=await An({provider:"openai",providerOptions:c,schema:Pg}))!=null?d:{},{responseHeaders:m,value:x,rawValue:v}=await Zn({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:bn(this.config.headers(),r),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:f.dimensions,user:f.user},failedResponseHandler:En,successfulResponseHandler:mr(Bg),abortSignal:i,fetch:this.config.fetch});return{warnings:[],embeddings:x.data.map(g=>g.embedding),usage:x.usage?{tokens:x.usage.prompt_tokens}:void 0,response:{headers:m,body:v}}}},Fa=Fe(()=>Le(N({created:j().nullish(),data:ue(N({b64_json:w(),revised_prompt:w().nullish()})),background:w().nullish(),output_format:w().nullish(),size:w().nullish(),quality:w().nullish(),usage:N({input_tokens:j().nullish(),output_tokens:j().nullish(),total_tokens:j().nullish(),input_tokens_details:N({image_tokens:j().nullish(),text_tokens:j().nullish()}).nullish()}).nullish()}))),Fg={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10,"gpt-image-2":10,"chatgpt-image-latest":10},Ug=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1","gpt-image-2"];function zg(t){return Ug.some(r=>t.startsWith(r))}var vu=N({quality:Ae(["standard","hd","low","medium","high","auto"]).optional(),background:Ae(["transparent","opaque","auto"]).optional(),outputFormat:Ae(["png","jpeg","webp"]).optional(),outputCompression:j().int().min(0).max(100).optional(),user:w().optional()}),Vg=Fe(()=>Le(vu.extend({style:Ae(["vivid","natural"]).optional(),moderation:Ae(["auto","low"]).optional()}))),Zg=Fe(()=>Le(vu.extend({inputFidelity:Ae(["high","low"]).optional()}))),$g=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v3"}get maxImagesPerCall(){var t;return(t=Fg[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,files:r,mask:i,n:c,size:d,aspectRatio:f,seed:m,providerOptions:x,headers:v,abortSignal:g}){var E,A,D,T,S,P,M,ee,$,F,re;const Z=[];f!=null&&Z.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),m!=null&&Z.push({type:"unsupported",feature:"seed"});const B=(D=(A=(E=this.config._internal)==null?void 0:E.currentDate)==null?void 0:A.call(E))!=null?D:new Date;if(r!=null){const we=(T=await An({provider:"openai",providerOptions:x,schema:Zg}))!=null?T:{},{value:G,responseHeaders:me}=await xu({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:bn(this.config.headers(),v),formData:Jp({model:this.modelId,prompt:t,image:await Promise.all(r.map(fe=>fe.type==="file"?new Blob([fe.data instanceof Uint8Array?new Blob([fe.data],{type:fe.mediaType}):new Blob([qi(fe.data)],{type:fe.mediaType})],{type:fe.mediaType}):lu(fe.url))),mask:i!=null?await jg(i):void 0,n:c,size:d,quality:we.quality,background:we.background,output_format:we.outputFormat,output_compression:we.outputCompression,input_fidelity:we.inputFidelity,user:we.user}),failedResponseHandler:En,successfulResponseHandler:mr(Fa),abortSignal:g,fetch:this.config.fetch});return{images:G.data.map(fe=>fe.b64_json),warnings:Z,usage:G.usage!=null?{inputTokens:(S=G.usage.input_tokens)!=null?S:void 0,outputTokens:(P=G.usage.output_tokens)!=null?P:void 0,totalTokens:(M=G.usage.total_tokens)!=null?M:void 0}:void 0,response:{timestamp:B,modelId:this.modelId,headers:me},providerMetadata:{openai:{images:G.data.map((fe,te)=>{var q,ke,le,Te,Je,xe;return{...fe.revised_prompt?{revisedPrompt:fe.revised_prompt}:{},created:(q=G.created)!=null?q:void 0,size:(ke=G.size)!=null?ke:void 0,quality:(le=G.quality)!=null?le:void 0,background:(Te=G.background)!=null?Te:void 0,outputFormat:(Je=G.output_format)!=null?Je:void 0,...Ua((xe=G.usage)==null?void 0:xe.input_tokens_details,te,G.data.length)}})}}}}const L=(ee=await An({provider:"openai",providerOptions:x,schema:Vg}))!=null?ee:{},{value:W,responseHeaders:z}=await Zn({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:bn(this.config.headers(),v),body:{model:this.modelId,prompt:t,n:c,size:d,quality:L.quality,style:L.style,background:L.background,moderation:L.moderation,output_format:L.outputFormat,output_compression:L.outputCompression,user:L.user,...zg(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:En,successfulResponseHandler:mr(Fa),abortSignal:g,fetch:this.config.fetch});return{images:W.data.map(we=>we.b64_json),warnings:Z,usage:W.usage!=null?{inputTokens:($=W.usage.input_tokens)!=null?$:void 0,outputTokens:(F=W.usage.output_tokens)!=null?F:void 0,totalTokens:(re=W.usage.total_tokens)!=null?re:void 0}:void 0,response:{timestamp:B,modelId:this.modelId,headers:z},providerMetadata:{openai:{images:W.data.map((we,G)=>{var me,fe,te,q,ke,le;return{...we.revised_prompt?{revisedPrompt:we.revised_prompt}:{},created:(me=W.created)!=null?me:void 0,size:(fe=W.size)!=null?fe:void 0,quality:(te=W.quality)!=null?te:void 0,background:(q=W.background)!=null?q:void 0,outputFormat:(ke=W.output_format)!=null?ke:void 0,...Ua((le=W.usage)==null?void 0:le.input_tokens_details,G,W.data.length)}})}}}}};function Ua(t,r,i){if(t==null)return{};const c={};if(t.image_tokens!=null){const d=Math.floor(t.image_tokens/i),f=t.image_tokens-d*(i-1);c.imageTokens=r===i-1?f:d}if(t.text_tokens!=null){const d=Math.floor(t.text_tokens/i),f=t.text_tokens-d*(i-1);c.textTokens=r===i-1?f:d}return c}async function jg(t){if(!t)return;if(t.type==="url")return lu(t.url);const r=t.data instanceof Uint8Array?t.data:qi(t.data);return new Blob([r],{type:t.mediaType})}var Cu=Fe(()=>Le(N({callId:w(),operation:mt("type",[N({type:Y("create_file"),path:w(),diff:w()}),N({type:Y("delete_file"),path:w()}),N({type:Y("update_file"),path:w(),diff:w()})])}))),bu=Fe(()=>Le(N({status:Ae(["completed","failed"]),output:w().optional()}))),Hg=Dn({id:"openai.apply_patch",inputSchema:Cu,outputSchema:bu}),Wg=Hg,Gg=Fe(()=>Le(N({code:w().nullish(),containerId:w()}))),qg=Fe(()=>Le(N({outputs:ue(mt("type",[N({type:Y("logs"),logs:w()}),N({type:Y("image"),url:w()})])).nullish()}))),Xg=Fe(()=>Le(N({container:st([w(),N({fileIds:ue(w()).optional()})]).optional()}))),Yg=Dn({id:"openai.code_interpreter",inputSchema:Gg,outputSchema:qg}),Kg=(t={})=>Yg(t),Jg=Fe(()=>Le(N({name:w(),description:w().optional(),format:st([N({type:Y("grammar"),syntax:Ae(["regex","lark"]),definition:w()}),N({type:Y("text")})]).optional()}))),Qg=Fe(()=>Le(w())),e2=pg({id:"openai.custom",inputSchema:Qg}),t2=t=>e2(t),Au=N({key:w(),type:Ae(["eq","ne","gt","gte","lt","lte","in","nin"]),value:st([w(),j(),Mt(),ue(w())])}),Eu=N({type:Ae(["and","or"]),filters:ue(st([Au,Wi(()=>Eu)]))}),n2=Fe(()=>Le(N({vectorStoreIds:ue(w()),maxNumResults:j().optional(),ranking:N({ranker:w().optional(),scoreThreshold:j().optional()}).optional(),filters:st([Au,Eu]).optional()}))),r2=Fe(()=>Le(N({queries:ue(w()),results:ue(N({attributes:wt(w(),Cn()),fileId:w(),filename:w(),score:j(),text:w()})).nullable()}))),o2=Dn({id:"openai.file_search",inputSchema:N({}),outputSchema:r2}),i2=Fe(()=>Le(N({background:Ae(["auto","opaque","transparent"]).optional(),inputFidelity:Ae(["low","high"]).optional(),inputImageMask:N({fileId:w().optional(),imageUrl:w().optional()}).optional(),model:w().optional(),moderation:Ae(["auto"]).optional(),outputCompression:j().int().min(0).max(100).optional(),outputFormat:Ae(["png","jpeg","webp"]).optional(),partialImages:j().int().min(0).max(3).optional(),quality:Ae(["auto","low","medium","high"]).optional(),size:Ae(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),s2=Fe(()=>Le(N({}))),a2=Fe(()=>Le(N({result:w()}))),l2=Dn({id:"openai.image_generation",inputSchema:s2,outputSchema:a2}),c2=(t={})=>l2(t),Iu=Fe(()=>Le(N({action:N({type:Y("exec"),command:ue(w()),timeoutMs:j().optional(),user:w().optional(),workingDirectory:w().optional(),env:wt(w(),w()).optional()})}))),Su=Fe(()=>Le(N({output:w()}))),u2=Dn({id:"openai.local_shell",inputSchema:Iu,outputSchema:Su}),Tu=Fe(()=>Le(N({action:N({commands:ue(w()),timeoutMs:j().optional(),maxOutputLength:j().optional()})}))),ki=Fe(()=>Le(N({output:ue(N({stdout:w(),stderr:w(),outcome:mt("type",[N({type:Y("timeout")}),N({type:Y("exit"),exitCode:j()})])}))}))),d2=ue(mt("type",[N({type:Y("skillReference"),skillId:w(),version:w().optional()}),N({type:Y("inline"),name:w(),description:w(),source:N({type:Y("base64"),mediaType:Y("application/zip"),data:w()})})])).optional(),f2=Fe(()=>Le(N({environment:st([N({type:Y("containerAuto"),fileIds:ue(w()).optional(),memoryLimit:Ae(["1g","4g","16g","64g"]).optional(),networkPolicy:mt("type",[N({type:Y("disabled")}),N({type:Y("allowlist"),allowedDomains:ue(w()),domainSecrets:ue(N({domain:w(),name:w(),value:w()})).optional()})]).optional(),skills:d2}),N({type:Y("containerReference"),containerId:w()}),N({type:Y("local").optional(),skills:ue(N({name:w(),description:w(),path:w()})).optional()})]).optional()}))),h2=Dn({id:"openai.shell",inputSchema:Tu,outputSchema:ki}),p2=Fe(()=>Le(N({execution:Ae(["server","client"]).optional(),description:w().optional(),parameters:wt(w(),Cn()).optional()}))),Ri=Fe(()=>Le(N({arguments:Cn().optional(),call_id:w().nullish()}))),Mi=Fe(()=>Le(N({tools:ue(wt(w(),Cn()))}))),m2=Dn({id:"openai.tool_search",inputSchema:Ri,outputSchema:Mi}),g2=(t={})=>m2(t),x2=Fe(()=>Le(N({externalWebAccess:Mt().optional(),filters:N({allowedDomains:ue(w()).optional()}).optional(),searchContextSize:Ae(["low","medium","high"]).optional(),userLocation:N({type:Y("approximate"),country:w().optional(),city:w().optional(),region:w().optional(),timezone:w().optional()}).optional()}))),y2=Fe(()=>Le(N({}))),w2=Fe(()=>Le(N({action:mt("type",[N({type:Y("search"),query:w().optional(),queries:ue(w()).optional()}),N({type:Y("openPage"),url:w().nullish()}),N({type:Y("findInPage"),url:w().nullish(),pattern:w().nullish()})]).optional(),sources:ue(mt("type",[N({type:Y("url"),url:w()}),N({type:Y("api"),name:w()})])).optional()}))),_2=Dn({id:"openai.web_search",inputSchema:y2,outputSchema:w2}),v2=(t={})=>_2(t),C2=Fe(()=>Le(N({searchContextSize:Ae(["low","medium","high"]).optional(),userLocation:N({type:Y("approximate"),country:w().optional(),city:w().optional(),region:w().optional(),timezone:w().optional()}).optional()}))),b2=Fe(()=>Le(N({}))),A2=Fe(()=>Le(N({action:mt("type",[N({type:Y("search"),query:w().optional()}),N({type:Y("openPage"),url:w().nullish()}),N({type:Y("findInPage"),url:w().nullish(),pattern:w().nullish()})]).optional()}))),E2=Dn({id:"openai.web_search_preview",inputSchema:b2,outputSchema:A2}),Di=Wi(()=>st([w(),j(),Mt(),bc(),ue(Di),wt(w(),Di)])),I2=Fe(()=>Le(N({serverLabel:w(),allowedTools:st([ue(w()),N({readOnly:Mt().optional(),toolNames:ue(w()).optional()})]).optional(),authorization:w().optional(),connectorId:w().optional(),headers:wt(w(),w()).optional(),requireApproval:st([Ae(["always","never"]),N({never:N({toolNames:ue(w()).optional()}).optional()})]).optional(),serverDescription:w().optional(),serverUrl:w().optional()}).refine(t=>t.serverUrl!=null||t.connectorId!=null,"One of serverUrl or connectorId must be provided."))),S2=Fe(()=>Le(N({}))),T2=Fe(()=>Le(N({type:Y("call"),serverLabel:w(),name:w(),arguments:w(),output:w().nullish(),error:st([w(),Di]).optional()}))),N2=Dn({id:"openai.mcp",inputSchema:S2,outputSchema:T2}),O2=t=>N2(t),k2={applyPatch:Wg,customTool:t2,codeInterpreter:Kg,fileSearch:o2,imageGeneration:c2,localShell:u2,shell:h2,webSearchPreview:E2,webSearch:v2,mcp:O2,toolSearch:g2};function za(t){var r,i,c,d,f,m;if(t==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const x=t.input_tokens,v=t.output_tokens,g=(i=(r=t.input_tokens_details)==null?void 0:r.cached_tokens)!=null?i:0,E=(d=(c=t.input_tokens_details)==null?void 0:c.cache_write_tokens)!=null?d:void 0,A=(m=(f=t.output_tokens_details)==null?void 0:f.reasoning_tokens)!=null?m:0;return{inputTokens:{total:x,noCache:x-g-(E??0),cacheRead:g,cacheWrite:E},outputTokens:{total:v,text:v-A,reasoning:A},raw:t}}function R2(t){return JSON.stringify(t===void 0?{}:t)}function Nr(t,r){var i;return(i=t?.[r])==null?void 0:i.promptCacheBreakpoint}function Va(t,r){return r?r.some(i=>t.startsWith(i)):!1}async function M2({prompt:t,toolNameMapping:r,systemMessageMode:i,providerOptionsName:c,fileIdPrefixes:d,passThroughUnsupportedFiles:f=!1,store:m,hasConversation:x=!1,hasPreviousResponseId:v=!1,hasLocalShellTool:g=!1,hasShellTool:E=!1,hasApplyPatchTool:A=!1,customProviderToolNames:D}){var T,S,P,M,ee,$,F,re,Z,B,L,W,z,we,G,me,fe,te,q,ke,le,Te,Je;let xe=[];const $e=[],Ue=new Set;for(const{role:Ze,content:qe,providerOptions:ze}of t)switch(Ze){case"system":{switch(i){case"system":{const ie=Nr(ze,c);xe.push({role:"system",content:ie==null?qe:[{type:"input_text",text:qe,prompt_cache_breakpoint:ie}]});break}case"developer":{const ie=Nr(ze,c);xe.push({role:"developer",content:ie==null?qe:[{type:"input_text",text:qe,prompt_cache_breakpoint:ie}]});break}case"remove":{$e.push({type:"other",message:"system messages are removed for this model"});break}default:{const ie=i;throw new Error(`Unsupported system message mode: ${ie}`)}}break}case"user":{xe.push({role:"user",content:qe.map((ie,de)=>{var _e,Pe,ae;switch(ie.type){case"text":{const J=Nr(ie.providerOptions,c);return{type:"input_text",text:ie.text,...J!=null&&{prompt_cache_breakpoint:J}}}case"file":{const J=Nr(ie.providerOptions,c),ye=ie.mediaType==="image/*"?"image/jpeg":ie.mediaType;if(ye.startsWith("image/"))return{type:"input_image",...ie.data instanceof URL?{image_url:ie.data.toString()}:typeof ie.data=="string"&&Va(ie.data,d)?{file_id:ie.data}:{image_url:`data:${ye};base64,${kr(ie.data)}`},detail:(Pe=(_e=ie.providerOptions)==null?void 0:_e[c])==null?void 0:Pe.imageDetail,...J!=null&&{prompt_cache_breakpoint:J}};if(ie.data instanceof URL)return{type:"input_file",file_url:ie.data.toString(),...J!=null&&{prompt_cache_breakpoint:J}};if(ye!=="application/pdf"&&!f)throw new Mn({functionality:`file part media type ${ye}`});return{type:"input_file",...typeof ie.data=="string"&&Va(ie.data,d)?{file_id:ie.data}:{filename:(ae=ie.filename)!=null?ae:ye==="application/pdf"?`part-${de}.pdf`:`part-${de}`,file_data:`data:${ye};base64,${kr(ie.data)}`},...J!=null&&{prompt_cache_breakpoint:J}}}}})});break}case"assistant":{const ie={};for(const de of qe)switch(de.type){case"text":{const _e=(T=de.providerOptions)==null?void 0:T[c],Pe=_e?.itemId,ae=_e?.phase;if(x&&Pe!=null)break;if(m&&Pe!=null){xe.push({type:"item_reference",id:Pe});break}xe.push({role:"assistant",content:[{type:"output_text",text:de.text}],id:Pe,...ae!=null&&{phase:ae}});break}case"tool-call":{const _e=($=(P=(S=de.providerOptions)==null?void 0:S[c])==null?void 0:P.itemId)!=null?$:(ee=(M=de.providerMetadata)==null?void 0:M[c])==null?void 0:ee.itemId,Pe=(L=(re=(F=de.providerOptions)==null?void 0:F[c])==null?void 0:re.namespace)!=null?L:(B=(Z=de.providerMetadata)==null?void 0:Z[c])==null?void 0:B.namespace;if(x&&_e!=null)break;const ae=r.toProviderToolName(de.toolName);if(ae==="tool_search"){if(m&&_e!=null){xe.push({type:"item_reference",id:_e});break}const ye=typeof de.input=="string"?await mu({text:de.input,schema:Ri}):await Dt({value:de.input,schema:Ri}),Se=ye.call_id!=null?"client":"server";xe.push({type:"tool_search_call",id:_e??de.toolCallId,execution:Se,call_id:(W=ye.call_id)!=null?W:null,status:"completed",arguments:ye.arguments});break}if(de.providerExecuted){m&&_e!=null&&xe.push({type:"item_reference",id:_e});break}if(v&&m&&_e!=null)break;const J=g&&ae==="local_shell"||E&&ae==="shell"||A&&ae==="apply_patch"||((z=D?.has(ae))!=null?z:!1);if(m&&_e!=null&&J){xe.push({type:"item_reference",id:_e});break}if(g&&ae==="local_shell"){const ye=await Dt({value:de.input,schema:Iu});xe.push({type:"local_shell_call",call_id:de.toolCallId,id:_e,action:{type:"exec",command:ye.action.command,timeout_ms:ye.action.timeoutMs,user:ye.action.user,working_directory:ye.action.workingDirectory,env:ye.action.env}});break}if(E&&ae==="shell"){const ye=await Dt({value:de.input,schema:Tu});xe.push({type:"shell_call",call_id:de.toolCallId,id:_e,status:"completed",action:{commands:ye.action.commands,timeout_ms:ye.action.timeoutMs,max_output_length:ye.action.maxOutputLength}});break}if(A&&ae==="apply_patch"){const ye=await Dt({value:de.input,schema:Cu});xe.push({type:"apply_patch_call",call_id:ye.callId,id:_e,status:"completed",operation:ye.operation});break}if(D?.has(ae)){xe.push({type:"custom_tool_call",call_id:de.toolCallId,name:ae,input:typeof de.input=="string"?de.input:JSON.stringify(de.input),id:_e});break}xe.push({type:"function_call",call_id:de.toolCallId,name:ae,arguments:R2(de.input),...Pe!=null&&{namespace:Pe}});break}case"tool-result":{if(de.output.type==="execution-denied"||de.output.type==="json"&&typeof de.output.value=="object"&&de.output.value!=null&&"type"in de.output.value&&de.output.value.type==="execution-denied"||x)break;const _e=r.toProviderToolName(de.toolName);if(_e==="tool_search"){const Pe=(me=(G=(we=de.providerOptions)==null?void 0:we[c])==null?void 0:G.itemId)!=null?me:de.toolCallId;if(m)xe.push({type:"item_reference",id:Pe});else if(de.output.type==="json"){const ae=await Dt({value:de.output.value,schema:Mi});xe.push({type:"tool_search_output",id:Pe,execution:"server",call_id:null,status:"completed",tools:ae.tools})}break}if(E&&_e==="shell"){if(de.output.type==="json"){const Pe=await Dt({value:de.output.value,schema:ki});xe.push({type:"shell_call_output",call_id:de.toolCallId,output:Pe.output.map(ae=>({stdout:ae.stdout,stderr:ae.stderr,outcome:ae.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:ae.outcome.exitCode}}))})}break}if(m){const Pe=(q=(te=(fe=de.providerOptions)==null?void 0:fe[c])==null?void 0:te.itemId)!=null?q:de.toolCallId;xe.push({type:"item_reference",id:Pe})}else $e.push({type:"other",message:`Results for OpenAI tool ${de.toolName} are not sent to the API when store is false`});break}case"reasoning":{const _e=await An({provider:c,providerOptions:de.providerOptions,schema:D2}),Pe=_e?.itemId;if((x||v)&&Pe!=null)break;if(Pe!=null){const ae=ie[Pe];if(m)ae===void 0&&(xe.push({type:"item_reference",id:Pe}),ie[Pe]={type:"reasoning",id:Pe,summary:[]});else{const J=[];de.text.length>0?J.push({type:"summary_text",text:de.text}):ae!==void 0&&$e.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(de)}.`}),ae===void 0?(ie[Pe]={type:"reasoning",id:Pe,encrypted_content:_e?.reasoningEncryptedContent,summary:J},xe.push(ie[Pe])):(ae.summary.push(...J),_e?.reasoningEncryptedContent!=null&&(ae.encrypted_content=_e.reasoningEncryptedContent))}}else{const ae=_e?.reasoningEncryptedContent;if(ae!=null){const J=[];de.text.length>0&&J.push({type:"summary_text",text:de.text}),xe.push({type:"reasoning",encrypted_content:ae,summary:J})}else $e.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(de)}.`})}break}}break}case"tool":{for(const ie of qe){if(ie.type==="tool-approval-response"){const ae=ie;if(Ue.has(ae.approvalId))continue;Ue.add(ae.approvalId),m&&xe.push({type:"item_reference",id:ae.approvalId}),xe.push({type:"mcp_approval_response",approval_request_id:ae.approvalId,approve:ae.approved});continue}const de=ie.output;if(de.type==="execution-denied"&&((le=(ke=de.providerOptions)==null?void 0:ke.openai)==null?void 0:le.approvalId))continue;const _e=r.toProviderToolName(ie.toolName);if(_e==="tool_search"&&de.type==="json"){const ae=await Dt({value:de.value,schema:Mi});xe.push({type:"tool_search_output",execution:"client",call_id:ie.toolCallId,status:"completed",tools:ae.tools});continue}if(g&&_e==="local_shell"&&de.type==="json"){const ae=await Dt({value:de.value,schema:Su});xe.push({type:"local_shell_call_output",call_id:ie.toolCallId,output:ae.output});continue}if(E&&_e==="shell"&&de.type==="json"){const ae=await Dt({value:de.value,schema:ki});xe.push({type:"shell_call_output",call_id:ie.toolCallId,output:ae.output.map(J=>({stdout:J.stdout,stderr:J.stderr,outcome:J.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:J.outcome.exitCode}}))});continue}if(A&&ie.toolName==="apply_patch"&&de.type==="json"){const ae=await Dt({value:de.value,schema:bu});xe.push({type:"apply_patch_call_output",call_id:ie.toolCallId,status:ae.status,output:ae.output});continue}if(D?.has(_e)){let ae;switch(de.type){case"text":case"error-text":ae=de.value;break;case"execution-denied":ae=(Te=de.reason)!=null?Te:"Tool call execution denied.";break;case"json":case"error-json":ae=JSON.stringify(de.value);break;case"content":ae=de.value.map(J=>{var ye,Se,Ve,St,vt;const et=Nr(J.providerOptions,c);switch(J.type){case"text":return{type:"input_text",text:J.text,...et!=null&&{prompt_cache_breakpoint:et}};case"image-data":return{type:"input_image",image_url:`data:${J.mediaType};base64,${J.data}`,detail:(Se=(ye=J.providerOptions)==null?void 0:ye[c])==null?void 0:Se.imageDetail,...et!=null&&{prompt_cache_breakpoint:et}};case"image-url":return{type:"input_image",image_url:J.url,detail:(St=(Ve=J.providerOptions)==null?void 0:Ve[c])==null?void 0:St.imageDetail,...et!=null&&{prompt_cache_breakpoint:et}};case"file-data":return{type:"input_file",filename:(vt=J.filename)!=null?vt:"data",file_data:`data:${J.mediaType};base64,${J.data}`,...et!=null&&{prompt_cache_breakpoint:et}};case"file-url":return{type:"input_file",file_url:J.url,...et!=null&&{prompt_cache_breakpoint:et}};default:$e.push({type:"other",message:`unsupported custom tool content part type: ${J.type}`});return}}).filter(Ia);break;default:ae=""}xe.push({type:"custom_tool_call_output",call_id:ie.toolCallId,output:ae});continue}let Pe;switch(de.type){case"text":case"error-text":Pe=de.value;break;case"execution-denied":Pe=(Je=de.reason)!=null?Je:"Tool call execution denied.";break;case"json":case"error-json":Pe=JSON.stringify(de.value);break;case"content":Pe=de.value.map(ae=>{var J,ye,Se,Ve,St;const vt=Nr(ae.providerOptions,c);switch(ae.type){case"text":return{type:"input_text",text:ae.text,...vt!=null&&{prompt_cache_breakpoint:vt}};case"image-data":return{type:"input_image",image_url:`data:${ae.mediaType};base64,${ae.data}`,detail:(ye=(J=ae.providerOptions)==null?void 0:J[c])==null?void 0:ye.imageDetail,...vt!=null&&{prompt_cache_breakpoint:vt}};case"image-url":return{type:"input_image",image_url:ae.url,detail:(Ve=(Se=ae.providerOptions)==null?void 0:Se[c])==null?void 0:Ve.imageDetail,...vt!=null&&{prompt_cache_breakpoint:vt}};case"file-data":return{type:"input_file",filename:(St=ae.filename)!=null?St:"data",file_data:`data:${ae.mediaType};base64,${ae.data}`,...vt!=null&&{prompt_cache_breakpoint:vt}};case"file-url":return{type:"input_file",file_url:ae.url,...vt!=null&&{prompt_cache_breakpoint:vt}};default:{$e.push({type:"other",message:`unsupported tool content part type: ${ae.type}`});return}}}).filter(Ia);break}xe.push({type:"function_call_output",call_id:ie.toolCallId,output:Pe})}break}default:{const ie=Ze;throw new Error(`Unsupported role: ${ie}`)}}return!m&&xe.some(Ze=>"type"in Ze&&Ze.type==="reasoning"&&Ze.encrypted_content==null)&&($e.push({type:"other",message:"Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts."}),xe=xe.filter(Ze=>!("type"in Ze)||Ze.type!=="reasoning"||Ze.encrypted_content!=null)),{input:xe,warnings:$e}}var D2=N({itemId:w().nullish(),reasoningEncryptedContent:w().nullish()});function gi({finishReason:t,hasFunctionCall:r}){switch(t){case void 0:case null:return r?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return r?"tool-calls":"other"}}var ro=Wi(()=>st([w(),j(),Mt(),bc(),ue(ro),wt(w(),ro.optional())])),P2=N({type:Y("error"),sequence_number:j(),error:N({type:w(),code:w(),message:w(),param:w().nullish()})}),B2=N({type:Y("error"),sequence_number:j(),code:w().nullish(),message:w(),param:w().nullish()}),L2=Fe(()=>Le(st([N({type:Y("response.output_text.delta"),item_id:w(),delta:w(),logprobs:ue(N({token:w(),logprob:j(),top_logprobs:ue(N({token:w(),logprob:j()}))})).nullish()}),N({type:Ae(["response.completed","response.incomplete"]),response:N({incomplete_details:N({reason:w()}).nullish(),usage:N({input_tokens:j(),input_tokens_details:N({cached_tokens:j().nullish(),cache_write_tokens:j().nullish(),orchestration_input_tokens:j().nullish(),orchestration_input_cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:N({reasoning_tokens:j().nullish(),orchestration_output_tokens:j().nullish()}).nullish()}),reasoning:N({context:w().nullish()}).nullish(),service_tier:w().nullish()})}),N({type:Y("response.failed"),sequence_number:j(),response:N({error:N({code:w().nullish(),message:w()}).nullish(),incomplete_details:N({reason:w()}).nullish(),usage:N({input_tokens:j(),input_tokens_details:N({cached_tokens:j().nullish(),cache_write_tokens:j().nullish(),orchestration_input_tokens:j().nullish(),orchestration_input_cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:N({reasoning_tokens:j().nullish(),orchestration_output_tokens:j().nullish()}).nullish()}).nullish(),reasoning:N({context:w().nullish()}).nullish(),service_tier:w().nullish()})}),N({type:Y("response.created"),response:N({id:w(),created_at:j(),model:w(),service_tier:w().nullish()})}),N({type:Y("response.output_item.added"),output_index:j(),item:mt("type",[N({type:Y("message"),id:w(),phase:Ae(["commentary","final_answer"]).nullish()}),N({type:Y("reasoning"),id:w(),encrypted_content:w().nullish()}),N({type:Y("function_call"),id:w(),call_id:w(),name:w(),arguments:w(),namespace:w().nullish()}),N({type:Y("web_search_call"),id:w(),status:w()}),N({type:Y("computer_call"),id:w(),status:w()}),N({type:Y("file_search_call"),id:w()}),N({type:Y("image_generation_call"),id:w()}),N({type:Y("code_interpreter_call"),id:w(),container_id:w(),code:w().nullable(),outputs:ue(mt("type",[N({type:Y("logs"),logs:w()}),N({type:Y("image"),url:w()})])).nullable(),status:w()}),N({type:Y("mcp_call"),id:w(),status:w(),approval_request_id:w().nullish()}),N({type:Y("mcp_list_tools"),id:w()}),N({type:Y("mcp_approval_request"),id:w()}),N({type:Y("apply_patch_call"),id:w(),call_id:w(),status:Ae(["in_progress","completed"]),operation:mt("type",[N({type:Y("create_file"),path:w(),diff:w()}),N({type:Y("delete_file"),path:w()}),N({type:Y("update_file"),path:w(),diff:w()})])}),N({type:Y("custom_tool_call"),id:w(),call_id:w(),name:w(),input:w()}),N({type:Y("shell_call"),id:w(),call_id:w(),status:Ae(["in_progress","completed","incomplete"]),action:N({commands:ue(w())})}),N({type:Y("shell_call_output"),id:w(),call_id:w(),status:Ae(["in_progress","completed","incomplete"]),output:ue(N({stdout:w(),stderr:w(),outcome:mt("type",[N({type:Y("timeout")}),N({type:Y("exit"),exit_code:j()})])}))}),N({type:Y("tool_search_call"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),arguments:Cn()}),N({type:Y("tool_search_output"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),tools:ue(wt(w(),ro.optional()))})])}),N({type:Y("response.output_item.done"),output_index:j(),item:mt("type",[N({type:Y("message"),id:w(),phase:Ae(["commentary","final_answer"]).nullish()}),N({type:Y("reasoning"),id:w(),encrypted_content:w().nullish()}),N({type:Y("function_call"),id:w(),call_id:w(),name:w(),arguments:w(),status:Y("completed"),namespace:w().nullish()}),N({type:Y("custom_tool_call"),id:w(),call_id:w(),name:w(),input:w(),status:Y("completed")}),N({type:Y("code_interpreter_call"),id:w(),code:w().nullable(),container_id:w(),outputs:ue(mt("type",[N({type:Y("logs"),logs:w()}),N({type:Y("image"),url:w()})])).nullable()}),N({type:Y("image_generation_call"),id:w(),result:w()}),N({type:Y("web_search_call"),id:w(),status:w(),action:mt("type",[N({type:Y("search"),query:w().nullish(),queries:ue(w()).nullish(),sources:ue(mt("type",[N({type:Y("url"),url:w()}),N({type:Y("api"),name:w()})])).nullish()}),N({type:Y("open_page"),url:w().nullish()}),N({type:Y("find_in_page"),url:w().nullish(),pattern:w().nullish()})]).nullish()}),N({type:Y("file_search_call"),id:w(),queries:ue(w()),results:ue(N({attributes:wt(w(),st([w(),j(),Mt()])),file_id:w(),filename:w(),score:j(),text:w()})).nullish()}),N({type:Y("local_shell_call"),id:w(),call_id:w(),action:N({type:Y("exec"),command:ue(w()),timeout_ms:j().optional(),user:w().optional(),working_directory:w().optional(),env:wt(w(),w()).optional()})}),N({type:Y("computer_call"),id:w(),status:Y("completed")}),N({type:Y("mcp_call"),id:w(),status:w(),arguments:w(),name:w(),server_label:w(),output:w().nullish(),error:st([w(),N({type:w().optional(),code:st([j(),w()]).optional(),message:w().optional()}).loose()]).nullish(),approval_request_id:w().nullish()}),N({type:Y("mcp_list_tools"),id:w(),server_label:w(),tools:ue(N({name:w(),description:w().optional(),input_schema:xr(),annotations:wt(w(),Cn()).optional()})),error:st([w(),N({type:w().optional(),code:st([j(),w()]).optional(),message:w().optional()}).loose()]).optional()}),N({type:Y("mcp_approval_request"),id:w(),server_label:w(),name:w(),arguments:w(),approval_request_id:w().optional()}),N({type:Y("apply_patch_call"),id:w(),call_id:w(),status:Ae(["in_progress","completed"]),operation:mt("type",[N({type:Y("create_file"),path:w(),diff:w()}),N({type:Y("delete_file"),path:w()}),N({type:Y("update_file"),path:w(),diff:w()})])}),N({type:Y("shell_call"),id:w(),call_id:w(),status:Ae(["in_progress","completed","incomplete"]),action:N({commands:ue(w())})}),N({type:Y("shell_call_output"),id:w(),call_id:w(),status:Ae(["in_progress","completed","incomplete"]),output:ue(N({stdout:w(),stderr:w(),outcome:mt("type",[N({type:Y("timeout")}),N({type:Y("exit"),exit_code:j()})])}))}),N({type:Y("tool_search_call"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),arguments:Cn()}),N({type:Y("tool_search_output"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),tools:ue(wt(w(),ro.optional()))})])}),N({type:Y("response.function_call_arguments.delta"),item_id:w(),output_index:j(),delta:w()}),N({type:Y("response.custom_tool_call_input.delta"),item_id:w(),output_index:j(),delta:w()}),N({type:Y("response.image_generation_call.partial_image"),item_id:w(),output_index:j(),partial_image_b64:w()}),N({type:Y("response.code_interpreter_call_code.delta"),item_id:w(),output_index:j(),delta:w()}),N({type:Y("response.code_interpreter_call_code.done"),item_id:w(),output_index:j(),code:w()}),N({type:Y("response.output_text.annotation.added"),annotation:mt("type",[N({type:Y("url_citation"),start_index:j(),end_index:j(),url:w(),title:w()}),N({type:Y("file_citation"),file_id:w(),filename:w(),index:j()}),N({type:Y("container_file_citation"),container_id:w(),file_id:w(),filename:w(),start_index:j(),end_index:j()}),N({type:Y("file_path"),file_id:w(),index:j()})])}),N({type:Y("response.reasoning_summary_part.added"),item_id:w(),summary_index:j()}),N({type:Y("response.reasoning_summary_text.delta"),item_id:w(),summary_index:j(),delta:w()}),N({type:Y("response.reasoning_summary_part.done"),item_id:w(),summary_index:j()}),N({type:Y("response.apply_patch_call_operation_diff.delta"),item_id:w(),output_index:j(),delta:w(),obfuscation:w().nullish()}),N({type:Y("response.apply_patch_call_operation_diff.done"),item_id:w(),output_index:j(),diff:w()}),P2,B2,N({type:w()}).loose().transform(t=>({type:"unknown_chunk",message:t.type}))]))),F2=Fe(()=>Le(N({id:w().optional(),created_at:j().optional(),error:N({message:w(),type:w(),param:w().nullish(),code:w()}).nullish(),model:w().optional(),output:ue(mt("type",[N({type:Y("message"),role:Y("assistant"),id:w(),phase:Ae(["commentary","final_answer"]).nullish(),content:ue(N({type:Y("output_text"),text:w(),logprobs:ue(N({token:w(),logprob:j(),top_logprobs:ue(N({token:w(),logprob:j()}))})).nullish(),annotations:ue(mt("type",[N({type:Y("url_citation"),start_index:j(),end_index:j(),url:w(),title:w()}),N({type:Y("file_citation"),file_id:w(),filename:w(),index:j()}),N({type:Y("container_file_citation"),container_id:w(),file_id:w(),filename:w(),start_index:j(),end_index:j()}),N({type:Y("file_path"),file_id:w(),index:j()})]))}))}),N({type:Y("web_search_call"),id:w(),status:w(),action:mt("type",[N({type:Y("search"),query:w().nullish(),queries:ue(w()).nullish(),sources:ue(mt("type",[N({type:Y("url"),url:w()}),N({type:Y("api"),name:w()})])).nullish()}),N({type:Y("open_page"),url:w().nullish()}),N({type:Y("find_in_page"),url:w().nullish(),pattern:w().nullish()})]).nullish()}),N({type:Y("file_search_call"),id:w(),queries:ue(w()),results:ue(N({attributes:wt(w(),st([w(),j(),Mt()])),file_id:w(),filename:w(),score:j(),text:w()})).nullish()}),N({type:Y("code_interpreter_call"),id:w(),code:w().nullable(),container_id:w(),outputs:ue(mt("type",[N({type:Y("logs"),logs:w()}),N({type:Y("image"),url:w()})])).nullable()}),N({type:Y("image_generation_call"),id:w(),result:w()}),N({type:Y("local_shell_call"),id:w(),call_id:w(),action:N({type:Y("exec"),command:ue(w()),timeout_ms:j().optional(),user:w().optional(),working_directory:w().optional(),env:wt(w(),w()).optional()})}),N({type:Y("function_call"),call_id:w(),name:w(),arguments:w(),id:w(),namespace:w().nullish()}),N({type:Y("custom_tool_call"),call_id:w(),name:w(),input:w(),id:w()}),N({type:Y("computer_call"),id:w(),status:w().optional()}),N({type:Y("reasoning"),id:w(),encrypted_content:w().nullish(),summary:ue(N({type:Y("summary_text"),text:w()}))}),N({type:Y("mcp_call"),id:w(),status:w(),arguments:w(),name:w(),server_label:w(),output:w().nullish(),error:st([w(),N({type:w().optional(),code:st([j(),w()]).optional(),message:w().optional()}).loose()]).nullish(),approval_request_id:w().nullish()}),N({type:Y("mcp_list_tools"),id:w(),server_label:w(),tools:ue(N({name:w(),description:w().optional(),input_schema:xr(),annotations:wt(w(),Cn()).optional()})),error:st([w(),N({type:w().optional(),code:st([j(),w()]).optional(),message:w().optional()}).loose()]).optional()}),N({type:Y("mcp_approval_request"),id:w(),server_label:w(),name:w(),arguments:w(),approval_request_id:w().optional()}),N({type:Y("apply_patch_call"),id:w(),call_id:w(),status:Ae(["in_progress","completed"]),operation:mt("type",[N({type:Y("create_file"),path:w(),diff:w()}),N({type:Y("delete_file"),path:w()}),N({type:Y("update_file"),path:w(),diff:w()})])}),N({type:Y("shell_call"),id:w(),call_id:w(),status:Ae(["in_progress","completed","incomplete"]),action:N({commands:ue(w())})}),N({type:Y("shell_call_output"),id:w(),call_id:w(),status:Ae(["in_progress","completed","incomplete"]),output:ue(N({stdout:w(),stderr:w(),outcome:mt("type",[N({type:Y("timeout")}),N({type:Y("exit"),exit_code:j()})])}))}),N({type:Y("tool_search_call"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),arguments:Cn()}),N({type:Y("tool_search_output"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),tools:ue(wt(w(),ro.optional()))})])).optional(),service_tier:w().nullish(),reasoning:N({context:w().nullish()}).nullish(),incomplete_details:N({reason:w()}).nullish(),usage:N({input_tokens:j(),input_tokens_details:N({cached_tokens:j().nullish(),cache_write_tokens:j().nullish(),orchestration_input_tokens:j().nullish(),orchestration_input_cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:N({reasoning_tokens:j().nullish(),orchestration_output_tokens:j().nullish()}).nullish()}).optional()}))),Nu=20,Za=Fe(()=>Le(N({conversation:w().nullish(),include:ue(Ae(["reasoning.encrypted_content","file_search_call.results","web_search_call.results","message.output_text.logprobs"])).nullish(),instructions:w().nullish(),logprobs:st([Mt(),j().min(1).max(Nu)]).optional(),maxToolCalls:j().nullish(),metadata:xr().nullish(),parallelToolCalls:Mt().nullish(),previousResponseId:w().nullish(),promptCacheKey:w().nullish(),promptCacheOptions:N({mode:Ae(["implicit","explicit"]).optional(),ttl:Y("30m").optional()}).optional(),promptCacheRetention:Ae(["in_memory","24h"]).nullish(),reasoningEffort:w().nullish(),reasoningMode:Ae(["standard","pro"]).optional(),reasoningContext:Ae(["auto","current_turn","all_turns"]).optional(),reasoningSummary:w().nullish(),safetyIdentifier:w().nullish(),serviceTier:Ae(["auto","flex","priority","default"]).nullish(),store:Mt().nullish(),passThroughUnsupportedFiles:Mt().optional(),strictJsonSchema:Mt().nullish(),textVerbosity:Ae(["low","medium","high"]).nullish(),truncation:Ae(["auto","disabled"]).nullish(),user:w().nullish(),systemMessageMode:Ae(["system","developer","remove"]).optional(),forceReasoning:Mt().optional(),allowedTools:N({toolNames:ue(w()).min(1),mode:Ae(["auto","required"]).optional()}).optional()})));async function U2({tools:t,toolChoice:r,allowedTools:i,toolNameMapping:c,customProviderToolNames:d}){var f,m,x;t=t?.length?t:void 0;const v=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:v};const g=[],E=new Map,A=d??new Set;for(const T of t)switch(T.type){case"function":{const S=(f=T.providerOptions)==null?void 0:f.openai,P=z2({tool:T,options:S}),M=S?.namespace;if(M==null)g.push(P);else{let ee=E.get(M.name);if(ee==null)ee={type:"namespace",name:M.name,description:M.description,tools:[]},E.set(M.name,ee),g.push(ee);else if(ee.description!==M.description)throw new Mn({functionality:`conflicting descriptions for OpenAI tool namespace "${M.name}"`});ee.tools.push(P)}break}case"provider":{switch(T.id){case"openai.file_search":{const S=await Dt({value:T.args,schema:n2});g.push({type:"file_search",vector_store_ids:S.vectorStoreIds,max_num_results:S.maxNumResults,ranking_options:S.ranking?{ranker:S.ranking.ranker,score_threshold:S.ranking.scoreThreshold}:void 0,filters:S.filters});break}case"openai.local_shell":{g.push({type:"local_shell"});break}case"openai.shell":{const S=await Dt({value:T.args,schema:f2});g.push({type:"shell",...S.environment&&{environment:V2(S.environment)}});break}case"openai.apply_patch":{g.push({type:"apply_patch"});break}case"openai.web_search_preview":{const S=await Dt({value:T.args,schema:C2});g.push({type:"web_search_preview",search_context_size:S.searchContextSize,user_location:S.userLocation});break}case"openai.web_search":{const S=await Dt({value:T.args,schema:x2});g.push({type:"web_search",filters:S.filters!=null?{allowed_domains:S.filters.allowedDomains}:void 0,external_web_access:S.externalWebAccess,search_context_size:S.searchContextSize,user_location:S.userLocation});break}case"openai.code_interpreter":{const S=await Dt({value:T.args,schema:Xg});g.push({type:"code_interpreter",container:S.container==null?{type:"auto",file_ids:void 0}:typeof S.container=="string"?S.container:{type:"auto",file_ids:S.container.fileIds}});break}case"openai.image_generation":{const S=await Dt({value:T.args,schema:i2});g.push({type:"image_generation",background:S.background,input_fidelity:S.inputFidelity,input_image_mask:S.inputImageMask?{file_id:S.inputImageMask.fileId,image_url:S.inputImageMask.imageUrl}:void 0,model:S.model,moderation:S.moderation,partial_images:S.partialImages,quality:S.quality,output_compression:S.outputCompression,output_format:S.outputFormat,size:S.size});break}case"openai.mcp":{const S=await Dt({value:T.args,schema:I2}),P=$=>({tool_names:$.toolNames}),M=S.requireApproval,ee=M==null?void 0:typeof M=="string"?M:M.never!=null?{never:P(M.never)}:void 0;g.push({type:"mcp",server_label:S.serverLabel,allowed_tools:Array.isArray(S.allowedTools)?S.allowedTools:S.allowedTools?{read_only:S.allowedTools.readOnly,tool_names:S.allowedTools.toolNames}:void 0,authorization:S.authorization,connector_id:S.connectorId,headers:S.headers,require_approval:ee??"never",server_description:S.serverDescription,server_url:S.serverUrl});break}case"openai.custom":{const S=await Dt({value:T.args,schema:Jg});g.push({type:"custom",name:S.name,description:S.description,format:S.format}),A.add(S.name);break}case"openai.tool_search":{const S=await Dt({value:T.args,schema:p2});g.push({type:"tool_search",...S.execution!=null?{execution:S.execution}:{},...S.description!=null?{description:S.description}:{},...S.parameters!=null?{parameters:S.parameters}:{}});break}}break}default:v.push({type:"unsupported",feature:`function tool ${T}`});break}if(i!=null)return{tools:g,toolChoice:{type:"allowed_tools",mode:(m=i.mode)!=null?m:"auto",tools:i.toolNames.map(T=>{var S;return{type:"function",name:(S=c?.toProviderToolName(T))!=null?S:T}})},toolWarnings:v};if(r==null)return{tools:g,toolChoice:void 0,toolWarnings:v};const D=r.type;switch(D){case"auto":case"none":case"required":return{tools:g,toolChoice:D,toolWarnings:v};case"tool":{const T=(x=c?.toProviderToolName(r.toolName))!=null?x:r.toolName;return{tools:g,toolChoice:T==="code_interpreter"||T==="file_search"||T==="image_generation"||T==="web_search_preview"||T==="web_search"||T==="mcp"||T==="apply_patch"?{type:T}:A.has(T)?{type:"custom",name:T}:{type:"function",name:T},toolWarnings:v}}default:{const T=D;throw new Mn({functionality:`tool choice type: ${T}`})}}}function z2({tool:t,options:r}){const i=r?.deferLoading;return{type:"function",name:t.name,description:t.description,parameters:t.inputSchema,...t.strict!=null?{strict:t.strict}:{},...i!=null?{defer_loading:i}:{}}}function V2(t){if(t.type==="containerReference")return{type:"container_reference",container_id:t.containerId};if(t.type==="containerAuto"){const i=t;return{type:"container_auto",file_ids:i.fileIds,memory_limit:i.memoryLimit,network_policy:i.networkPolicy==null?void 0:i.networkPolicy.type==="disabled"?{type:"disabled"}:{type:"allowlist",allowed_domains:i.networkPolicy.allowedDomains,domain_secrets:i.networkPolicy.domainSecrets},skills:Z2(i.skills)}}return{type:"local",skills:t.skills}}function Z2(t){return t?.map(r=>r.type==="skillReference"?{type:"skill_reference",skill_id:r.skillId,version:r.version}:{type:"inline",name:r.name,description:r.description,source:{type:"base64",media_type:r.source.mediaType,data:r.source.data}})}function $a(t){var r,i;const c={};for(const d of t)if(d.role==="assistant")for(const f of d.content){if(f.type!=="tool-call")continue;const m=(i=(r=f.providerOptions)==null?void 0:r.openai)==null?void 0:i.approvalRequestId;m!=null&&(c[m]=f.toolCallId)}return c}var $2=class{constructor(t,r){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=t,this.config=r}get provider(){return this.config.provider}async getArgs({maxOutputTokens:t,temperature:r,stopSequences:i,topP:c,topK:d,presencePenalty:f,frequencyPenalty:m,seed:x,prompt:v,providerOptions:g,tools:E,toolChoice:A,responseFormat:D}){var T,S,P,M,ee,$,F,re,Z,B,L;const W=[],z=_u(this.modelId);d!=null&&W.push({type:"unsupported",feature:"topK"}),x!=null&&W.push({type:"unsupported",feature:"seed"}),f!=null&&W.push({type:"unsupported",feature:"presencePenalty"}),m!=null&&W.push({type:"unsupported",feature:"frequencyPenalty"}),i!=null&&W.push({type:"unsupported",feature:"stopSequences"});const we=this.config.provider.includes("azure")?"azure":"openai";let G=await An({provider:we,providerOptions:g,schema:Za});G==null&&we!=="openai"&&(G=await An({provider:"openai",providerOptions:g,schema:Za}));const me=(T=G?.forceReasoning)!=null?T:z.isReasoningModel;G?.conversation&&G?.previousResponseId&&W.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const fe=Gp({tools:E,providerToolNames:{"openai.code_interpreter":"code_interpreter","openai.file_search":"file_search","openai.image_generation":"image_generation","openai.local_shell":"local_shell","openai.shell":"shell","openai.web_search":"web_search","openai.web_search_preview":"web_search_preview","openai.mcp":"mcp","openai.apply_patch":"apply_patch","openai.tool_search":"tool_search"},resolveProviderToolName:ae=>ae.id==="openai.custom"?ae.args.name:void 0}),te=new Set,{tools:q,toolChoice:ke,toolWarnings:le}=await U2({tools:E,toolChoice:A,allowedTools:(S=G?.allowedTools)!=null?S:void 0,toolNameMapping:fe,customProviderToolNames:te}),{input:Te,warnings:Je}=await M2({prompt:v,toolNameMapping:fe,systemMessageMode:(P=G?.systemMessageMode)!=null?P:me?"developer":z.systemMessageMode,providerOptionsName:we,fileIdPrefixes:this.config.fileIdPrefixes,passThroughUnsupportedFiles:(M=G?.passThroughUnsupportedFiles)!=null?M:!1,store:(ee=G?.store)!=null?ee:!0,hasConversation:G?.conversation!=null,hasPreviousResponseId:G?.previousResponseId!=null,hasLocalShellTool:Ze("openai.local_shell"),hasShellTool:Ze("openai.shell"),hasApplyPatchTool:Ze("openai.apply_patch"),customProviderToolNames:te.size>0?te:void 0});W.push(...Je);const xe=($=G?.strictJsonSchema)!=null?$:!0;let $e=G?.include;function Ue(ae){$e==null?$e=[ae]:$e.includes(ae)||($e=[...$e,ae])}function Ze(ae){return E?.find(J=>J.type==="provider"&&J.id===ae)!=null}const qe=typeof G?.logprobs=="number"?G?.logprobs:G?.logprobs===!0?Nu:void 0;qe&&Ue("message.output_text.logprobs");const ze=(F=E?.find(ae=>ae.type==="provider"&&(ae.id==="openai.web_search"||ae.id==="openai.web_search_preview")))==null?void 0:F.name;ze&&Ue("web_search_call.action.sources"),Ze("openai.code_interpreter")&&Ue("code_interpreter_call.outputs");const ie=G?.store;ie===!1&&me&&Ue("reasoning.encrypted_content");const de={model:this.modelId,input:Te,temperature:r,top_p:c,max_output_tokens:t,...(D?.type==="json"||G?.textVerbosity)&&{text:{...D?.type==="json"&&{format:D.schema!=null?{type:"json_schema",strict:xe,name:(re=D.name)!=null?re:"response",description:D.description,schema:D.schema}:{type:"json_object"}},...G?.textVerbosity&&{verbosity:G.textVerbosity}}},conversation:G?.conversation,max_tool_calls:G?.maxToolCalls,metadata:G?.metadata,parallel_tool_calls:G?.parallelToolCalls,previous_response_id:G?.previousResponseId,store:ie,user:G?.user,instructions:G?.instructions,service_tier:G?.serviceTier,include:$e,prompt_cache_key:G?.promptCacheKey,prompt_cache_options:G?.promptCacheOptions,prompt_cache_retention:G?.promptCacheRetention,safety_identifier:G?.safetyIdentifier,top_logprobs:qe,truncation:G?.truncation,...me&&(G?.reasoningEffort!=null||G?.reasoningSummary!=null||G?.reasoningMode!=null||G?.reasoningContext!=null)&&{reasoning:{...G?.reasoningEffort!=null&&{effort:G.reasoningEffort},...G?.reasoningSummary!=null&&{summary:G.reasoningSummary},...G?.reasoningMode!=null&&{mode:G.reasoningMode},...G?.reasoningContext!=null&&{context:G.reasoningContext}}}};me?G?.reasoningEffort==="none"&&z.supportsNonReasoningParameters||(de.temperature!=null&&(de.temperature=void 0,W.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),de.top_p!=null&&(de.top_p=void 0,W.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(G?.reasoningEffort!=null&&W.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),G?.reasoningSummary!=null&&W.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"}),G?.reasoningMode!=null&&W.push({type:"unsupported",feature:"reasoningMode",details:"reasoningMode is not supported for non-reasoning models"}),G?.reasoningContext!=null&&W.push({type:"unsupported",feature:"reasoningContext",details:"reasoningContext is not supported for non-reasoning models"})),G?.serviceTier==="flex"&&!z.supportsFlexProcessing&&(W.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete de.service_tier),G?.serviceTier==="priority"&&!z.supportsPriorityProcessing&&(W.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete de.service_tier);const _e=(L=(B=(Z=E?.find(ae=>ae.type==="provider"&&ae.id==="openai.shell"))==null?void 0:Z.args)==null?void 0:B.environment)==null?void 0:L.type,Pe=_e==="containerAuto"||_e==="containerReference";return{webSearchToolName:ze,args:{...de,tools:q,tool_choice:ke},warnings:[...W,...le],store:ie,toolNameMapping:fe,providerOptionsName:we,isShellProviderExecuted:Pe}}async doGenerate(t){var r,i,c,d,f,m,x,v,g,E,A,D,T,S,P,M,ee,$,F,re,Z,B,L,W,z,we,G,me,fe;const{args:te,warnings:q,webSearchToolName:ke,toolNameMapping:le,providerOptionsName:Te,isShellProviderExecuted:Je}=await this.getArgs(t),xe=this.config.url({path:"/responses",modelId:this.modelId}),$e=$a(t.prompt),{responseHeaders:Ue,value:Ze,rawValue:qe}=await Zn({url:xe,headers:bn(this.config.headers(),t.headers),body:te,failedResponseHandler:En,successfulResponseHandler:mr(F2),abortSignal:t.abortSignal,fetch:this.config.fetch});if(Ze.error)throw new Kt({message:Ze.error.message,url:xe,requestBodyValues:te,statusCode:400,responseHeaders:Ue,responseBody:qe,isRetryable:!1});const ze=[],ie=[];let de=!1;const _e=[];for(const J of Ze.output)switch(J.type){case"reasoning":{J.summary.length===0&&J.summary.push({type:"summary_text",text:""});for(const ye of J.summary)ze.push({type:"reasoning",text:ye.text,providerMetadata:{[Te]:{itemId:J.id,reasoningEncryptedContent:(r=J.encrypted_content)!=null?r:null}}});break}case"image_generation_call":{ze.push({type:"tool-call",toolCallId:J.id,toolName:le.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),ze.push({type:"tool-result",toolCallId:J.id,toolName:le.toCustomToolName("image_generation"),result:{result:J.result}});break}case"tool_search_call":{const ye=(i=J.call_id)!=null?i:J.id,Se=J.execution==="server";Se&&_e.push(ye),ze.push({type:"tool-call",toolCallId:ye,toolName:le.toCustomToolName("tool_search"),input:JSON.stringify({arguments:J.arguments,call_id:J.call_id}),...Se?{providerExecuted:!0}:{},providerMetadata:{[Te]:{itemId:J.id}}});break}case"tool_search_output":{const ye=(d=(c=J.call_id)!=null?c:_e.shift())!=null?d:J.id;ze.push({type:"tool-result",toolCallId:ye,toolName:le.toCustomToolName("tool_search"),result:{tools:J.tools},providerMetadata:{[Te]:{itemId:J.id}}});break}case"local_shell_call":{ze.push({type:"tool-call",toolCallId:J.call_id,toolName:le.toCustomToolName("local_shell"),input:JSON.stringify({action:J.action}),providerMetadata:{[Te]:{itemId:J.id}}});break}case"shell_call":{ze.push({type:"tool-call",toolCallId:J.call_id,toolName:le.toCustomToolName("shell"),input:JSON.stringify({action:{commands:J.action.commands}}),...Je&&{providerExecuted:!0},providerMetadata:{[Te]:{itemId:J.id}}});break}case"shell_call_output":{ze.push({type:"tool-result",toolCallId:J.call_id,toolName:le.toCustomToolName("shell"),result:{output:J.output.map(ye=>({stdout:ye.stdout,stderr:ye.stderr,outcome:ye.outcome.type==="exit"?{type:"exit",exitCode:ye.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const ye of J.content){(m=(f=t.providerOptions)==null?void 0:f[Te])!=null&&m.logprobs&&ye.logprobs&&ie.push(ye.logprobs);const Se={itemId:J.id,...J.phase!=null&&{phase:J.phase},...ye.annotations.length>0&&{annotations:ye.annotations}};ze.push({type:"text",text:ye.text,providerMetadata:{[Te]:Se}});for(const Ve of ye.annotations)Ve.type==="url_citation"?ze.push({type:"source",sourceType:"url",id:(g=(v=(x=this.config).generateId)==null?void 0:v.call(x))!=null?g:rn(),url:Ve.url,title:Ve.title}):Ve.type==="file_citation"?ze.push({type:"source",sourceType:"document",id:(D=(A=(E=this.config).generateId)==null?void 0:A.call(E))!=null?D:rn(),mediaType:"text/plain",title:Ve.filename,filename:Ve.filename,providerMetadata:{[Te]:{type:Ve.type,fileId:Ve.file_id,index:Ve.index}}}):Ve.type==="container_file_citation"?ze.push({type:"source",sourceType:"document",id:(P=(S=(T=this.config).generateId)==null?void 0:S.call(T))!=null?P:rn(),mediaType:"text/plain",title:Ve.filename,filename:Ve.filename,providerMetadata:{[Te]:{type:Ve.type,fileId:Ve.file_id,containerId:Ve.container_id}}}):Ve.type==="file_path"&&ze.push({type:"source",sourceType:"document",id:($=(ee=(M=this.config).generateId)==null?void 0:ee.call(M))!=null?$:rn(),mediaType:"application/octet-stream",title:Ve.file_id,filename:Ve.file_id,providerMetadata:{[Te]:{type:Ve.type,fileId:Ve.file_id,index:Ve.index}}})}break}case"function_call":{de=!0,ze.push({type:"tool-call",toolCallId:J.call_id,toolName:J.name,input:J.arguments,providerMetadata:{[Te]:{itemId:J.id,...J.namespace!=null&&{namespace:J.namespace}}}});break}case"custom_tool_call":{de=!0;const ye=le.toCustomToolName(J.name);ze.push({type:"tool-call",toolCallId:J.call_id,toolName:ye,input:JSON.stringify(J.input),providerMetadata:{[Te]:{itemId:J.id}}});break}case"web_search_call":{ze.push({type:"tool-call",toolCallId:J.id,toolName:le.toCustomToolName(ke??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),ze.push({type:"tool-result",toolCallId:J.id,toolName:le.toCustomToolName(ke??"web_search"),result:Ga(J.action)});break}case"mcp_call":{const ye=J.approval_request_id!=null&&(F=$e[J.approval_request_id])!=null?F:J.id,Se=`mcp.${J.name}`;ze.push({type:"tool-call",toolCallId:ye,toolName:Se,input:J.arguments,providerExecuted:!0,dynamic:!0}),ze.push({type:"tool-result",toolCallId:ye,toolName:Se,result:{type:"call",serverLabel:J.server_label,name:J.name,arguments:J.arguments,...J.output!=null?{output:J.output}:{},...J.error!=null?{error:J.error}:{}},providerMetadata:{[Te]:{itemId:J.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const ye=(re=J.approval_request_id)!=null?re:J.id,Se=(L=(B=(Z=this.config).generateId)==null?void 0:B.call(Z))!=null?L:rn(),Ve=`mcp.${J.name}`;ze.push({type:"tool-call",toolCallId:Se,toolName:Ve,input:J.arguments,providerExecuted:!0,dynamic:!0}),ze.push({type:"tool-approval-request",approvalId:ye,toolCallId:Se});break}case"computer_call":{ze.push({type:"tool-call",toolCallId:J.id,toolName:le.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),ze.push({type:"tool-result",toolCallId:J.id,toolName:le.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:J.status||"completed"}});break}case"file_search_call":{ze.push({type:"tool-call",toolCallId:J.id,toolName:le.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),ze.push({type:"tool-result",toolCallId:J.id,toolName:le.toCustomToolName("file_search"),result:{queries:J.queries,results:(z=(W=J.results)==null?void 0:W.map(ye=>({attributes:ye.attributes,fileId:ye.file_id,filename:ye.filename,score:ye.score,text:ye.text})))!=null?z:null}});break}case"code_interpreter_call":{ze.push({type:"tool-call",toolCallId:J.id,toolName:le.toCustomToolName("code_interpreter"),input:JSON.stringify({code:J.code,containerId:J.container_id}),providerExecuted:!0}),ze.push({type:"tool-result",toolCallId:J.id,toolName:le.toCustomToolName("code_interpreter"),result:{outputs:J.outputs}});break}case"apply_patch_call":{ze.push({type:"tool-call",toolCallId:J.call_id,toolName:le.toCustomToolName("apply_patch"),input:JSON.stringify({callId:J.call_id,operation:J.operation}),providerMetadata:{[Te]:{itemId:J.id}}});break}}const Pe={[Te]:{responseId:Ze.id,...ie.length>0?{logprobs:ie}:{},...typeof Ze.service_tier=="string"?{serviceTier:Ze.service_tier}:{},...((we=Ze.reasoning)==null?void 0:we.context)!=null?{reasoningContext:Ze.reasoning.context}:{}}},ae=Ze.usage;return{content:ze,finishReason:{unified:gi({finishReason:(G=Ze.incomplete_details)==null?void 0:G.reason,hasFunctionCall:de}),raw:(fe=(me=Ze.incomplete_details)==null?void 0:me.reason)!=null?fe:void 0},usage:za(ae),request:{body:te},response:{id:Ze.id,timestamp:new Date(Ze.created_at*1e3),modelId:Ze.model,headers:Ue,body:qe},providerMetadata:Pe,warnings:q}}async doStream(t){const{args:r,warnings:i,webSearchToolName:c,toolNameMapping:d,store:f,providerOptionsName:m,isShellProviderExecuted:x}=await this.getArgs(t),v=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:g,value:E}=await Zn({url:v,headers:bn(this.config.headers(),t.headers),body:{...r,stream:!0},failedResponseHandler:En,successfulResponseHandler:Ji(L2),abortSignal:t.abortSignal,fetch:this.config.fetch}),A=await es({stream:E,getError:fe=>Wa(fe)||ja(fe)&&fe.response.error!=null?fe:void 0,isOutputChunk:ix,url:v,requestBodyValues:r,responseHeaders:g}),D=this,T=$a(t.prompt),S=new Map;let P={unified:"other",raw:void 0},M;const ee=[];let $=null;const F={},re=[];let Z,B=!1;const L={};let W,z;const we=[];let G=!1;return{stream:A.pipeThrough(new TransformStream({start(fe){fe.enqueue({type:"stream-start",warnings:i})},transform(fe,te){var q,ke,le,Te,Je,xe,$e,Ue,Ze,qe,ze,ie,de,_e,Pe,ae,J,ye,Se,Ve,St,vt,et,nt,Xe,In,be,Bn,$n,qt,jn,Ft,rr,sn,At,or,Ln,wr,gt,ge;if(t.includeRawChunks&&te.enqueue({type:"raw",rawValue:fe.rawValue}),!fe.success){const ne=H2(fe.rawValue)?W2({value:fe.rawValue,cause:fe.error,url:v,requestBodyValues:r,responseHeaders:g}):fe.error;P={unified:"error",raw:void 0},te.enqueue({type:"error",error:ne});return}const O=fe.value;if(Ha(O)){if(O.item.type==="function_call")F[O.output_index]={toolName:O.item.name,toolCallId:O.item.call_id},te.enqueue({type:"tool-input-start",id:O.item.call_id,toolName:O.item.name});else if(O.item.type==="custom_tool_call"){const ne=d.toCustomToolName(O.item.name);F[O.output_index]={toolName:ne,toolCallId:O.item.call_id},te.enqueue({type:"tool-input-start",id:O.item.call_id,toolName:ne})}else if(O.item.type==="web_search_call")F[O.output_index]={toolName:d.toCustomToolName(c??"web_search"),toolCallId:O.item.id},te.enqueue({type:"tool-input-start",id:O.item.id,toolName:d.toCustomToolName(c??"web_search"),providerExecuted:!0}),te.enqueue({type:"tool-input-end",id:O.item.id}),te.enqueue({type:"tool-call",toolCallId:O.item.id,toolName:d.toCustomToolName(c??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(O.item.type==="computer_call")F[O.output_index]={toolName:d.toCustomToolName("computer_use"),toolCallId:O.item.id},te.enqueue({type:"tool-input-start",id:O.item.id,toolName:d.toCustomToolName("computer_use"),providerExecuted:!0});else if(O.item.type==="code_interpreter_call")F[O.output_index]={toolName:d.toCustomToolName("code_interpreter"),toolCallId:O.item.id,codeInterpreter:{containerId:O.item.container_id}},te.enqueue({type:"tool-input-start",id:O.item.id,toolName:d.toCustomToolName("code_interpreter"),providerExecuted:!0}),te.enqueue({type:"tool-input-delta",id:O.item.id,delta:`{"containerId":"${O.item.container_id}","code":"`});else if(O.item.type==="file_search_call")te.enqueue({type:"tool-call",toolCallId:O.item.id,toolName:d.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(O.item.type==="image_generation_call")te.enqueue({type:"tool-call",toolCallId:O.item.id,toolName:d.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(O.item.type==="tool_search_call"){const ne=O.item.id,Me=d.toCustomToolName("tool_search"),Ee=O.item.execution==="server";F[O.output_index]={toolName:Me,toolCallId:ne,toolSearchExecution:(q=O.item.execution)!=null?q:"server"},Ee&&te.enqueue({type:"tool-input-start",id:ne,toolName:Me,providerExecuted:!0})}else if(O.item.type!=="tool_search_output"){if(!(O.item.type==="mcp_call"||O.item.type==="mcp_list_tools"||O.item.type==="mcp_approval_request"))if(O.item.type==="apply_patch_call"){const{call_id:ne,operation:Me}=O.item;if(F[O.output_index]={toolName:d.toCustomToolName("apply_patch"),toolCallId:ne,applyPatch:{hasDiff:Me.type==="delete_file",endEmitted:Me.type==="delete_file"}},te.enqueue({type:"tool-input-start",id:ne,toolName:d.toCustomToolName("apply_patch")}),Me.type==="delete_file"){const Ee=JSON.stringify({callId:ne,operation:Me});te.enqueue({type:"tool-input-delta",id:ne,delta:Ee}),te.enqueue({type:"tool-input-end",id:ne})}else te.enqueue({type:"tool-input-delta",id:ne,delta:`{"callId":"${fr(ne)}","operation":{"type":"${fr(Me.type)}","path":"${fr(Me.path)}","diff":"`})}else O.item.type==="shell_call"?F[O.output_index]={toolName:d.toCustomToolName("shell"),toolCallId:O.item.call_id}:O.item.type==="shell_call_output"||(O.item.type==="message"?(re.splice(0,re.length),Z=(ke=O.item.phase)!=null?ke:void 0,te.enqueue({type:"text-start",id:O.item.id,providerMetadata:{[m]:{itemId:O.item.id,...O.item.phase!=null&&{phase:O.item.phase}}}})):Ha(O)&&O.item.type==="reasoning"&&(L[O.item.id]={encryptedContent:O.item.encrypted_content,summaryParts:{0:"active"}},te.enqueue({type:"reasoning-start",id:`${O.item.id}:0`,providerMetadata:{[m]:{itemId:O.item.id,reasoningEncryptedContent:(le=O.item.encrypted_content)!=null?le:null}}})))}}else if(q2(O)){if(O.item.type==="message"){const ne=(Te=O.item.phase)!=null?Te:Z;Z=void 0,te.enqueue({type:"text-end",id:O.item.id,providerMetadata:{[m]:{itemId:O.item.id,...ne!=null&&{phase:ne},...re.length>0&&{annotations:re}}}})}else if(O.item.type==="function_call")F[O.output_index]=void 0,B=!0,te.enqueue({type:"tool-input-end",id:O.item.call_id,...O.item.namespace!=null&&{providerMetadata:{[m]:{namespace:O.item.namespace}}}}),te.enqueue({type:"tool-call",toolCallId:O.item.call_id,toolName:O.item.name,input:O.item.arguments,providerMetadata:{[m]:{itemId:O.item.id,...O.item.namespace!=null&&{namespace:O.item.namespace}}}});else if(O.item.type==="custom_tool_call"){F[O.output_index]=void 0,B=!0;const ne=d.toCustomToolName(O.item.name);te.enqueue({type:"tool-input-end",id:O.item.call_id}),te.enqueue({type:"tool-call",toolCallId:O.item.call_id,toolName:ne,input:JSON.stringify(O.item.input),providerMetadata:{[m]:{itemId:O.item.id}}})}else if(O.item.type==="web_search_call")F[O.output_index]=void 0,te.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:d.toCustomToolName(c??"web_search"),result:Ga(O.item.action)});else if(O.item.type==="computer_call")F[O.output_index]=void 0,te.enqueue({type:"tool-input-end",id:O.item.id}),te.enqueue({type:"tool-call",toolCallId:O.item.id,toolName:d.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),te.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:d.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:O.item.status||"completed"}});else if(O.item.type==="file_search_call")F[O.output_index]=void 0,te.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:d.toCustomToolName("file_search"),result:{queries:O.item.queries,results:(xe=(Je=O.item.results)==null?void 0:Je.map(ne=>({attributes:ne.attributes,fileId:ne.file_id,filename:ne.filename,score:ne.score,text:ne.text})))!=null?xe:null}});else if(O.item.type==="code_interpreter_call")F[O.output_index]=void 0,te.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:d.toCustomToolName("code_interpreter"),result:{outputs:O.item.outputs}});else if(O.item.type==="image_generation_call")te.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:d.toCustomToolName("image_generation"),result:{result:O.item.result}});else if(O.item.type==="tool_search_call"){const ne=F[O.output_index],Me=O.item.execution==="server";if(ne!=null){const Ee=Me?ne.toolCallId:($e=O.item.call_id)!=null?$e:O.item.id;Me?we.push(Ee):te.enqueue({type:"tool-input-start",id:Ee,toolName:ne.toolName}),te.enqueue({type:"tool-input-end",id:Ee}),te.enqueue({type:"tool-call",toolCallId:Ee,toolName:ne.toolName,input:JSON.stringify({arguments:O.item.arguments,call_id:Me?null:Ee}),...Me?{providerExecuted:!0}:{},providerMetadata:{[m]:{itemId:O.item.id}}})}F[O.output_index]=void 0}else if(O.item.type==="tool_search_output"){const ne=(Ze=(Ue=O.item.call_id)!=null?Ue:we.shift())!=null?Ze:O.item.id;te.enqueue({type:"tool-result",toolCallId:ne,toolName:d.toCustomToolName("tool_search"),result:{tools:O.item.tools},providerMetadata:{[m]:{itemId:O.item.id}}})}else if(O.item.type==="mcp_call"){F[O.output_index]=void 0;const ne=(qe=O.item.approval_request_id)!=null?qe:void 0,Me=ne!=null&&(ie=(ze=S.get(ne))!=null?ze:T[ne])!=null?ie:O.item.id,Ee=`mcp.${O.item.name}`;te.enqueue({type:"tool-call",toolCallId:Me,toolName:Ee,input:O.item.arguments,providerExecuted:!0,dynamic:!0}),te.enqueue({type:"tool-result",toolCallId:Me,toolName:Ee,result:{type:"call",serverLabel:O.item.server_label,name:O.item.name,arguments:O.item.arguments,...O.item.output!=null?{output:O.item.output}:{},...O.item.error!=null?{error:O.item.error}:{}},providerMetadata:{[m]:{itemId:O.item.id}}})}else if(O.item.type==="mcp_list_tools")F[O.output_index]=void 0;else if(O.item.type==="apply_patch_call"){const ne=F[O.output_index];ne?.applyPatch&&!ne.applyPatch.endEmitted&&O.item.operation.type!=="delete_file"&&(ne.applyPatch.hasDiff||te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:fr(O.item.operation.diff)}),te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:'"}}'}),te.enqueue({type:"tool-input-end",id:ne.toolCallId}),ne.applyPatch.endEmitted=!0),ne&&O.item.status==="completed"&&te.enqueue({type:"tool-call",toolCallId:ne.toolCallId,toolName:d.toCustomToolName("apply_patch"),input:JSON.stringify({callId:O.item.call_id,operation:O.item.operation}),providerMetadata:{[m]:{itemId:O.item.id}}}),F[O.output_index]=void 0}else if(O.item.type==="mcp_approval_request"){F[O.output_index]=void 0;const ne=(Pe=(_e=(de=D.config).generateId)==null?void 0:_e.call(de))!=null?Pe:rn(),Me=(ae=O.item.approval_request_id)!=null?ae:O.item.id;S.set(Me,ne);const Ee=`mcp.${O.item.name}`;te.enqueue({type:"tool-call",toolCallId:ne,toolName:Ee,input:O.item.arguments,providerExecuted:!0,dynamic:!0}),te.enqueue({type:"tool-approval-request",approvalId:Me,toolCallId:ne})}else if(O.item.type==="local_shell_call")F[O.output_index]=void 0,te.enqueue({type:"tool-call",toolCallId:O.item.call_id,toolName:d.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:O.item.action.command,timeoutMs:O.item.action.timeout_ms,user:O.item.action.user,workingDirectory:O.item.action.working_directory,env:O.item.action.env}}),providerMetadata:{[m]:{itemId:O.item.id}}});else if(O.item.type==="shell_call")F[O.output_index]=void 0,te.enqueue({type:"tool-call",toolCallId:O.item.call_id,toolName:d.toCustomToolName("shell"),input:JSON.stringify({action:{commands:O.item.action.commands}}),...x&&{providerExecuted:!0},providerMetadata:{[m]:{itemId:O.item.id}}});else if(O.item.type==="shell_call_output")te.enqueue({type:"tool-result",toolCallId:O.item.call_id,toolName:d.toCustomToolName("shell"),result:{output:O.item.output.map(ne=>({stdout:ne.stdout,stderr:ne.stderr,outcome:ne.outcome.type==="exit"?{type:"exit",exitCode:ne.outcome.exit_code}:{type:"timeout"}}))}});else if(O.item.type==="reasoning"){const ne=L[O.item.id],Me=Object.entries(ne.summaryParts).filter(([Ee,Oe])=>Oe==="active"||Oe==="can-conclude").map(([Ee])=>Ee);for(const Ee of Me)te.enqueue({type:"reasoning-end",id:`${O.item.id}:${Ee}`,providerMetadata:{[m]:{itemId:O.item.id,reasoningEncryptedContent:(J=O.item.encrypted_content)!=null?J:null}}});delete L[O.item.id]}}else if(K2(O)){const ne=F[O.output_index];ne!=null&&te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:O.delta})}else if(J2(O)){const ne=F[O.output_index];ne!=null&&te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:O.delta})}else if(nx(O)){const ne=F[O.output_index];ne?.applyPatch&&(te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:fr(O.delta)}),ne.applyPatch.hasDiff=!0)}else if(rx(O)){const ne=F[O.output_index];ne?.applyPatch&&!ne.applyPatch.endEmitted&&(ne.applyPatch.hasDiff||(te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:fr(O.diff)}),ne.applyPatch.hasDiff=!0),te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:'"}}'}),te.enqueue({type:"tool-input-end",id:ne.toolCallId}),ne.applyPatch.endEmitted=!0)}else if(Q2(O))te.enqueue({type:"tool-result",toolCallId:O.item_id,toolName:d.toCustomToolName("image_generation"),result:{result:O.partial_image_b64},preliminary:!0});else if(ex(O)){const ne=F[O.output_index];ne!=null&&te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:fr(O.delta)})}else if(tx(O)){const ne=F[O.output_index];ne!=null&&(te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:'"}'}),te.enqueue({type:"tool-input-end",id:ne.toolCallId}),te.enqueue({type:"tool-call",toolCallId:ne.toolCallId,toolName:d.toCustomToolName("code_interpreter"),input:JSON.stringify({code:O.code,containerId:ne.codeInterpreter.containerId}),providerExecuted:!0}))}else if(Y2(O))$=O.response.id,te.enqueue({type:"response-metadata",id:O.response.id,timestamp:new Date(O.response.created_at*1e3),modelId:O.response.model});else if(j2(O))te.enqueue({type:"text-delta",id:O.item_id,delta:O.delta}),(Se=(ye=t.providerOptions)==null?void 0:ye[m])!=null&&Se.logprobs&&O.logprobs&&ee.push(O.logprobs);else if(O.type==="response.reasoning_summary_part.added"){if(O.summary_index>0){const ne=L[O.item_id];ne.summaryParts[O.summary_index]="active";for(const Me of Object.keys(ne.summaryParts))ne.summaryParts[Me]==="can-conclude"&&(te.enqueue({type:"reasoning-end",id:`${O.item_id}:${Me}`,providerMetadata:{[m]:{itemId:O.item_id}}}),ne.summaryParts[Me]="concluded");te.enqueue({type:"reasoning-start",id:`${O.item_id}:${O.summary_index}`,providerMetadata:{[m]:{itemId:O.item_id,reasoningEncryptedContent:(St=(Ve=L[O.item_id])==null?void 0:Ve.encryptedContent)!=null?St:null}}})}}else if(O.type==="response.reasoning_summary_text.delta")te.enqueue({type:"reasoning-delta",id:`${O.item_id}:${O.summary_index}`,delta:O.delta,providerMetadata:{[m]:{itemId:O.item_id}}});else if(O.type==="response.reasoning_summary_part.done")f?(te.enqueue({type:"reasoning-end",id:`${O.item_id}:${O.summary_index}`,providerMetadata:{[m]:{itemId:O.item_id}}}),L[O.item_id].summaryParts[O.summary_index]="concluded"):L[O.item_id].summaryParts[O.summary_index]="can-conclude";else if(X2(O))P={unified:gi({finishReason:(vt=O.response.incomplete_details)==null?void 0:vt.reason,hasFunctionCall:B}),raw:(nt=(et=O.response.incomplete_details)==null?void 0:et.reason)!=null?nt:void 0},M=O.response.usage,typeof O.response.service_tier=="string"&&(W=O.response.service_tier),((Xe=O.response.reasoning)==null?void 0:Xe.context)!=null&&(z=O.response.reasoning.context);else if(ja(O)){const ne=(In=O.response.incomplete_details)==null?void 0:In.reason;P={unified:ne?gi({finishReason:ne,hasFunctionCall:B}):"error",raw:ne??"error"},M=(be=O.response.usage)!=null?be:void 0,((Bn=O.response.reasoning)==null?void 0:Bn.context)!=null&&(z=O.response.reasoning.context),!G&&O.response.error!=null&&(G=!0,te.enqueue({type:"error",error:{type:"response.failed",sequence_number:O.sequence_number,response:{error:O.response.error,incomplete_details:O.response.incomplete_details,service_tier:O.response.service_tier}}}))}else ox(O)?(re.push(O.annotation),O.annotation.type==="url_citation"?te.enqueue({type:"source",sourceType:"url",id:(jn=(qt=($n=D.config).generateId)==null?void 0:qt.call($n))!=null?jn:rn(),url:O.annotation.url,title:O.annotation.title}):O.annotation.type==="file_citation"?te.enqueue({type:"source",sourceType:"document",id:(sn=(rr=(Ft=D.config).generateId)==null?void 0:rr.call(Ft))!=null?sn:rn(),mediaType:"text/plain",title:O.annotation.filename,filename:O.annotation.filename,providerMetadata:{[m]:{type:O.annotation.type,fileId:O.annotation.file_id,index:O.annotation.index}}}):O.annotation.type==="container_file_citation"?te.enqueue({type:"source",sourceType:"document",id:(Ln=(or=(At=D.config).generateId)==null?void 0:or.call(At))!=null?Ln:rn(),mediaType:"text/plain",title:O.annotation.filename,filename:O.annotation.filename,providerMetadata:{[m]:{type:O.annotation.type,fileId:O.annotation.file_id,containerId:O.annotation.container_id}}}):O.annotation.type==="file_path"&&te.enqueue({type:"source",sourceType:"document",id:(ge=(gt=(wr=D.config).generateId)==null?void 0:gt.call(wr))!=null?ge:rn(),mediaType:"application/octet-stream",title:O.annotation.file_id,filename:O.annotation.file_id,providerMetadata:{[m]:{type:O.annotation.type,fileId:O.annotation.file_id,index:O.annotation.index}}})):Wa(O)&&(G=!0,P={unified:"error",raw:"error"},te.enqueue({type:"error",error:O}))},flush(fe){const te={[m]:{responseId:$,...ee.length>0?{logprobs:ee}:{},...W!==void 0?{serviceTier:W}:{},...z!==void 0?{reasoningContext:z}:{}}};fe.enqueue({type:"finish",finishReason:P,usage:za(M),providerMetadata:te})}})),request:{body:r},response:{headers:g}}}};function j2(t){return t.type==="response.output_text.delta"}function H2(t){const r=G2(t);return r!=null&&Array.isArray(r.choices)&&typeof r.type!="string"}function W2({value:t,cause:r,url:i,requestBodyValues:c,responseHeaders:d}){return new Kt({message:"Received a Chat Completions stream while using the OpenAI Responses API. The default OpenAI provider model uses the Responses API. If your custom baseURL targets a Chat Completions-compatible endpoint, use openai.chat('model-id') or createOpenAI(...).chat('model-id') instead. You can also use @ai-sdk/openai-compatible for OpenAI-compatible providers.",url:i,requestBodyValues:c,responseHeaders:d,responseBody:JSON.stringify(t),cause:r,data:t,isRetryable:!1})}function G2(t){return typeof t=="object"&&t!=null?t:void 0}function q2(t){return t.type==="response.output_item.done"}function X2(t){return t.type==="response.completed"||t.type==="response.incomplete"}function ja(t){return t.type==="response.failed"}function Y2(t){return t.type==="response.created"}function K2(t){return t.type==="response.function_call_arguments.delta"}function J2(t){return t.type==="response.custom_tool_call_input.delta"}function Q2(t){return t.type==="response.image_generation_call.partial_image"}function ex(t){return t.type==="response.code_interpreter_call_code.delta"}function tx(t){return t.type==="response.code_interpreter_call_code.done"}function nx(t){return t.type==="response.apply_patch_call_operation_diff.delta"}function rx(t){return t.type==="response.apply_patch_call_operation_diff.done"}function Ha(t){return t.type==="response.output_item.added"}function ox(t){return t.type==="response.output_text.annotation.added"}function Wa(t){return t.type==="error"}function ix(t){return!(t.type==="response.created"||t.type==="response.failed"||t.type==="error"||t.type==="unknown_chunk")}function Ga(t){var r;if(t==null)return{};switch(t.type){case"search":return{action:{type:"search",query:(r=t.query)!=null?r:void 0,...t.queries!=null&&{queries:t.queries}},...t.sources!=null&&{sources:t.sources}};case"open_page":return{action:{type:"openPage",url:t.url}};case"find_in_page":return{action:{type:"findInPage",url:t.url,pattern:t.pattern}}}}function fr(t){return JSON.stringify(t).slice(1,-1)}var sx=Fe(()=>Le(N({instructions:w().nullish(),speed:j().min(.25).max(4).default(1).nullish()}))),ax=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({text:t,voice:r="alloy",outputFormat:i="mp3",speed:c,instructions:d,language:f,providerOptions:m}){const x=[],v=await An({provider:"openai",providerOptions:m,schema:sx}),g={model:this.modelId,input:t,voice:r,response_format:"mp3",speed:c,instructions:d};if(i&&(["mp3","opus","aac","flac","wav","pcm"].includes(i)?g.response_format=i:x.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${i}. Using mp3 instead.`})),v){const E={};for(const A in E){const D=E[A];D!==void 0&&(g[A]=D)}}return f&&x.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${f}" was ignored.`}),{requestBody:g,warnings:x}}async doGenerate(t){var r,i,c;const d=(c=(i=(r=this.config._internal)==null?void 0:r.currentDate)==null?void 0:i.call(r))!=null?c:new Date,{requestBody:f,warnings:m}=await this.getArgs(t),{value:x,responseHeaders:v,rawValue:g}=await Zn({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:bn(this.config.headers(),t.headers),body:f,failedResponseHandler:En,successfulResponseHandler:xg(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:x,warnings:m,request:{body:JSON.stringify(f)},response:{timestamp:d,modelId:this.modelId,headers:v,body:g}}}},lx=Fe(()=>Le(N({text:w(),language:w().nullish(),duration:j().nullish(),words:ue(N({word:w(),start:j(),end:j()})).nullish(),segments:ue(N({id:j(),seek:j(),start:j(),end:j(),text:w(),tokens:ue(j()),temperature:j(),avg_logprob:j(),compression_ratio:j(),no_speech_prob:j()})).nullish()}))),cx=Fe(()=>Le(N({include:ue(w()).optional(),language:w().optional(),prompt:w().optional(),temperature:j().min(0).max(1).default(0).optional(),timestampGranularities:ue(Ae(["word","segment"])).default(["segment"]).optional()}))),qa={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},ux=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({audio:t,mediaType:r,providerOptions:i}){const c=[],d=await An({provider:"openai",providerOptions:i,schema:cx}),f=new FormData,m=t instanceof Uint8Array?new Blob([t]):new Blob([qi(t)]);f.append("model",this.modelId);const x=gm(r);if(f.append("file",new File([m],"audio",{type:r}),`audio.${x}`),d){const v={include:d.include,language:d.language,prompt:d.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:d.temperature,timestamp_granularities:d.timestampGranularities};for(const[g,E]of Object.entries(v))if(E!=null)if(Array.isArray(E))for(const A of E)f.append(`${g}[]`,String(A));else f.append(g,String(E))}return{formData:f,warnings:c}}async doGenerate(t){var r,i,c,d,f,m,x,v;const g=(c=(i=(r=this.config._internal)==null?void 0:r.currentDate)==null?void 0:i.call(r))!=null?c:new Date,{formData:E,warnings:A}=await this.getArgs(t),{value:D,responseHeaders:T,rawValue:S}=await xu({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:bn(this.config.headers(),t.headers),formData:E,failedResponseHandler:En,successfulResponseHandler:mr(lx),abortSignal:t.abortSignal,fetch:this.config.fetch}),P=D.language!=null&&D.language in qa?qa[D.language]:void 0;return{text:D.text,segments:(x=(m=(d=D.segments)==null?void 0:d.map(M=>({text:M.text,startSecond:M.start,endSecond:M.end})))!=null?m:(f=D.words)==null?void 0:f.map(M=>({text:M.word,startSecond:M.start,endSecond:M.end})))!=null?x:[],language:P,durationInSeconds:(v=D.duration)!=null?v:void 0,warnings:A,response:{timestamp:g,modelId:this.modelId,headers:T,body:S}}}},dx="3.0.84";function Ou(t={}){var r,i;const c=(r=yg(mm({settingValue:t.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?r:"https://api.openai.com/v1",d=(i=t.name)!=null?i:"openai",f=()=>cu({Authorization:`Bearer ${pm({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers},`ai-sdk/openai/${dx}`),m=P=>new Tg(P,{provider:`${d}.chat`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),x=P=>new Mg(P,{provider:`${d}.completion`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),v=P=>new Lg(P,{provider:`${d}.embedding`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),g=P=>new $g(P,{provider:`${d}.image`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),E=P=>new ux(P,{provider:`${d}.transcription`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),A=P=>new ax(P,{provider:`${d}.speech`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),D=P=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return T(P)},T=P=>new $2(P,{provider:`${d}.responses`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch,fileIdPrefixes:["file-"]}),S=function(P){return D(P)};return S.specificationVersion="v3",S.languageModel=D,S.chat=m,S.completion=x,S.responses=T,S.embedding=v,S.embeddingModel=v,S.textEmbedding=v,S.textEmbeddingModel=v,S.image=g,S.imageModel=g,S.transcription=E,S.transcriptionModel=E,S.speech=A,S.speechModel=A,S.tools=k2,S}Ou();const fx={deepseek:{prompt:{strategy:"append",id:"5ed1b9071c15d1ed59b5827ea5dcabd4",params:{customComponents:[{name:"选择用户组件",description:"选择用户组件,用于选择用户,支持模糊搜索",component:"TinyUser",schema:{properties:[{property:"modelValue",label:"用户绑定工号",required:!0,description:"用户的工号,双向绑定值",type:"string"},{property:"valueField",label:"值字段",required:!0,description:"用户工号值的绑定字段",type:"string"}]}}],customExamples:[{name:"选择用户示例",schema:{componentName:"Page",state:{reviewer:""},children:[{componentName:"h3",props:{},children:"输入用户名搜索工号并选择用户"},{componentName:"TinyUser",props:{modelValue:{type:"JSExpression",model:!0,value:"this.state.reviewer"},valueField:"uid"}},{componentName:"TinyButton",props:{text:"提交"}}]}}],customActions:[{name:"continueChat",description:"继续对话, 用于表单的提交按钮等",parameters:{type:"object",properties:{message:{type:"string",description:"对话消息,可以是按钮文本等,也可以是其他内容"}}}}]}}}};class hx{constructor(r={}){this.option=r}async traverse(r){const i=_.ref();return this.option.debug&&console.log("【stream-debug】 响应对象体:",i),(async()=>{let d,f,m,x,v;for await(const g of r.fullStream)switch(this.option.debug&&console.log("【stream-debug】 "+(new Date().getTime()/1e3).toString().slice(-6)+g.type,g),g.type){case"start":d=_.reactive({running:!0,steps:[]}),i.value=d,this.option.onStart?.(d);break;case"start-step":f=_.reactive({running:!0,contents:[],request:g.request}),d.steps.push(f),this.option.onStep?.(f);break;case"reasoning-start":m=_.reactive({type:"reasoning",id:g.id,running:!0,text:""}),f.contents.push(m),this.option.onReasoning?.(m);break;case"reasoning-delta":m.text+=g.text;break;case"reasoning-end":m.running=!1;break;case"text-start":x=_.reactive({type:"text",id:g.id,running:!0,text:""}),f.contents.push(x),this.option.onText?.(x);break;case"text-delta":x.text+=g.text;break;case"text-end":x.running=!1;break;case"tool-input-start":v=_.reactive({type:"tool",running:!0,id:g.id,toolCallId:g.id,title:"",toolName:g.toolName,dynamic:g.dynamic,inputStr:"",input:{},output:{}}),f.contents.push(v),this.option.onTool?.(v);break;case"tool-input-delta":v.inputStr+=g.delta;break;case"tool-input-end":break;case"tool-call":v.input=g.input;break;case"tool-result":v.output=g.output,v.running=!1;break;case"tool-error":v.error=g.error,v.running=!1;break;case"finish-step":f.running=!1,f.finishReason=g.finishReason,f.usage=g.usage;break;case"finish":d.running=!1,d.finishReason=g.finishReason,d.totalUsage=g.totalUsage,this.option.onFinish?.();break;case"source":case"file":break;case"error":d&&(d.running=!1,d.error=g.error,d.finishReason="error"),this.option.onFinish?.();break;case"abort":d&&(d.running=!1,d.error={message:g.reason},d.finishReason="other"),this.option.onFinish?.();break}})(),i}}function px(t){const r=[];let i=0;for(;i<t.length;){const c="```schemaJson",d=t.indexOf(c,i),f=c.length;if(d===-1){const g=t.slice(i).trim();g&&r.push({type:"markdown",content:g});break}const m=t.slice(i,d).trim();m&&r.push({type:"markdown",content:m});const x=t.indexOf("```",d+f);let v;x===-1?(v=t.slice(d+f).trim(),i=t.length):(v=t.slice(d+f,x).trim(),i=x+3),r.push({type:"schema-card",content:v})}return r}class mx{staticPrompt="";skillMetaPrompt="";tempPrompt="";getSystemPrompt(){return`
55
+ ${r}:`]}}function Pa({id:t,model:r,created:i}){return{id:t??void 0,modelId:r??void 0,timestamp:i!=null?new Date(i*1e3):void 0}}function Ba(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var Rg=Fe(()=>Le(N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(N({text:w(),finish_reason:w(),logprobs:N({tokens:ue(w()),token_logprobs:ue(j()),top_logprobs:ue(wt(w(),j())).nullish()}).nullish()})),usage:N({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}))),Mg=Fe(()=>Le(st([N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(N({text:w(),finish_reason:w().nullish(),index:j(),logprobs:N({tokens:ue(w()),token_logprobs:ue(j()),top_logprobs:ue(wt(w(),j())).nullish()}).nullish()})),usage:N({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}),Qi]))),La=Fe(()=>Le(N({echo:Mt().optional(),logitBias:wt(w(),j()).optional(),suffix:w().optional(),user:w().optional(),logprobs:st([Mt(),j()]).optional()}))),Dg=class{constructor(t,r){this.specificationVersion="v3",this.supportedUrls={},this.modelId=t,this.config=r}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:r,temperature:i,topP:c,topK:d,frequencyPenalty:f,presencePenalty:m,stopSequences:x,responseFormat:v,tools:g,toolChoice:E,seed:A,providerOptions:D}){const T=[],S={...await An({provider:"openai",providerOptions:D,schema:La}),...await An({provider:this.providerOptionsName,providerOptions:D,schema:La})};d!=null&&T.push({type:"unsupported",feature:"topK"}),g?.length&&T.push({type:"unsupported",feature:"tools"}),E!=null&&T.push({type:"unsupported",feature:"toolChoice"}),v!=null&&v.type!=="text"&&T.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:P,stopSequences:M}=kg({prompt:t}),ee=[...M??[],...x??[]];return{args:{model:this.modelId,echo:S.echo,logit_bias:S.logitBias,logprobs:S?.logprobs===!0?0:S?.logprobs===!1?void 0:S?.logprobs,suffix:S.suffix,user:S.user,max_tokens:r,temperature:i,top_p:c,frequency_penalty:f,presence_penalty:m,seed:A,prompt:P,stop:ee.length>0?ee:void 0},warnings:T}}async doGenerate(t){var r;const{args:i,warnings:c}=await this.getArgs(t),{responseHeaders:d,value:f,rawValue:m}=await Zn({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:bn(this.config.headers(),t.headers),body:i,failedResponseHandler:En,successfulResponseHandler:mr(Rg),abortSignal:t.abortSignal,fetch:this.config.fetch}),x=f.choices[0],v={openai:{}};return x.logprobs!=null&&(v.openai.logprobs=x.logprobs),{content:[{type:"text",text:x.text}],usage:Da(f.usage),finishReason:{unified:Ba(x.finish_reason),raw:(r=x.finish_reason)!=null?r:void 0},request:{body:i},response:{...Pa(f),headers:d,body:m},providerMetadata:v,warnings:c}}async doStream(t){const{args:r,warnings:i}=await this.getArgs(t),c={...r,stream:!0,stream_options:{include_usage:!0}},d=this.config.url({path:"/completions",modelId:this.modelId}),{responseHeaders:f,value:m}=await Zn({url:d,headers:bn(this.config.headers(),t.headers),body:c,failedResponseHandler:En,successfulResponseHandler:Ji(Mg),abortSignal:t.abortSignal,fetch:this.config.fetch}),x=await es({stream:m,getError:T=>"error"in T?T.error:void 0,isOutputChunk:Pg,url:d,requestBodyValues:c,responseHeaders:f});let v={unified:"other",raw:void 0};const g={openai:{}};let E,A=!0;return{stream:x.pipeThrough(new TransformStream({start(T){T.enqueue({type:"stream-start",warnings:i})},transform(T,S){if(t.includeRawChunks&&S.enqueue({type:"raw",rawValue:T.rawValue}),!T.success){v={unified:"error",raw:void 0},S.enqueue({type:"error",error:T.error});return}const P=T.value;if("error"in P){v={unified:"error",raw:void 0},S.enqueue({type:"error",error:P.error});return}A&&(A=!1,S.enqueue({type:"response-metadata",...Pa(P)}),S.enqueue({type:"text-start",id:"0"})),P.usage!=null&&(E=P.usage);const M=P.choices[0];M?.finish_reason!=null&&(v={unified:Ba(M.finish_reason),raw:M.finish_reason}),M?.logprobs!=null&&(g.openai.logprobs=M.logprobs),M?.text!=null&&M.text.length>0&&S.enqueue({type:"text-delta",id:"0",delta:M.text})},flush(T){A||T.enqueue({type:"text-end",id:"0"}),T.enqueue({type:"finish",finishReason:v,providerMetadata:g,usage:Da(E)})}})),request:{body:c},response:{headers:f}}}};function Pg(t){return!("error"in t)&&t.choices.some(r=>r.text.length>0)}var Bg=Fe(()=>Le(N({dimensions:j().optional(),user:w().optional()}))),Lg=Fe(()=>Le(N({data:ue(N({embedding:ue(j())})),usage:N({prompt_tokens:j()}).nullish()}))),Fg=class{constructor(t,r){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=r}get provider(){return this.config.provider}async doEmbed({values:t,headers:r,abortSignal:i,providerOptions:c}){var d;if(t.length>this.maxEmbeddingsPerCall)throw new jp({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const f=(d=await An({provider:"openai",providerOptions:c,schema:Bg}))!=null?d:{},{responseHeaders:m,value:x,rawValue:v}=await Zn({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:bn(this.config.headers(),r),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:f.dimensions,user:f.user},failedResponseHandler:En,successfulResponseHandler:mr(Lg),abortSignal:i,fetch:this.config.fetch});return{warnings:[],embeddings:x.data.map(g=>g.embedding),usage:x.usage?{tokens:x.usage.prompt_tokens}:void 0,response:{headers:m,body:v}}}},Fa=Fe(()=>Le(N({created:j().nullish(),data:ue(N({b64_json:w(),revised_prompt:w().nullish()})),background:w().nullish(),output_format:w().nullish(),size:w().nullish(),quality:w().nullish(),usage:N({input_tokens:j().nullish(),output_tokens:j().nullish(),total_tokens:j().nullish(),input_tokens_details:N({image_tokens:j().nullish(),text_tokens:j().nullish()}).nullish()}).nullish()}))),Ug={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10,"gpt-image-2":10,"chatgpt-image-latest":10},zg=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1","gpt-image-2"];function Vg(t){return zg.some(r=>t.startsWith(r))}var vu=N({quality:Ae(["standard","hd","low","medium","high","auto"]).optional(),background:Ae(["transparent","opaque","auto"]).optional(),outputFormat:Ae(["png","jpeg","webp"]).optional(),outputCompression:j().int().min(0).max(100).optional(),user:w().optional()}),Zg=Fe(()=>Le(vu.extend({style:Ae(["vivid","natural"]).optional(),moderation:Ae(["auto","low"]).optional()}))),$g=Fe(()=>Le(vu.extend({inputFidelity:Ae(["high","low"]).optional()}))),jg=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v3"}get maxImagesPerCall(){var t;return(t=Ug[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,files:r,mask:i,n:c,size:d,aspectRatio:f,seed:m,providerOptions:x,headers:v,abortSignal:g}){var E,A,D,T,S,P,M,ee,$,F,re;const Z=[];f!=null&&Z.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),m!=null&&Z.push({type:"unsupported",feature:"seed"});const B=(D=(A=(E=this.config._internal)==null?void 0:E.currentDate)==null?void 0:A.call(E))!=null?D:new Date;if(r!=null){const we=(T=await An({provider:"openai",providerOptions:x,schema:$g}))!=null?T:{},{value:G,responseHeaders:me}=await xu({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:bn(this.config.headers(),v),formData:Jp({model:this.modelId,prompt:t,image:await Promise.all(r.map(fe=>fe.type==="file"?new Blob([fe.data instanceof Uint8Array?new Blob([fe.data],{type:fe.mediaType}):new Blob([qi(fe.data)],{type:fe.mediaType})],{type:fe.mediaType}):lu(fe.url))),mask:i!=null?await Hg(i):void 0,n:c,size:d,quality:we.quality,background:we.background,output_format:we.outputFormat,output_compression:we.outputCompression,input_fidelity:we.inputFidelity,user:we.user}),failedResponseHandler:En,successfulResponseHandler:mr(Fa),abortSignal:g,fetch:this.config.fetch});return{images:G.data.map(fe=>fe.b64_json),warnings:Z,usage:G.usage!=null?{inputTokens:(S=G.usage.input_tokens)!=null?S:void 0,outputTokens:(P=G.usage.output_tokens)!=null?P:void 0,totalTokens:(M=G.usage.total_tokens)!=null?M:void 0}:void 0,response:{timestamp:B,modelId:this.modelId,headers:me},providerMetadata:{openai:{images:G.data.map((fe,te)=>{var q,ke,le,Te,Je,xe;return{...fe.revised_prompt?{revisedPrompt:fe.revised_prompt}:{},created:(q=G.created)!=null?q:void 0,size:(ke=G.size)!=null?ke:void 0,quality:(le=G.quality)!=null?le:void 0,background:(Te=G.background)!=null?Te:void 0,outputFormat:(Je=G.output_format)!=null?Je:void 0,...Ua((xe=G.usage)==null?void 0:xe.input_tokens_details,te,G.data.length)}})}}}}const L=(ee=await An({provider:"openai",providerOptions:x,schema:Zg}))!=null?ee:{},{value:W,responseHeaders:z}=await Zn({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:bn(this.config.headers(),v),body:{model:this.modelId,prompt:t,n:c,size:d,quality:L.quality,style:L.style,background:L.background,moderation:L.moderation,output_format:L.outputFormat,output_compression:L.outputCompression,user:L.user,...Vg(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:En,successfulResponseHandler:mr(Fa),abortSignal:g,fetch:this.config.fetch});return{images:W.data.map(we=>we.b64_json),warnings:Z,usage:W.usage!=null?{inputTokens:($=W.usage.input_tokens)!=null?$:void 0,outputTokens:(F=W.usage.output_tokens)!=null?F:void 0,totalTokens:(re=W.usage.total_tokens)!=null?re:void 0}:void 0,response:{timestamp:B,modelId:this.modelId,headers:z},providerMetadata:{openai:{images:W.data.map((we,G)=>{var me,fe,te,q,ke,le;return{...we.revised_prompt?{revisedPrompt:we.revised_prompt}:{},created:(me=W.created)!=null?me:void 0,size:(fe=W.size)!=null?fe:void 0,quality:(te=W.quality)!=null?te:void 0,background:(q=W.background)!=null?q:void 0,outputFormat:(ke=W.output_format)!=null?ke:void 0,...Ua((le=W.usage)==null?void 0:le.input_tokens_details,G,W.data.length)}})}}}}};function Ua(t,r,i){if(t==null)return{};const c={};if(t.image_tokens!=null){const d=Math.floor(t.image_tokens/i),f=t.image_tokens-d*(i-1);c.imageTokens=r===i-1?f:d}if(t.text_tokens!=null){const d=Math.floor(t.text_tokens/i),f=t.text_tokens-d*(i-1);c.textTokens=r===i-1?f:d}return c}async function Hg(t){if(!t)return;if(t.type==="url")return lu(t.url);const r=t.data instanceof Uint8Array?t.data:qi(t.data);return new Blob([r],{type:t.mediaType})}var Cu=Fe(()=>Le(N({callId:w(),operation:mt("type",[N({type:Y("create_file"),path:w(),diff:w()}),N({type:Y("delete_file"),path:w()}),N({type:Y("update_file"),path:w(),diff:w()})])}))),bu=Fe(()=>Le(N({status:Ae(["completed","failed"]),output:w().optional()}))),Wg=Dn({id:"openai.apply_patch",inputSchema:Cu,outputSchema:bu}),Gg=Wg,qg=Fe(()=>Le(N({code:w().nullish(),containerId:w()}))),Xg=Fe(()=>Le(N({outputs:ue(mt("type",[N({type:Y("logs"),logs:w()}),N({type:Y("image"),url:w()})])).nullish()}))),Yg=Fe(()=>Le(N({container:st([w(),N({fileIds:ue(w()).optional()})]).optional()}))),Kg=Dn({id:"openai.code_interpreter",inputSchema:qg,outputSchema:Xg}),Jg=(t={})=>Kg(t),Qg=Fe(()=>Le(N({name:w(),description:w().optional(),format:st([N({type:Y("grammar"),syntax:Ae(["regex","lark"]),definition:w()}),N({type:Y("text")})]).optional()}))),e2=Fe(()=>Le(w())),t2=mg({id:"openai.custom",inputSchema:e2}),n2=t=>t2(t),Au=N({key:w(),type:Ae(["eq","ne","gt","gte","lt","lte","in","nin"]),value:st([w(),j(),Mt(),ue(w())])}),Eu=N({type:Ae(["and","or"]),filters:ue(st([Au,Wi(()=>Eu)]))}),r2=Fe(()=>Le(N({vectorStoreIds:ue(w()),maxNumResults:j().optional(),ranking:N({ranker:w().optional(),scoreThreshold:j().optional()}).optional(),filters:st([Au,Eu]).optional()}))),o2=Fe(()=>Le(N({queries:ue(w()),results:ue(N({attributes:wt(w(),Cn()),fileId:w(),filename:w(),score:j(),text:w()})).nullable()}))),i2=Dn({id:"openai.file_search",inputSchema:N({}),outputSchema:o2}),s2=Fe(()=>Le(N({background:Ae(["auto","opaque","transparent"]).optional(),inputFidelity:Ae(["low","high"]).optional(),inputImageMask:N({fileId:w().optional(),imageUrl:w().optional()}).optional(),model:w().optional(),moderation:Ae(["auto"]).optional(),outputCompression:j().int().min(0).max(100).optional(),outputFormat:Ae(["png","jpeg","webp"]).optional(),partialImages:j().int().min(0).max(3).optional(),quality:Ae(["auto","low","medium","high"]).optional(),size:Ae(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),a2=Fe(()=>Le(N({}))),l2=Fe(()=>Le(N({result:w()}))),c2=Dn({id:"openai.image_generation",inputSchema:a2,outputSchema:l2}),u2=(t={})=>c2(t),Iu=Fe(()=>Le(N({action:N({type:Y("exec"),command:ue(w()),timeoutMs:j().optional(),user:w().optional(),workingDirectory:w().optional(),env:wt(w(),w()).optional()})}))),Su=Fe(()=>Le(N({output:w()}))),d2=Dn({id:"openai.local_shell",inputSchema:Iu,outputSchema:Su}),Tu=Fe(()=>Le(N({action:N({commands:ue(w()),timeoutMs:j().optional(),maxOutputLength:j().optional()})}))),ki=Fe(()=>Le(N({output:ue(N({stdout:w(),stderr:w(),outcome:mt("type",[N({type:Y("timeout")}),N({type:Y("exit"),exitCode:j()})])}))}))),f2=ue(mt("type",[N({type:Y("skillReference"),skillId:w(),version:w().optional()}),N({type:Y("inline"),name:w(),description:w(),source:N({type:Y("base64"),mediaType:Y("application/zip"),data:w()})})])).optional(),h2=Fe(()=>Le(N({environment:st([N({type:Y("containerAuto"),fileIds:ue(w()).optional(),memoryLimit:Ae(["1g","4g","16g","64g"]).optional(),networkPolicy:mt("type",[N({type:Y("disabled")}),N({type:Y("allowlist"),allowedDomains:ue(w()),domainSecrets:ue(N({domain:w(),name:w(),value:w()})).optional()})]).optional(),skills:f2}),N({type:Y("containerReference"),containerId:w()}),N({type:Y("local").optional(),skills:ue(N({name:w(),description:w(),path:w()})).optional()})]).optional()}))),p2=Dn({id:"openai.shell",inputSchema:Tu,outputSchema:ki}),m2=Fe(()=>Le(N({execution:Ae(["server","client"]).optional(),description:w().optional(),parameters:wt(w(),Cn()).optional()}))),Ri=Fe(()=>Le(N({arguments:Cn().optional(),call_id:w().nullish()}))),Mi=Fe(()=>Le(N({tools:ue(wt(w(),Cn()))}))),g2=Dn({id:"openai.tool_search",inputSchema:Ri,outputSchema:Mi}),x2=(t={})=>g2(t),y2=Fe(()=>Le(N({externalWebAccess:Mt().optional(),filters:N({allowedDomains:ue(w()).optional()}).optional(),searchContextSize:Ae(["low","medium","high"]).optional(),userLocation:N({type:Y("approximate"),country:w().optional(),city:w().optional(),region:w().optional(),timezone:w().optional()}).optional()}))),w2=Fe(()=>Le(N({}))),_2=Fe(()=>Le(N({action:mt("type",[N({type:Y("search"),query:w().optional(),queries:ue(w()).optional()}),N({type:Y("openPage"),url:w().nullish()}),N({type:Y("findInPage"),url:w().nullish(),pattern:w().nullish()})]).optional(),sources:ue(mt("type",[N({type:Y("url"),url:w()}),N({type:Y("api"),name:w()})])).optional()}))),v2=Dn({id:"openai.web_search",inputSchema:w2,outputSchema:_2}),C2=(t={})=>v2(t),b2=Fe(()=>Le(N({searchContextSize:Ae(["low","medium","high"]).optional(),userLocation:N({type:Y("approximate"),country:w().optional(),city:w().optional(),region:w().optional(),timezone:w().optional()}).optional()}))),A2=Fe(()=>Le(N({}))),E2=Fe(()=>Le(N({action:mt("type",[N({type:Y("search"),query:w().optional()}),N({type:Y("openPage"),url:w().nullish()}),N({type:Y("findInPage"),url:w().nullish(),pattern:w().nullish()})]).optional()}))),I2=Dn({id:"openai.web_search_preview",inputSchema:A2,outputSchema:E2}),Di=Wi(()=>st([w(),j(),Mt(),bc(),ue(Di),wt(w(),Di)])),S2=Fe(()=>Le(N({serverLabel:w(),allowedTools:st([ue(w()),N({readOnly:Mt().optional(),toolNames:ue(w()).optional()})]).optional(),authorization:w().optional(),connectorId:w().optional(),headers:wt(w(),w()).optional(),requireApproval:st([Ae(["always","never"]),N({never:N({toolNames:ue(w()).optional()}).optional()})]).optional(),serverDescription:w().optional(),serverUrl:w().optional()}).refine(t=>t.serverUrl!=null||t.connectorId!=null,"One of serverUrl or connectorId must be provided."))),T2=Fe(()=>Le(N({}))),N2=Fe(()=>Le(N({type:Y("call"),serverLabel:w(),name:w(),arguments:w(),output:w().nullish(),error:st([w(),Di]).optional()}))),O2=Dn({id:"openai.mcp",inputSchema:T2,outputSchema:N2}),k2=t=>O2(t),R2={applyPatch:Gg,customTool:n2,codeInterpreter:Jg,fileSearch:i2,imageGeneration:u2,localShell:d2,shell:p2,webSearchPreview:I2,webSearch:C2,mcp:k2,toolSearch:x2};function za(t){var r,i,c,d,f,m;if(t==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const x=t.input_tokens,v=t.output_tokens,g=(i=(r=t.input_tokens_details)==null?void 0:r.cached_tokens)!=null?i:0,E=(d=(c=t.input_tokens_details)==null?void 0:c.cache_write_tokens)!=null?d:void 0,A=(m=(f=t.output_tokens_details)==null?void 0:f.reasoning_tokens)!=null?m:0;return{inputTokens:{total:x,noCache:x-g-(E??0),cacheRead:g,cacheWrite:E},outputTokens:{total:v,text:v-A,reasoning:A},raw:t}}function M2(t){return JSON.stringify(t===void 0?{}:t)}function Nr(t,r){var i;return(i=t?.[r])==null?void 0:i.promptCacheBreakpoint}function Va(t,r){return r?r.some(i=>t.startsWith(i)):!1}async function D2({prompt:t,toolNameMapping:r,systemMessageMode:i,providerOptionsName:c,fileIdPrefixes:d,passThroughUnsupportedFiles:f=!1,store:m,hasConversation:x=!1,hasPreviousResponseId:v=!1,hasLocalShellTool:g=!1,hasShellTool:E=!1,hasApplyPatchTool:A=!1,customProviderToolNames:D}){var T,S,P,M,ee,$,F,re,Z,B,L,W,z,we,G,me,fe,te,q,ke,le,Te,Je;let xe=[];const $e=[],Ue=new Set;for(const{role:Ze,content:qe,providerOptions:ze}of t)switch(Ze){case"system":{switch(i){case"system":{const ie=Nr(ze,c);xe.push({role:"system",content:ie==null?qe:[{type:"input_text",text:qe,prompt_cache_breakpoint:ie}]});break}case"developer":{const ie=Nr(ze,c);xe.push({role:"developer",content:ie==null?qe:[{type:"input_text",text:qe,prompt_cache_breakpoint:ie}]});break}case"remove":{$e.push({type:"other",message:"system messages are removed for this model"});break}default:{const ie=i;throw new Error(`Unsupported system message mode: ${ie}`)}}break}case"user":{xe.push({role:"user",content:qe.map((ie,de)=>{var _e,Pe,ae;switch(ie.type){case"text":{const J=Nr(ie.providerOptions,c);return{type:"input_text",text:ie.text,...J!=null&&{prompt_cache_breakpoint:J}}}case"file":{const J=Nr(ie.providerOptions,c),ye=ie.mediaType==="image/*"?"image/jpeg":ie.mediaType;if(ye.startsWith("image/"))return{type:"input_image",...ie.data instanceof URL?{image_url:ie.data.toString()}:typeof ie.data=="string"&&Va(ie.data,d)?{file_id:ie.data}:{image_url:`data:${ye};base64,${kr(ie.data)}`},detail:(Pe=(_e=ie.providerOptions)==null?void 0:_e[c])==null?void 0:Pe.imageDetail,...J!=null&&{prompt_cache_breakpoint:J}};if(ie.data instanceof URL)return{type:"input_file",file_url:ie.data.toString(),...J!=null&&{prompt_cache_breakpoint:J}};if(ye!=="application/pdf"&&!f)throw new Mn({functionality:`file part media type ${ye}`});return{type:"input_file",...typeof ie.data=="string"&&Va(ie.data,d)?{file_id:ie.data}:{filename:(ae=ie.filename)!=null?ae:ye==="application/pdf"?`part-${de}.pdf`:`part-${de}`,file_data:`data:${ye};base64,${kr(ie.data)}`},...J!=null&&{prompt_cache_breakpoint:J}}}}})});break}case"assistant":{const ie={};for(const de of qe)switch(de.type){case"text":{const _e=(T=de.providerOptions)==null?void 0:T[c],Pe=_e?.itemId,ae=_e?.phase;if(x&&Pe!=null)break;if(m&&Pe!=null){xe.push({type:"item_reference",id:Pe});break}xe.push({role:"assistant",content:[{type:"output_text",text:de.text}],id:Pe,...ae!=null&&{phase:ae}});break}case"tool-call":{const _e=($=(P=(S=de.providerOptions)==null?void 0:S[c])==null?void 0:P.itemId)!=null?$:(ee=(M=de.providerMetadata)==null?void 0:M[c])==null?void 0:ee.itemId,Pe=(L=(re=(F=de.providerOptions)==null?void 0:F[c])==null?void 0:re.namespace)!=null?L:(B=(Z=de.providerMetadata)==null?void 0:Z[c])==null?void 0:B.namespace;if(x&&_e!=null)break;const ae=r.toProviderToolName(de.toolName);if(ae==="tool_search"){if(m&&_e!=null){xe.push({type:"item_reference",id:_e});break}const ye=typeof de.input=="string"?await mu({text:de.input,schema:Ri}):await Dt({value:de.input,schema:Ri}),Se=ye.call_id!=null?"client":"server";xe.push({type:"tool_search_call",id:_e??de.toolCallId,execution:Se,call_id:(W=ye.call_id)!=null?W:null,status:"completed",arguments:ye.arguments});break}if(de.providerExecuted){m&&_e!=null&&xe.push({type:"item_reference",id:_e});break}if(v&&m&&_e!=null)break;const J=g&&ae==="local_shell"||E&&ae==="shell"||A&&ae==="apply_patch"||((z=D?.has(ae))!=null?z:!1);if(m&&_e!=null&&J){xe.push({type:"item_reference",id:_e});break}if(g&&ae==="local_shell"){const ye=await Dt({value:de.input,schema:Iu});xe.push({type:"local_shell_call",call_id:de.toolCallId,id:_e,action:{type:"exec",command:ye.action.command,timeout_ms:ye.action.timeoutMs,user:ye.action.user,working_directory:ye.action.workingDirectory,env:ye.action.env}});break}if(E&&ae==="shell"){const ye=await Dt({value:de.input,schema:Tu});xe.push({type:"shell_call",call_id:de.toolCallId,id:_e,status:"completed",action:{commands:ye.action.commands,timeout_ms:ye.action.timeoutMs,max_output_length:ye.action.maxOutputLength}});break}if(A&&ae==="apply_patch"){const ye=await Dt({value:de.input,schema:Cu});xe.push({type:"apply_patch_call",call_id:ye.callId,id:_e,status:"completed",operation:ye.operation});break}if(D?.has(ae)){xe.push({type:"custom_tool_call",call_id:de.toolCallId,name:ae,input:typeof de.input=="string"?de.input:JSON.stringify(de.input),id:_e});break}xe.push({type:"function_call",call_id:de.toolCallId,name:ae,arguments:M2(de.input),...Pe!=null&&{namespace:Pe}});break}case"tool-result":{if(de.output.type==="execution-denied"||de.output.type==="json"&&typeof de.output.value=="object"&&de.output.value!=null&&"type"in de.output.value&&de.output.value.type==="execution-denied"||x)break;const _e=r.toProviderToolName(de.toolName);if(_e==="tool_search"){const Pe=(me=(G=(we=de.providerOptions)==null?void 0:we[c])==null?void 0:G.itemId)!=null?me:de.toolCallId;if(m)xe.push({type:"item_reference",id:Pe});else if(de.output.type==="json"){const ae=await Dt({value:de.output.value,schema:Mi});xe.push({type:"tool_search_output",id:Pe,execution:"server",call_id:null,status:"completed",tools:ae.tools})}break}if(E&&_e==="shell"){if(de.output.type==="json"){const Pe=await Dt({value:de.output.value,schema:ki});xe.push({type:"shell_call_output",call_id:de.toolCallId,output:Pe.output.map(ae=>({stdout:ae.stdout,stderr:ae.stderr,outcome:ae.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:ae.outcome.exitCode}}))})}break}if(m){const Pe=(q=(te=(fe=de.providerOptions)==null?void 0:fe[c])==null?void 0:te.itemId)!=null?q:de.toolCallId;xe.push({type:"item_reference",id:Pe})}else $e.push({type:"other",message:`Results for OpenAI tool ${de.toolName} are not sent to the API when store is false`});break}case"reasoning":{const _e=await An({provider:c,providerOptions:de.providerOptions,schema:P2}),Pe=_e?.itemId;if((x||v)&&Pe!=null)break;if(Pe!=null){const ae=ie[Pe];if(m)ae===void 0&&(xe.push({type:"item_reference",id:Pe}),ie[Pe]={type:"reasoning",id:Pe,summary:[]});else{const J=[];de.text.length>0?J.push({type:"summary_text",text:de.text}):ae!==void 0&&$e.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(de)}.`}),ae===void 0?(ie[Pe]={type:"reasoning",id:Pe,encrypted_content:_e?.reasoningEncryptedContent,summary:J},xe.push(ie[Pe])):(ae.summary.push(...J),_e?.reasoningEncryptedContent!=null&&(ae.encrypted_content=_e.reasoningEncryptedContent))}}else{const ae=_e?.reasoningEncryptedContent;if(ae!=null){const J=[];de.text.length>0&&J.push({type:"summary_text",text:de.text}),xe.push({type:"reasoning",encrypted_content:ae,summary:J})}else $e.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(de)}.`})}break}}break}case"tool":{for(const ie of qe){if(ie.type==="tool-approval-response"){const ae=ie;if(Ue.has(ae.approvalId))continue;Ue.add(ae.approvalId),m&&xe.push({type:"item_reference",id:ae.approvalId}),xe.push({type:"mcp_approval_response",approval_request_id:ae.approvalId,approve:ae.approved});continue}const de=ie.output;if(de.type==="execution-denied"&&((le=(ke=de.providerOptions)==null?void 0:ke.openai)==null?void 0:le.approvalId))continue;const _e=r.toProviderToolName(ie.toolName);if(_e==="tool_search"&&de.type==="json"){const ae=await Dt({value:de.value,schema:Mi});xe.push({type:"tool_search_output",execution:"client",call_id:ie.toolCallId,status:"completed",tools:ae.tools});continue}if(g&&_e==="local_shell"&&de.type==="json"){const ae=await Dt({value:de.value,schema:Su});xe.push({type:"local_shell_call_output",call_id:ie.toolCallId,output:ae.output});continue}if(E&&_e==="shell"&&de.type==="json"){const ae=await Dt({value:de.value,schema:ki});xe.push({type:"shell_call_output",call_id:ie.toolCallId,output:ae.output.map(J=>({stdout:J.stdout,stderr:J.stderr,outcome:J.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:J.outcome.exitCode}}))});continue}if(A&&ie.toolName==="apply_patch"&&de.type==="json"){const ae=await Dt({value:de.value,schema:bu});xe.push({type:"apply_patch_call_output",call_id:ie.toolCallId,status:ae.status,output:ae.output});continue}if(D?.has(_e)){let ae;switch(de.type){case"text":case"error-text":ae=de.value;break;case"execution-denied":ae=(Te=de.reason)!=null?Te:"Tool call execution denied.";break;case"json":case"error-json":ae=JSON.stringify(de.value);break;case"content":ae=de.value.map(J=>{var ye,Se,Ve,St,vt;const et=Nr(J.providerOptions,c);switch(J.type){case"text":return{type:"input_text",text:J.text,...et!=null&&{prompt_cache_breakpoint:et}};case"image-data":return{type:"input_image",image_url:`data:${J.mediaType};base64,${J.data}`,detail:(Se=(ye=J.providerOptions)==null?void 0:ye[c])==null?void 0:Se.imageDetail,...et!=null&&{prompt_cache_breakpoint:et}};case"image-url":return{type:"input_image",image_url:J.url,detail:(St=(Ve=J.providerOptions)==null?void 0:Ve[c])==null?void 0:St.imageDetail,...et!=null&&{prompt_cache_breakpoint:et}};case"file-data":return{type:"input_file",filename:(vt=J.filename)!=null?vt:"data",file_data:`data:${J.mediaType};base64,${J.data}`,...et!=null&&{prompt_cache_breakpoint:et}};case"file-url":return{type:"input_file",file_url:J.url,...et!=null&&{prompt_cache_breakpoint:et}};default:$e.push({type:"other",message:`unsupported custom tool content part type: ${J.type}`});return}}).filter(Ia);break;default:ae=""}xe.push({type:"custom_tool_call_output",call_id:ie.toolCallId,output:ae});continue}let Pe;switch(de.type){case"text":case"error-text":Pe=de.value;break;case"execution-denied":Pe=(Je=de.reason)!=null?Je:"Tool call execution denied.";break;case"json":case"error-json":Pe=JSON.stringify(de.value);break;case"content":Pe=de.value.map(ae=>{var J,ye,Se,Ve,St;const vt=Nr(ae.providerOptions,c);switch(ae.type){case"text":return{type:"input_text",text:ae.text,...vt!=null&&{prompt_cache_breakpoint:vt}};case"image-data":return{type:"input_image",image_url:`data:${ae.mediaType};base64,${ae.data}`,detail:(ye=(J=ae.providerOptions)==null?void 0:J[c])==null?void 0:ye.imageDetail,...vt!=null&&{prompt_cache_breakpoint:vt}};case"image-url":return{type:"input_image",image_url:ae.url,detail:(Ve=(Se=ae.providerOptions)==null?void 0:Se[c])==null?void 0:Ve.imageDetail,...vt!=null&&{prompt_cache_breakpoint:vt}};case"file-data":return{type:"input_file",filename:(St=ae.filename)!=null?St:"data",file_data:`data:${ae.mediaType};base64,${ae.data}`,...vt!=null&&{prompt_cache_breakpoint:vt}};case"file-url":return{type:"input_file",file_url:ae.url,...vt!=null&&{prompt_cache_breakpoint:vt}};default:{$e.push({type:"other",message:`unsupported tool content part type: ${ae.type}`});return}}}).filter(Ia);break}xe.push({type:"function_call_output",call_id:ie.toolCallId,output:Pe})}break}default:{const ie=Ze;throw new Error(`Unsupported role: ${ie}`)}}return!m&&xe.some(Ze=>"type"in Ze&&Ze.type==="reasoning"&&Ze.encrypted_content==null)&&($e.push({type:"other",message:"Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts."}),xe=xe.filter(Ze=>!("type"in Ze)||Ze.type!=="reasoning"||Ze.encrypted_content!=null)),{input:xe,warnings:$e}}var P2=N({itemId:w().nullish(),reasoningEncryptedContent:w().nullish()});function gi({finishReason:t,hasFunctionCall:r}){switch(t){case void 0:case null:return r?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return r?"tool-calls":"other"}}var ro=Wi(()=>st([w(),j(),Mt(),bc(),ue(ro),wt(w(),ro.optional())])),B2=N({type:Y("error"),sequence_number:j(),error:N({type:w(),code:w(),message:w(),param:w().nullish()})}),L2=N({type:Y("error"),sequence_number:j(),code:w().nullish(),message:w(),param:w().nullish()}),F2=Fe(()=>Le(st([N({type:Y("response.output_text.delta"),item_id:w(),delta:w(),logprobs:ue(N({token:w(),logprob:j(),top_logprobs:ue(N({token:w(),logprob:j()}))})).nullish()}),N({type:Ae(["response.completed","response.incomplete"]),response:N({incomplete_details:N({reason:w()}).nullish(),usage:N({input_tokens:j(),input_tokens_details:N({cached_tokens:j().nullish(),cache_write_tokens:j().nullish(),orchestration_input_tokens:j().nullish(),orchestration_input_cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:N({reasoning_tokens:j().nullish(),orchestration_output_tokens:j().nullish()}).nullish()}),reasoning:N({context:w().nullish()}).nullish(),service_tier:w().nullish()})}),N({type:Y("response.failed"),sequence_number:j(),response:N({error:N({code:w().nullish(),message:w()}).nullish(),incomplete_details:N({reason:w()}).nullish(),usage:N({input_tokens:j(),input_tokens_details:N({cached_tokens:j().nullish(),cache_write_tokens:j().nullish(),orchestration_input_tokens:j().nullish(),orchestration_input_cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:N({reasoning_tokens:j().nullish(),orchestration_output_tokens:j().nullish()}).nullish()}).nullish(),reasoning:N({context:w().nullish()}).nullish(),service_tier:w().nullish()})}),N({type:Y("response.created"),response:N({id:w(),created_at:j(),model:w(),service_tier:w().nullish()})}),N({type:Y("response.output_item.added"),output_index:j(),item:mt("type",[N({type:Y("message"),id:w(),phase:Ae(["commentary","final_answer"]).nullish()}),N({type:Y("reasoning"),id:w(),encrypted_content:w().nullish()}),N({type:Y("function_call"),id:w(),call_id:w(),name:w(),arguments:w(),namespace:w().nullish()}),N({type:Y("web_search_call"),id:w(),status:w()}),N({type:Y("computer_call"),id:w(),status:w()}),N({type:Y("file_search_call"),id:w()}),N({type:Y("image_generation_call"),id:w()}),N({type:Y("code_interpreter_call"),id:w(),container_id:w(),code:w().nullable(),outputs:ue(mt("type",[N({type:Y("logs"),logs:w()}),N({type:Y("image"),url:w()})])).nullable(),status:w()}),N({type:Y("mcp_call"),id:w(),status:w(),approval_request_id:w().nullish()}),N({type:Y("mcp_list_tools"),id:w()}),N({type:Y("mcp_approval_request"),id:w()}),N({type:Y("apply_patch_call"),id:w(),call_id:w(),status:Ae(["in_progress","completed"]),operation:mt("type",[N({type:Y("create_file"),path:w(),diff:w()}),N({type:Y("delete_file"),path:w()}),N({type:Y("update_file"),path:w(),diff:w()})])}),N({type:Y("custom_tool_call"),id:w(),call_id:w(),name:w(),input:w()}),N({type:Y("shell_call"),id:w(),call_id:w(),status:Ae(["in_progress","completed","incomplete"]),action:N({commands:ue(w())})}),N({type:Y("shell_call_output"),id:w(),call_id:w(),status:Ae(["in_progress","completed","incomplete"]),output:ue(N({stdout:w(),stderr:w(),outcome:mt("type",[N({type:Y("timeout")}),N({type:Y("exit"),exit_code:j()})])}))}),N({type:Y("tool_search_call"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),arguments:Cn()}),N({type:Y("tool_search_output"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),tools:ue(wt(w(),ro.optional()))})])}),N({type:Y("response.output_item.done"),output_index:j(),item:mt("type",[N({type:Y("message"),id:w(),phase:Ae(["commentary","final_answer"]).nullish()}),N({type:Y("reasoning"),id:w(),encrypted_content:w().nullish()}),N({type:Y("function_call"),id:w(),call_id:w(),name:w(),arguments:w(),status:Y("completed"),namespace:w().nullish()}),N({type:Y("custom_tool_call"),id:w(),call_id:w(),name:w(),input:w(),status:Y("completed")}),N({type:Y("code_interpreter_call"),id:w(),code:w().nullable(),container_id:w(),outputs:ue(mt("type",[N({type:Y("logs"),logs:w()}),N({type:Y("image"),url:w()})])).nullable()}),N({type:Y("image_generation_call"),id:w(),result:w()}),N({type:Y("web_search_call"),id:w(),status:w(),action:mt("type",[N({type:Y("search"),query:w().nullish(),queries:ue(w()).nullish(),sources:ue(mt("type",[N({type:Y("url"),url:w()}),N({type:Y("api"),name:w()})])).nullish()}),N({type:Y("open_page"),url:w().nullish()}),N({type:Y("find_in_page"),url:w().nullish(),pattern:w().nullish()})]).nullish()}),N({type:Y("file_search_call"),id:w(),queries:ue(w()),results:ue(N({attributes:wt(w(),st([w(),j(),Mt()])),file_id:w(),filename:w(),score:j(),text:w()})).nullish()}),N({type:Y("local_shell_call"),id:w(),call_id:w(),action:N({type:Y("exec"),command:ue(w()),timeout_ms:j().optional(),user:w().optional(),working_directory:w().optional(),env:wt(w(),w()).optional()})}),N({type:Y("computer_call"),id:w(),status:Y("completed")}),N({type:Y("mcp_call"),id:w(),status:w(),arguments:w(),name:w(),server_label:w(),output:w().nullish(),error:st([w(),N({type:w().optional(),code:st([j(),w()]).optional(),message:w().optional()}).loose()]).nullish(),approval_request_id:w().nullish()}),N({type:Y("mcp_list_tools"),id:w(),server_label:w(),tools:ue(N({name:w(),description:w().optional(),input_schema:xr(),annotations:wt(w(),Cn()).optional()})),error:st([w(),N({type:w().optional(),code:st([j(),w()]).optional(),message:w().optional()}).loose()]).optional()}),N({type:Y("mcp_approval_request"),id:w(),server_label:w(),name:w(),arguments:w(),approval_request_id:w().optional()}),N({type:Y("apply_patch_call"),id:w(),call_id:w(),status:Ae(["in_progress","completed"]),operation:mt("type",[N({type:Y("create_file"),path:w(),diff:w()}),N({type:Y("delete_file"),path:w()}),N({type:Y("update_file"),path:w(),diff:w()})])}),N({type:Y("shell_call"),id:w(),call_id:w(),status:Ae(["in_progress","completed","incomplete"]),action:N({commands:ue(w())})}),N({type:Y("shell_call_output"),id:w(),call_id:w(),status:Ae(["in_progress","completed","incomplete"]),output:ue(N({stdout:w(),stderr:w(),outcome:mt("type",[N({type:Y("timeout")}),N({type:Y("exit"),exit_code:j()})])}))}),N({type:Y("tool_search_call"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),arguments:Cn()}),N({type:Y("tool_search_output"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),tools:ue(wt(w(),ro.optional()))})])}),N({type:Y("response.function_call_arguments.delta"),item_id:w(),output_index:j(),delta:w()}),N({type:Y("response.custom_tool_call_input.delta"),item_id:w(),output_index:j(),delta:w()}),N({type:Y("response.image_generation_call.partial_image"),item_id:w(),output_index:j(),partial_image_b64:w()}),N({type:Y("response.code_interpreter_call_code.delta"),item_id:w(),output_index:j(),delta:w()}),N({type:Y("response.code_interpreter_call_code.done"),item_id:w(),output_index:j(),code:w()}),N({type:Y("response.output_text.annotation.added"),annotation:mt("type",[N({type:Y("url_citation"),start_index:j(),end_index:j(),url:w(),title:w()}),N({type:Y("file_citation"),file_id:w(),filename:w(),index:j()}),N({type:Y("container_file_citation"),container_id:w(),file_id:w(),filename:w(),start_index:j(),end_index:j()}),N({type:Y("file_path"),file_id:w(),index:j()})])}),N({type:Y("response.reasoning_summary_part.added"),item_id:w(),summary_index:j()}),N({type:Y("response.reasoning_summary_text.delta"),item_id:w(),summary_index:j(),delta:w()}),N({type:Y("response.reasoning_summary_part.done"),item_id:w(),summary_index:j()}),N({type:Y("response.apply_patch_call_operation_diff.delta"),item_id:w(),output_index:j(),delta:w(),obfuscation:w().nullish()}),N({type:Y("response.apply_patch_call_operation_diff.done"),item_id:w(),output_index:j(),diff:w()}),B2,L2,N({type:w()}).loose().transform(t=>({type:"unknown_chunk",message:t.type}))]))),U2=Fe(()=>Le(N({id:w().optional(),created_at:j().optional(),error:N({message:w(),type:w(),param:w().nullish(),code:w()}).nullish(),model:w().optional(),output:ue(mt("type",[N({type:Y("message"),role:Y("assistant"),id:w(),phase:Ae(["commentary","final_answer"]).nullish(),content:ue(N({type:Y("output_text"),text:w(),logprobs:ue(N({token:w(),logprob:j(),top_logprobs:ue(N({token:w(),logprob:j()}))})).nullish(),annotations:ue(mt("type",[N({type:Y("url_citation"),start_index:j(),end_index:j(),url:w(),title:w()}),N({type:Y("file_citation"),file_id:w(),filename:w(),index:j()}),N({type:Y("container_file_citation"),container_id:w(),file_id:w(),filename:w(),start_index:j(),end_index:j()}),N({type:Y("file_path"),file_id:w(),index:j()})]))}))}),N({type:Y("web_search_call"),id:w(),status:w(),action:mt("type",[N({type:Y("search"),query:w().nullish(),queries:ue(w()).nullish(),sources:ue(mt("type",[N({type:Y("url"),url:w()}),N({type:Y("api"),name:w()})])).nullish()}),N({type:Y("open_page"),url:w().nullish()}),N({type:Y("find_in_page"),url:w().nullish(),pattern:w().nullish()})]).nullish()}),N({type:Y("file_search_call"),id:w(),queries:ue(w()),results:ue(N({attributes:wt(w(),st([w(),j(),Mt()])),file_id:w(),filename:w(),score:j(),text:w()})).nullish()}),N({type:Y("code_interpreter_call"),id:w(),code:w().nullable(),container_id:w(),outputs:ue(mt("type",[N({type:Y("logs"),logs:w()}),N({type:Y("image"),url:w()})])).nullable()}),N({type:Y("image_generation_call"),id:w(),result:w()}),N({type:Y("local_shell_call"),id:w(),call_id:w(),action:N({type:Y("exec"),command:ue(w()),timeout_ms:j().optional(),user:w().optional(),working_directory:w().optional(),env:wt(w(),w()).optional()})}),N({type:Y("function_call"),call_id:w(),name:w(),arguments:w(),id:w(),namespace:w().nullish()}),N({type:Y("custom_tool_call"),call_id:w(),name:w(),input:w(),id:w()}),N({type:Y("computer_call"),id:w(),status:w().optional()}),N({type:Y("reasoning"),id:w(),encrypted_content:w().nullish(),summary:ue(N({type:Y("summary_text"),text:w()}))}),N({type:Y("mcp_call"),id:w(),status:w(),arguments:w(),name:w(),server_label:w(),output:w().nullish(),error:st([w(),N({type:w().optional(),code:st([j(),w()]).optional(),message:w().optional()}).loose()]).nullish(),approval_request_id:w().nullish()}),N({type:Y("mcp_list_tools"),id:w(),server_label:w(),tools:ue(N({name:w(),description:w().optional(),input_schema:xr(),annotations:wt(w(),Cn()).optional()})),error:st([w(),N({type:w().optional(),code:st([j(),w()]).optional(),message:w().optional()}).loose()]).optional()}),N({type:Y("mcp_approval_request"),id:w(),server_label:w(),name:w(),arguments:w(),approval_request_id:w().optional()}),N({type:Y("apply_patch_call"),id:w(),call_id:w(),status:Ae(["in_progress","completed"]),operation:mt("type",[N({type:Y("create_file"),path:w(),diff:w()}),N({type:Y("delete_file"),path:w()}),N({type:Y("update_file"),path:w(),diff:w()})])}),N({type:Y("shell_call"),id:w(),call_id:w(),status:Ae(["in_progress","completed","incomplete"]),action:N({commands:ue(w())})}),N({type:Y("shell_call_output"),id:w(),call_id:w(),status:Ae(["in_progress","completed","incomplete"]),output:ue(N({stdout:w(),stderr:w(),outcome:mt("type",[N({type:Y("timeout")}),N({type:Y("exit"),exit_code:j()})])}))}),N({type:Y("tool_search_call"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),arguments:Cn()}),N({type:Y("tool_search_output"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),tools:ue(wt(w(),ro.optional()))})])).optional(),service_tier:w().nullish(),reasoning:N({context:w().nullish()}).nullish(),incomplete_details:N({reason:w()}).nullish(),usage:N({input_tokens:j(),input_tokens_details:N({cached_tokens:j().nullish(),cache_write_tokens:j().nullish(),orchestration_input_tokens:j().nullish(),orchestration_input_cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:N({reasoning_tokens:j().nullish(),orchestration_output_tokens:j().nullish()}).nullish()}).optional()}))),Nu=20,Za=Fe(()=>Le(N({conversation:w().nullish(),include:ue(Ae(["reasoning.encrypted_content","file_search_call.results","web_search_call.results","message.output_text.logprobs"])).nullish(),instructions:w().nullish(),logprobs:st([Mt(),j().min(1).max(Nu)]).optional(),maxToolCalls:j().nullish(),metadata:xr().nullish(),parallelToolCalls:Mt().nullish(),previousResponseId:w().nullish(),promptCacheKey:w().nullish(),promptCacheOptions:N({mode:Ae(["implicit","explicit"]).optional(),ttl:Y("30m").optional()}).optional(),promptCacheRetention:Ae(["in_memory","24h"]).nullish(),reasoningEffort:w().nullish(),reasoningMode:Ae(["standard","pro"]).optional(),reasoningContext:Ae(["auto","current_turn","all_turns"]).optional(),reasoningSummary:w().nullish(),safetyIdentifier:w().nullish(),serviceTier:Ae(["auto","flex","priority","default"]).nullish(),store:Mt().nullish(),passThroughUnsupportedFiles:Mt().optional(),strictJsonSchema:Mt().nullish(),textVerbosity:Ae(["low","medium","high"]).nullish(),truncation:Ae(["auto","disabled"]).nullish(),user:w().nullish(),systemMessageMode:Ae(["system","developer","remove"]).optional(),forceReasoning:Mt().optional(),allowedTools:N({toolNames:ue(w()).min(1),mode:Ae(["auto","required"]).optional()}).optional()})));async function z2({tools:t,toolChoice:r,allowedTools:i,toolNameMapping:c,customProviderToolNames:d}){var f,m,x;t=t?.length?t:void 0;const v=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:v};const g=[],E=new Map,A=d??new Set;for(const T of t)switch(T.type){case"function":{const S=(f=T.providerOptions)==null?void 0:f.openai,P=V2({tool:T,options:S}),M=S?.namespace;if(M==null)g.push(P);else{let ee=E.get(M.name);if(ee==null)ee={type:"namespace",name:M.name,description:M.description,tools:[]},E.set(M.name,ee),g.push(ee);else if(ee.description!==M.description)throw new Mn({functionality:`conflicting descriptions for OpenAI tool namespace "${M.name}"`});ee.tools.push(P)}break}case"provider":{switch(T.id){case"openai.file_search":{const S=await Dt({value:T.args,schema:r2});g.push({type:"file_search",vector_store_ids:S.vectorStoreIds,max_num_results:S.maxNumResults,ranking_options:S.ranking?{ranker:S.ranking.ranker,score_threshold:S.ranking.scoreThreshold}:void 0,filters:S.filters});break}case"openai.local_shell":{g.push({type:"local_shell"});break}case"openai.shell":{const S=await Dt({value:T.args,schema:h2});g.push({type:"shell",...S.environment&&{environment:Z2(S.environment)}});break}case"openai.apply_patch":{g.push({type:"apply_patch"});break}case"openai.web_search_preview":{const S=await Dt({value:T.args,schema:b2});g.push({type:"web_search_preview",search_context_size:S.searchContextSize,user_location:S.userLocation});break}case"openai.web_search":{const S=await Dt({value:T.args,schema:y2});g.push({type:"web_search",filters:S.filters!=null?{allowed_domains:S.filters.allowedDomains}:void 0,external_web_access:S.externalWebAccess,search_context_size:S.searchContextSize,user_location:S.userLocation});break}case"openai.code_interpreter":{const S=await Dt({value:T.args,schema:Yg});g.push({type:"code_interpreter",container:S.container==null?{type:"auto",file_ids:void 0}:typeof S.container=="string"?S.container:{type:"auto",file_ids:S.container.fileIds}});break}case"openai.image_generation":{const S=await Dt({value:T.args,schema:s2});g.push({type:"image_generation",background:S.background,input_fidelity:S.inputFidelity,input_image_mask:S.inputImageMask?{file_id:S.inputImageMask.fileId,image_url:S.inputImageMask.imageUrl}:void 0,model:S.model,moderation:S.moderation,partial_images:S.partialImages,quality:S.quality,output_compression:S.outputCompression,output_format:S.outputFormat,size:S.size});break}case"openai.mcp":{const S=await Dt({value:T.args,schema:S2}),P=$=>({tool_names:$.toolNames}),M=S.requireApproval,ee=M==null?void 0:typeof M=="string"?M:M.never!=null?{never:P(M.never)}:void 0;g.push({type:"mcp",server_label:S.serverLabel,allowed_tools:Array.isArray(S.allowedTools)?S.allowedTools:S.allowedTools?{read_only:S.allowedTools.readOnly,tool_names:S.allowedTools.toolNames}:void 0,authorization:S.authorization,connector_id:S.connectorId,headers:S.headers,require_approval:ee??"never",server_description:S.serverDescription,server_url:S.serverUrl});break}case"openai.custom":{const S=await Dt({value:T.args,schema:Qg});g.push({type:"custom",name:S.name,description:S.description,format:S.format}),A.add(S.name);break}case"openai.tool_search":{const S=await Dt({value:T.args,schema:m2});g.push({type:"tool_search",...S.execution!=null?{execution:S.execution}:{},...S.description!=null?{description:S.description}:{},...S.parameters!=null?{parameters:S.parameters}:{}});break}}break}default:v.push({type:"unsupported",feature:`function tool ${T}`});break}if(i!=null)return{tools:g,toolChoice:{type:"allowed_tools",mode:(m=i.mode)!=null?m:"auto",tools:i.toolNames.map(T=>{var S;return{type:"function",name:(S=c?.toProviderToolName(T))!=null?S:T}})},toolWarnings:v};if(r==null)return{tools:g,toolChoice:void 0,toolWarnings:v};const D=r.type;switch(D){case"auto":case"none":case"required":return{tools:g,toolChoice:D,toolWarnings:v};case"tool":{const T=(x=c?.toProviderToolName(r.toolName))!=null?x:r.toolName;return{tools:g,toolChoice:T==="code_interpreter"||T==="file_search"||T==="image_generation"||T==="web_search_preview"||T==="web_search"||T==="mcp"||T==="apply_patch"?{type:T}:A.has(T)?{type:"custom",name:T}:{type:"function",name:T},toolWarnings:v}}default:{const T=D;throw new Mn({functionality:`tool choice type: ${T}`})}}}function V2({tool:t,options:r}){const i=r?.deferLoading;return{type:"function",name:t.name,description:t.description,parameters:t.inputSchema,...t.strict!=null?{strict:t.strict}:{},...i!=null?{defer_loading:i}:{}}}function Z2(t){if(t.type==="containerReference")return{type:"container_reference",container_id:t.containerId};if(t.type==="containerAuto"){const i=t;return{type:"container_auto",file_ids:i.fileIds,memory_limit:i.memoryLimit,network_policy:i.networkPolicy==null?void 0:i.networkPolicy.type==="disabled"?{type:"disabled"}:{type:"allowlist",allowed_domains:i.networkPolicy.allowedDomains,domain_secrets:i.networkPolicy.domainSecrets},skills:$2(i.skills)}}return{type:"local",skills:t.skills}}function $2(t){return t?.map(r=>r.type==="skillReference"?{type:"skill_reference",skill_id:r.skillId,version:r.version}:{type:"inline",name:r.name,description:r.description,source:{type:"base64",media_type:r.source.mediaType,data:r.source.data}})}function $a(t){var r,i;const c={};for(const d of t)if(d.role==="assistant")for(const f of d.content){if(f.type!=="tool-call")continue;const m=(i=(r=f.providerOptions)==null?void 0:r.openai)==null?void 0:i.approvalRequestId;m!=null&&(c[m]=f.toolCallId)}return c}var j2=class{constructor(t,r){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=t,this.config=r}get provider(){return this.config.provider}async getArgs({maxOutputTokens:t,temperature:r,stopSequences:i,topP:c,topK:d,presencePenalty:f,frequencyPenalty:m,seed:x,prompt:v,providerOptions:g,tools:E,toolChoice:A,responseFormat:D}){var T,S,P,M,ee,$,F,re,Z,B,L;const W=[],z=_u(this.modelId);d!=null&&W.push({type:"unsupported",feature:"topK"}),x!=null&&W.push({type:"unsupported",feature:"seed"}),f!=null&&W.push({type:"unsupported",feature:"presencePenalty"}),m!=null&&W.push({type:"unsupported",feature:"frequencyPenalty"}),i!=null&&W.push({type:"unsupported",feature:"stopSequences"});const we=this.config.provider.includes("azure")?"azure":"openai";let G=await An({provider:we,providerOptions:g,schema:Za});G==null&&we!=="openai"&&(G=await An({provider:"openai",providerOptions:g,schema:Za}));const me=(T=G?.forceReasoning)!=null?T:z.isReasoningModel;G?.conversation&&G?.previousResponseId&&W.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const fe=Gp({tools:E,providerToolNames:{"openai.code_interpreter":"code_interpreter","openai.file_search":"file_search","openai.image_generation":"image_generation","openai.local_shell":"local_shell","openai.shell":"shell","openai.web_search":"web_search","openai.web_search_preview":"web_search_preview","openai.mcp":"mcp","openai.apply_patch":"apply_patch","openai.tool_search":"tool_search"},resolveProviderToolName:ae=>ae.id==="openai.custom"?ae.args.name:void 0}),te=new Set,{tools:q,toolChoice:ke,toolWarnings:le}=await z2({tools:E,toolChoice:A,allowedTools:(S=G?.allowedTools)!=null?S:void 0,toolNameMapping:fe,customProviderToolNames:te}),{input:Te,warnings:Je}=await D2({prompt:v,toolNameMapping:fe,systemMessageMode:(P=G?.systemMessageMode)!=null?P:me?"developer":z.systemMessageMode,providerOptionsName:we,fileIdPrefixes:this.config.fileIdPrefixes,passThroughUnsupportedFiles:(M=G?.passThroughUnsupportedFiles)!=null?M:!1,store:(ee=G?.store)!=null?ee:!0,hasConversation:G?.conversation!=null,hasPreviousResponseId:G?.previousResponseId!=null,hasLocalShellTool:Ze("openai.local_shell"),hasShellTool:Ze("openai.shell"),hasApplyPatchTool:Ze("openai.apply_patch"),customProviderToolNames:te.size>0?te:void 0});W.push(...Je);const xe=($=G?.strictJsonSchema)!=null?$:!0;let $e=G?.include;function Ue(ae){$e==null?$e=[ae]:$e.includes(ae)||($e=[...$e,ae])}function Ze(ae){return E?.find(J=>J.type==="provider"&&J.id===ae)!=null}const qe=typeof G?.logprobs=="number"?G?.logprobs:G?.logprobs===!0?Nu:void 0;qe&&Ue("message.output_text.logprobs");const ze=(F=E?.find(ae=>ae.type==="provider"&&(ae.id==="openai.web_search"||ae.id==="openai.web_search_preview")))==null?void 0:F.name;ze&&Ue("web_search_call.action.sources"),Ze("openai.code_interpreter")&&Ue("code_interpreter_call.outputs");const ie=G?.store;ie===!1&&me&&Ue("reasoning.encrypted_content");const de={model:this.modelId,input:Te,temperature:r,top_p:c,max_output_tokens:t,...(D?.type==="json"||G?.textVerbosity)&&{text:{...D?.type==="json"&&{format:D.schema!=null?{type:"json_schema",strict:xe,name:(re=D.name)!=null?re:"response",description:D.description,schema:D.schema}:{type:"json_object"}},...G?.textVerbosity&&{verbosity:G.textVerbosity}}},conversation:G?.conversation,max_tool_calls:G?.maxToolCalls,metadata:G?.metadata,parallel_tool_calls:G?.parallelToolCalls,previous_response_id:G?.previousResponseId,store:ie,user:G?.user,instructions:G?.instructions,service_tier:G?.serviceTier,include:$e,prompt_cache_key:G?.promptCacheKey,prompt_cache_options:G?.promptCacheOptions,prompt_cache_retention:G?.promptCacheRetention,safety_identifier:G?.safetyIdentifier,top_logprobs:qe,truncation:G?.truncation,...me&&(G?.reasoningEffort!=null||G?.reasoningSummary!=null||G?.reasoningMode!=null||G?.reasoningContext!=null)&&{reasoning:{...G?.reasoningEffort!=null&&{effort:G.reasoningEffort},...G?.reasoningSummary!=null&&{summary:G.reasoningSummary},...G?.reasoningMode!=null&&{mode:G.reasoningMode},...G?.reasoningContext!=null&&{context:G.reasoningContext}}}};me?G?.reasoningEffort==="none"&&z.supportsNonReasoningParameters||(de.temperature!=null&&(de.temperature=void 0,W.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),de.top_p!=null&&(de.top_p=void 0,W.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(G?.reasoningEffort!=null&&W.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),G?.reasoningSummary!=null&&W.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"}),G?.reasoningMode!=null&&W.push({type:"unsupported",feature:"reasoningMode",details:"reasoningMode is not supported for non-reasoning models"}),G?.reasoningContext!=null&&W.push({type:"unsupported",feature:"reasoningContext",details:"reasoningContext is not supported for non-reasoning models"})),G?.serviceTier==="flex"&&!z.supportsFlexProcessing&&(W.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete de.service_tier),G?.serviceTier==="priority"&&!z.supportsPriorityProcessing&&(W.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete de.service_tier);const _e=(L=(B=(Z=E?.find(ae=>ae.type==="provider"&&ae.id==="openai.shell"))==null?void 0:Z.args)==null?void 0:B.environment)==null?void 0:L.type,Pe=_e==="containerAuto"||_e==="containerReference";return{webSearchToolName:ze,args:{...de,tools:q,tool_choice:ke},warnings:[...W,...le],store:ie,toolNameMapping:fe,providerOptionsName:we,isShellProviderExecuted:Pe}}async doGenerate(t){var r,i,c,d,f,m,x,v,g,E,A,D,T,S,P,M,ee,$,F,re,Z,B,L,W,z,we,G,me,fe;const{args:te,warnings:q,webSearchToolName:ke,toolNameMapping:le,providerOptionsName:Te,isShellProviderExecuted:Je}=await this.getArgs(t),xe=this.config.url({path:"/responses",modelId:this.modelId}),$e=$a(t.prompt),{responseHeaders:Ue,value:Ze,rawValue:qe}=await Zn({url:xe,headers:bn(this.config.headers(),t.headers),body:te,failedResponseHandler:En,successfulResponseHandler:mr(U2),abortSignal:t.abortSignal,fetch:this.config.fetch});if(Ze.error)throw new Kt({message:Ze.error.message,url:xe,requestBodyValues:te,statusCode:400,responseHeaders:Ue,responseBody:qe,isRetryable:!1});const ze=[],ie=[];let de=!1;const _e=[];for(const J of Ze.output)switch(J.type){case"reasoning":{J.summary.length===0&&J.summary.push({type:"summary_text",text:""});for(const ye of J.summary)ze.push({type:"reasoning",text:ye.text,providerMetadata:{[Te]:{itemId:J.id,reasoningEncryptedContent:(r=J.encrypted_content)!=null?r:null}}});break}case"image_generation_call":{ze.push({type:"tool-call",toolCallId:J.id,toolName:le.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),ze.push({type:"tool-result",toolCallId:J.id,toolName:le.toCustomToolName("image_generation"),result:{result:J.result}});break}case"tool_search_call":{const ye=(i=J.call_id)!=null?i:J.id,Se=J.execution==="server";Se&&_e.push(ye),ze.push({type:"tool-call",toolCallId:ye,toolName:le.toCustomToolName("tool_search"),input:JSON.stringify({arguments:J.arguments,call_id:J.call_id}),...Se?{providerExecuted:!0}:{},providerMetadata:{[Te]:{itemId:J.id}}});break}case"tool_search_output":{const ye=(d=(c=J.call_id)!=null?c:_e.shift())!=null?d:J.id;ze.push({type:"tool-result",toolCallId:ye,toolName:le.toCustomToolName("tool_search"),result:{tools:J.tools},providerMetadata:{[Te]:{itemId:J.id}}});break}case"local_shell_call":{ze.push({type:"tool-call",toolCallId:J.call_id,toolName:le.toCustomToolName("local_shell"),input:JSON.stringify({action:J.action}),providerMetadata:{[Te]:{itemId:J.id}}});break}case"shell_call":{ze.push({type:"tool-call",toolCallId:J.call_id,toolName:le.toCustomToolName("shell"),input:JSON.stringify({action:{commands:J.action.commands}}),...Je&&{providerExecuted:!0},providerMetadata:{[Te]:{itemId:J.id}}});break}case"shell_call_output":{ze.push({type:"tool-result",toolCallId:J.call_id,toolName:le.toCustomToolName("shell"),result:{output:J.output.map(ye=>({stdout:ye.stdout,stderr:ye.stderr,outcome:ye.outcome.type==="exit"?{type:"exit",exitCode:ye.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const ye of J.content){(m=(f=t.providerOptions)==null?void 0:f[Te])!=null&&m.logprobs&&ye.logprobs&&ie.push(ye.logprobs);const Se={itemId:J.id,...J.phase!=null&&{phase:J.phase},...ye.annotations.length>0&&{annotations:ye.annotations}};ze.push({type:"text",text:ye.text,providerMetadata:{[Te]:Se}});for(const Ve of ye.annotations)Ve.type==="url_citation"?ze.push({type:"source",sourceType:"url",id:(g=(v=(x=this.config).generateId)==null?void 0:v.call(x))!=null?g:rn(),url:Ve.url,title:Ve.title}):Ve.type==="file_citation"?ze.push({type:"source",sourceType:"document",id:(D=(A=(E=this.config).generateId)==null?void 0:A.call(E))!=null?D:rn(),mediaType:"text/plain",title:Ve.filename,filename:Ve.filename,providerMetadata:{[Te]:{type:Ve.type,fileId:Ve.file_id,index:Ve.index}}}):Ve.type==="container_file_citation"?ze.push({type:"source",sourceType:"document",id:(P=(S=(T=this.config).generateId)==null?void 0:S.call(T))!=null?P:rn(),mediaType:"text/plain",title:Ve.filename,filename:Ve.filename,providerMetadata:{[Te]:{type:Ve.type,fileId:Ve.file_id,containerId:Ve.container_id}}}):Ve.type==="file_path"&&ze.push({type:"source",sourceType:"document",id:($=(ee=(M=this.config).generateId)==null?void 0:ee.call(M))!=null?$:rn(),mediaType:"application/octet-stream",title:Ve.file_id,filename:Ve.file_id,providerMetadata:{[Te]:{type:Ve.type,fileId:Ve.file_id,index:Ve.index}}})}break}case"function_call":{de=!0,ze.push({type:"tool-call",toolCallId:J.call_id,toolName:J.name,input:J.arguments,providerMetadata:{[Te]:{itemId:J.id,...J.namespace!=null&&{namespace:J.namespace}}}});break}case"custom_tool_call":{de=!0;const ye=le.toCustomToolName(J.name);ze.push({type:"tool-call",toolCallId:J.call_id,toolName:ye,input:JSON.stringify(J.input),providerMetadata:{[Te]:{itemId:J.id}}});break}case"web_search_call":{ze.push({type:"tool-call",toolCallId:J.id,toolName:le.toCustomToolName(ke??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),ze.push({type:"tool-result",toolCallId:J.id,toolName:le.toCustomToolName(ke??"web_search"),result:Ga(J.action)});break}case"mcp_call":{const ye=J.approval_request_id!=null&&(F=$e[J.approval_request_id])!=null?F:J.id,Se=`mcp.${J.name}`;ze.push({type:"tool-call",toolCallId:ye,toolName:Se,input:J.arguments,providerExecuted:!0,dynamic:!0}),ze.push({type:"tool-result",toolCallId:ye,toolName:Se,result:{type:"call",serverLabel:J.server_label,name:J.name,arguments:J.arguments,...J.output!=null?{output:J.output}:{},...J.error!=null?{error:J.error}:{}},providerMetadata:{[Te]:{itemId:J.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const ye=(re=J.approval_request_id)!=null?re:J.id,Se=(L=(B=(Z=this.config).generateId)==null?void 0:B.call(Z))!=null?L:rn(),Ve=`mcp.${J.name}`;ze.push({type:"tool-call",toolCallId:Se,toolName:Ve,input:J.arguments,providerExecuted:!0,dynamic:!0}),ze.push({type:"tool-approval-request",approvalId:ye,toolCallId:Se});break}case"computer_call":{ze.push({type:"tool-call",toolCallId:J.id,toolName:le.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),ze.push({type:"tool-result",toolCallId:J.id,toolName:le.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:J.status||"completed"}});break}case"file_search_call":{ze.push({type:"tool-call",toolCallId:J.id,toolName:le.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),ze.push({type:"tool-result",toolCallId:J.id,toolName:le.toCustomToolName("file_search"),result:{queries:J.queries,results:(z=(W=J.results)==null?void 0:W.map(ye=>({attributes:ye.attributes,fileId:ye.file_id,filename:ye.filename,score:ye.score,text:ye.text})))!=null?z:null}});break}case"code_interpreter_call":{ze.push({type:"tool-call",toolCallId:J.id,toolName:le.toCustomToolName("code_interpreter"),input:JSON.stringify({code:J.code,containerId:J.container_id}),providerExecuted:!0}),ze.push({type:"tool-result",toolCallId:J.id,toolName:le.toCustomToolName("code_interpreter"),result:{outputs:J.outputs}});break}case"apply_patch_call":{ze.push({type:"tool-call",toolCallId:J.call_id,toolName:le.toCustomToolName("apply_patch"),input:JSON.stringify({callId:J.call_id,operation:J.operation}),providerMetadata:{[Te]:{itemId:J.id}}});break}}const Pe={[Te]:{responseId:Ze.id,...ie.length>0?{logprobs:ie}:{},...typeof Ze.service_tier=="string"?{serviceTier:Ze.service_tier}:{},...((we=Ze.reasoning)==null?void 0:we.context)!=null?{reasoningContext:Ze.reasoning.context}:{}}},ae=Ze.usage;return{content:ze,finishReason:{unified:gi({finishReason:(G=Ze.incomplete_details)==null?void 0:G.reason,hasFunctionCall:de}),raw:(fe=(me=Ze.incomplete_details)==null?void 0:me.reason)!=null?fe:void 0},usage:za(ae),request:{body:te},response:{id:Ze.id,timestamp:new Date(Ze.created_at*1e3),modelId:Ze.model,headers:Ue,body:qe},providerMetadata:Pe,warnings:q}}async doStream(t){const{args:r,warnings:i,webSearchToolName:c,toolNameMapping:d,store:f,providerOptionsName:m,isShellProviderExecuted:x}=await this.getArgs(t),v=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:g,value:E}=await Zn({url:v,headers:bn(this.config.headers(),t.headers),body:{...r,stream:!0},failedResponseHandler:En,successfulResponseHandler:Ji(F2),abortSignal:t.abortSignal,fetch:this.config.fetch}),A=await es({stream:E,getError:fe=>Wa(fe)||ja(fe)&&fe.response.error!=null?fe:void 0,isOutputChunk:sx,url:v,requestBodyValues:r,responseHeaders:g}),D=this,T=$a(t.prompt),S=new Map;let P={unified:"other",raw:void 0},M;const ee=[];let $=null;const F={},re=[];let Z,B=!1;const L={};let W,z;const we=[];let G=!1;return{stream:A.pipeThrough(new TransformStream({start(fe){fe.enqueue({type:"stream-start",warnings:i})},transform(fe,te){var q,ke,le,Te,Je,xe,$e,Ue,Ze,qe,ze,ie,de,_e,Pe,ae,J,ye,Se,Ve,St,vt,et,nt,Xe,In,be,Bn,$n,qt,jn,Ft,rr,sn,At,or,Ln,wr,gt,ge;if(t.includeRawChunks&&te.enqueue({type:"raw",rawValue:fe.rawValue}),!fe.success){const ne=W2(fe.rawValue)?G2({value:fe.rawValue,cause:fe.error,url:v,requestBodyValues:r,responseHeaders:g}):fe.error;P={unified:"error",raw:void 0},te.enqueue({type:"error",error:ne});return}const O=fe.value;if(Ha(O)){if(O.item.type==="function_call")F[O.output_index]={toolName:O.item.name,toolCallId:O.item.call_id},te.enqueue({type:"tool-input-start",id:O.item.call_id,toolName:O.item.name});else if(O.item.type==="custom_tool_call"){const ne=d.toCustomToolName(O.item.name);F[O.output_index]={toolName:ne,toolCallId:O.item.call_id},te.enqueue({type:"tool-input-start",id:O.item.call_id,toolName:ne})}else if(O.item.type==="web_search_call")F[O.output_index]={toolName:d.toCustomToolName(c??"web_search"),toolCallId:O.item.id},te.enqueue({type:"tool-input-start",id:O.item.id,toolName:d.toCustomToolName(c??"web_search"),providerExecuted:!0}),te.enqueue({type:"tool-input-end",id:O.item.id}),te.enqueue({type:"tool-call",toolCallId:O.item.id,toolName:d.toCustomToolName(c??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(O.item.type==="computer_call")F[O.output_index]={toolName:d.toCustomToolName("computer_use"),toolCallId:O.item.id},te.enqueue({type:"tool-input-start",id:O.item.id,toolName:d.toCustomToolName("computer_use"),providerExecuted:!0});else if(O.item.type==="code_interpreter_call")F[O.output_index]={toolName:d.toCustomToolName("code_interpreter"),toolCallId:O.item.id,codeInterpreter:{containerId:O.item.container_id}},te.enqueue({type:"tool-input-start",id:O.item.id,toolName:d.toCustomToolName("code_interpreter"),providerExecuted:!0}),te.enqueue({type:"tool-input-delta",id:O.item.id,delta:`{"containerId":"${O.item.container_id}","code":"`});else if(O.item.type==="file_search_call")te.enqueue({type:"tool-call",toolCallId:O.item.id,toolName:d.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(O.item.type==="image_generation_call")te.enqueue({type:"tool-call",toolCallId:O.item.id,toolName:d.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(O.item.type==="tool_search_call"){const ne=O.item.id,Me=d.toCustomToolName("tool_search"),Ee=O.item.execution==="server";F[O.output_index]={toolName:Me,toolCallId:ne,toolSearchExecution:(q=O.item.execution)!=null?q:"server"},Ee&&te.enqueue({type:"tool-input-start",id:ne,toolName:Me,providerExecuted:!0})}else if(O.item.type!=="tool_search_output"){if(!(O.item.type==="mcp_call"||O.item.type==="mcp_list_tools"||O.item.type==="mcp_approval_request"))if(O.item.type==="apply_patch_call"){const{call_id:ne,operation:Me}=O.item;if(F[O.output_index]={toolName:d.toCustomToolName("apply_patch"),toolCallId:ne,applyPatch:{hasDiff:Me.type==="delete_file",endEmitted:Me.type==="delete_file"}},te.enqueue({type:"tool-input-start",id:ne,toolName:d.toCustomToolName("apply_patch")}),Me.type==="delete_file"){const Ee=JSON.stringify({callId:ne,operation:Me});te.enqueue({type:"tool-input-delta",id:ne,delta:Ee}),te.enqueue({type:"tool-input-end",id:ne})}else te.enqueue({type:"tool-input-delta",id:ne,delta:`{"callId":"${fr(ne)}","operation":{"type":"${fr(Me.type)}","path":"${fr(Me.path)}","diff":"`})}else O.item.type==="shell_call"?F[O.output_index]={toolName:d.toCustomToolName("shell"),toolCallId:O.item.call_id}:O.item.type==="shell_call_output"||(O.item.type==="message"?(re.splice(0,re.length),Z=(ke=O.item.phase)!=null?ke:void 0,te.enqueue({type:"text-start",id:O.item.id,providerMetadata:{[m]:{itemId:O.item.id,...O.item.phase!=null&&{phase:O.item.phase}}}})):Ha(O)&&O.item.type==="reasoning"&&(L[O.item.id]={encryptedContent:O.item.encrypted_content,summaryParts:{0:"active"}},te.enqueue({type:"reasoning-start",id:`${O.item.id}:0`,providerMetadata:{[m]:{itemId:O.item.id,reasoningEncryptedContent:(le=O.item.encrypted_content)!=null?le:null}}})))}}else if(X2(O)){if(O.item.type==="message"){const ne=(Te=O.item.phase)!=null?Te:Z;Z=void 0,te.enqueue({type:"text-end",id:O.item.id,providerMetadata:{[m]:{itemId:O.item.id,...ne!=null&&{phase:ne},...re.length>0&&{annotations:re}}}})}else if(O.item.type==="function_call")F[O.output_index]=void 0,B=!0,te.enqueue({type:"tool-input-end",id:O.item.call_id,...O.item.namespace!=null&&{providerMetadata:{[m]:{namespace:O.item.namespace}}}}),te.enqueue({type:"tool-call",toolCallId:O.item.call_id,toolName:O.item.name,input:O.item.arguments,providerMetadata:{[m]:{itemId:O.item.id,...O.item.namespace!=null&&{namespace:O.item.namespace}}}});else if(O.item.type==="custom_tool_call"){F[O.output_index]=void 0,B=!0;const ne=d.toCustomToolName(O.item.name);te.enqueue({type:"tool-input-end",id:O.item.call_id}),te.enqueue({type:"tool-call",toolCallId:O.item.call_id,toolName:ne,input:JSON.stringify(O.item.input),providerMetadata:{[m]:{itemId:O.item.id}}})}else if(O.item.type==="web_search_call")F[O.output_index]=void 0,te.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:d.toCustomToolName(c??"web_search"),result:Ga(O.item.action)});else if(O.item.type==="computer_call")F[O.output_index]=void 0,te.enqueue({type:"tool-input-end",id:O.item.id}),te.enqueue({type:"tool-call",toolCallId:O.item.id,toolName:d.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),te.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:d.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:O.item.status||"completed"}});else if(O.item.type==="file_search_call")F[O.output_index]=void 0,te.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:d.toCustomToolName("file_search"),result:{queries:O.item.queries,results:(xe=(Je=O.item.results)==null?void 0:Je.map(ne=>({attributes:ne.attributes,fileId:ne.file_id,filename:ne.filename,score:ne.score,text:ne.text})))!=null?xe:null}});else if(O.item.type==="code_interpreter_call")F[O.output_index]=void 0,te.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:d.toCustomToolName("code_interpreter"),result:{outputs:O.item.outputs}});else if(O.item.type==="image_generation_call")te.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:d.toCustomToolName("image_generation"),result:{result:O.item.result}});else if(O.item.type==="tool_search_call"){const ne=F[O.output_index],Me=O.item.execution==="server";if(ne!=null){const Ee=Me?ne.toolCallId:($e=O.item.call_id)!=null?$e:O.item.id;Me?we.push(Ee):te.enqueue({type:"tool-input-start",id:Ee,toolName:ne.toolName}),te.enqueue({type:"tool-input-end",id:Ee}),te.enqueue({type:"tool-call",toolCallId:Ee,toolName:ne.toolName,input:JSON.stringify({arguments:O.item.arguments,call_id:Me?null:Ee}),...Me?{providerExecuted:!0}:{},providerMetadata:{[m]:{itemId:O.item.id}}})}F[O.output_index]=void 0}else if(O.item.type==="tool_search_output"){const ne=(Ze=(Ue=O.item.call_id)!=null?Ue:we.shift())!=null?Ze:O.item.id;te.enqueue({type:"tool-result",toolCallId:ne,toolName:d.toCustomToolName("tool_search"),result:{tools:O.item.tools},providerMetadata:{[m]:{itemId:O.item.id}}})}else if(O.item.type==="mcp_call"){F[O.output_index]=void 0;const ne=(qe=O.item.approval_request_id)!=null?qe:void 0,Me=ne!=null&&(ie=(ze=S.get(ne))!=null?ze:T[ne])!=null?ie:O.item.id,Ee=`mcp.${O.item.name}`;te.enqueue({type:"tool-call",toolCallId:Me,toolName:Ee,input:O.item.arguments,providerExecuted:!0,dynamic:!0}),te.enqueue({type:"tool-result",toolCallId:Me,toolName:Ee,result:{type:"call",serverLabel:O.item.server_label,name:O.item.name,arguments:O.item.arguments,...O.item.output!=null?{output:O.item.output}:{},...O.item.error!=null?{error:O.item.error}:{}},providerMetadata:{[m]:{itemId:O.item.id}}})}else if(O.item.type==="mcp_list_tools")F[O.output_index]=void 0;else if(O.item.type==="apply_patch_call"){const ne=F[O.output_index];ne?.applyPatch&&!ne.applyPatch.endEmitted&&O.item.operation.type!=="delete_file"&&(ne.applyPatch.hasDiff||te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:fr(O.item.operation.diff)}),te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:'"}}'}),te.enqueue({type:"tool-input-end",id:ne.toolCallId}),ne.applyPatch.endEmitted=!0),ne&&O.item.status==="completed"&&te.enqueue({type:"tool-call",toolCallId:ne.toolCallId,toolName:d.toCustomToolName("apply_patch"),input:JSON.stringify({callId:O.item.call_id,operation:O.item.operation}),providerMetadata:{[m]:{itemId:O.item.id}}}),F[O.output_index]=void 0}else if(O.item.type==="mcp_approval_request"){F[O.output_index]=void 0;const ne=(Pe=(_e=(de=D.config).generateId)==null?void 0:_e.call(de))!=null?Pe:rn(),Me=(ae=O.item.approval_request_id)!=null?ae:O.item.id;S.set(Me,ne);const Ee=`mcp.${O.item.name}`;te.enqueue({type:"tool-call",toolCallId:ne,toolName:Ee,input:O.item.arguments,providerExecuted:!0,dynamic:!0}),te.enqueue({type:"tool-approval-request",approvalId:Me,toolCallId:ne})}else if(O.item.type==="local_shell_call")F[O.output_index]=void 0,te.enqueue({type:"tool-call",toolCallId:O.item.call_id,toolName:d.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:O.item.action.command,timeoutMs:O.item.action.timeout_ms,user:O.item.action.user,workingDirectory:O.item.action.working_directory,env:O.item.action.env}}),providerMetadata:{[m]:{itemId:O.item.id}}});else if(O.item.type==="shell_call")F[O.output_index]=void 0,te.enqueue({type:"tool-call",toolCallId:O.item.call_id,toolName:d.toCustomToolName("shell"),input:JSON.stringify({action:{commands:O.item.action.commands}}),...x&&{providerExecuted:!0},providerMetadata:{[m]:{itemId:O.item.id}}});else if(O.item.type==="shell_call_output")te.enqueue({type:"tool-result",toolCallId:O.item.call_id,toolName:d.toCustomToolName("shell"),result:{output:O.item.output.map(ne=>({stdout:ne.stdout,stderr:ne.stderr,outcome:ne.outcome.type==="exit"?{type:"exit",exitCode:ne.outcome.exit_code}:{type:"timeout"}}))}});else if(O.item.type==="reasoning"){const ne=L[O.item.id],Me=Object.entries(ne.summaryParts).filter(([Ee,Oe])=>Oe==="active"||Oe==="can-conclude").map(([Ee])=>Ee);for(const Ee of Me)te.enqueue({type:"reasoning-end",id:`${O.item.id}:${Ee}`,providerMetadata:{[m]:{itemId:O.item.id,reasoningEncryptedContent:(J=O.item.encrypted_content)!=null?J:null}}});delete L[O.item.id]}}else if(J2(O)){const ne=F[O.output_index];ne!=null&&te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:O.delta})}else if(Q2(O)){const ne=F[O.output_index];ne!=null&&te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:O.delta})}else if(rx(O)){const ne=F[O.output_index];ne?.applyPatch&&(te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:fr(O.delta)}),ne.applyPatch.hasDiff=!0)}else if(ox(O)){const ne=F[O.output_index];ne?.applyPatch&&!ne.applyPatch.endEmitted&&(ne.applyPatch.hasDiff||(te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:fr(O.diff)}),ne.applyPatch.hasDiff=!0),te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:'"}}'}),te.enqueue({type:"tool-input-end",id:ne.toolCallId}),ne.applyPatch.endEmitted=!0)}else if(ex(O))te.enqueue({type:"tool-result",toolCallId:O.item_id,toolName:d.toCustomToolName("image_generation"),result:{result:O.partial_image_b64},preliminary:!0});else if(tx(O)){const ne=F[O.output_index];ne!=null&&te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:fr(O.delta)})}else if(nx(O)){const ne=F[O.output_index];ne!=null&&(te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:'"}'}),te.enqueue({type:"tool-input-end",id:ne.toolCallId}),te.enqueue({type:"tool-call",toolCallId:ne.toolCallId,toolName:d.toCustomToolName("code_interpreter"),input:JSON.stringify({code:O.code,containerId:ne.codeInterpreter.containerId}),providerExecuted:!0}))}else if(K2(O))$=O.response.id,te.enqueue({type:"response-metadata",id:O.response.id,timestamp:new Date(O.response.created_at*1e3),modelId:O.response.model});else if(H2(O))te.enqueue({type:"text-delta",id:O.item_id,delta:O.delta}),(Se=(ye=t.providerOptions)==null?void 0:ye[m])!=null&&Se.logprobs&&O.logprobs&&ee.push(O.logprobs);else if(O.type==="response.reasoning_summary_part.added"){if(O.summary_index>0){const ne=L[O.item_id];ne.summaryParts[O.summary_index]="active";for(const Me of Object.keys(ne.summaryParts))ne.summaryParts[Me]==="can-conclude"&&(te.enqueue({type:"reasoning-end",id:`${O.item_id}:${Me}`,providerMetadata:{[m]:{itemId:O.item_id}}}),ne.summaryParts[Me]="concluded");te.enqueue({type:"reasoning-start",id:`${O.item_id}:${O.summary_index}`,providerMetadata:{[m]:{itemId:O.item_id,reasoningEncryptedContent:(St=(Ve=L[O.item_id])==null?void 0:Ve.encryptedContent)!=null?St:null}}})}}else if(O.type==="response.reasoning_summary_text.delta")te.enqueue({type:"reasoning-delta",id:`${O.item_id}:${O.summary_index}`,delta:O.delta,providerMetadata:{[m]:{itemId:O.item_id}}});else if(O.type==="response.reasoning_summary_part.done")f?(te.enqueue({type:"reasoning-end",id:`${O.item_id}:${O.summary_index}`,providerMetadata:{[m]:{itemId:O.item_id}}}),L[O.item_id].summaryParts[O.summary_index]="concluded"):L[O.item_id].summaryParts[O.summary_index]="can-conclude";else if(Y2(O))P={unified:gi({finishReason:(vt=O.response.incomplete_details)==null?void 0:vt.reason,hasFunctionCall:B}),raw:(nt=(et=O.response.incomplete_details)==null?void 0:et.reason)!=null?nt:void 0},M=O.response.usage,typeof O.response.service_tier=="string"&&(W=O.response.service_tier),((Xe=O.response.reasoning)==null?void 0:Xe.context)!=null&&(z=O.response.reasoning.context);else if(ja(O)){const ne=(In=O.response.incomplete_details)==null?void 0:In.reason;P={unified:ne?gi({finishReason:ne,hasFunctionCall:B}):"error",raw:ne??"error"},M=(be=O.response.usage)!=null?be:void 0,((Bn=O.response.reasoning)==null?void 0:Bn.context)!=null&&(z=O.response.reasoning.context),!G&&O.response.error!=null&&(G=!0,te.enqueue({type:"error",error:{type:"response.failed",sequence_number:O.sequence_number,response:{error:O.response.error,incomplete_details:O.response.incomplete_details,service_tier:O.response.service_tier}}}))}else ix(O)?(re.push(O.annotation),O.annotation.type==="url_citation"?te.enqueue({type:"source",sourceType:"url",id:(jn=(qt=($n=D.config).generateId)==null?void 0:qt.call($n))!=null?jn:rn(),url:O.annotation.url,title:O.annotation.title}):O.annotation.type==="file_citation"?te.enqueue({type:"source",sourceType:"document",id:(sn=(rr=(Ft=D.config).generateId)==null?void 0:rr.call(Ft))!=null?sn:rn(),mediaType:"text/plain",title:O.annotation.filename,filename:O.annotation.filename,providerMetadata:{[m]:{type:O.annotation.type,fileId:O.annotation.file_id,index:O.annotation.index}}}):O.annotation.type==="container_file_citation"?te.enqueue({type:"source",sourceType:"document",id:(Ln=(or=(At=D.config).generateId)==null?void 0:or.call(At))!=null?Ln:rn(),mediaType:"text/plain",title:O.annotation.filename,filename:O.annotation.filename,providerMetadata:{[m]:{type:O.annotation.type,fileId:O.annotation.file_id,containerId:O.annotation.container_id}}}):O.annotation.type==="file_path"&&te.enqueue({type:"source",sourceType:"document",id:(ge=(gt=(wr=D.config).generateId)==null?void 0:gt.call(wr))!=null?ge:rn(),mediaType:"application/octet-stream",title:O.annotation.file_id,filename:O.annotation.file_id,providerMetadata:{[m]:{type:O.annotation.type,fileId:O.annotation.file_id,index:O.annotation.index}}})):Wa(O)&&(G=!0,P={unified:"error",raw:"error"},te.enqueue({type:"error",error:O}))},flush(fe){const te={[m]:{responseId:$,...ee.length>0?{logprobs:ee}:{},...W!==void 0?{serviceTier:W}:{},...z!==void 0?{reasoningContext:z}:{}}};fe.enqueue({type:"finish",finishReason:P,usage:za(M),providerMetadata:te})}})),request:{body:r},response:{headers:g}}}};function H2(t){return t.type==="response.output_text.delta"}function W2(t){const r=q2(t);return r!=null&&Array.isArray(r.choices)&&typeof r.type!="string"}function G2({value:t,cause:r,url:i,requestBodyValues:c,responseHeaders:d}){return new Kt({message:"Received a Chat Completions stream while using the OpenAI Responses API. The default OpenAI provider model uses the Responses API. If your custom baseURL targets a Chat Completions-compatible endpoint, use openai.chat('model-id') or createOpenAI(...).chat('model-id') instead. You can also use @ai-sdk/openai-compatible for OpenAI-compatible providers.",url:i,requestBodyValues:c,responseHeaders:d,responseBody:JSON.stringify(t),cause:r,data:t,isRetryable:!1})}function q2(t){return typeof t=="object"&&t!=null?t:void 0}function X2(t){return t.type==="response.output_item.done"}function Y2(t){return t.type==="response.completed"||t.type==="response.incomplete"}function ja(t){return t.type==="response.failed"}function K2(t){return t.type==="response.created"}function J2(t){return t.type==="response.function_call_arguments.delta"}function Q2(t){return t.type==="response.custom_tool_call_input.delta"}function ex(t){return t.type==="response.image_generation_call.partial_image"}function tx(t){return t.type==="response.code_interpreter_call_code.delta"}function nx(t){return t.type==="response.code_interpreter_call_code.done"}function rx(t){return t.type==="response.apply_patch_call_operation_diff.delta"}function ox(t){return t.type==="response.apply_patch_call_operation_diff.done"}function Ha(t){return t.type==="response.output_item.added"}function ix(t){return t.type==="response.output_text.annotation.added"}function Wa(t){return t.type==="error"}function sx(t){return!(t.type==="response.created"||t.type==="response.failed"||t.type==="error"||t.type==="unknown_chunk")}function Ga(t){var r;if(t==null)return{};switch(t.type){case"search":return{action:{type:"search",query:(r=t.query)!=null?r:void 0,...t.queries!=null&&{queries:t.queries}},...t.sources!=null&&{sources:t.sources}};case"open_page":return{action:{type:"openPage",url:t.url}};case"find_in_page":return{action:{type:"findInPage",url:t.url,pattern:t.pattern}}}}function fr(t){return JSON.stringify(t).slice(1,-1)}var ax=Fe(()=>Le(N({instructions:w().nullish(),speed:j().min(.25).max(4).default(1).nullish()}))),lx=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({text:t,voice:r="alloy",outputFormat:i="mp3",speed:c,instructions:d,language:f,providerOptions:m}){const x=[],v=await An({provider:"openai",providerOptions:m,schema:ax}),g={model:this.modelId,input:t,voice:r,response_format:"mp3",speed:c,instructions:d};if(i&&(["mp3","opus","aac","flac","wav","pcm"].includes(i)?g.response_format=i:x.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${i}. Using mp3 instead.`})),v){const E={};for(const A in E){const D=E[A];D!==void 0&&(g[A]=D)}}return f&&x.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${f}" was ignored.`}),{requestBody:g,warnings:x}}async doGenerate(t){var r,i,c;const d=(c=(i=(r=this.config._internal)==null?void 0:r.currentDate)==null?void 0:i.call(r))!=null?c:new Date,{requestBody:f,warnings:m}=await this.getArgs(t),{value:x,responseHeaders:v,rawValue:g}=await Zn({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:bn(this.config.headers(),t.headers),body:f,failedResponseHandler:En,successfulResponseHandler:yg(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:x,warnings:m,request:{body:JSON.stringify(f)},response:{timestamp:d,modelId:this.modelId,headers:v,body:g}}}},cx=Fe(()=>Le(N({text:w(),language:w().nullish(),duration:j().nullish(),words:ue(N({word:w(),start:j(),end:j()})).nullish(),segments:ue(N({id:j(),seek:j(),start:j(),end:j(),text:w(),tokens:ue(j()),temperature:j(),avg_logprob:j(),compression_ratio:j(),no_speech_prob:j()})).nullish()}))),ux=Fe(()=>Le(N({include:ue(w()).optional(),language:w().optional(),prompt:w().optional(),temperature:j().min(0).max(1).default(0).optional(),timestampGranularities:ue(Ae(["word","segment"])).default(["segment"]).optional()}))),qa={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},dx=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({audio:t,mediaType:r,providerOptions:i}){const c=[],d=await An({provider:"openai",providerOptions:i,schema:ux}),f=new FormData,m=t instanceof Uint8Array?new Blob([t]):new Blob([qi(t)]);f.append("model",this.modelId);const x=gm(r);if(f.append("file",new File([m],"audio",{type:r}),`audio.${x}`),d){const v={include:d.include,language:d.language,prompt:d.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:d.temperature,timestamp_granularities:d.timestampGranularities};for(const[g,E]of Object.entries(v))if(E!=null)if(Array.isArray(E))for(const A of E)f.append(`${g}[]`,String(A));else f.append(g,String(E))}return{formData:f,warnings:c}}async doGenerate(t){var r,i,c,d,f,m,x,v;const g=(c=(i=(r=this.config._internal)==null?void 0:r.currentDate)==null?void 0:i.call(r))!=null?c:new Date,{formData:E,warnings:A}=await this.getArgs(t),{value:D,responseHeaders:T,rawValue:S}=await xu({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:bn(this.config.headers(),t.headers),formData:E,failedResponseHandler:En,successfulResponseHandler:mr(cx),abortSignal:t.abortSignal,fetch:this.config.fetch}),P=D.language!=null&&D.language in qa?qa[D.language]:void 0;return{text:D.text,segments:(x=(m=(d=D.segments)==null?void 0:d.map(M=>({text:M.text,startSecond:M.start,endSecond:M.end})))!=null?m:(f=D.words)==null?void 0:f.map(M=>({text:M.word,startSecond:M.start,endSecond:M.end})))!=null?x:[],language:P,durationInSeconds:(v=D.duration)!=null?v:void 0,warnings:A,response:{timestamp:g,modelId:this.modelId,headers:T,body:S}}}},fx="3.0.86";function Ou(t={}){var r,i;const c=(r=wg(mm({settingValue:t.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?r:"https://api.openai.com/v1",d=(i=t.name)!=null?i:"openai",f=()=>cu({Authorization:`Bearer ${pm({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers},`ai-sdk/openai/${fx}`),m=P=>new Ng(P,{provider:`${d}.chat`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),x=P=>new Dg(P,{provider:`${d}.completion`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),v=P=>new Fg(P,{provider:`${d}.embedding`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),g=P=>new jg(P,{provider:`${d}.image`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),E=P=>new dx(P,{provider:`${d}.transcription`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),A=P=>new lx(P,{provider:`${d}.speech`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),D=P=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return T(P)},T=P=>new j2(P,{provider:`${d}.responses`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch,fileIdPrefixes:["file-"]}),S=function(P){return D(P)};return S.specificationVersion="v3",S.languageModel=D,S.chat=m,S.completion=x,S.responses=T,S.embedding=v,S.embeddingModel=v,S.textEmbedding=v,S.textEmbeddingModel=v,S.image=g,S.imageModel=g,S.transcription=E,S.transcriptionModel=E,S.speech=A,S.speechModel=A,S.tools=R2,S}Ou();const hx={deepseek:{prompt:{strategy:"append",id:"5ed1b9071c15d1ed59b5827ea5dcabd4",params:{customComponents:[{name:"选择用户组件",description:"选择用户组件,用于选择用户,支持模糊搜索",component:"TinyUser",schema:{properties:[{property:"modelValue",label:"用户绑定工号",required:!0,description:"用户的工号,双向绑定值",type:"string"},{property:"valueField",label:"值字段",required:!0,description:"用户工号值的绑定字段",type:"string"}]}}],customExamples:[{name:"选择用户示例",schema:{componentName:"Page",state:{reviewer:""},children:[{componentName:"h3",props:{},children:"输入用户名搜索工号并选择用户"},{componentName:"TinyUser",props:{modelValue:{type:"JSExpression",model:!0,value:"this.state.reviewer"},valueField:"uid"}},{componentName:"TinyButton",props:{text:"提交"}}]}}],customActions:[{name:"continueChat",description:"继续对话, 用于表单的提交按钮等",parameters:{type:"object",properties:{message:{type:"string",description:"对话消息,可以是按钮文本等,也可以是其他内容"}}}}]}}}};class px{constructor(r={}){this.option=r}async traverse(r){const i=_.ref();return this.option.debug&&console.log("【stream-debug】 响应对象体:",i),(async()=>{let d,f,m,x,v;for await(const g of r.fullStream)switch(this.option.debug&&console.log("【stream-debug】 "+(new Date().getTime()/1e3).toString().slice(-6)+g.type,g),g.type){case"start":d=_.reactive({running:!0,steps:[]}),i.value=d,this.option.onStart?.(d);break;case"start-step":f=_.reactive({running:!0,contents:[],request:g.request}),d.steps.push(f),this.option.onStep?.(f);break;case"reasoning-start":m=_.reactive({type:"reasoning",id:g.id,running:!0,text:""}),f.contents.push(m),this.option.onReasoning?.(m);break;case"reasoning-delta":m.text+=g.text;break;case"reasoning-end":m.running=!1;break;case"text-start":x=_.reactive({type:"text",id:g.id,running:!0,text:""}),f.contents.push(x),this.option.onText?.(x);break;case"text-delta":x.text+=g.text;break;case"text-end":x.running=!1;break;case"tool-input-start":v=_.reactive({type:"tool",running:!0,id:g.id,toolCallId:g.id,title:"",toolName:g.toolName,dynamic:g.dynamic,inputStr:"",input:{},output:{}}),f.contents.push(v),this.option.onTool?.(v);break;case"tool-input-delta":v.inputStr+=g.delta;break;case"tool-input-end":break;case"tool-call":v.input=g.input;break;case"tool-result":v.output=g.output,v.running=!1;break;case"tool-error":v.error=g.error,v.running=!1;break;case"finish-step":f.running=!1,f.finishReason=g.finishReason,f.usage=g.usage;break;case"finish":d.running=!1,d.finishReason=g.finishReason,d.totalUsage=g.totalUsage,this.option.onFinish?.();break;case"source":case"file":break;case"error":d&&(d.running=!1,d.error=g.error,d.finishReason="error"),this.option.onFinish?.();break;case"abort":d&&(d.running=!1,d.error={message:g.reason},d.finishReason="other"),this.option.onFinish?.();break}})(),i}}function mx(t){const r=[];let i=0;for(;i<t.length;){const c="```schemaJson",d=t.indexOf(c,i),f=c.length;if(d===-1){const g=t.slice(i).trim();g&&r.push({type:"markdown",content:g});break}const m=t.slice(i,d).trim();m&&r.push({type:"markdown",content:m});const x=t.indexOf("```",d+f);let v;x===-1?(v=t.slice(d+f).trim(),i=t.length):(v=t.slice(d+f,x).trim(),i=x+3),r.push({type:"schema-card",content:v})}return r}class gx{staticPrompt="";skillMetaPrompt="";tempPrompt="";getSystemPrompt(){return`
56
56
  当前时间:${new Date().toLocaleDateString()}。
57
57
  ${this.staticPrompt}
58
58
  ${this.skillMetaPrompt}
59
59
  ${this.tempPrompt}
60
- `}setStatic(r){this.staticPrompt=r}setSkillMeta(r){this.skillMetaPrompt=r}setTemp(r){this.tempPrompt=r}appendTemp(r){this.tempPrompt+=r}}const xi={model:"deepseek-ai/DeepSeek-V3",maxSteps:30,extraTools:{}},Xa={apiKey:"sk-trial",baseURL:"https://agent.opentiny.design/api/v1/ai/",genuiUrl:"https://agent.opentiny.design/api/v1/ai/prompt",providerType:"deepseek"};function gx(t,r){if(!r&&!t)return;if(!t)return r;if(!r)return t;const i={...r};for(const[c,d]of Object.entries(t))d&&typeof d=="object"&&!Array.isArray(d)?i[c]={...i[c]||{},...d}:i[c]=d;return i}class xx extends Kn.BaseModelProvider{transport;agent;promptManager;llmConfig={...xi,...Xa};isGenuiEnabled;debugStream=!1;emit;constructor(r,i,c,d){super(r);let f;c&&"llm"in c?f={...xi,...c}:f={...xi,...Xa,...c||{}},this.llmConfig=f;const x={llmConfig:f.llm?{llm:f.llm}:{...f}};this.agent=new Jn.AgentModelProvider(x),this.promptManager=new mx,this.promptManager.setStatic(i),this.emit=d}updateLLMConfig({model:r,baseURL:i,genuiUrl:c,apiKey:d,providerType:f,useReActMode:m,llm:x,providerOptions:v,headers:g}){if(x)this.agent.llm=x,this.llmConfig.model=r,this.llmConfig.useReActMode=m||!1,this.agent.useReActMode=m||!1;else if(f&&i&&d){const E=this.isGenuiEnabled?.value&&c||i;this.llmConfig.model=r,this.llmConfig.apiKey=d,this.llmConfig.baseURL=i,this.llmConfig.providerType=f,this.llmConfig.useReActMode=m||!1,this.agent.useReActMode=m||!1;let A;if(f==="deepseek")A=kc;else if(f==="openai")A=Ou;else if(typeof f=="function")A=f;else throw new Error(`Unsupported providerType: ${f}`);this.agent.llm=A({apiKey:d,baseURL:E,...g?{headers:g}:{}})}this.llmConfig.providerOptions=v,this.llmConfig.headers=g}cleanGetSkillContentToolResult(r){const i=r[r.length-1];if(i.role==="tool"&&i.content.length>0){const c=i.content[i.content.length-1];c.type==="tool-result"&&c.toolName==="get_skill_content"&&(c.output.value.content="查询到技能内容已添加到系统提示词中。")}}cleanupOldSnapshotsInMessages(r){if(!r||r.length===0)return r;const c=this.agent.useReActMode===!0?"user":"tool",d=r[r.length-1];if(!d||d.role!==c||!this.isSnapshotContent(d.content))return r;const f=[...r];for(let m=f.length-2;m>=0;m--){const x=f[m];x.role===c&&this.isSnapshotContent(x.content)&&this.replaceSnapshotWithPlaceholder(x)}return f}removeSnapshotData(r){if(!r)return r;const i=["无障碍树快照:","无障碍树快照:","快照内容:","快照内容:","页面无障碍树快照:","页面无障碍树快照:","操作后的页面快照:","操作后的页面快照:"];let c=-1;for(const f of i){const m=r.indexOf(f);if(m!==-1){c=m;break}}if(c!==-1){const f=r.substring(0,c).trim();return f?`${f} 📸 [历史快照已清理]`:"📸 历史快照已清理"}const d=["已成功获取页面无障碍树快照","takeSnapshot","snapshotId_counter"];for(const f of d)if(r.startsWith(f))return"📸 历史快照已清理";return r}replaceSnapshotWithPlaceholder(r){if(Array.isArray(r.content)){const i=r.content[0];if(i?.output?.value?.content){const c=i.output.value.content;Array.isArray(c)&&(i.output.value.content=c.map(d=>d.type==="image"||d.type==="image_url"?null:d.type==="text"&&d.text&&this.isSnapshotContent(d.text)?{type:"text",text:this.removeSnapshotData(d.text)}:d).filter(d=>d!==null)),i.output.value.screenshot&&delete i.output.value.screenshot}else r.content=r.content.filter(c=>c.type!=="image"&&c.type!=="image_url")}else typeof r.content=="string"&&this.isSnapshotContent(r.content)&&(r.content=this.removeSnapshotData(r.content))}isSnapshotContent(r){if(!r)return!1;const i=["无障碍树快照","takeSnapshot","snapshotId_counter","UID 格式","快照 ID","操作后的页面快照","已成功获取页面无障碍树快照","快照内容:"];if(typeof r=="string")return i.some(c=>r.includes(c));if(Array.isArray(r))for(const c of r){const d=c?.output?.value?.content?.[0]?.text;if(d&&i.some(f=>d.includes(f))||c.type==="text"&&c.text&&i.some(f=>c.text.includes(f))||c.type==="image"||c.type==="image_url")return!0}return!1}async chatStream(r,i){let c=r.messages[r.messages.length-1];if(!c)return;const d={model:this.llmConfig.model,system:this.promptManager.getSystemPrompt(),abortSignal:r.options?.signal,toolChoice:"auto",tools:this.llmConfig.extraTools||{},maxSteps:this.llmConfig.maxSteps,providerOptions:gx(this.llmConfig.providerOptions,fx),prepareStep:({messages:T})=>{this.cleanGetSkillContentToolResult(T);const S=this.cleanupOldSnapshotsInMessages(T),P=Object.keys(this.llmConfig.extraTools||{});Object.values(this.agent.mcpTools||{}).forEach(ee=>{P.push(...Object.keys(ee||{}))});const M=Array.from(new Set(P)).filter(ee=>!this.agent.ignoreToolnames.includes(ee));return{system:this.promptManager.getSystemPrompt(),messages:S,activeTools:M}},onStepFinish:T=>{if(T.finishReason==="tool-calls"&&T.content.length>0){const S=T.content[T.content.length-1];if(S.toolName==="get_skill_content"&&S.type==="tool-result"){const P=S.output.content;this.promptManager.appendTemp(P)}}},onFinish:async()=>{await this.agent.closeAll(),this.promptManager.setTemp(""),this.emit?.("chat-stream-finish")}},f={role:"user",content:c.content},x=[...(T=>T.map(S=>({role:S.role,content:S.content})))(this.agent.responseMessages),f];d.messages=x;const v=await this.agent.chatStream(d),g=new qp,A=await new hx({debug:this.debugStream,onFinish:()=>{_.nextTick(()=>{g.resolve(),i.onDone()})}}).traverse(v),D={role:"assistant",content:"",uiContent:[]};return _.watch(A,T=>{if(!T)i.onData(D);else{const P=T.steps.map(M=>M.contents).flat().map(M=>{if(M.type==="text")return px(M.text);if(M.type==="reasoning")return{type:"collapsible-text",title:"思考过程",content:M.text,thinkId:M.id};if(M.type==="tool")return{type:"tool",id:M.id,name:M.toolName,content:JSON.stringify({input:M.inputStr,output:M.output}),status:M.error?"failed":M.running?"running":"success"}});if(T?.error){const M={type:"markdown",content:`**错误**:${T.error.responseBody||T.error.message||"未知错误"}`};P.push(M)}(T.steps.length>=1||T?.error)&&i.onData({...D,uiContent:P.flat(),usage:T.totalUsage||null})}},{deep:!0}),g.promise}chat(r){throw new Error("Method not implemented.")}}const yx=({systemPrompt:t,llmConfig:r,emit:i})=>{const c=new xx({provider:"custom"},t,r,i),d=new Kn.AIClient({providerImplementation:c,provider:"custom"}),{messageManager:f,createConversation:m,getCurrentConversation:x,switchConversation:v,deleteConversation:g,updateTitle:E,state:A}=Kn.useConversation({client:d,autoSave:!0,events:{onLoaded(){},onReceiveData(Z,B,L){L(),B.value[B.value.length-1].role==="assistant"&&B.value.pop(),i("before-ai-render",Z),B.value.push(Z)}}}),{messageState:D,inputMessage:T,sendMessage:S,abortRequest:P,messages:M,addMessage:ee,send:$}=f,F=_.ref(),re=async(Z,B,L)=>{if(L){const{shouldBlock:z}=await L(Z);if(z)return!1}T.value=Z;const W=x();if(W&&W.title==="新会话"&&E(W.id,T.value.slice(0,15)),B&&B.length>0){const z=[{type:"text",text:T.value},...B],we=[];T.value&&we.push({type:"text",content:T.value});for(const me of B)me.type==="image"&&me.image&&we.push({type:"image",content:me.image});const G={role:"user",content:z,uiContent:we};M.value.push(G),T.value="",$()}else{const z={role:"user",content:T.value,uiContent:[{type:"text",content:T.value}]};M.value.push(z),T.value="",$()}return!0};return _.onMounted(()=>{F.value?.focus()}),_.onUnmounted(()=>{c.agent.closeAll()}),{agent:c.agent,customAgentProvider:c,client:d,messageManager:f,addMessage:ee,send:$,conversationState:A,messages:M,messageState:D,inputMessage:T,sendMessage:S,abortRequest:P,senderRef:F,handleSendMessage:re,createConversation:m,switchConversation:v,deleteConversation:g,getCurrentConversation:x}};function wx(){}const Pn=Object.assign,ts=typeof window<"u",Zo=t=>t!==null&&typeof t=="object",tr=t=>t!=null,Pi=t=>typeof t=="function",_x=t=>Zo(t)&&Pi(t.then)&&Pi(t.catch),ku=t=>typeof t=="number"||/^\d+(\.\d+)?$/.test(t),vx=()=>ts?/ios|iphone|ipad|ipod/.test(navigator.userAgent.toLowerCase()):!1;function Ya(t,r){const i=r.split(".");let c=t;return i.forEach(d=>{var f;c=Zo(c)&&(f=c[d])!=null?f:""}),c}function Cx(t,r,i){return r.reduce((c,d)=>(c[d]=t[d],c),{})}const Po=null,un=[Number,String],pr={type:Boolean,default:!0},bx=t=>({type:Number,default:t}),dn=t=>({type:String,default:t});var ns=typeof window<"u";function Ru(t){let r;_.onMounted(()=>{t(),_.nextTick(()=>{r=!0})}),_.onActivated(()=>{r&&t()})}function Mu(t,r,i={}){if(!ns)return;const{target:c=window,passive:d=!1,capture:f=!1}=i;let m=!1,x;const v=A=>{if(m)return;const D=_.unref(A);D&&!x&&(D.addEventListener(t,r,{capture:f,passive:d}),x=!0)},g=A=>{if(m)return;const D=_.unref(A);D&&x&&(D.removeEventListener(t,r,f),x=!1)};_.onUnmounted(()=>g(c)),_.onDeactivated(()=>g(c)),Ru(()=>v(c));let E;return _.isRef(c)&&(E=_.watch(c,(A,D)=>{g(D),v(A)})),()=>{E?.(),g(c),m=!0}}var Eo,yi;function Ax(){if(!Eo&&(Eo=_.ref(0),yi=_.ref(0),ns)){const t=()=>{Eo.value=window.innerWidth,yi.value=window.innerHeight};t(),window.addEventListener("resize",t,{passive:!0}),window.addEventListener("orientationchange",t,{passive:!0})}return{width:Eo,height:yi}}var Ex=/scroll|auto|overlay/i,Ix=ns?window:void 0;function Sx(t){return t.tagName!=="HTML"&&t.tagName!=="BODY"&&t.nodeType===1}function Ka(t,r=Ix){let i=t;for(;i&&i!==r&&Sx(i);){const{overflowY:c}=window.getComputedStyle(i);if(Ex.test(c))return i;i=i.parentNode}return r}vx();const Tx=t=>t.stopPropagation();function Du(t,r){(typeof t.cancelable!="boolean"||t.cancelable)&&t.preventDefault(),Tx(t)}Ax();function vn(t){if(tr(t))return ku(t)?`${t}px`:String(t)}function Nx(t){if(tr(t)){if(Array.isArray(t))return{width:vn(t[0]),height:vn(t[1])};const r=vn(t);return{width:r,height:r}}}function Ox(t){const r={};return t!==void 0&&(r.zIndex=+t),r}const kx=/-(\w)/g,Pu=t=>t.replace(kx,(r,i)=>i.toUpperCase()),Rx=t=>t.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,""),{hasOwnProperty:Mx}=Object.prototype;function Dx(t,r,i){const c=r[i];tr(c)&&(!Mx.call(t,i)||!Zo(c)?t[i]=c:t[i]=Bu(Object(t[i]),c))}function Bu(t,r){return Object.keys(r).forEach(i=>{Dx(t,r,i)}),t}var Px={name:"姓名",tel:"电话",save:"保存",clear:"清空",undo:"撤销",cancel:"取消",confirm:"确认",delete:"删除",loading:"加载中...",noCoupon:"暂无优惠券",nameEmpty:"请填写姓名",addContact:"添加联系人",telInvalid:"请填写正确的电话",vanCalendar:{end:"结束",start:"开始",title:"日期选择",weekdays:["日","一","二","三","四","五","六"],monthTitle:(t,r)=>`${t}年${r}月`,rangePrompt:t=>`最多选择 ${t} 天`},vanCascader:{select:"请选择"},vanPagination:{prev:"上一页",next:"下一页"},vanPullRefresh:{pulling:"下拉即可刷新...",loosing:"释放即可刷新..."},vanSubmitBar:{label:"合计:"},vanCoupon:{unlimited:"无门槛",discount:t=>`${t}折`,condition:t=>`满${t}元可用`},vanCouponCell:{title:"优惠券",count:t=>`${t}张可用`},vanCouponList:{exchange:"兑换",close:"不使用",enable:"可用",disabled:"不可用",placeholder:"输入优惠码"},vanAddressEdit:{area:"地区",areaEmpty:"请选择地区",addressEmpty:"请填写详细地址",addressDetail:"详细地址",defaultAddress:"设为默认收货地址"},vanAddressList:{add:"新增地址"}};const Ja=_.ref("zh-CN"),Qa=_.reactive({"zh-CN":Px}),Bx={messages(){return Qa[Ja.value]},use(t,r){Ja.value=t,this.add({[t]:r})},add(t={}){Bu(Qa,t)}};var Lx=Bx;function Fx(t){const r=Pu(t)+".";return(i,...c)=>{const d=Lx.messages(),f=Ya(d,r+i)||Ya(d,i);return Pi(f)?f(...c):f}}function Bi(t,r){return r?typeof r=="string"?` ${t}--${r}`:Array.isArray(r)?r.reduce((i,c)=>i+Bi(t,c),""):Object.keys(r).reduce((i,c)=>i+(r[c]?Bi(t,c):""),""):""}function Ux(t){return(r,i)=>(r&&typeof r!="string"&&(i=r,r=""),r=r?`${t}__${r}`:t,`${r}${Bi(r,i)}`)}function yr(t){const r=`van-${t}`;return[r,Ux(r),Fx(r)]}const zx="van-haptics-feedback",el=5;function Vx(t,{args:r=[],done:i,canceled:c,error:d}){if(t){const f=t.apply(null,r);_x(f)?f.then(m=>{m?i():c&&c()}).catch(d||wx):f?i():c&&c()}else i()}function lo(t){return t.install=r=>{const{name:i}=t;i&&(r.component(i,t),r.component(Pu(`-${i}`),t))},t}const Zx=Symbol();function Lu(t){const r=_.getCurrentInstance();r&&Pn(r.proxy,t)}const[$x,tl]=yr("badge"),jx={dot:Boolean,max:un,tag:dn("div"),color:String,offset:Array,content:un,showZero:pr,position:dn("top-right")};var Hx=_.defineComponent({name:$x,props:jx,setup(t,{slots:r}){const i=()=>{if(r.content)return!0;const{content:x,showZero:v}=t;return tr(x)&&x!==""&&(v||x!==0&&x!=="0")},c=()=>{const{dot:x,max:v,content:g}=t;if(!x&&i())return r.content?r.content():tr(v)&&ku(g)&&+g>+v?`${v}+`:g},d=x=>x.startsWith("-")?x.replace("-",""):`-${x}`,f=_.computed(()=>{const x={background:t.color};if(t.offset){const[v,g]=t.offset,{position:E}=t,[A,D]=E.split("-");r.default?(typeof g=="number"?x[A]=vn(A==="top"?g:-g):x[A]=A==="top"?vn(g):d(g),typeof v=="number"?x[D]=vn(D==="left"?v:-v):x[D]=D==="left"?vn(v):d(v)):(x.marginTop=vn(g),x.marginLeft=vn(v))}return x}),m=()=>{if(i()||t.dot)return _.createVNode("div",{class:tl([t.position,{dot:t.dot,fixed:!!r.default}]),style:f.value},[c()])};return()=>{if(r.default){const{tag:x}=t;return _.createVNode(x,{class:tl("wrapper")},{default:()=>[r.default(),m()]})}return m()}}});const Wx=lo(Hx);let Fu=2e3;const Gx=()=>++Fu,qx=t=>{Fu=t},[Uu,Xx]=yr("config-provider"),zu=Symbol(Uu),Yx={tag:dn("div"),theme:dn("light"),zIndex:Number,themeVars:Object,themeVarsDark:Object,themeVarsLight:Object,themeVarsScope:dn("local"),iconPrefix:String};function Kx(t){return t.replace(/([a-zA-Z])(\d)/g,"$1-$2")}function Jx(t){const r={};return Object.keys(t).forEach(i=>{const c=Kx(Rx(i));r[`--van-${c}`]=t[i]}),r}function Io(t={},r={}){Object.keys(t).forEach(i=>{t[i]!==r[i]&&document.documentElement.style.setProperty(i,t[i])}),Object.keys(r).forEach(i=>{t[i]||document.documentElement.style.removeProperty(i)})}_.defineComponent({name:Uu,props:Yx,setup(t,{slots:r}){const i=_.computed(()=>Jx(Pn({},t.themeVars,t.theme==="dark"?t.themeVarsDark:t.themeVarsLight)));if(ts){const c=()=>{document.documentElement.classList.add(`van-theme-${t.theme}`)},d=(f=t.theme)=>{document.documentElement.classList.remove(`van-theme-${f}`)};_.watch(()=>t.theme,(f,m)=>{m&&d(m),c()},{immediate:!0}),_.onActivated(c),_.onDeactivated(d),_.onBeforeUnmount(d),_.watch(i,(f,m)=>{t.themeVarsScope==="global"&&Io(f,m)}),_.watch(()=>t.themeVarsScope,(f,m)=>{m==="global"&&Io({},i.value),f==="global"&&Io(i.value,{})}),t.themeVarsScope==="global"&&Io(i.value,{})}return _.provide(zu,t),_.watchEffect(()=>{t.zIndex!==void 0&&qx(t.zIndex)}),()=>_.createVNode(t.tag,{class:Xx(),style:t.themeVarsScope==="local"?i.value:void 0},{default:()=>{var c;return[(c=r.default)==null?void 0:c.call(r)]}})}});const[Qx,nl]=yr("icon"),ey=t=>t?.includes("/"),ty={dot:Boolean,tag:dn("i"),name:String,size:un,badge:un,color:String,badgeProps:Object,classPrefix:String};var ny=_.defineComponent({name:Qx,props:ty,setup(t,{slots:r}){const i=_.inject(zu,null),c=_.computed(()=>t.classPrefix||i?.iconPrefix||nl());return()=>{const{tag:d,dot:f,name:m,size:x,badge:v,color:g}=t,E=ey(m);return _.createVNode(Wx,_.mergeProps({dot:f,tag:d,class:[c.value,E?"":`${c.value}-${m}`],style:{color:g,fontSize:vn(x)},content:v},t.badgeProps),{default:()=>{var A;return[(A=r.default)==null?void 0:A.call(r),E&&_.createVNode("img",{class:nl("image"),src:m},null)]}})}}});const rs=lo(ny),[ry,Kr]=yr("loading"),oy=Array(12).fill(null).map((t,r)=>_.createVNode("i",{class:Kr("line",String(r+1))},null)),iy=_.createVNode("svg",{class:Kr("circular"),viewBox:"25 25 50 50"},[_.createVNode("circle",{cx:"50",cy:"50",r:"20",fill:"none"},null)]),sy={size:un,type:dn("circular"),color:String,vertical:Boolean,textSize:un,textColor:String};var ay=_.defineComponent({name:ry,props:sy,setup(t,{slots:r}){const i=_.computed(()=>Pn({color:t.color},Nx(t.size))),c=()=>{const f=t.type==="spinner"?oy:iy;return _.createVNode("span",{class:Kr("spinner",t.type),style:i.value},[r.icon?r.icon():f])},d=()=>{var f;if(r.default)return _.createVNode("span",{class:Kr("text"),style:{fontSize:vn(t.textSize),color:(f=t.textColor)!=null?f:t.color}},[r.default()])};return()=>{const{type:f,vertical:m}=t;return _.createVNode("div",{class:Kr([f,{vertical:m}]),"aria-live":"polite","aria-busy":!0},[c(),d()])}}});const ly=lo(ay),cy={show:Boolean,zIndex:un,overlay:pr,duration:un,teleport:[String,Object],lockScroll:pr,lazyRender:pr,beforeClose:Function,overlayProps:Object,overlayStyle:Object,overlayClass:Po,transitionAppear:Boolean,closeOnClickOverlay:pr};function uy(t,r){return t>r?"horizontal":r>t?"vertical":""}function dy(){const t=_.ref(0),r=_.ref(0),i=_.ref(0),c=_.ref(0),d=_.ref(0),f=_.ref(0),m=_.ref(""),x=_.ref(!0),v=()=>m.value==="vertical",g=()=>m.value==="horizontal",E=()=>{i.value=0,c.value=0,d.value=0,f.value=0,m.value="",x.value=!0};return{move:(T=>{const S=T.touches[0];i.value=(S.clientX<0?0:S.clientX)-t.value,c.value=S.clientY-r.value,d.value=Math.abs(i.value),f.value=Math.abs(c.value);const P=10;(!m.value||d.value<P&&f.value<P)&&(m.value=uy(d.value,f.value)),x.value&&(d.value>el||f.value>el)&&(x.value=!1)}),start:(T=>{E(),t.value=T.touches[0].clientX,r.value=T.touches[0].clientY}),reset:E,startX:t,startY:r,deltaX:i,deltaY:c,offsetX:d,offsetY:f,direction:m,isVertical:v,isHorizontal:g,isTap:x}}let Hr=0;const rl="van-overflow-hidden";function fy(t,r){const i=dy(),c="01",d="10",f=E=>{i.move(E);const A=i.deltaY.value>0?d:c;let D=Ka(E.target,t.value);for(;D.scrollHeight<=D.offsetHeight&&D!==t.value&&D.parentElement;)D=Ka(D.parentElement,t.value);const{scrollHeight:T,offsetHeight:S,scrollTop:P}=D;let M="11";P===0?M=S>=T?"00":"01":P+S>=T&&(M="10"),M!=="11"&&i.isVertical()&&!(parseInt(M,2)&parseInt(A,2))&&Du(E)},m=()=>{document.addEventListener("touchstart",i.start),document.addEventListener("touchmove",f,{passive:!1}),Hr||document.body.classList.add(rl),Hr++},x=()=>{Hr&&(document.removeEventListener("touchstart",i.start),document.removeEventListener("touchmove",f),Hr--,Hr||document.body.classList.remove(rl))},v=()=>r()&&m(),g=()=>r()&&x();Ru(v),_.onDeactivated(g),_.onBeforeUnmount(g),_.watch(r,E=>{E?m():x()})}function Vu(t){const r=_.ref(!1);return _.watch(t,i=>{i&&(r.value=i)},{immediate:!0}),i=>()=>r.value?i():null}const ol=()=>{var t;const{scopeId:r}=((t=_.getCurrentInstance())==null?void 0:t.vnode)||{};return r?{[r]:""}:null},[hy,py]=yr("overlay"),my={show:Boolean,zIndex:un,duration:un,className:Po,lockScroll:pr,lazyRender:pr,customStyle:Object,teleport:[String,Object]};var gy=_.defineComponent({name:hy,inheritAttrs:!1,props:my,setup(t,{attrs:r,slots:i}){const c=_.ref(),d=Vu(()=>t.show||!t.lazyRender),f=x=>{t.lockScroll&&Du(x)},m=d(()=>{var x;const v=Pn(Ox(t.zIndex),t.customStyle);return tr(t.duration)&&(v.animationDuration=`${t.duration}s`),_.withDirectives(_.createVNode("div",_.mergeProps({ref:c,style:v,class:[py(),t.className]},r),[(x=i.default)==null?void 0:x.call(i)]),[[_.vShow,t.show]])});return Mu("touchmove",f,{target:c}),()=>{const x=_.createVNode(_.Transition,{name:"van-fade",appear:!0},{default:m});return t.teleport?_.createVNode(_.Teleport,{to:t.teleport},{default:()=>[x]}):x}}});const xy=lo(gy),yy=Pn({},cy,{round:Boolean,position:dn("center"),closeIcon:dn("cross"),closeable:Boolean,transition:String,iconPrefix:String,closeOnPopstate:Boolean,closeIconPosition:dn("top-right"),destroyOnClose:Boolean,safeAreaInsetTop:Boolean,safeAreaInsetBottom:Boolean}),[wy,il]=yr("popup");var _y=_.defineComponent({name:wy,inheritAttrs:!1,props:yy,emits:["open","close","opened","closed","keydown","update:show","clickOverlay","clickCloseIcon"],setup(t,{emit:r,attrs:i,slots:c}){let d,f;const m=_.ref(),x=_.ref(),v=Vu(()=>t.show||!t.lazyRender),g=_.computed(()=>{const B={zIndex:m.value};if(tr(t.duration)){const L=t.position==="center"?"animationDuration":"transitionDuration";B[L]=`${t.duration}s`}return B}),E=()=>{d||(d=!0,m.value=t.zIndex!==void 0?+t.zIndex:Gx(),r("open"))},A=()=>{d&&Vx(t.beforeClose,{done(){d=!1,r("close"),r("update:show",!1)}})},D=B=>{r("clickOverlay",B),t.closeOnClickOverlay&&A()},T=()=>{if(t.overlay){const B=Pn({show:t.show,class:t.overlayClass,zIndex:m.value,duration:t.duration,customStyle:t.overlayStyle,role:t.closeOnClickOverlay?"button":void 0,tabindex:t.closeOnClickOverlay?0:void 0},t.overlayProps);return _.createVNode(xy,_.mergeProps(B,ol(),{onClick:D}),{default:c["overlay-content"]})}},S=B=>{r("clickCloseIcon",B),A()},P=()=>{if(t.closeable)return _.createVNode(rs,{role:"button",tabindex:0,name:t.closeIcon,class:[il("close-icon",t.closeIconPosition),zx],classPrefix:t.iconPrefix,onClick:S},null)};let M;const ee=()=>{M&&clearTimeout(M),M=setTimeout(()=>{r("opened")})},$=()=>r("closed"),F=B=>r("keydown",B),re=v(()=>{var B;const{destroyOnClose:L,round:W,position:z,safeAreaInsetTop:we,safeAreaInsetBottom:G,show:me}=t;if(!(!me&&L))return _.withDirectives(_.createVNode("div",_.mergeProps({ref:x,style:g.value,role:"dialog",tabindex:0,class:[il({round:W,[z]:z}),{"van-safe-area-top":we,"van-safe-area-bottom":G}],onKeydown:F},i,ol()),[(B=c.default)==null?void 0:B.call(c),P()]),[[_.vShow,me]])}),Z=()=>{const{position:B,transition:L,transitionAppear:W}=t,z=B==="center"?"van-fade":`van-popup-slide-${B}`;return _.createVNode(_.Transition,{name:L||z,appear:W,onAfterEnter:ee,onAfterLeave:$},{default:re})};return _.watch(()=>t.show,B=>{B&&!d&&(E(),i.tabindex===0&&_.nextTick(()=>{var L;(L=x.value)==null||L.focus()})),!B&&d&&(d=!1,r("close"))}),Lu({popupRef:x}),fy(x,()=>t.show&&t.lockScroll),Mu("popstate",()=>{t.closeOnPopstate&&(A(),f=!1)}),_.onMounted(()=>{t.show&&E()}),_.onActivated(()=>{f&&(r("update:show",!0),f=!1)}),_.onDeactivated(()=>{t.show&&t.teleport&&(A(),f=!0)}),_.provide(Zx,()=>t.show),()=>t.teleport?_.createVNode(_.Teleport,{to:t.teleport},{default:()=>[T(),Z()]}):_.createVNode(_.Fragment,null,[T(),Z()])}});const vy=lo(_y);let Wr=0;function Cy(t){t?(Wr||document.body.classList.add("van-toast--unclickable"),Wr++):Wr&&(Wr--,Wr||document.body.classList.remove("van-toast--unclickable"))}const[by,Or]=yr("toast"),Ay=["show","overlay","teleport","transition","overlayClass","overlayStyle","closeOnClickOverlay","zIndex"],Ey={icon:String,show:Boolean,type:dn("text"),overlay:Boolean,message:un,iconSize:un,duration:bx(2e3),position:dn("middle"),teleport:[String,Object],wordBreak:String,className:Po,iconPrefix:String,transition:dn("van-fade"),loadingType:String,forbidClick:Boolean,overlayClass:Po,overlayStyle:Object,closeOnClick:Boolean,closeOnClickOverlay:Boolean,zIndex:un};var Iy=_.defineComponent({name:by,props:Ey,emits:["update:show"],setup(t,{emit:r,slots:i}){let c,d=!1;const f=()=>{const A=t.show&&t.forbidClick;d!==A&&(d=A,Cy(d))},m=A=>r("update:show",A),x=()=>{t.closeOnClick&&m(!1)},v=()=>clearTimeout(c),g=()=>{const{icon:A,type:D,iconSize:T,iconPrefix:S,loadingType:P}=t;if(A||D==="success"||D==="fail")return _.createVNode(rs,{name:A||D,size:T,class:Or("icon"),classPrefix:S},null);if(D==="loading")return _.createVNode(ly,{class:Or("loading"),size:T,type:P},null)},E=()=>{const{type:A,message:D}=t;if(i.message)return _.createVNode("div",{class:Or("text")},[i.message()]);if(tr(D)&&D!=="")return A==="html"?_.createVNode("div",{key:0,class:Or("text"),innerHTML:String(D)},null):_.createVNode("div",{class:Or("text")},[D])};return _.watch(()=>[t.show,t.forbidClick],f),_.watch(()=>[t.show,t.type,t.message,t.duration],()=>{v(),t.show&&t.duration>0&&(c=setTimeout(()=>{m(!1)},t.duration))}),_.onMounted(f),_.onUnmounted(f),()=>_.createVNode(vy,_.mergeProps({class:[Or([t.position,t.wordBreak==="normal"?"break-normal":t.wordBreak,{[t.type]:!t.icon}]),t.className],lockScroll:!1,onClick:x,onClosed:v,"onUpdate:show":m},Cx(t,Ay)),{default:()=>[g(),E()]})}});function Sy(){const t=_.reactive({show:!1}),r=d=>{t.show=d},i=d=>{Pn(t,d,{transitionAppear:!0}),r(!0)},c=()=>r(!1);return Lu({open:i,close:c,toggle:r}),{open:i,close:c,state:t,toggle:r}}function Ty(t){const r=_.createApp(t),i=document.createElement("div");return document.body.appendChild(i),{instance:r.mount(i),unmount(){r.unmount(),document.body.removeChild(i)}}}const Ny={icon:"",type:"text",message:"",className:"",overlay:!1,onClose:void 0,onOpened:void 0,duration:2e3,teleport:"body",iconSize:void 0,iconPrefix:void 0,position:"middle",transition:"van-fade",forbidClick:!1,loadingType:void 0,overlayClass:"",overlayStyle:void 0,closeOnClick:!1,closeOnClickOverlay:!1};let So=[],Oy=!1,sl=Pn({},Ny);const ky=new Map;function Zu(t){return Zo(t)?t:{message:t}}function Ry(){const{instance:t}=Ty({setup(){const r=_.ref(""),{open:i,state:c,close:d,toggle:f}=Sy(),m=()=>{},x=()=>{const v={onClosed:m,"onUpdate:show":f};return _.createVNode(Iy,_.mergeProps(c,v),null)};return _.watch(r,v=>{c.message=v}),_.getCurrentInstance().render=x,{open:i,close:d,message:r}}});return t}function My(){if(!So.length||Oy){const t=Ry();So.push(t)}return So[So.length-1]}function it(t={}){if(!ts)return{};const r=My(),i=Zu(t);return r.open(Pn({},sl,ky.get(i.type||sl.type),i)),r}const Dy=t=>r=>it(Pn({type:t},Zu(r))),$u=Dy("loading"),Py=t=>{try{const r=JSON.parse(t),i=[];if(!r.mcpServers||typeof r.mcpServers!="object")throw new Error("JSON 格式错误:缺少 mcpServers 字段");for(const[c,d]of Object.entries(r.mcpServers)){const f=By(d);f&&i.push({name:c,config:f})}return i}catch(r){throw new Error(`JSON 解析失败: ${r instanceof Error?r.message:"未知错误"}`)}},By=t=>{if(!t||typeof t!="object"||!t.url)return null;const{type:r,url:i,sessionId:c,headers:d}=t;return r==="streamableHttp"||r==="sse"?{type:r,url:i,headers:d,useAISdkClient:!0}:{type:"streamableHttp",url:i,headers:d,useAISdkClient:!0}},Ly=(t,r,i)=>{const c=async(f,m,x,v,g)=>{if(await t.insertMcpServer(f,m)){const A=t.mcpTools[f];if(A){const T={id:`plugin-${f.replace("mcp-server-","")}`,name:x,icon:g||i,description:v||(typeof m=="object"&&"url"in m?m.url:""),enabled:!0,expanded:!0,tools:Object.keys(A).map(S=>({id:S,name:S,description:A[S].description,enabled:!0})),originMcpConfig:_.markRaw(m)};return r.value.push(T),!0}else return await t.removeMcpServer(f),!1}else return!1};return{handleCustomAdd:async(f,m)=>{$u("添加工具中...");try{if(f==="code"){if(typeof m!="string"){it("添加工具失败:code 类型需要 JSON 字符串格式");return}const $=Py(m);if($.length===0){it("添加工具失败:JSON 配置格式不正确或未找到有效的服务器配置");return}let F=0,re=0;for(const{name:Z,config:B}of $){const L=`mcp-server-${Z}`;await c(L,B,Z)?F++:re++}await t.closeAll(),re===0?it(`成功添加 ${F} 个工具`):F>0?it(`成功添加 ${F} 个工具,${re} 个失败`):it("添加工具失败:所有服务器都无法连接");return}if(typeof m=="string"){it("添加工具失败:数据格式不正确");return}const{description:x,headers:v,name:g,thumbnail:E,type:A,url:D}=m;if(!g||!D||!A){it("添加工具失败:缺少必要参数(名称、URL或类型)");return}const S=`mcp-server-${`custom-${g}-${Date.now()}`}`;let P;if(typeof v=="string"&&v.trim())try{P=JSON.parse(v)}catch($){console.warn("Failed to parse headers JSON:",$)}else typeof v=="object"&&(P=v);await c(S,{type:A,url:D,headers:P,useAISdkClient:!0},g,x,E)?(await t.closeAll(),it("添加工具完成")):it("重复添加工具或无法获取工具列表")}catch(x){console.error("handleCustomAdd error:",x),it(`添加工具失败:${x instanceof Error?x.message:"未知错误"}`)}}}};function Fy(t,r,i){const c=_.ref([]),d=_.ref([]),f=_.ref(!1),m=Z=>t.mcpServers[Z]?.type==="local",x=(Z,B)=>{B?t.ignoreToolnames=t.ignoreToolnames.filter(L=>L!==Z):t.ignoreToolnames.includes(Z)||t.ignoreToolnames.push(Z)},v=(Z,B)=>{r.value||(r.value={});const L={...r.value};Z===null?Object.keys(L).forEach(W=>{L[W]=B}):L[Z]=B,r.value=L},g=Z=>{const B=d.value.find(L=>L.id===Z);B&&(B.addState="idle")},E=Z=>{const B=t.mcpTools[Z];if(!B)return[];const L=m(Z),W=r.value||{};return Object.keys(B).map(z=>{const we=Object.prototype.hasOwnProperty.call(W,z),G=L&&we?W[z]:!0;return x(z,G),{id:z,name:z,description:B[z].description,enabled:G}})},A=()=>{c.value.forEach(B=>{const L=new Map(B.tools.map(z=>[z.id,z.enabled])),W=E(B.id).map(z=>{const we=L.has(z.id)?!!L.get(z.id):z.enabled;return x(z.id,we),{...z,enabled:we}});B.tools=W});const Z=new Set(c.value.flatMap(B=>B.tools.map(L=>L.id)));t.ignoreToolnames=t.ignoreToolnames.filter(B=>Z.has(B))},D=async Z=>{const B=Z.pluginId;if(!await t.insertMcpServer(B,Z.mcpServer))return!1;if(!t.mcpTools[B])return await t.removeMcpServer(B),!1;const z=E(B);if(z.length===0&&Z.mcpServer?.type!=="builtin")return await t.removeMcpServer(B),!1;const we=c.value.find(me=>me.id===Z.pluginId);if(we)return we.tools=z,we.originMcpConfig=_.markRaw(Z.mcpServer),!0;const G={id:Z.pluginId,name:Z.name,icon:Z.icon||i,description:Z.description,enabled:!0,expanded:!1,tools:z,originMcpConfig:_.markRaw(Z.mcpServer)};return c.value.push(G),!0};return{installedPlugins:c,marketPlugins:d,pluginVisible:f,loadMcpServerToPlugin:async(Z,B)=>{let L=B.name,W=B.description;if(!L||!W){if("type"in B&&B.type==="local")L=L||"本地工具",W=W||"本地工具列表";else if("type"in B&&B.type==="builtin")L=L||"浏览器内置工具",W=W||"通过 document.modelContext 暴露的浏览器原生 MCP 工具";else if("url"in B)try{const z=new URL(B.url);L=L||z.origin,W=W||z.searchParams.get("sessionId")||("sessionId"in B?B.sessionId:"")||""}catch(z){console.error("[usePlugin] Failed to parse MCP server URL:",B.url,z),L=L||"未知插件",W=W||""}}await D({pluginId:Z,name:L||"",description:W||"",mcpServer:B})},togglePlugin:(Z,B)=>{const L=m(Z.id);Z.tools.forEach(W=>{W.enabled=B,x(W.id,B),L&&v(W.id,B)})},toggleTool:(Z,B,L)=>{const W=m(Z.id);Z.tools.forEach(z=>{z.id===B&&(z.enabled=L)}),x(B,L),W&&v(B,L)},deletePlugin:async Z=>{const B=c.value.find(W=>W.id===Z.id);if(!B)return;c.value=c.value.filter(W=>W.id!==B.id),g(B.id);const L=Z.id;await t.removeMcpServer(L)},addPluginCore:D,addPluginFromMarket:async Z=>{Z.addState="loading";const B={type:Z.type,url:Z.url,headers:Z.headers,useAISdkClient:!0},L=await D({pluginId:Z.id,name:Z.name,description:Z.description||"",icon:Z.icon,mcpServer:B});Z.addState=L?"added":"idle"},addPluginFromScan:async(Z,B)=>{const L={type:"streamableHttp",url:`${B}mcp?sessionId=${Z}`};let W="未知插件";try{W=new URL(`${B}mcp?sessionId=${Z}`).origin}catch(z){console.error("[usePlugin] Failed to parse scan URL:",z)}return await D({pluginId:`plugin-${Z}`,name:W,description:Z,mcpServer:L})},handleClientDisconnected:async Z=>{const B=Z,L=c.value.find(W=>W.id===B);return await t.removeMcpServer(Z),L?(c.value=c.value.filter(W=>W.id!==B),g(B),L):null},searchPlugin:(Z,B)=>Z.trim()===""||B.name.toLowerCase().includes(Z.toLowerCase()),syncInstalledPluginTools:A}}function Uy(t){const{onToolCatalogChanged:r}=t,i=typeof window<"u"&&window!==window.top,c=D=>D===window||i&&D===window.parent;let d=!1,f=!1,m=!1;const x=async()=>{if(!(!r||d)){if(f){m=!0;return}f=!0;try{do{m=!1;try{await r()}catch(D){console.warn("[useRouteBasedTools] refresh tool catalog failed:",D)}}while(m&&!d)}finally{f=!1}}},v=D=>{!c(D.source)||D.data?.type!==Jn.MSG_TOOL_REGISTERED&&D.data?.type!==Jn.MSG_TOOL_UNREGISTERED||x()};let g=!1;const E=()=>{g||(d=!1,g=!0,window.addEventListener("message",v),i&&window.parent&&window.parent.postMessage({type:Jn.MSG_REMOTER_READY},"*"))},A=()=>{g&&(d=!0,m=!1,g=!1,window.removeEventListener("message",v))};_.onMounted(()=>{E()}),_.onUnmounted(()=>{A()})}function zy(t){const{skillsRef:r,customAgentProvider:i}=t,c=_.shallowRef([]);_.watchEffect(async()=>{const x=r?.value;c.value=x?await Jn.getSkillOverviews(x):[]});const d=_.computed(()=>{const x=c.value;return x.length>0?Jn.formatSkillsForSystemPrompt(x):""}),f=_.computed(()=>{const x=r?.value;return x?Jn.createSkillTools(x):{}});return _.watchEffect(()=>{if(i.promptManager.setSkillMeta(d.value),i.llmConfig){const x=i.llmConfig.extraTools??{};i.llmConfig.extraTools={...x,...f.value}}}),{processSkillMentions:async()=>({shouldBlock:!1,skillItems:[]}),skillPromptPart:d,skillTools:f,skillOverviews:c}}const Vy=["title"],Zy=_.defineComponent({__name:"TokenUsage",props:{usage:{type:Object,default:""}},setup(t){const r=t,i=_.computed(()=>r.usage.totalTokens===0||typeof r.usage.totalTokens>"u"),c=_.computed(()=>{const{inputTokens:f=0,outputTokens:m=0,totalTokens:x=0,inputTokenDetails:v,outputTokenDetails:g}=r.usage,E=v?.cacheReadTokens||0,A=g?.reasoningTokens||0;return{cachedInputTokens:[E/x*100+"%",E],inputTokens:[(f-E)/x*100+"%",f],reasoningTokens:[A/x*100+"%",A],outputTokens:[(m-A)/x*100+"%",m]}}),d=_.computed(()=>{const{inputTokens:f=0,outputTokens:m=0,totalTokens:x=0,inputTokenDetails:v,outputTokenDetails:g}=r.usage,E=v?.cacheReadTokens||0,A=g?.reasoningTokens||0;return[`inputTokens: ${f}`,`outputTokens: ${m}`,`totalTokens: ${x}`,`cachedInputTokens: ${E}`,`reasoningTokens: ${A}`].join(`
61
- `)});return(f,m)=>i.value?_.createCommentVNode("",!0):(_.openBlock(),_.createElementBlock("div",{key:0,class:"token-usage-wrap",title:d.value},[(_.openBlock(!0),_.createElementBlock(_.Fragment,null,_.renderList(c.value,(x,v)=>(_.openBlock(),_.createElementBlock("div",{key:v,class:_.normalizeClass(v),style:_.normalizeStyle({width:x[0]})},null,6))),128))],8,Vy))}}),nr=(t,r)=>{const i=t.__vccOpts||t;for(const[c,d]of r)i[c]=d;return i},$y=nr(Zy,[["__scopeId","data-v-000098b4"]]),jy={width:"100.000000",height:"100.000000",viewBox:"0 0 100 100",fill:"none",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink"};function Hy(t,r){return _.openBlock(),_.createElementBlock("svg",jy,[...r[0]||(r[0]=[_.createStaticVNode('<desc> Created with Pixso. </desc><defs><radialGradient gradientTransform="translate(32.4474 65.1156) rotate(128.932) scale(22.991 20.6919)" cx="0.000000" cy="0.000000" r="1.000000" id="paint_radial_9_3090_0" gradientUnits="userSpaceOnUse"><stop stop-color="#5ADDF8"></stop><stop stop-color="#AEBFFF"></stop><stop offset="0.329153" stop-color="#1476FF"></stop><stop offset="0.667785" stop-color="#655AF8"></stop><stop offset="0.868255" stop-color="#948CFF"></stop><stop offset="1.000000" stop-color="#D25AF8"></stop><stop offset="1.000000" stop-color="#5A8BF8"></stop></radialGradient><linearGradient x1="30.999874" y1="85.000229" x2="30.499891" y2="70.500214" id="paint_linear_9_3092_0" gradientUnits="userSpaceOnUse"><stop stop-color="#000000" stop-opacity="0.000000"></stop><stop offset="1.000000" stop-color="#000000"></stop></linearGradient><radialGradient gradientTransform="translate(26.9999 24.7118) rotate(38.3655) scale(77.7996 109.496)" cx="0.000000" cy="0.000000" r="1.000000" id="paint_radial_9_3094_0" gradientUnits="userSpaceOnUse"><stop stop-color="#5ADDF8"></stop><stop stop-color="#AEBFFF"></stop><stop offset="0.329153" stop-color="#1476FF"></stop><stop offset="0.667785" stop-color="#655AF8"></stop><stop offset="0.868255" stop-color="#948CFF"></stop><stop offset="1.000000" stop-color="#D25AF8"></stop><stop offset="1.000000" stop-color="#5A8BF8"></stop></radialGradient></defs><rect id="NEXT-LOGO-无背景渐变-右" width="100.000000" height="99.999939" transform="matrix(-1 0 0 1 100 0)" fill="#FFFFFF" fill-opacity="0"></rect>',3),_.createElementVNode("mask",{id:"mask9_3088","mask-type":"alpha",maskUnits:"userSpaceOnUse",x:"0.000061",y:"0.000061",width:"99.999939",height:"99.999939"},[_.createElementVNode("rect",{id:"画板 1773",width:"99.999962",height:"99.999947",transform:"matrix(-1 0 0 1 100 6.10352e-05)",fill:"#000000","fill-opacity":"1.000000"})],-1),_.createStaticVNode('<g mask="url(#mask9_3088)"><path id="矢量 1" d="M35.93 81.01L36 63L18 63.07L32.48 82.23C33.61 83.71 35.93 82.9 35.93 81.01Z" fill="url(#paint_radial_9_3090_0)" fill-opacity="1.000000" fill-rule="evenodd"></path><g opacity="0.100000" style="mix-blend-mode:normal;"><path id="矢量 1" d="M35.93 81.01L36 63L18 63.07L32.48 82.23C33.61 83.71 35.93 82.9 35.93 81.01Z" fill="url(#paint_linear_9_3092_0)" fill-opacity="1.000000" fill-rule="evenodd"></path></g><rect id="矩形 5" x="12.000000" y="19.000183" rx="26.999992" width="75.999977" height="53.999985" fill="url(#paint_radial_9_3094_0)" fill-opacity="1.000000"></rect><rect id="矩形 5" rx="26.499992" width="74.999977" height="52.999985" transform="matrix(-1 0 0 1 87.5 19.5002)" fill="#000000" fill-opacity="0"></rect><rect id="矩形 5" rx="26.499992" width="74.999977" height="52.999985" transform="matrix(-1 0 0 1 87.5 19.5002)" stroke="#000000" stroke-opacity="0" stroke-width="1.000000"></rect><path id="path" d="M45.39 59.06C44.22 60.05 42.9 60.66 41.43 60.89C39.95 61.12 38.57 61.04 37.28 60.65C36 60.26 34.04 58.58 34.04 58.58C34.04 58.58 29.02 54.73 29.02 45.61C29.02 36.5 33.5 32.5 33.5 32.5C33.5 32.5 34.72 31.31 36.5 31C38.29 30.68 39.43 30.98 40.66 31.33C50.89 34.23 62.38 34.33 72.58 31.33C73.81 30.98 74.91 30.93 75.89 31.17C76.87 31.42 77.71 31.89 78.42 32.59C81.65 35.81 82.87 41.06 83 45.61C83.12 50.09 81.97 55.24 78.94 58.54C78.04 59.52 76.98 60.22 75.78 60.63C74.58 61.04 73.32 61.12 71.99 60.89C70.66 60.66 69.48 60.05 68.46 59.06C68.01 58.62 67.39 58.07 66.57 57.4C65.76 56.73 64.83 56.08 63.79 55.44C62.75 54.8 61.62 54.25 60.39 53.8C59.16 53.35 57.91 53.13 56.62 53.13C55.36 53.13 54.16 53.36 53 53.83C51.85 54.29 50.79 54.84 49.82 55.48C48.86 56.12 48 56.78 47.26 57.45C46.51 58.11 45.89 58.65 45.39 59.06Z" fill="#FFFFFF" fill-opacity="1.000000" fill-rule="nonzero"></path><rect id="矩形 841" rx="2.000000" width="3.999999" height="11.999996" transform="matrix(-0.999983 0.00577157 0.00577157 0.999983 76.1109 38.0356)" fill="#1476FF" fill-opacity="1.000000"></rect><path id="合并" d="M42.96 38C43.77 37.97 44.55 38.42 44.92 39.19L48.73 47.11C49.22 48.13 48.79 49.34 47.75 49.81C46.72 50.28 45.48 49.83 44.99 48.8L42.96 44.59L40.94 48.81C40.45 49.83 39.21 50.28 38.18 49.81C37.14 49.34 36.7 48.13 37.2 47.11L41 39.19C41.37 38.42 42.16 37.98 42.96 38Z" fill="#1476FF" fill-opacity="1.000000" fill-rule="evenodd"></path></g>',1)])])}const ju={render:Hy};function Wy(t){const{messages:r,messageState:i,inputMessage:c,handleSendMessage:d}=t,f=_.h(ju,{style:{width:"48px",height:"48px"}}),m=_.ref({}),x=_.computed(()=>Kn.GeneratingStatus.includes(i.status)),v=_.computed(()=>r.value.findLastIndex(T=>T.role==="assistant")),g=T=>T===void 0?"复制":m.value[T]?"复制成功":"复制",E=async T=>{const P=r.value[T].uiContent.map(M=>M.content).join(`
62
- `);try{await navigator.clipboard.writeText(P),T!==void 0&&(m.value[T]=!0,setTimeout(()=>{m.value[T]=!1},3e3))}catch(M){console.error("复制失败:",M),it("复制失败,请重试")}},A=async T=>{const S=r.value.findLastIndex((M,ee)=>M.role==="user"&&ee<=T);if(S===-1){console.warn("未找到可重新生成的用户消息"),it("无法重新生成消息");return}const P=r.value[S];if(r.value=r.value.slice(0,S),Array.isArray(P.content)){const ee=P.content.find(F=>F.type==="text")?.text||"",$=P.content.filter(F=>F.type!=="text");c.value=ee,await d(ee,$.length>0?$:void 0)}else c.value=P.content,await d(P.content)},D={assistant:{type:"markdown",placement:"start",avatar:t.props.roleAvatar.assistant,maxWidth:"80%",customContentField:"uiContent",slots:{footer:({index:T})=>{const S=v.value===T;return x.value&&S?"":_.h("div",{class:["assistant-actions",{"latest-assistant":S,"historical-assistant":!S}],style:{display:"flex",justifyContent:"flex-start",alignItems:"center",gap:"4px"}},[_.h(Vt.IconButton,{icon:Mr.IconRefresh,size:24,onClick:()=>A(T)}),_.h(Id,{effect:"light",content:g(T),placement:"right",visibleArrow:!1},()=>_.h(Vt.IconButton,{icon:Mr.IconCopy,size:24,onClick:()=>E(T)})),r.value[T].usage?_.h($y,{usage:r.value[T].usage}):null])}}},user:{placement:"end",avatar:t.props.roleAvatar.user,maxWidth:"80%",customContentField:"uiContent"}};return{welcomeIcon:f,roles:D,copyingStates:m,isProcessing:x,latestAssistantMessageIndex:v,copyTooltipContent:g,copyMessageToClipboard:E,regenerateMessage:A}}function Gy(t){const{createConversation:r,switchConversation:i,deleteConversation:c,getCurrentConversation:d,abortRequest:f,conversationState:m,customAgentProvider:x}=t,v=_.ref(!1),g=()=>{_.nextTick(()=>{const S=document.querySelector("div.tr-bubble-list");S&&S.scrollTo({top:S.scrollHeight,behavior:"smooth"})})};return{showHistory:v,handleCreateConversation:()=>{f();const S=[];x.agent.responseMessages=S,r();const P=d();P.aiSdkMessages=S},handleHistorySelect:S=>{f(),i(S.id);const P=d();x.agent.responseMessages=P.aiSdkMessages,v.value=!1,g()},handleHistoryUpdateTitle:(S,P)=>{P.title=S},handleHistoryDelete:(S,P)=>{if(S.id==="delete"){if(m.currentId===P.id){it("不允许删除当前会话");return}c(P.id)}},scrollToBottom:g}}function qy(t){const{sessionId:r,agentRoot:i,mode:c,qrCodeUrl:d,remoteUrl:f,menuItems:m,AILogoUrl:x,show:v,addPluginFromScan:g,inputMessage:E}=t;let A=null,D=!1;const T=async $=>{if($u("添加工具中..."),$){const F=await g($,i.value);it(F?"添加工具完成":"重复添加工具或添加失败")}else it("添加工具失败")},S=async $=>{if(/^\/[A-Za-z0-9-]{6,}$/.test($)){try{const F=await fetch(`${i.value}client?sessionId=${$.slice(1)}`);if(!F.ok)throw new Error(`HTTP ${F.status}`);const Z=(await F.json())?.data?.sessionId;Z?await T(Z):it("添加工具失败,请检查识别码是否正确"),E.value=""}catch(F){console.error("识别码处理失败:",F),it("添加工具失败,请检查识别码是否正确"),E.value=""}return!0}return!1},P=()=>{const $=F=>{A&&(A.destroy(),A=null),A=Jn.createRemoter({sessionId:F||void 0,qrCodeUrl:d,remoteUrl:f,menuItems:m?.value,logoUrl:x,onShowAIChat:()=>v.value=!0}),v.value&&A.hide()};_.watch(r,F=>{if(c!=="remoter")return;const re=!!F;A?!D&&re&&($(F),D=!0):($(F),D=re)},{immediate:!0}),m&&_.watch(m,()=>{c==="remoter"&&A&&$(r.value)},{deep:!0}),_.watch(v,F=>{A&&(F?A.hide():A.show())},{immediate:!0})},M=()=>{_.watch(r,$=>{$&&T($)})};return{handleScanSuccess:T,handleSessionIdInput:S,initialize:()=>{r.value&&T(r.value),c==="remoter"&&P(),M()},initializeRemoter:P,watchSessionIdChanges:M}}function Xy(t){return new Promise((r,i)=>{const c=new FileReader;c.onload=()=>r(c.result),c.onerror=i,c.readAsDataURL(t)})}function Yy(t){return t.type.startsWith("image/")}function Ky(t,r){const i=r*1024*1024;return t.size<=i}async function Jy(t){if(t.length===0)return[];const r=[];for(const i of t)if(i.rawFile)try{const c=await Xy(i.rawFile);Yy(i.rawFile)&&r.push({type:"image",image:c})}catch(c){console.error("文件转换失败:",c),it({type:"fail",message:"文件处理失败"})}return r}function Qy(t={}){const r=_.ref([]),i=async d=>{if(!d||d.length===0)return;c();const f=_.unref(t.maxFileSize)||10,m=_.unref(t.supportedTypes)||["image/"];for(const x of d){if(!m.some(g=>x.type.startsWith(g))){it({type:"fail",message:`不支持的文件类型: ${x.type}`});continue}if(!Ky(x,f)){it({type:"fail",message:`文件大小超过 ${f}MB 限制`});continue}r.value.push({rawFile:x,url:URL.createObjectURL(x)})}},c=()=>{r.value.forEach(d=>{d.url&&URL.revokeObjectURL(d.url)}),r.value=[]};return{attachments:r,handleFilesSelected:i,clearAttachments:c}}function ew(t){const{selectedModel:r,selectedModelId:i}=t,c=_.computed(()=>r.value?.multimodal?.supportImages??!1),d=_.computed(()=>r.value?.multimodal?.maxFileSize||10),f=_.computed(()=>r.value?.multimodal?.supportedMimeTypes||["image/"]),{attachments:m,handleFilesSelected:x,clearAttachments:v}=Qy({maxFileSize:d,supportedTypes:f});return _.watch(i,()=>{if(m.value.length>0&&r.value){const T=r.value.multimodal?.maxFileSize||10,S=r.value.multimodal?.supportedMimeTypes||["image/"];m.value.filter(M=>{if(!M.rawFile||!S.some(F=>M.rawFile.type.startsWith(F)))return!0;const $=T*1024*1024;return M.rawFile.size>$}).length>0&&(v(),it("切换模型后,之前选择的附件已清空"))}}),{hasMultimodalSupport:c,attachments:m,onFilesSelected:T=>{x(T)},checkCanSendAttachments:()=>m.value.length>0&&!c.value?(it("当前模型不支持附件,请先移除附件或切换支持多模态的模型"),!1):!0,processAttachments:async()=>m.value.length===0?[]:await Jy(m.value),cleanupAttachments:()=>{m.value.length>0&&v()},clearAttachments:v}}var Ce;(function(t){t[t.QR_CODE=0]="QR_CODE",t[t.AZTEC=1]="AZTEC",t[t.CODABAR=2]="CODABAR",t[t.CODE_39=3]="CODE_39",t[t.CODE_93=4]="CODE_93",t[t.CODE_128=5]="CODE_128",t[t.DATA_MATRIX=6]="DATA_MATRIX",t[t.MAXICODE=7]="MAXICODE",t[t.ITF=8]="ITF",t[t.EAN_13=9]="EAN_13",t[t.EAN_8=10]="EAN_8",t[t.PDF_417=11]="PDF_417",t[t.RSS_14=12]="RSS_14",t[t.RSS_EXPANDED=13]="RSS_EXPANDED",t[t.UPC_A=14]="UPC_A",t[t.UPC_E=15]="UPC_E",t[t.UPC_EAN_EXTENSION=16]="UPC_EAN_EXTENSION"})(Ce||(Ce={}));var al=new Map([[Ce.QR_CODE,"QR_CODE"],[Ce.AZTEC,"AZTEC"],[Ce.CODABAR,"CODABAR"],[Ce.CODE_39,"CODE_39"],[Ce.CODE_93,"CODE_93"],[Ce.CODE_128,"CODE_128"],[Ce.DATA_MATRIX,"DATA_MATRIX"],[Ce.MAXICODE,"MAXICODE"],[Ce.ITF,"ITF"],[Ce.EAN_13,"EAN_13"],[Ce.EAN_8,"EAN_8"],[Ce.PDF_417,"PDF_417"],[Ce.RSS_14,"RSS_14"],[Ce.RSS_EXPANDED,"RSS_EXPANDED"],[Ce.UPC_A,"UPC_A"],[Ce.UPC_E,"UPC_E"],[Ce.UPC_EAN_EXTENSION,"UPC_EAN_EXTENSION"]]),ll;(function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.URL=1]="URL"})(ll||(ll={}));function tw(t){return Object.values(Ce).includes(t)}var oo;(function(t){t[t.SCAN_TYPE_CAMERA=0]="SCAN_TYPE_CAMERA",t[t.SCAN_TYPE_FILE=1]="SCAN_TYPE_FILE"})(oo||(oo={}));var nw=(function(){function t(){}return t.GITHUB_PROJECT_URL="https://github.com/mebjas/html5-qrcode",t.SCAN_DEFAULT_FPS=2,t.DEFAULT_DISABLE_FLIP=!1,t.DEFAULT_REMEMBER_LAST_CAMERA_USED=!0,t.DEFAULT_SUPPORTED_SCAN_TYPE=[oo.SCAN_TYPE_CAMERA,oo.SCAN_TYPE_FILE],t})(),Hu=(function(){function t(r,i){this.format=r,this.formatName=i}return t.prototype.toString=function(){return this.formatName},t.create=function(r){if(!al.has(r))throw"".concat(r," not in html5QrcodeSupportedFormatsTextMap");return new t(r,al.get(r))},t})(),cl=(function(){function t(){}return t.createFromText=function(r){var i={text:r};return{decodedText:r,result:i}},t.createFromQrcodeResult=function(r){return{decodedText:r.text,result:r}},t})(),Li;(function(t){t[t.UNKWOWN_ERROR=0]="UNKWOWN_ERROR",t[t.IMPLEMENTATION_ERROR=1]="IMPLEMENTATION_ERROR",t[t.NO_CODE_FOUND_ERROR=2]="NO_CODE_FOUND_ERROR"})(Li||(Li={}));var rw=(function(){function t(){}return t.createFrom=function(r){return{errorMessage:r,type:Li.UNKWOWN_ERROR}},t})(),ow=(function(){function t(r){this.verbose=r}return t.prototype.log=function(r){this.verbose&&console.log(r)},t.prototype.warn=function(r){this.verbose&&console.warn(r)},t.prototype.logError=function(r,i){(this.verbose||i===!0)&&console.error(r)},t.prototype.logErrors=function(r){if(r.length===0)throw"Logger#logError called without arguments";this.verbose&&console.error(r)},t})();function zn(t){return typeof t>"u"||t===null}var Rr=(function(){function t(){}return t.codeParseError=function(r){return"QR code parse error, error = ".concat(r)},t.errorGettingUserMedia=function(r){return"Error getting userMedia, error = ".concat(r)},t.onlyDeviceSupportedError=function(){return"The device doesn't support navigator.mediaDevices , only supported cameraIdOrConfig in this case is deviceId parameter (string)."},t.cameraStreamingNotSupported=function(){return"Camera streaming not supported by the browser."},t.unableToQuerySupportedDevices=function(){return"Unable to query supported devices, unknown error."},t.insecureContextCameraQueryError=function(){return"Camera access is only supported in secure context like https or localhost."},t.scannerPaused=function(){return"Scanner paused"},t})(),Wu=(function(){function t(){}return t.isMediaStreamConstraintsValid=function(r,i){if(typeof r!="object"){var c=typeof r;return i.logError("videoConstraints should be of type object, the "+"object passed is of type ".concat(c,"."),!0),!1}for(var d=["autoGainControl","channelCount","echoCancellation","latency","noiseSuppression","sampleRate","sampleSize","volume"],f=new Set(d),m=Object.keys(r),x=0,v=m;x<v.length;x++){var g=v[x];if(f.has(g))return i.logError("".concat(g," is not supported videoConstaints."),!0),!1}return!0},t})(),To=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function iw(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var qr={exports:{}},sw=qr.exports,ul;function aw(){return ul||(ul=1,(function(t,r){(function(i,c){c(r)})(sw,(function(i){function c(C){return C==null}var d=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(C,e){C.__proto__=e}||function(C,e){for(var n in e)e.hasOwnProperty(n)&&(C[n]=e[n])};function f(C,e){d(C,e);function n(){this.constructor=C}C.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function m(C,e){var n=Object.setPrototypeOf;n?n(C,e):C.__proto__=e}function x(C,e){e===void 0&&(e=C.constructor);var n=Error.captureStackTrace;n&&n(C,e)}var v=(function(C){f(e,C);function e(n){var o=this.constructor,s=C.call(this,n)||this;return Object.defineProperty(s,"name",{value:o.name,enumerable:!1}),m(s,o.prototype),x(s),s}return e})(Error);class g extends v{constructor(e=void 0){super(e),this.message=e}getKind(){return this.constructor.kind}}g.kind="Exception";class E extends g{}E.kind="ArgumentException";class A extends g{}A.kind="IllegalArgumentException";class D{constructor(e){if(this.binarizer=e,e===null)throw new A("Binarizer must be non-null.")}getWidth(){return this.binarizer.getWidth()}getHeight(){return this.binarizer.getHeight()}getBlackRow(e,n){return this.binarizer.getBlackRow(e,n)}getBlackMatrix(){return(this.matrix===null||this.matrix===void 0)&&(this.matrix=this.binarizer.getBlackMatrix()),this.matrix}isCropSupported(){return this.binarizer.getLuminanceSource().isCropSupported()}crop(e,n,o,s){const a=this.binarizer.getLuminanceSource().crop(e,n,o,s);return new D(this.binarizer.createBinarizer(a))}isRotateSupported(){return this.binarizer.getLuminanceSource().isRotateSupported()}rotateCounterClockwise(){const e=this.binarizer.getLuminanceSource().rotateCounterClockwise();return new D(this.binarizer.createBinarizer(e))}rotateCounterClockwise45(){const e=this.binarizer.getLuminanceSource().rotateCounterClockwise45();return new D(this.binarizer.createBinarizer(e))}toString(){try{return this.getBlackMatrix().toString()}catch{return""}}}class T extends g{static getChecksumInstance(){return new T}}T.kind="ChecksumException";class S{constructor(e){this.source=e}getLuminanceSource(){return this.source}getWidth(){return this.source.getWidth()}getHeight(){return this.source.getHeight()}}class P{static arraycopy(e,n,o,s,a){for(;a--;)o[s++]=e[n++]}static currentTimeMillis(){return Date.now()}}class M extends g{}M.kind="IndexOutOfBoundsException";class ee extends M{constructor(e=void 0,n=void 0){super(n),this.index=e,this.message=n}}ee.kind="ArrayIndexOutOfBoundsException";class ${static fill(e,n){for(let o=0,s=e.length;o<s;o++)e[o]=n}static fillWithin(e,n,o,s){$.rangeCheck(e.length,n,o);for(let a=n;a<o;a++)e[a]=s}static rangeCheck(e,n,o){if(n>o)throw new A("fromIndex("+n+") > toIndex("+o+")");if(n<0)throw new ee(n);if(o>e)throw new ee(o)}static asList(...e){return e}static create(e,n,o){return Array.from({length:e}).map(a=>Array.from({length:n}).fill(o))}static createInt32Array(e,n,o){return Array.from({length:e}).map(a=>Int32Array.from({length:n}).fill(o))}static equals(e,n){if(!e||!n||!e.length||!n.length||e.length!==n.length)return!1;for(let o=0,s=e.length;o<s;o++)if(e[o]!==n[o])return!1;return!0}static hashCode(e){if(e===null)return 0;let n=1;for(const o of e)n=31*n+o;return n}static fillUint8Array(e,n){for(let o=0;o!==e.length;o++)e[o]=n}static copyOf(e,n){return e.slice(0,n)}static copyOfUint8Array(e,n){if(e.length<=n){const o=new Uint8Array(n);return o.set(e),o}return e.slice(0,n)}static copyOfRange(e,n,o){const s=o-n,a=new Int32Array(s);return P.arraycopy(e,n,a,0,s),a}static binarySearch(e,n,o){o===void 0&&(o=$.numberComparator);let s=0,a=e.length-1;for(;s<=a;){const l=a+s>>1,u=o(n,e[l]);if(u>0)s=l+1;else if(u<0)a=l-1;else return l}return-s-1}static numberComparator(e,n){return e-n}}class F{static numberOfTrailingZeros(e){let n;if(e===0)return 32;let o=31;return n=e<<16,n!==0&&(o-=16,e=n),n=e<<8,n!==0&&(o-=8,e=n),n=e<<4,n!==0&&(o-=4,e=n),n=e<<2,n!==0&&(o-=2,e=n),o-(e<<1>>>31)}static numberOfLeadingZeros(e){if(e===0)return 32;let n=1;return e>>>16||(n+=16,e<<=16),e>>>24||(n+=8,e<<=8),e>>>28||(n+=4,e<<=4),e>>>30||(n+=2,e<<=2),n-=e>>>31,n}static toHexString(e){return e.toString(16)}static toBinaryString(e){return String(parseInt(String(e),2))}static bitCount(e){return e=e-(e>>>1&1431655765),e=(e&858993459)+(e>>>2&858993459),e=e+(e>>>4)&252645135,e=e+(e>>>8),e=e+(e>>>16),e&63}static truncDivision(e,n){return Math.trunc(e/n)}static parseInt(e,n=void 0){return parseInt(e,n)}}F.MIN_VALUE_32_BITS=-2147483648,F.MAX_VALUE=Number.MAX_SAFE_INTEGER;class re{constructor(e,n){e===void 0?(this.size=0,this.bits=new Int32Array(1)):(this.size=e,n==null?this.bits=re.makeArray(e):this.bits=n)}getSize(){return this.size}getSizeInBytes(){return Math.floor((this.size+7)/8)}ensureCapacity(e){if(e>this.bits.length*32){const n=re.makeArray(e);P.arraycopy(this.bits,0,n,0,this.bits.length),this.bits=n}}get(e){return(this.bits[Math.floor(e/32)]&1<<(e&31))!==0}set(e){this.bits[Math.floor(e/32)]|=1<<(e&31)}flip(e){this.bits[Math.floor(e/32)]^=1<<(e&31)}getNextSet(e){const n=this.size;if(e>=n)return n;const o=this.bits;let s=Math.floor(e/32),a=o[s];a&=~((1<<(e&31))-1);const l=o.length;for(;a===0;){if(++s===l)return n;a=o[s]}const u=s*32+F.numberOfTrailingZeros(a);return u>n?n:u}getNextUnset(e){const n=this.size;if(e>=n)return n;const o=this.bits;let s=Math.floor(e/32),a=~o[s];a&=~((1<<(e&31))-1);const l=o.length;for(;a===0;){if(++s===l)return n;a=~o[s]}const u=s*32+F.numberOfTrailingZeros(a);return u>n?n:u}setBulk(e,n){this.bits[Math.floor(e/32)]=n}setRange(e,n){if(n<e||e<0||n>this.size)throw new A;if(n===e)return;n--;const o=Math.floor(e/32),s=Math.floor(n/32),a=this.bits;for(let l=o;l<=s;l++){const u=l>o?0:e&31,p=(2<<(l<s?31:n&31))-(1<<u);a[l]|=p}}clear(){const e=this.bits.length,n=this.bits;for(let o=0;o<e;o++)n[o]=0}isRange(e,n,o){if(n<e||e<0||n>this.size)throw new A;if(n===e)return!0;n--;const s=Math.floor(e/32),a=Math.floor(n/32),l=this.bits;for(let u=s;u<=a;u++){const h=u>s?0:e&31,y=(2<<(u<a?31:n&31))-(1<<h)&4294967295;if((l[u]&y)!==(o?y:0))return!1}return!0}appendBit(e){this.ensureCapacity(this.size+1),e&&(this.bits[Math.floor(this.size/32)]|=1<<(this.size&31)),this.size++}appendBits(e,n){if(n<0||n>32)throw new A("Num bits must be between 0 and 32");this.ensureCapacity(this.size+n);for(let o=n;o>0;o--)this.appendBit((e>>o-1&1)===1)}appendBitArray(e){const n=e.size;this.ensureCapacity(this.size+n);for(let o=0;o<n;o++)this.appendBit(e.get(o))}xor(e){if(this.size!==e.size)throw new A("Sizes don't match");const n=this.bits;for(let o=0,s=n.length;o<s;o++)n[o]^=e.bits[o]}toBytes(e,n,o,s){for(let a=0;a<s;a++){let l=0;for(let u=0;u<8;u++)this.get(e)&&(l|=1<<7-u),e++;n[o+a]=l}}getBitArray(){return this.bits}reverse(){const e=new Int32Array(this.bits.length),n=Math.floor((this.size-1)/32),o=n+1,s=this.bits;for(let a=0;a<o;a++){let l=s[a];l=l>>1&1431655765|(l&1431655765)<<1,l=l>>2&858993459|(l&858993459)<<2,l=l>>4&252645135|(l&252645135)<<4,l=l>>8&16711935|(l&16711935)<<8,l=l>>16&65535|(l&65535)<<16,e[n-a]=l}if(this.size!==o*32){const a=o*32-this.size;let l=e[0]>>>a;for(let u=1;u<o;u++){const h=e[u];l|=h<<32-a,e[u-1]=l,l=h>>>a}e[o-1]=l}this.bits=e}static makeArray(e){return new Int32Array(Math.floor((e+31)/32))}equals(e){if(!(e instanceof re))return!1;const n=e;return this.size===n.size&&$.equals(this.bits,n.bits)}hashCode(){return 31*this.size+$.hashCode(this.bits)}toString(){let e="";for(let n=0,o=this.size;n<o;n++)(n&7)===0&&(e+=" "),e+=this.get(n)?"X":".";return e}clone(){return new re(this.size,this.bits.slice())}}var Z;(function(C){C[C.OTHER=0]="OTHER",C[C.PURE_BARCODE=1]="PURE_BARCODE",C[C.POSSIBLE_FORMATS=2]="POSSIBLE_FORMATS",C[C.TRY_HARDER=3]="TRY_HARDER",C[C.CHARACTER_SET=4]="CHARACTER_SET",C[C.ALLOWED_LENGTHS=5]="ALLOWED_LENGTHS",C[C.ASSUME_CODE_39_CHECK_DIGIT=6]="ASSUME_CODE_39_CHECK_DIGIT",C[C.ASSUME_GS1=7]="ASSUME_GS1",C[C.RETURN_CODABAR_START_END=8]="RETURN_CODABAR_START_END",C[C.NEED_RESULT_POINT_CALLBACK=9]="NEED_RESULT_POINT_CALLBACK",C[C.ALLOWED_EAN_EXTENSIONS=10]="ALLOWED_EAN_EXTENSIONS"})(Z||(Z={}));var B=Z;class L extends g{static getFormatInstance(){return new L}}L.kind="FormatException";var W;(function(C){C[C.Cp437=0]="Cp437",C[C.ISO8859_1=1]="ISO8859_1",C[C.ISO8859_2=2]="ISO8859_2",C[C.ISO8859_3=3]="ISO8859_3",C[C.ISO8859_4=4]="ISO8859_4",C[C.ISO8859_5=5]="ISO8859_5",C[C.ISO8859_6=6]="ISO8859_6",C[C.ISO8859_7=7]="ISO8859_7",C[C.ISO8859_8=8]="ISO8859_8",C[C.ISO8859_9=9]="ISO8859_9",C[C.ISO8859_10=10]="ISO8859_10",C[C.ISO8859_11=11]="ISO8859_11",C[C.ISO8859_13=12]="ISO8859_13",C[C.ISO8859_14=13]="ISO8859_14",C[C.ISO8859_15=14]="ISO8859_15",C[C.ISO8859_16=15]="ISO8859_16",C[C.SJIS=16]="SJIS",C[C.Cp1250=17]="Cp1250",C[C.Cp1251=18]="Cp1251",C[C.Cp1252=19]="Cp1252",C[C.Cp1256=20]="Cp1256",C[C.UnicodeBigUnmarked=21]="UnicodeBigUnmarked",C[C.UTF8=22]="UTF8",C[C.ASCII=23]="ASCII",C[C.Big5=24]="Big5",C[C.GB18030=25]="GB18030",C[C.EUC_KR=26]="EUC_KR"})(W||(W={}));class z{constructor(e,n,o,...s){this.valueIdentifier=e,this.name=o,typeof n=="number"?this.values=Int32Array.from([n]):this.values=n,this.otherEncodingNames=s,z.VALUE_IDENTIFIER_TO_ECI.set(e,this),z.NAME_TO_ECI.set(o,this);const a=this.values;for(let l=0,u=a.length;l!==u;l++){const h=a[l];z.VALUES_TO_ECI.set(h,this)}for(const l of s)z.NAME_TO_ECI.set(l,this)}getValueIdentifier(){return this.valueIdentifier}getName(){return this.name}getValue(){return this.values[0]}static getCharacterSetECIByValue(e){if(e<0||e>=900)throw new L("incorect value");const n=z.VALUES_TO_ECI.get(e);if(n===void 0)throw new L("incorect value");return n}static getCharacterSetECIByName(e){const n=z.NAME_TO_ECI.get(e);if(n===void 0)throw new L("incorect value");return n}equals(e){if(!(e instanceof z))return!1;const n=e;return this.getName()===n.getName()}}z.VALUE_IDENTIFIER_TO_ECI=new Map,z.VALUES_TO_ECI=new Map,z.NAME_TO_ECI=new Map,z.Cp437=new z(W.Cp437,Int32Array.from([0,2]),"Cp437"),z.ISO8859_1=new z(W.ISO8859_1,Int32Array.from([1,3]),"ISO-8859-1","ISO88591","ISO8859_1"),z.ISO8859_2=new z(W.ISO8859_2,4,"ISO-8859-2","ISO88592","ISO8859_2"),z.ISO8859_3=new z(W.ISO8859_3,5,"ISO-8859-3","ISO88593","ISO8859_3"),z.ISO8859_4=new z(W.ISO8859_4,6,"ISO-8859-4","ISO88594","ISO8859_4"),z.ISO8859_5=new z(W.ISO8859_5,7,"ISO-8859-5","ISO88595","ISO8859_5"),z.ISO8859_6=new z(W.ISO8859_6,8,"ISO-8859-6","ISO88596","ISO8859_6"),z.ISO8859_7=new z(W.ISO8859_7,9,"ISO-8859-7","ISO88597","ISO8859_7"),z.ISO8859_8=new z(W.ISO8859_8,10,"ISO-8859-8","ISO88598","ISO8859_8"),z.ISO8859_9=new z(W.ISO8859_9,11,"ISO-8859-9","ISO88599","ISO8859_9"),z.ISO8859_10=new z(W.ISO8859_10,12,"ISO-8859-10","ISO885910","ISO8859_10"),z.ISO8859_11=new z(W.ISO8859_11,13,"ISO-8859-11","ISO885911","ISO8859_11"),z.ISO8859_13=new z(W.ISO8859_13,15,"ISO-8859-13","ISO885913","ISO8859_13"),z.ISO8859_14=new z(W.ISO8859_14,16,"ISO-8859-14","ISO885914","ISO8859_14"),z.ISO8859_15=new z(W.ISO8859_15,17,"ISO-8859-15","ISO885915","ISO8859_15"),z.ISO8859_16=new z(W.ISO8859_16,18,"ISO-8859-16","ISO885916","ISO8859_16"),z.SJIS=new z(W.SJIS,20,"SJIS","Shift_JIS"),z.Cp1250=new z(W.Cp1250,21,"Cp1250","windows-1250"),z.Cp1251=new z(W.Cp1251,22,"Cp1251","windows-1251"),z.Cp1252=new z(W.Cp1252,23,"Cp1252","windows-1252"),z.Cp1256=new z(W.Cp1256,24,"Cp1256","windows-1256"),z.UnicodeBigUnmarked=new z(W.UnicodeBigUnmarked,25,"UnicodeBigUnmarked","UTF-16BE","UnicodeBig"),z.UTF8=new z(W.UTF8,26,"UTF8","UTF-8"),z.ASCII=new z(W.ASCII,Int32Array.from([27,170]),"ASCII","US-ASCII"),z.Big5=new z(W.Big5,28,"Big5"),z.GB18030=new z(W.GB18030,29,"GB18030","GB2312","EUC_CN","GBK"),z.EUC_KR=new z(W.EUC_KR,30,"EUC_KR","EUC-KR");class we extends g{}we.kind="UnsupportedOperationException";class G{static decode(e,n){const o=this.encodingName(n);return this.customDecoder?this.customDecoder(e,o):typeof TextDecoder>"u"||this.shouldDecodeOnFallback(o)?this.decodeFallback(e,o):new TextDecoder(o).decode(e)}static shouldDecodeOnFallback(e){return!G.isBrowser()&&e==="ISO-8859-1"}static encode(e,n){const o=this.encodingName(n);return this.customEncoder?this.customEncoder(e,o):typeof TextEncoder>"u"?this.encodeFallback(e):new TextEncoder().encode(e)}static isBrowser(){return typeof window<"u"&&{}.toString.call(window)==="[object Window]"}static encodingName(e){return typeof e=="string"?e:e.getName()}static encodingCharacterSet(e){return e instanceof z?e:z.getCharacterSetECIByName(e)}static decodeFallback(e,n){const o=this.encodingCharacterSet(n);if(G.isDecodeFallbackSupported(o)){let s="";for(let a=0,l=e.length;a<l;a++){let u=e[a].toString(16);u.length<2&&(u="0"+u),s+="%"+u}return decodeURIComponent(s)}if(o.equals(z.UnicodeBigUnmarked))return String.fromCharCode.apply(null,new Uint16Array(e.buffer));throw new we(`Encoding ${this.encodingName(n)} not supported by fallback.`)}static isDecodeFallbackSupported(e){return e.equals(z.UTF8)||e.equals(z.ISO8859_1)||e.equals(z.ASCII)}static encodeFallback(e){const o=btoa(unescape(encodeURIComponent(e))).split(""),s=[];for(let a=0;a<o.length;a++)s.push(o[a].charCodeAt(0));return new Uint8Array(s)}}class me{static castAsNonUtf8Char(e,n=null){const o=n?n.getName():this.ISO88591;return G.decode(new Uint8Array([e]),o)}static guessEncoding(e,n){if(n!=null&&n.get(B.CHARACTER_SET)!==void 0)return n.get(B.CHARACTER_SET).toString();const o=e.length;let s=!0,a=!0,l=!0,u=0,h=0,p=0,y=0,b=0,I=0,R=0,U=0,V=0,H=0,Q=0;const he=e.length>3&&e[0]===239&&e[1]===187&&e[2]===191;for(let pe=0;pe<o&&(s||a||l);pe++){const ce=e[pe]&255;l&&(u>0?(ce&128)===0?l=!1:u--:(ce&128)!==0&&((ce&64)===0?l=!1:(u++,(ce&32)===0?h++:(u++,(ce&16)===0?p++:(u++,(ce&8)===0?y++:l=!1))))),s&&(ce>127&&ce<160?s=!1:ce>159&&(ce<192||ce===215||ce===247)&&Q++),a&&(b>0?ce<64||ce===127||ce>252?a=!1:b--:ce===128||ce===160||ce>239?a=!1:ce>160&&ce<224?(I++,U=0,R++,R>V&&(V=R)):ce>127?(b++,R=0,U++,U>H&&(H=U)):(R=0,U=0))}return l&&u>0&&(l=!1),a&&b>0&&(a=!1),l&&(he||h+p+y>0)?me.UTF8:a&&(me.ASSUME_SHIFT_JIS||V>=3||H>=3)?me.SHIFT_JIS:s&&a?V===2&&I===2||Q*10>=o?me.SHIFT_JIS:me.ISO88591:s?me.ISO88591:a?me.SHIFT_JIS:l?me.UTF8:me.PLATFORM_DEFAULT_ENCODING}static format(e,...n){let o=-1;function s(l,u,h,p,y,b){if(l==="%%")return"%";if(n[++o]===void 0)return;l=p?parseInt(p.substr(1)):void 0;let I=y?parseInt(y.substr(1)):void 0,R;switch(b){case"s":R=n[o];break;case"c":R=n[o][0];break;case"f":R=parseFloat(n[o]).toFixed(l);break;case"p":R=parseFloat(n[o]).toPrecision(l);break;case"e":R=parseFloat(n[o]).toExponential(l);break;case"x":R=parseInt(n[o]).toString(I||16);break;case"d":R=parseFloat(parseInt(n[o],I||10).toPrecision(l)).toFixed(0);break}R=typeof R=="object"?JSON.stringify(R):(+R).toString(I);let U=parseInt(h),V=h&&h[0]+""=="0"?"0":" ";for(;R.length<U;)R=u!==void 0?R+V:V+R;return R}let a=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return e.replace(a,s)}static getBytes(e,n){return G.encode(e,n)}static getCharCode(e,n=0){return e.charCodeAt(n)}static getCharAt(e){return String.fromCharCode(e)}}me.SHIFT_JIS=z.SJIS.getName(),me.GB2312="GB2312",me.ISO88591=z.ISO8859_1.getName(),me.EUC_JP="EUC_JP",me.UTF8=z.UTF8.getName(),me.PLATFORM_DEFAULT_ENCODING=me.UTF8,me.ASSUME_SHIFT_JIS=!1;class fe{constructor(e=""){this.value=e}enableDecoding(e){return this.encoding=e,this}append(e){return typeof e=="string"?this.value+=e.toString():this.encoding?this.value+=me.castAsNonUtf8Char(e,this.encoding):this.value+=String.fromCharCode(e),this}appendChars(e,n,o){for(let s=n;n<n+o;s++)this.append(e[s]);return this}length(){return this.value.length}charAt(e){return this.value.charAt(e)}deleteCharAt(e){this.value=this.value.substr(0,e)+this.value.substring(e+1)}setCharAt(e,n){this.value=this.value.substr(0,e)+n+this.value.substr(e+1)}substring(e,n){return this.value.substring(e,n)}setLengthToZero(){this.value=""}toString(){return this.value}insert(e,n){this.value=this.value.substr(0,e)+n+this.value.substr(e+n.length)}}class te{constructor(e,n,o,s){if(this.width=e,this.height=n,this.rowSize=o,this.bits=s,n==null&&(n=e),this.height=n,e<1||n<1)throw new A("Both dimensions must be greater than 0");o==null&&(o=Math.floor((e+31)/32)),this.rowSize=o,s==null&&(this.bits=new Int32Array(this.rowSize*this.height))}static parseFromBooleanArray(e){const n=e.length,o=e[0].length,s=new te(o,n);for(let a=0;a<n;a++){const l=e[a];for(let u=0;u<o;u++)l[u]&&s.set(u,a)}return s}static parseFromString(e,n,o){if(e===null)throw new A("stringRepresentation cannot be null");const s=new Array(e.length);let a=0,l=0,u=-1,h=0,p=0;for(;p<e.length;)if(e.charAt(p)===`
60
+ `}setStatic(r){this.staticPrompt=r}setSkillMeta(r){this.skillMetaPrompt=r}setTemp(r){this.tempPrompt=r}appendTemp(r){this.tempPrompt+=r}}const xi={model:"deepseek-ai/DeepSeek-V3",maxSteps:30,extraTools:{}},Xa={apiKey:"sk-trial",baseURL:"https://agent.opentiny.design/api/v1/ai/",genuiUrl:"https://agent.opentiny.design/api/v1/ai/prompt",providerType:"deepseek"};function xx(t,r){if(!r&&!t)return;if(!t)return r;if(!r)return t;const i={...r};for(const[c,d]of Object.entries(t))d&&typeof d=="object"&&!Array.isArray(d)?i[c]={...i[c]||{},...d}:i[c]=d;return i}class yx extends Kn.BaseModelProvider{transport;agent;promptManager;llmConfig={...xi,...Xa};isGenuiEnabled;debugStream=!1;emit;constructor(r,i,c,d){super(r);let f;c&&"llm"in c?f={...xi,...c}:f={...xi,...Xa,...c||{}},this.llmConfig=f;const x={llmConfig:f.llm?{llm:f.llm}:{...f}};this.agent=new Jn.AgentModelProvider(x),this.promptManager=new gx,this.promptManager.setStatic(i),this.emit=d}updateLLMConfig({model:r,baseURL:i,genuiUrl:c,apiKey:d,providerType:f,useReActMode:m,llm:x,providerOptions:v,headers:g}){if(x)this.agent.llm=x,this.llmConfig.model=r,this.llmConfig.useReActMode=m||!1,this.agent.useReActMode=m||!1;else if(f&&i&&d){const E=this.isGenuiEnabled?.value&&c||i;this.llmConfig.model=r,this.llmConfig.apiKey=d,this.llmConfig.baseURL=i,this.llmConfig.providerType=f,this.llmConfig.useReActMode=m||!1,this.agent.useReActMode=m||!1;let A;if(f==="deepseek")A=kc;else if(f==="openai")A=Ou;else if(typeof f=="function")A=f;else throw new Error(`Unsupported providerType: ${f}`);this.agent.llm=A({apiKey:d,baseURL:E,...g?{headers:g}:{}})}this.llmConfig.providerOptions=v,this.llmConfig.headers=g}cleanGetSkillContentToolResult(r){const i=r[r.length-1];if(i.role==="tool"&&i.content.length>0){const c=i.content[i.content.length-1];c.type==="tool-result"&&c.toolName==="get_skill_content"&&(c.output.value.content="查询到技能内容已添加到系统提示词中。")}}cleanupOldSnapshotsInMessages(r){if(!r||r.length===0)return r;const c=this.agent.useReActMode===!0?"user":"tool",d=r[r.length-1];if(!d||d.role!==c||!this.isSnapshotContent(d.content))return r;const f=[...r];for(let m=f.length-2;m>=0;m--){const x=f[m];x.role===c&&this.isSnapshotContent(x.content)&&this.replaceSnapshotWithPlaceholder(x)}return f}removeSnapshotData(r){if(!r)return r;const i=["无障碍树快照:","无障碍树快照:","快照内容:","快照内容:","页面无障碍树快照:","页面无障碍树快照:","操作后的页面快照:","操作后的页面快照:"];let c=-1;for(const f of i){const m=r.indexOf(f);if(m!==-1){c=m;break}}if(c!==-1){const f=r.substring(0,c).trim();return f?`${f} 📸 [历史快照已清理]`:"📸 历史快照已清理"}const d=["已成功获取页面无障碍树快照","takeSnapshot","snapshotId_counter"];for(const f of d)if(r.startsWith(f))return"📸 历史快照已清理";return r}replaceSnapshotWithPlaceholder(r){if(Array.isArray(r.content)){const i=r.content[0];if(i?.output?.value?.content){const c=i.output.value.content;Array.isArray(c)&&(i.output.value.content=c.map(d=>d.type==="image"||d.type==="image_url"?null:d.type==="text"&&d.text&&this.isSnapshotContent(d.text)?{type:"text",text:this.removeSnapshotData(d.text)}:d).filter(d=>d!==null)),i.output.value.screenshot&&delete i.output.value.screenshot}else r.content=r.content.filter(c=>c.type!=="image"&&c.type!=="image_url")}else typeof r.content=="string"&&this.isSnapshotContent(r.content)&&(r.content=this.removeSnapshotData(r.content))}isSnapshotContent(r){if(!r)return!1;const i=["无障碍树快照","takeSnapshot","snapshotId_counter","UID 格式","快照 ID","操作后的页面快照","已成功获取页面无障碍树快照","快照内容:"];if(typeof r=="string")return i.some(c=>r.includes(c));if(Array.isArray(r))for(const c of r){const d=c?.output?.value?.content?.[0]?.text;if(d&&i.some(f=>d.includes(f))||c.type==="text"&&c.text&&i.some(f=>c.text.includes(f))||c.type==="image"||c.type==="image_url")return!0}return!1}async chatStream(r,i){let c=r.messages[r.messages.length-1];if(!c)return;const d={model:this.llmConfig.model,system:this.promptManager.getSystemPrompt(),abortSignal:r.options?.signal,toolChoice:"auto",tools:this.llmConfig.extraTools||{},maxSteps:this.llmConfig.maxSteps,providerOptions:xx(this.llmConfig.providerOptions,hx),prepareStep:({messages:T})=>{this.cleanGetSkillContentToolResult(T);const S=this.cleanupOldSnapshotsInMessages(T),P=Object.keys(this.llmConfig.extraTools||{});Object.values(this.agent.mcpTools||{}).forEach(ee=>{P.push(...Object.keys(ee||{}))});const M=Array.from(new Set(P)).filter(ee=>!this.agent.ignoreToolnames.includes(ee));return{system:this.promptManager.getSystemPrompt(),messages:S,activeTools:M}},onStepFinish:T=>{if(T.finishReason==="tool-calls"&&T.content.length>0){const S=T.content[T.content.length-1];if(S.toolName==="get_skill_content"&&S.type==="tool-result"){const P=S.output.content;this.promptManager.appendTemp(P)}}},onFinish:async()=>{await this.agent.closeAll(),this.promptManager.setTemp(""),this.emit?.("chat-stream-finish")}},f={role:"user",content:c.content},x=[...(T=>T.map(S=>({role:S.role,content:S.content})))(this.agent.responseMessages),f];d.messages=x;const v=await this.agent.chatStream(d),g=new qp,A=await new px({debug:this.debugStream,onFinish:()=>{_.nextTick(()=>{g.resolve(),i.onDone()})}}).traverse(v),D={role:"assistant",content:"",uiContent:[]};return _.watch(A,T=>{if(!T)i.onData(D);else{const P=T.steps.map(M=>M.contents).flat().map(M=>{if(M.type==="text")return mx(M.text);if(M.type==="reasoning")return{type:"collapsible-text",title:"思考过程",content:M.text,thinkId:M.id};if(M.type==="tool")return{type:"tool",id:M.id,name:M.toolName,content:JSON.stringify({input:M.inputStr,output:M.output}),status:M.error?"failed":M.running?"running":"success"}});if(T?.error){const M={type:"markdown",content:`**错误**:${T.error.responseBody||T.error.message||"未知错误"}`};P.push(M)}(T.steps.length>=1||T?.error)&&i.onData({...D,uiContent:P.flat(),usage:T.totalUsage||null})}},{deep:!0}),g.promise}chat(r){throw new Error("Method not implemented.")}}const wx=({systemPrompt:t,llmConfig:r,emit:i})=>{const c=new yx({provider:"custom"},t,r,i),d=new Kn.AIClient({providerImplementation:c,provider:"custom"}),{messageManager:f,createConversation:m,getCurrentConversation:x,switchConversation:v,deleteConversation:g,updateTitle:E,state:A}=Kn.useConversation({client:d,autoSave:!0,events:{onLoaded(){},onReceiveData(Z,B,L){L(),B.value[B.value.length-1].role==="assistant"&&B.value.pop(),i("before-ai-render",Z),B.value.push(Z)}}}),{messageState:D,inputMessage:T,sendMessage:S,abortRequest:P,messages:M,addMessage:ee,send:$}=f,F=_.ref(),re=async(Z,B,L)=>{if(L){const{shouldBlock:z}=await L(Z);if(z)return!1}T.value=Z;const W=x();if(W&&W.title==="新会话"&&E(W.id,T.value.slice(0,15)),B&&B.length>0){const z=[{type:"text",text:T.value},...B],we=[];T.value&&we.push({type:"text",content:T.value});for(const me of B)me.type==="image"&&me.image&&we.push({type:"image",content:me.image});const G={role:"user",content:z,uiContent:we};M.value.push(G),T.value="",$()}else{const z={role:"user",content:T.value,uiContent:[{type:"text",content:T.value}]};M.value.push(z),T.value="",$()}return!0};return _.onMounted(()=>{F.value?.focus()}),_.onUnmounted(()=>{c.agent.closeAll()}),{agent:c.agent,customAgentProvider:c,client:d,messageManager:f,addMessage:ee,send:$,conversationState:A,messages:M,messageState:D,inputMessage:T,sendMessage:S,abortRequest:P,senderRef:F,handleSendMessage:re,createConversation:m,switchConversation:v,deleteConversation:g,getCurrentConversation:x}};function _x(){}const Pn=Object.assign,ts=typeof window<"u",Zo=t=>t!==null&&typeof t=="object",tr=t=>t!=null,Pi=t=>typeof t=="function",vx=t=>Zo(t)&&Pi(t.then)&&Pi(t.catch),ku=t=>typeof t=="number"||/^\d+(\.\d+)?$/.test(t),Cx=()=>ts?/ios|iphone|ipad|ipod/.test(navigator.userAgent.toLowerCase()):!1;function Ya(t,r){const i=r.split(".");let c=t;return i.forEach(d=>{var f;c=Zo(c)&&(f=c[d])!=null?f:""}),c}function bx(t,r,i){return r.reduce((c,d)=>(c[d]=t[d],c),{})}const Po=null,un=[Number,String],pr={type:Boolean,default:!0},Ax=t=>({type:Number,default:t}),dn=t=>({type:String,default:t});var ns=typeof window<"u";function Ru(t){let r;_.onMounted(()=>{t(),_.nextTick(()=>{r=!0})}),_.onActivated(()=>{r&&t()})}function Mu(t,r,i={}){if(!ns)return;const{target:c=window,passive:d=!1,capture:f=!1}=i;let m=!1,x;const v=A=>{if(m)return;const D=_.unref(A);D&&!x&&(D.addEventListener(t,r,{capture:f,passive:d}),x=!0)},g=A=>{if(m)return;const D=_.unref(A);D&&x&&(D.removeEventListener(t,r,f),x=!1)};_.onUnmounted(()=>g(c)),_.onDeactivated(()=>g(c)),Ru(()=>v(c));let E;return _.isRef(c)&&(E=_.watch(c,(A,D)=>{g(D),v(A)})),()=>{E?.(),g(c),m=!0}}var Eo,yi;function Ex(){if(!Eo&&(Eo=_.ref(0),yi=_.ref(0),ns)){const t=()=>{Eo.value=window.innerWidth,yi.value=window.innerHeight};t(),window.addEventListener("resize",t,{passive:!0}),window.addEventListener("orientationchange",t,{passive:!0})}return{width:Eo,height:yi}}var Ix=/scroll|auto|overlay/i,Sx=ns?window:void 0;function Tx(t){return t.tagName!=="HTML"&&t.tagName!=="BODY"&&t.nodeType===1}function Ka(t,r=Sx){let i=t;for(;i&&i!==r&&Tx(i);){const{overflowY:c}=window.getComputedStyle(i);if(Ix.test(c))return i;i=i.parentNode}return r}Cx();const Nx=t=>t.stopPropagation();function Du(t,r){(typeof t.cancelable!="boolean"||t.cancelable)&&t.preventDefault(),Nx(t)}Ex();function vn(t){if(tr(t))return ku(t)?`${t}px`:String(t)}function Ox(t){if(tr(t)){if(Array.isArray(t))return{width:vn(t[0]),height:vn(t[1])};const r=vn(t);return{width:r,height:r}}}function kx(t){const r={};return t!==void 0&&(r.zIndex=+t),r}const Rx=/-(\w)/g,Pu=t=>t.replace(Rx,(r,i)=>i.toUpperCase()),Mx=t=>t.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,""),{hasOwnProperty:Dx}=Object.prototype;function Px(t,r,i){const c=r[i];tr(c)&&(!Dx.call(t,i)||!Zo(c)?t[i]=c:t[i]=Bu(Object(t[i]),c))}function Bu(t,r){return Object.keys(r).forEach(i=>{Px(t,r,i)}),t}var Bx={name:"姓名",tel:"电话",save:"保存",clear:"清空",undo:"撤销",cancel:"取消",confirm:"确认",delete:"删除",loading:"加载中...",noCoupon:"暂无优惠券",nameEmpty:"请填写姓名",addContact:"添加联系人",telInvalid:"请填写正确的电话",vanCalendar:{end:"结束",start:"开始",title:"日期选择",weekdays:["日","一","二","三","四","五","六"],monthTitle:(t,r)=>`${t}年${r}月`,rangePrompt:t=>`最多选择 ${t} 天`},vanCascader:{select:"请选择"},vanPagination:{prev:"上一页",next:"下一页"},vanPullRefresh:{pulling:"下拉即可刷新...",loosing:"释放即可刷新..."},vanSubmitBar:{label:"合计:"},vanCoupon:{unlimited:"无门槛",discount:t=>`${t}折`,condition:t=>`满${t}元可用`},vanCouponCell:{title:"优惠券",count:t=>`${t}张可用`},vanCouponList:{exchange:"兑换",close:"不使用",enable:"可用",disabled:"不可用",placeholder:"输入优惠码"},vanAddressEdit:{area:"地区",areaEmpty:"请选择地区",addressEmpty:"请填写详细地址",addressDetail:"详细地址",defaultAddress:"设为默认收货地址"},vanAddressList:{add:"新增地址"}};const Ja=_.ref("zh-CN"),Qa=_.reactive({"zh-CN":Bx}),Lx={messages(){return Qa[Ja.value]},use(t,r){Ja.value=t,this.add({[t]:r})},add(t={}){Bu(Qa,t)}};var Fx=Lx;function Ux(t){const r=Pu(t)+".";return(i,...c)=>{const d=Fx.messages(),f=Ya(d,r+i)||Ya(d,i);return Pi(f)?f(...c):f}}function Bi(t,r){return r?typeof r=="string"?` ${t}--${r}`:Array.isArray(r)?r.reduce((i,c)=>i+Bi(t,c),""):Object.keys(r).reduce((i,c)=>i+(r[c]?Bi(t,c):""),""):""}function zx(t){return(r,i)=>(r&&typeof r!="string"&&(i=r,r=""),r=r?`${t}__${r}`:t,`${r}${Bi(r,i)}`)}function yr(t){const r=`van-${t}`;return[r,zx(r),Ux(r)]}const Vx="van-haptics-feedback",el=5;function Zx(t,{args:r=[],done:i,canceled:c,error:d}){if(t){const f=t.apply(null,r);vx(f)?f.then(m=>{m?i():c&&c()}).catch(d||_x):f?i():c&&c()}else i()}function lo(t){return t.install=r=>{const{name:i}=t;i&&(r.component(i,t),r.component(Pu(`-${i}`),t))},t}const $x=Symbol();function Lu(t){const r=_.getCurrentInstance();r&&Pn(r.proxy,t)}const[jx,tl]=yr("badge"),Hx={dot:Boolean,max:un,tag:dn("div"),color:String,offset:Array,content:un,showZero:pr,position:dn("top-right")};var Wx=_.defineComponent({name:jx,props:Hx,setup(t,{slots:r}){const i=()=>{if(r.content)return!0;const{content:x,showZero:v}=t;return tr(x)&&x!==""&&(v||x!==0&&x!=="0")},c=()=>{const{dot:x,max:v,content:g}=t;if(!x&&i())return r.content?r.content():tr(v)&&ku(g)&&+g>+v?`${v}+`:g},d=x=>x.startsWith("-")?x.replace("-",""):`-${x}`,f=_.computed(()=>{const x={background:t.color};if(t.offset){const[v,g]=t.offset,{position:E}=t,[A,D]=E.split("-");r.default?(typeof g=="number"?x[A]=vn(A==="top"?g:-g):x[A]=A==="top"?vn(g):d(g),typeof v=="number"?x[D]=vn(D==="left"?v:-v):x[D]=D==="left"?vn(v):d(v)):(x.marginTop=vn(g),x.marginLeft=vn(v))}return x}),m=()=>{if(i()||t.dot)return _.createVNode("div",{class:tl([t.position,{dot:t.dot,fixed:!!r.default}]),style:f.value},[c()])};return()=>{if(r.default){const{tag:x}=t;return _.createVNode(x,{class:tl("wrapper")},{default:()=>[r.default(),m()]})}return m()}}});const Gx=lo(Wx);let Fu=2e3;const qx=()=>++Fu,Xx=t=>{Fu=t},[Uu,Yx]=yr("config-provider"),zu=Symbol(Uu),Kx={tag:dn("div"),theme:dn("light"),zIndex:Number,themeVars:Object,themeVarsDark:Object,themeVarsLight:Object,themeVarsScope:dn("local"),iconPrefix:String};function Jx(t){return t.replace(/([a-zA-Z])(\d)/g,"$1-$2")}function Qx(t){const r={};return Object.keys(t).forEach(i=>{const c=Jx(Mx(i));r[`--van-${c}`]=t[i]}),r}function Io(t={},r={}){Object.keys(t).forEach(i=>{t[i]!==r[i]&&document.documentElement.style.setProperty(i,t[i])}),Object.keys(r).forEach(i=>{t[i]||document.documentElement.style.removeProperty(i)})}_.defineComponent({name:Uu,props:Kx,setup(t,{slots:r}){const i=_.computed(()=>Qx(Pn({},t.themeVars,t.theme==="dark"?t.themeVarsDark:t.themeVarsLight)));if(ts){const c=()=>{document.documentElement.classList.add(`van-theme-${t.theme}`)},d=(f=t.theme)=>{document.documentElement.classList.remove(`van-theme-${f}`)};_.watch(()=>t.theme,(f,m)=>{m&&d(m),c()},{immediate:!0}),_.onActivated(c),_.onDeactivated(d),_.onBeforeUnmount(d),_.watch(i,(f,m)=>{t.themeVarsScope==="global"&&Io(f,m)}),_.watch(()=>t.themeVarsScope,(f,m)=>{m==="global"&&Io({},i.value),f==="global"&&Io(i.value,{})}),t.themeVarsScope==="global"&&Io(i.value,{})}return _.provide(zu,t),_.watchEffect(()=>{t.zIndex!==void 0&&Xx(t.zIndex)}),()=>_.createVNode(t.tag,{class:Yx(),style:t.themeVarsScope==="local"?i.value:void 0},{default:()=>{var c;return[(c=r.default)==null?void 0:c.call(r)]}})}});const[ey,nl]=yr("icon"),ty=t=>t?.includes("/"),ny={dot:Boolean,tag:dn("i"),name:String,size:un,badge:un,color:String,badgeProps:Object,classPrefix:String};var ry=_.defineComponent({name:ey,props:ny,setup(t,{slots:r}){const i=_.inject(zu,null),c=_.computed(()=>t.classPrefix||i?.iconPrefix||nl());return()=>{const{tag:d,dot:f,name:m,size:x,badge:v,color:g}=t,E=ty(m);return _.createVNode(Gx,_.mergeProps({dot:f,tag:d,class:[c.value,E?"":`${c.value}-${m}`],style:{color:g,fontSize:vn(x)},content:v},t.badgeProps),{default:()=>{var A;return[(A=r.default)==null?void 0:A.call(r),E&&_.createVNode("img",{class:nl("image"),src:m},null)]}})}}});const rs=lo(ry),[oy,Kr]=yr("loading"),iy=Array(12).fill(null).map((t,r)=>_.createVNode("i",{class:Kr("line",String(r+1))},null)),sy=_.createVNode("svg",{class:Kr("circular"),viewBox:"25 25 50 50"},[_.createVNode("circle",{cx:"50",cy:"50",r:"20",fill:"none"},null)]),ay={size:un,type:dn("circular"),color:String,vertical:Boolean,textSize:un,textColor:String};var ly=_.defineComponent({name:oy,props:ay,setup(t,{slots:r}){const i=_.computed(()=>Pn({color:t.color},Ox(t.size))),c=()=>{const f=t.type==="spinner"?iy:sy;return _.createVNode("span",{class:Kr("spinner",t.type),style:i.value},[r.icon?r.icon():f])},d=()=>{var f;if(r.default)return _.createVNode("span",{class:Kr("text"),style:{fontSize:vn(t.textSize),color:(f=t.textColor)!=null?f:t.color}},[r.default()])};return()=>{const{type:f,vertical:m}=t;return _.createVNode("div",{class:Kr([f,{vertical:m}]),"aria-live":"polite","aria-busy":!0},[c(),d()])}}});const cy=lo(ly),uy={show:Boolean,zIndex:un,overlay:pr,duration:un,teleport:[String,Object],lockScroll:pr,lazyRender:pr,beforeClose:Function,overlayProps:Object,overlayStyle:Object,overlayClass:Po,transitionAppear:Boolean,closeOnClickOverlay:pr};function dy(t,r){return t>r?"horizontal":r>t?"vertical":""}function fy(){const t=_.ref(0),r=_.ref(0),i=_.ref(0),c=_.ref(0),d=_.ref(0),f=_.ref(0),m=_.ref(""),x=_.ref(!0),v=()=>m.value==="vertical",g=()=>m.value==="horizontal",E=()=>{i.value=0,c.value=0,d.value=0,f.value=0,m.value="",x.value=!0};return{move:(T=>{const S=T.touches[0];i.value=(S.clientX<0?0:S.clientX)-t.value,c.value=S.clientY-r.value,d.value=Math.abs(i.value),f.value=Math.abs(c.value);const P=10;(!m.value||d.value<P&&f.value<P)&&(m.value=dy(d.value,f.value)),x.value&&(d.value>el||f.value>el)&&(x.value=!1)}),start:(T=>{E(),t.value=T.touches[0].clientX,r.value=T.touches[0].clientY}),reset:E,startX:t,startY:r,deltaX:i,deltaY:c,offsetX:d,offsetY:f,direction:m,isVertical:v,isHorizontal:g,isTap:x}}let Hr=0;const rl="van-overflow-hidden";function hy(t,r){const i=fy(),c="01",d="10",f=E=>{i.move(E);const A=i.deltaY.value>0?d:c;let D=Ka(E.target,t.value);for(;D.scrollHeight<=D.offsetHeight&&D!==t.value&&D.parentElement;)D=Ka(D.parentElement,t.value);const{scrollHeight:T,offsetHeight:S,scrollTop:P}=D;let M="11";P===0?M=S>=T?"00":"01":P+S>=T&&(M="10"),M!=="11"&&i.isVertical()&&!(parseInt(M,2)&parseInt(A,2))&&Du(E)},m=()=>{document.addEventListener("touchstart",i.start),document.addEventListener("touchmove",f,{passive:!1}),Hr||document.body.classList.add(rl),Hr++},x=()=>{Hr&&(document.removeEventListener("touchstart",i.start),document.removeEventListener("touchmove",f),Hr--,Hr||document.body.classList.remove(rl))},v=()=>r()&&m(),g=()=>r()&&x();Ru(v),_.onDeactivated(g),_.onBeforeUnmount(g),_.watch(r,E=>{E?m():x()})}function Vu(t){const r=_.ref(!1);return _.watch(t,i=>{i&&(r.value=i)},{immediate:!0}),i=>()=>r.value?i():null}const ol=()=>{var t;const{scopeId:r}=((t=_.getCurrentInstance())==null?void 0:t.vnode)||{};return r?{[r]:""}:null},[py,my]=yr("overlay"),gy={show:Boolean,zIndex:un,duration:un,className:Po,lockScroll:pr,lazyRender:pr,customStyle:Object,teleport:[String,Object]};var xy=_.defineComponent({name:py,inheritAttrs:!1,props:gy,setup(t,{attrs:r,slots:i}){const c=_.ref(),d=Vu(()=>t.show||!t.lazyRender),f=x=>{t.lockScroll&&Du(x)},m=d(()=>{var x;const v=Pn(kx(t.zIndex),t.customStyle);return tr(t.duration)&&(v.animationDuration=`${t.duration}s`),_.withDirectives(_.createVNode("div",_.mergeProps({ref:c,style:v,class:[my(),t.className]},r),[(x=i.default)==null?void 0:x.call(i)]),[[_.vShow,t.show]])});return Mu("touchmove",f,{target:c}),()=>{const x=_.createVNode(_.Transition,{name:"van-fade",appear:!0},{default:m});return t.teleport?_.createVNode(_.Teleport,{to:t.teleport},{default:()=>[x]}):x}}});const yy=lo(xy),wy=Pn({},uy,{round:Boolean,position:dn("center"),closeIcon:dn("cross"),closeable:Boolean,transition:String,iconPrefix:String,closeOnPopstate:Boolean,closeIconPosition:dn("top-right"),destroyOnClose:Boolean,safeAreaInsetTop:Boolean,safeAreaInsetBottom:Boolean}),[_y,il]=yr("popup");var vy=_.defineComponent({name:_y,inheritAttrs:!1,props:wy,emits:["open","close","opened","closed","keydown","update:show","clickOverlay","clickCloseIcon"],setup(t,{emit:r,attrs:i,slots:c}){let d,f;const m=_.ref(),x=_.ref(),v=Vu(()=>t.show||!t.lazyRender),g=_.computed(()=>{const B={zIndex:m.value};if(tr(t.duration)){const L=t.position==="center"?"animationDuration":"transitionDuration";B[L]=`${t.duration}s`}return B}),E=()=>{d||(d=!0,m.value=t.zIndex!==void 0?+t.zIndex:qx(),r("open"))},A=()=>{d&&Zx(t.beforeClose,{done(){d=!1,r("close"),r("update:show",!1)}})},D=B=>{r("clickOverlay",B),t.closeOnClickOverlay&&A()},T=()=>{if(t.overlay){const B=Pn({show:t.show,class:t.overlayClass,zIndex:m.value,duration:t.duration,customStyle:t.overlayStyle,role:t.closeOnClickOverlay?"button":void 0,tabindex:t.closeOnClickOverlay?0:void 0},t.overlayProps);return _.createVNode(yy,_.mergeProps(B,ol(),{onClick:D}),{default:c["overlay-content"]})}},S=B=>{r("clickCloseIcon",B),A()},P=()=>{if(t.closeable)return _.createVNode(rs,{role:"button",tabindex:0,name:t.closeIcon,class:[il("close-icon",t.closeIconPosition),Vx],classPrefix:t.iconPrefix,onClick:S},null)};let M;const ee=()=>{M&&clearTimeout(M),M=setTimeout(()=>{r("opened")})},$=()=>r("closed"),F=B=>r("keydown",B),re=v(()=>{var B;const{destroyOnClose:L,round:W,position:z,safeAreaInsetTop:we,safeAreaInsetBottom:G,show:me}=t;if(!(!me&&L))return _.withDirectives(_.createVNode("div",_.mergeProps({ref:x,style:g.value,role:"dialog",tabindex:0,class:[il({round:W,[z]:z}),{"van-safe-area-top":we,"van-safe-area-bottom":G}],onKeydown:F},i,ol()),[(B=c.default)==null?void 0:B.call(c),P()]),[[_.vShow,me]])}),Z=()=>{const{position:B,transition:L,transitionAppear:W}=t,z=B==="center"?"van-fade":`van-popup-slide-${B}`;return _.createVNode(_.Transition,{name:L||z,appear:W,onAfterEnter:ee,onAfterLeave:$},{default:re})};return _.watch(()=>t.show,B=>{B&&!d&&(E(),i.tabindex===0&&_.nextTick(()=>{var L;(L=x.value)==null||L.focus()})),!B&&d&&(d=!1,r("close"))}),Lu({popupRef:x}),hy(x,()=>t.show&&t.lockScroll),Mu("popstate",()=>{t.closeOnPopstate&&(A(),f=!1)}),_.onMounted(()=>{t.show&&E()}),_.onActivated(()=>{f&&(r("update:show",!0),f=!1)}),_.onDeactivated(()=>{t.show&&t.teleport&&(A(),f=!0)}),_.provide($x,()=>t.show),()=>t.teleport?_.createVNode(_.Teleport,{to:t.teleport},{default:()=>[T(),Z()]}):_.createVNode(_.Fragment,null,[T(),Z()])}});const Cy=lo(vy);let Wr=0;function by(t){t?(Wr||document.body.classList.add("van-toast--unclickable"),Wr++):Wr&&(Wr--,Wr||document.body.classList.remove("van-toast--unclickable"))}const[Ay,Or]=yr("toast"),Ey=["show","overlay","teleport","transition","overlayClass","overlayStyle","closeOnClickOverlay","zIndex"],Iy={icon:String,show:Boolean,type:dn("text"),overlay:Boolean,message:un,iconSize:un,duration:Ax(2e3),position:dn("middle"),teleport:[String,Object],wordBreak:String,className:Po,iconPrefix:String,transition:dn("van-fade"),loadingType:String,forbidClick:Boolean,overlayClass:Po,overlayStyle:Object,closeOnClick:Boolean,closeOnClickOverlay:Boolean,zIndex:un};var Sy=_.defineComponent({name:Ay,props:Iy,emits:["update:show"],setup(t,{emit:r,slots:i}){let c,d=!1;const f=()=>{const A=t.show&&t.forbidClick;d!==A&&(d=A,by(d))},m=A=>r("update:show",A),x=()=>{t.closeOnClick&&m(!1)},v=()=>clearTimeout(c),g=()=>{const{icon:A,type:D,iconSize:T,iconPrefix:S,loadingType:P}=t;if(A||D==="success"||D==="fail")return _.createVNode(rs,{name:A||D,size:T,class:Or("icon"),classPrefix:S},null);if(D==="loading")return _.createVNode(cy,{class:Or("loading"),size:T,type:P},null)},E=()=>{const{type:A,message:D}=t;if(i.message)return _.createVNode("div",{class:Or("text")},[i.message()]);if(tr(D)&&D!=="")return A==="html"?_.createVNode("div",{key:0,class:Or("text"),innerHTML:String(D)},null):_.createVNode("div",{class:Or("text")},[D])};return _.watch(()=>[t.show,t.forbidClick],f),_.watch(()=>[t.show,t.type,t.message,t.duration],()=>{v(),t.show&&t.duration>0&&(c=setTimeout(()=>{m(!1)},t.duration))}),_.onMounted(f),_.onUnmounted(f),()=>_.createVNode(Cy,_.mergeProps({class:[Or([t.position,t.wordBreak==="normal"?"break-normal":t.wordBreak,{[t.type]:!t.icon}]),t.className],lockScroll:!1,onClick:x,onClosed:v,"onUpdate:show":m},bx(t,Ey)),{default:()=>[g(),E()]})}});function Ty(){const t=_.reactive({show:!1}),r=d=>{t.show=d},i=d=>{Pn(t,d,{transitionAppear:!0}),r(!0)},c=()=>r(!1);return Lu({open:i,close:c,toggle:r}),{open:i,close:c,state:t,toggle:r}}function Ny(t){const r=_.createApp(t),i=document.createElement("div");return document.body.appendChild(i),{instance:r.mount(i),unmount(){r.unmount(),document.body.removeChild(i)}}}const Oy={icon:"",type:"text",message:"",className:"",overlay:!1,onClose:void 0,onOpened:void 0,duration:2e3,teleport:"body",iconSize:void 0,iconPrefix:void 0,position:"middle",transition:"van-fade",forbidClick:!1,loadingType:void 0,overlayClass:"",overlayStyle:void 0,closeOnClick:!1,closeOnClickOverlay:!1};let So=[],ky=!1,sl=Pn({},Oy);const Ry=new Map;function Zu(t){return Zo(t)?t:{message:t}}function My(){const{instance:t}=Ny({setup(){const r=_.ref(""),{open:i,state:c,close:d,toggle:f}=Ty(),m=()=>{},x=()=>{const v={onClosed:m,"onUpdate:show":f};return _.createVNode(Sy,_.mergeProps(c,v),null)};return _.watch(r,v=>{c.message=v}),_.getCurrentInstance().render=x,{open:i,close:d,message:r}}});return t}function Dy(){if(!So.length||ky){const t=My();So.push(t)}return So[So.length-1]}function it(t={}){if(!ts)return{};const r=Dy(),i=Zu(t);return r.open(Pn({},sl,Ry.get(i.type||sl.type),i)),r}const Py=t=>r=>it(Pn({type:t},Zu(r))),$u=Py("loading"),By=t=>{try{const r=JSON.parse(t),i=[];if(!r.mcpServers||typeof r.mcpServers!="object")throw new Error("JSON 格式错误:缺少 mcpServers 字段");for(const[c,d]of Object.entries(r.mcpServers)){const f=Ly(d);f&&i.push({name:c,config:f})}return i}catch(r){throw new Error(`JSON 解析失败: ${r instanceof Error?r.message:"未知错误"}`)}},Ly=t=>{if(!t||typeof t!="object"||!t.url)return null;const{type:r,url:i,sessionId:c,headers:d}=t;return r==="streamableHttp"||r==="sse"?{type:r,url:i,headers:d,useAISdkClient:!0}:{type:"streamableHttp",url:i,headers:d,useAISdkClient:!0}},Fy=(t,r,i)=>{const c=async(f,m,x,v,g)=>{if(await t.insertMcpServer(f,m)){const A=t.mcpTools[f];if(A){const T={id:`plugin-${f.replace("mcp-server-","")}`,name:x,icon:g||i,description:v||(typeof m=="object"&&"url"in m?m.url:""),enabled:!0,expanded:!0,tools:Object.keys(A).map(S=>({id:S,name:S,description:A[S].description,enabled:!0})),originMcpConfig:_.markRaw(m)};return r.value.push(T),!0}else return await t.removeMcpServer(f),!1}else return!1};return{handleCustomAdd:async(f,m)=>{$u("添加工具中...");try{if(f==="code"){if(typeof m!="string"){it("添加工具失败:code 类型需要 JSON 字符串格式");return}const $=By(m);if($.length===0){it("添加工具失败:JSON 配置格式不正确或未找到有效的服务器配置");return}let F=0,re=0;for(const{name:Z,config:B}of $){const L=`mcp-server-${Z}`;await c(L,B,Z)?F++:re++}await t.closeAll(),re===0?it(`成功添加 ${F} 个工具`):F>0?it(`成功添加 ${F} 个工具,${re} 个失败`):it("添加工具失败:所有服务器都无法连接");return}if(typeof m=="string"){it("添加工具失败:数据格式不正确");return}const{description:x,headers:v,name:g,thumbnail:E,type:A,url:D}=m;if(!g||!D||!A){it("添加工具失败:缺少必要参数(名称、URL或类型)");return}const S=`mcp-server-${`custom-${g}-${Date.now()}`}`;let P;if(typeof v=="string"&&v.trim())try{P=JSON.parse(v)}catch($){console.warn("Failed to parse headers JSON:",$)}else typeof v=="object"&&(P=v);await c(S,{type:A,url:D,headers:P,useAISdkClient:!0},g,x,E)?(await t.closeAll(),it("添加工具完成")):it("重复添加工具或无法获取工具列表")}catch(x){console.error("handleCustomAdd error:",x),it(`添加工具失败:${x instanceof Error?x.message:"未知错误"}`)}}}};function Uy(t,r,i){const c=_.ref([]),d=_.ref([]),f=_.ref(!1),m=Z=>t.mcpServers[Z]?.type==="local",x=(Z,B)=>{B?t.ignoreToolnames=t.ignoreToolnames.filter(L=>L!==Z):t.ignoreToolnames.includes(Z)||t.ignoreToolnames.push(Z)},v=(Z,B)=>{r.value||(r.value={});const L={...r.value};Z===null?Object.keys(L).forEach(W=>{L[W]=B}):L[Z]=B,r.value=L},g=Z=>{const B=d.value.find(L=>L.id===Z);B&&(B.addState="idle")},E=Z=>{const B=t.mcpTools[Z];if(!B)return[];const L=m(Z),W=r.value||{};return Object.keys(B).map(z=>{const we=Object.prototype.hasOwnProperty.call(W,z),G=L&&we?W[z]:!0;return x(z,G),{id:z,name:z,description:B[z].description,enabled:G}})},A=()=>{c.value.forEach(B=>{const L=new Map(B.tools.map(z=>[z.id,z.enabled])),W=E(B.id).map(z=>{const we=L.has(z.id)?!!L.get(z.id):z.enabled;return x(z.id,we),{...z,enabled:we}});B.tools=W});const Z=new Set(c.value.flatMap(B=>B.tools.map(L=>L.id)));t.ignoreToolnames=t.ignoreToolnames.filter(B=>Z.has(B))},D=async Z=>{const B=Z.pluginId;if(!await t.insertMcpServer(B,Z.mcpServer))return!1;if(!t.mcpTools[B])return await t.removeMcpServer(B),!1;const z=E(B);if(z.length===0&&Z.mcpServer?.type!=="builtin")return await t.removeMcpServer(B),!1;const we=c.value.find(me=>me.id===Z.pluginId);if(we)return we.tools=z,we.originMcpConfig=_.markRaw(Z.mcpServer),!0;const G={id:Z.pluginId,name:Z.name,icon:Z.icon||i,description:Z.description,enabled:!0,expanded:!1,tools:z,originMcpConfig:_.markRaw(Z.mcpServer)};return c.value.push(G),!0};return{installedPlugins:c,marketPlugins:d,pluginVisible:f,loadMcpServerToPlugin:async(Z,B)=>{let L=B.name,W=B.description;if(!L||!W){if("type"in B&&B.type==="local")L=L||"本地工具",W=W||"本地工具列表";else if("type"in B&&B.type==="builtin")L=L||"浏览器内置工具",W=W||"通过 document.modelContext 暴露的浏览器原生 MCP 工具";else if("url"in B)try{const z=new URL(B.url);L=L||z.origin,W=W||z.searchParams.get("sessionId")||("sessionId"in B?B.sessionId:"")||""}catch(z){console.error("[usePlugin] Failed to parse MCP server URL:",B.url,z),L=L||"未知插件",W=W||""}}await D({pluginId:Z,name:L||"",description:W||"",mcpServer:B})},togglePlugin:(Z,B)=>{const L=m(Z.id);Z.tools.forEach(W=>{W.enabled=B,x(W.id,B),L&&v(W.id,B)})},toggleTool:(Z,B,L)=>{const W=m(Z.id);Z.tools.forEach(z=>{z.id===B&&(z.enabled=L)}),x(B,L),W&&v(B,L)},deletePlugin:async Z=>{const B=c.value.find(W=>W.id===Z.id);if(!B)return;c.value=c.value.filter(W=>W.id!==B.id),g(B.id);const L=Z.id;await t.removeMcpServer(L)},addPluginCore:D,addPluginFromMarket:async Z=>{Z.addState="loading";const B={type:Z.type,url:Z.url,headers:Z.headers,useAISdkClient:!0},L=await D({pluginId:Z.id,name:Z.name,description:Z.description||"",icon:Z.icon,mcpServer:B});Z.addState=L?"added":"idle"},addPluginFromScan:async(Z,B)=>{const L={type:"streamableHttp",url:`${B}mcp?sessionId=${Z}`};let W="未知插件";try{W=new URL(`${B}mcp?sessionId=${Z}`).origin}catch(z){console.error("[usePlugin] Failed to parse scan URL:",z)}return await D({pluginId:`plugin-${Z}`,name:W,description:Z,mcpServer:L})},handleClientDisconnected:async Z=>{const B=Z,L=c.value.find(W=>W.id===B);return await t.removeMcpServer(Z),L?(c.value=c.value.filter(W=>W.id!==B),g(B),L):null},searchPlugin:(Z,B)=>Z.trim()===""||B.name.toLowerCase().includes(Z.toLowerCase()),syncInstalledPluginTools:A}}function zy(t){const{onToolCatalogChanged:r}=t,i=typeof window<"u"&&window!==window.top,c=D=>D===window||i&&D===window.parent;let d=!1,f=!1,m=!1;const x=async()=>{if(!(!r||d)){if(f){m=!0;return}f=!0;try{do{m=!1;try{await r()}catch(D){console.warn("[useRouteBasedTools] refresh tool catalog failed:",D)}}while(m&&!d)}finally{f=!1}}},v=D=>{!c(D.source)||D.data?.type!==Jn.MSG_TOOL_REGISTERED&&D.data?.type!==Jn.MSG_TOOL_UNREGISTERED||x()};let g=!1;const E=()=>{g||(d=!1,g=!0,window.addEventListener("message",v),i&&window.parent&&window.parent.postMessage({type:Jn.MSG_REMOTER_READY},"*"))},A=()=>{g&&(d=!0,m=!1,g=!1,window.removeEventListener("message",v))};_.onMounted(()=>{E()}),_.onUnmounted(()=>{A()})}function Vy(t){const{skillsRef:r,customAgentProvider:i}=t,c=_.shallowRef([]);_.watchEffect(async()=>{const x=r?.value;c.value=x?await Jn.getSkillOverviews(x):[]});const d=_.computed(()=>{const x=c.value;return x.length>0?Jn.formatSkillsForSystemPrompt(x):""}),f=_.computed(()=>{const x=r?.value;return x?Jn.createSkillTools(x):{}});return _.watchEffect(()=>{if(i.promptManager.setSkillMeta(d.value),i.llmConfig){const x=i.llmConfig.extraTools??{};i.llmConfig.extraTools={...x,...f.value}}}),{processSkillMentions:async()=>({shouldBlock:!1,skillItems:[]}),skillPromptPart:d,skillTools:f,skillOverviews:c}}const Zy=["title"],$y=_.defineComponent({__name:"TokenUsage",props:{usage:{type:Object,default:""}},setup(t){const r=t,i=_.computed(()=>r.usage.totalTokens===0||typeof r.usage.totalTokens>"u"),c=_.computed(()=>{const{inputTokens:f=0,outputTokens:m=0,totalTokens:x=0,inputTokenDetails:v,outputTokenDetails:g}=r.usage,E=v?.cacheReadTokens||0,A=g?.reasoningTokens||0;return{cachedInputTokens:[E/x*100+"%",E],inputTokens:[(f-E)/x*100+"%",f],reasoningTokens:[A/x*100+"%",A],outputTokens:[(m-A)/x*100+"%",m]}}),d=_.computed(()=>{const{inputTokens:f=0,outputTokens:m=0,totalTokens:x=0,inputTokenDetails:v,outputTokenDetails:g}=r.usage,E=v?.cacheReadTokens||0,A=g?.reasoningTokens||0;return[`inputTokens: ${f}`,`outputTokens: ${m}`,`totalTokens: ${x}`,`cachedInputTokens: ${E}`,`reasoningTokens: ${A}`].join(`
61
+ `)});return(f,m)=>i.value?_.createCommentVNode("",!0):(_.openBlock(),_.createElementBlock("div",{key:0,class:"token-usage-wrap",title:d.value},[(_.openBlock(!0),_.createElementBlock(_.Fragment,null,_.renderList(c.value,(x,v)=>(_.openBlock(),_.createElementBlock("div",{key:v,class:_.normalizeClass(v),style:_.normalizeStyle({width:x[0]})},null,6))),128))],8,Zy))}}),nr=(t,r)=>{const i=t.__vccOpts||t;for(const[c,d]of r)i[c]=d;return i},jy=nr($y,[["__scopeId","data-v-000098b4"]]),Hy={width:"100.000000",height:"100.000000",viewBox:"0 0 100 100",fill:"none",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink"};function Wy(t,r){return _.openBlock(),_.createElementBlock("svg",Hy,[...r[0]||(r[0]=[_.createStaticVNode('<desc> Created with Pixso. </desc><defs><radialGradient gradientTransform="translate(32.4474 65.1156) rotate(128.932) scale(22.991 20.6919)" cx="0.000000" cy="0.000000" r="1.000000" id="paint_radial_9_3090_0" gradientUnits="userSpaceOnUse"><stop stop-color="#5ADDF8"></stop><stop stop-color="#AEBFFF"></stop><stop offset="0.329153" stop-color="#1476FF"></stop><stop offset="0.667785" stop-color="#655AF8"></stop><stop offset="0.868255" stop-color="#948CFF"></stop><stop offset="1.000000" stop-color="#D25AF8"></stop><stop offset="1.000000" stop-color="#5A8BF8"></stop></radialGradient><linearGradient x1="30.999874" y1="85.000229" x2="30.499891" y2="70.500214" id="paint_linear_9_3092_0" gradientUnits="userSpaceOnUse"><stop stop-color="#000000" stop-opacity="0.000000"></stop><stop offset="1.000000" stop-color="#000000"></stop></linearGradient><radialGradient gradientTransform="translate(26.9999 24.7118) rotate(38.3655) scale(77.7996 109.496)" cx="0.000000" cy="0.000000" r="1.000000" id="paint_radial_9_3094_0" gradientUnits="userSpaceOnUse"><stop stop-color="#5ADDF8"></stop><stop stop-color="#AEBFFF"></stop><stop offset="0.329153" stop-color="#1476FF"></stop><stop offset="0.667785" stop-color="#655AF8"></stop><stop offset="0.868255" stop-color="#948CFF"></stop><stop offset="1.000000" stop-color="#D25AF8"></stop><stop offset="1.000000" stop-color="#5A8BF8"></stop></radialGradient></defs><rect id="NEXT-LOGO-无背景渐变-右" width="100.000000" height="99.999939" transform="matrix(-1 0 0 1 100 0)" fill="#FFFFFF" fill-opacity="0"></rect>',3),_.createElementVNode("mask",{id:"mask9_3088","mask-type":"alpha",maskUnits:"userSpaceOnUse",x:"0.000061",y:"0.000061",width:"99.999939",height:"99.999939"},[_.createElementVNode("rect",{id:"画板 1773",width:"99.999962",height:"99.999947",transform:"matrix(-1 0 0 1 100 6.10352e-05)",fill:"#000000","fill-opacity":"1.000000"})],-1),_.createStaticVNode('<g mask="url(#mask9_3088)"><path id="矢量 1" d="M35.93 81.01L36 63L18 63.07L32.48 82.23C33.61 83.71 35.93 82.9 35.93 81.01Z" fill="url(#paint_radial_9_3090_0)" fill-opacity="1.000000" fill-rule="evenodd"></path><g opacity="0.100000" style="mix-blend-mode:normal;"><path id="矢量 1" d="M35.93 81.01L36 63L18 63.07L32.48 82.23C33.61 83.71 35.93 82.9 35.93 81.01Z" fill="url(#paint_linear_9_3092_0)" fill-opacity="1.000000" fill-rule="evenodd"></path></g><rect id="矩形 5" x="12.000000" y="19.000183" rx="26.999992" width="75.999977" height="53.999985" fill="url(#paint_radial_9_3094_0)" fill-opacity="1.000000"></rect><rect id="矩形 5" rx="26.499992" width="74.999977" height="52.999985" transform="matrix(-1 0 0 1 87.5 19.5002)" fill="#000000" fill-opacity="0"></rect><rect id="矩形 5" rx="26.499992" width="74.999977" height="52.999985" transform="matrix(-1 0 0 1 87.5 19.5002)" stroke="#000000" stroke-opacity="0" stroke-width="1.000000"></rect><path id="path" d="M45.39 59.06C44.22 60.05 42.9 60.66 41.43 60.89C39.95 61.12 38.57 61.04 37.28 60.65C36 60.26 34.04 58.58 34.04 58.58C34.04 58.58 29.02 54.73 29.02 45.61C29.02 36.5 33.5 32.5 33.5 32.5C33.5 32.5 34.72 31.31 36.5 31C38.29 30.68 39.43 30.98 40.66 31.33C50.89 34.23 62.38 34.33 72.58 31.33C73.81 30.98 74.91 30.93 75.89 31.17C76.87 31.42 77.71 31.89 78.42 32.59C81.65 35.81 82.87 41.06 83 45.61C83.12 50.09 81.97 55.24 78.94 58.54C78.04 59.52 76.98 60.22 75.78 60.63C74.58 61.04 73.32 61.12 71.99 60.89C70.66 60.66 69.48 60.05 68.46 59.06C68.01 58.62 67.39 58.07 66.57 57.4C65.76 56.73 64.83 56.08 63.79 55.44C62.75 54.8 61.62 54.25 60.39 53.8C59.16 53.35 57.91 53.13 56.62 53.13C55.36 53.13 54.16 53.36 53 53.83C51.85 54.29 50.79 54.84 49.82 55.48C48.86 56.12 48 56.78 47.26 57.45C46.51 58.11 45.89 58.65 45.39 59.06Z" fill="#FFFFFF" fill-opacity="1.000000" fill-rule="nonzero"></path><rect id="矩形 841" rx="2.000000" width="3.999999" height="11.999996" transform="matrix(-0.999983 0.00577157 0.00577157 0.999983 76.1109 38.0356)" fill="#1476FF" fill-opacity="1.000000"></rect><path id="合并" d="M42.96 38C43.77 37.97 44.55 38.42 44.92 39.19L48.73 47.11C49.22 48.13 48.79 49.34 47.75 49.81C46.72 50.28 45.48 49.83 44.99 48.8L42.96 44.59L40.94 48.81C40.45 49.83 39.21 50.28 38.18 49.81C37.14 49.34 36.7 48.13 37.2 47.11L41 39.19C41.37 38.42 42.16 37.98 42.96 38Z" fill="#1476FF" fill-opacity="1.000000" fill-rule="evenodd"></path></g>',1)])])}const ju={render:Wy};function Gy(t){const{messages:r,messageState:i,inputMessage:c,handleSendMessage:d}=t,f=_.h(ju,{style:{width:"48px",height:"48px"}}),m=_.ref({}),x=_.computed(()=>Kn.GeneratingStatus.includes(i.status)),v=_.computed(()=>r.value.findLastIndex(T=>T.role==="assistant")),g=T=>T===void 0?"复制":m.value[T]?"复制成功":"复制",E=async T=>{const P=r.value[T].uiContent.map(M=>M.content).join(`
62
+ `);try{await navigator.clipboard.writeText(P),T!==void 0&&(m.value[T]=!0,setTimeout(()=>{m.value[T]=!1},3e3))}catch(M){console.error("复制失败:",M),it("复制失败,请重试")}},A=async T=>{const S=r.value.findLastIndex((M,ee)=>M.role==="user"&&ee<=T);if(S===-1){console.warn("未找到可重新生成的用户消息"),it("无法重新生成消息");return}const P=r.value[S];if(r.value=r.value.slice(0,S),Array.isArray(P.content)){const ee=P.content.find(F=>F.type==="text")?.text||"",$=P.content.filter(F=>F.type!=="text");c.value=ee,await d(ee,$.length>0?$:void 0)}else c.value=P.content,await d(P.content)},D={assistant:{type:"markdown",placement:"start",avatar:t.props.roleAvatar.assistant,maxWidth:"80%",customContentField:"uiContent",slots:{footer:({index:T})=>{const S=v.value===T;return x.value&&S?"":_.h("div",{class:["assistant-actions",{"latest-assistant":S,"historical-assistant":!S}],style:{display:"flex",justifyContent:"flex-start",alignItems:"center",gap:"4px"}},[_.h(Vt.IconButton,{icon:Mr.IconRefresh,size:24,onClick:()=>A(T)}),_.h(Id,{effect:"light",content:g(T),placement:"right",visibleArrow:!1},()=>_.h(Vt.IconButton,{icon:Mr.IconCopy,size:24,onClick:()=>E(T)})),r.value[T].usage?_.h(jy,{usage:r.value[T].usage}):null])}}},user:{placement:"end",avatar:t.props.roleAvatar.user,maxWidth:"80%",customContentField:"uiContent"}};return{welcomeIcon:f,roles:D,copyingStates:m,isProcessing:x,latestAssistantMessageIndex:v,copyTooltipContent:g,copyMessageToClipboard:E,regenerateMessage:A}}function qy(t){const{createConversation:r,switchConversation:i,deleteConversation:c,getCurrentConversation:d,abortRequest:f,conversationState:m,customAgentProvider:x}=t,v=_.ref(!1),g=()=>{_.nextTick(()=>{const S=document.querySelector("div.tr-bubble-list");S&&S.scrollTo({top:S.scrollHeight,behavior:"smooth"})})};return{showHistory:v,handleCreateConversation:()=>{f();const S=[];x.agent.responseMessages=S,r();const P=d();P.aiSdkMessages=S},handleHistorySelect:S=>{f(),i(S.id);const P=d();x.agent.responseMessages=P.aiSdkMessages,v.value=!1,g()},handleHistoryUpdateTitle:(S,P)=>{P.title=S},handleHistoryDelete:(S,P)=>{if(S.id==="delete"){if(m.currentId===P.id){it("不允许删除当前会话");return}c(P.id)}},scrollToBottom:g}}function Xy(t){const{sessionId:r,agentRoot:i,mode:c,qrCodeUrl:d,remoteUrl:f,menuItems:m,AILogoUrl:x,show:v,addPluginFromScan:g,inputMessage:E}=t;let A=null,D=!1;const T=async $=>{if($u("添加工具中..."),$){const F=await g($,i.value);it(F?"添加工具完成":"重复添加工具或添加失败")}else it("添加工具失败")},S=async $=>{if(/^\/[A-Za-z0-9-]{6,}$/.test($)){try{const F=await fetch(`${i.value}client?sessionId=${$.slice(1)}`);if(!F.ok)throw new Error(`HTTP ${F.status}`);const Z=(await F.json())?.data?.sessionId;Z?await T(Z):it("添加工具失败,请检查识别码是否正确"),E.value=""}catch(F){console.error("识别码处理失败:",F),it("添加工具失败,请检查识别码是否正确"),E.value=""}return!0}return!1},P=()=>{const $=F=>{A&&(A.destroy(),A=null),A=Jn.createRemoter({sessionId:F||void 0,qrCodeUrl:d,remoteUrl:f,menuItems:m?.value,logoUrl:x,onShowAIChat:()=>v.value=!0}),v.value&&A.hide()};_.watch(r,F=>{if(c!=="remoter")return;const re=!!F;A?!D&&re&&($(F),D=!0):($(F),D=re)},{immediate:!0}),m&&_.watch(m,()=>{c==="remoter"&&A&&$(r.value)},{deep:!0}),_.watch(v,F=>{A&&(F?A.hide():A.show())},{immediate:!0})},M=()=>{_.watch(r,$=>{$&&T($)})};return{handleScanSuccess:T,handleSessionIdInput:S,initialize:()=>{r.value&&T(r.value),c==="remoter"&&P(),M()},initializeRemoter:P,watchSessionIdChanges:M}}function Yy(t){return new Promise((r,i)=>{const c=new FileReader;c.onload=()=>r(c.result),c.onerror=i,c.readAsDataURL(t)})}function Ky(t){return t.type.startsWith("image/")}function Jy(t,r){const i=r*1024*1024;return t.size<=i}async function Qy(t){if(t.length===0)return[];const r=[];for(const i of t)if(i.rawFile)try{const c=await Yy(i.rawFile);Ky(i.rawFile)&&r.push({type:"image",image:c})}catch(c){console.error("文件转换失败:",c),it({type:"fail",message:"文件处理失败"})}return r}function ew(t={}){const r=_.ref([]),i=async d=>{if(!d||d.length===0)return;c();const f=_.unref(t.maxFileSize)||10,m=_.unref(t.supportedTypes)||["image/"];for(const x of d){if(!m.some(g=>x.type.startsWith(g))){it({type:"fail",message:`不支持的文件类型: ${x.type}`});continue}if(!Jy(x,f)){it({type:"fail",message:`文件大小超过 ${f}MB 限制`});continue}r.value.push({rawFile:x,url:URL.createObjectURL(x)})}},c=()=>{r.value.forEach(d=>{d.url&&URL.revokeObjectURL(d.url)}),r.value=[]};return{attachments:r,handleFilesSelected:i,clearAttachments:c}}function tw(t){const{selectedModel:r,selectedModelId:i}=t,c=_.computed(()=>r.value?.multimodal?.supportImages??!1),d=_.computed(()=>r.value?.multimodal?.maxFileSize||10),f=_.computed(()=>r.value?.multimodal?.supportedMimeTypes||["image/"]),{attachments:m,handleFilesSelected:x,clearAttachments:v}=ew({maxFileSize:d,supportedTypes:f});return _.watch(i,()=>{if(m.value.length>0&&r.value){const T=r.value.multimodal?.maxFileSize||10,S=r.value.multimodal?.supportedMimeTypes||["image/"];m.value.filter(M=>{if(!M.rawFile||!S.some(F=>M.rawFile.type.startsWith(F)))return!0;const $=T*1024*1024;return M.rawFile.size>$}).length>0&&(v(),it("切换模型后,之前选择的附件已清空"))}}),{hasMultimodalSupport:c,attachments:m,onFilesSelected:T=>{x(T)},checkCanSendAttachments:()=>m.value.length>0&&!c.value?(it("当前模型不支持附件,请先移除附件或切换支持多模态的模型"),!1):!0,processAttachments:async()=>m.value.length===0?[]:await Qy(m.value),cleanupAttachments:()=>{m.value.length>0&&v()},clearAttachments:v}}var Ce;(function(t){t[t.QR_CODE=0]="QR_CODE",t[t.AZTEC=1]="AZTEC",t[t.CODABAR=2]="CODABAR",t[t.CODE_39=3]="CODE_39",t[t.CODE_93=4]="CODE_93",t[t.CODE_128=5]="CODE_128",t[t.DATA_MATRIX=6]="DATA_MATRIX",t[t.MAXICODE=7]="MAXICODE",t[t.ITF=8]="ITF",t[t.EAN_13=9]="EAN_13",t[t.EAN_8=10]="EAN_8",t[t.PDF_417=11]="PDF_417",t[t.RSS_14=12]="RSS_14",t[t.RSS_EXPANDED=13]="RSS_EXPANDED",t[t.UPC_A=14]="UPC_A",t[t.UPC_E=15]="UPC_E",t[t.UPC_EAN_EXTENSION=16]="UPC_EAN_EXTENSION"})(Ce||(Ce={}));var al=new Map([[Ce.QR_CODE,"QR_CODE"],[Ce.AZTEC,"AZTEC"],[Ce.CODABAR,"CODABAR"],[Ce.CODE_39,"CODE_39"],[Ce.CODE_93,"CODE_93"],[Ce.CODE_128,"CODE_128"],[Ce.DATA_MATRIX,"DATA_MATRIX"],[Ce.MAXICODE,"MAXICODE"],[Ce.ITF,"ITF"],[Ce.EAN_13,"EAN_13"],[Ce.EAN_8,"EAN_8"],[Ce.PDF_417,"PDF_417"],[Ce.RSS_14,"RSS_14"],[Ce.RSS_EXPANDED,"RSS_EXPANDED"],[Ce.UPC_A,"UPC_A"],[Ce.UPC_E,"UPC_E"],[Ce.UPC_EAN_EXTENSION,"UPC_EAN_EXTENSION"]]),ll;(function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.URL=1]="URL"})(ll||(ll={}));function nw(t){return Object.values(Ce).includes(t)}var oo;(function(t){t[t.SCAN_TYPE_CAMERA=0]="SCAN_TYPE_CAMERA",t[t.SCAN_TYPE_FILE=1]="SCAN_TYPE_FILE"})(oo||(oo={}));var rw=(function(){function t(){}return t.GITHUB_PROJECT_URL="https://github.com/mebjas/html5-qrcode",t.SCAN_DEFAULT_FPS=2,t.DEFAULT_DISABLE_FLIP=!1,t.DEFAULT_REMEMBER_LAST_CAMERA_USED=!0,t.DEFAULT_SUPPORTED_SCAN_TYPE=[oo.SCAN_TYPE_CAMERA,oo.SCAN_TYPE_FILE],t})(),Hu=(function(){function t(r,i){this.format=r,this.formatName=i}return t.prototype.toString=function(){return this.formatName},t.create=function(r){if(!al.has(r))throw"".concat(r," not in html5QrcodeSupportedFormatsTextMap");return new t(r,al.get(r))},t})(),cl=(function(){function t(){}return t.createFromText=function(r){var i={text:r};return{decodedText:r,result:i}},t.createFromQrcodeResult=function(r){return{decodedText:r.text,result:r}},t})(),Li;(function(t){t[t.UNKWOWN_ERROR=0]="UNKWOWN_ERROR",t[t.IMPLEMENTATION_ERROR=1]="IMPLEMENTATION_ERROR",t[t.NO_CODE_FOUND_ERROR=2]="NO_CODE_FOUND_ERROR"})(Li||(Li={}));var ow=(function(){function t(){}return t.createFrom=function(r){return{errorMessage:r,type:Li.UNKWOWN_ERROR}},t})(),iw=(function(){function t(r){this.verbose=r}return t.prototype.log=function(r){this.verbose&&console.log(r)},t.prototype.warn=function(r){this.verbose&&console.warn(r)},t.prototype.logError=function(r,i){(this.verbose||i===!0)&&console.error(r)},t.prototype.logErrors=function(r){if(r.length===0)throw"Logger#logError called without arguments";this.verbose&&console.error(r)},t})();function zn(t){return typeof t>"u"||t===null}var Rr=(function(){function t(){}return t.codeParseError=function(r){return"QR code parse error, error = ".concat(r)},t.errorGettingUserMedia=function(r){return"Error getting userMedia, error = ".concat(r)},t.onlyDeviceSupportedError=function(){return"The device doesn't support navigator.mediaDevices , only supported cameraIdOrConfig in this case is deviceId parameter (string)."},t.cameraStreamingNotSupported=function(){return"Camera streaming not supported by the browser."},t.unableToQuerySupportedDevices=function(){return"Unable to query supported devices, unknown error."},t.insecureContextCameraQueryError=function(){return"Camera access is only supported in secure context like https or localhost."},t.scannerPaused=function(){return"Scanner paused"},t})(),Wu=(function(){function t(){}return t.isMediaStreamConstraintsValid=function(r,i){if(typeof r!="object"){var c=typeof r;return i.logError("videoConstraints should be of type object, the "+"object passed is of type ".concat(c,"."),!0),!1}for(var d=["autoGainControl","channelCount","echoCancellation","latency","noiseSuppression","sampleRate","sampleSize","volume"],f=new Set(d),m=Object.keys(r),x=0,v=m;x<v.length;x++){var g=v[x];if(f.has(g))return i.logError("".concat(g," is not supported videoConstaints."),!0),!1}return!0},t})(),To=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function sw(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var qr={exports:{}},aw=qr.exports,ul;function lw(){return ul||(ul=1,(function(t,r){(function(i,c){c(r)})(aw,(function(i){function c(C){return C==null}var d=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(C,e){C.__proto__=e}||function(C,e){for(var n in e)e.hasOwnProperty(n)&&(C[n]=e[n])};function f(C,e){d(C,e);function n(){this.constructor=C}C.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function m(C,e){var n=Object.setPrototypeOf;n?n(C,e):C.__proto__=e}function x(C,e){e===void 0&&(e=C.constructor);var n=Error.captureStackTrace;n&&n(C,e)}var v=(function(C){f(e,C);function e(n){var o=this.constructor,s=C.call(this,n)||this;return Object.defineProperty(s,"name",{value:o.name,enumerable:!1}),m(s,o.prototype),x(s),s}return e})(Error);class g extends v{constructor(e=void 0){super(e),this.message=e}getKind(){return this.constructor.kind}}g.kind="Exception";class E extends g{}E.kind="ArgumentException";class A extends g{}A.kind="IllegalArgumentException";class D{constructor(e){if(this.binarizer=e,e===null)throw new A("Binarizer must be non-null.")}getWidth(){return this.binarizer.getWidth()}getHeight(){return this.binarizer.getHeight()}getBlackRow(e,n){return this.binarizer.getBlackRow(e,n)}getBlackMatrix(){return(this.matrix===null||this.matrix===void 0)&&(this.matrix=this.binarizer.getBlackMatrix()),this.matrix}isCropSupported(){return this.binarizer.getLuminanceSource().isCropSupported()}crop(e,n,o,s){const a=this.binarizer.getLuminanceSource().crop(e,n,o,s);return new D(this.binarizer.createBinarizer(a))}isRotateSupported(){return this.binarizer.getLuminanceSource().isRotateSupported()}rotateCounterClockwise(){const e=this.binarizer.getLuminanceSource().rotateCounterClockwise();return new D(this.binarizer.createBinarizer(e))}rotateCounterClockwise45(){const e=this.binarizer.getLuminanceSource().rotateCounterClockwise45();return new D(this.binarizer.createBinarizer(e))}toString(){try{return this.getBlackMatrix().toString()}catch{return""}}}class T extends g{static getChecksumInstance(){return new T}}T.kind="ChecksumException";class S{constructor(e){this.source=e}getLuminanceSource(){return this.source}getWidth(){return this.source.getWidth()}getHeight(){return this.source.getHeight()}}class P{static arraycopy(e,n,o,s,a){for(;a--;)o[s++]=e[n++]}static currentTimeMillis(){return Date.now()}}class M extends g{}M.kind="IndexOutOfBoundsException";class ee extends M{constructor(e=void 0,n=void 0){super(n),this.index=e,this.message=n}}ee.kind="ArrayIndexOutOfBoundsException";class ${static fill(e,n){for(let o=0,s=e.length;o<s;o++)e[o]=n}static fillWithin(e,n,o,s){$.rangeCheck(e.length,n,o);for(let a=n;a<o;a++)e[a]=s}static rangeCheck(e,n,o){if(n>o)throw new A("fromIndex("+n+") > toIndex("+o+")");if(n<0)throw new ee(n);if(o>e)throw new ee(o)}static asList(...e){return e}static create(e,n,o){return Array.from({length:e}).map(a=>Array.from({length:n}).fill(o))}static createInt32Array(e,n,o){return Array.from({length:e}).map(a=>Int32Array.from({length:n}).fill(o))}static equals(e,n){if(!e||!n||!e.length||!n.length||e.length!==n.length)return!1;for(let o=0,s=e.length;o<s;o++)if(e[o]!==n[o])return!1;return!0}static hashCode(e){if(e===null)return 0;let n=1;for(const o of e)n=31*n+o;return n}static fillUint8Array(e,n){for(let o=0;o!==e.length;o++)e[o]=n}static copyOf(e,n){return e.slice(0,n)}static copyOfUint8Array(e,n){if(e.length<=n){const o=new Uint8Array(n);return o.set(e),o}return e.slice(0,n)}static copyOfRange(e,n,o){const s=o-n,a=new Int32Array(s);return P.arraycopy(e,n,a,0,s),a}static binarySearch(e,n,o){o===void 0&&(o=$.numberComparator);let s=0,a=e.length-1;for(;s<=a;){const l=a+s>>1,u=o(n,e[l]);if(u>0)s=l+1;else if(u<0)a=l-1;else return l}return-s-1}static numberComparator(e,n){return e-n}}class F{static numberOfTrailingZeros(e){let n;if(e===0)return 32;let o=31;return n=e<<16,n!==0&&(o-=16,e=n),n=e<<8,n!==0&&(o-=8,e=n),n=e<<4,n!==0&&(o-=4,e=n),n=e<<2,n!==0&&(o-=2,e=n),o-(e<<1>>>31)}static numberOfLeadingZeros(e){if(e===0)return 32;let n=1;return e>>>16||(n+=16,e<<=16),e>>>24||(n+=8,e<<=8),e>>>28||(n+=4,e<<=4),e>>>30||(n+=2,e<<=2),n-=e>>>31,n}static toHexString(e){return e.toString(16)}static toBinaryString(e){return String(parseInt(String(e),2))}static bitCount(e){return e=e-(e>>>1&1431655765),e=(e&858993459)+(e>>>2&858993459),e=e+(e>>>4)&252645135,e=e+(e>>>8),e=e+(e>>>16),e&63}static truncDivision(e,n){return Math.trunc(e/n)}static parseInt(e,n=void 0){return parseInt(e,n)}}F.MIN_VALUE_32_BITS=-2147483648,F.MAX_VALUE=Number.MAX_SAFE_INTEGER;class re{constructor(e,n){e===void 0?(this.size=0,this.bits=new Int32Array(1)):(this.size=e,n==null?this.bits=re.makeArray(e):this.bits=n)}getSize(){return this.size}getSizeInBytes(){return Math.floor((this.size+7)/8)}ensureCapacity(e){if(e>this.bits.length*32){const n=re.makeArray(e);P.arraycopy(this.bits,0,n,0,this.bits.length),this.bits=n}}get(e){return(this.bits[Math.floor(e/32)]&1<<(e&31))!==0}set(e){this.bits[Math.floor(e/32)]|=1<<(e&31)}flip(e){this.bits[Math.floor(e/32)]^=1<<(e&31)}getNextSet(e){const n=this.size;if(e>=n)return n;const o=this.bits;let s=Math.floor(e/32),a=o[s];a&=~((1<<(e&31))-1);const l=o.length;for(;a===0;){if(++s===l)return n;a=o[s]}const u=s*32+F.numberOfTrailingZeros(a);return u>n?n:u}getNextUnset(e){const n=this.size;if(e>=n)return n;const o=this.bits;let s=Math.floor(e/32),a=~o[s];a&=~((1<<(e&31))-1);const l=o.length;for(;a===0;){if(++s===l)return n;a=~o[s]}const u=s*32+F.numberOfTrailingZeros(a);return u>n?n:u}setBulk(e,n){this.bits[Math.floor(e/32)]=n}setRange(e,n){if(n<e||e<0||n>this.size)throw new A;if(n===e)return;n--;const o=Math.floor(e/32),s=Math.floor(n/32),a=this.bits;for(let l=o;l<=s;l++){const u=l>o?0:e&31,p=(2<<(l<s?31:n&31))-(1<<u);a[l]|=p}}clear(){const e=this.bits.length,n=this.bits;for(let o=0;o<e;o++)n[o]=0}isRange(e,n,o){if(n<e||e<0||n>this.size)throw new A;if(n===e)return!0;n--;const s=Math.floor(e/32),a=Math.floor(n/32),l=this.bits;for(let u=s;u<=a;u++){const h=u>s?0:e&31,y=(2<<(u<a?31:n&31))-(1<<h)&4294967295;if((l[u]&y)!==(o?y:0))return!1}return!0}appendBit(e){this.ensureCapacity(this.size+1),e&&(this.bits[Math.floor(this.size/32)]|=1<<(this.size&31)),this.size++}appendBits(e,n){if(n<0||n>32)throw new A("Num bits must be between 0 and 32");this.ensureCapacity(this.size+n);for(let o=n;o>0;o--)this.appendBit((e>>o-1&1)===1)}appendBitArray(e){const n=e.size;this.ensureCapacity(this.size+n);for(let o=0;o<n;o++)this.appendBit(e.get(o))}xor(e){if(this.size!==e.size)throw new A("Sizes don't match");const n=this.bits;for(let o=0,s=n.length;o<s;o++)n[o]^=e.bits[o]}toBytes(e,n,o,s){for(let a=0;a<s;a++){let l=0;for(let u=0;u<8;u++)this.get(e)&&(l|=1<<7-u),e++;n[o+a]=l}}getBitArray(){return this.bits}reverse(){const e=new Int32Array(this.bits.length),n=Math.floor((this.size-1)/32),o=n+1,s=this.bits;for(let a=0;a<o;a++){let l=s[a];l=l>>1&1431655765|(l&1431655765)<<1,l=l>>2&858993459|(l&858993459)<<2,l=l>>4&252645135|(l&252645135)<<4,l=l>>8&16711935|(l&16711935)<<8,l=l>>16&65535|(l&65535)<<16,e[n-a]=l}if(this.size!==o*32){const a=o*32-this.size;let l=e[0]>>>a;for(let u=1;u<o;u++){const h=e[u];l|=h<<32-a,e[u-1]=l,l=h>>>a}e[o-1]=l}this.bits=e}static makeArray(e){return new Int32Array(Math.floor((e+31)/32))}equals(e){if(!(e instanceof re))return!1;const n=e;return this.size===n.size&&$.equals(this.bits,n.bits)}hashCode(){return 31*this.size+$.hashCode(this.bits)}toString(){let e="";for(let n=0,o=this.size;n<o;n++)(n&7)===0&&(e+=" "),e+=this.get(n)?"X":".";return e}clone(){return new re(this.size,this.bits.slice())}}var Z;(function(C){C[C.OTHER=0]="OTHER",C[C.PURE_BARCODE=1]="PURE_BARCODE",C[C.POSSIBLE_FORMATS=2]="POSSIBLE_FORMATS",C[C.TRY_HARDER=3]="TRY_HARDER",C[C.CHARACTER_SET=4]="CHARACTER_SET",C[C.ALLOWED_LENGTHS=5]="ALLOWED_LENGTHS",C[C.ASSUME_CODE_39_CHECK_DIGIT=6]="ASSUME_CODE_39_CHECK_DIGIT",C[C.ASSUME_GS1=7]="ASSUME_GS1",C[C.RETURN_CODABAR_START_END=8]="RETURN_CODABAR_START_END",C[C.NEED_RESULT_POINT_CALLBACK=9]="NEED_RESULT_POINT_CALLBACK",C[C.ALLOWED_EAN_EXTENSIONS=10]="ALLOWED_EAN_EXTENSIONS"})(Z||(Z={}));var B=Z;class L extends g{static getFormatInstance(){return new L}}L.kind="FormatException";var W;(function(C){C[C.Cp437=0]="Cp437",C[C.ISO8859_1=1]="ISO8859_1",C[C.ISO8859_2=2]="ISO8859_2",C[C.ISO8859_3=3]="ISO8859_3",C[C.ISO8859_4=4]="ISO8859_4",C[C.ISO8859_5=5]="ISO8859_5",C[C.ISO8859_6=6]="ISO8859_6",C[C.ISO8859_7=7]="ISO8859_7",C[C.ISO8859_8=8]="ISO8859_8",C[C.ISO8859_9=9]="ISO8859_9",C[C.ISO8859_10=10]="ISO8859_10",C[C.ISO8859_11=11]="ISO8859_11",C[C.ISO8859_13=12]="ISO8859_13",C[C.ISO8859_14=13]="ISO8859_14",C[C.ISO8859_15=14]="ISO8859_15",C[C.ISO8859_16=15]="ISO8859_16",C[C.SJIS=16]="SJIS",C[C.Cp1250=17]="Cp1250",C[C.Cp1251=18]="Cp1251",C[C.Cp1252=19]="Cp1252",C[C.Cp1256=20]="Cp1256",C[C.UnicodeBigUnmarked=21]="UnicodeBigUnmarked",C[C.UTF8=22]="UTF8",C[C.ASCII=23]="ASCII",C[C.Big5=24]="Big5",C[C.GB18030=25]="GB18030",C[C.EUC_KR=26]="EUC_KR"})(W||(W={}));class z{constructor(e,n,o,...s){this.valueIdentifier=e,this.name=o,typeof n=="number"?this.values=Int32Array.from([n]):this.values=n,this.otherEncodingNames=s,z.VALUE_IDENTIFIER_TO_ECI.set(e,this),z.NAME_TO_ECI.set(o,this);const a=this.values;for(let l=0,u=a.length;l!==u;l++){const h=a[l];z.VALUES_TO_ECI.set(h,this)}for(const l of s)z.NAME_TO_ECI.set(l,this)}getValueIdentifier(){return this.valueIdentifier}getName(){return this.name}getValue(){return this.values[0]}static getCharacterSetECIByValue(e){if(e<0||e>=900)throw new L("incorect value");const n=z.VALUES_TO_ECI.get(e);if(n===void 0)throw new L("incorect value");return n}static getCharacterSetECIByName(e){const n=z.NAME_TO_ECI.get(e);if(n===void 0)throw new L("incorect value");return n}equals(e){if(!(e instanceof z))return!1;const n=e;return this.getName()===n.getName()}}z.VALUE_IDENTIFIER_TO_ECI=new Map,z.VALUES_TO_ECI=new Map,z.NAME_TO_ECI=new Map,z.Cp437=new z(W.Cp437,Int32Array.from([0,2]),"Cp437"),z.ISO8859_1=new z(W.ISO8859_1,Int32Array.from([1,3]),"ISO-8859-1","ISO88591","ISO8859_1"),z.ISO8859_2=new z(W.ISO8859_2,4,"ISO-8859-2","ISO88592","ISO8859_2"),z.ISO8859_3=new z(W.ISO8859_3,5,"ISO-8859-3","ISO88593","ISO8859_3"),z.ISO8859_4=new z(W.ISO8859_4,6,"ISO-8859-4","ISO88594","ISO8859_4"),z.ISO8859_5=new z(W.ISO8859_5,7,"ISO-8859-5","ISO88595","ISO8859_5"),z.ISO8859_6=new z(W.ISO8859_6,8,"ISO-8859-6","ISO88596","ISO8859_6"),z.ISO8859_7=new z(W.ISO8859_7,9,"ISO-8859-7","ISO88597","ISO8859_7"),z.ISO8859_8=new z(W.ISO8859_8,10,"ISO-8859-8","ISO88598","ISO8859_8"),z.ISO8859_9=new z(W.ISO8859_9,11,"ISO-8859-9","ISO88599","ISO8859_9"),z.ISO8859_10=new z(W.ISO8859_10,12,"ISO-8859-10","ISO885910","ISO8859_10"),z.ISO8859_11=new z(W.ISO8859_11,13,"ISO-8859-11","ISO885911","ISO8859_11"),z.ISO8859_13=new z(W.ISO8859_13,15,"ISO-8859-13","ISO885913","ISO8859_13"),z.ISO8859_14=new z(W.ISO8859_14,16,"ISO-8859-14","ISO885914","ISO8859_14"),z.ISO8859_15=new z(W.ISO8859_15,17,"ISO-8859-15","ISO885915","ISO8859_15"),z.ISO8859_16=new z(W.ISO8859_16,18,"ISO-8859-16","ISO885916","ISO8859_16"),z.SJIS=new z(W.SJIS,20,"SJIS","Shift_JIS"),z.Cp1250=new z(W.Cp1250,21,"Cp1250","windows-1250"),z.Cp1251=new z(W.Cp1251,22,"Cp1251","windows-1251"),z.Cp1252=new z(W.Cp1252,23,"Cp1252","windows-1252"),z.Cp1256=new z(W.Cp1256,24,"Cp1256","windows-1256"),z.UnicodeBigUnmarked=new z(W.UnicodeBigUnmarked,25,"UnicodeBigUnmarked","UTF-16BE","UnicodeBig"),z.UTF8=new z(W.UTF8,26,"UTF8","UTF-8"),z.ASCII=new z(W.ASCII,Int32Array.from([27,170]),"ASCII","US-ASCII"),z.Big5=new z(W.Big5,28,"Big5"),z.GB18030=new z(W.GB18030,29,"GB18030","GB2312","EUC_CN","GBK"),z.EUC_KR=new z(W.EUC_KR,30,"EUC_KR","EUC-KR");class we extends g{}we.kind="UnsupportedOperationException";class G{static decode(e,n){const o=this.encodingName(n);return this.customDecoder?this.customDecoder(e,o):typeof TextDecoder>"u"||this.shouldDecodeOnFallback(o)?this.decodeFallback(e,o):new TextDecoder(o).decode(e)}static shouldDecodeOnFallback(e){return!G.isBrowser()&&e==="ISO-8859-1"}static encode(e,n){const o=this.encodingName(n);return this.customEncoder?this.customEncoder(e,o):typeof TextEncoder>"u"?this.encodeFallback(e):new TextEncoder().encode(e)}static isBrowser(){return typeof window<"u"&&{}.toString.call(window)==="[object Window]"}static encodingName(e){return typeof e=="string"?e:e.getName()}static encodingCharacterSet(e){return e instanceof z?e:z.getCharacterSetECIByName(e)}static decodeFallback(e,n){const o=this.encodingCharacterSet(n);if(G.isDecodeFallbackSupported(o)){let s="";for(let a=0,l=e.length;a<l;a++){let u=e[a].toString(16);u.length<2&&(u="0"+u),s+="%"+u}return decodeURIComponent(s)}if(o.equals(z.UnicodeBigUnmarked))return String.fromCharCode.apply(null,new Uint16Array(e.buffer));throw new we(`Encoding ${this.encodingName(n)} not supported by fallback.`)}static isDecodeFallbackSupported(e){return e.equals(z.UTF8)||e.equals(z.ISO8859_1)||e.equals(z.ASCII)}static encodeFallback(e){const o=btoa(unescape(encodeURIComponent(e))).split(""),s=[];for(let a=0;a<o.length;a++)s.push(o[a].charCodeAt(0));return new Uint8Array(s)}}class me{static castAsNonUtf8Char(e,n=null){const o=n?n.getName():this.ISO88591;return G.decode(new Uint8Array([e]),o)}static guessEncoding(e,n){if(n!=null&&n.get(B.CHARACTER_SET)!==void 0)return n.get(B.CHARACTER_SET).toString();const o=e.length;let s=!0,a=!0,l=!0,u=0,h=0,p=0,y=0,b=0,I=0,R=0,U=0,V=0,H=0,Q=0;const he=e.length>3&&e[0]===239&&e[1]===187&&e[2]===191;for(let pe=0;pe<o&&(s||a||l);pe++){const ce=e[pe]&255;l&&(u>0?(ce&128)===0?l=!1:u--:(ce&128)!==0&&((ce&64)===0?l=!1:(u++,(ce&32)===0?h++:(u++,(ce&16)===0?p++:(u++,(ce&8)===0?y++:l=!1))))),s&&(ce>127&&ce<160?s=!1:ce>159&&(ce<192||ce===215||ce===247)&&Q++),a&&(b>0?ce<64||ce===127||ce>252?a=!1:b--:ce===128||ce===160||ce>239?a=!1:ce>160&&ce<224?(I++,U=0,R++,R>V&&(V=R)):ce>127?(b++,R=0,U++,U>H&&(H=U)):(R=0,U=0))}return l&&u>0&&(l=!1),a&&b>0&&(a=!1),l&&(he||h+p+y>0)?me.UTF8:a&&(me.ASSUME_SHIFT_JIS||V>=3||H>=3)?me.SHIFT_JIS:s&&a?V===2&&I===2||Q*10>=o?me.SHIFT_JIS:me.ISO88591:s?me.ISO88591:a?me.SHIFT_JIS:l?me.UTF8:me.PLATFORM_DEFAULT_ENCODING}static format(e,...n){let o=-1;function s(l,u,h,p,y,b){if(l==="%%")return"%";if(n[++o]===void 0)return;l=p?parseInt(p.substr(1)):void 0;let I=y?parseInt(y.substr(1)):void 0,R;switch(b){case"s":R=n[o];break;case"c":R=n[o][0];break;case"f":R=parseFloat(n[o]).toFixed(l);break;case"p":R=parseFloat(n[o]).toPrecision(l);break;case"e":R=parseFloat(n[o]).toExponential(l);break;case"x":R=parseInt(n[o]).toString(I||16);break;case"d":R=parseFloat(parseInt(n[o],I||10).toPrecision(l)).toFixed(0);break}R=typeof R=="object"?JSON.stringify(R):(+R).toString(I);let U=parseInt(h),V=h&&h[0]+""=="0"?"0":" ";for(;R.length<U;)R=u!==void 0?R+V:V+R;return R}let a=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return e.replace(a,s)}static getBytes(e,n){return G.encode(e,n)}static getCharCode(e,n=0){return e.charCodeAt(n)}static getCharAt(e){return String.fromCharCode(e)}}me.SHIFT_JIS=z.SJIS.getName(),me.GB2312="GB2312",me.ISO88591=z.ISO8859_1.getName(),me.EUC_JP="EUC_JP",me.UTF8=z.UTF8.getName(),me.PLATFORM_DEFAULT_ENCODING=me.UTF8,me.ASSUME_SHIFT_JIS=!1;class fe{constructor(e=""){this.value=e}enableDecoding(e){return this.encoding=e,this}append(e){return typeof e=="string"?this.value+=e.toString():this.encoding?this.value+=me.castAsNonUtf8Char(e,this.encoding):this.value+=String.fromCharCode(e),this}appendChars(e,n,o){for(let s=n;n<n+o;s++)this.append(e[s]);return this}length(){return this.value.length}charAt(e){return this.value.charAt(e)}deleteCharAt(e){this.value=this.value.substr(0,e)+this.value.substring(e+1)}setCharAt(e,n){this.value=this.value.substr(0,e)+n+this.value.substr(e+1)}substring(e,n){return this.value.substring(e,n)}setLengthToZero(){this.value=""}toString(){return this.value}insert(e,n){this.value=this.value.substr(0,e)+n+this.value.substr(e+n.length)}}class te{constructor(e,n,o,s){if(this.width=e,this.height=n,this.rowSize=o,this.bits=s,n==null&&(n=e),this.height=n,e<1||n<1)throw new A("Both dimensions must be greater than 0");o==null&&(o=Math.floor((e+31)/32)),this.rowSize=o,s==null&&(this.bits=new Int32Array(this.rowSize*this.height))}static parseFromBooleanArray(e){const n=e.length,o=e[0].length,s=new te(o,n);for(let a=0;a<n;a++){const l=e[a];for(let u=0;u<o;u++)l[u]&&s.set(u,a)}return s}static parseFromString(e,n,o){if(e===null)throw new A("stringRepresentation cannot be null");const s=new Array(e.length);let a=0,l=0,u=-1,h=0,p=0;for(;p<e.length;)if(e.charAt(p)===`
63
63
  `||e.charAt(p)==="\r"){if(a>l){if(u===-1)u=a-l;else if(a-l!==u)throw new A("row lengths do not match");l=a,h++}p++}else if(e.substring(p,p+n.length)===n)p+=n.length,s[a]=!0,a++;else if(e.substring(p,p+o.length)===o)p+=o.length,s[a]=!1,a++;else throw new A("illegal character encountered: "+e.substring(p));if(a>l){if(u===-1)u=a-l;else if(a-l!==u)throw new A("row lengths do not match");h++}const y=new te(u,h);for(let b=0;b<a;b++)s[b]&&y.set(Math.floor(b%u),Math.floor(b/u));return y}get(e,n){const o=n*this.rowSize+Math.floor(e/32);return(this.bits[o]>>>(e&31)&1)!==0}set(e,n){const o=n*this.rowSize+Math.floor(e/32);this.bits[o]|=1<<(e&31)&4294967295}unset(e,n){const o=n*this.rowSize+Math.floor(e/32);this.bits[o]&=~(1<<(e&31)&4294967295)}flip(e,n){const o=n*this.rowSize+Math.floor(e/32);this.bits[o]^=1<<(e&31)&4294967295}xor(e){if(this.width!==e.getWidth()||this.height!==e.getHeight()||this.rowSize!==e.getRowSize())throw new A("input matrix dimensions do not match");const n=new re(Math.floor(this.width/32)+1),o=this.rowSize,s=this.bits;for(let a=0,l=this.height;a<l;a++){const u=a*o,h=e.getRow(a,n).getBitArray();for(let p=0;p<o;p++)s[u+p]^=h[p]}}clear(){const e=this.bits,n=e.length;for(let o=0;o<n;o++)e[o]=0}setRegion(e,n,o,s){if(n<0||e<0)throw new A("Left and top must be nonnegative");if(s<1||o<1)throw new A("Height and width must be at least 1");const a=e+o,l=n+s;if(l>this.height||a>this.width)throw new A("The region must fit inside the matrix");const u=this.rowSize,h=this.bits;for(let p=n;p<l;p++){const y=p*u;for(let b=e;b<a;b++)h[y+Math.floor(b/32)]|=1<<(b&31)&4294967295}}getRow(e,n){n==null||n.getSize()<this.width?n=new re(this.width):n.clear();const o=this.rowSize,s=this.bits,a=e*o;for(let l=0;l<o;l++)n.setBulk(l*32,s[a+l]);return n}setRow(e,n){P.arraycopy(n.getBitArray(),0,this.bits,e*this.rowSize,this.rowSize)}rotate180(){const e=this.getWidth(),n=this.getHeight();let o=new re(e),s=new re(e);for(let a=0,l=Math.floor((n+1)/2);a<l;a++)o=this.getRow(a,o),s=this.getRow(n-1-a,s),o.reverse(),s.reverse(),this.setRow(a,s),this.setRow(n-1-a,o)}getEnclosingRectangle(){const e=this.width,n=this.height,o=this.rowSize,s=this.bits;let a=e,l=n,u=-1,h=-1;for(let p=0;p<n;p++)for(let y=0;y<o;y++){const b=s[p*o+y];if(b!==0){if(p<l&&(l=p),p>h&&(h=p),y*32<a){let I=0;for(;(b<<31-I&4294967295)===0;)I++;y*32+I<a&&(a=y*32+I)}if(y*32+31>u){let I=31;for(;!(b>>>I);)I--;y*32+I>u&&(u=y*32+I)}}}return u<a||h<l?null:Int32Array.from([a,l,u-a+1,h-l+1])}getTopLeftOnBit(){const e=this.rowSize,n=this.bits;let o=0;for(;o<n.length&&n[o]===0;)o++;if(o===n.length)return null;const s=o/e;let a=o%e*32;const l=n[o];let u=0;for(;(l<<31-u&4294967295)===0;)u++;return a+=u,Int32Array.from([a,s])}getBottomRightOnBit(){const e=this.rowSize,n=this.bits;let o=n.length-1;for(;o>=0&&n[o]===0;)o--;if(o<0)return null;const s=Math.floor(o/e);let a=Math.floor(o%e)*32;const l=n[o];let u=31;for(;!(l>>>u);)u--;return a+=u,Int32Array.from([a,s])}getWidth(){return this.width}getHeight(){return this.height}getRowSize(){return this.rowSize}equals(e){if(!(e instanceof te))return!1;const n=e;return this.width===n.width&&this.height===n.height&&this.rowSize===n.rowSize&&$.equals(this.bits,n.bits)}hashCode(){let e=this.width;return e=31*e+this.width,e=31*e+this.height,e=31*e+this.rowSize,e=31*e+$.hashCode(this.bits),e}toString(e="X ",n=" ",o=`
64
64
  `){return this.buildToString(e,n,o)}buildToString(e,n,o){let s=new fe;for(let a=0,l=this.height;a<l;a++){for(let u=0,h=this.width;u<h;u++)s.append(this.get(u,a)?e:n);s.append(o)}return s.toString()}clone(){return new te(this.width,this.height,this.rowSize,this.bits.slice())}}class q extends g{static getNotFoundInstance(){return new q}}q.kind="NotFoundException";class ke extends S{constructor(e){super(e),this.luminances=ke.EMPTY,this.buckets=new Int32Array(ke.LUMINANCE_BUCKETS)}getBlackRow(e,n){const o=this.getLuminanceSource(),s=o.getWidth();n==null||n.getSize()<s?n=new re(s):n.clear(),this.initArrays(s);const a=o.getRow(e,this.luminances),l=this.buckets;for(let h=0;h<s;h++)l[(a[h]&255)>>ke.LUMINANCE_SHIFT]++;const u=ke.estimateBlackPoint(l);if(s<3)for(let h=0;h<s;h++)(a[h]&255)<u&&n.set(h);else{let h=a[0]&255,p=a[1]&255;for(let y=1;y<s-1;y++){const b=a[y+1]&255;(p*4-h-b)/2<u&&n.set(y),h=p,p=b}}return n}getBlackMatrix(){const e=this.getLuminanceSource(),n=e.getWidth(),o=e.getHeight(),s=new te(n,o);this.initArrays(n);const a=this.buckets;for(let h=1;h<5;h++){const p=Math.floor(o*h/5),y=e.getRow(p,this.luminances),b=Math.floor(n*4/5);for(let I=Math.floor(n/5);I<b;I++){const R=y[I]&255;a[R>>ke.LUMINANCE_SHIFT]++}}const l=ke.estimateBlackPoint(a),u=e.getMatrix();for(let h=0;h<o;h++){const p=h*n;for(let y=0;y<n;y++)(u[p+y]&255)<l&&s.set(y,h)}return s}createBinarizer(e){return new ke(e)}initArrays(e){this.luminances.length<e&&(this.luminances=new Uint8ClampedArray(e));const n=this.buckets;for(let o=0;o<ke.LUMINANCE_BUCKETS;o++)n[o]=0}static estimateBlackPoint(e){const n=e.length;let o=0,s=0,a=0;for(let y=0;y<n;y++)e[y]>a&&(s=y,a=e[y]),e[y]>o&&(o=e[y]);let l=0,u=0;for(let y=0;y<n;y++){const b=y-s,I=e[y]*b*b;I>u&&(l=y,u=I)}if(s>l){const y=s;s=l,l=y}if(l-s<=n/16)throw new q;let h=l-1,p=-1;for(let y=l-1;y>s;y--){const b=y-s,I=b*b*(l-y)*(o-e[y]);I>p&&(h=y,p=I)}return h<<ke.LUMINANCE_SHIFT}}ke.LUMINANCE_BITS=5,ke.LUMINANCE_SHIFT=8-ke.LUMINANCE_BITS,ke.LUMINANCE_BUCKETS=1<<ke.LUMINANCE_BITS,ke.EMPTY=Uint8ClampedArray.from([0]);class le extends ke{constructor(e){super(e),this.matrix=null}getBlackMatrix(){if(this.matrix!==null)return this.matrix;const e=this.getLuminanceSource(),n=e.getWidth(),o=e.getHeight();if(n>=le.MINIMUM_DIMENSION&&o>=le.MINIMUM_DIMENSION){const s=e.getMatrix();let a=n>>le.BLOCK_SIZE_POWER;(n&le.BLOCK_SIZE_MASK)!==0&&a++;let l=o>>le.BLOCK_SIZE_POWER;(o&le.BLOCK_SIZE_MASK)!==0&&l++;const u=le.calculateBlackPoints(s,a,l,n,o),h=new te(n,o);le.calculateThresholdForBlock(s,a,l,n,o,u,h),this.matrix=h}else this.matrix=super.getBlackMatrix();return this.matrix}createBinarizer(e){return new le(e)}static calculateThresholdForBlock(e,n,o,s,a,l,u){const h=a-le.BLOCK_SIZE,p=s-le.BLOCK_SIZE;for(let y=0;y<o;y++){let b=y<<le.BLOCK_SIZE_POWER;b>h&&(b=h);const I=le.cap(y,2,o-3);for(let R=0;R<n;R++){let U=R<<le.BLOCK_SIZE_POWER;U>p&&(U=p);const V=le.cap(R,2,n-3);let H=0;for(let he=-2;he<=2;he++){const pe=l[I+he];H+=pe[V-2]+pe[V-1]+pe[V]+pe[V+1]+pe[V+2]}const Q=H/25;le.thresholdBlock(e,U,b,Q,s,u)}}}static cap(e,n,o){return e<n?n:e>o?o:e}static thresholdBlock(e,n,o,s,a,l){for(let u=0,h=o*a+n;u<le.BLOCK_SIZE;u++,h+=a)for(let p=0;p<le.BLOCK_SIZE;p++)(e[h+p]&255)<=s&&l.set(n+p,o+u)}static calculateBlackPoints(e,n,o,s,a){const l=a-le.BLOCK_SIZE,u=s-le.BLOCK_SIZE,h=new Array(o);for(let p=0;p<o;p++){h[p]=new Int32Array(n);let y=p<<le.BLOCK_SIZE_POWER;y>l&&(y=l);for(let b=0;b<n;b++){let I=b<<le.BLOCK_SIZE_POWER;I>u&&(I=u);let R=0,U=255,V=0;for(let Q=0,he=y*s+I;Q<le.BLOCK_SIZE;Q++,he+=s){for(let pe=0;pe<le.BLOCK_SIZE;pe++){const ce=e[he+pe]&255;R+=ce,ce<U&&(U=ce),ce>V&&(V=ce)}if(V-U>le.MIN_DYNAMIC_RANGE)for(Q++,he+=s;Q<le.BLOCK_SIZE;Q++,he+=s)for(let pe=0;pe<le.BLOCK_SIZE;pe++)R+=e[he+pe]&255}let H=R>>le.BLOCK_SIZE_POWER*2;if(V-U<=le.MIN_DYNAMIC_RANGE&&(H=U/2,p>0&&b>0)){const Q=(h[p-1][b]+2*h[p][b-1]+h[p-1][b-1])/4;U<Q&&(H=Q)}h[p][b]=H}}return h}}le.BLOCK_SIZE_POWER=3,le.BLOCK_SIZE=1<<le.BLOCK_SIZE_POWER,le.BLOCK_SIZE_MASK=le.BLOCK_SIZE-1,le.MINIMUM_DIMENSION=le.BLOCK_SIZE*5,le.MIN_DYNAMIC_RANGE=24;class Te{constructor(e,n){this.width=e,this.height=n}getWidth(){return this.width}getHeight(){return this.height}isCropSupported(){return!1}crop(e,n,o,s){throw new we("This luminance source does not support cropping.")}isRotateSupported(){return!1}rotateCounterClockwise(){throw new we("This luminance source does not support rotation by 90 degrees.")}rotateCounterClockwise45(){throw new we("This luminance source does not support rotation by 45 degrees.")}toString(){const e=new Uint8ClampedArray(this.width);let n=new fe;for(let o=0;o<this.height;o++){const s=this.getRow(o,e);for(let a=0;a<this.width;a++){const l=s[a]&255;let u;l<64?u="#":l<128?u="+":l<192?u=".":u=" ",n.append(u)}n.append(`
65
65
  `)}return n.toString()}}class Je extends Te{constructor(e){super(e.getWidth(),e.getHeight()),this.delegate=e}getRow(e,n){const o=this.delegate.getRow(e,n),s=this.getWidth();for(let a=0;a<s;a++)o[a]=255-(o[a]&255);return o}getMatrix(){const e=this.delegate.getMatrix(),n=this.getWidth()*this.getHeight(),o=new Uint8ClampedArray(n);for(let s=0;s<n;s++)o[s]=255-(e[s]&255);return o}isCropSupported(){return this.delegate.isCropSupported()}crop(e,n,o,s){return new Je(this.delegate.crop(e,n,o,s))}isRotateSupported(){return this.delegate.isRotateSupported()}invert(){return this.delegate}rotateCounterClockwise(){return new Je(this.delegate.rotateCounterClockwise())}rotateCounterClockwise45(){return new Je(this.delegate.rotateCounterClockwise45())}}class xe extends Te{constructor(e){super(e.width,e.height),this.canvas=e,this.tempCanvasElement=null,this.buffer=xe.makeBufferFromCanvasImageData(e)}static makeBufferFromCanvasImageData(e){const n=e.getContext("2d").getImageData(0,0,e.width,e.height);return xe.toGrayscaleBuffer(n.data,e.width,e.height)}static toGrayscaleBuffer(e,n,o){const s=new Uint8ClampedArray(n*o);for(let a=0,l=0,u=e.length;a<u;a+=4,l++){let h;if(e[a+3]===0)h=255;else{const y=e[a],b=e[a+1],I=e[a+2];h=306*y+601*b+117*I+512>>10}s[l]=h}return s}getRow(e,n){if(e<0||e>=this.getHeight())throw new A("Requested row is outside the image: "+e);const o=this.getWidth(),s=e*o;return n===null?n=this.buffer.slice(s,s+o):(n.length<o&&(n=new Uint8ClampedArray(o)),n.set(this.buffer.slice(s,s+o))),n}getMatrix(){return this.buffer}isCropSupported(){return!0}crop(e,n,o,s){return super.crop(e,n,o,s),this}isRotateSupported(){return!0}rotateCounterClockwise(){return this.rotate(-90),this}rotateCounterClockwise45(){return this.rotate(-45),this}getTempCanvasElement(){if(this.tempCanvasElement===null){const e=this.canvas.ownerDocument.createElement("canvas");e.width=this.canvas.width,e.height=this.canvas.height,this.tempCanvasElement=e}return this.tempCanvasElement}rotate(e){const n=this.getTempCanvasElement(),o=n.getContext("2d"),s=e*xe.DEGREE_TO_RADIANS,a=this.canvas.width,l=this.canvas.height,u=Math.ceil(Math.abs(Math.cos(s))*a+Math.abs(Math.sin(s))*l),h=Math.ceil(Math.abs(Math.sin(s))*a+Math.abs(Math.cos(s))*l);return n.width=u,n.height=h,o.translate(u/2,h/2),o.rotate(s),o.drawImage(this.canvas,a/-2,l/-2),this.buffer=xe.makeBufferFromCanvasImageData(n),this}invert(){return new Je(this)}}xe.DEGREE_TO_RADIANS=Math.PI/180;class $e{constructor(e,n,o){this.deviceId=e,this.label=n,this.kind="videoinput",this.groupId=o||void 0}toJSON(){return{kind:this.kind,groupId:this.groupId,deviceId:this.deviceId,label:this.label}}}var Ue=(globalThis||To||self||window||void 0)&&(globalThis||To||self||window||void 0).__awaiter||function(C,e,n,o){function s(a){return a instanceof n?a:new n(function(l){l(a)})}return new(n||(n=Promise))(function(a,l){function u(y){try{p(o.next(y))}catch(b){l(b)}}function h(y){try{p(o.throw(y))}catch(b){l(b)}}function p(y){y.done?a(y.value):s(y.value).then(u,h)}p((o=o.apply(C,e||[])).next())})};class Ze{constructor(e,n=500,o){this.reader=e,this.timeBetweenScansMillis=n,this._hints=o,this._stopContinuousDecode=!1,this._stopAsyncDecode=!1,this._timeBetweenDecodingAttempts=0}get hasNavigator(){return typeof navigator<"u"}get isMediaDevicesSuported(){return this.hasNavigator&&!!navigator.mediaDevices}get canEnumerateDevices(){return!!(this.isMediaDevicesSuported&&navigator.mediaDevices.enumerateDevices)}get timeBetweenDecodingAttempts(){return this._timeBetweenDecodingAttempts}set timeBetweenDecodingAttempts(e){this._timeBetweenDecodingAttempts=e<0?0:e}set hints(e){this._hints=e||null}get hints(){return this._hints}listVideoInputDevices(){return Ue(this,void 0,void 0,function*(){if(!this.hasNavigator)throw new Error("Can't enumerate devices, navigator is not present.");if(!this.canEnumerateDevices)throw new Error("Can't enumerate devices, method not supported.");const e=yield navigator.mediaDevices.enumerateDevices(),n=[];for(const o of e){const s=o.kind==="video"?"videoinput":o.kind;if(s!=="videoinput")continue;const a=o.deviceId||o.id,l=o.label||`Video device ${n.length+1}`,u=o.groupId,h={deviceId:a,label:l,kind:s,groupId:u};n.push(h)}return n})}getVideoInputDevices(){return Ue(this,void 0,void 0,function*(){return(yield this.listVideoInputDevices()).map(n=>new $e(n.deviceId,n.label))})}findDeviceById(e){return Ue(this,void 0,void 0,function*(){const n=yield this.listVideoInputDevices();return n?n.find(o=>o.deviceId===e):null})}decodeFromInputVideoDevice(e,n){return Ue(this,void 0,void 0,function*(){return yield this.decodeOnceFromVideoDevice(e,n)})}decodeOnceFromVideoDevice(e,n){return Ue(this,void 0,void 0,function*(){this.reset();let o;e?o={deviceId:{exact:e}}:o={facingMode:"environment"};const s={video:o};return yield this.decodeOnceFromConstraints(s,n)})}decodeOnceFromConstraints(e,n){return Ue(this,void 0,void 0,function*(){const o=yield navigator.mediaDevices.getUserMedia(e);return yield this.decodeOnceFromStream(o,n)})}decodeOnceFromStream(e,n){return Ue(this,void 0,void 0,function*(){this.reset();const o=yield this.attachStreamToVideo(e,n);return yield this.decodeOnce(o)})}decodeFromInputVideoDeviceContinuously(e,n,o){return Ue(this,void 0,void 0,function*(){return yield this.decodeFromVideoDevice(e,n,o)})}decodeFromVideoDevice(e,n,o){return Ue(this,void 0,void 0,function*(){let s;e?s={deviceId:{exact:e}}:s={facingMode:"environment"};const a={video:s};return yield this.decodeFromConstraints(a,n,o)})}decodeFromConstraints(e,n,o){return Ue(this,void 0,void 0,function*(){const s=yield navigator.mediaDevices.getUserMedia(e);return yield this.decodeFromStream(s,n,o)})}decodeFromStream(e,n,o){return Ue(this,void 0,void 0,function*(){this.reset();const s=yield this.attachStreamToVideo(e,n);return yield this.decodeContinuously(s,o)})}stopAsyncDecode(){this._stopAsyncDecode=!0}stopContinuousDecode(){this._stopContinuousDecode=!0}attachStreamToVideo(e,n){return Ue(this,void 0,void 0,function*(){const o=this.prepareVideoElement(n);return this.addVideoSource(o,e),this.videoElement=o,this.stream=e,yield this.playVideoOnLoadAsync(o),o})}playVideoOnLoadAsync(e){return new Promise((n,o)=>this.playVideoOnLoad(e,()=>n()))}playVideoOnLoad(e,n){this.videoEndedListener=()=>this.stopStreams(),this.videoCanPlayListener=()=>this.tryPlayVideo(e),e.addEventListener("ended",this.videoEndedListener),e.addEventListener("canplay",this.videoCanPlayListener),e.addEventListener("playing",n),this.tryPlayVideo(e)}isVideoPlaying(e){return e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>2}tryPlayVideo(e){return Ue(this,void 0,void 0,function*(){if(this.isVideoPlaying(e)){console.warn("Trying to play video that is already playing.");return}try{yield e.play()}catch{console.warn("It was not possible to play the video.")}})}getMediaElement(e,n){const o=document.getElementById(e);if(!o)throw new E(`element with id '${e}' not found`);if(o.nodeName.toLowerCase()!==n.toLowerCase())throw new E(`element with id '${e}' must be an ${n} element`);return o}decodeFromImage(e,n){if(!e&&!n)throw new E("either imageElement with a src set or an url must be provided");return n&&!e?this.decodeFromImageUrl(n):this.decodeFromImageElement(e)}decodeFromVideo(e,n){if(!e&&!n)throw new E("Either an element with a src set or an URL must be provided");return n&&!e?this.decodeFromVideoUrl(n):this.decodeFromVideoElement(e)}decodeFromVideoContinuously(e,n,o){if(e===void 0&&n===void 0)throw new E("Either an element with a src set or an URL must be provided");return n&&!e?this.decodeFromVideoUrlContinuously(n,o):this.decodeFromVideoElementContinuously(e,o)}decodeFromImageElement(e){if(!e)throw new E("An image element must be provided.");this.reset();const n=this.prepareImageElement(e);this.imageElement=n;let o;return this.isImageLoaded(n)?o=this.decodeOnce(n,!1,!0):o=this._decodeOnLoadImage(n),o}decodeFromVideoElement(e){const n=this._decodeFromVideoElementSetup(e);return this._decodeOnLoadVideo(n)}decodeFromVideoElementContinuously(e,n){const o=this._decodeFromVideoElementSetup(e);return this._decodeOnLoadVideoContinuously(o,n)}_decodeFromVideoElementSetup(e){if(!e)throw new E("A video element must be provided.");this.reset();const n=this.prepareVideoElement(e);return this.videoElement=n,n}decodeFromImageUrl(e){if(!e)throw new E("An URL must be provided.");this.reset();const n=this.prepareImageElement();this.imageElement=n;const o=this._decodeOnLoadImage(n);return n.src=e,o}decodeFromVideoUrl(e){if(!e)throw new E("An URL must be provided.");this.reset();const n=this.prepareVideoElement(),o=this.decodeFromVideoElement(n);return n.src=e,o}decodeFromVideoUrlContinuously(e,n){if(!e)throw new E("An URL must be provided.");this.reset();const o=this.prepareVideoElement(),s=this.decodeFromVideoElementContinuously(o,n);return o.src=e,s}_decodeOnLoadImage(e){return new Promise((n,o)=>{this.imageLoadedListener=()=>this.decodeOnce(e,!1,!0).then(n,o),e.addEventListener("load",this.imageLoadedListener)})}_decodeOnLoadVideo(e){return Ue(this,void 0,void 0,function*(){return yield this.playVideoOnLoadAsync(e),yield this.decodeOnce(e)})}_decodeOnLoadVideoContinuously(e,n){return Ue(this,void 0,void 0,function*(){yield this.playVideoOnLoadAsync(e),this.decodeContinuously(e,n)})}isImageLoaded(e){return!(!e.complete||e.naturalWidth===0)}prepareImageElement(e){let n;return typeof e>"u"&&(n=document.createElement("img"),n.width=200,n.height=200),typeof e=="string"&&(n=this.getMediaElement(e,"img")),e instanceof HTMLImageElement&&(n=e),n}prepareVideoElement(e){let n;return!e&&typeof document<"u"&&(n=document.createElement("video"),n.width=200,n.height=200),typeof e=="string"&&(n=this.getMediaElement(e,"video")),e instanceof HTMLVideoElement&&(n=e),n.setAttribute("autoplay","true"),n.setAttribute("muted","true"),n.setAttribute("playsinline","true"),n}decodeOnce(e,n=!0,o=!0){this._stopAsyncDecode=!1;const s=(a,l)=>{if(this._stopAsyncDecode){l(new q("Video stream has ended before any code could be detected.")),this._stopAsyncDecode=void 0;return}try{const u=this.decode(e);a(u)}catch(u){const h=n&&u instanceof q,y=(u instanceof T||u instanceof L)&&o;if(h||y)return setTimeout(s,this._timeBetweenDecodingAttempts,a,l);l(u)}};return new Promise((a,l)=>s(a,l))}decodeContinuously(e,n){this._stopContinuousDecode=!1;const o=()=>{if(this._stopContinuousDecode){this._stopContinuousDecode=void 0;return}try{const s=this.decode(e);n(s,null),setTimeout(o,this.timeBetweenScansMillis)}catch(s){n(null,s);const a=s instanceof T||s instanceof L,l=s instanceof q;(a||l)&&setTimeout(o,this._timeBetweenDecodingAttempts)}};o()}decode(e){const n=this.createBinaryBitmap(e);return this.decodeBitmap(n)}_isHTMLVideoElement(e){return e.videoWidth!==0}drawFrameOnCanvas(e,n,o){n||(n={sx:0,sy:0,sWidth:e.videoWidth,sHeight:e.videoHeight,dx:0,dy:0,dWidth:e.videoWidth,dHeight:e.videoHeight}),o||(o=this.captureCanvasContext),o.drawImage(e,n.sx,n.sy,n.sWidth,n.sHeight,n.dx,n.dy,n.dWidth,n.dHeight)}drawImageOnCanvas(e,n,o=this.captureCanvasContext){n||(n={sx:0,sy:0,sWidth:e.naturalWidth,sHeight:e.naturalHeight,dx:0,dy:0,dWidth:e.naturalWidth,dHeight:e.naturalHeight}),o||(o=this.captureCanvasContext),o.drawImage(e,n.sx,n.sy,n.sWidth,n.sHeight,n.dx,n.dy,n.dWidth,n.dHeight)}createBinaryBitmap(e){this.getCaptureCanvasContext(e),this._isHTMLVideoElement(e)?this.drawFrameOnCanvas(e):this.drawImageOnCanvas(e);const n=this.getCaptureCanvas(e),o=new xe(n),s=new le(o);return new D(s)}getCaptureCanvasContext(e){if(!this.captureCanvasContext){const o=this.getCaptureCanvas(e).getContext("2d");this.captureCanvasContext=o}return this.captureCanvasContext}getCaptureCanvas(e){if(!this.captureCanvas){const n=this.createCaptureCanvas(e);this.captureCanvas=n}return this.captureCanvas}decodeBitmap(e){return this.reader.decode(e,this._hints)}createCaptureCanvas(e){if(typeof document>"u")return this._destroyCaptureCanvas(),null;const n=document.createElement("canvas");let o,s;return typeof e<"u"&&(e instanceof HTMLVideoElement?(o=e.videoWidth,s=e.videoHeight):e instanceof HTMLImageElement&&(o=e.naturalWidth||e.width,s=e.naturalHeight||e.height)),n.style.width=o+"px",n.style.height=s+"px",n.width=o,n.height=s,n}stopStreams(){this.stream&&(this.stream.getVideoTracks().forEach(e=>e.stop()),this.stream=void 0),this._stopAsyncDecode===!1&&this.stopAsyncDecode(),this._stopContinuousDecode===!1&&this.stopContinuousDecode()}reset(){this.stopStreams(),this._destroyVideoElement(),this._destroyImageElement(),this._destroyCaptureCanvas()}_destroyVideoElement(){this.videoElement&&(typeof this.videoEndedListener<"u"&&this.videoElement.removeEventListener("ended",this.videoEndedListener),typeof this.videoPlayingEventListener<"u"&&this.videoElement.removeEventListener("playing",this.videoPlayingEventListener),typeof this.videoCanPlayListener<"u"&&this.videoElement.removeEventListener("loadedmetadata",this.videoCanPlayListener),this.cleanVideoSource(this.videoElement),this.videoElement=void 0)}_destroyImageElement(){this.imageElement&&(this.imageLoadedListener!==void 0&&this.imageElement.removeEventListener("load",this.imageLoadedListener),this.imageElement.src=void 0,this.imageElement.removeAttribute("src"),this.imageElement=void 0)}_destroyCaptureCanvas(){this.captureCanvasContext=void 0,this.captureCanvas=void 0}addVideoSource(e,n){try{e.srcObject=n}catch{e.src=URL.createObjectURL(n)}}cleanVideoSource(e){try{e.srcObject=null}catch{e.src=""}this.videoElement.removeAttribute("src")}}class qe{constructor(e,n,o=n==null?0:8*n.length,s,a,l=P.currentTimeMillis()){this.text=e,this.rawBytes=n,this.numBits=o,this.resultPoints=s,this.format=a,this.timestamp=l,this.text=e,this.rawBytes=n,o==null?this.numBits=n==null?0:8*n.length:this.numBits=o,this.resultPoints=s,this.format=a,this.resultMetadata=null,l==null?this.timestamp=P.currentTimeMillis():this.timestamp=l}getText(){return this.text}getRawBytes(){return this.rawBytes}getNumBits(){return this.numBits}getResultPoints(){return this.resultPoints}getBarcodeFormat(){return this.format}getResultMetadata(){return this.resultMetadata}putMetadata(e,n){this.resultMetadata===null&&(this.resultMetadata=new Map),this.resultMetadata.set(e,n)}putAllMetadata(e){e!==null&&(this.resultMetadata===null?this.resultMetadata=e:this.resultMetadata=new Map(e))}addResultPoints(e){const n=this.resultPoints;if(n===null)this.resultPoints=e;else if(e!==null&&e.length>0){const o=new Array(n.length+e.length);P.arraycopy(n,0,o,0,n.length),P.arraycopy(e,0,o,n.length,e.length),this.resultPoints=o}}getTimestamp(){return this.timestamp}toString(){return this.text}}var ze;(function(C){C[C.AZTEC=0]="AZTEC",C[C.CODABAR=1]="CODABAR",C[C.CODE_39=2]="CODE_39",C[C.CODE_93=3]="CODE_93",C[C.CODE_128=4]="CODE_128",C[C.DATA_MATRIX=5]="DATA_MATRIX",C[C.EAN_8=6]="EAN_8",C[C.EAN_13=7]="EAN_13",C[C.ITF=8]="ITF",C[C.MAXICODE=9]="MAXICODE",C[C.PDF_417=10]="PDF_417",C[C.QR_CODE=11]="QR_CODE",C[C.RSS_14=12]="RSS_14",C[C.RSS_EXPANDED=13]="RSS_EXPANDED",C[C.UPC_A=14]="UPC_A",C[C.UPC_E=15]="UPC_E",C[C.UPC_EAN_EXTENSION=16]="UPC_EAN_EXTENSION"})(ze||(ze={}));var ie=ze,de;(function(C){C[C.OTHER=0]="OTHER",C[C.ORIENTATION=1]="ORIENTATION",C[C.BYTE_SEGMENTS=2]="BYTE_SEGMENTS",C[C.ERROR_CORRECTION_LEVEL=3]="ERROR_CORRECTION_LEVEL",C[C.ISSUE_NUMBER=4]="ISSUE_NUMBER",C[C.SUGGESTED_PRICE=5]="SUGGESTED_PRICE",C[C.POSSIBLE_COUNTRY=6]="POSSIBLE_COUNTRY",C[C.UPC_EAN_EXTENSION=7]="UPC_EAN_EXTENSION",C[C.PDF417_EXTRA_METADATA=8]="PDF417_EXTRA_METADATA",C[C.STRUCTURED_APPEND_SEQUENCE=9]="STRUCTURED_APPEND_SEQUENCE",C[C.STRUCTURED_APPEND_PARITY=10]="STRUCTURED_APPEND_PARITY"})(de||(de={}));var _e=de;class Pe{constructor(e,n,o,s,a=-1,l=-1){this.rawBytes=e,this.text=n,this.byteSegments=o,this.ecLevel=s,this.structuredAppendSequenceNumber=a,this.structuredAppendParity=l,this.numBits=e==null?0:8*e.length}getRawBytes(){return this.rawBytes}getNumBits(){return this.numBits}setNumBits(e){this.numBits=e}getText(){return this.text}getByteSegments(){return this.byteSegments}getECLevel(){return this.ecLevel}getErrorsCorrected(){return this.errorsCorrected}setErrorsCorrected(e){this.errorsCorrected=e}getErasures(){return this.erasures}setErasures(e){this.erasures=e}getOther(){return this.other}setOther(e){this.other=e}hasStructuredAppend(){return this.structuredAppendParity>=0&&this.structuredAppendSequenceNumber>=0}getStructuredAppendParity(){return this.structuredAppendParity}getStructuredAppendSequenceNumber(){return this.structuredAppendSequenceNumber}}class ae{exp(e){return this.expTable[e]}log(e){if(e===0)throw new A;return this.logTable[e]}static addOrSubtract(e,n){return e^n}}class J{constructor(e,n){if(n.length===0)throw new A;this.field=e;const o=n.length;if(o>1&&n[0]===0){let s=1;for(;s<o&&n[s]===0;)s++;s===o?this.coefficients=Int32Array.from([0]):(this.coefficients=new Int32Array(o-s),P.arraycopy(n,s,this.coefficients,0,this.coefficients.length))}else this.coefficients=n}getCoefficients(){return this.coefficients}getDegree(){return this.coefficients.length-1}isZero(){return this.coefficients[0]===0}getCoefficient(e){return this.coefficients[this.coefficients.length-1-e]}evaluateAt(e){if(e===0)return this.getCoefficient(0);const n=this.coefficients;let o;if(e===1){o=0;for(let l=0,u=n.length;l!==u;l++){const h=n[l];o=ae.addOrSubtract(o,h)}return o}o=n[0];const s=n.length,a=this.field;for(let l=1;l<s;l++)o=ae.addOrSubtract(a.multiply(e,o),n[l]);return o}addOrSubtract(e){if(!this.field.equals(e.field))throw new A("GenericGFPolys do not have same GenericGF field");if(this.isZero())return e;if(e.isZero())return this;let n=this.coefficients,o=e.coefficients;if(n.length>o.length){const l=n;n=o,o=l}let s=new Int32Array(o.length);const a=o.length-n.length;P.arraycopy(o,0,s,0,a);for(let l=a;l<o.length;l++)s[l]=ae.addOrSubtract(n[l-a],o[l]);return new J(this.field,s)}multiply(e){if(!this.field.equals(e.field))throw new A("GenericGFPolys do not have same GenericGF field");if(this.isZero()||e.isZero())return this.field.getZero();const n=this.coefficients,o=n.length,s=e.coefficients,a=s.length,l=new Int32Array(o+a-1),u=this.field;for(let h=0;h<o;h++){const p=n[h];for(let y=0;y<a;y++)l[h+y]=ae.addOrSubtract(l[h+y],u.multiply(p,s[y]))}return new J(u,l)}multiplyScalar(e){if(e===0)return this.field.getZero();if(e===1)return this;const n=this.coefficients.length,o=this.field,s=new Int32Array(n),a=this.coefficients;for(let l=0;l<n;l++)s[l]=o.multiply(a[l],e);return new J(o,s)}multiplyByMonomial(e,n){if(e<0)throw new A;if(n===0)return this.field.getZero();const o=this.coefficients,s=o.length,a=new Int32Array(s+e),l=this.field;for(let u=0;u<s;u++)a[u]=l.multiply(o[u],n);return new J(l,a)}divide(e){if(!this.field.equals(e.field))throw new A("GenericGFPolys do not have same GenericGF field");if(e.isZero())throw new A("Divide by 0");const n=this.field;let o=n.getZero(),s=this;const a=e.getCoefficient(e.getDegree()),l=n.inverse(a);for(;s.getDegree()>=e.getDegree()&&!s.isZero();){const u=s.getDegree()-e.getDegree(),h=n.multiply(s.getCoefficient(s.getDegree()),l),p=e.multiplyByMonomial(u,h),y=n.buildMonomial(u,h);o=o.addOrSubtract(y),s=s.addOrSubtract(p)}return[o,s]}toString(){let e="";for(let n=this.getDegree();n>=0;n--){let o=this.getCoefficient(n);if(o!==0){if(o<0?(e+=" - ",o=-o):e.length>0&&(e+=" + "),n===0||o!==1){const s=this.field.log(o);s===0?e+="1":s===1?e+="a":(e+="a^",e+=s)}n!==0&&(n===1?e+="x":(e+="x^",e+=n))}}return e}}class ye extends g{}ye.kind="ArithmeticException";class Se extends ae{constructor(e,n,o){super(),this.primitive=e,this.size=n,this.generatorBase=o;const s=new Int32Array(n);let a=1;for(let u=0;u<n;u++)s[u]=a,a*=2,a>=n&&(a^=e,a&=n-1);this.expTable=s;const l=new Int32Array(n);for(let u=0;u<n-1;u++)l[s[u]]=u;this.logTable=l,this.zero=new J(this,Int32Array.from([0])),this.one=new J(this,Int32Array.from([1]))}getZero(){return this.zero}getOne(){return this.one}buildMonomial(e,n){if(e<0)throw new A;if(n===0)return this.zero;const o=new Int32Array(e+1);return o[0]=n,new J(this,o)}inverse(e){if(e===0)throw new ye;return this.expTable[this.size-this.logTable[e]-1]}multiply(e,n){return e===0||n===0?0:this.expTable[(this.logTable[e]+this.logTable[n])%(this.size-1)]}getSize(){return this.size}getGeneratorBase(){return this.generatorBase}toString(){return"GF(0x"+F.toHexString(this.primitive)+","+this.size+")"}equals(e){return e===this}}Se.AZTEC_DATA_12=new Se(4201,4096,1),Se.AZTEC_DATA_10=new Se(1033,1024,1),Se.AZTEC_DATA_6=new Se(67,64,1),Se.AZTEC_PARAM=new Se(19,16,1),Se.QR_CODE_FIELD_256=new Se(285,256,0),Se.DATA_MATRIX_FIELD_256=new Se(301,256,1),Se.AZTEC_DATA_8=Se.DATA_MATRIX_FIELD_256,Se.MAXICODE_FIELD_64=Se.AZTEC_DATA_6;class Ve extends g{}Ve.kind="ReedSolomonException";class St extends g{}St.kind="IllegalStateException";class vt{constructor(e){this.field=e}decode(e,n){const o=this.field,s=new J(o,e),a=new Int32Array(n);let l=!0;for(let R=0;R<n;R++){const U=s.evaluateAt(o.exp(R+o.getGeneratorBase()));a[a.length-1-R]=U,U!==0&&(l=!1)}if(l)return;const u=new J(o,a),h=this.runEuclideanAlgorithm(o.buildMonomial(n,1),u,n),p=h[0],y=h[1],b=this.findErrorLocations(p),I=this.findErrorMagnitudes(y,b);for(let R=0;R<b.length;R++){const U=e.length-1-o.log(b[R]);if(U<0)throw new Ve("Bad error location");e[U]=Se.addOrSubtract(e[U],I[R])}}runEuclideanAlgorithm(e,n,o){if(e.getDegree()<n.getDegree()){const R=e;e=n,n=R}const s=this.field;let a=e,l=n,u=s.getZero(),h=s.getOne();for(;l.getDegree()>=(o/2|0);){let R=a,U=u;if(a=l,u=h,a.isZero())throw new Ve("r_{i-1} was zero");l=R;let V=s.getZero();const H=a.getCoefficient(a.getDegree()),Q=s.inverse(H);for(;l.getDegree()>=a.getDegree()&&!l.isZero();){const he=l.getDegree()-a.getDegree(),pe=s.multiply(l.getCoefficient(l.getDegree()),Q);V=V.addOrSubtract(s.buildMonomial(he,pe)),l=l.addOrSubtract(a.multiplyByMonomial(he,pe))}if(h=V.multiply(u).addOrSubtract(U),l.getDegree()>=a.getDegree())throw new St("Division algorithm failed to reduce polynomial?")}const p=h.getCoefficient(0);if(p===0)throw new Ve("sigmaTilde(0) was zero");const y=s.inverse(p),b=h.multiplyScalar(y),I=l.multiplyScalar(y);return[b,I]}findErrorLocations(e){const n=e.getDegree();if(n===1)return Int32Array.from([e.getCoefficient(1)]);const o=new Int32Array(n);let s=0;const a=this.field;for(let l=1;l<a.getSize()&&s<n;l++)e.evaluateAt(l)===0&&(o[s]=a.inverse(l),s++);if(s!==n)throw new Ve("Error locator degree does not match number of roots");return o}findErrorMagnitudes(e,n){const o=n.length,s=new Int32Array(o),a=this.field;for(let l=0;l<o;l++){const u=a.inverse(n[l]);let h=1;for(let p=0;p<o;p++)if(l!==p){const y=a.multiply(n[p],u),b=(y&1)===0?y|1:y&-2;h=a.multiply(h,b)}s[l]=a.multiply(e.evaluateAt(u),a.inverse(h)),a.getGeneratorBase()!==0&&(s[l]=a.multiply(s[l],u))}return s}}var et;(function(C){C[C.UPPER=0]="UPPER",C[C.LOWER=1]="LOWER",C[C.MIXED=2]="MIXED",C[C.DIGIT=3]="DIGIT",C[C.PUNCT=4]="PUNCT",C[C.BINARY=5]="BINARY"})(et||(et={}));class nt{decode(e){this.ddata=e;let n=e.getBits(),o=this.extractBits(n),s=this.correctBits(o),a=nt.convertBoolArrayToByteArray(s),l=nt.getEncodedData(s),u=new Pe(a,l,null,null);return u.setNumBits(s.length),u}static highLevelDecode(e){return this.getEncodedData(e)}static getEncodedData(e){let n=e.length,o=et.UPPER,s=et.UPPER,a="",l=0;for(;l<n;)if(s===et.BINARY){if(n-l<5)break;let u=nt.readCode(e,l,5);if(l+=5,u===0){if(n-l<11)break;u=nt.readCode(e,l,11)+31,l+=11}for(let h=0;h<u;h++){if(n-l<8){l=n;break}const p=nt.readCode(e,l,8);a+=me.castAsNonUtf8Char(p),l+=8}s=o}else{let u=s===et.DIGIT?4:5;if(n-l<u)break;let h=nt.readCode(e,l,u);l+=u;let p=nt.getCharacter(s,h);p.startsWith("CTRL_")?(o=s,s=nt.getTable(p.charAt(5)),p.charAt(6)==="L"&&(o=s)):(a+=p,s=o)}return a}static getTable(e){switch(e){case"L":return et.LOWER;case"P":return et.PUNCT;case"M":return et.MIXED;case"D":return et.DIGIT;case"B":return et.BINARY;case"U":default:return et.UPPER}}static getCharacter(e,n){switch(e){case et.UPPER:return nt.UPPER_TABLE[n];case et.LOWER:return nt.LOWER_TABLE[n];case et.MIXED:return nt.MIXED_TABLE[n];case et.PUNCT:return nt.PUNCT_TABLE[n];case et.DIGIT:return nt.DIGIT_TABLE[n];default:throw new St("Bad table")}}correctBits(e){let n,o;this.ddata.getNbLayers()<=2?(o=6,n=Se.AZTEC_DATA_6):this.ddata.getNbLayers()<=8?(o=8,n=Se.AZTEC_DATA_8):this.ddata.getNbLayers()<=22?(o=10,n=Se.AZTEC_DATA_10):(o=12,n=Se.AZTEC_DATA_12);let s=this.ddata.getNbDatablocks(),a=e.length/o;if(a<s)throw new L;let l=e.length%o,u=new Int32Array(a);for(let I=0;I<a;I++,l+=o)u[I]=nt.readCode(e,l,o);try{new vt(n).decode(u,a-s)}catch(I){throw new L(I)}let h=(1<<o)-1,p=0;for(let I=0;I<s;I++){let R=u[I];if(R===0||R===h)throw new L;(R===1||R===h-1)&&p++}let y=new Array(s*o-p),b=0;for(let I=0;I<s;I++){let R=u[I];if(R===1||R===h-1)y.fill(R>1,b,b+o-1),b+=o-1;else for(let U=o-1;U>=0;--U)y[b++]=(R&1<<U)!==0}return y}extractBits(e){let n=this.ddata.isCompact(),o=this.ddata.getNbLayers(),s=(n?11:14)+o*4,a=new Int32Array(s),l=new Array(this.totalBitsInLayer(o,n));if(n)for(let u=0;u<a.length;u++)a[u]=u;else{let u=s+1+2*F.truncDivision(F.truncDivision(s,2)-1,15),h=s/2,p=F.truncDivision(u,2);for(let y=0;y<h;y++){let b=y+F.truncDivision(y,15);a[h-y-1]=p-b-1,a[h+y]=p+b+1}}for(let u=0,h=0;u<o;u++){let p=(o-u)*4+(n?9:12),y=u*2,b=s-1-y;for(let I=0;I<p;I++){let R=I*2;for(let U=0;U<2;U++)l[h+R+U]=e.get(a[y+U],a[y+I]),l[h+2*p+R+U]=e.get(a[y+I],a[b-U]),l[h+4*p+R+U]=e.get(a[b-U],a[b-I]),l[h+6*p+R+U]=e.get(a[b-I],a[y+U])}h+=p*8}return l}static readCode(e,n,o){let s=0;for(let a=n;a<n+o;a++)s<<=1,e[a]&&(s|=1);return s}static readByte(e,n){let o=e.length-n;return o>=8?nt.readCode(e,n,8):nt.readCode(e,n,o)<<8-o}static convertBoolArrayToByteArray(e){let n=new Uint8Array((e.length+7)/8);for(let o=0;o<n.length;o++)n[o]=nt.readByte(e,8*o);return n}totalBitsInLayer(e,n){return((n?88:112)+16*e)*e}}nt.UPPER_TABLE=["CTRL_PS"," ","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","CTRL_LL","CTRL_ML","CTRL_DL","CTRL_BS"],nt.LOWER_TABLE=["CTRL_PS"," ","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","CTRL_US","CTRL_ML","CTRL_DL","CTRL_BS"],nt.MIXED_TABLE=["CTRL_PS"," ","\\1","\\2","\\3","\\4","\\5","\\6","\\7","\b"," ",`
@@ -78,7 +78,7 @@ ${this.tempPrompt}
78
78
  `),e.append(`>>
79
79
  `),e.toString()}setMode(e){this.mode=e}setECLevel(e){this.ecLevel=e}setVersion(e){this.version=e}setMaskPattern(e){this.maskPattern=e}setMatrix(e){this.matrix=e}static isValidMaskPattern(e){return e>=0&&e<lr.NUM_MASK_PATTERNS}}lr.NUM_MASK_PATTERNS=8;class dt extends g{}dt.kind="WriterException";class De{constructor(){}static clearMatrix(e){e.clear(255)}static buildMatrix(e,n,o,s,a){De.clearMatrix(a),De.embedBasicPatterns(o,a),De.embedTypeInfo(n,s,a),De.maybeEmbedVersionInfo(o,a),De.embedDataBits(e,s,a)}static embedBasicPatterns(e,n){De.embedPositionDetectionPatternsAndSeparators(n),De.embedDarkDotAtLeftBottomCorner(n),De.maybeEmbedPositionAdjustmentPatterns(e,n),De.embedTimingPatterns(n)}static embedTypeInfo(e,n,o){const s=new re;De.makeTypeInfoBits(e,n,s);for(let a=0,l=s.getSize();a<l;++a){const u=s.get(s.getSize()-1-a),h=De.TYPE_INFO_COORDINATES[a],p=h[0],y=h[1];if(o.setBoolean(p,y,u),a<8){const b=o.getWidth()-a-1;o.setBoolean(b,8,u)}else{const I=o.getHeight()-7+(a-8);o.setBoolean(8,I,u)}}}static maybeEmbedVersionInfo(e,n){if(e.getVersionNumber()<7)return;const o=new re;De.makeVersionInfoBits(e,o);let s=17;for(let a=0;a<6;++a)for(let l=0;l<3;++l){const u=o.get(s);s--,n.setBoolean(a,n.getHeight()-11+l,u),n.setBoolean(n.getHeight()-11+l,a,u)}}static embedDataBits(e,n,o){let s=0,a=-1,l=o.getWidth()-1,u=o.getHeight()-1;for(;l>0;){for(l===6&&(l-=1);u>=0&&u<o.getHeight();){for(let h=0;h<2;++h){const p=l-h;if(!De.isEmpty(o.get(p,u)))continue;let y;s<e.getSize()?(y=e.get(s),++s):y=!1,n!==255&&Nt.getDataMaskBit(n,p,u)&&(y=!y),o.setBoolean(p,u,y)}u+=a}a=-a,u+=a,l-=2}if(s!==e.getSize())throw new dt("Not all bits consumed: "+s+"/"+e.getSize())}static findMSBSet(e){return 32-F.numberOfLeadingZeros(e)}static calculateBCHCode(e,n){if(n===0)throw new A("0 polynomial");const o=De.findMSBSet(n);for(e<<=o-1;De.findMSBSet(e)>=o;)e^=n<<De.findMSBSet(e)-o;return e}static makeTypeInfoBits(e,n,o){if(!lr.isValidMaskPattern(n))throw new dt("Invalid mask pattern");const s=e.getBits()<<3|n;o.appendBits(s,5);const a=De.calculateBCHCode(s,De.TYPE_INFO_POLY);o.appendBits(a,10);const l=new re;if(l.appendBits(De.TYPE_INFO_MASK_PATTERN,15),o.xor(l),o.getSize()!==15)throw new dt("should not happen but we got: "+o.getSize())}static makeVersionInfoBits(e,n){n.appendBits(e.getVersionNumber(),6);const o=De.calculateBCHCode(e.getVersionNumber(),De.VERSION_INFO_POLY);if(n.appendBits(o,12),n.getSize()!==18)throw new dt("should not happen but we got: "+n.getSize())}static isEmpty(e){return e===255}static embedTimingPatterns(e){for(let n=8;n<e.getWidth()-8;++n){const o=(n+1)%2;De.isEmpty(e.get(n,6))&&e.setNumber(n,6,o),De.isEmpty(e.get(6,n))&&e.setNumber(6,n,o)}}static embedDarkDotAtLeftBottomCorner(e){if(e.get(8,e.getHeight()-8)===0)throw new dt;e.setNumber(8,e.getHeight()-8,1)}static embedHorizontalSeparationPattern(e,n,o){for(let s=0;s<8;++s){if(!De.isEmpty(o.get(e+s,n)))throw new dt;o.setNumber(e+s,n,0)}}static embedVerticalSeparationPattern(e,n,o){for(let s=0;s<7;++s){if(!De.isEmpty(o.get(e,n+s)))throw new dt;o.setNumber(e,n+s,0)}}static embedPositionAdjustmentPattern(e,n,o){for(let s=0;s<5;++s){const a=De.POSITION_ADJUSTMENT_PATTERN[s];for(let l=0;l<5;++l)o.setNumber(e+l,n+s,a[l])}}static embedPositionDetectionPattern(e,n,o){for(let s=0;s<7;++s){const a=De.POSITION_DETECTION_PATTERN[s];for(let l=0;l<7;++l)o.setNumber(e+l,n+s,a[l])}}static embedPositionDetectionPatternsAndSeparators(e){const n=De.POSITION_DETECTION_PATTERN[0].length;De.embedPositionDetectionPattern(0,0,e),De.embedPositionDetectionPattern(e.getWidth()-n,0,e),De.embedPositionDetectionPattern(0,e.getWidth()-n,e);const o=8;De.embedHorizontalSeparationPattern(0,o-1,e),De.embedHorizontalSeparationPattern(e.getWidth()-o,o-1,e),De.embedHorizontalSeparationPattern(0,e.getWidth()-o,e);const s=7;De.embedVerticalSeparationPattern(s,0,e),De.embedVerticalSeparationPattern(e.getHeight()-s-1,0,e),De.embedVerticalSeparationPattern(s,e.getHeight()-s,e)}static maybeEmbedPositionAdjustmentPatterns(e,n){if(e.getVersionNumber()<2)return;const o=e.getVersionNumber()-1,s=De.POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[o];for(let a=0,l=s.length;a!==l;a++){const u=s[a];if(u>=0)for(let h=0;h!==l;h++){const p=s[h];p>=0&&De.isEmpty(n.get(p,u))&&De.embedPositionAdjustmentPattern(p-2,u-2,n)}}}}De.POSITION_DETECTION_PATTERN=Array.from([Int32Array.from([1,1,1,1,1,1,1]),Int32Array.from([1,0,0,0,0,0,1]),Int32Array.from([1,0,1,1,1,0,1]),Int32Array.from([1,0,1,1,1,0,1]),Int32Array.from([1,0,1,1,1,0,1]),Int32Array.from([1,0,0,0,0,0,1]),Int32Array.from([1,1,1,1,1,1,1])]),De.POSITION_ADJUSTMENT_PATTERN=Array.from([Int32Array.from([1,1,1,1,1]),Int32Array.from([1,0,0,0,1]),Int32Array.from([1,0,1,0,1]),Int32Array.from([1,0,0,0,1]),Int32Array.from([1,1,1,1,1])]),De.POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE=Array.from([Int32Array.from([-1,-1,-1,-1,-1,-1,-1]),Int32Array.from([6,18,-1,-1,-1,-1,-1]),Int32Array.from([6,22,-1,-1,-1,-1,-1]),Int32Array.from([6,26,-1,-1,-1,-1,-1]),Int32Array.from([6,30,-1,-1,-1,-1,-1]),Int32Array.from([6,34,-1,-1,-1,-1,-1]),Int32Array.from([6,22,38,-1,-1,-1,-1]),Int32Array.from([6,24,42,-1,-1,-1,-1]),Int32Array.from([6,26,46,-1,-1,-1,-1]),Int32Array.from([6,28,50,-1,-1,-1,-1]),Int32Array.from([6,30,54,-1,-1,-1,-1]),Int32Array.from([6,32,58,-1,-1,-1,-1]),Int32Array.from([6,34,62,-1,-1,-1,-1]),Int32Array.from([6,26,46,66,-1,-1,-1]),Int32Array.from([6,26,48,70,-1,-1,-1]),Int32Array.from([6,26,50,74,-1,-1,-1]),Int32Array.from([6,30,54,78,-1,-1,-1]),Int32Array.from([6,30,56,82,-1,-1,-1]),Int32Array.from([6,30,58,86,-1,-1,-1]),Int32Array.from([6,34,62,90,-1,-1,-1]),Int32Array.from([6,28,50,72,94,-1,-1]),Int32Array.from([6,26,50,74,98,-1,-1]),Int32Array.from([6,30,54,78,102,-1,-1]),Int32Array.from([6,28,54,80,106,-1,-1]),Int32Array.from([6,32,58,84,110,-1,-1]),Int32Array.from([6,30,58,86,114,-1,-1]),Int32Array.from([6,34,62,90,118,-1,-1]),Int32Array.from([6,26,50,74,98,122,-1]),Int32Array.from([6,30,54,78,102,126,-1]),Int32Array.from([6,26,52,78,104,130,-1]),Int32Array.from([6,30,56,82,108,134,-1]),Int32Array.from([6,34,60,86,112,138,-1]),Int32Array.from([6,30,58,86,114,142,-1]),Int32Array.from([6,34,62,90,118,146,-1]),Int32Array.from([6,30,54,78,102,126,150]),Int32Array.from([6,24,50,76,102,128,154]),Int32Array.from([6,28,54,80,106,132,158]),Int32Array.from([6,32,58,84,110,136,162]),Int32Array.from([6,26,54,82,110,138,166]),Int32Array.from([6,30,58,86,114,142,170])]),De.TYPE_INFO_COORDINATES=Array.from([Int32Array.from([8,0]),Int32Array.from([8,1]),Int32Array.from([8,2]),Int32Array.from([8,3]),Int32Array.from([8,4]),Int32Array.from([8,5]),Int32Array.from([8,7]),Int32Array.from([8,8]),Int32Array.from([7,8]),Int32Array.from([5,8]),Int32Array.from([4,8]),Int32Array.from([3,8]),Int32Array.from([2,8]),Int32Array.from([1,8]),Int32Array.from([0,8])]),De.VERSION_INFO_POLY=7973,De.TYPE_INFO_POLY=1335,De.TYPE_INFO_MASK_PATTERN=21522;class md{constructor(e,n){this.dataBytes=e,this.errorCorrectionBytes=n}getDataBytes(){return this.dataBytes}getErrorCorrectionBytes(){return this.errorCorrectionBytes}}class xt{constructor(){}static calculateMaskPenalty(e){return Nt.applyMaskPenaltyRule1(e)+Nt.applyMaskPenaltyRule2(e)+Nt.applyMaskPenaltyRule3(e)+Nt.applyMaskPenaltyRule4(e)}static encode(e,n,o=null){let s=xt.DEFAULT_BYTE_MODE_ENCODING;const a=o!==null&&o.get(Bt.CHARACTER_SET)!==void 0;a&&(s=o.get(Bt.CHARACTER_SET).toString());const l=this.chooseMode(e,s),u=new re;if(l===Re.BYTE&&(a||xt.DEFAULT_BYTE_MODE_ENCODING!==s)){const pe=z.getCharacterSetECIByName(s);pe!==void 0&&this.appendECI(pe,u)}this.appendModeInfo(l,u);const h=new re;this.appendBytes(e,l,h,s);let p;if(o!==null&&o.get(Bt.QR_VERSION)!==void 0){const pe=Number.parseInt(o.get(Bt.QR_VERSION).toString(),10);p=Ne.getVersionForNumber(pe);const ce=this.calculateBitsNeeded(l,u,h,p);if(!this.willFit(ce,p,n))throw new dt("Data too big for requested version")}else p=this.recommendVersion(n,l,u,h);const y=new re;y.appendBitArray(u);const b=l===Re.BYTE?h.getSizeInBytes():e.length;this.appendLengthInfo(b,p,l,y),y.appendBitArray(h);const I=p.getECBlocksForLevel(n),R=p.getTotalCodewords()-I.getTotalECCodewords();this.terminateBits(R,y);const U=this.interleaveWithECBytes(y,p.getTotalCodewords(),R,I.getNumBlocks()),V=new lr;V.setECLevel(n),V.setMode(l),V.setVersion(p);const H=p.getDimensionForVersion(),Q=new go(H,H),he=this.chooseMaskPattern(U,n,p,Q);return V.setMaskPattern(he),De.buildMatrix(U,n,p,he,Q),V.setMatrix(Q),V}static recommendVersion(e,n,o,s){const a=this.calculateBitsNeeded(n,o,s,Ne.getVersionForNumber(1)),l=this.chooseVersion(a,e),u=this.calculateBitsNeeded(n,o,s,l);return this.chooseVersion(u,e)}static calculateBitsNeeded(e,n,o,s){return n.getSize()+e.getCharacterCountBits(s)+o.getSize()}static getAlphanumericCode(e){return e<xt.ALPHANUMERIC_TABLE.length?xt.ALPHANUMERIC_TABLE[e]:-1}static chooseMode(e,n=null){if(z.SJIS.getName()===n&&this.isOnlyDoubleByteKanji(e))return Re.KANJI;let o=!1,s=!1;for(let a=0,l=e.length;a<l;++a){const u=e.charAt(a);if(xt.isDigit(u))o=!0;else if(this.getAlphanumericCode(u.charCodeAt(0))!==-1)s=!0;else return Re.BYTE}return s?Re.ALPHANUMERIC:o?Re.NUMERIC:Re.BYTE}static isOnlyDoubleByteKanji(e){let n;try{n=G.encode(e,z.SJIS)}catch{return!1}const o=n.length;if(o%2!==0)return!1;for(let s=0;s<o;s+=2){const a=n[s]&255;if((a<129||a>159)&&(a<224||a>235))return!1}return!0}static chooseMaskPattern(e,n,o,s){let a=Number.MAX_SAFE_INTEGER,l=-1;for(let u=0;u<lr.NUM_MASK_PATTERNS;u++){De.buildMatrix(e,n,o,u,s);let h=this.calculateMaskPenalty(s);h<a&&(a=h,l=u)}return l}static chooseVersion(e,n){for(let o=1;o<=40;o++){const s=Ne.getVersionForNumber(o);if(xt.willFit(e,s,n))return s}throw new dt("Data too big")}static willFit(e,n,o){const s=n.getTotalCodewords(),l=n.getECBlocksForLevel(o).getTotalECCodewords(),u=s-l,h=(e+7)/8;return u>=h}static terminateBits(e,n){const o=e*8;if(n.getSize()>o)throw new dt("data bits cannot fit in the QR Code"+n.getSize()+" > "+o);for(let l=0;l<4&&n.getSize()<o;++l)n.appendBit(!1);const s=n.getSize()&7;if(s>0)for(let l=s;l<8;l++)n.appendBit(!1);const a=e-n.getSizeInBytes();for(let l=0;l<a;++l)n.appendBits((l&1)===0?236:17,8);if(n.getSize()!==o)throw new dt("Bits size does not equal capacity")}static getNumDataBytesAndNumECBytesForBlockID(e,n,o,s,a,l){if(s>=o)throw new dt("Block ID too large");const u=e%o,h=o-u,p=Math.floor(e/o),y=p+1,b=Math.floor(n/o),I=b+1,R=p-b,U=y-I;if(R!==U)throw new dt("EC bytes mismatch");if(o!==h+u)throw new dt("RS blocks mismatch");if(e!==(b+R)*h+(I+U)*u)throw new dt("Total bytes mismatch");s<h?(a[0]=b,l[0]=R):(a[0]=I,l[0]=U)}static interleaveWithECBytes(e,n,o,s){if(e.getSizeInBytes()!==o)throw new dt("Number of bits and data bytes does not match");let a=0,l=0,u=0;const h=new Array;for(let y=0;y<s;++y){const b=new Int32Array(1),I=new Int32Array(1);xt.getNumDataBytesAndNumECBytesForBlockID(n,o,s,y,b,I);const R=b[0],U=new Uint8Array(R);e.toBytes(8*a,U,0,R);const V=xt.generateECBytes(U,I[0]);h.push(new md(U,V)),l=Math.max(l,R),u=Math.max(u,V.length),a+=b[0]}if(o!==a)throw new dt("Data bytes does not match offset");const p=new re;for(let y=0;y<l;++y)for(const b of h){const I=b.getDataBytes();y<I.length&&p.appendBits(I[y],8)}for(let y=0;y<u;++y)for(const b of h){const I=b.getErrorCorrectionBytes();y<I.length&&p.appendBits(I[y],8)}if(n!==p.getSizeInBytes())throw new dt("Interleaving error: "+n+" and "+p.getSizeInBytes()+" differ.");return p}static generateECBytes(e,n){const o=e.length,s=new Int32Array(o+n);for(let l=0;l<o;l++)s[l]=e[l]&255;new ti(Se.QR_CODE_FIELD_256).encode(s,n);const a=new Uint8Array(n);for(let l=0;l<n;l++)a[l]=s[o+l];return a}static appendModeInfo(e,n){n.appendBits(e.getBits(),4)}static appendLengthInfo(e,n,o,s){const a=o.getCharacterCountBits(n);if(e>=1<<a)throw new dt(e+" is bigger than "+((1<<a)-1));s.appendBits(e,a)}static appendBytes(e,n,o,s){switch(n){case Re.NUMERIC:xt.appendNumericBytes(e,o);break;case Re.ALPHANUMERIC:xt.appendAlphanumericBytes(e,o);break;case Re.BYTE:xt.append8BitBytes(e,o,s);break;case Re.KANJI:xt.appendKanjiBytes(e,o);break;default:throw new dt("Invalid mode: "+n)}}static getDigit(e){return e.charCodeAt(0)-48}static isDigit(e){const n=xt.getDigit(e);return n>=0&&n<=9}static appendNumericBytes(e,n){const o=e.length;let s=0;for(;s<o;){const a=xt.getDigit(e.charAt(s));if(s+2<o){const l=xt.getDigit(e.charAt(s+1)),u=xt.getDigit(e.charAt(s+2));n.appendBits(a*100+l*10+u,10),s+=3}else if(s+1<o){const l=xt.getDigit(e.charAt(s+1));n.appendBits(a*10+l,7),s+=2}else n.appendBits(a,4),s++}}static appendAlphanumericBytes(e,n){const o=e.length;let s=0;for(;s<o;){const a=xt.getAlphanumericCode(e.charCodeAt(s));if(a===-1)throw new dt;if(s+1<o){const l=xt.getAlphanumericCode(e.charCodeAt(s+1));if(l===-1)throw new dt;n.appendBits(a*45+l,11),s+=2}else n.appendBits(a,6),s++}}static append8BitBytes(e,n,o){let s;try{s=G.encode(e,o)}catch(a){throw new dt(a)}for(let a=0,l=s.length;a!==l;a++){const u=s[a];n.appendBits(u,8)}}static appendKanjiBytes(e,n){let o;try{o=G.encode(e,z.SJIS)}catch(a){throw new dt(a)}const s=o.length;for(let a=0;a<s;a+=2){const l=o[a]&255,u=o[a+1]&255,h=l<<8&4294967295|u;let p=-1;if(h>=33088&&h<=40956?p=h-33088:h>=57408&&h<=60351&&(p=h-49472),p===-1)throw new dt("Invalid byte sequence");const y=(p>>8)*192+(p&255);n.appendBits(y,13)}}static appendECI(e,n){n.appendBits(Re.ECI.getBits(),4),n.appendBits(e.getValue(),8)}}xt.ALPHANUMERIC_TABLE=Int32Array.from([-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,36,-1,-1,-1,37,38,-1,-1,-1,-1,39,40,-1,41,42,43,0,1,2,3,4,5,6,7,8,9,44,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,-1,-1,-1,-1,-1]),xt.DEFAULT_BYTE_MODE_ENCODING=z.UTF8.getName();class cr{write(e,n,o,s=null){if(e.length===0)throw new A("Found empty contents");if(n<0||o<0)throw new A("Requested dimensions are too small: "+n+"x"+o);let a=pt.L,l=cr.QUIET_ZONE_SIZE;s!==null&&(s.get(Bt.ERROR_CORRECTION)!==void 0&&(a=pt.fromString(s.get(Bt.ERROR_CORRECTION).toString())),s.get(Bt.MARGIN)!==void 0&&(l=Number.parseInt(s.get(Bt.MARGIN).toString(),10)));const u=xt.encode(e,a,s);return this.renderResult(u,n,o,l)}writeToDom(e,n,o,s,a=null){typeof e=="string"&&(e=document.querySelector(e));const l=this.write(n,o,s,a);e&&e.appendChild(l)}renderResult(e,n,o,s){const a=e.getMatrix();if(a===null)throw new St;const l=a.getWidth(),u=a.getHeight(),h=l+s*2,p=u+s*2,y=Math.max(n,h),b=Math.max(o,p),I=Math.min(Math.floor(y/h),Math.floor(b/p)),R=Math.floor((y-l*I)/2),U=Math.floor((b-u*I)/2),V=this.createSVGElement(y,b);for(let H=0,Q=U;H<u;H++,Q+=I)for(let he=0,pe=R;he<l;he++,pe+=I)if(a.get(he,H)===1){const ce=this.createSvgRectElement(pe,Q,I,I);V.appendChild(ce)}return V}createSVGElement(e,n){const o=document.createElementNS(cr.SVG_NS,"svg");return o.setAttributeNS(null,"height",e.toString()),o.setAttributeNS(null,"width",n.toString()),o}createSvgRectElement(e,n,o,s){const a=document.createElementNS(cr.SVG_NS,"rect");return a.setAttributeNS(null,"x",e.toString()),a.setAttributeNS(null,"y",n.toString()),a.setAttributeNS(null,"height",o.toString()),a.setAttributeNS(null,"width",s.toString()),a.setAttributeNS(null,"fill","#000000"),a}}cr.QUIET_ZONE_SIZE=4,cr.SVG_NS="http://www.w3.org/2000/svg";class Er{encode(e,n,o,s,a){if(e.length===0)throw new A("Found empty contents");if(n!==ie.QR_CODE)throw new A("Can only encode QR_CODE, but got "+n);if(o<0||s<0)throw new A(`Requested dimensions are too small: ${o}x${s}`);let l=pt.L,u=Er.QUIET_ZONE_SIZE;a!==null&&(a.get(Bt.ERROR_CORRECTION)!==void 0&&(l=pt.fromString(a.get(Bt.ERROR_CORRECTION).toString())),a.get(Bt.MARGIN)!==void 0&&(u=Number.parseInt(a.get(Bt.MARGIN).toString(),10)));const h=xt.encode(e,l,a);return Er.renderResult(h,o,s,u)}static renderResult(e,n,o,s){const a=e.getMatrix();if(a===null)throw new St;const l=a.getWidth(),u=a.getHeight(),h=l+s*2,p=u+s*2,y=Math.max(n,h),b=Math.max(o,p),I=Math.min(Math.floor(y/h),Math.floor(b/p)),R=Math.floor((y-l*I)/2),U=Math.floor((b-u*I)/2),V=new te(y,b);for(let H=0,Q=U;H<u;H++,Q+=I)for(let he=0,pe=R;he<l;he++,pe+=I)a.get(he,H)===1&&V.setRegion(pe,Q,I,I);return V}}Er.QUIET_ZONE_SIZE=4;class gd{encode(e,n,o,s,a){let l;switch(n){case ie.QR_CODE:l=new Er;break;default:throw new A("No encoder available for format "+n)}return l.encode(e,n,o,s,a)}}class On extends Te{constructor(e,n,o,s,a,l,u,h){if(super(l,u),this.yuvData=e,this.dataWidth=n,this.dataHeight=o,this.left=s,this.top=a,s+l>n||a+u>o)throw new A("Crop rectangle does not fit within image data.");h&&this.reverseHorizontal(l,u)}getRow(e,n){if(e<0||e>=this.getHeight())throw new A("Requested row is outside the image: "+e);const o=this.getWidth();(n==null||n.length<o)&&(n=new Uint8ClampedArray(o));const s=(e+this.top)*this.dataWidth+this.left;return P.arraycopy(this.yuvData,s,n,0,o),n}getMatrix(){const e=this.getWidth(),n=this.getHeight();if(e===this.dataWidth&&n===this.dataHeight)return this.yuvData;const o=e*n,s=new Uint8ClampedArray(o);let a=this.top*this.dataWidth+this.left;if(e===this.dataWidth)return P.arraycopy(this.yuvData,a,s,0,o),s;for(let l=0;l<n;l++){const u=l*e;P.arraycopy(this.yuvData,a,s,u,e),a+=this.dataWidth}return s}isCropSupported(){return!0}crop(e,n,o,s){return new On(this.yuvData,this.dataWidth,this.dataHeight,this.left+e,this.top+n,o,s,!1)}renderThumbnail(){const e=this.getWidth()/On.THUMBNAIL_SCALE_FACTOR,n=this.getHeight()/On.THUMBNAIL_SCALE_FACTOR,o=new Int32Array(e*n),s=this.yuvData;let a=this.top*this.dataWidth+this.left;for(let l=0;l<n;l++){const u=l*e;for(let h=0;h<e;h++){const p=s[a+h*On.THUMBNAIL_SCALE_FACTOR]&255;o[u+h]=4278190080|p*65793}a+=this.dataWidth*On.THUMBNAIL_SCALE_FACTOR}return o}getThumbnailWidth(){return this.getWidth()/On.THUMBNAIL_SCALE_FACTOR}getThumbnailHeight(){return this.getHeight()/On.THUMBNAIL_SCALE_FACTOR}reverseHorizontal(e,n){const o=this.yuvData;for(let s=0,a=this.top*this.dataWidth+this.left;s<n;s++,a+=this.dataWidth){const l=a+e/2;for(let u=a,h=a+e-1;u<l;u++,h--){const p=o[u];o[u]=o[h],o[h]=p}}}invert(){return new Je(this)}}On.THUMBNAIL_SCALE_FACTOR=2;class ni extends Te{constructor(e,n,o,s,a,l,u){if(super(n,o),this.dataWidth=s,this.dataHeight=a,this.left=l,this.top=u,e.BYTES_PER_ELEMENT===4){const h=n*o,p=new Uint8ClampedArray(h);for(let y=0;y<h;y++){const b=e[y],I=b>>16&255,R=b>>7&510,U=b&255;p[y]=(I+R+U)/4&255}this.luminances=p}else this.luminances=e;if(s===void 0&&(this.dataWidth=n),a===void 0&&(this.dataHeight=o),l===void 0&&(this.left=0),u===void 0&&(this.top=0),this.left+n>this.dataWidth||this.top+o>this.dataHeight)throw new A("Crop rectangle does not fit within image data.")}getRow(e,n){if(e<0||e>=this.getHeight())throw new A("Requested row is outside the image: "+e);const o=this.getWidth();(n==null||n.length<o)&&(n=new Uint8ClampedArray(o));const s=(e+this.top)*this.dataWidth+this.left;return P.arraycopy(this.luminances,s,n,0,o),n}getMatrix(){const e=this.getWidth(),n=this.getHeight();if(e===this.dataWidth&&n===this.dataHeight)return this.luminances;const o=e*n,s=new Uint8ClampedArray(o);let a=this.top*this.dataWidth+this.left;if(e===this.dataWidth)return P.arraycopy(this.luminances,a,s,0,o),s;for(let l=0;l<n;l++){const u=l*e;P.arraycopy(this.luminances,a,s,u,e),a+=this.dataWidth}return s}isCropSupported(){return!0}crop(e,n,o,s){return new ni(this.luminances,o,s,this.dataWidth,this.dataHeight,this.left+e,this.top+n)}invert(){return new Je(this)}}class ys extends z{static forName(e){return this.getCharacterSetECIByName(e)}}class ri{}ri.ISO_8859_1=z.ISO8859_1;class ws{isCompact(){return this.compact}setCompact(e){this.compact=e}getSize(){return this.size}setSize(e){this.size=e}getLayers(){return this.layers}setLayers(e){this.layers=e}getCodeWords(){return this.codeWords}setCodeWords(e){this.codeWords=e}getMatrix(){return this.matrix}setMatrix(e){this.matrix=e}}class _s{static singletonList(e){return[e]}static min(e,n){return e.sort(n)[0]}}class xd{constructor(e){this.previous=e}getPrevious(){return this.previous}}class Ir extends xd{constructor(e,n,o){super(e),this.value=n,this.bitCount=o}appendTo(e,n){e.appendBits(this.value,this.bitCount)}add(e,n){return new Ir(this,e,n)}addBinaryShift(e,n){return console.warn("addBinaryShift on SimpleToken, this simply returns a copy of this token"),new Ir(this,e,n)}toString(){let e=this.value&(1<<this.bitCount)-1;return e|=1<<this.bitCount,"<"+F.toBinaryString(e|1<<this.bitCount).substring(1)+">"}}class oi extends Ir{constructor(e,n,o){super(e,0,0),this.binaryShiftStart=n,this.binaryShiftByteCount=o}appendTo(e,n){for(let o=0;o<this.binaryShiftByteCount;o++)(o===0||o===31&&this.binaryShiftByteCount<=62)&&(e.appendBits(31,5),this.binaryShiftByteCount>62?e.appendBits(this.binaryShiftByteCount-31,16):o===0?e.appendBits(Math.min(this.binaryShiftByteCount,31),5):e.appendBits(this.binaryShiftByteCount-31,5)),e.appendBits(n[this.binaryShiftStart+o],8)}addBinaryShift(e,n){return new oi(this,e,n)}toString(){return"<"+this.binaryShiftStart+"::"+(this.binaryShiftStart+this.binaryShiftByteCount-1)+">"}}function yd(C,e,n){return new oi(C,e,n)}function zr(C,e,n){return new Ir(C,e,n)}const wd=["UPPER","LOWER","DIGIT","MIXED","PUNCT"],Yn=0,xo=1,gn=2,vs=3,kn=4,_d=new Ir(null,0,0),ii=[Int32Array.from([0,(5<<16)+28,(5<<16)+30,(5<<16)+29,656318]),Int32Array.from([(9<<16)+480+14,0,(5<<16)+30,(5<<16)+29,656318]),Int32Array.from([(4<<16)+14,(9<<16)+448+28,0,(9<<16)+448+29,932798]),Int32Array.from([(5<<16)+29,(5<<16)+28,656318,0,(5<<16)+30]),Int32Array.from([(5<<16)+31,656380,656382,656381,0])];function vd(C){for(let e of C)$.fill(e,-1);return C[Yn][kn]=0,C[xo][kn]=0,C[xo][Yn]=28,C[vs][kn]=0,C[gn][kn]=0,C[gn][Yn]=15,C}const Cs=vd($.createInt32Array(6,6));class Rn{constructor(e,n,o,s){this.token=e,this.mode=n,this.binaryShiftByteCount=o,this.bitCount=s}getMode(){return this.mode}getToken(){return this.token}getBinaryShiftByteCount(){return this.binaryShiftByteCount}getBitCount(){return this.bitCount}latchAndAppend(e,n){let o=this.bitCount,s=this.token;if(e!==this.mode){let l=ii[this.mode][e];s=zr(s,l&65535,l>>16),o+=l>>16}let a=e===gn?4:5;return s=zr(s,n,a),new Rn(s,e,0,o+a)}shiftAndAppend(e,n){let o=this.token,s=this.mode===gn?4:5;return o=zr(o,Cs[this.mode][e],s),o=zr(o,n,5),new Rn(o,this.mode,0,this.bitCount+s+5)}addBinaryShiftChar(e){let n=this.token,o=this.mode,s=this.bitCount;if(this.mode===kn||this.mode===gn){let u=ii[o][Yn];n=zr(n,u&65535,u>>16),s+=u>>16,o=Yn}let a=this.binaryShiftByteCount===0||this.binaryShiftByteCount===31?18:this.binaryShiftByteCount===62?9:8,l=new Rn(n,o,this.binaryShiftByteCount+1,s+a);return l.binaryShiftByteCount===2078&&(l=l.endBinaryShift(e+1)),l}endBinaryShift(e){if(this.binaryShiftByteCount===0)return this;let n=this.token;return n=yd(n,e-this.binaryShiftByteCount,this.binaryShiftByteCount),new Rn(n,this.mode,0,this.bitCount)}isBetterThanOrEqualTo(e){let n=this.bitCount+(ii[this.mode][e.mode]>>16);return this.binaryShiftByteCount<e.binaryShiftByteCount?n+=Rn.calculateBinaryShiftCost(e)-Rn.calculateBinaryShiftCost(this):this.binaryShiftByteCount>e.binaryShiftByteCount&&e.binaryShiftByteCount>0&&(n+=10),n<=e.bitCount}toBitArray(e){let n=[];for(let s=this.endBinaryShift(e.length).token;s!==null;s=s.getPrevious())n.unshift(s);let o=new re;for(const s of n)s.appendTo(o,e);return o}toString(){return me.format("%s bits=%d bytes=%d",wd[this.mode],this.bitCount,this.binaryShiftByteCount)}static calculateBinaryShiftCost(e){return e.binaryShiftByteCount>62?21:e.binaryShiftByteCount>31?20:e.binaryShiftByteCount>0?10:0}}Rn.INITIAL_STATE=new Rn(_d,Yn,0,0);function Cd(C){const e=me.getCharCode(" "),n=me.getCharCode("."),o=me.getCharCode(",");C[Yn][e]=1;const s=me.getCharCode("Z"),a=me.getCharCode("A");for(let I=a;I<=s;I++)C[Yn][I]=I-a+2;C[xo][e]=1;const l=me.getCharCode("z"),u=me.getCharCode("a");for(let I=u;I<=l;I++)C[xo][I]=I-u+2;C[gn][e]=1;const h=me.getCharCode("9"),p=me.getCharCode("0");for(let I=p;I<=h;I++)C[gn][I]=I-p+2;C[gn][o]=12,C[gn][n]=13;const y=["\0"," ","","","","","","","\x07","\b"," ",`
80
80
  `,"\v","\f","\r","\x1B","","","","","@","\\","^","_","`","|","~",""];for(let I=0;I<y.length;I++)C[vs][me.getCharCode(y[I])]=I;const b=["\0","\r","\0","\0","\0","\0","!","'","#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","[","]","{","}"];for(let I=0;I<b.length;I++)me.getCharCode(b[I])>0&&(C[kn][me.getCharCode(b[I])]=I);return C}const si=Cd($.createInt32Array(5,256));class Vr{constructor(e){this.text=e}encode(){const e=me.getCharCode(" "),n=me.getCharCode(`
81
- `);let o=_s.singletonList(Rn.INITIAL_STATE);for(let a=0;a<this.text.length;a++){let l,u=a+1<this.text.length?this.text[a+1]:0;switch(this.text[a]){case me.getCharCode("\r"):l=u===n?2:0;break;case me.getCharCode("."):l=u===e?3:0;break;case me.getCharCode(","):l=u===e?4:0;break;case me.getCharCode(":"):l=u===e?5:0;break;default:l=0}l>0?(o=Vr.updateStateListForPair(o,a,l),a++):o=this.updateStateListForChar(o,a)}return _s.min(o,(a,l)=>a.getBitCount()-l.getBitCount()).toBitArray(this.text)}updateStateListForChar(e,n){const o=[];for(let s of e)this.updateStateForChar(s,n,o);return Vr.simplifyStates(o)}updateStateForChar(e,n,o){let s=this.text[n]&255,a=si[e.getMode()][s]>0,l=null;for(let u=0;u<=kn;u++){let h=si[u][s];if(h>0){if(l==null&&(l=e.endBinaryShift(n)),!a||u===e.getMode()||u===gn){const p=l.latchAndAppend(u,h);o.push(p)}if(!a&&Cs[e.getMode()][u]>=0){const p=l.shiftAndAppend(u,h);o.push(p)}}}if(e.getBinaryShiftByteCount()>0||si[e.getMode()][s]===0){let u=e.addBinaryShiftChar(n);o.push(u)}}static updateStateListForPair(e,n,o){const s=[];for(let a of e)this.updateStateForPair(a,n,o,s);return this.simplifyStates(s)}static updateStateForPair(e,n,o,s){let a=e.endBinaryShift(n);if(s.push(a.latchAndAppend(kn,o)),e.getMode()!==kn&&s.push(a.shiftAndAppend(kn,o)),o===3||o===4){let l=a.latchAndAppend(gn,16-o).latchAndAppend(gn,1);s.push(l)}if(e.getBinaryShiftByteCount()>0){let l=e.addBinaryShiftChar(n).addBinaryShiftChar(n+1);s.push(l)}}static simplifyStates(e){let n=[];for(const o of e){let s=!0;for(const a of n){if(a.isBetterThanOrEqualTo(o)){s=!1;break}o.isBetterThanOrEqualTo(a)&&(n=n.filter(l=>l!==a))}s&&n.push(o)}return n}}class tt{constructor(){}static encodeBytes(e){return tt.encode(e,tt.DEFAULT_EC_PERCENT,tt.DEFAULT_AZTEC_LAYERS)}static encode(e,n,o){let s=new Vr(e).encode(),a=F.truncDivision(s.getSize()*n,100)+11,l=s.getSize()+a,u,h,p,y,b;if(o!==tt.DEFAULT_AZTEC_LAYERS){if(u=o<0,h=Math.abs(o),h>(u?tt.MAX_NB_BITS_COMPACT:tt.MAX_NB_BITS))throw new A(me.format("Illegal value %s for layers",o));p=tt.totalBitsInLayer(h,u),y=tt.WORD_SIZE[h];let ce=p-p%y;if(b=tt.stuffBits(s,y),b.getSize()+a>ce)throw new A("Data to large for user specified layer");if(u&&b.getSize()>y*64)throw new A("Data to large for user specified layer")}else{y=0,b=null;for(let ce=0;;ce++){if(ce>tt.MAX_NB_BITS)throw new A("Data too large for an Aztec code");if(u=ce<=3,h=u?ce+1:ce,p=tt.totalBitsInLayer(h,u),l>p)continue;(b==null||y!==tt.WORD_SIZE[h])&&(y=tt.WORD_SIZE[h],b=tt.stuffBits(s,y));let Ke=p-p%y;if(!(u&&b.getSize()>y*64)&&b.getSize()+a<=Ke)break}}let I=tt.generateCheckWords(b,p,y),R=b.getSize()/y,U=tt.generateModeMessage(u,h,R),V=(u?11:14)+h*4,H=new Int32Array(V),Q;if(u){Q=V;for(let ce=0;ce<H.length;ce++)H[ce]=ce}else{Q=V+1+2*F.truncDivision(F.truncDivision(V,2)-1,15);let ce=F.truncDivision(V,2),Ke=F.truncDivision(Q,2);for(let He=0;He<ce;He++){let tn=He+F.truncDivision(He,15);H[ce-He-1]=Ke-tn-1,H[ce+He]=Ke+tn+1}}let he=new te(Q);for(let ce=0,Ke=0;ce<h;ce++){let He=(h-ce)*4+(u?9:12);for(let tn=0;tn<He;tn++){let yn=tn*2;for(let nn=0;nn<2;nn++)I.get(Ke+yn+nn)&&he.set(H[ce*2+nn],H[ce*2+tn]),I.get(Ke+He*2+yn+nn)&&he.set(H[ce*2+tn],H[V-1-ce*2-nn]),I.get(Ke+He*4+yn+nn)&&he.set(H[V-1-ce*2-nn],H[V-1-ce*2-tn]),I.get(Ke+He*6+yn+nn)&&he.set(H[V-1-ce*2-tn],H[ce*2+nn])}Ke+=He*8}if(tt.drawModeMessage(he,u,Q,U),u)tt.drawBullsEye(he,F.truncDivision(Q,2),5);else{tt.drawBullsEye(he,F.truncDivision(Q,2),7);for(let ce=0,Ke=0;ce<F.truncDivision(V,2)-1;ce+=15,Ke+=16)for(let He=F.truncDivision(Q,2)&1;He<Q;He+=2)he.set(F.truncDivision(Q,2)-Ke,He),he.set(F.truncDivision(Q,2)+Ke,He),he.set(He,F.truncDivision(Q,2)-Ke),he.set(He,F.truncDivision(Q,2)+Ke)}let pe=new ws;return pe.setCompact(u),pe.setSize(Q),pe.setLayers(h),pe.setCodeWords(R),pe.setMatrix(he),pe}static drawBullsEye(e,n,o){for(let s=0;s<o;s+=2)for(let a=n-s;a<=n+s;a++)e.set(a,n-s),e.set(a,n+s),e.set(n-s,a),e.set(n+s,a);e.set(n-o,n-o),e.set(n-o+1,n-o),e.set(n-o,n-o+1),e.set(n+o,n-o),e.set(n+o,n-o+1),e.set(n+o,n+o-1)}static generateModeMessage(e,n,o){let s=new re;return e?(s.appendBits(n-1,2),s.appendBits(o-1,6),s=tt.generateCheckWords(s,28,4)):(s.appendBits(n-1,5),s.appendBits(o-1,11),s=tt.generateCheckWords(s,40,4)),s}static drawModeMessage(e,n,o,s){let a=F.truncDivision(o,2);if(n)for(let l=0;l<7;l++){let u=a-3+l;s.get(l)&&e.set(u,a-5),s.get(l+7)&&e.set(a+5,u),s.get(20-l)&&e.set(u,a+5),s.get(27-l)&&e.set(a-5,u)}else for(let l=0;l<10;l++){let u=a-5+l+F.truncDivision(l,5);s.get(l)&&e.set(u,a-7),s.get(l+10)&&e.set(a+7,u),s.get(29-l)&&e.set(u,a+7),s.get(39-l)&&e.set(a-7,u)}}static generateCheckWords(e,n,o){let s=e.getSize()/o,a=new ti(tt.getGF(o)),l=F.truncDivision(n,o),u=tt.bitsToWords(e,o,l);a.encode(u,l-s);let h=n%o,p=new re;p.appendBits(0,h);for(const y of Array.from(u))p.appendBits(y,o);return p}static bitsToWords(e,n,o){let s=new Int32Array(o),a,l;for(a=0,l=e.getSize()/n;a<l;a++){let u=0;for(let h=0;h<n;h++)u|=e.get(a*n+h)?1<<n-h-1:0;s[a]=u}return s}static getGF(e){switch(e){case 4:return Se.AZTEC_PARAM;case 6:return Se.AZTEC_DATA_6;case 8:return Se.AZTEC_DATA_8;case 10:return Se.AZTEC_DATA_10;case 12:return Se.AZTEC_DATA_12;default:throw new A("Unsupported word size "+e)}}static stuffBits(e,n){let o=new re,s=e.getSize(),a=(1<<n)-2;for(let l=0;l<s;l+=n){let u=0;for(let h=0;h<n;h++)(l+h>=s||e.get(l+h))&&(u|=1<<n-1-h);(u&a)===a?(o.appendBits(u&a,n),l--):(u&a)===0?(o.appendBits(u|1,n),l--):o.appendBits(u,n)}return o}static totalBitsInLayer(e,n){return((n?88:112)+16*e)*e}}tt.DEFAULT_EC_PERCENT=33,tt.DEFAULT_AZTEC_LAYERS=0,tt.MAX_NB_BITS=32,tt.MAX_NB_BITS_COMPACT=4,tt.WORD_SIZE=Int32Array.from([4,6,6,8,8,8,8,8,8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,12,12,12,12,12,12,12,12,12,12]);class yo{encode(e,n,o,s){return this.encodeWithHints(e,n,o,s,null)}encodeWithHints(e,n,o,s,a){let l=ri.ISO_8859_1,u=tt.DEFAULT_EC_PERCENT,h=tt.DEFAULT_AZTEC_LAYERS;return a!=null&&(a.has(Bt.CHARACTER_SET)&&(l=ys.forName(a.get(Bt.CHARACTER_SET).toString())),a.has(Bt.ERROR_CORRECTION)&&(u=F.parseInt(a.get(Bt.ERROR_CORRECTION).toString())),a.has(Bt.AZTEC_LAYERS)&&(h=F.parseInt(a.get(Bt.AZTEC_LAYERS).toString()))),yo.encodeLayers(e,n,o,s,l,u,h)}static encodeLayers(e,n,o,s,a,l,u){if(n!==ie.AZTEC)throw new A("Can only encode AZTEC, but got "+n);let h=tt.encode(me.getBytes(e,a),l,u);return yo.renderResult(h,o,s)}static renderResult(e,n,o){let s=e.getMatrix();if(s==null)throw new St;let a=s.getWidth(),l=s.getHeight(),u=Math.max(n,a),h=Math.max(o,l),p=Math.min(u/a,h/l),y=(u-a*p)/2,b=(h-l*p)/2,I=new te(u,h);for(let R=0,U=b;R<l;R++,U+=p)for(let V=0,H=y;V<a;V++,H+=p)s.get(V,R)&&I.setRegion(H,U,p,p);return I}}i.AbstractExpandedDecoder=Ho,i.ArgumentException=E,i.ArithmeticException=ye,i.AztecCode=ws,i.AztecCodeReader=Ln,i.AztecCodeWriter=yo,i.AztecDecoder=nt,i.AztecDetector=or,i.AztecDetectorResult=$n,i.AztecEncoder=tt,i.AztecHighLevelEncoder=Vr,i.AztecPoint=At,i.BarcodeFormat=ie,i.Binarizer=S,i.BinaryBitmap=D,i.BitArray=re,i.BitMatrix=te,i.BitSource=Xo,i.BrowserAztecCodeReader=wr,i.BrowserBarcodeReader=Qu,i.BrowserCodeReader=Ze,i.BrowserDatamatrixCodeReader=td,i.BrowserMultiFormatReader=fd,i.BrowserPDF417Reader=hd,i.BrowserQRCodeReader=pd,i.BrowserQRCodeSvgWriter=cr,i.CharacterSetECI=z,i.ChecksumException=T,i.Code128Reader=ge,i.Code39Reader=O,i.DataMatrixDecodedBitStreamParser=Wn,i.DataMatrixReader=Gn,i.DecodeHintType=B,i.DecoderResult=Pe,i.DefaultGridSampler=rr,i.DetectorResult=Bn,i.EAN13Reader=Fn,i.EncodeHintType=Bt,i.Exception=g,i.FormatException=L,i.GenericGF=Se,i.GenericGFPoly=J,i.GlobalHistogramBinarizer=ke,i.GridSampler=jn,i.GridSamplerInstance=sn,i.HTMLCanvasElementLuminanceSource=xe,i.HybridBinarizer=le,i.ITFReader=ne,i.IllegalArgumentException=A,i.IllegalStateException=St,i.InvertedLuminanceSource=Je,i.LuminanceSource=Te,i.MathUtils=Xe,i.MultiFormatOneDReader=br,i.MultiFormatReader=xs,i.MultiFormatWriter=gd,i.NotFoundException=q,i.OneDReader=gt,i.PDF417DecodedBitStreamParser=K,i.PDF417DecoderErrorCorrection=ds,i.PDF417Reader=jt,i.PDF417ResultMetadata=hs,i.PerspectiveTransform=Ft,i.PlanarYUVLuminanceSource=On,i.QRCodeByteMatrix=go,i.QRCodeDataMask=pn,i.QRCodeDecodedBitStreamParser=Et,i.QRCodeDecoderErrorCorrectionLevel=pt,i.QRCodeDecoderFormatInformation=Gt,i.QRCodeEncoder=xt,i.QRCodeEncoderQRCode=lr,i.QRCodeMaskUtil=Nt,i.QRCodeMatrixUtil=De,i.QRCodeMode=Re,i.QRCodeReader=qn,i.QRCodeVersion=Ne,i.QRCodeWriter=Er,i.RGBLuminanceSource=ni,i.RSS14Reader=Tt,i.RSSExpandedReader=se,i.ReaderException=mo,i.ReedSolomonDecoder=vt,i.ReedSolomonEncoder=ti,i.ReedSolomonException=Ve,i.Result=qe,i.ResultMetadataType=_e,i.ResultPoint=be,i.StringUtils=me,i.UnsupportedOperationException=we,i.VideoInputDevice=$e,i.WhiteRectangleDetector=qt,i.WriterException=dt,i.ZXingArrays=$,i.ZXingCharset=ys,i.ZXingInteger=F,i.ZXingStandardCharsets=ri,i.ZXingStringBuilder=fe,i.ZXingStringEncoding=G,i.ZXingSystem=P,i.createAbstractExpandedDecoder=cs,Object.defineProperty(i,"__esModule",{value:!0})}))})(qr,qr.exports)),qr.exports}var yt=aw();const lw=iw(yt),cw=Td({__proto__:null,default:lw},[yt]);var dl=(function(){function t(r,i,c){if(this.formatMap=new Map([[Ce.QR_CODE,yt.BarcodeFormat.QR_CODE],[Ce.AZTEC,yt.BarcodeFormat.AZTEC],[Ce.CODABAR,yt.BarcodeFormat.CODABAR],[Ce.CODE_39,yt.BarcodeFormat.CODE_39],[Ce.CODE_93,yt.BarcodeFormat.CODE_93],[Ce.CODE_128,yt.BarcodeFormat.CODE_128],[Ce.DATA_MATRIX,yt.BarcodeFormat.DATA_MATRIX],[Ce.MAXICODE,yt.BarcodeFormat.MAXICODE],[Ce.ITF,yt.BarcodeFormat.ITF],[Ce.EAN_13,yt.BarcodeFormat.EAN_13],[Ce.EAN_8,yt.BarcodeFormat.EAN_8],[Ce.PDF_417,yt.BarcodeFormat.PDF_417],[Ce.RSS_14,yt.BarcodeFormat.RSS_14],[Ce.RSS_EXPANDED,yt.BarcodeFormat.RSS_EXPANDED],[Ce.UPC_A,yt.BarcodeFormat.UPC_A],[Ce.UPC_E,yt.BarcodeFormat.UPC_E],[Ce.UPC_EAN_EXTENSION,yt.BarcodeFormat.UPC_EAN_EXTENSION]]),this.reverseFormatMap=this.createReverseFormatMap(),!cw)throw"Use html5qrcode.min.js without edit, ZXing not found.";this.verbose=i,this.logger=c;var d=this.createZXingFormats(r),f=new Map;f.set(yt.DecodeHintType.POSSIBLE_FORMATS,d),f.set(yt.DecodeHintType.TRY_HARDER,!1),this.hints=f}return t.prototype.decodeAsync=function(r){var i=this;return new Promise(function(c,d){try{c(i.decode(r))}catch(f){d(f)}})},t.prototype.decode=function(r){var i=new yt.MultiFormatReader(this.verbose,this.hints),c=new yt.HTMLCanvasElementLuminanceSource(r),d=new yt.BinaryBitmap(new yt.HybridBinarizer(c)),f=i.decode(d);return{text:f.text,format:Hu.create(this.toHtml5QrcodeSupportedFormats(f.format)),debugData:this.createDebugData()}},t.prototype.createReverseFormatMap=function(){var r=new Map;return this.formatMap.forEach(function(i,c,d){r.set(i,c)}),r},t.prototype.toHtml5QrcodeSupportedFormats=function(r){if(!this.reverseFormatMap.has(r))throw"reverseFormatMap doesn't have ".concat(r);return this.reverseFormatMap.get(r)},t.prototype.createZXingFormats=function(r){for(var i=[],c=0,d=r;c<d.length;c++){var f=d[c];this.formatMap.has(f)?i.push(this.formatMap.get(f)):this.logger.logError("".concat(f," is not supported by")+"ZXingHtml5QrcodeShim")}return i},t.prototype.createDebugData=function(){return{decoderName:"zxing-js"}},t})(),uw=function(t,r,i,c){function d(f){return f instanceof i?f:new i(function(m){m(f)})}return new(i||(i=Promise))(function(f,m){function x(E){try{g(c.next(E))}catch(A){m(A)}}function v(E){try{g(c.throw(E))}catch(A){m(A)}}function g(E){E.done?f(E.value):d(E.value).then(x,v)}g((c=c.apply(t,r||[])).next())})},dw=function(t,r){var i={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,d,f,m;return m={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function x(g){return function(E){return v([g,E])}}function v(g){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,g[0]&&(i=0)),i;)try{if(c=1,d&&(f=g[0]&2?d.return:g[0]?d.throw||((f=d.return)&&f.call(d),0):d.next)&&!(f=f.call(d,g[1])).done)return f;switch(d=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return i.label++,{value:g[1],done:!1};case 5:i.label++,d=g[1],g=[0];continue;case 7:g=i.ops.pop(),i.trys.pop();continue;default:if(f=i.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){i=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){i.label=g[1];break}if(g[0]===6&&i.label<f[1]){i.label=f[1],f=g;break}if(f&&i.label<f[2]){i.label=f[2],i.ops.push(g);break}f[2]&&i.ops.pop(),i.trys.pop();continue}g=r.call(t,i)}catch(E){g=[6,E],d=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},fl=(function(){function t(r,i,c){if(this.formatMap=new Map([[Ce.QR_CODE,"qr_code"],[Ce.AZTEC,"aztec"],[Ce.CODABAR,"codabar"],[Ce.CODE_39,"code_39"],[Ce.CODE_93,"code_93"],[Ce.CODE_128,"code_128"],[Ce.DATA_MATRIX,"data_matrix"],[Ce.ITF,"itf"],[Ce.EAN_13,"ean_13"],[Ce.EAN_8,"ean_8"],[Ce.PDF_417,"pdf417"],[Ce.UPC_A,"upc_a"],[Ce.UPC_E,"upc_e"]]),this.reverseFormatMap=this.createReverseFormatMap(),!t.isSupported())throw"Use html5qrcode.min.js without edit, Use BarcodeDetectorDelegate only if it isSupported();";this.verbose=i,this.logger=c;var d=this.createBarcodeDetectorFormats(r);if(this.detector=new BarcodeDetector(d),!this.detector)throw"BarcodeDetector detector not supported"}return t.isSupported=function(){if(!("BarcodeDetector"in window))return!1;var r=new BarcodeDetector({formats:["qr_code"]});return typeof r<"u"},t.prototype.decodeAsync=function(r){return uw(this,void 0,void 0,function(){var i,c;return dw(this,function(d){switch(d.label){case 0:return[4,this.detector.detect(r)];case 1:if(i=d.sent(),!i||i.length===0)throw"No barcode or QR code detected.";return c=this.selectLargestBarcode(i),[2,{text:c.rawValue,format:Hu.create(this.toHtml5QrcodeSupportedFormats(c.format)),debugData:this.createDebugData()}]}})})},t.prototype.selectLargestBarcode=function(r){for(var i=null,c=0,d=0,f=r;d<f.length;d++){var m=f[d],x=m.boundingBox.width*m.boundingBox.height;x>c&&(c=x,i=m)}if(!i)throw"No largest barcode found";return i},t.prototype.createBarcodeDetectorFormats=function(r){for(var i=[],c=0,d=r;c<d.length;c++){var f=d[c];this.formatMap.has(f)?i.push(this.formatMap.get(f)):this.logger.warn("".concat(f," is not supported by")+"BarcodeDetectorDelegate")}return{formats:i}},t.prototype.toHtml5QrcodeSupportedFormats=function(r){if(!this.reverseFormatMap.has(r))throw"reverseFormatMap doesn't have ".concat(r);return this.reverseFormatMap.get(r)},t.prototype.createReverseFormatMap=function(){var r=new Map;return this.formatMap.forEach(function(i,c,d){r.set(i,c)}),r},t.prototype.createDebugData=function(){return{decoderName:"BarcodeDetector"}},t})(),hl=function(t,r,i,c){function d(f){return f instanceof i?f:new i(function(m){m(f)})}return new(i||(i=Promise))(function(f,m){function x(E){try{g(c.next(E))}catch(A){m(A)}}function v(E){try{g(c.throw(E))}catch(A){m(A)}}function g(E){E.done?f(E.value):d(E.value).then(x,v)}g((c=c.apply(t,r||[])).next())})},pl=function(t,r){var i={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,d,f,m;return m={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function x(g){return function(E){return v([g,E])}}function v(g){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,g[0]&&(i=0)),i;)try{if(c=1,d&&(f=g[0]&2?d.return:g[0]?d.throw||((f=d.return)&&f.call(d),0):d.next)&&!(f=f.call(d,g[1])).done)return f;switch(d=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return i.label++,{value:g[1],done:!1};case 5:i.label++,d=g[1],g=[0];continue;case 7:g=i.ops.pop(),i.trys.pop();continue;default:if(f=i.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){i=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){i.label=g[1];break}if(g[0]===6&&i.label<f[1]){i.label=f[1],f=g;break}if(f&&i.label<f[2]){i.label=f[2],i.ops.push(g);break}f[2]&&i.ops.pop(),i.trys.pop();continue}g=r.call(t,i)}catch(E){g=[6,E],d=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},fw=(function(){function t(r,i,c,d){this.EXECUTIONS_TO_REPORT_PERFORMANCE=100,this.executions=0,this.executionResults=[],this.wasPrimaryDecoderUsedInLastDecode=!1,this.verbose=c,i&&fl.isSupported()?(this.primaryDecoder=new fl(r,c,d),this.secondaryDecoder=new dl(r,c,d)):this.primaryDecoder=new dl(r,c,d)}return t.prototype.decodeAsync=function(r){return hl(this,void 0,void 0,function(){var i;return pl(this,function(c){switch(c.label){case 0:i=performance.now(),c.label=1;case 1:return c.trys.push([1,,3,4]),[4,this.getDecoder().decodeAsync(r)];case 2:return[2,c.sent()];case 3:return this.possiblyLogPerformance(i),[7];case 4:return[2]}})})},t.prototype.decodeRobustlyAsync=function(r){return hl(this,void 0,void 0,function(){var i,c;return pl(this,function(d){switch(d.label){case 0:i=performance.now(),d.label=1;case 1:return d.trys.push([1,3,4,5]),[4,this.primaryDecoder.decodeAsync(r)];case 2:return[2,d.sent()];case 3:if(c=d.sent(),this.secondaryDecoder)return[2,this.secondaryDecoder.decodeAsync(r)];throw c;case 4:return this.possiblyLogPerformance(i),[7];case 5:return[2]}})})},t.prototype.getDecoder=function(){return this.secondaryDecoder?this.wasPrimaryDecoderUsedInLastDecode===!1?(this.wasPrimaryDecoderUsedInLastDecode=!0,this.primaryDecoder):(this.wasPrimaryDecoderUsedInLastDecode=!1,this.secondaryDecoder):this.primaryDecoder},t.prototype.possiblyLogPerformance=function(r){if(this.verbose){var i=performance.now()-r;this.executionResults.push(i),this.executions++,this.possiblyFlushPerformanceReport()}},t.prototype.possiblyFlushPerformanceReport=function(){if(!(this.executions<this.EXECUTIONS_TO_REPORT_PERFORMANCE)){for(var r=0,i=0,c=this.executionResults;i<c.length;i++){var d=c[i];r+=d}var f=r/this.executionResults.length;console.log("".concat(f," ms for ").concat(this.executionResults.length," last runs.")),this.executions=0,this.executionResults=[]}},t})(),os=(function(){var t=function(r,i){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(c,d){c.__proto__=d}||function(c,d){for(var f in d)Object.prototype.hasOwnProperty.call(d,f)&&(c[f]=d[f])},t(r,i)};return function(r,i){if(typeof i!="function"&&i!==null)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");t(r,i);function c(){this.constructor=r}r.prototype=i===null?Object.create(i):(c.prototype=i.prototype,new c)}})(),Bo=function(t,r,i,c){function d(f){return f instanceof i?f:new i(function(m){m(f)})}return new(i||(i=Promise))(function(f,m){function x(E){try{g(c.next(E))}catch(A){m(A)}}function v(E){try{g(c.throw(E))}catch(A){m(A)}}function g(E){E.done?f(E.value):d(E.value).then(x,v)}g((c=c.apply(t,r||[])).next())})},Lo=function(t,r){var i={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,d,f,m;return m={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function x(g){return function(E){return v([g,E])}}function v(g){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,g[0]&&(i=0)),i;)try{if(c=1,d&&(f=g[0]&2?d.return:g[0]?d.throw||((f=d.return)&&f.call(d),0):d.next)&&!(f=f.call(d,g[1])).done)return f;switch(d=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return i.label++,{value:g[1],done:!1};case 5:i.label++,d=g[1],g=[0];continue;case 7:g=i.ops.pop(),i.trys.pop();continue;default:if(f=i.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){i=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){i.label=g[1];break}if(g[0]===6&&i.label<f[1]){i.label=f[1],f=g;break}if(f&&i.label<f[2]){i.label=f[2],i.ops.push(g);break}f[2]&&i.ops.pop(),i.trys.pop();continue}g=r.call(t,i)}catch(E){g=[6,E],d=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},Gu=(function(){function t(r,i){this.name=r,this.track=i}return t.prototype.isSupported=function(){return this.track.getCapabilities?this.name in this.track.getCapabilities():!1},t.prototype.apply=function(r){var i={};i[this.name]=r;var c={advanced:[i]};return this.track.applyConstraints(c)},t.prototype.value=function(){var r=this.track.getSettings();if(this.name in r){var i=r[this.name];return i}return null},t})(),hw=(function(t){os(r,t);function r(i,c){return t.call(this,i,c)||this}return r.prototype.min=function(){return this.getCapabilities().min},r.prototype.max=function(){return this.getCapabilities().max},r.prototype.step=function(){return this.getCapabilities().step},r.prototype.apply=function(i){var c={};c[this.name]=i;var d={advanced:[c]};return this.track.applyConstraints(d)},r.prototype.getCapabilities=function(){this.failIfNotSupported();var i=this.track.getCapabilities(),c=i[this.name];return{min:c.min,max:c.max,step:c.step}},r.prototype.failIfNotSupported=function(){if(!this.isSupported())throw new Error("".concat(this.name," capability not supported"))},r})(Gu),pw=(function(t){os(r,t);function r(i){return t.call(this,"zoom",i)||this}return r})(hw),mw=(function(t){os(r,t);function r(i){return t.call(this,"torch",i)||this}return r})(Gu),gw=(function(){function t(r){this.track=r}return t.prototype.zoomFeature=function(){return new pw(this.track)},t.prototype.torchFeature=function(){return new mw(this.track)},t})(),xw=(function(){function t(r,i,c){this.isClosed=!1,this.parentElement=r,this.mediaStream=i,this.callbacks=c,this.surface=this.createVideoElement(this.parentElement.clientWidth),r.append(this.surface)}return t.prototype.createVideoElement=function(r){var i=document.createElement("video");return i.style.width="".concat(r,"px"),i.style.display="block",i.muted=!0,i.setAttribute("muted","true"),i.playsInline=!0,i},t.prototype.setupSurface=function(){var r=this;this.surface.onabort=function(){throw"RenderedCameraImpl video surface onabort() called"},this.surface.onerror=function(){throw"RenderedCameraImpl video surface onerror() called"};var i=function(){var c=r.surface.clientWidth,d=r.surface.clientHeight;r.callbacks.onRenderSurfaceReady(c,d),r.surface.removeEventListener("playing",i)};this.surface.addEventListener("playing",i),this.surface.srcObject=this.mediaStream,this.surface.play()},t.create=function(r,i,c,d){return Bo(this,void 0,void 0,function(){var f,m;return Lo(this,function(x){switch(x.label){case 0:return f=new t(r,i,d),c.aspectRatio?(m={aspectRatio:c.aspectRatio},[4,f.getFirstTrackOrFail().applyConstraints(m)]):[3,2];case 1:x.sent(),x.label=2;case 2:return f.setupSurface(),[2,f]}})})},t.prototype.failIfClosed=function(){if(this.isClosed)throw"The RenderedCamera has already been closed."},t.prototype.getFirstTrackOrFail=function(){if(this.failIfClosed(),this.mediaStream.getVideoTracks().length===0)throw"No video tracks found";return this.mediaStream.getVideoTracks()[0]},t.prototype.pause=function(){this.failIfClosed(),this.surface.pause()},t.prototype.resume=function(r){this.failIfClosed();var i=this,c=function(){setTimeout(r,200),i.surface.removeEventListener("playing",c)};this.surface.addEventListener("playing",c),this.surface.play()},t.prototype.isPaused=function(){return this.failIfClosed(),this.surface.paused},t.prototype.getSurface=function(){return this.failIfClosed(),this.surface},t.prototype.getRunningTrackCapabilities=function(){return this.getFirstTrackOrFail().getCapabilities()},t.prototype.getRunningTrackSettings=function(){return this.getFirstTrackOrFail().getSettings()},t.prototype.applyVideoConstraints=function(r){return Bo(this,void 0,void 0,function(){return Lo(this,function(i){if("aspectRatio"in r)throw"Changing 'aspectRatio' in run-time is not yet supported.";return[2,this.getFirstTrackOrFail().applyConstraints(r)]})})},t.prototype.close=function(){if(this.isClosed)return Promise.resolve();var r=this;return new Promise(function(i,c){var d=r.mediaStream.getVideoTracks(),f=d.length,m=0;r.mediaStream.getVideoTracks().forEach(function(x){r.mediaStream.removeTrack(x),x.stop(),++m,m>=f&&(r.isClosed=!0,r.parentElement.removeChild(r.surface),i())})})},t.prototype.getCapabilities=function(){return new gw(this.getFirstTrackOrFail())},t})(),yw=(function(){function t(r){this.mediaStream=r}return t.prototype.render=function(r,i,c){return Bo(this,void 0,void 0,function(){return Lo(this,function(d){return[2,xw.create(r,this.mediaStream,i,c)]})})},t.create=function(r){return Bo(this,void 0,void 0,function(){var i,c;return Lo(this,function(d){switch(d.label){case 0:if(!navigator.mediaDevices)throw"navigator.mediaDevices not supported";return i={audio:!1,video:r},[4,navigator.mediaDevices.getUserMedia(i)];case 1:return c=d.sent(),[2,new t(c)]}})})},t})(),ml=function(t,r,i,c){function d(f){return f instanceof i?f:new i(function(m){m(f)})}return new(i||(i=Promise))(function(f,m){function x(E){try{g(c.next(E))}catch(A){m(A)}}function v(E){try{g(c.throw(E))}catch(A){m(A)}}function g(E){E.done?f(E.value):d(E.value).then(x,v)}g((c=c.apply(t,r||[])).next())})},gl=function(t,r){var i={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,d,f,m;return m={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function x(g){return function(E){return v([g,E])}}function v(g){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,g[0]&&(i=0)),i;)try{if(c=1,d&&(f=g[0]&2?d.return:g[0]?d.throw||((f=d.return)&&f.call(d),0):d.next)&&!(f=f.call(d,g[1])).done)return f;switch(d=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return i.label++,{value:g[1],done:!1};case 5:i.label++,d=g[1],g=[0];continue;case 7:g=i.ops.pop(),i.trys.pop();continue;default:if(f=i.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){i=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){i.label=g[1];break}if(g[0]===6&&i.label<f[1]){i.label=f[1],f=g;break}if(f&&i.label<f[2]){i.label=f[2],i.ops.push(g);break}f[2]&&i.ops.pop(),i.trys.pop();continue}g=r.call(t,i)}catch(E){g=[6,E],d=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},ww=(function(){function t(){}return t.failIfNotSupported=function(){return ml(this,void 0,void 0,function(){return gl(this,function(r){if(!navigator.mediaDevices)throw"navigator.mediaDevices not supported";return[2,new t]})})},t.prototype.create=function(r){return ml(this,void 0,void 0,function(){return gl(this,function(i){return[2,yw.create(r)]})})},t})(),_w=function(t,r,i,c){function d(f){return f instanceof i?f:new i(function(m){m(f)})}return new(i||(i=Promise))(function(f,m){function x(E){try{g(c.next(E))}catch(A){m(A)}}function v(E){try{g(c.throw(E))}catch(A){m(A)}}function g(E){E.done?f(E.value):d(E.value).then(x,v)}g((c=c.apply(t,r||[])).next())})},vw=function(t,r){var i={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,d,f,m;return m={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function x(g){return function(E){return v([g,E])}}function v(g){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,g[0]&&(i=0)),i;)try{if(c=1,d&&(f=g[0]&2?d.return:g[0]?d.throw||((f=d.return)&&f.call(d),0):d.next)&&!(f=f.call(d,g[1])).done)return f;switch(d=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return i.label++,{value:g[1],done:!1};case 5:i.label++,d=g[1],g=[0];continue;case 7:g=i.ops.pop(),i.trys.pop();continue;default:if(f=i.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){i=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){i.label=g[1];break}if(g[0]===6&&i.label<f[1]){i.label=f[1],f=g;break}if(f&&i.label<f[2]){i.label=f[2],i.ops.push(g);break}f[2]&&i.ops.pop(),i.trys.pop();continue}g=r.call(t,i)}catch(E){g=[6,E],d=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},Cw=(function(){function t(){}return t.retrieve=function(){if(navigator.mediaDevices)return t.getCamerasFromMediaDevices();var r=MediaStreamTrack;return MediaStreamTrack&&r.getSources?t.getCamerasFromMediaStreamTrack():t.rejectWithError()},t.rejectWithError=function(){var r=Rr.unableToQuerySupportedDevices();return t.isHttpsOrLocalhost()||(r=Rr.insecureContextCameraQueryError()),Promise.reject(r)},t.isHttpsOrLocalhost=function(){if(location.protocol==="https:")return!0;var r=location.host.split(":")[0];return r==="127.0.0.1"||r==="localhost"},t.getCamerasFromMediaDevices=function(){return _w(this,void 0,void 0,function(){var r,i,c,d,f,m,x;return vw(this,function(v){switch(v.label){case 0:return r=function(g){for(var E=g.getVideoTracks(),A=0,D=E;A<D.length;A++){var T=D[A];T.enabled=!1,T.stop(),g.removeTrack(T)}},[4,navigator.mediaDevices.getUserMedia({audio:!1,video:!0})];case 1:return i=v.sent(),[4,navigator.mediaDevices.enumerateDevices()];case 2:for(c=v.sent(),d=[],f=0,m=c;f<m.length;f++)x=m[f],x.kind==="videoinput"&&d.push({id:x.deviceId,label:x.label});return r(i),[2,d]}})})},t.getCamerasFromMediaStreamTrack=function(){return new Promise(function(r,i){var c=function(f){for(var m=[],x=0,v=f;x<v.length;x++){var g=v[x];g.kind==="video"&&m.push({id:g.id,label:g.label})}r(m)},d=MediaStreamTrack;d.getSources(c)})},t})(),Ot;(function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.NOT_STARTED=1]="NOT_STARTED",t[t.SCANNING=2]="SCANNING",t[t.PAUSED=3]="PAUSED"})(Ot||(Ot={}));var bw=(function(){function t(){this.state=Ot.NOT_STARTED,this.onGoingTransactionNewState=Ot.UNKNOWN}return t.prototype.directTransition=function(r){this.failIfTransitionOngoing(),this.validateTransition(r),this.state=r},t.prototype.startTransition=function(r){return this.failIfTransitionOngoing(),this.validateTransition(r),this.onGoingTransactionNewState=r,this},t.prototype.execute=function(){if(this.onGoingTransactionNewState===Ot.UNKNOWN)throw"Transaction is already cancelled, cannot execute().";var r=this.onGoingTransactionNewState;this.onGoingTransactionNewState=Ot.UNKNOWN,this.directTransition(r)},t.prototype.cancel=function(){if(this.onGoingTransactionNewState===Ot.UNKNOWN)throw"Transaction is already cancelled, cannot cancel().";this.onGoingTransactionNewState=Ot.UNKNOWN},t.prototype.getState=function(){return this.state},t.prototype.failIfTransitionOngoing=function(){if(this.onGoingTransactionNewState!==Ot.UNKNOWN)throw"Cannot transition to a new state, already under transition"},t.prototype.validateTransition=function(r){switch(this.state){case Ot.UNKNOWN:throw"Transition from unknown is not allowed";case Ot.NOT_STARTED:this.failIfNewStateIs(r,[Ot.PAUSED]);break;case Ot.SCANNING:break;case Ot.PAUSED:break}},t.prototype.failIfNewStateIs=function(r,i){for(var c=0,d=i;c<d.length;c++){var f=d[c];if(r===f)throw"Cannot transition from ".concat(this.state," to ").concat(r)}},t})(),Aw=(function(){function t(r){this.stateManager=r}return t.prototype.startTransition=function(r){return this.stateManager.startTransition(r)},t.prototype.directTransition=function(r){this.stateManager.directTransition(r)},t.prototype.getState=function(){return this.stateManager.getState()},t.prototype.canScanFile=function(){return this.stateManager.getState()===Ot.NOT_STARTED},t.prototype.isScanning=function(){return this.stateManager.getState()!==Ot.NOT_STARTED},t.prototype.isStrictlyScanning=function(){return this.stateManager.getState()===Ot.SCANNING},t.prototype.isPaused=function(){return this.stateManager.getState()===Ot.PAUSED},t})(),Ew=(function(){function t(){}return t.create=function(){return new Aw(new bw)},t})(),Iw=(function(){var t=function(r,i){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(c,d){c.__proto__=d}||function(c,d){for(var f in d)Object.prototype.hasOwnProperty.call(d,f)&&(c[f]=d[f])},t(r,i)};return function(r,i){if(typeof i!="function"&&i!==null)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");t(r,i);function c(){this.constructor=r}r.prototype=i===null?Object.create(i):(c.prototype=i.prototype,new c)}})(),ln=(function(t){Iw(r,t);function r(){return t!==null&&t.apply(this,arguments)||this}return r.DEFAULT_WIDTH=300,r.DEFAULT_WIDTH_OFFSET=2,r.FILE_SCAN_MIN_HEIGHT=300,r.FILE_SCAN_HIDDEN_CANVAS_PADDING=100,r.MIN_QR_BOX_SIZE=50,r.SHADED_LEFT=1,r.SHADED_RIGHT=2,r.SHADED_TOP=3,r.SHADED_BOTTOM=4,r.SHADED_REGION_ELEMENT_ID="qr-shaded-region",r.VERBOSE=!1,r.BORDER_SHADER_DEFAULT_COLOR="#ffffff",r.BORDER_SHADER_MATCH_COLOR="rgb(90, 193, 56)",r})(nw),Sw=(function(){function t(r,i){this.logger=i,this.fps=ln.SCAN_DEFAULT_FPS,r?(r.fps&&(this.fps=r.fps),this.disableFlip=r.disableFlip===!0,this.qrbox=r.qrbox,this.aspectRatio=r.aspectRatio,this.videoConstraints=r.videoConstraints):this.disableFlip=ln.DEFAULT_DISABLE_FLIP}return t.prototype.isMediaStreamConstraintsValid=function(){return this.videoConstraints?Wu.isMediaStreamConstraintsValid(this.videoConstraints,this.logger):(this.logger.logError("Empty videoConstraints",!0),!1)},t.prototype.isShadedBoxEnabled=function(){return!zn(this.qrbox)},t.create=function(r,i){return new t(r,i)},t})(),xl=(function(){function t(r,i){if(this.element=null,this.canvasElement=null,this.scannerPausedUiElement=null,this.hasBorderShaders=null,this.borderShaders=null,this.qrMatch=null,this.renderedCamera=null,this.qrRegion=null,this.context=null,this.lastScanImageFile=null,this.isScanning=!1,!document.getElementById(r))throw"HTML Element with id=".concat(r," not found");this.elementId=r,this.verbose=!1;var c;typeof i=="boolean"?this.verbose=i===!0:i&&(c=i,this.verbose=c.verbose===!0,c.experimentalFeatures),this.logger=new ow(this.verbose),this.qrcode=new fw(this.getSupportedFormats(i),this.getUseBarCodeDetectorIfSupported(c),this.verbose,this.logger),this.foreverScanTimeout,this.shouldScan=!0,this.stateManagerProxy=Ew.create()}return t.prototype.start=function(r,i,c,d){var f=this;if(!r)throw"cameraIdOrConfig is required";if(!c||typeof c!="function")throw"qrCodeSuccessCallback is required and should be a function.";var m;d?m=d:m=this.verbose?this.logger.log:function(){};var x=Sw.create(i,this.logger);this.clearElement();var v=!1;x.videoConstraints&&(x.isMediaStreamConstraintsValid()?v=!0:this.logger.logError("'videoConstraints' is not valid 'MediaStreamConstraints, it will be ignored.'",!0));var g=v,E=document.getElementById(this.elementId);E.clientWidth?E.clientWidth:ln.DEFAULT_WIDTH,E.style.position="relative",this.shouldScan=!0,this.element=E;var A=this,D=this.stateManagerProxy.startTransition(Ot.SCANNING);return new Promise(function(T,S){var P=g?x.videoConstraints:A.createVideoConstraints(r);if(!P){D.cancel(),S("videoConstraints should be defined");return}var M={};(!g||x.aspectRatio)&&(M.aspectRatio=x.aspectRatio);var ee={onRenderSurfaceReady:function($,F){A.setupUi($,F,x),A.isScanning=!0,A.foreverScan(x,c,m)}};ww.failIfNotSupported().then(function($){$.create(P).then(function(F){return F.render(f.element,M,ee).then(function(re){A.renderedCamera=re,D.execute(),T(null)}).catch(function(re){D.cancel(),S(re)})}).catch(function(F){D.cancel(),S(Rr.errorGettingUserMedia(F))})}).catch(function($){D.cancel(),S(Rr.cameraStreamingNotSupported())})})},t.prototype.pause=function(r){if(!this.stateManagerProxy.isStrictlyScanning())throw"Cannot pause, scanner is not scanning.";this.stateManagerProxy.directTransition(Ot.PAUSED),this.showPausedState(),(zn(r)||r!==!0)&&(r=!1),r&&this.renderedCamera&&this.renderedCamera.pause()},t.prototype.resume=function(){if(!this.stateManagerProxy.isPaused())throw"Cannot result, scanner is not paused.";if(!this.renderedCamera)throw"renderedCamera doesn't exist while trying resume()";var r=this,i=function(){r.stateManagerProxy.directTransition(Ot.SCANNING),r.hidePausedState()};if(!this.renderedCamera.isPaused()){i();return}this.renderedCamera.resume(function(){i()})},t.prototype.getState=function(){return this.stateManagerProxy.getState()},t.prototype.stop=function(){var r=this;if(!this.stateManagerProxy.isScanning())throw"Cannot stop, scanner is not running or paused.";var i=this.stateManagerProxy.startTransition(Ot.NOT_STARTED);this.shouldScan=!1,this.foreverScanTimeout&&clearTimeout(this.foreverScanTimeout);var c=function(){if(r.element){var f=document.getElementById(ln.SHADED_REGION_ELEMENT_ID);f&&r.element.removeChild(f)}},d=this;return this.renderedCamera.close().then(function(){return d.renderedCamera=null,d.element&&(d.element.removeChild(d.canvasElement),d.canvasElement=null),c(),d.qrRegion&&(d.qrRegion=null),d.context&&(d.context=null),i.execute(),d.hidePausedState(),d.isScanning=!1,Promise.resolve()})},t.prototype.scanFile=function(r,i){return this.scanFileV2(r,i).then(function(c){return c.decodedText})},t.prototype.scanFileV2=function(r,i){var c=this;if(!r||!(r instanceof File))throw"imageFile argument is mandatory and should be instance of File. Use 'event.target.files[0]'.";if(zn(i)&&(i=!0),!this.stateManagerProxy.canScanFile())throw"Cannot start file scan - ongoing camera scan";return new Promise(function(d,f){c.possiblyCloseLastScanImageFile(),c.clearElement(),c.lastScanImageFile=URL.createObjectURL(r);var m=new Image;m.onload=function(){var x=m.width,v=m.height,g=document.getElementById(c.elementId),E=g.clientWidth?g.clientWidth:ln.DEFAULT_WIDTH,A=Math.max(g.clientHeight?g.clientHeight:v,ln.FILE_SCAN_MIN_HEIGHT),D=c.computeCanvasDrawConfig(x,v,E,A);if(i){var T=c.createCanvasElement(E,A,"qr-canvas-visible");T.style.display="inline-block",g.appendChild(T);var S=T.getContext("2d");if(!S)throw"Unable to get 2d context from canvas";S.canvas.width=E,S.canvas.height=A,S.drawImage(m,0,0,x,v,D.x,D.y,D.width,D.height)}var P=ln.FILE_SCAN_HIDDEN_CANVAS_PADDING,M=Math.max(m.width,D.width),ee=Math.max(m.height,D.height),$=M+2*P,F=ee+2*P,re=c.createCanvasElement($,F);g.appendChild(re);var Z=re.getContext("2d");if(!Z)throw"Unable to get 2d context from canvas";Z.canvas.width=$,Z.canvas.height=F,Z.drawImage(m,0,0,x,v,P,P,M,ee);try{c.qrcode.decodeRobustlyAsync(re).then(function(B){d(cl.createFromQrcodeResult(B))}).catch(f)}catch(B){f("QR code parse error, error = ".concat(B))}},m.onerror=f,m.onabort=f,m.onstalled=f,m.onsuspend=f,m.src=URL.createObjectURL(r)})},t.prototype.clear=function(){this.clearElement()},t.getCameras=function(){return Cw.retrieve()},t.prototype.getRunningTrackCapabilities=function(){return this.getRenderedCameraOrFail().getRunningTrackCapabilities()},t.prototype.getRunningTrackSettings=function(){return this.getRenderedCameraOrFail().getRunningTrackSettings()},t.prototype.getRunningTrackCameraCapabilities=function(){return this.getRenderedCameraOrFail().getCapabilities()},t.prototype.applyVideoConstraints=function(r){if(r){if(!Wu.isMediaStreamConstraintsValid(r,this.logger))throw"invalid videoConstaints passed, check logs for more details"}else throw"videoConstaints is required argument.";return this.getRenderedCameraOrFail().applyVideoConstraints(r)},t.prototype.getRenderedCameraOrFail=function(){if(this.renderedCamera==null)throw"Scanning is not in running state, call this API only when QR code scanning using camera is in running state.";return this.renderedCamera},t.prototype.getSupportedFormats=function(r){var i=[Ce.QR_CODE,Ce.AZTEC,Ce.CODABAR,Ce.CODE_39,Ce.CODE_93,Ce.CODE_128,Ce.DATA_MATRIX,Ce.MAXICODE,Ce.ITF,Ce.EAN_13,Ce.EAN_8,Ce.PDF_417,Ce.RSS_14,Ce.RSS_EXPANDED,Ce.UPC_A,Ce.UPC_E,Ce.UPC_EAN_EXTENSION];if(!r||typeof r=="boolean"||!r.formatsToSupport)return i;if(!Array.isArray(r.formatsToSupport))throw"configOrVerbosityFlag.formatsToSupport should be undefined or an array.";if(r.formatsToSupport.length===0)throw"Atleast 1 formatsToSupport is needed.";for(var c=[],d=0,f=r.formatsToSupport;d<f.length;d++){var m=f[d];tw(m)?c.push(m):this.logger.warn("Invalid format: ".concat(m," passed in config, ignoring."))}if(c.length===0)throw"None of formatsToSupport match supported values.";return c},t.prototype.getUseBarCodeDetectorIfSupported=function(r){if(zn(r))return!0;if(!zn(r.useBarCodeDetectorIfSupported))return r.useBarCodeDetectorIfSupported!==!1;if(zn(r.experimentalFeatures))return!0;var i=r.experimentalFeatures;return zn(i.useBarCodeDetectorIfSupported)?!0:i.useBarCodeDetectorIfSupported!==!1},t.prototype.validateQrboxSize=function(r,i,c){var d=this,f=c.qrbox;this.validateQrboxConfig(f);var m=this.toQrdimensions(r,i,f),x=function(g){if(g<ln.MIN_QR_BOX_SIZE)throw"minimum size of 'config.qrbox' dimension value is"+" ".concat(ln.MIN_QR_BOX_SIZE,"px.")},v=function(g){return g>r&&(d.logger.warn("`qrbox.width` or `qrbox` is larger than the width of the root element. The width will be truncated to the width of root element."),g=r),g};x(m.width),x(m.height),m.width=v(m.width)},t.prototype.validateQrboxConfig=function(r){if(typeof r!="number"&&typeof r!="function"&&(r.width===void 0||r.height===void 0))throw"Invalid instance of QrDimensions passed for 'config.qrbox'. Both 'width' and 'height' should be set."},t.prototype.toQrdimensions=function(r,i,c){if(typeof c=="number")return{width:c,height:c};if(typeof c=="function")try{return c(r,i)}catch(d){throw new Error("qrbox config was passed as a function but it failed with unknown error"+d)}return c},t.prototype.setupUi=function(r,i,c){c.isShadedBoxEnabled()&&this.validateQrboxSize(r,i,c);var d=zn(c.qrbox)?{width:r,height:i}:c.qrbox;this.validateQrboxConfig(d);var f=this.toQrdimensions(r,i,d);f.height>i&&this.logger.warn("[Html5Qrcode] config.qrbox has height that isgreater than the height of the video stream. Shading will be ignored");var m=c.isShadedBoxEnabled()&&f.height<=i,x={x:0,y:0,width:r,height:i},v=m?this.getShadedRegionBounds(r,i,f):x,g=this.createCanvasElement(v.width,v.height),E={willReadFrequently:!0},A=g.getContext("2d",E);A.canvas.width=v.width,A.canvas.height=v.height,this.element.append(g),m&&this.possiblyInsertShadingElement(this.element,r,i,f),this.createScannerPausedUiElement(this.element),this.qrRegion=v,this.context=A,this.canvasElement=g},t.prototype.createScannerPausedUiElement=function(r){var i=document.createElement("div");i.innerText=Rr.scannerPaused(),i.style.display="none",i.style.position="absolute",i.style.top="0px",i.style.zIndex="1",i.style.background="rgba(9, 9, 9, 0.46)",i.style.color="#FFECEC",i.style.textAlign="center",i.style.width="100%",r.appendChild(i),this.scannerPausedUiElement=i},t.prototype.scanContext=function(r,i){var c=this;return this.stateManagerProxy.isPaused()?Promise.resolve(!1):this.qrcode.decodeAsync(this.canvasElement).then(function(d){return r(d.text,cl.createFromQrcodeResult(d)),c.possiblyUpdateShaders(!0),!0}).catch(function(d){c.possiblyUpdateShaders(!1);var f=Rr.codeParseError(d);return i(f,rw.createFrom(f)),!1})},t.prototype.foreverScan=function(r,i,c){var d=this;if(this.shouldScan&&this.renderedCamera){var f=this.renderedCamera.getSurface(),m=f.videoWidth/f.clientWidth,x=f.videoHeight/f.clientHeight;if(!this.qrRegion)throw"qrRegion undefined when localMediaStream is ready.";var v=this.qrRegion.width*m,g=this.qrRegion.height*x,E=this.qrRegion.x*m,A=this.qrRegion.y*x;this.context.drawImage(f,E,A,v,g,0,0,this.qrRegion.width,this.qrRegion.height);var D=function(){d.foreverScanTimeout=setTimeout(function(){d.foreverScan(r,i,c)},d.getTimeoutFps(r.fps))};this.scanContext(i,c).then(function(T){!T&&r.disableFlip!==!0?(d.context.translate(d.context.canvas.width,0),d.context.scale(-1,1),d.scanContext(i,c).finally(function(){D()})):D()}).catch(function(T){d.logger.logError("Error happend while scanning context",T),D()})}},t.prototype.createVideoConstraints=function(r){if(typeof r=="string")return{deviceId:{exact:r}};if(typeof r=="object"){var i="facingMode",c="deviceId",d={user:!0,environment:!0},f="exact",m=function(S){if(S in d)return!0;throw"config has invalid 'facingMode' value = "+"'".concat(S,"'")},x=Object.keys(r);if(x.length!==1)throw"'cameraIdOrConfig' object should have exactly 1 key,"+" if passed as an object, found ".concat(x.length," keys");var v=Object.keys(r)[0];if(v!==i&&v!==c)throw"Only '".concat(i,"' and '").concat(c,"' ")+" are supported for 'cameraIdOrConfig'";if(v===i){var g=r.facingMode;if(typeof g=="string"){if(m(g))return{facingMode:g}}else if(typeof g=="object")if(f in g){if(m(g["".concat(f)]))return{facingMode:{exact:g["".concat(f)]}}}else throw"'facingMode' should be string or object with"+" ".concat(f," as key.");else{var E=typeof g;throw"Invalid type of 'facingMode' = ".concat(E)}}else{var A=r.deviceId;if(typeof A=="string")return{deviceId:A};if(typeof A=="object"){if(f in A)return{deviceId:{exact:A["".concat(f)]}};throw"'deviceId' should be string or object with"+" ".concat(f," as key.")}else{var D=typeof A;throw"Invalid type of 'deviceId' = ".concat(D)}}}var T=typeof r;throw"Invalid type of 'cameraIdOrConfig' = ".concat(T)},t.prototype.computeCanvasDrawConfig=function(r,i,c,d){if(r<=c&&i<=d){var f=(c-r)/2,m=(d-i)/2;return{x:f,y:m,width:r,height:i}}else{var x=r,v=i;return r>c&&(i=c/r*i,r=c),i>d&&(r=d/i*r,i=d),this.logger.log("Image downsampled from "+"".concat(x,"X").concat(v)+" to ".concat(r,"X").concat(i,".")),this.computeCanvasDrawConfig(r,i,c,d)}},t.prototype.clearElement=function(){if(this.stateManagerProxy.isScanning())throw"Cannot clear while scan is ongoing, close it first.";var r=document.getElementById(this.elementId);r&&(r.innerHTML="")},t.prototype.possiblyUpdateShaders=function(r){this.qrMatch!==r&&(this.hasBorderShaders&&this.borderShaders&&this.borderShaders.length&&this.borderShaders.forEach(function(i){i.style.backgroundColor=r?ln.BORDER_SHADER_MATCH_COLOR:ln.BORDER_SHADER_DEFAULT_COLOR}),this.qrMatch=r)},t.prototype.possiblyCloseLastScanImageFile=function(){this.lastScanImageFile&&(URL.revokeObjectURL(this.lastScanImageFile),this.lastScanImageFile=null)},t.prototype.createCanvasElement=function(r,i,c){var d=r,f=i,m=document.createElement("canvas");return m.style.width="".concat(d,"px"),m.style.height="".concat(f,"px"),m.style.display="none",m.id=zn(c)?"qr-canvas":c,m},t.prototype.getShadedRegionBounds=function(r,i,c){if(c.width>r||c.height>i)throw"'config.qrbox' dimensions should not be greater than the dimensions of the root HTML element.";return{x:(r-c.width)/2,y:(i-c.height)/2,width:c.width,height:c.height}},t.prototype.possiblyInsertShadingElement=function(r,i,c,d){if(!(i-d.width<1||c-d.height<1)){var f=document.createElement("div");f.style.position="absolute";var m=(i-d.width)/2,x=(c-d.height)/2;if(f.style.borderLeft="".concat(m,"px solid rgba(0, 0, 0, 0.48)"),f.style.borderRight="".concat(m,"px solid rgba(0, 0, 0, 0.48)"),f.style.borderTop="".concat(x,"px solid rgba(0, 0, 0, 0.48)"),f.style.borderBottom="".concat(x,"px solid rgba(0, 0, 0, 0.48)"),f.style.boxSizing="border-box",f.style.top="0px",f.style.bottom="0px",f.style.left="0px",f.style.right="0px",f.id="".concat(ln.SHADED_REGION_ELEMENT_ID),i-d.width<11||c-d.height<11)this.hasBorderShaders=!1;else{var v=5,g=40;this.insertShaderBorders(f,g,v,-v,null,0,!0),this.insertShaderBorders(f,g,v,-v,null,0,!1),this.insertShaderBorders(f,g,v,null,-v,0,!0),this.insertShaderBorders(f,g,v,null,-v,0,!1),this.insertShaderBorders(f,v,g+v,-v,null,-v,!0),this.insertShaderBorders(f,v,g+v,null,-v,-v,!0),this.insertShaderBorders(f,v,g+v,-v,null,-v,!1),this.insertShaderBorders(f,v,g+v,null,-v,-v,!1),this.hasBorderShaders=!0}r.append(f)}},t.prototype.insertShaderBorders=function(r,i,c,d,f,m,x){var v=document.createElement("div");v.style.position="absolute",v.style.backgroundColor=ln.BORDER_SHADER_DEFAULT_COLOR,v.style.width="".concat(i,"px"),v.style.height="".concat(c,"px"),d!==null&&(v.style.top="".concat(d,"px")),f!==null&&(v.style.bottom="".concat(f,"px")),x?v.style.left="".concat(m,"px"):v.style.right="".concat(m,"px"),this.borderShaders||(this.borderShaders=[]),this.borderShaders.push(v),r.appendChild(v)},t.prototype.showPausedState=function(){if(!this.scannerPausedUiElement)throw"[internal error] scanner paused UI element not found";this.scannerPausedUiElement.style.display="block"},t.prototype.hidePausedState=function(){if(!this.scannerPausedUiElement)throw"[internal error] scanner paused UI element not found";this.scannerPausedUiElement.style.display="none"},t.prototype.getTimeoutFps=function(r){return 1e3/r},t})(),yl;(function(t){t[t.STATUS_DEFAULT=0]="STATUS_DEFAULT",t[t.STATUS_SUCCESS=1]="STATUS_SUCCESS",t[t.STATUS_WARNING=2]="STATUS_WARNING",t[t.STATUS_REQUESTING_PERMISSION=3]="STATUS_REQUESTING_PERMISSION"})(yl||(yl={}));const Tw={class:"scan-code"},Nw={class:"btn"},Ow={class:"left-back"},kw=_.defineComponent({name:"QrCodeScan",__name:"QrCodeScan",emits:["scanSuccess"],setup(t,{emit:r}){const i=r,c=Sd.IconScan(),d=_.reactive({html5QrCode:null}),f=_.ref(!1),m=()=>{if(!d.html5QrCode){it("摄像头无访问权限!");return}f.value=!0,d.html5QrCode.start({facingMode:"environment"},{fps:30,aspectRatio:1,supportedScanTypes:[oo.SCAN_TYPE_CAMERA],showTorchButtonIfSupported:!0,showZoomSliderIfSupported:!0,defaultZoomValueIfSupported:2,useBarCodeDetectorIfSupported:!0},A=>{try{const T=new URL(A).searchParams.get("sessionId");T?i("scanSuccess",T):it("无效的二维码")}catch{it("无效的二维码")}E()}).catch(A=>{console.log(A),it({message:"二维码识别失败",duration:3e3})})},x=()=>{g().then(()=>{m()})},v=()=>{E()},g=()=>xl.getCameras().then(A=>{A&&A.length&&(d.html5QrCode=new xl("reader"))}).catch(()=>{it({message:"摄像头无访问权限!",duration:3e3})}),E=()=>{d.html5QrCode&&d.html5QrCode.stop().then(A=>{console.log("停止扫码",A)}).catch(A=>{console.log(A),it("停止扫码失败")}).finally(()=>{f.value=!1})};return _.onUnmounted(()=>{d.html5QrCode&&d.html5QrCode.isScanning&&E()}),(A,D)=>{const T=rs;return _.openBlock(),_.createElementBlock("div",null,[_.createVNode(_.unref(Vt.TrIconButton),{icon:_.unref(c),size:"28",svgSize:"20",onClick:D[0]||(D[0]=S=>x())},null,8,["icon"]),(_.openBlock(),_.createBlock(_.Teleport,{to:"body"},[_.withDirectives(_.createElementVNode("div",Tw,[D[1]||(D[1]=_.createElementVNode("div",{class:"container"},[_.createElementVNode("div",{class:"qrcode"},[_.createElementVNode("div",{id:"reader"})])],-1)),_.createElementVNode("div",Nw,[_.createElementVNode("div",Ow,[_.createVNode(T,{name:"arrow-left",onClick:v})])])],512),[[_.vShow,f.value]])]))])}}}),Rw=nr(kw,[["__scopeId","data-v-2d988579"]]);function is(t,r,i){const c=_.computed(()=>t?Array.isArray(t)?t:t.value:[]),d=()=>{const E=c.value;if(E.length===0)return"";if(r){const D=typeof r=="string"?r:r.value;if(D&&E.some(T=>T.id===D))return D}const A=E.find(D=>D.isDefault);return A?A.id:E[0].id};let f,m=!1;if(r&&typeof r!="string")f=r,m=!0,(!f.value||!c.value.some(E=>E.id===f.value))&&(f.value=d());else{let E;r&&typeof r=="string"&&(E=r),f=_.ref(E&&c.value.some(A=>A.id===E)?E:d())}(!m||i)&&_.watch(f,E=>{i&&i(E)});const x=_.computed(()=>c.value.find(E=>E.id===f.value)),v=_.computed(()=>c.value);return{selectedModelId:f,selectedModel:x,availableModels:v,setSelectedModel:E=>{c.value.find(D=>D.id===E)?f.value=E:console.warn(`[useModel] Model not found: ${E}`)}}}const Mw=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const Dw=Object.prototype.toString,Pw=t=>Dw.call(t)==="[object Object]",No=()=>{};function wi(t){return Array.isArray(t)?t:[t]}function Bw(t,r,i){return _.watch(t,r,{...i,immediate:!0})}const qu=Mw?window:void 0;function Xr(t){var r;const i=_.toValue(t);return(r=i?.$el)!==null&&r!==void 0?r:i}function _i(...t){const r=(c,d,f,m)=>(c.addEventListener(d,f,m),()=>c.removeEventListener(d,f,m)),i=_.computed(()=>{const c=wi(_.toValue(t[0])).filter(d=>d!=null);return c.every(d=>typeof d!="string")?c:void 0});return Bw(()=>{var c,d;return[(c=(d=i.value)===null||d===void 0?void 0:d.map(f=>Xr(f)))!==null&&c!==void 0?c:[qu].filter(f=>f!=null),wi(_.toValue(i.value?t[1]:t[0])),wi(_.unref(i.value?t[2]:t[1])),_.toValue(i.value?t[3]:t[2])]},([c,d,f,m],x,v)=>{if(!c?.length||!d?.length||!f?.length)return;const g=Pw(m)?{...m}:m,E=c.flatMap(A=>d.flatMap(D=>f.map(T=>r(A,D,T,g))));v(()=>{E.forEach(A=>A())})},{flush:"post"})}function Lw(t,r,i={}){const{window:c=qu,ignore:d=[],capture:f=!0,detectIframe:m=!1,controls:x=!1}=i;if(!c)return x?{stop:No,cancel:No,trigger:No}:No;let v=!0;const g=M=>_.toValue(d).some(ee=>{if(typeof ee=="string")return Array.from(c.document.querySelectorAll(ee)).some($=>$===M.target||M.composedPath().includes($));{const $=Xr(ee);return $&&(M.target===$||M.composedPath().includes($))}});function E(M){const ee=_.toValue(M);return ee&&ee.$.subTree.shapeFlag===16}function A(M,ee){const $=_.toValue(M),F=$.$.subTree&&$.$.subTree.children;return F==null||!Array.isArray(F)?!1:F.some(re=>re.el===ee.target||ee.composedPath().includes(re.el))}const D=M=>{const ee=Xr(t);if(M.target!=null&&!(!(ee instanceof Element)&&E(t)&&A(t,M))&&!(!ee||ee===M.target||M.composedPath().includes(ee))){if("detail"in M&&M.detail===0&&(v=!g(M)),!v){v=!0;return}r(M)}};let T=!1;const S=[_i(c,"click",M=>{T||(T=!0,setTimeout(()=>{T=!1},0),D(M))},{passive:!0,capture:f}),_i(c,"pointerdown",M=>{const ee=Xr(t);v=!g(M)&&!!(ee&&!M.composedPath().includes(ee))},{passive:!0}),m&&_i(c,"blur",M=>{setTimeout(()=>{const ee=Xr(t);let $=c.document.activeElement;for(;$?.shadowRoot;)$=$.shadowRoot.activeElement;$?.tagName==="IFRAME"&&!ee?.contains(c.document.activeElement)&&r(M)},0)},{passive:!0})].filter(Boolean),P=()=>S.forEach(M=>M());return x?{stop:P,cancel:()=>{v=!1},trigger:M=>{v=!0,D(M),v=!1}}:P}const Fw=["data-active","disabled"],Uw=_.defineComponent({__name:"Button",props:{active:{type:Boolean},rounded:{type:Boolean},size:{default:"medium"},disabled:{type:Boolean}},setup(t){return(r,i)=>(_.openBlock(),_.createElementBlock("button",{class:_.normalizeClass(["button",{rounded:t.rounded,[t.size]:!0}]),"data-active":t.active||void 0,disabled:t.disabled||void 0},[_.renderSlot(r.$slots,"default",{},void 0,!0)],10,Fw))}}),ss=nr(Uw,[["__scopeId","data-v-6f582cce"]]),zw={viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",fill:"none"};function Vw(t,r){return _.openBlock(),_.createElementBlock("svg",zw,[...r[0]||(r[0]=[_.createElementVNode("rect",{id:"大模型",width:"16.000000",height:"16.000000",x:"0.000000",y:"0.000000"},null,-1),_.createElementVNode("path",{id:"矢量 90",d:"M13.683 2.26904C12.5753 1.16177 10.344 1.47577 8.02582 2.86527C5.70758 1.47576 3.47637 1.16179 2.36913 2.26904C1.2619 3.37646 1.57573 5.60771 2.96524 7.92589C1.57573 10.2441 1.2619 12.4754 2.36913 13.5827C3.47637 14.6901 5.7078 14.3762 8.02599 12.9867C10.344 14.3762 12.5752 14.6901 13.6825 13.5827C14.7901 12.4754 14.4761 10.2441 13.0866 7.92594C14.4761 5.60775 14.7902 3.37646 13.683 2.26904ZM10.8544 5.09764C11.4667 5.70995 12.0076 6.34819 12.4699 6.99044C12.7244 6.52061 12.9268 6.06037 13.077 5.60959C13.2948 4.95652 13.3832 4.38597 13.3426 3.89769C13.3089 3.49437 13.1869 3.18725 12.9754 2.97631C12.7645 2.76513 12.4574 2.64282 12.0541 2.60912C11.5658 2.56835 10.9955 2.65698 10.3422 2.87475C9.89153 3.02497 9.43121 3.22735 8.96135 3.48197C9.60365 3.94428 10.242 4.48527 10.8544 5.09764ZM5.70991 2.87475C6.16049 3.02494 6.62073 3.22729 7.09051 3.48185C6.44826 3.94412 5.81002 4.48507 5.19771 5.09739C4.58523 5.70982 4.04417 6.34819 3.58181 6.99055C3.32716 6.52071 3.1248 6.06037 2.97459 5.60959C2.75682 4.95677 2.66844 4.38597 2.70897 3.89769C2.74266 3.49437 2.86522 3.18725 3.07615 2.97631C3.28709 2.76513 3.59421 2.64282 3.99753 2.60912C4.4858 2.5686 5.0566 2.65698 5.70991 2.87475ZM5.90473 5.80466Q4.89236 6.81738 4.14938 7.92595C4.64428 8.66515 5.2294 9.3722 5.90473 10.0473C6.57966 10.7222 7.28696 11.3074 8.02584 11.8027C8.76507 11.3074 9.47197 10.7222 10.1474 10.0473C10.8222 9.37218 11.4074 8.66511 11.9027 7.92588Q11.1597 6.81736 10.1474 5.80466C9.47203 5.12956 8.7652 4.54447 8.02604 4.04937C7.28683 4.54447 6.5796 5.12956 5.90473 5.80466ZM7.99992 6.90011C7.44768 6.90011 6.99993 7.34787 6.99993 7.90011C6.99993 8.45235 7.44768 8.9001 7.99992 8.9001C8.55216 8.9001 8.99991 8.45235 8.99991 7.90011C8.99991 7.34787 8.55216 6.90011 7.99992 6.90011ZM10.3422 12.9772C9.89161 12.827 9.43138 12.6246 8.96148 12.37C9.60377 11.9077 10.242 11.3667 10.8544 10.7543C11.4667 10.142 12.0077 9.50369 12.4699 8.8614C12.7245 9.33127 12.9268 9.79154 13.077 10.2421C13.2948 10.8952 13.3832 11.4658 13.3426 11.954C13.3089 12.3574 13.1864 12.6647 12.9754 12.8757C12.7645 13.0866 12.4574 13.2089 12.0541 13.2426C11.5658 13.2834 10.995 13.195 10.3422 12.9772ZM2.97459 10.2421C3.12478 9.7914 3.32733 9.3312 3.58196 8.86141C4.04428 9.50369 4.5853 10.142 5.19771 10.7543C5.81003 11.3667 6.44827 11.9077 7.09052 12.37C6.62074 12.6246 6.16049 12.827 5.70991 12.9772C5.0566 13.195 4.48629 13.2834 3.99802 13.2426C3.5947 13.2089 3.28709 13.0866 3.07615 12.8757C2.86522 12.6647 2.74315 12.3574 2.70946 11.954C2.66844 11.4658 2.75682 10.8952 2.97459 10.2421Z",fill:"rgb(89,89,89)","fill-rule":"evenodd"},null,-1)])])}const Zw={render:Vw},$w={class:"button-text"},jw={class:"dropdown-menu__items"},Hw=["onClick"],Ww=_.defineComponent({__name:"ModelSwitch",props:_.mergeModels({modelConfigs:{}},{selectedModelId:{type:String,default:void 0,required:!1},selectedModelIdModifiers:{}}),emits:["update:selectedModelId"],setup(t){const r=t,i=_.useModel(t,"selectedModelId"),c=_.computed(()=>{const T=r.modelConfigs;return T?Array.isArray(T)?T:T.value:[]}),{selectedModel:d,availableModels:f,setSelectedModel:m}=is(c,i),x=_.ref(!1),v=T=>{m(T),E()},g=()=>{x.value=!x.value},E=()=>{x.value=!1},A=_.ref(null),D=_.ref(null);return Lw(D,()=>{E()},{ignore:[A]}),(T,S)=>(_.openBlock(),_.createElementBlock("div",{class:"model-switch-wrapper",ref_key:"wrapperRef",ref:A},[_.createVNode(ss,{size:"small",class:"action-button",rounded:"",onClick:g},{default:_.withCtx(()=>[(_.openBlock(),_.createBlock(_.resolveDynamicComponent(_.unref(d)?.icon),{width:16,height:16,class:"selected-model__icon"})),_.createElementVNode("span",$w,_.toDisplayString(_.unref(d)?.label),1),_.createVNode(_.unref(Zw),{width:16,height:16})]),_:1}),_.createVNode(_.Transition,{name:"dropdown"},{default:_.withCtx(()=>[x.value?(_.openBlock(),_.createElementBlock("div",{key:0,class:"dropdown-menu",ref_key:"dropdownMenuRef",ref:D},[_.createElementVNode("div",jw,[(_.openBlock(!0),_.createElementBlock(_.Fragment,null,_.renderList(_.unref(f),P=>(_.openBlock(),_.createElementBlock("div",{key:P.id,class:_.normalizeClass(["dropdown-menu__item",{"active-menu":P.id===i.value}]),onClick:_.withModifiers(M=>v(P.id),["stop"])},[P.icon?(_.openBlock(),_.createBlock(_.resolveDynamicComponent(P.icon),{key:0,width:16,height:16,class:"dropdown-menu__icon"})):_.createCommentVNode("",!0),_.createElementVNode("span",null,_.toDisplayString(P.label),1)],10,Hw))),128))])],512)):_.createCommentVNode("",!0)]),_:1}),x.value?(_.openBlock(),_.createElementBlock("div",{key:0,class:"dropdown-overlay",onClick:E})):_.createCommentVNode("",!0)],512))}}),Gw=nr(Ww,[["__scopeId","data-v-475491fd"]]),qw={key:0,class:"active-count"},Xw=_.defineComponent({__name:"PluginToggleButton",props:{installedPlugins:{}},emits:["click"],setup(t){const r=t,i=_.computed(()=>r.installedPlugins.filter(c=>c.enabled).length);return(c,d)=>(_.openBlock(),_.createBlock(ss,{size:"small",class:"action-button",active:i.value>0,rounded:"",onClick:d[0]||(d[0]=f=>c.$emit("click"))},{default:_.withCtx(()=>[_.createVNode(_.unref(Mr.IconPlugin),{class:"icon",style:{"font-size":"16px"}}),d[1]||(d[1]=_.createElementVNode("span",{class:"button-text"},"扩展",-1)),i.value>0?(_.openBlock(),_.createElementBlock("span",qw,_.toDisplayString(i.value),1)):_.createCommentVNode("",!0)]),_:1},8,["active"]))}}),Yw=nr(Xw,[["__scopeId","data-v-c2a16c66"]]),Kw={"data-v-99394ae9":"",viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",width:"16.000000",height:"16.000000",fill:"none",customFrame:"#000000",size:"16"};function Jw(t,r){return _.openBlock(),_.createElementBlock("svg",Kw,[...r[0]||(r[0]=[_.createElementVNode("rect",{id:"生成式UI",width:"16.000000",height:"16.000000",x:"0.000000",y:"0.000000",fill:"currentColor","fill-opacity":"0"},null,-1),_.createElementVNode("path",{id:"矢量 154",d:"M7.41014 2.09741L7.67112 2.70606C7.68333 2.73438 7.70579 2.75684 7.73411 2.76905L8.34275 3.02979C8.43968 3.0713 8.43968 3.20875 8.34275 3.25025L7.73411 3.51124C7.70579 3.52345 7.68333 3.54591 7.67112 3.57423L7.41014 4.18288C7.36863 4.2798 7.23118 4.2798 7.18968 4.18288L6.92894 3.57423C6.91673 3.54591 6.89427 3.52345 6.86595 3.51124L6.25731 3.25025C6.16039 3.20875 6.16039 3.0713 6.25731 3.02979L6.86595 2.76905C6.89427 2.75684 6.91673 2.73438 6.92894 2.70606L7.18968 2.09741C7.23118 2.00049 7.36863 2.00049 7.41014 2.09741ZM4.57006 11.9625L7.27611 8.09746L9.69944 4.63674L10.592 3.36207C10.6899 3.22218 10.8017 3.09864 10.9272 2.99122C11.0529 2.88404 11.1926 2.79297 11.3459 2.71802C11.4992 2.64332 11.657 2.58936 11.8191 2.5564C11.9809 2.52369 12.1472 2.51172 12.3176 2.52051C12.5315 2.53174 12.7336 2.57373 12.9238 2.64649C13.0678 2.70118 13.205 2.77369 13.3354 2.86353C13.4651 2.95289 13.5813 3.05445 13.6836 3.16822C13.8064 3.3047 13.9094 3.45851 13.9929 3.6299C14.0766 3.80128 14.1342 3.97731 14.1662 4.15773C14.1928 4.30861 14.2014 4.46267 14.1919 4.61989C14.1823 4.7781 14.1547 4.93069 14.1096 5.07791C14.0495 5.27249 13.958 5.45755 13.8352 5.63309L7.81321 14.2335Q7.66985 14.4382 7.48649 14.5965Q7.4825 14.6 7.4785 14.6034Q7.29063 14.7641 7.06102 14.8766C6.90794 14.9513 6.75072 15.0052 6.5891 15.0384C6.42748 15.0714 6.2617 15.0836 6.09154 15.0751C5.87743 15.0643 5.67504 15.0226 5.48436 14.9503C5.34008 14.8956 5.20287 14.8233 5.07201 14.7335C4.94213 14.6444 4.82592 14.5428 4.72313 14.4291C4.60033 14.2928 4.49682 14.1388 4.41308 13.9674C4.32934 13.7958 4.27123 13.6197 4.23925 13.4391C4.21239 13.2882 4.20385 13.1339 4.21313 12.9767C4.22265 12.8184 4.24999 12.6656 4.2954 12.5184C4.35546 12.3233 4.44701 12.138 4.57006 11.9625ZM4.7185 4.67361L4.18383 3.42579C4.11449 3.26441 3.88549 3.26441 3.81616 3.42579L3.28149 4.67361C3.26123 4.72073 3.22363 4.75832 3.17651 4.77859L1.92871 5.31326C1.76733 5.3826 1.76733 5.6116 1.92871 5.68094L3.17651 6.21561C3.22363 6.23587 3.26123 6.27347 3.28149 6.32059L3.81616 7.56841C3.88549 7.73003 4.11449 7.73003 4.18383 7.56841L4.7185 6.32059C4.73876 6.27347 4.77636 6.23587 4.82348 6.21561L6.07128 5.68094C6.23265 5.6116 6.23265 5.3826 6.07128 5.31326L4.82348 4.77859C4.77636 4.75832 4.73876 4.72073 4.7185 4.67361ZM5.38915 12.536C5.32006 12.6346 5.27099 12.7384 5.24169 12.8475C5.22533 12.9088 5.21532 12.9718 5.21141 13.0362C5.20726 13.1063 5.21044 13.1751 5.22094 13.2428C5.23583 13.3402 5.2661 13.4354 5.31151 13.5282C5.35692 13.6209 5.41332 13.7032 5.48095 13.775C5.52806 13.8248 5.58031 13.8695 5.63817 13.9093C5.69139 13.9459 5.7473 13.9764 5.80565 14.0011C5.9099 14.0453 6.02196 14.0702 6.14208 14.0763C6.2263 14.0807 6.30834 14.0746 6.38841 14.0582C6.46825 14.0418 6.54613 14.015 6.62181 13.9781C6.69749 13.941 6.76634 13.8961 6.8286 13.8429C6.89061 13.7899 6.94578 13.7289 6.99412 13.6598L11.9415 6.59405L10.3381 5.46789L5.38915 12.536ZM10.9168 4.6415L12.5202 5.76762L13.0161 5.05935C13.0849 4.96096 13.134 4.85745 13.1633 4.74831C13.1797 4.68703 13.1897 4.62429 13.1936 4.55959C13.198 4.48977 13.1948 4.42092 13.1843 4.35329C13.1694 4.25588 13.1394 4.16091 13.0942 4.06813C13.0488 3.97536 12.9926 3.89308 12.925 3.8213C12.8781 3.7715 12.8259 3.72682 12.7683 3.68703C12.7148 3.6504 12.6591 3.61964 12.6008 3.59474C12.4968 3.55079 12.385 3.5254 12.2651 3.5193C12.1806 3.51466 12.0984 3.52076 12.0183 3.53688C11.9382 3.55324 11.8601 3.57985 11.7841 3.61696C11.7082 3.65407 11.6391 3.69899 11.5771 3.75221C11.5149 3.80519 11.4594 3.86647 11.4111 3.93556L10.9168 4.6415Z",fill:"currentColor","fill-rule":"evenodd"},null,-1)])])}const Qw={render:Jw},e_=_.defineComponent({__name:"GenUISwitch",props:{genuiEnabled:{type:Boolean,type:Boolean,default:!1,required:!1},genuiEnabledModifiers:{}},emits:["update:genuiEnabled"],setup(t){const r=_.useModel(t,"genuiEnabled"),i=()=>{r.value=!r.value};return(c,d)=>(_.openBlock(),_.createBlock(ss,{class:"action-button",active:r.value,rounded:"",size:"small",onClick:i},{default:_.withCtx(()=>[_.createVNode(_.unref(Qw),{width:16,height:16}),d[0]||(d[0]=_.createElementVNode("span",{class:"button-text"},"生成式UI",-1))]),_:1},8,["active"]))}}),t_=nr(e_,[["__scopeId","data-v-7f3b0372"]]),n_={class:"bubble-image-wrapper"},r_=["src"],o_=["src"],i_=_.defineComponent({__name:"BubbleImageRenderer",props:{content:{}},setup(t){const r=_.ref(!1),i=_.ref(null),c=()=>{r.value=!0},d=()=>{r.value=!1};return _.watch(r,f=>{f&&_.nextTick(()=>{i.value?.focus()})}),(f,m)=>(_.openBlock(),_.createElementBlock("div",n_,[_.createElementVNode("img",{src:t.content,class:"bubble-image",alt:"用户上传的图片",onClick:c},null,8,r_),(_.openBlock(),_.createBlock(_.Teleport,{to:"body"},[r.value?(_.openBlock(),_.createElementBlock("div",{key:0,class:"image-preview-modal",role:"dialog","aria-modal":"true","aria-label":"图片预览",onClick:d,onKeydown:_.withKeys(d,["esc"])},[_.createElementVNode("button",{ref_key:"closeButtonRef",ref:i,class:"preview-close",type:"button","aria-label":"关闭预览",onClick:d},[...m[1]||(m[1]=[_.createElementVNode("svg",{viewBox:"0 0 1024 1024",width:"24",height:"24","aria-hidden":"true"},[_.createElementVNode("path",{d:"M563.8 512l262.5-312.9c4.4-5.2.7-13.1-6.1-13.1h-79.8c-4.7 0-9.2 2.1-12.3 5.7L511.6 449.8 295.1 191.7c-3-3.6-7.5-5.7-12.3-5.7H203c-6.8 0-10.5 7.9-6.1 13.1L459.4 512 196.9 824.9A7.95 7.95 0 0 0 203 838h79.8c4.7 0 9.2-2.1 12.3-5.7l216.5-258.1 216.5 258.1c3 3.6 7.5 5.7 12.3 5.7h79.8c6.8 0 10.5-7.9 6.1-13.1L563.8 512z",fill:"currentColor"})],-1)])],512),_.createElementVNode("div",{class:"preview-content",onClick:m[0]||(m[0]=_.withModifiers(()=>{},["stop"]))},[_.createElementVNode("img",{src:t.content,alt:"预览图片"},null,8,o_)])],32)):_.createCommentVNode("",!0)]))]))}}),s_=nr(i_,[["__scopeId","data-v-91c75579"]]),a_=`
81
+ `);let o=_s.singletonList(Rn.INITIAL_STATE);for(let a=0;a<this.text.length;a++){let l,u=a+1<this.text.length?this.text[a+1]:0;switch(this.text[a]){case me.getCharCode("\r"):l=u===n?2:0;break;case me.getCharCode("."):l=u===e?3:0;break;case me.getCharCode(","):l=u===e?4:0;break;case me.getCharCode(":"):l=u===e?5:0;break;default:l=0}l>0?(o=Vr.updateStateListForPair(o,a,l),a++):o=this.updateStateListForChar(o,a)}return _s.min(o,(a,l)=>a.getBitCount()-l.getBitCount()).toBitArray(this.text)}updateStateListForChar(e,n){const o=[];for(let s of e)this.updateStateForChar(s,n,o);return Vr.simplifyStates(o)}updateStateForChar(e,n,o){let s=this.text[n]&255,a=si[e.getMode()][s]>0,l=null;for(let u=0;u<=kn;u++){let h=si[u][s];if(h>0){if(l==null&&(l=e.endBinaryShift(n)),!a||u===e.getMode()||u===gn){const p=l.latchAndAppend(u,h);o.push(p)}if(!a&&Cs[e.getMode()][u]>=0){const p=l.shiftAndAppend(u,h);o.push(p)}}}if(e.getBinaryShiftByteCount()>0||si[e.getMode()][s]===0){let u=e.addBinaryShiftChar(n);o.push(u)}}static updateStateListForPair(e,n,o){const s=[];for(let a of e)this.updateStateForPair(a,n,o,s);return this.simplifyStates(s)}static updateStateForPair(e,n,o,s){let a=e.endBinaryShift(n);if(s.push(a.latchAndAppend(kn,o)),e.getMode()!==kn&&s.push(a.shiftAndAppend(kn,o)),o===3||o===4){let l=a.latchAndAppend(gn,16-o).latchAndAppend(gn,1);s.push(l)}if(e.getBinaryShiftByteCount()>0){let l=e.addBinaryShiftChar(n).addBinaryShiftChar(n+1);s.push(l)}}static simplifyStates(e){let n=[];for(const o of e){let s=!0;for(const a of n){if(a.isBetterThanOrEqualTo(o)){s=!1;break}o.isBetterThanOrEqualTo(a)&&(n=n.filter(l=>l!==a))}s&&n.push(o)}return n}}class tt{constructor(){}static encodeBytes(e){return tt.encode(e,tt.DEFAULT_EC_PERCENT,tt.DEFAULT_AZTEC_LAYERS)}static encode(e,n,o){let s=new Vr(e).encode(),a=F.truncDivision(s.getSize()*n,100)+11,l=s.getSize()+a,u,h,p,y,b;if(o!==tt.DEFAULT_AZTEC_LAYERS){if(u=o<0,h=Math.abs(o),h>(u?tt.MAX_NB_BITS_COMPACT:tt.MAX_NB_BITS))throw new A(me.format("Illegal value %s for layers",o));p=tt.totalBitsInLayer(h,u),y=tt.WORD_SIZE[h];let ce=p-p%y;if(b=tt.stuffBits(s,y),b.getSize()+a>ce)throw new A("Data to large for user specified layer");if(u&&b.getSize()>y*64)throw new A("Data to large for user specified layer")}else{y=0,b=null;for(let ce=0;;ce++){if(ce>tt.MAX_NB_BITS)throw new A("Data too large for an Aztec code");if(u=ce<=3,h=u?ce+1:ce,p=tt.totalBitsInLayer(h,u),l>p)continue;(b==null||y!==tt.WORD_SIZE[h])&&(y=tt.WORD_SIZE[h],b=tt.stuffBits(s,y));let Ke=p-p%y;if(!(u&&b.getSize()>y*64)&&b.getSize()+a<=Ke)break}}let I=tt.generateCheckWords(b,p,y),R=b.getSize()/y,U=tt.generateModeMessage(u,h,R),V=(u?11:14)+h*4,H=new Int32Array(V),Q;if(u){Q=V;for(let ce=0;ce<H.length;ce++)H[ce]=ce}else{Q=V+1+2*F.truncDivision(F.truncDivision(V,2)-1,15);let ce=F.truncDivision(V,2),Ke=F.truncDivision(Q,2);for(let He=0;He<ce;He++){let tn=He+F.truncDivision(He,15);H[ce-He-1]=Ke-tn-1,H[ce+He]=Ke+tn+1}}let he=new te(Q);for(let ce=0,Ke=0;ce<h;ce++){let He=(h-ce)*4+(u?9:12);for(let tn=0;tn<He;tn++){let yn=tn*2;for(let nn=0;nn<2;nn++)I.get(Ke+yn+nn)&&he.set(H[ce*2+nn],H[ce*2+tn]),I.get(Ke+He*2+yn+nn)&&he.set(H[ce*2+tn],H[V-1-ce*2-nn]),I.get(Ke+He*4+yn+nn)&&he.set(H[V-1-ce*2-nn],H[V-1-ce*2-tn]),I.get(Ke+He*6+yn+nn)&&he.set(H[V-1-ce*2-tn],H[ce*2+nn])}Ke+=He*8}if(tt.drawModeMessage(he,u,Q,U),u)tt.drawBullsEye(he,F.truncDivision(Q,2),5);else{tt.drawBullsEye(he,F.truncDivision(Q,2),7);for(let ce=0,Ke=0;ce<F.truncDivision(V,2)-1;ce+=15,Ke+=16)for(let He=F.truncDivision(Q,2)&1;He<Q;He+=2)he.set(F.truncDivision(Q,2)-Ke,He),he.set(F.truncDivision(Q,2)+Ke,He),he.set(He,F.truncDivision(Q,2)-Ke),he.set(He,F.truncDivision(Q,2)+Ke)}let pe=new ws;return pe.setCompact(u),pe.setSize(Q),pe.setLayers(h),pe.setCodeWords(R),pe.setMatrix(he),pe}static drawBullsEye(e,n,o){for(let s=0;s<o;s+=2)for(let a=n-s;a<=n+s;a++)e.set(a,n-s),e.set(a,n+s),e.set(n-s,a),e.set(n+s,a);e.set(n-o,n-o),e.set(n-o+1,n-o),e.set(n-o,n-o+1),e.set(n+o,n-o),e.set(n+o,n-o+1),e.set(n+o,n+o-1)}static generateModeMessage(e,n,o){let s=new re;return e?(s.appendBits(n-1,2),s.appendBits(o-1,6),s=tt.generateCheckWords(s,28,4)):(s.appendBits(n-1,5),s.appendBits(o-1,11),s=tt.generateCheckWords(s,40,4)),s}static drawModeMessage(e,n,o,s){let a=F.truncDivision(o,2);if(n)for(let l=0;l<7;l++){let u=a-3+l;s.get(l)&&e.set(u,a-5),s.get(l+7)&&e.set(a+5,u),s.get(20-l)&&e.set(u,a+5),s.get(27-l)&&e.set(a-5,u)}else for(let l=0;l<10;l++){let u=a-5+l+F.truncDivision(l,5);s.get(l)&&e.set(u,a-7),s.get(l+10)&&e.set(a+7,u),s.get(29-l)&&e.set(u,a+7),s.get(39-l)&&e.set(a-7,u)}}static generateCheckWords(e,n,o){let s=e.getSize()/o,a=new ti(tt.getGF(o)),l=F.truncDivision(n,o),u=tt.bitsToWords(e,o,l);a.encode(u,l-s);let h=n%o,p=new re;p.appendBits(0,h);for(const y of Array.from(u))p.appendBits(y,o);return p}static bitsToWords(e,n,o){let s=new Int32Array(o),a,l;for(a=0,l=e.getSize()/n;a<l;a++){let u=0;for(let h=0;h<n;h++)u|=e.get(a*n+h)?1<<n-h-1:0;s[a]=u}return s}static getGF(e){switch(e){case 4:return Se.AZTEC_PARAM;case 6:return Se.AZTEC_DATA_6;case 8:return Se.AZTEC_DATA_8;case 10:return Se.AZTEC_DATA_10;case 12:return Se.AZTEC_DATA_12;default:throw new A("Unsupported word size "+e)}}static stuffBits(e,n){let o=new re,s=e.getSize(),a=(1<<n)-2;for(let l=0;l<s;l+=n){let u=0;for(let h=0;h<n;h++)(l+h>=s||e.get(l+h))&&(u|=1<<n-1-h);(u&a)===a?(o.appendBits(u&a,n),l--):(u&a)===0?(o.appendBits(u|1,n),l--):o.appendBits(u,n)}return o}static totalBitsInLayer(e,n){return((n?88:112)+16*e)*e}}tt.DEFAULT_EC_PERCENT=33,tt.DEFAULT_AZTEC_LAYERS=0,tt.MAX_NB_BITS=32,tt.MAX_NB_BITS_COMPACT=4,tt.WORD_SIZE=Int32Array.from([4,6,6,8,8,8,8,8,8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,12,12,12,12,12,12,12,12,12,12]);class yo{encode(e,n,o,s){return this.encodeWithHints(e,n,o,s,null)}encodeWithHints(e,n,o,s,a){let l=ri.ISO_8859_1,u=tt.DEFAULT_EC_PERCENT,h=tt.DEFAULT_AZTEC_LAYERS;return a!=null&&(a.has(Bt.CHARACTER_SET)&&(l=ys.forName(a.get(Bt.CHARACTER_SET).toString())),a.has(Bt.ERROR_CORRECTION)&&(u=F.parseInt(a.get(Bt.ERROR_CORRECTION).toString())),a.has(Bt.AZTEC_LAYERS)&&(h=F.parseInt(a.get(Bt.AZTEC_LAYERS).toString()))),yo.encodeLayers(e,n,o,s,l,u,h)}static encodeLayers(e,n,o,s,a,l,u){if(n!==ie.AZTEC)throw new A("Can only encode AZTEC, but got "+n);let h=tt.encode(me.getBytes(e,a),l,u);return yo.renderResult(h,o,s)}static renderResult(e,n,o){let s=e.getMatrix();if(s==null)throw new St;let a=s.getWidth(),l=s.getHeight(),u=Math.max(n,a),h=Math.max(o,l),p=Math.min(u/a,h/l),y=(u-a*p)/2,b=(h-l*p)/2,I=new te(u,h);for(let R=0,U=b;R<l;R++,U+=p)for(let V=0,H=y;V<a;V++,H+=p)s.get(V,R)&&I.setRegion(H,U,p,p);return I}}i.AbstractExpandedDecoder=Ho,i.ArgumentException=E,i.ArithmeticException=ye,i.AztecCode=ws,i.AztecCodeReader=Ln,i.AztecCodeWriter=yo,i.AztecDecoder=nt,i.AztecDetector=or,i.AztecDetectorResult=$n,i.AztecEncoder=tt,i.AztecHighLevelEncoder=Vr,i.AztecPoint=At,i.BarcodeFormat=ie,i.Binarizer=S,i.BinaryBitmap=D,i.BitArray=re,i.BitMatrix=te,i.BitSource=Xo,i.BrowserAztecCodeReader=wr,i.BrowserBarcodeReader=Qu,i.BrowserCodeReader=Ze,i.BrowserDatamatrixCodeReader=td,i.BrowserMultiFormatReader=fd,i.BrowserPDF417Reader=hd,i.BrowserQRCodeReader=pd,i.BrowserQRCodeSvgWriter=cr,i.CharacterSetECI=z,i.ChecksumException=T,i.Code128Reader=ge,i.Code39Reader=O,i.DataMatrixDecodedBitStreamParser=Wn,i.DataMatrixReader=Gn,i.DecodeHintType=B,i.DecoderResult=Pe,i.DefaultGridSampler=rr,i.DetectorResult=Bn,i.EAN13Reader=Fn,i.EncodeHintType=Bt,i.Exception=g,i.FormatException=L,i.GenericGF=Se,i.GenericGFPoly=J,i.GlobalHistogramBinarizer=ke,i.GridSampler=jn,i.GridSamplerInstance=sn,i.HTMLCanvasElementLuminanceSource=xe,i.HybridBinarizer=le,i.ITFReader=ne,i.IllegalArgumentException=A,i.IllegalStateException=St,i.InvertedLuminanceSource=Je,i.LuminanceSource=Te,i.MathUtils=Xe,i.MultiFormatOneDReader=br,i.MultiFormatReader=xs,i.MultiFormatWriter=gd,i.NotFoundException=q,i.OneDReader=gt,i.PDF417DecodedBitStreamParser=K,i.PDF417DecoderErrorCorrection=ds,i.PDF417Reader=jt,i.PDF417ResultMetadata=hs,i.PerspectiveTransform=Ft,i.PlanarYUVLuminanceSource=On,i.QRCodeByteMatrix=go,i.QRCodeDataMask=pn,i.QRCodeDecodedBitStreamParser=Et,i.QRCodeDecoderErrorCorrectionLevel=pt,i.QRCodeDecoderFormatInformation=Gt,i.QRCodeEncoder=xt,i.QRCodeEncoderQRCode=lr,i.QRCodeMaskUtil=Nt,i.QRCodeMatrixUtil=De,i.QRCodeMode=Re,i.QRCodeReader=qn,i.QRCodeVersion=Ne,i.QRCodeWriter=Er,i.RGBLuminanceSource=ni,i.RSS14Reader=Tt,i.RSSExpandedReader=se,i.ReaderException=mo,i.ReedSolomonDecoder=vt,i.ReedSolomonEncoder=ti,i.ReedSolomonException=Ve,i.Result=qe,i.ResultMetadataType=_e,i.ResultPoint=be,i.StringUtils=me,i.UnsupportedOperationException=we,i.VideoInputDevice=$e,i.WhiteRectangleDetector=qt,i.WriterException=dt,i.ZXingArrays=$,i.ZXingCharset=ys,i.ZXingInteger=F,i.ZXingStandardCharsets=ri,i.ZXingStringBuilder=fe,i.ZXingStringEncoding=G,i.ZXingSystem=P,i.createAbstractExpandedDecoder=cs,Object.defineProperty(i,"__esModule",{value:!0})}))})(qr,qr.exports)),qr.exports}var yt=lw();const cw=sw(yt),uw=Td({__proto__:null,default:cw},[yt]);var dl=(function(){function t(r,i,c){if(this.formatMap=new Map([[Ce.QR_CODE,yt.BarcodeFormat.QR_CODE],[Ce.AZTEC,yt.BarcodeFormat.AZTEC],[Ce.CODABAR,yt.BarcodeFormat.CODABAR],[Ce.CODE_39,yt.BarcodeFormat.CODE_39],[Ce.CODE_93,yt.BarcodeFormat.CODE_93],[Ce.CODE_128,yt.BarcodeFormat.CODE_128],[Ce.DATA_MATRIX,yt.BarcodeFormat.DATA_MATRIX],[Ce.MAXICODE,yt.BarcodeFormat.MAXICODE],[Ce.ITF,yt.BarcodeFormat.ITF],[Ce.EAN_13,yt.BarcodeFormat.EAN_13],[Ce.EAN_8,yt.BarcodeFormat.EAN_8],[Ce.PDF_417,yt.BarcodeFormat.PDF_417],[Ce.RSS_14,yt.BarcodeFormat.RSS_14],[Ce.RSS_EXPANDED,yt.BarcodeFormat.RSS_EXPANDED],[Ce.UPC_A,yt.BarcodeFormat.UPC_A],[Ce.UPC_E,yt.BarcodeFormat.UPC_E],[Ce.UPC_EAN_EXTENSION,yt.BarcodeFormat.UPC_EAN_EXTENSION]]),this.reverseFormatMap=this.createReverseFormatMap(),!uw)throw"Use html5qrcode.min.js without edit, ZXing not found.";this.verbose=i,this.logger=c;var d=this.createZXingFormats(r),f=new Map;f.set(yt.DecodeHintType.POSSIBLE_FORMATS,d),f.set(yt.DecodeHintType.TRY_HARDER,!1),this.hints=f}return t.prototype.decodeAsync=function(r){var i=this;return new Promise(function(c,d){try{c(i.decode(r))}catch(f){d(f)}})},t.prototype.decode=function(r){var i=new yt.MultiFormatReader(this.verbose,this.hints),c=new yt.HTMLCanvasElementLuminanceSource(r),d=new yt.BinaryBitmap(new yt.HybridBinarizer(c)),f=i.decode(d);return{text:f.text,format:Hu.create(this.toHtml5QrcodeSupportedFormats(f.format)),debugData:this.createDebugData()}},t.prototype.createReverseFormatMap=function(){var r=new Map;return this.formatMap.forEach(function(i,c,d){r.set(i,c)}),r},t.prototype.toHtml5QrcodeSupportedFormats=function(r){if(!this.reverseFormatMap.has(r))throw"reverseFormatMap doesn't have ".concat(r);return this.reverseFormatMap.get(r)},t.prototype.createZXingFormats=function(r){for(var i=[],c=0,d=r;c<d.length;c++){var f=d[c];this.formatMap.has(f)?i.push(this.formatMap.get(f)):this.logger.logError("".concat(f," is not supported by")+"ZXingHtml5QrcodeShim")}return i},t.prototype.createDebugData=function(){return{decoderName:"zxing-js"}},t})(),dw=function(t,r,i,c){function d(f){return f instanceof i?f:new i(function(m){m(f)})}return new(i||(i=Promise))(function(f,m){function x(E){try{g(c.next(E))}catch(A){m(A)}}function v(E){try{g(c.throw(E))}catch(A){m(A)}}function g(E){E.done?f(E.value):d(E.value).then(x,v)}g((c=c.apply(t,r||[])).next())})},fw=function(t,r){var i={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,d,f,m;return m={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function x(g){return function(E){return v([g,E])}}function v(g){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,g[0]&&(i=0)),i;)try{if(c=1,d&&(f=g[0]&2?d.return:g[0]?d.throw||((f=d.return)&&f.call(d),0):d.next)&&!(f=f.call(d,g[1])).done)return f;switch(d=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return i.label++,{value:g[1],done:!1};case 5:i.label++,d=g[1],g=[0];continue;case 7:g=i.ops.pop(),i.trys.pop();continue;default:if(f=i.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){i=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){i.label=g[1];break}if(g[0]===6&&i.label<f[1]){i.label=f[1],f=g;break}if(f&&i.label<f[2]){i.label=f[2],i.ops.push(g);break}f[2]&&i.ops.pop(),i.trys.pop();continue}g=r.call(t,i)}catch(E){g=[6,E],d=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},fl=(function(){function t(r,i,c){if(this.formatMap=new Map([[Ce.QR_CODE,"qr_code"],[Ce.AZTEC,"aztec"],[Ce.CODABAR,"codabar"],[Ce.CODE_39,"code_39"],[Ce.CODE_93,"code_93"],[Ce.CODE_128,"code_128"],[Ce.DATA_MATRIX,"data_matrix"],[Ce.ITF,"itf"],[Ce.EAN_13,"ean_13"],[Ce.EAN_8,"ean_8"],[Ce.PDF_417,"pdf417"],[Ce.UPC_A,"upc_a"],[Ce.UPC_E,"upc_e"]]),this.reverseFormatMap=this.createReverseFormatMap(),!t.isSupported())throw"Use html5qrcode.min.js without edit, Use BarcodeDetectorDelegate only if it isSupported();";this.verbose=i,this.logger=c;var d=this.createBarcodeDetectorFormats(r);if(this.detector=new BarcodeDetector(d),!this.detector)throw"BarcodeDetector detector not supported"}return t.isSupported=function(){if(!("BarcodeDetector"in window))return!1;var r=new BarcodeDetector({formats:["qr_code"]});return typeof r<"u"},t.prototype.decodeAsync=function(r){return dw(this,void 0,void 0,function(){var i,c;return fw(this,function(d){switch(d.label){case 0:return[4,this.detector.detect(r)];case 1:if(i=d.sent(),!i||i.length===0)throw"No barcode or QR code detected.";return c=this.selectLargestBarcode(i),[2,{text:c.rawValue,format:Hu.create(this.toHtml5QrcodeSupportedFormats(c.format)),debugData:this.createDebugData()}]}})})},t.prototype.selectLargestBarcode=function(r){for(var i=null,c=0,d=0,f=r;d<f.length;d++){var m=f[d],x=m.boundingBox.width*m.boundingBox.height;x>c&&(c=x,i=m)}if(!i)throw"No largest barcode found";return i},t.prototype.createBarcodeDetectorFormats=function(r){for(var i=[],c=0,d=r;c<d.length;c++){var f=d[c];this.formatMap.has(f)?i.push(this.formatMap.get(f)):this.logger.warn("".concat(f," is not supported by")+"BarcodeDetectorDelegate")}return{formats:i}},t.prototype.toHtml5QrcodeSupportedFormats=function(r){if(!this.reverseFormatMap.has(r))throw"reverseFormatMap doesn't have ".concat(r);return this.reverseFormatMap.get(r)},t.prototype.createReverseFormatMap=function(){var r=new Map;return this.formatMap.forEach(function(i,c,d){r.set(i,c)}),r},t.prototype.createDebugData=function(){return{decoderName:"BarcodeDetector"}},t})(),hl=function(t,r,i,c){function d(f){return f instanceof i?f:new i(function(m){m(f)})}return new(i||(i=Promise))(function(f,m){function x(E){try{g(c.next(E))}catch(A){m(A)}}function v(E){try{g(c.throw(E))}catch(A){m(A)}}function g(E){E.done?f(E.value):d(E.value).then(x,v)}g((c=c.apply(t,r||[])).next())})},pl=function(t,r){var i={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,d,f,m;return m={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function x(g){return function(E){return v([g,E])}}function v(g){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,g[0]&&(i=0)),i;)try{if(c=1,d&&(f=g[0]&2?d.return:g[0]?d.throw||((f=d.return)&&f.call(d),0):d.next)&&!(f=f.call(d,g[1])).done)return f;switch(d=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return i.label++,{value:g[1],done:!1};case 5:i.label++,d=g[1],g=[0];continue;case 7:g=i.ops.pop(),i.trys.pop();continue;default:if(f=i.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){i=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){i.label=g[1];break}if(g[0]===6&&i.label<f[1]){i.label=f[1],f=g;break}if(f&&i.label<f[2]){i.label=f[2],i.ops.push(g);break}f[2]&&i.ops.pop(),i.trys.pop();continue}g=r.call(t,i)}catch(E){g=[6,E],d=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},hw=(function(){function t(r,i,c,d){this.EXECUTIONS_TO_REPORT_PERFORMANCE=100,this.executions=0,this.executionResults=[],this.wasPrimaryDecoderUsedInLastDecode=!1,this.verbose=c,i&&fl.isSupported()?(this.primaryDecoder=new fl(r,c,d),this.secondaryDecoder=new dl(r,c,d)):this.primaryDecoder=new dl(r,c,d)}return t.prototype.decodeAsync=function(r){return hl(this,void 0,void 0,function(){var i;return pl(this,function(c){switch(c.label){case 0:i=performance.now(),c.label=1;case 1:return c.trys.push([1,,3,4]),[4,this.getDecoder().decodeAsync(r)];case 2:return[2,c.sent()];case 3:return this.possiblyLogPerformance(i),[7];case 4:return[2]}})})},t.prototype.decodeRobustlyAsync=function(r){return hl(this,void 0,void 0,function(){var i,c;return pl(this,function(d){switch(d.label){case 0:i=performance.now(),d.label=1;case 1:return d.trys.push([1,3,4,5]),[4,this.primaryDecoder.decodeAsync(r)];case 2:return[2,d.sent()];case 3:if(c=d.sent(),this.secondaryDecoder)return[2,this.secondaryDecoder.decodeAsync(r)];throw c;case 4:return this.possiblyLogPerformance(i),[7];case 5:return[2]}})})},t.prototype.getDecoder=function(){return this.secondaryDecoder?this.wasPrimaryDecoderUsedInLastDecode===!1?(this.wasPrimaryDecoderUsedInLastDecode=!0,this.primaryDecoder):(this.wasPrimaryDecoderUsedInLastDecode=!1,this.secondaryDecoder):this.primaryDecoder},t.prototype.possiblyLogPerformance=function(r){if(this.verbose){var i=performance.now()-r;this.executionResults.push(i),this.executions++,this.possiblyFlushPerformanceReport()}},t.prototype.possiblyFlushPerformanceReport=function(){if(!(this.executions<this.EXECUTIONS_TO_REPORT_PERFORMANCE)){for(var r=0,i=0,c=this.executionResults;i<c.length;i++){var d=c[i];r+=d}var f=r/this.executionResults.length;console.log("".concat(f," ms for ").concat(this.executionResults.length," last runs.")),this.executions=0,this.executionResults=[]}},t})(),os=(function(){var t=function(r,i){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(c,d){c.__proto__=d}||function(c,d){for(var f in d)Object.prototype.hasOwnProperty.call(d,f)&&(c[f]=d[f])},t(r,i)};return function(r,i){if(typeof i!="function"&&i!==null)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");t(r,i);function c(){this.constructor=r}r.prototype=i===null?Object.create(i):(c.prototype=i.prototype,new c)}})(),Bo=function(t,r,i,c){function d(f){return f instanceof i?f:new i(function(m){m(f)})}return new(i||(i=Promise))(function(f,m){function x(E){try{g(c.next(E))}catch(A){m(A)}}function v(E){try{g(c.throw(E))}catch(A){m(A)}}function g(E){E.done?f(E.value):d(E.value).then(x,v)}g((c=c.apply(t,r||[])).next())})},Lo=function(t,r){var i={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,d,f,m;return m={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function x(g){return function(E){return v([g,E])}}function v(g){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,g[0]&&(i=0)),i;)try{if(c=1,d&&(f=g[0]&2?d.return:g[0]?d.throw||((f=d.return)&&f.call(d),0):d.next)&&!(f=f.call(d,g[1])).done)return f;switch(d=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return i.label++,{value:g[1],done:!1};case 5:i.label++,d=g[1],g=[0];continue;case 7:g=i.ops.pop(),i.trys.pop();continue;default:if(f=i.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){i=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){i.label=g[1];break}if(g[0]===6&&i.label<f[1]){i.label=f[1],f=g;break}if(f&&i.label<f[2]){i.label=f[2],i.ops.push(g);break}f[2]&&i.ops.pop(),i.trys.pop();continue}g=r.call(t,i)}catch(E){g=[6,E],d=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},Gu=(function(){function t(r,i){this.name=r,this.track=i}return t.prototype.isSupported=function(){return this.track.getCapabilities?this.name in this.track.getCapabilities():!1},t.prototype.apply=function(r){var i={};i[this.name]=r;var c={advanced:[i]};return this.track.applyConstraints(c)},t.prototype.value=function(){var r=this.track.getSettings();if(this.name in r){var i=r[this.name];return i}return null},t})(),pw=(function(t){os(r,t);function r(i,c){return t.call(this,i,c)||this}return r.prototype.min=function(){return this.getCapabilities().min},r.prototype.max=function(){return this.getCapabilities().max},r.prototype.step=function(){return this.getCapabilities().step},r.prototype.apply=function(i){var c={};c[this.name]=i;var d={advanced:[c]};return this.track.applyConstraints(d)},r.prototype.getCapabilities=function(){this.failIfNotSupported();var i=this.track.getCapabilities(),c=i[this.name];return{min:c.min,max:c.max,step:c.step}},r.prototype.failIfNotSupported=function(){if(!this.isSupported())throw new Error("".concat(this.name," capability not supported"))},r})(Gu),mw=(function(t){os(r,t);function r(i){return t.call(this,"zoom",i)||this}return r})(pw),gw=(function(t){os(r,t);function r(i){return t.call(this,"torch",i)||this}return r})(Gu),xw=(function(){function t(r){this.track=r}return t.prototype.zoomFeature=function(){return new mw(this.track)},t.prototype.torchFeature=function(){return new gw(this.track)},t})(),yw=(function(){function t(r,i,c){this.isClosed=!1,this.parentElement=r,this.mediaStream=i,this.callbacks=c,this.surface=this.createVideoElement(this.parentElement.clientWidth),r.append(this.surface)}return t.prototype.createVideoElement=function(r){var i=document.createElement("video");return i.style.width="".concat(r,"px"),i.style.display="block",i.muted=!0,i.setAttribute("muted","true"),i.playsInline=!0,i},t.prototype.setupSurface=function(){var r=this;this.surface.onabort=function(){throw"RenderedCameraImpl video surface onabort() called"},this.surface.onerror=function(){throw"RenderedCameraImpl video surface onerror() called"};var i=function(){var c=r.surface.clientWidth,d=r.surface.clientHeight;r.callbacks.onRenderSurfaceReady(c,d),r.surface.removeEventListener("playing",i)};this.surface.addEventListener("playing",i),this.surface.srcObject=this.mediaStream,this.surface.play()},t.create=function(r,i,c,d){return Bo(this,void 0,void 0,function(){var f,m;return Lo(this,function(x){switch(x.label){case 0:return f=new t(r,i,d),c.aspectRatio?(m={aspectRatio:c.aspectRatio},[4,f.getFirstTrackOrFail().applyConstraints(m)]):[3,2];case 1:x.sent(),x.label=2;case 2:return f.setupSurface(),[2,f]}})})},t.prototype.failIfClosed=function(){if(this.isClosed)throw"The RenderedCamera has already been closed."},t.prototype.getFirstTrackOrFail=function(){if(this.failIfClosed(),this.mediaStream.getVideoTracks().length===0)throw"No video tracks found";return this.mediaStream.getVideoTracks()[0]},t.prototype.pause=function(){this.failIfClosed(),this.surface.pause()},t.prototype.resume=function(r){this.failIfClosed();var i=this,c=function(){setTimeout(r,200),i.surface.removeEventListener("playing",c)};this.surface.addEventListener("playing",c),this.surface.play()},t.prototype.isPaused=function(){return this.failIfClosed(),this.surface.paused},t.prototype.getSurface=function(){return this.failIfClosed(),this.surface},t.prototype.getRunningTrackCapabilities=function(){return this.getFirstTrackOrFail().getCapabilities()},t.prototype.getRunningTrackSettings=function(){return this.getFirstTrackOrFail().getSettings()},t.prototype.applyVideoConstraints=function(r){return Bo(this,void 0,void 0,function(){return Lo(this,function(i){if("aspectRatio"in r)throw"Changing 'aspectRatio' in run-time is not yet supported.";return[2,this.getFirstTrackOrFail().applyConstraints(r)]})})},t.prototype.close=function(){if(this.isClosed)return Promise.resolve();var r=this;return new Promise(function(i,c){var d=r.mediaStream.getVideoTracks(),f=d.length,m=0;r.mediaStream.getVideoTracks().forEach(function(x){r.mediaStream.removeTrack(x),x.stop(),++m,m>=f&&(r.isClosed=!0,r.parentElement.removeChild(r.surface),i())})})},t.prototype.getCapabilities=function(){return new xw(this.getFirstTrackOrFail())},t})(),ww=(function(){function t(r){this.mediaStream=r}return t.prototype.render=function(r,i,c){return Bo(this,void 0,void 0,function(){return Lo(this,function(d){return[2,yw.create(r,this.mediaStream,i,c)]})})},t.create=function(r){return Bo(this,void 0,void 0,function(){var i,c;return Lo(this,function(d){switch(d.label){case 0:if(!navigator.mediaDevices)throw"navigator.mediaDevices not supported";return i={audio:!1,video:r},[4,navigator.mediaDevices.getUserMedia(i)];case 1:return c=d.sent(),[2,new t(c)]}})})},t})(),ml=function(t,r,i,c){function d(f){return f instanceof i?f:new i(function(m){m(f)})}return new(i||(i=Promise))(function(f,m){function x(E){try{g(c.next(E))}catch(A){m(A)}}function v(E){try{g(c.throw(E))}catch(A){m(A)}}function g(E){E.done?f(E.value):d(E.value).then(x,v)}g((c=c.apply(t,r||[])).next())})},gl=function(t,r){var i={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,d,f,m;return m={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function x(g){return function(E){return v([g,E])}}function v(g){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,g[0]&&(i=0)),i;)try{if(c=1,d&&(f=g[0]&2?d.return:g[0]?d.throw||((f=d.return)&&f.call(d),0):d.next)&&!(f=f.call(d,g[1])).done)return f;switch(d=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return i.label++,{value:g[1],done:!1};case 5:i.label++,d=g[1],g=[0];continue;case 7:g=i.ops.pop(),i.trys.pop();continue;default:if(f=i.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){i=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){i.label=g[1];break}if(g[0]===6&&i.label<f[1]){i.label=f[1],f=g;break}if(f&&i.label<f[2]){i.label=f[2],i.ops.push(g);break}f[2]&&i.ops.pop(),i.trys.pop();continue}g=r.call(t,i)}catch(E){g=[6,E],d=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},_w=(function(){function t(){}return t.failIfNotSupported=function(){return ml(this,void 0,void 0,function(){return gl(this,function(r){if(!navigator.mediaDevices)throw"navigator.mediaDevices not supported";return[2,new t]})})},t.prototype.create=function(r){return ml(this,void 0,void 0,function(){return gl(this,function(i){return[2,ww.create(r)]})})},t})(),vw=function(t,r,i,c){function d(f){return f instanceof i?f:new i(function(m){m(f)})}return new(i||(i=Promise))(function(f,m){function x(E){try{g(c.next(E))}catch(A){m(A)}}function v(E){try{g(c.throw(E))}catch(A){m(A)}}function g(E){E.done?f(E.value):d(E.value).then(x,v)}g((c=c.apply(t,r||[])).next())})},Cw=function(t,r){var i={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,d,f,m;return m={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function x(g){return function(E){return v([g,E])}}function v(g){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,g[0]&&(i=0)),i;)try{if(c=1,d&&(f=g[0]&2?d.return:g[0]?d.throw||((f=d.return)&&f.call(d),0):d.next)&&!(f=f.call(d,g[1])).done)return f;switch(d=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return i.label++,{value:g[1],done:!1};case 5:i.label++,d=g[1],g=[0];continue;case 7:g=i.ops.pop(),i.trys.pop();continue;default:if(f=i.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){i=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){i.label=g[1];break}if(g[0]===6&&i.label<f[1]){i.label=f[1],f=g;break}if(f&&i.label<f[2]){i.label=f[2],i.ops.push(g);break}f[2]&&i.ops.pop(),i.trys.pop();continue}g=r.call(t,i)}catch(E){g=[6,E],d=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},bw=(function(){function t(){}return t.retrieve=function(){if(navigator.mediaDevices)return t.getCamerasFromMediaDevices();var r=MediaStreamTrack;return MediaStreamTrack&&r.getSources?t.getCamerasFromMediaStreamTrack():t.rejectWithError()},t.rejectWithError=function(){var r=Rr.unableToQuerySupportedDevices();return t.isHttpsOrLocalhost()||(r=Rr.insecureContextCameraQueryError()),Promise.reject(r)},t.isHttpsOrLocalhost=function(){if(location.protocol==="https:")return!0;var r=location.host.split(":")[0];return r==="127.0.0.1"||r==="localhost"},t.getCamerasFromMediaDevices=function(){return vw(this,void 0,void 0,function(){var r,i,c,d,f,m,x;return Cw(this,function(v){switch(v.label){case 0:return r=function(g){for(var E=g.getVideoTracks(),A=0,D=E;A<D.length;A++){var T=D[A];T.enabled=!1,T.stop(),g.removeTrack(T)}},[4,navigator.mediaDevices.getUserMedia({audio:!1,video:!0})];case 1:return i=v.sent(),[4,navigator.mediaDevices.enumerateDevices()];case 2:for(c=v.sent(),d=[],f=0,m=c;f<m.length;f++)x=m[f],x.kind==="videoinput"&&d.push({id:x.deviceId,label:x.label});return r(i),[2,d]}})})},t.getCamerasFromMediaStreamTrack=function(){return new Promise(function(r,i){var c=function(f){for(var m=[],x=0,v=f;x<v.length;x++){var g=v[x];g.kind==="video"&&m.push({id:g.id,label:g.label})}r(m)},d=MediaStreamTrack;d.getSources(c)})},t})(),Ot;(function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.NOT_STARTED=1]="NOT_STARTED",t[t.SCANNING=2]="SCANNING",t[t.PAUSED=3]="PAUSED"})(Ot||(Ot={}));var Aw=(function(){function t(){this.state=Ot.NOT_STARTED,this.onGoingTransactionNewState=Ot.UNKNOWN}return t.prototype.directTransition=function(r){this.failIfTransitionOngoing(),this.validateTransition(r),this.state=r},t.prototype.startTransition=function(r){return this.failIfTransitionOngoing(),this.validateTransition(r),this.onGoingTransactionNewState=r,this},t.prototype.execute=function(){if(this.onGoingTransactionNewState===Ot.UNKNOWN)throw"Transaction is already cancelled, cannot execute().";var r=this.onGoingTransactionNewState;this.onGoingTransactionNewState=Ot.UNKNOWN,this.directTransition(r)},t.prototype.cancel=function(){if(this.onGoingTransactionNewState===Ot.UNKNOWN)throw"Transaction is already cancelled, cannot cancel().";this.onGoingTransactionNewState=Ot.UNKNOWN},t.prototype.getState=function(){return this.state},t.prototype.failIfTransitionOngoing=function(){if(this.onGoingTransactionNewState!==Ot.UNKNOWN)throw"Cannot transition to a new state, already under transition"},t.prototype.validateTransition=function(r){switch(this.state){case Ot.UNKNOWN:throw"Transition from unknown is not allowed";case Ot.NOT_STARTED:this.failIfNewStateIs(r,[Ot.PAUSED]);break;case Ot.SCANNING:break;case Ot.PAUSED:break}},t.prototype.failIfNewStateIs=function(r,i){for(var c=0,d=i;c<d.length;c++){var f=d[c];if(r===f)throw"Cannot transition from ".concat(this.state," to ").concat(r)}},t})(),Ew=(function(){function t(r){this.stateManager=r}return t.prototype.startTransition=function(r){return this.stateManager.startTransition(r)},t.prototype.directTransition=function(r){this.stateManager.directTransition(r)},t.prototype.getState=function(){return this.stateManager.getState()},t.prototype.canScanFile=function(){return this.stateManager.getState()===Ot.NOT_STARTED},t.prototype.isScanning=function(){return this.stateManager.getState()!==Ot.NOT_STARTED},t.prototype.isStrictlyScanning=function(){return this.stateManager.getState()===Ot.SCANNING},t.prototype.isPaused=function(){return this.stateManager.getState()===Ot.PAUSED},t})(),Iw=(function(){function t(){}return t.create=function(){return new Ew(new Aw)},t})(),Sw=(function(){var t=function(r,i){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(c,d){c.__proto__=d}||function(c,d){for(var f in d)Object.prototype.hasOwnProperty.call(d,f)&&(c[f]=d[f])},t(r,i)};return function(r,i){if(typeof i!="function"&&i!==null)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");t(r,i);function c(){this.constructor=r}r.prototype=i===null?Object.create(i):(c.prototype=i.prototype,new c)}})(),ln=(function(t){Sw(r,t);function r(){return t!==null&&t.apply(this,arguments)||this}return r.DEFAULT_WIDTH=300,r.DEFAULT_WIDTH_OFFSET=2,r.FILE_SCAN_MIN_HEIGHT=300,r.FILE_SCAN_HIDDEN_CANVAS_PADDING=100,r.MIN_QR_BOX_SIZE=50,r.SHADED_LEFT=1,r.SHADED_RIGHT=2,r.SHADED_TOP=3,r.SHADED_BOTTOM=4,r.SHADED_REGION_ELEMENT_ID="qr-shaded-region",r.VERBOSE=!1,r.BORDER_SHADER_DEFAULT_COLOR="#ffffff",r.BORDER_SHADER_MATCH_COLOR="rgb(90, 193, 56)",r})(rw),Tw=(function(){function t(r,i){this.logger=i,this.fps=ln.SCAN_DEFAULT_FPS,r?(r.fps&&(this.fps=r.fps),this.disableFlip=r.disableFlip===!0,this.qrbox=r.qrbox,this.aspectRatio=r.aspectRatio,this.videoConstraints=r.videoConstraints):this.disableFlip=ln.DEFAULT_DISABLE_FLIP}return t.prototype.isMediaStreamConstraintsValid=function(){return this.videoConstraints?Wu.isMediaStreamConstraintsValid(this.videoConstraints,this.logger):(this.logger.logError("Empty videoConstraints",!0),!1)},t.prototype.isShadedBoxEnabled=function(){return!zn(this.qrbox)},t.create=function(r,i){return new t(r,i)},t})(),xl=(function(){function t(r,i){if(this.element=null,this.canvasElement=null,this.scannerPausedUiElement=null,this.hasBorderShaders=null,this.borderShaders=null,this.qrMatch=null,this.renderedCamera=null,this.qrRegion=null,this.context=null,this.lastScanImageFile=null,this.isScanning=!1,!document.getElementById(r))throw"HTML Element with id=".concat(r," not found");this.elementId=r,this.verbose=!1;var c;typeof i=="boolean"?this.verbose=i===!0:i&&(c=i,this.verbose=c.verbose===!0,c.experimentalFeatures),this.logger=new iw(this.verbose),this.qrcode=new hw(this.getSupportedFormats(i),this.getUseBarCodeDetectorIfSupported(c),this.verbose,this.logger),this.foreverScanTimeout,this.shouldScan=!0,this.stateManagerProxy=Iw.create()}return t.prototype.start=function(r,i,c,d){var f=this;if(!r)throw"cameraIdOrConfig is required";if(!c||typeof c!="function")throw"qrCodeSuccessCallback is required and should be a function.";var m;d?m=d:m=this.verbose?this.logger.log:function(){};var x=Tw.create(i,this.logger);this.clearElement();var v=!1;x.videoConstraints&&(x.isMediaStreamConstraintsValid()?v=!0:this.logger.logError("'videoConstraints' is not valid 'MediaStreamConstraints, it will be ignored.'",!0));var g=v,E=document.getElementById(this.elementId);E.clientWidth?E.clientWidth:ln.DEFAULT_WIDTH,E.style.position="relative",this.shouldScan=!0,this.element=E;var A=this,D=this.stateManagerProxy.startTransition(Ot.SCANNING);return new Promise(function(T,S){var P=g?x.videoConstraints:A.createVideoConstraints(r);if(!P){D.cancel(),S("videoConstraints should be defined");return}var M={};(!g||x.aspectRatio)&&(M.aspectRatio=x.aspectRatio);var ee={onRenderSurfaceReady:function($,F){A.setupUi($,F,x),A.isScanning=!0,A.foreverScan(x,c,m)}};_w.failIfNotSupported().then(function($){$.create(P).then(function(F){return F.render(f.element,M,ee).then(function(re){A.renderedCamera=re,D.execute(),T(null)}).catch(function(re){D.cancel(),S(re)})}).catch(function(F){D.cancel(),S(Rr.errorGettingUserMedia(F))})}).catch(function($){D.cancel(),S(Rr.cameraStreamingNotSupported())})})},t.prototype.pause=function(r){if(!this.stateManagerProxy.isStrictlyScanning())throw"Cannot pause, scanner is not scanning.";this.stateManagerProxy.directTransition(Ot.PAUSED),this.showPausedState(),(zn(r)||r!==!0)&&(r=!1),r&&this.renderedCamera&&this.renderedCamera.pause()},t.prototype.resume=function(){if(!this.stateManagerProxy.isPaused())throw"Cannot result, scanner is not paused.";if(!this.renderedCamera)throw"renderedCamera doesn't exist while trying resume()";var r=this,i=function(){r.stateManagerProxy.directTransition(Ot.SCANNING),r.hidePausedState()};if(!this.renderedCamera.isPaused()){i();return}this.renderedCamera.resume(function(){i()})},t.prototype.getState=function(){return this.stateManagerProxy.getState()},t.prototype.stop=function(){var r=this;if(!this.stateManagerProxy.isScanning())throw"Cannot stop, scanner is not running or paused.";var i=this.stateManagerProxy.startTransition(Ot.NOT_STARTED);this.shouldScan=!1,this.foreverScanTimeout&&clearTimeout(this.foreverScanTimeout);var c=function(){if(r.element){var f=document.getElementById(ln.SHADED_REGION_ELEMENT_ID);f&&r.element.removeChild(f)}},d=this;return this.renderedCamera.close().then(function(){return d.renderedCamera=null,d.element&&(d.element.removeChild(d.canvasElement),d.canvasElement=null),c(),d.qrRegion&&(d.qrRegion=null),d.context&&(d.context=null),i.execute(),d.hidePausedState(),d.isScanning=!1,Promise.resolve()})},t.prototype.scanFile=function(r,i){return this.scanFileV2(r,i).then(function(c){return c.decodedText})},t.prototype.scanFileV2=function(r,i){var c=this;if(!r||!(r instanceof File))throw"imageFile argument is mandatory and should be instance of File. Use 'event.target.files[0]'.";if(zn(i)&&(i=!0),!this.stateManagerProxy.canScanFile())throw"Cannot start file scan - ongoing camera scan";return new Promise(function(d,f){c.possiblyCloseLastScanImageFile(),c.clearElement(),c.lastScanImageFile=URL.createObjectURL(r);var m=new Image;m.onload=function(){var x=m.width,v=m.height,g=document.getElementById(c.elementId),E=g.clientWidth?g.clientWidth:ln.DEFAULT_WIDTH,A=Math.max(g.clientHeight?g.clientHeight:v,ln.FILE_SCAN_MIN_HEIGHT),D=c.computeCanvasDrawConfig(x,v,E,A);if(i){var T=c.createCanvasElement(E,A,"qr-canvas-visible");T.style.display="inline-block",g.appendChild(T);var S=T.getContext("2d");if(!S)throw"Unable to get 2d context from canvas";S.canvas.width=E,S.canvas.height=A,S.drawImage(m,0,0,x,v,D.x,D.y,D.width,D.height)}var P=ln.FILE_SCAN_HIDDEN_CANVAS_PADDING,M=Math.max(m.width,D.width),ee=Math.max(m.height,D.height),$=M+2*P,F=ee+2*P,re=c.createCanvasElement($,F);g.appendChild(re);var Z=re.getContext("2d");if(!Z)throw"Unable to get 2d context from canvas";Z.canvas.width=$,Z.canvas.height=F,Z.drawImage(m,0,0,x,v,P,P,M,ee);try{c.qrcode.decodeRobustlyAsync(re).then(function(B){d(cl.createFromQrcodeResult(B))}).catch(f)}catch(B){f("QR code parse error, error = ".concat(B))}},m.onerror=f,m.onabort=f,m.onstalled=f,m.onsuspend=f,m.src=URL.createObjectURL(r)})},t.prototype.clear=function(){this.clearElement()},t.getCameras=function(){return bw.retrieve()},t.prototype.getRunningTrackCapabilities=function(){return this.getRenderedCameraOrFail().getRunningTrackCapabilities()},t.prototype.getRunningTrackSettings=function(){return this.getRenderedCameraOrFail().getRunningTrackSettings()},t.prototype.getRunningTrackCameraCapabilities=function(){return this.getRenderedCameraOrFail().getCapabilities()},t.prototype.applyVideoConstraints=function(r){if(r){if(!Wu.isMediaStreamConstraintsValid(r,this.logger))throw"invalid videoConstaints passed, check logs for more details"}else throw"videoConstaints is required argument.";return this.getRenderedCameraOrFail().applyVideoConstraints(r)},t.prototype.getRenderedCameraOrFail=function(){if(this.renderedCamera==null)throw"Scanning is not in running state, call this API only when QR code scanning using camera is in running state.";return this.renderedCamera},t.prototype.getSupportedFormats=function(r){var i=[Ce.QR_CODE,Ce.AZTEC,Ce.CODABAR,Ce.CODE_39,Ce.CODE_93,Ce.CODE_128,Ce.DATA_MATRIX,Ce.MAXICODE,Ce.ITF,Ce.EAN_13,Ce.EAN_8,Ce.PDF_417,Ce.RSS_14,Ce.RSS_EXPANDED,Ce.UPC_A,Ce.UPC_E,Ce.UPC_EAN_EXTENSION];if(!r||typeof r=="boolean"||!r.formatsToSupport)return i;if(!Array.isArray(r.formatsToSupport))throw"configOrVerbosityFlag.formatsToSupport should be undefined or an array.";if(r.formatsToSupport.length===0)throw"Atleast 1 formatsToSupport is needed.";for(var c=[],d=0,f=r.formatsToSupport;d<f.length;d++){var m=f[d];nw(m)?c.push(m):this.logger.warn("Invalid format: ".concat(m," passed in config, ignoring."))}if(c.length===0)throw"None of formatsToSupport match supported values.";return c},t.prototype.getUseBarCodeDetectorIfSupported=function(r){if(zn(r))return!0;if(!zn(r.useBarCodeDetectorIfSupported))return r.useBarCodeDetectorIfSupported!==!1;if(zn(r.experimentalFeatures))return!0;var i=r.experimentalFeatures;return zn(i.useBarCodeDetectorIfSupported)?!0:i.useBarCodeDetectorIfSupported!==!1},t.prototype.validateQrboxSize=function(r,i,c){var d=this,f=c.qrbox;this.validateQrboxConfig(f);var m=this.toQrdimensions(r,i,f),x=function(g){if(g<ln.MIN_QR_BOX_SIZE)throw"minimum size of 'config.qrbox' dimension value is"+" ".concat(ln.MIN_QR_BOX_SIZE,"px.")},v=function(g){return g>r&&(d.logger.warn("`qrbox.width` or `qrbox` is larger than the width of the root element. The width will be truncated to the width of root element."),g=r),g};x(m.width),x(m.height),m.width=v(m.width)},t.prototype.validateQrboxConfig=function(r){if(typeof r!="number"&&typeof r!="function"&&(r.width===void 0||r.height===void 0))throw"Invalid instance of QrDimensions passed for 'config.qrbox'. Both 'width' and 'height' should be set."},t.prototype.toQrdimensions=function(r,i,c){if(typeof c=="number")return{width:c,height:c};if(typeof c=="function")try{return c(r,i)}catch(d){throw new Error("qrbox config was passed as a function but it failed with unknown error"+d)}return c},t.prototype.setupUi=function(r,i,c){c.isShadedBoxEnabled()&&this.validateQrboxSize(r,i,c);var d=zn(c.qrbox)?{width:r,height:i}:c.qrbox;this.validateQrboxConfig(d);var f=this.toQrdimensions(r,i,d);f.height>i&&this.logger.warn("[Html5Qrcode] config.qrbox has height that isgreater than the height of the video stream. Shading will be ignored");var m=c.isShadedBoxEnabled()&&f.height<=i,x={x:0,y:0,width:r,height:i},v=m?this.getShadedRegionBounds(r,i,f):x,g=this.createCanvasElement(v.width,v.height),E={willReadFrequently:!0},A=g.getContext("2d",E);A.canvas.width=v.width,A.canvas.height=v.height,this.element.append(g),m&&this.possiblyInsertShadingElement(this.element,r,i,f),this.createScannerPausedUiElement(this.element),this.qrRegion=v,this.context=A,this.canvasElement=g},t.prototype.createScannerPausedUiElement=function(r){var i=document.createElement("div");i.innerText=Rr.scannerPaused(),i.style.display="none",i.style.position="absolute",i.style.top="0px",i.style.zIndex="1",i.style.background="rgba(9, 9, 9, 0.46)",i.style.color="#FFECEC",i.style.textAlign="center",i.style.width="100%",r.appendChild(i),this.scannerPausedUiElement=i},t.prototype.scanContext=function(r,i){var c=this;return this.stateManagerProxy.isPaused()?Promise.resolve(!1):this.qrcode.decodeAsync(this.canvasElement).then(function(d){return r(d.text,cl.createFromQrcodeResult(d)),c.possiblyUpdateShaders(!0),!0}).catch(function(d){c.possiblyUpdateShaders(!1);var f=Rr.codeParseError(d);return i(f,ow.createFrom(f)),!1})},t.prototype.foreverScan=function(r,i,c){var d=this;if(this.shouldScan&&this.renderedCamera){var f=this.renderedCamera.getSurface(),m=f.videoWidth/f.clientWidth,x=f.videoHeight/f.clientHeight;if(!this.qrRegion)throw"qrRegion undefined when localMediaStream is ready.";var v=this.qrRegion.width*m,g=this.qrRegion.height*x,E=this.qrRegion.x*m,A=this.qrRegion.y*x;this.context.drawImage(f,E,A,v,g,0,0,this.qrRegion.width,this.qrRegion.height);var D=function(){d.foreverScanTimeout=setTimeout(function(){d.foreverScan(r,i,c)},d.getTimeoutFps(r.fps))};this.scanContext(i,c).then(function(T){!T&&r.disableFlip!==!0?(d.context.translate(d.context.canvas.width,0),d.context.scale(-1,1),d.scanContext(i,c).finally(function(){D()})):D()}).catch(function(T){d.logger.logError("Error happend while scanning context",T),D()})}},t.prototype.createVideoConstraints=function(r){if(typeof r=="string")return{deviceId:{exact:r}};if(typeof r=="object"){var i="facingMode",c="deviceId",d={user:!0,environment:!0},f="exact",m=function(S){if(S in d)return!0;throw"config has invalid 'facingMode' value = "+"'".concat(S,"'")},x=Object.keys(r);if(x.length!==1)throw"'cameraIdOrConfig' object should have exactly 1 key,"+" if passed as an object, found ".concat(x.length," keys");var v=Object.keys(r)[0];if(v!==i&&v!==c)throw"Only '".concat(i,"' and '").concat(c,"' ")+" are supported for 'cameraIdOrConfig'";if(v===i){var g=r.facingMode;if(typeof g=="string"){if(m(g))return{facingMode:g}}else if(typeof g=="object")if(f in g){if(m(g["".concat(f)]))return{facingMode:{exact:g["".concat(f)]}}}else throw"'facingMode' should be string or object with"+" ".concat(f," as key.");else{var E=typeof g;throw"Invalid type of 'facingMode' = ".concat(E)}}else{var A=r.deviceId;if(typeof A=="string")return{deviceId:A};if(typeof A=="object"){if(f in A)return{deviceId:{exact:A["".concat(f)]}};throw"'deviceId' should be string or object with"+" ".concat(f," as key.")}else{var D=typeof A;throw"Invalid type of 'deviceId' = ".concat(D)}}}var T=typeof r;throw"Invalid type of 'cameraIdOrConfig' = ".concat(T)},t.prototype.computeCanvasDrawConfig=function(r,i,c,d){if(r<=c&&i<=d){var f=(c-r)/2,m=(d-i)/2;return{x:f,y:m,width:r,height:i}}else{var x=r,v=i;return r>c&&(i=c/r*i,r=c),i>d&&(r=d/i*r,i=d),this.logger.log("Image downsampled from "+"".concat(x,"X").concat(v)+" to ".concat(r,"X").concat(i,".")),this.computeCanvasDrawConfig(r,i,c,d)}},t.prototype.clearElement=function(){if(this.stateManagerProxy.isScanning())throw"Cannot clear while scan is ongoing, close it first.";var r=document.getElementById(this.elementId);r&&(r.innerHTML="")},t.prototype.possiblyUpdateShaders=function(r){this.qrMatch!==r&&(this.hasBorderShaders&&this.borderShaders&&this.borderShaders.length&&this.borderShaders.forEach(function(i){i.style.backgroundColor=r?ln.BORDER_SHADER_MATCH_COLOR:ln.BORDER_SHADER_DEFAULT_COLOR}),this.qrMatch=r)},t.prototype.possiblyCloseLastScanImageFile=function(){this.lastScanImageFile&&(URL.revokeObjectURL(this.lastScanImageFile),this.lastScanImageFile=null)},t.prototype.createCanvasElement=function(r,i,c){var d=r,f=i,m=document.createElement("canvas");return m.style.width="".concat(d,"px"),m.style.height="".concat(f,"px"),m.style.display="none",m.id=zn(c)?"qr-canvas":c,m},t.prototype.getShadedRegionBounds=function(r,i,c){if(c.width>r||c.height>i)throw"'config.qrbox' dimensions should not be greater than the dimensions of the root HTML element.";return{x:(r-c.width)/2,y:(i-c.height)/2,width:c.width,height:c.height}},t.prototype.possiblyInsertShadingElement=function(r,i,c,d){if(!(i-d.width<1||c-d.height<1)){var f=document.createElement("div");f.style.position="absolute";var m=(i-d.width)/2,x=(c-d.height)/2;if(f.style.borderLeft="".concat(m,"px solid rgba(0, 0, 0, 0.48)"),f.style.borderRight="".concat(m,"px solid rgba(0, 0, 0, 0.48)"),f.style.borderTop="".concat(x,"px solid rgba(0, 0, 0, 0.48)"),f.style.borderBottom="".concat(x,"px solid rgba(0, 0, 0, 0.48)"),f.style.boxSizing="border-box",f.style.top="0px",f.style.bottom="0px",f.style.left="0px",f.style.right="0px",f.id="".concat(ln.SHADED_REGION_ELEMENT_ID),i-d.width<11||c-d.height<11)this.hasBorderShaders=!1;else{var v=5,g=40;this.insertShaderBorders(f,g,v,-v,null,0,!0),this.insertShaderBorders(f,g,v,-v,null,0,!1),this.insertShaderBorders(f,g,v,null,-v,0,!0),this.insertShaderBorders(f,g,v,null,-v,0,!1),this.insertShaderBorders(f,v,g+v,-v,null,-v,!0),this.insertShaderBorders(f,v,g+v,null,-v,-v,!0),this.insertShaderBorders(f,v,g+v,-v,null,-v,!1),this.insertShaderBorders(f,v,g+v,null,-v,-v,!1),this.hasBorderShaders=!0}r.append(f)}},t.prototype.insertShaderBorders=function(r,i,c,d,f,m,x){var v=document.createElement("div");v.style.position="absolute",v.style.backgroundColor=ln.BORDER_SHADER_DEFAULT_COLOR,v.style.width="".concat(i,"px"),v.style.height="".concat(c,"px"),d!==null&&(v.style.top="".concat(d,"px")),f!==null&&(v.style.bottom="".concat(f,"px")),x?v.style.left="".concat(m,"px"):v.style.right="".concat(m,"px"),this.borderShaders||(this.borderShaders=[]),this.borderShaders.push(v),r.appendChild(v)},t.prototype.showPausedState=function(){if(!this.scannerPausedUiElement)throw"[internal error] scanner paused UI element not found";this.scannerPausedUiElement.style.display="block"},t.prototype.hidePausedState=function(){if(!this.scannerPausedUiElement)throw"[internal error] scanner paused UI element not found";this.scannerPausedUiElement.style.display="none"},t.prototype.getTimeoutFps=function(r){return 1e3/r},t})(),yl;(function(t){t[t.STATUS_DEFAULT=0]="STATUS_DEFAULT",t[t.STATUS_SUCCESS=1]="STATUS_SUCCESS",t[t.STATUS_WARNING=2]="STATUS_WARNING",t[t.STATUS_REQUESTING_PERMISSION=3]="STATUS_REQUESTING_PERMISSION"})(yl||(yl={}));const Nw={class:"scan-code"},Ow={class:"btn"},kw={class:"left-back"},Rw=_.defineComponent({name:"QrCodeScan",__name:"QrCodeScan",emits:["scanSuccess"],setup(t,{emit:r}){const i=r,c=Sd.IconScan(),d=_.reactive({html5QrCode:null}),f=_.ref(!1),m=()=>{if(!d.html5QrCode){it("摄像头无访问权限!");return}f.value=!0,d.html5QrCode.start({facingMode:"environment"},{fps:30,aspectRatio:1,supportedScanTypes:[oo.SCAN_TYPE_CAMERA],showTorchButtonIfSupported:!0,showZoomSliderIfSupported:!0,defaultZoomValueIfSupported:2,useBarCodeDetectorIfSupported:!0},A=>{try{const T=new URL(A).searchParams.get("sessionId");T?i("scanSuccess",T):it("无效的二维码")}catch{it("无效的二维码")}E()}).catch(A=>{console.log(A),it({message:"二维码识别失败",duration:3e3})})},x=()=>{g().then(()=>{m()})},v=()=>{E()},g=()=>xl.getCameras().then(A=>{A&&A.length&&(d.html5QrCode=new xl("reader"))}).catch(()=>{it({message:"摄像头无访问权限!",duration:3e3})}),E=()=>{d.html5QrCode&&d.html5QrCode.stop().then(A=>{console.log("停止扫码",A)}).catch(A=>{console.log(A),it("停止扫码失败")}).finally(()=>{f.value=!1})};return _.onUnmounted(()=>{d.html5QrCode&&d.html5QrCode.isScanning&&E()}),(A,D)=>{const T=rs;return _.openBlock(),_.createElementBlock("div",null,[_.createVNode(_.unref(Vt.TrIconButton),{icon:_.unref(c),size:"28",svgSize:"20",onClick:D[0]||(D[0]=S=>x())},null,8,["icon"]),(_.openBlock(),_.createBlock(_.Teleport,{to:"body"},[_.withDirectives(_.createElementVNode("div",Nw,[D[1]||(D[1]=_.createElementVNode("div",{class:"container"},[_.createElementVNode("div",{class:"qrcode"},[_.createElementVNode("div",{id:"reader"})])],-1)),_.createElementVNode("div",Ow,[_.createElementVNode("div",kw,[_.createVNode(T,{name:"arrow-left",onClick:v})])])],512),[[_.vShow,f.value]])]))])}}}),Mw=nr(Rw,[["__scopeId","data-v-2d988579"]]);function is(t,r,i){const c=_.computed(()=>t?Array.isArray(t)?t:t.value:[]),d=()=>{const E=c.value;if(E.length===0)return"";if(r){const D=typeof r=="string"?r:r.value;if(D&&E.some(T=>T.id===D))return D}const A=E.find(D=>D.isDefault);return A?A.id:E[0].id};let f,m=!1;if(r&&typeof r!="string")f=r,m=!0,(!f.value||!c.value.some(E=>E.id===f.value))&&(f.value=d());else{let E;r&&typeof r=="string"&&(E=r),f=_.ref(E&&c.value.some(A=>A.id===E)?E:d())}(!m||i)&&_.watch(f,E=>{i&&i(E)});const x=_.computed(()=>c.value.find(E=>E.id===f.value)),v=_.computed(()=>c.value);return{selectedModelId:f,selectedModel:x,availableModels:v,setSelectedModel:E=>{c.value.find(D=>D.id===E)?f.value=E:console.warn(`[useModel] Model not found: ${E}`)}}}const Dw=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const Pw=Object.prototype.toString,Bw=t=>Pw.call(t)==="[object Object]",No=()=>{};function wi(t){return Array.isArray(t)?t:[t]}function Lw(t,r,i){return _.watch(t,r,{...i,immediate:!0})}const qu=Dw?window:void 0;function Xr(t){var r;const i=_.toValue(t);return(r=i?.$el)!==null&&r!==void 0?r:i}function _i(...t){const r=(c,d,f,m)=>(c.addEventListener(d,f,m),()=>c.removeEventListener(d,f,m)),i=_.computed(()=>{const c=wi(_.toValue(t[0])).filter(d=>d!=null);return c.every(d=>typeof d!="string")?c:void 0});return Lw(()=>{var c,d;return[(c=(d=i.value)===null||d===void 0?void 0:d.map(f=>Xr(f)))!==null&&c!==void 0?c:[qu].filter(f=>f!=null),wi(_.toValue(i.value?t[1]:t[0])),wi(_.unref(i.value?t[2]:t[1])),_.toValue(i.value?t[3]:t[2])]},([c,d,f,m],x,v)=>{if(!c?.length||!d?.length||!f?.length)return;const g=Bw(m)?{...m}:m,E=c.flatMap(A=>d.flatMap(D=>f.map(T=>r(A,D,T,g))));v(()=>{E.forEach(A=>A())})},{flush:"post"})}function Fw(t,r,i={}){const{window:c=qu,ignore:d=[],capture:f=!0,detectIframe:m=!1,controls:x=!1}=i;if(!c)return x?{stop:No,cancel:No,trigger:No}:No;let v=!0;const g=M=>_.toValue(d).some(ee=>{if(typeof ee=="string")return Array.from(c.document.querySelectorAll(ee)).some($=>$===M.target||M.composedPath().includes($));{const $=Xr(ee);return $&&(M.target===$||M.composedPath().includes($))}});function E(M){const ee=_.toValue(M);return ee&&ee.$.subTree.shapeFlag===16}function A(M,ee){const $=_.toValue(M),F=$.$.subTree&&$.$.subTree.children;return F==null||!Array.isArray(F)?!1:F.some(re=>re.el===ee.target||ee.composedPath().includes(re.el))}const D=M=>{const ee=Xr(t);if(M.target!=null&&!(!(ee instanceof Element)&&E(t)&&A(t,M))&&!(!ee||ee===M.target||M.composedPath().includes(ee))){if("detail"in M&&M.detail===0&&(v=!g(M)),!v){v=!0;return}r(M)}};let T=!1;const S=[_i(c,"click",M=>{T||(T=!0,setTimeout(()=>{T=!1},0),D(M))},{passive:!0,capture:f}),_i(c,"pointerdown",M=>{const ee=Xr(t);v=!g(M)&&!!(ee&&!M.composedPath().includes(ee))},{passive:!0}),m&&_i(c,"blur",M=>{setTimeout(()=>{const ee=Xr(t);let $=c.document.activeElement;for(;$?.shadowRoot;)$=$.shadowRoot.activeElement;$?.tagName==="IFRAME"&&!ee?.contains(c.document.activeElement)&&r(M)},0)},{passive:!0})].filter(Boolean),P=()=>S.forEach(M=>M());return x?{stop:P,cancel:()=>{v=!1},trigger:M=>{v=!0,D(M),v=!1}}:P}const Uw=["data-active","disabled"],zw=_.defineComponent({__name:"Button",props:{active:{type:Boolean},rounded:{type:Boolean},size:{default:"medium"},disabled:{type:Boolean}},setup(t){return(r,i)=>(_.openBlock(),_.createElementBlock("button",{class:_.normalizeClass(["button",{rounded:t.rounded,[t.size]:!0}]),"data-active":t.active||void 0,disabled:t.disabled||void 0},[_.renderSlot(r.$slots,"default",{},void 0,!0)],10,Uw))}}),ss=nr(zw,[["__scopeId","data-v-6f582cce"]]),Vw={viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",fill:"none"};function Zw(t,r){return _.openBlock(),_.createElementBlock("svg",Vw,[...r[0]||(r[0]=[_.createElementVNode("rect",{id:"大模型",width:"16.000000",height:"16.000000",x:"0.000000",y:"0.000000"},null,-1),_.createElementVNode("path",{id:"矢量 90",d:"M13.683 2.26904C12.5753 1.16177 10.344 1.47577 8.02582 2.86527C5.70758 1.47576 3.47637 1.16179 2.36913 2.26904C1.2619 3.37646 1.57573 5.60771 2.96524 7.92589C1.57573 10.2441 1.2619 12.4754 2.36913 13.5827C3.47637 14.6901 5.7078 14.3762 8.02599 12.9867C10.344 14.3762 12.5752 14.6901 13.6825 13.5827C14.7901 12.4754 14.4761 10.2441 13.0866 7.92594C14.4761 5.60775 14.7902 3.37646 13.683 2.26904ZM10.8544 5.09764C11.4667 5.70995 12.0076 6.34819 12.4699 6.99044C12.7244 6.52061 12.9268 6.06037 13.077 5.60959C13.2948 4.95652 13.3832 4.38597 13.3426 3.89769C13.3089 3.49437 13.1869 3.18725 12.9754 2.97631C12.7645 2.76513 12.4574 2.64282 12.0541 2.60912C11.5658 2.56835 10.9955 2.65698 10.3422 2.87475C9.89153 3.02497 9.43121 3.22735 8.96135 3.48197C9.60365 3.94428 10.242 4.48527 10.8544 5.09764ZM5.70991 2.87475C6.16049 3.02494 6.62073 3.22729 7.09051 3.48185C6.44826 3.94412 5.81002 4.48507 5.19771 5.09739C4.58523 5.70982 4.04417 6.34819 3.58181 6.99055C3.32716 6.52071 3.1248 6.06037 2.97459 5.60959C2.75682 4.95677 2.66844 4.38597 2.70897 3.89769C2.74266 3.49437 2.86522 3.18725 3.07615 2.97631C3.28709 2.76513 3.59421 2.64282 3.99753 2.60912C4.4858 2.5686 5.0566 2.65698 5.70991 2.87475ZM5.90473 5.80466Q4.89236 6.81738 4.14938 7.92595C4.64428 8.66515 5.2294 9.3722 5.90473 10.0473C6.57966 10.7222 7.28696 11.3074 8.02584 11.8027C8.76507 11.3074 9.47197 10.7222 10.1474 10.0473C10.8222 9.37218 11.4074 8.66511 11.9027 7.92588Q11.1597 6.81736 10.1474 5.80466C9.47203 5.12956 8.7652 4.54447 8.02604 4.04937C7.28683 4.54447 6.5796 5.12956 5.90473 5.80466ZM7.99992 6.90011C7.44768 6.90011 6.99993 7.34787 6.99993 7.90011C6.99993 8.45235 7.44768 8.9001 7.99992 8.9001C8.55216 8.9001 8.99991 8.45235 8.99991 7.90011C8.99991 7.34787 8.55216 6.90011 7.99992 6.90011ZM10.3422 12.9772C9.89161 12.827 9.43138 12.6246 8.96148 12.37C9.60377 11.9077 10.242 11.3667 10.8544 10.7543C11.4667 10.142 12.0077 9.50369 12.4699 8.8614C12.7245 9.33127 12.9268 9.79154 13.077 10.2421C13.2948 10.8952 13.3832 11.4658 13.3426 11.954C13.3089 12.3574 13.1864 12.6647 12.9754 12.8757C12.7645 13.0866 12.4574 13.2089 12.0541 13.2426C11.5658 13.2834 10.995 13.195 10.3422 12.9772ZM2.97459 10.2421C3.12478 9.7914 3.32733 9.3312 3.58196 8.86141C4.04428 9.50369 4.5853 10.142 5.19771 10.7543C5.81003 11.3667 6.44827 11.9077 7.09052 12.37C6.62074 12.6246 6.16049 12.827 5.70991 12.9772C5.0566 13.195 4.48629 13.2834 3.99802 13.2426C3.5947 13.2089 3.28709 13.0866 3.07615 12.8757C2.86522 12.6647 2.74315 12.3574 2.70946 11.954C2.66844 11.4658 2.75682 10.8952 2.97459 10.2421Z",fill:"rgb(89,89,89)","fill-rule":"evenodd"},null,-1)])])}const $w={render:Zw},jw={class:"button-text"},Hw={class:"dropdown-menu__items"},Ww=["onClick"],Gw=_.defineComponent({__name:"ModelSwitch",props:_.mergeModels({modelConfigs:{}},{selectedModelId:{type:String,default:void 0,required:!1},selectedModelIdModifiers:{}}),emits:["update:selectedModelId"],setup(t){const r=t,i=_.useModel(t,"selectedModelId"),c=_.computed(()=>{const T=r.modelConfigs;return T?Array.isArray(T)?T:T.value:[]}),{selectedModel:d,availableModels:f,setSelectedModel:m}=is(c,i),x=_.ref(!1),v=T=>{m(T),E()},g=()=>{x.value=!x.value},E=()=>{x.value=!1},A=_.ref(null),D=_.ref(null);return Fw(D,()=>{E()},{ignore:[A]}),(T,S)=>(_.openBlock(),_.createElementBlock("div",{class:"model-switch-wrapper",ref_key:"wrapperRef",ref:A},[_.createVNode(ss,{size:"small",class:"action-button",rounded:"",onClick:g},{default:_.withCtx(()=>[(_.openBlock(),_.createBlock(_.resolveDynamicComponent(_.unref(d)?.icon),{width:16,height:16,class:"selected-model__icon"})),_.createElementVNode("span",jw,_.toDisplayString(_.unref(d)?.label),1),_.createVNode(_.unref($w),{width:16,height:16})]),_:1}),_.createVNode(_.Transition,{name:"dropdown"},{default:_.withCtx(()=>[x.value?(_.openBlock(),_.createElementBlock("div",{key:0,class:"dropdown-menu",ref_key:"dropdownMenuRef",ref:D},[_.createElementVNode("div",Hw,[(_.openBlock(!0),_.createElementBlock(_.Fragment,null,_.renderList(_.unref(f),P=>(_.openBlock(),_.createElementBlock("div",{key:P.id,class:_.normalizeClass(["dropdown-menu__item",{"active-menu":P.id===i.value}]),onClick:_.withModifiers(M=>v(P.id),["stop"])},[P.icon?(_.openBlock(),_.createBlock(_.resolveDynamicComponent(P.icon),{key:0,width:16,height:16,class:"dropdown-menu__icon"})):_.createCommentVNode("",!0),_.createElementVNode("span",null,_.toDisplayString(P.label),1)],10,Ww))),128))])],512)):_.createCommentVNode("",!0)]),_:1}),x.value?(_.openBlock(),_.createElementBlock("div",{key:0,class:"dropdown-overlay",onClick:E})):_.createCommentVNode("",!0)],512))}}),qw=nr(Gw,[["__scopeId","data-v-475491fd"]]),Xw={key:0,class:"active-count"},Yw=_.defineComponent({__name:"PluginToggleButton",props:{installedPlugins:{}},emits:["click"],setup(t){const r=t,i=_.computed(()=>r.installedPlugins.filter(c=>c.enabled).length);return(c,d)=>(_.openBlock(),_.createBlock(ss,{size:"small",class:"action-button",active:i.value>0,rounded:"",onClick:d[0]||(d[0]=f=>c.$emit("click"))},{default:_.withCtx(()=>[_.createVNode(_.unref(Mr.IconPlugin),{class:"icon",style:{"font-size":"16px"}}),d[1]||(d[1]=_.createElementVNode("span",{class:"button-text"},"扩展",-1)),i.value>0?(_.openBlock(),_.createElementBlock("span",Xw,_.toDisplayString(i.value),1)):_.createCommentVNode("",!0)]),_:1},8,["active"]))}}),Kw=nr(Yw,[["__scopeId","data-v-c2a16c66"]]),Jw={"data-v-99394ae9":"",viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",width:"16.000000",height:"16.000000",fill:"none",customFrame:"#000000",size:"16"};function Qw(t,r){return _.openBlock(),_.createElementBlock("svg",Jw,[...r[0]||(r[0]=[_.createElementVNode("rect",{id:"生成式UI",width:"16.000000",height:"16.000000",x:"0.000000",y:"0.000000",fill:"currentColor","fill-opacity":"0"},null,-1),_.createElementVNode("path",{id:"矢量 154",d:"M7.41014 2.09741L7.67112 2.70606C7.68333 2.73438 7.70579 2.75684 7.73411 2.76905L8.34275 3.02979C8.43968 3.0713 8.43968 3.20875 8.34275 3.25025L7.73411 3.51124C7.70579 3.52345 7.68333 3.54591 7.67112 3.57423L7.41014 4.18288C7.36863 4.2798 7.23118 4.2798 7.18968 4.18288L6.92894 3.57423C6.91673 3.54591 6.89427 3.52345 6.86595 3.51124L6.25731 3.25025C6.16039 3.20875 6.16039 3.0713 6.25731 3.02979L6.86595 2.76905C6.89427 2.75684 6.91673 2.73438 6.92894 2.70606L7.18968 2.09741C7.23118 2.00049 7.36863 2.00049 7.41014 2.09741ZM4.57006 11.9625L7.27611 8.09746L9.69944 4.63674L10.592 3.36207C10.6899 3.22218 10.8017 3.09864 10.9272 2.99122C11.0529 2.88404 11.1926 2.79297 11.3459 2.71802C11.4992 2.64332 11.657 2.58936 11.8191 2.5564C11.9809 2.52369 12.1472 2.51172 12.3176 2.52051C12.5315 2.53174 12.7336 2.57373 12.9238 2.64649C13.0678 2.70118 13.205 2.77369 13.3354 2.86353C13.4651 2.95289 13.5813 3.05445 13.6836 3.16822C13.8064 3.3047 13.9094 3.45851 13.9929 3.6299C14.0766 3.80128 14.1342 3.97731 14.1662 4.15773C14.1928 4.30861 14.2014 4.46267 14.1919 4.61989C14.1823 4.7781 14.1547 4.93069 14.1096 5.07791C14.0495 5.27249 13.958 5.45755 13.8352 5.63309L7.81321 14.2335Q7.66985 14.4382 7.48649 14.5965Q7.4825 14.6 7.4785 14.6034Q7.29063 14.7641 7.06102 14.8766C6.90794 14.9513 6.75072 15.0052 6.5891 15.0384C6.42748 15.0714 6.2617 15.0836 6.09154 15.0751C5.87743 15.0643 5.67504 15.0226 5.48436 14.9503C5.34008 14.8956 5.20287 14.8233 5.07201 14.7335C4.94213 14.6444 4.82592 14.5428 4.72313 14.4291C4.60033 14.2928 4.49682 14.1388 4.41308 13.9674C4.32934 13.7958 4.27123 13.6197 4.23925 13.4391C4.21239 13.2882 4.20385 13.1339 4.21313 12.9767C4.22265 12.8184 4.24999 12.6656 4.2954 12.5184C4.35546 12.3233 4.44701 12.138 4.57006 11.9625ZM4.7185 4.67361L4.18383 3.42579C4.11449 3.26441 3.88549 3.26441 3.81616 3.42579L3.28149 4.67361C3.26123 4.72073 3.22363 4.75832 3.17651 4.77859L1.92871 5.31326C1.76733 5.3826 1.76733 5.6116 1.92871 5.68094L3.17651 6.21561C3.22363 6.23587 3.26123 6.27347 3.28149 6.32059L3.81616 7.56841C3.88549 7.73003 4.11449 7.73003 4.18383 7.56841L4.7185 6.32059C4.73876 6.27347 4.77636 6.23587 4.82348 6.21561L6.07128 5.68094C6.23265 5.6116 6.23265 5.3826 6.07128 5.31326L4.82348 4.77859C4.77636 4.75832 4.73876 4.72073 4.7185 4.67361ZM5.38915 12.536C5.32006 12.6346 5.27099 12.7384 5.24169 12.8475C5.22533 12.9088 5.21532 12.9718 5.21141 13.0362C5.20726 13.1063 5.21044 13.1751 5.22094 13.2428C5.23583 13.3402 5.2661 13.4354 5.31151 13.5282C5.35692 13.6209 5.41332 13.7032 5.48095 13.775C5.52806 13.8248 5.58031 13.8695 5.63817 13.9093C5.69139 13.9459 5.7473 13.9764 5.80565 14.0011C5.9099 14.0453 6.02196 14.0702 6.14208 14.0763C6.2263 14.0807 6.30834 14.0746 6.38841 14.0582C6.46825 14.0418 6.54613 14.015 6.62181 13.9781C6.69749 13.941 6.76634 13.8961 6.8286 13.8429C6.89061 13.7899 6.94578 13.7289 6.99412 13.6598L11.9415 6.59405L10.3381 5.46789L5.38915 12.536ZM10.9168 4.6415L12.5202 5.76762L13.0161 5.05935C13.0849 4.96096 13.134 4.85745 13.1633 4.74831C13.1797 4.68703 13.1897 4.62429 13.1936 4.55959C13.198 4.48977 13.1948 4.42092 13.1843 4.35329C13.1694 4.25588 13.1394 4.16091 13.0942 4.06813C13.0488 3.97536 12.9926 3.89308 12.925 3.8213C12.8781 3.7715 12.8259 3.72682 12.7683 3.68703C12.7148 3.6504 12.6591 3.61964 12.6008 3.59474C12.4968 3.55079 12.385 3.5254 12.2651 3.5193C12.1806 3.51466 12.0984 3.52076 12.0183 3.53688C11.9382 3.55324 11.8601 3.57985 11.7841 3.61696C11.7082 3.65407 11.6391 3.69899 11.5771 3.75221C11.5149 3.80519 11.4594 3.86647 11.4111 3.93556L10.9168 4.6415Z",fill:"currentColor","fill-rule":"evenodd"},null,-1)])])}const e_={render:Qw},t_=_.defineComponent({__name:"GenUISwitch",props:{genuiEnabled:{type:Boolean,type:Boolean,default:!1,required:!1},genuiEnabledModifiers:{}},emits:["update:genuiEnabled"],setup(t){const r=_.useModel(t,"genuiEnabled"),i=()=>{r.value=!r.value};return(c,d)=>(_.openBlock(),_.createBlock(ss,{class:"action-button",active:r.value,rounded:"",size:"small",onClick:i},{default:_.withCtx(()=>[_.createVNode(_.unref(e_),{width:16,height:16}),d[0]||(d[0]=_.createElementVNode("span",{class:"button-text"},"生成式UI",-1))]),_:1},8,["active"]))}}),n_=nr(t_,[["__scopeId","data-v-7f3b0372"]]),r_={class:"bubble-image-wrapper"},o_=["src"],i_=["src"],s_=_.defineComponent({__name:"BubbleImageRenderer",props:{content:{}},setup(t){const r=_.ref(!1),i=_.ref(null),c=()=>{r.value=!0},d=()=>{r.value=!1};return _.watch(r,f=>{f&&_.nextTick(()=>{i.value?.focus()})}),(f,m)=>(_.openBlock(),_.createElementBlock("div",r_,[_.createElementVNode("img",{src:t.content,class:"bubble-image",alt:"用户上传的图片",onClick:c},null,8,o_),(_.openBlock(),_.createBlock(_.Teleport,{to:"body"},[r.value?(_.openBlock(),_.createElementBlock("div",{key:0,class:"image-preview-modal",role:"dialog","aria-modal":"true","aria-label":"图片预览",onClick:d,onKeydown:_.withKeys(d,["esc"])},[_.createElementVNode("button",{ref_key:"closeButtonRef",ref:i,class:"preview-close",type:"button","aria-label":"关闭预览",onClick:d},[...m[1]||(m[1]=[_.createElementVNode("svg",{viewBox:"0 0 1024 1024",width:"24",height:"24","aria-hidden":"true"},[_.createElementVNode("path",{d:"M563.8 512l262.5-312.9c4.4-5.2.7-13.1-6.1-13.1h-79.8c-4.7 0-9.2 2.1-12.3 5.7L511.6 449.8 295.1 191.7c-3-3.6-7.5-5.7-12.3-5.7H203c-6.8 0-10.5 7.9-6.1 13.1L459.4 512 196.9 824.9A7.95 7.95 0 0 0 203 838h79.8c4.7 0 9.2-2.1 12.3-5.7l216.5-258.1 216.5 258.1c3 3.6 7.5 5.7 12.3 5.7h79.8c6.8 0 10.5-7.9 6.1-13.1L563.8 512z",fill:"currentColor"})],-1)])],512),_.createElementVNode("div",{class:"preview-content",onClick:m[0]||(m[0]=_.withModifiers(()=>{},["stop"]))},[_.createElementVNode("img",{src:t.content,alt:"预览图片"},null,8,i_)])],32)):_.createCommentVNode("",!0)]))]))}}),a_=nr(s_,[["__scopeId","data-v-91c75579"]]),l_=`
82
82
  <svg width="1em" height="1em" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
83
83
  <defs>
84
84
  <clipPath id="clip657_188316">
@@ -91,4 +91,4 @@ ${this.tempPrompt}
91
91
  <path id="path" d="M1.25 9.97C1.25 9.63 1.53 9.35 1.87 9.35L4.37 9.35C4.72 9.35 5 9.63 5 9.97C5 10.32 4.72 10.6 4.37 10.6L1.87 10.6C1.53 10.6 1.25 10.32 1.25 9.97ZM12.5 6.25C12.5 5.9 12.78 5.62 13.12 5.62L17.46 5.62C17.8 5.62 18.08 5.9 18.08 6.25C18.08 6.59 17.8 6.87 17.46 6.87L13.12 6.87C12.78 6.87 12.5 6.59 12.5 6.25ZM12.5 13.73C12.5 13.39 12.78 13.11 13.12 13.11L17.46 13.11C17.8 13.11 18.08 13.39 18.08 13.73C18.08 14.08 17.8 14.36 17.46 14.36L13.12 14.36C12.78 14.36 12.5 14.08 12.5 13.73Z" fill="currentColor" fill-opacity="1" fill-rule="nonzero"></path>
92
92
  </g>
93
93
  </svg>
94
- `,l_=btoa(a_),wl=`data:image/svg+xml;base64,${l_}`,vi=(t,r)=>{const[i,c]=t.split("#");return{id:r,text:i,inputMessage:c}},c_=t=>{const r={"zh-CN":{title:"OpenTiny NEXT",description:"我是你的私人智能助手",placeholder:"请输入您的问题",thinking:"正在思考中..."},"en-US":{title:"OpenTiny NEXT",description:"I am your private AI assistant",placeholder:"Please enter your question",thinking:"Thinking..."}},i=[{id:"office",text:t.locale==="zh-CN"?"办公助手":"Office Assistant",menus:["接收邮件#请同步邮箱的新邮件。","编写邮件#请新建一个邮件,收件人为 opentiny-next@meeting.com, 内容为举办一个临时会议。","安排会议#创建一个临时的在线会议,主题为讨论问题,时长为1小时。","整理文档#请分析附件中的销售情况,把销售额绘制成折线图。"].map(vi)},{id:"development",text:t.locale==="zh-CN"?"开发支持":"Development Support",menus:["遇到代码问题#请检查当前位置的报错原因。","架构建议#请使用NodeJs实现一个分块上传文件的模块。","最新的技术趋势#请分析Vue与React 框架的优劣分别是什么?"].map(vi)},{id:"management",text:t.locale==="zh-CN"?"项目管理":"Project Management",menus:["项目规划#如何开展品牌推广的活动?","任务分配#将本季度的销售任务分配给三个人,并生成甘特图进行跟踪。","进度跟踪#分析团队的任务完成情况。"].map(vi)}],c=[{label:t.locale==="zh-CN"?"企业办公助手":"Enterprise Office Assistant",description:t.locale==="zh-CN"?"需要我帮你处理邮件、安排会议、整理文档,还是优化工作流程?":"Need help with emails, meeting scheduling, document organization, or workflow optimization?",icon:_.h("span",{style:{fontSize:"18px"}},"🧠"),badge:"NEW"},{label:t.locale==="zh-CN"?"开发技术支持":"Development Support",description:t.locale==="zh-CN"?"遇到代码问题?需要架构建议?还是想了解最新的技术趋势?":"Facing code issues? Need architecture advice? Or want to learn about latest tech trends?",icon:_.h("span",{style:{fontSize:"18px"}},"💻")},{label:t.locale==="zh-CN"?"项目管理协作":"Project Management",description:t.locale==="zh-CN"?"需要项目规划、任务分配、进度跟踪,还是团队协作建议?":"Need project planning, task assignment, progress tracking, or team collaboration advice?",icon:_.h("span",{style:{fontSize:"18px"}},"📊")}];return{lang:r,pillItems:i,promptItems:c}},_l={"No client found for session ID":"受控端页面已关闭请重新打开或者刷新页面","Failed to create MCP client":"创建MCP客户端失败"},u_=t=>{console.log("message",t);const r=Object.keys(_l),i=r.findIndex(d=>t.includes(d));return(i!==-1?_l[r[i]]:t)||t},d_={class:"tr-container__title"},f_={style:{flex:"1"}},h_={class:"chat-input"},p_={class:"chat-input-pills"},m_={class:"attachments-container"},g_={class:"action-buttons"},x_=_.defineComponent({name:"TinyRemoter",__name:"TinyRobotChat",props:_.mergeModels({agentRoot:{type:String,default:"https://agent.opentiny.design/api/v1/webmcp-trial/"},sessionId:{type:String,default:void 0},menuItems:{type:Array},remoteUrl:{type:String},qrCodeUrl:{type:String},systemPrompt:{type:String,default:"你是一个智能助手,擅长通过工具调用帮助用户解决问题和满足用户需求"},title:{type:String,default:"OpenTiny NEXT"},locale:{type:String,default:"zh-CN"},AILogoUrl:{type:String},roleAvatar:{type:Object,default:()=>({user:_.h(Mr.IconUser,{style:{fontSize:"32px"}}),assistant:_.h(ju,{style:{fontSize:"32px"}})})},mode:{type:String,default:"remoter"},llmConfig:{type:Object,default:()=>({baseURL:"https://agent.opentiny.design/api/v1/ai/",genuiUrl:"https://agent.opentiny.design/api/v1/ai/prompt"})},inBrowserExt:{type:Boolean,default:!1},genUiComponents:{type:Object,default:()=>({})},customMarketMcpServers:{type:Array,default:()=>[]},mcpServers:{type:Object,default:void 0},llmConfigs:{type:Array,default:void 0},skills:{type:Object,default:void 0},layoutMode:{type:String,default:"fixed"},debugStream:{type:Boolean,default:!1},promptItems:{type:Array,default:void 0},pillItems:{type:Array,default:void 0}},{fullscreen:{type:Boolean,default:!1},fullscreenModifiers:{},show:{type:Boolean,default:!1},showModifiers:{},selectedModelId:{type:String,default:void 0,required:!1},selectedModelIdModifiers:{},genUiAble:{type:Boolean,default:!1,required:!1},genUiAbleModifiers:{},enabledTools:{type:Object,default:void 0,required:!1},enabledToolsModifiers:{}}),emits:_.mergeModels(["before-ai-render","chat-stream-finish"],["update:fullscreen","update:show","update:selectedModelId","update:genUiAble","update:enabledTools"]),setup(t,{expose:r,emit:i}){const c=t,d=i,f=_.useModel(t,"fullscreen"),m=_.useModel(t,"show"),x=_.useModel(t,"selectedModelId"),v=_.useModel(t,"genUiAble"),g=_.useModel(t,"enabledTools"),E=c.llmConfigs?_.toRef(c,"llmConfigs"):void 0,{selectedModel:A}=is(E,x),D=_.computed(()=>{const Ee=E?.value?.length?A.value:c.llmConfig;return Ee?!!(Ee.baseURL&&Ee.genuiUrl):!1}),{hasMultimodalSupport:T,attachments:S,onFilesSelected:P,checkCanSendAttachments:M,processAttachments:ee,cleanupAttachments:$}=ew({selectedModel:A,selectedModelId:x}),{agent:F,customAgentProvider:re,conversationState:Z,messages:B,messageState:L,inputMessage:W,abortRequest:z,senderRef:we,sendMessage:G,handleSendMessage:me,addMessage:fe,send:te,createConversation:q,switchConversation:ke,deleteConversation:le,getCurrentConversation:Te}=yx({systemPrompt:c.systemPrompt||"",llmConfig:c.llmConfig,emit:d});_.watch(()=>c.systemPrompt,Ee=>{re.promptManager.setStatic(Ee)}),re.isGenuiEnabled=v,re.debugStream=c.debugStream;const Je=_.toRef(c,"skills"),{processSkillMentions:xe}=zy({skillsRef:Je,customAgentProvider:re}),$e=async(Ee,Oe)=>me(Ee,Oe,xe),{welcomeIcon:Ue,roles:Ze}=Wy({props:c,messages:B,messageState:L,inputMessage:W,handleSendMessage:$e}),{showHistory:qe,handleCreateConversation:ze,handleHistorySelect:ie,handleHistoryUpdateTitle:de,handleHistoryDelete:_e}=Gy({createConversation:q,switchConversation:ke,deleteConversation:le,getCurrentConversation:Te,abortRequest:z,conversationState:Z,customAgentProvider:re}),Pe=()=>{if(A.value){const Ee=A.value;re.updateLLMConfig({model:Ee.model||"",baseURL:Ee.baseURL||"",genuiUrl:Ee.genuiUrl||"",apiKey:Ee.apiKey||"",providerType:Ee.providerType,useReActMode:Ee.useReActMode,llm:Ee.llm,providerOptions:Ee.providerOptions,headers:Ee.headers})}else re.updateLLMConfig(re.llmConfig)};c.llmConfigs&&_.watch(A,Pe,{immediate:!0}),_.watch(v,Pe,{immediate:!0});const ae={markdown:new Vt.BubbleMarkdownContentRenderer({mdConfig:{html:!0}}),"schema-card":Ee=>_.h(Ed.GenuiRenderer,{...Ee,customActions:{continueChat:{execute:(Oe,rt)=>{const Ye=typeof Oe=="string"?Oe:Oe.message,Fn=`${Ye},相关参数为:${JSON.stringify(rt?.state||{})}`;fe({role:"user",content:Fn,uiContent:[{type:"markdown",content:Ye}]}),te()}}},generating:Kn.GeneratingStatus.includes(L.status),customComponents:c.genUiComponents,requiredCompleteFieldSelectors:["[componentName=TinyUser] > props > modelValue"]}),image:s_};function J(Ee,Oe){ae[Ee]=Oe}const{installedPlugins:ye,marketPlugins:Se,pluginVisible:Ve,loadMcpServerToPlugin:St,togglePlugin:vt,toggleTool:et,deletePlugin:nt,addPluginCore:Xe,addPluginFromMarket:In,addPluginFromScan:be,handleClientDisconnected:Bn,searchPlugin:$n,syncInstalledPluginTools:qt}=Fy(F,g,wl);Uy({onToolCatalogChanged:async()=>{await F.refreshTools(),qt()}}),Se.value=[...c.customMarketMcpServers];const jn=_.ref([{value:"",label:"全部分类"},{value:"productivity",label:"生产力工具"},{value:"communication",label:"沟通协作"},{value:"development",label:"开发工具"},{value:"ai",label:"AI 助手"}]),Ft=c_(c),rr=_.computed(()=>c.pillItems??Ft.pillItems),sn=_.computed(()=>c.promptItems??Ft.promptItems),At=Ft.lang,{handleScanSuccess:or,handleSessionIdInput:Ln,initialize:wr}=qy({sessionId:_.toRef(c,"sessionId"),agentRoot:_.toRef(c,"agentRoot"),mode:c.mode,qrCodeUrl:c.qrCodeUrl,remoteUrl:c.remoteUrl,menuItems:_.toRef(c,"menuItems"),AILogoUrl:c.AILogoUrl,show:m,addPluginFromScan:be,inputMessage:W}),gt=async Ee=>{if(await Ln(W.value)||!M())return;const rt=await ee();try{await $e(Ee,rt),$()}catch(Ye){console.error("发送消息失败:",Ye)}},ge=_.computed(()=>Kn.GeneratingStatus.includes(L.status)?At[c.locale].thinking:At[c.locale].placeholder),O=_.computed(()=>Kn.GeneratingStatus.includes(L.status)),ne=Ee=>{W.value=Ee.inputMessage};wr(),_.onMounted(async()=>{setTimeout(()=>{ze()},100),F.onError=Oe=>{Oe&&it(u_(Oe))};const Ee=Se.value.filter(Oe=>Oe.addState==="added"&&Oe.enabled);for(const Oe of Ee)await In(Oe);if(c.mcpServers)for(const[Oe,rt]of Object.entries(c.mcpServers))await St(Oe,rt)});const{handleCustomAdd:Me}=Ly(F,ye,wl);return r({agent:F,welcomeIcon:Ue,messages:B,messageState:L,roles:Ze,inputMessage:W,senderRef:we,abortRequest:z,sendMessage:G,loadMcpServerToPlugin:St,handleClientDisconnected:Bn,addMessage:fe,installedPlugins:ye,addPluginCore:Xe,deletePlugin:nt,registerContentRenderer:J,async refreshPluginTools(){await F.refreshTools(),qt()}}),(Ee,Oe)=>(_.openBlock(),_.createBlock(_.unref(Vt.TrContainer),{show:m.value,"onUpdate:show":Oe[11]||(Oe[11]=rt=>m.value=rt),fullscreen:f.value,"onUpdate:fullscreen":Oe[12]||(Oe[12]=rt=>f.value=rt),style:_.normalizeStyle({position:t.layoutMode,width:t.layoutMode!=="fixed"?"unset":void 0,height:t.layoutMode!=="fixed"?"100%":void 0})},{title:_.withCtx(()=>[_.createElementVNode("h3",d_,_.toDisplayString(t.title),1)]),operations:_.withCtx(()=>[_.renderSlot(Ee.$slots,"operations",{},()=>[_.createVNode(_.unref(Vt.TrIconButton),{icon:_.unref(Mr.IconNewSession),size:"28",svgSize:"20",onClick:Oe[0]||(Oe[0]=rt=>_.unref(ze)())},null,8,["icon"]),_.createVNode(_.unref(Vt.TrIconButton),{icon:_.unref(Mr.IconHistory),size:"28",svgSize:"20",onClick:Oe[1]||(Oe[1]=rt=>qe.value=!_.unref(qe))},null,8,["icon"]),_.createVNode(Rw,{onScanSuccess:_.unref(or)},null,8,["onScanSuccess"]),_.createVNode(_.Transition,{name:"drawer-slide",appear:""},{default:_.withCtx(()=>[_.unref(qe)?(_.openBlock(),_.createElementBlock("div",{key:0,class:"drawer-overlay",onClick:Oe[4]||(Oe[4]=rt=>qe.value=!1)},[_.createElementVNode("div",{class:"drawer-container",onClick:Oe[3]||(Oe[3]=_.withModifiers(()=>{},["stop"])),style:{"--tr-history-item-selected-bg":"#ebeeff"}},[Oe[13]||(Oe[13]=_.createElementVNode("h4",null,"历史会话",-1)),_.createVNode(_.unref(Vt.TrHistory),{class:"tr-history-demo",selected:_.unref(Z).currentId,data:_.unref(Z).conversations,showRenameControls:!0,onClose:Oe[2]||(Oe[2]=rt=>qe.value=!1),onItemClick:_.unref(ie),onItemTitleChange:_.unref(de),onItemAction:_.unref(_e)},null,8,["selected","data","onItemClick","onItemTitleChange","onItemAction"])])])):_.createCommentVNode("",!0)]),_:1})],!0)]),footer:_.withCtx(()=>[_.createElementVNode("div",h_,[_.renderSlot(Ee.$slots,"suggestions",{},()=>[_.createElementVNode("div",p_,[(_.openBlock(!0),_.createElementBlock(_.Fragment,null,_.renderList(rr.value,rt=>(_.openBlock(),_.createBlock(_.unref(Vt.TrDropdownMenu),{key:rt.id,items:rt.menus,onItemClick:ne,trigger:"click"},{trigger:_.withCtx(()=>[_.createVNode(_.unref(Vt.TrSuggestionPillButton),null,{default:_.withCtx(()=>[_.createTextVNode(_.toDisplayString(rt.text),1)]),_:2},1024)]),_:2},1032,["items"]))),128))])],!0),_.createVNode(_.unref(Vt.TrSender),{ref_key:"senderRef",ref:we,mode:"multiple",modelValue:_.unref(W),"onUpdate:modelValue":Oe[9]||(Oe[9]=rt=>_.isRef(W)?W.value=rt:null),placeholder:ge.value,clearable:!!_.unref(W),loading:O.value,showWordLimit:!0,maxLength:2e4,onSubmit:gt,onCancel:_.unref(z)},_.createSlots({footer:_.withCtx(()=>[_.createElementVNode("div",g_,[_.createVNode(Yw,{"installed-plugins":_.unref(ye),onClick:Oe[6]||(Oe[6]=rt=>Ve.value=!_.unref(Ve))},null,8,["installed-plugins"]),_.unref(E)&&_.unref(E).length>0?(_.openBlock(),_.createBlock(Gw,{key:0,"model-configs":_.unref(E),"selected-model-id":x.value,"onUpdate:selectedModelId":Oe[7]||(Oe[7]=rt=>x.value=rt)},null,8,["model-configs","selected-model-id"])):_.createCommentVNode("",!0),D.value?(_.openBlock(),_.createBlock(t_,{key:1,"genui-enabled":v.value,"onUpdate:genuiEnabled":Oe[8]||(Oe[8]=rt=>v.value=rt)},null,8,["genui-enabled"])):_.createCommentVNode("",!0),_.unref(T)?(_.openBlock(),_.createBlock(_.unref(Vt.TrUploadButton),{key:2,accept:"image/*,application/pdf,.doc,.docx,.txt",multiple:!0,onSelect:_.unref(P)},null,8,["onSelect"])):_.createCommentVNode("",!0)])]),_:2},[_.unref(S).length>0?{name:"header",fn:_.withCtx(()=>[_.createElementVNode("div",m_,[_.createVNode(_.unref(Vt.TrAttachments),{items:_.unref(S),"onUpdate:items":Oe[5]||(Oe[5]=rt=>_.isRef(S)?S.value=rt:null)},null,8,["items"])])]),key:"0"}:void 0]),1032,["modelValue","placeholder","clearable","loading","onCancel"]),_.createVNode(_.unref(Vt.TrMcpServerPicker),{visible:_.unref(Ve),"onUpdate:visible":Oe[10]||(Oe[10]=rt=>_.isRef(Ve)?Ve.value=rt:null),"popup-config":{type:"drawer"},"show-custom-add-button":!0,marketTabTitle:"MCP市场",installedTabTitle:"已添加MCP服务",title:"扩展",installedPlugins:_.unref(ye),marketPlugins:_.unref(Se),"market-category-options":jn.value,"installed-search-fn":_.unref($n),"market-search-fn":_.unref($n),onPluginToggle:_.unref(vt),onPluginAdd:_.unref(In),onPluginDelete:_.unref(nt),onToolToggle:_.unref(et),onPluginCreate:_.unref(Me)},{"header-actions":_.withCtx(()=>[_.renderSlot(Ee.$slots,"header-actions",{},void 0,!0)]),_:3},8,["visible","installedPlugins","marketPlugins","market-category-options","installed-search-fn","market-search-fn","onPluginToggle","onPluginAdd","onPluginDelete","onToolToggle","onPluginCreate"])])]),default:_.withCtx(()=>[_.createVNode(_.unref(Vt.TrBubbleProvider),{"content-renderers":ae},{default:_.withCtx(()=>[_.unref(B).length===0?_.renderSlot(Ee.$slots,"welcome",{key:0},()=>[_.createElementVNode("div",f_,[_.createVNode(_.unref(Vt.TrWelcome),{title:_.unref(At)[t.locale].title,description:_.unref(At)[t.locale].description,icon:_.unref(Ue)},null,8,["title","description","icon"]),_.createVNode(_.unref(Vt.TrPrompts),{items:sn.value,wrap:!0,class:"tiny-prompts","item-class":"prompt-item"},null,8,["items"])])],!0):(_.openBlock(),_.createBlock(_.unref(Vt.TrBubbleList),{key:1,style:{flex:"1"},items:_.unref(B),roles:_.unref(Ze),"auto-scroll":"",loading:_.unref(L).status===_.unref(Kn.STATUS).PROCESSING,"loading-role":"assistant"},null,8,["items","roles","loading"]))]),_:3})]),_:3},8,["show","fullscreen","style"]))}}),Fi=nr(x_,[["__scopeId","data-v-635a2faf"]]);Fi.install=function(t){t.component("tiny-remoter",Fi)};exports.TinyRemoter=Fi;exports.useModel=is;
94
+ `,c_=btoa(l_),wl=`data:image/svg+xml;base64,${c_}`,vi=(t,r)=>{const[i,c]=t.split("#");return{id:r,text:i,inputMessage:c}},u_=t=>{const r={"zh-CN":{title:"OpenTiny NEXT",description:"我是你的私人智能助手",placeholder:"请输入您的问题",thinking:"正在思考中..."},"en-US":{title:"OpenTiny NEXT",description:"I am your private AI assistant",placeholder:"Please enter your question",thinking:"Thinking..."}},i=[{id:"office",text:t.locale==="zh-CN"?"办公助手":"Office Assistant",menus:["接收邮件#请同步邮箱的新邮件。","编写邮件#请新建一个邮件,收件人为 opentiny-next@meeting.com, 内容为举办一个临时会议。","安排会议#创建一个临时的在线会议,主题为讨论问题,时长为1小时。","整理文档#请分析附件中的销售情况,把销售额绘制成折线图。"].map(vi)},{id:"development",text:t.locale==="zh-CN"?"开发支持":"Development Support",menus:["遇到代码问题#请检查当前位置的报错原因。","架构建议#请使用NodeJs实现一个分块上传文件的模块。","最新的技术趋势#请分析Vue与React 框架的优劣分别是什么?"].map(vi)},{id:"management",text:t.locale==="zh-CN"?"项目管理":"Project Management",menus:["项目规划#如何开展品牌推广的活动?","任务分配#将本季度的销售任务分配给三个人,并生成甘特图进行跟踪。","进度跟踪#分析团队的任务完成情况。"].map(vi)}],c=[{label:t.locale==="zh-CN"?"企业办公助手":"Enterprise Office Assistant",description:t.locale==="zh-CN"?"需要我帮你处理邮件、安排会议、整理文档,还是优化工作流程?":"Need help with emails, meeting scheduling, document organization, or workflow optimization?",icon:_.h("span",{style:{fontSize:"18px"}},"🧠"),badge:"NEW"},{label:t.locale==="zh-CN"?"开发技术支持":"Development Support",description:t.locale==="zh-CN"?"遇到代码问题?需要架构建议?还是想了解最新的技术趋势?":"Facing code issues? Need architecture advice? Or want to learn about latest tech trends?",icon:_.h("span",{style:{fontSize:"18px"}},"💻")},{label:t.locale==="zh-CN"?"项目管理协作":"Project Management",description:t.locale==="zh-CN"?"需要项目规划、任务分配、进度跟踪,还是团队协作建议?":"Need project planning, task assignment, progress tracking, or team collaboration advice?",icon:_.h("span",{style:{fontSize:"18px"}},"📊")}];return{lang:r,pillItems:i,promptItems:c}},_l={"No client found for session ID":"受控端页面已关闭请重新打开或者刷新页面","Failed to create MCP client":"创建MCP客户端失败"},d_=t=>{console.log("message",t);const r=Object.keys(_l),i=r.findIndex(d=>t.includes(d));return(i!==-1?_l[r[i]]:t)||t},f_={class:"tr-container__title"},h_={style:{flex:"1"}},p_={class:"chat-input"},m_={class:"chat-input-pills"},g_={class:"attachments-container"},x_={class:"action-buttons"},y_=_.defineComponent({name:"TinyRemoter",__name:"TinyRobotChat",props:_.mergeModels({agentRoot:{type:String,default:"https://agent.opentiny.design/api/v1/webmcp-trial/"},sessionId:{type:String,default:void 0},menuItems:{type:Array},remoteUrl:{type:String},qrCodeUrl:{type:String},systemPrompt:{type:String,default:"你是一个智能助手,擅长通过工具调用帮助用户解决问题和满足用户需求"},title:{type:String,default:"OpenTiny NEXT"},locale:{type:String,default:"zh-CN"},AILogoUrl:{type:String},roleAvatar:{type:Object,default:()=>({user:_.h(Mr.IconUser,{style:{fontSize:"32px"}}),assistant:_.h(ju,{style:{fontSize:"32px"}})})},mode:{type:String,default:"remoter"},llmConfig:{type:Object,default:()=>({baseURL:"https://agent.opentiny.design/api/v1/ai/",genuiUrl:"https://agent.opentiny.design/api/v1/ai/prompt"})},inBrowserExt:{type:Boolean,default:!1},genUiComponents:{type:Object,default:()=>({})},customMarketMcpServers:{type:Array,default:()=>[]},mcpServers:{type:Object,default:void 0},llmConfigs:{type:Array,default:void 0},skills:{type:Object,default:void 0},layoutMode:{type:String,default:"fixed"},debugStream:{type:Boolean,default:!1},promptItems:{type:Array,default:void 0},pillItems:{type:Array,default:void 0}},{fullscreen:{type:Boolean,default:!1},fullscreenModifiers:{},show:{type:Boolean,default:!1},showModifiers:{},selectedModelId:{type:String,default:void 0,required:!1},selectedModelIdModifiers:{},genUiAble:{type:Boolean,default:!1,required:!1},genUiAbleModifiers:{},enabledTools:{type:Object,default:void 0,required:!1},enabledToolsModifiers:{}}),emits:_.mergeModels(["before-ai-render","chat-stream-finish"],["update:fullscreen","update:show","update:selectedModelId","update:genUiAble","update:enabledTools"]),setup(t,{expose:r,emit:i}){const c=t,d=i,f=_.useModel(t,"fullscreen"),m=_.useModel(t,"show"),x=_.useModel(t,"selectedModelId"),v=_.useModel(t,"genUiAble"),g=_.useModel(t,"enabledTools"),E=c.llmConfigs?_.toRef(c,"llmConfigs"):void 0,{selectedModel:A}=is(E,x),D=_.computed(()=>{const Ee=E?.value?.length?A.value:c.llmConfig;return Ee?!!(Ee.baseURL&&Ee.genuiUrl):!1}),{hasMultimodalSupport:T,attachments:S,onFilesSelected:P,checkCanSendAttachments:M,processAttachments:ee,cleanupAttachments:$}=tw({selectedModel:A,selectedModelId:x}),{agent:F,customAgentProvider:re,conversationState:Z,messages:B,messageState:L,inputMessage:W,abortRequest:z,senderRef:we,sendMessage:G,handleSendMessage:me,addMessage:fe,send:te,createConversation:q,switchConversation:ke,deleteConversation:le,getCurrentConversation:Te}=wx({systemPrompt:c.systemPrompt||"",llmConfig:c.llmConfig,emit:d});_.watch(()=>c.systemPrompt,Ee=>{re.promptManager.setStatic(Ee)}),re.isGenuiEnabled=v,re.debugStream=c.debugStream;const Je=_.toRef(c,"skills"),{processSkillMentions:xe}=Vy({skillsRef:Je,customAgentProvider:re}),$e=async(Ee,Oe)=>me(Ee,Oe,xe),{welcomeIcon:Ue,roles:Ze}=Gy({props:c,messages:B,messageState:L,inputMessage:W,handleSendMessage:$e}),{showHistory:qe,handleCreateConversation:ze,handleHistorySelect:ie,handleHistoryUpdateTitle:de,handleHistoryDelete:_e}=qy({createConversation:q,switchConversation:ke,deleteConversation:le,getCurrentConversation:Te,abortRequest:z,conversationState:Z,customAgentProvider:re}),Pe=()=>{if(A.value){const Ee=A.value;re.updateLLMConfig({model:Ee.model||"",baseURL:Ee.baseURL||"",genuiUrl:Ee.genuiUrl||"",apiKey:Ee.apiKey||"",providerType:Ee.providerType,useReActMode:Ee.useReActMode,llm:Ee.llm,providerOptions:Ee.providerOptions,headers:Ee.headers})}else re.updateLLMConfig(re.llmConfig)};c.llmConfigs&&_.watch(A,Pe,{immediate:!0}),_.watch(v,Pe,{immediate:!0});const ae={markdown:new Vt.BubbleMarkdownContentRenderer({mdConfig:{html:!0}}),"schema-card":Ee=>_.h(Ed.GenuiRenderer,{...Ee,customActions:{continueChat:{execute:(Oe,rt)=>{const Ye=typeof Oe=="string"?Oe:Oe.message,Fn=`${Ye},相关参数为:${JSON.stringify(rt?.state||{})}`;fe({role:"user",content:Fn,uiContent:[{type:"markdown",content:Ye}]}),te()}}},generating:Kn.GeneratingStatus.includes(L.status),customComponents:c.genUiComponents,requiredCompleteFieldSelectors:["[componentName=TinyUser] > props > modelValue"]}),image:a_};function J(Ee,Oe){ae[Ee]=Oe}const{installedPlugins:ye,marketPlugins:Se,pluginVisible:Ve,loadMcpServerToPlugin:St,togglePlugin:vt,toggleTool:et,deletePlugin:nt,addPluginCore:Xe,addPluginFromMarket:In,addPluginFromScan:be,handleClientDisconnected:Bn,searchPlugin:$n,syncInstalledPluginTools:qt}=Uy(F,g,wl);zy({onToolCatalogChanged:async()=>{await F.refreshTools(),qt()}}),Se.value=[...c.customMarketMcpServers];const jn=_.ref([{value:"",label:"全部分类"},{value:"productivity",label:"生产力工具"},{value:"communication",label:"沟通协作"},{value:"development",label:"开发工具"},{value:"ai",label:"AI 助手"}]),Ft=u_(c),rr=_.computed(()=>c.pillItems??Ft.pillItems),sn=_.computed(()=>c.promptItems??Ft.promptItems),At=Ft.lang,{handleScanSuccess:or,handleSessionIdInput:Ln,initialize:wr}=Xy({sessionId:_.toRef(c,"sessionId"),agentRoot:_.toRef(c,"agentRoot"),mode:c.mode,qrCodeUrl:c.qrCodeUrl,remoteUrl:c.remoteUrl,menuItems:_.toRef(c,"menuItems"),AILogoUrl:c.AILogoUrl,show:m,addPluginFromScan:be,inputMessage:W}),gt=async Ee=>{if(await Ln(W.value)||!M())return;const rt=await ee();try{await $e(Ee,rt),$()}catch(Ye){console.error("发送消息失败:",Ye)}},ge=_.computed(()=>Kn.GeneratingStatus.includes(L.status)?At[c.locale].thinking:At[c.locale].placeholder),O=_.computed(()=>Kn.GeneratingStatus.includes(L.status)),ne=Ee=>{W.value=Ee.inputMessage};wr(),_.onMounted(async()=>{setTimeout(()=>{ze()},100),F.onError=Oe=>{Oe&&it(d_(Oe))};const Ee=Se.value.filter(Oe=>Oe.addState==="added"&&Oe.enabled);for(const Oe of Ee)await In(Oe);if(c.mcpServers)for(const[Oe,rt]of Object.entries(c.mcpServers))await St(Oe,rt)});const{handleCustomAdd:Me}=Fy(F,ye,wl);return r({agent:F,welcomeIcon:Ue,messages:B,messageState:L,roles:Ze,inputMessage:W,senderRef:we,abortRequest:z,sendMessage:G,loadMcpServerToPlugin:St,handleClientDisconnected:Bn,addMessage:fe,installedPlugins:ye,addPluginCore:Xe,deletePlugin:nt,registerContentRenderer:J,async refreshPluginTools(){await F.refreshTools(),qt()}}),(Ee,Oe)=>(_.openBlock(),_.createBlock(_.unref(Vt.TrContainer),{show:m.value,"onUpdate:show":Oe[11]||(Oe[11]=rt=>m.value=rt),fullscreen:f.value,"onUpdate:fullscreen":Oe[12]||(Oe[12]=rt=>f.value=rt),style:_.normalizeStyle({position:t.layoutMode,width:t.layoutMode!=="fixed"?"unset":void 0,height:t.layoutMode!=="fixed"?"100%":void 0})},{title:_.withCtx(()=>[_.createElementVNode("h3",f_,_.toDisplayString(t.title),1)]),operations:_.withCtx(()=>[_.renderSlot(Ee.$slots,"operations",{},()=>[_.createVNode(_.unref(Vt.TrIconButton),{icon:_.unref(Mr.IconNewSession),size:"28",svgSize:"20",onClick:Oe[0]||(Oe[0]=rt=>_.unref(ze)())},null,8,["icon"]),_.createVNode(_.unref(Vt.TrIconButton),{icon:_.unref(Mr.IconHistory),size:"28",svgSize:"20",onClick:Oe[1]||(Oe[1]=rt=>qe.value=!_.unref(qe))},null,8,["icon"]),_.createVNode(Mw,{onScanSuccess:_.unref(or)},null,8,["onScanSuccess"]),_.createVNode(_.Transition,{name:"drawer-slide",appear:""},{default:_.withCtx(()=>[_.unref(qe)?(_.openBlock(),_.createElementBlock("div",{key:0,class:"drawer-overlay",onClick:Oe[4]||(Oe[4]=rt=>qe.value=!1)},[_.createElementVNode("div",{class:"drawer-container",onClick:Oe[3]||(Oe[3]=_.withModifiers(()=>{},["stop"])),style:{"--tr-history-item-selected-bg":"#ebeeff"}},[Oe[13]||(Oe[13]=_.createElementVNode("h4",null,"历史会话",-1)),_.createVNode(_.unref(Vt.TrHistory),{class:"tr-history-demo",selected:_.unref(Z).currentId,data:_.unref(Z).conversations,showRenameControls:!0,onClose:Oe[2]||(Oe[2]=rt=>qe.value=!1),onItemClick:_.unref(ie),onItemTitleChange:_.unref(de),onItemAction:_.unref(_e)},null,8,["selected","data","onItemClick","onItemTitleChange","onItemAction"])])])):_.createCommentVNode("",!0)]),_:1})],!0)]),footer:_.withCtx(()=>[_.createElementVNode("div",p_,[_.renderSlot(Ee.$slots,"suggestions",{},()=>[_.createElementVNode("div",m_,[(_.openBlock(!0),_.createElementBlock(_.Fragment,null,_.renderList(rr.value,rt=>(_.openBlock(),_.createBlock(_.unref(Vt.TrDropdownMenu),{key:rt.id,items:rt.menus,onItemClick:ne,trigger:"click"},{trigger:_.withCtx(()=>[_.createVNode(_.unref(Vt.TrSuggestionPillButton),null,{default:_.withCtx(()=>[_.createTextVNode(_.toDisplayString(rt.text),1)]),_:2},1024)]),_:2},1032,["items"]))),128))])],!0),_.createVNode(_.unref(Vt.TrSender),{ref_key:"senderRef",ref:we,mode:"multiple",modelValue:_.unref(W),"onUpdate:modelValue":Oe[9]||(Oe[9]=rt=>_.isRef(W)?W.value=rt:null),placeholder:ge.value,clearable:!!_.unref(W),loading:O.value,showWordLimit:!0,maxLength:2e4,onSubmit:gt,onCancel:_.unref(z)},_.createSlots({footer:_.withCtx(()=>[_.createElementVNode("div",x_,[_.createVNode(Kw,{"installed-plugins":_.unref(ye),onClick:Oe[6]||(Oe[6]=rt=>Ve.value=!_.unref(Ve))},null,8,["installed-plugins"]),_.unref(E)&&_.unref(E).length>0?(_.openBlock(),_.createBlock(qw,{key:0,"model-configs":_.unref(E),"selected-model-id":x.value,"onUpdate:selectedModelId":Oe[7]||(Oe[7]=rt=>x.value=rt)},null,8,["model-configs","selected-model-id"])):_.createCommentVNode("",!0),D.value?(_.openBlock(),_.createBlock(n_,{key:1,"genui-enabled":v.value,"onUpdate:genuiEnabled":Oe[8]||(Oe[8]=rt=>v.value=rt)},null,8,["genui-enabled"])):_.createCommentVNode("",!0),_.unref(T)?(_.openBlock(),_.createBlock(_.unref(Vt.TrUploadButton),{key:2,accept:"image/*,application/pdf,.doc,.docx,.txt",multiple:!0,onSelect:_.unref(P)},null,8,["onSelect"])):_.createCommentVNode("",!0)])]),_:2},[_.unref(S).length>0?{name:"header",fn:_.withCtx(()=>[_.createElementVNode("div",g_,[_.createVNode(_.unref(Vt.TrAttachments),{items:_.unref(S),"onUpdate:items":Oe[5]||(Oe[5]=rt=>_.isRef(S)?S.value=rt:null)},null,8,["items"])])]),key:"0"}:void 0]),1032,["modelValue","placeholder","clearable","loading","onCancel"]),_.createVNode(_.unref(Vt.TrMcpServerPicker),{visible:_.unref(Ve),"onUpdate:visible":Oe[10]||(Oe[10]=rt=>_.isRef(Ve)?Ve.value=rt:null),"popup-config":{type:"drawer"},"show-custom-add-button":!0,marketTabTitle:"MCP市场",installedTabTitle:"已添加MCP服务",title:"扩展",installedPlugins:_.unref(ye),marketPlugins:_.unref(Se),"market-category-options":jn.value,"installed-search-fn":_.unref($n),"market-search-fn":_.unref($n),onPluginToggle:_.unref(vt),onPluginAdd:_.unref(In),onPluginDelete:_.unref(nt),onToolToggle:_.unref(et),onPluginCreate:_.unref(Me)},{"header-actions":_.withCtx(()=>[_.renderSlot(Ee.$slots,"header-actions",{},void 0,!0)]),_:3},8,["visible","installedPlugins","marketPlugins","market-category-options","installed-search-fn","market-search-fn","onPluginToggle","onPluginAdd","onPluginDelete","onToolToggle","onPluginCreate"])])]),default:_.withCtx(()=>[_.createVNode(_.unref(Vt.TrBubbleProvider),{"content-renderers":ae},{default:_.withCtx(()=>[_.unref(B).length===0?_.renderSlot(Ee.$slots,"welcome",{},()=>[_.createElementVNode("div",h_,[_.createVNode(_.unref(Vt.TrWelcome),{title:_.unref(At)[t.locale].title,description:_.unref(At)[t.locale].description,icon:_.unref(Ue)},null,8,["title","description","icon"]),_.createVNode(_.unref(Vt.TrPrompts),{items:sn.value,wrap:!0,class:"tiny-prompts","item-class":"prompt-item"},null,8,["items"])])],!0,0):(_.openBlock(),_.createBlock(_.unref(Vt.TrBubbleList),{key:1,style:{flex:"1"},items:_.unref(B),roles:_.unref(Ze),"auto-scroll":"",loading:_.unref(L).status===_.unref(Kn.STATUS).PROCESSING,"loading-role":"assistant"},null,8,["items","roles","loading"]))]),_:3})]),_:3},8,["show","fullscreen","style"]))}}),Fi=nr(y_,[["__scopeId","data-v-635a2faf"]]);Fi.install=function(t){t.component("tiny-remoter",Fi)};exports.TinyRemoter=Fi;exports.useModel=is;