@rizom/brain 0.2.0-alpha.457 → 0.2.0-alpha.458

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.
@@ -0,0 +1,182 @@
1
+ // @bun
2
+ import{pa as RR,qa as UR,ra as $R}from"./index-16rgrexr.js";import{sa as mp}from"./index-48ksf4j5.js";import{$a as xn,$b as _d,$e as Fd,Aa as Do,Ae as QC,Ah as zT,Bf as ET,Bh as iT,Ca as Hx,Cd as ZI,Cf as Us,Dd as KI,De as Ls,Ee as MI,Fe as Mx,Ff as Qs,Fg as NT,Gf as AT,Hd as Qo,Hg as DT,If as jC,Ih as UT,Jb as nI,Je as NC,Jf as PT,Ka as Wx,Kd as WC,Kf as MT,Kg as wx,Lc as tC,Ld as VC,Lf as jT,Mb as AC,Md as Ns,Nb as QT,Nd as sT,Oa as Md,Ob as zx,Od as lT,Pa as Is,Pc as rC,Pd as cT,Qa as $x,Qd as uT,Ra as Lx,Rb as Xx,Rc as LT,Sb as qw,Sd as IC,Ta as qx,Tb as rt,Tc as qT,Td as CC,Te as Tp,Ua as zC,Ub as ir,Uc as OI,Ud as kC,Ue as ga,Va as yr,Vb as _T,Vc as iI,Ve as oI,Wb as tt,Wd as mt,We as PC,Xa as Fx,Xb as Xe,Xc as oC,Xe as Ax,Ya as Zx,Yb as Yi,Yc as wT,Ye as IT,Zb as pe,_a as wn,_b as ys,_c as Qr,_e as YT,ab as UC,ac as Xr,ae as _x,bb as $C,bg as mI,cb as LC,cc as vn,db as qC,dc as Ox,df as XT,eb as FC,fb as BC,gb as GC,hb as JC,ib as da,jb as yI,jf as MC,kb as nC,ld as Nr,lf as CT,mb as Wt,mc as ST,mf as kT,nb as Bs,ob as Bd,pb as LI,qb as JI,ub as Gs,ug as cI,uh as FT,va as jd,vg as uI,vh as nT,wg as pa,xa as Jx,ya as ar,ye as KC,yh as BT,ze as YC,zf as RT,zh as oT}from"./index-a0b2j769.js";import{Kh as Ss,Mh as xC,Nh as bs,Oh as ex,Ph as _s,Qh as tx,Rh as OT,Vh as Sn,Zh as en}from"./index-wymd3tew.js";import{$h as vr,_h as Ut}from"./index-y2qm5f33.js";import{Aj as Wd,Bj as KT,Cj as wC,Di as gt,Fi as is,Li as Xw,Pi as tT,Qj as pI,Ri as rT,Si as xx,Tj as EC,Uj as qd,Vi as hs,Xi as Rx,Zi as Ex,Zj as gT,bi as Gm,ci as Jm,di as r,ek as xT,fj as bn,hi as ap,ij as Yn,ji as ia,jk as CI,kj as ke,kk as vs,lj as ta,lk as TT,nj as kx,uj as As}from"./index-vwrhjcsj.js";import{qk as On,rk as ye,tk as Pl}from"./index-6nbmekgz.js";var Al=ye(function(eW,gg){var{defineProperty:El,getOwnPropertyDescriptor:SR,getOwnPropertyNames:wR}=Object,xR=Object.prototype.hasOwnProperty,TR=(e,t)=>{for(var n in t)El(e,n,{get:t[n],enumerable:!0})},IR=(e,t,n,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of wR(t))if(!xR.call(e,i)&&i!==n)El(e,i,{get:()=>t[i],enumerable:!(o=SR(t,i))||o.enumerable})}return e},CR=(e)=>IR(El({},"__esModule",{value:!0}),e),pg={};TR(pg,{SYMBOL_FOR_REQ_CONTEXT:()=>mg,getContext:()=>kR});gg.exports=CR(pg);var mg=Symbol.for("@vercel/request-context");function kR(){return globalThis[mg]?.get?.()??{}}});var yg=ye(function(tW,hg){var{defineProperty:jl,getOwnPropertyDescriptor:ER,getOwnPropertyNames:AR}=Object,PR=Object.prototype.hasOwnProperty,MR=(e,t)=>{for(var n in t)jl(e,n,{get:t[n],enumerable:!0})},jR=(e,t,n,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of AR(t))if(!PR.call(e,i)&&i!==n)jl(e,i,{get:()=>t[i],enumerable:!(o=ER(t,i))||o.enumerable})}return e},OR=(e)=>jR(jl({},"__esModule",{value:!0}),e),fg={};MR(fg,{getVercelOidcToken:()=>zR,getVercelOidcTokenSync:()=>Ml});hg.exports=OR(fg);var NR=Al(),DR=RR();async function zR(e){let t="",n;try{t=Ml()}catch(o){n=o}try{let[{getTokenPayload:o,isExpired:i},{refreshToken:a}]=await Promise.all([await import("./token-util-hdaedvrq.js").then((m)=>On(m.default)),await import("./token-wagdwj28.js").then((m)=>On(m.default))]);if(!t||i(o(t),e?.expirationBufferMs))await a(e),t=Ml()}catch(o){let i=n instanceof Error?n.message:"";if(o instanceof Error)i=`${i}
3
+ ${o.message}`;if(i)throw new DR.VercelOidcTokenError(i);throw o}return t}function Ml(){let e=(0,NR.getContext)().headers?.["x-vercel-oidc-token"]??process.env.VERCEL_OIDC_TOKEN;if(!e)throw Error("The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?");return e}});var Nl=ye(function(rW,Sg){var{defineProperty:Ol,getOwnPropertyDescriptor:LR,getOwnPropertyNames:qR}=Object,FR=Object.prototype.hasOwnProperty,BR=(e,t)=>{for(var n in t)Ol(e,n,{get:t[n],enumerable:!0})},GR=(e,t,n,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of qR(t))if(!FR.call(e,i)&&i!==n)Ol(e,i,{get:()=>t[i],enumerable:!(o=LR(t,i))||o.enumerable})}return e},JR=(e)=>GR(Ol({},"__esModule",{value:!0}),e),_g={};BR(_g,{AccessTokenMissingError:()=>bg.AccessTokenMissingError,RefreshAccessTokenFailedError:()=>bg.RefreshAccessTokenFailedError,getContext:()=>HR.getContext,getVercelOidcToken:()=>vg.getVercelOidcToken,getVercelOidcTokenSync:()=>vg.getVercelOidcTokenSync,getVercelToken:()=>WR.getVercelToken});Sg.exports=JR(_g);var vg=yg(),HR=Al(),bg=UR(),WR=$R()});var Ul=ye(function(yf){Object.defineProperty(yf,"__esModule",{value:!0});yf.VERSION=void 0;yf.VERSION="1.9.1"});var xf=ye(function(Sf){Object.defineProperty(Sf,"__esModule",{value:!0});Sf.isCompatible=Sf._makeCompatibilityCheck=void 0;var uA=Ul(),bf=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function _f(e){let t=new Set([e]),n=new Set,o=e.match(bf);if(!o)return()=>!1;let i={major:+o[1],minor:+o[2],patch:+o[3],prerelease:o[4]};if(i.prerelease!=null)return function(c){return c===e};function a(l){return n.add(l),!1}function s(l){return t.add(l),!0}return function(c){if(t.has(c))return!0;if(n.has(c))return!1;let u=c.match(bf);if(!u)return a(c);let d={major:+u[1],minor:+u[2],patch:+u[3],prerelease:u[4]};if(d.prerelease!=null)return a(c);if(i.major!==d.major)return a(c);if(i.major===0){if(i.minor===d.minor&&i.patch<=d.patch)return s(c);return a(c)}if(i.minor<=d.minor)return s(c);return a(c)}}Sf._makeCompatibilityCheck=_f;Sf.isCompatible=_f(uA.VERSION)});var Nn=ye(function(Tf){Object.defineProperty(Tf,"__esModule",{value:!0});Tf.unregisterGlobal=Tf.getGlobal=Tf.registerGlobal=void 0;var uo=Ul(),pA=xf(),mA=uo.VERSION.split(".")[0],bi=Symbol.for(`opentelemetry.js.api.${mA}`),_i=typeof globalThis==="object"?globalThis:typeof self==="object"?self:typeof window==="object"?window:typeof global==="object"?global:{};function gA(e,t,n,o=!1){var i;let a=_i[bi]=(i=_i[bi])!==null&&i!==void 0?i:{version:uo.VERSION};if(!o&&a[e]){let s=Error(`@opentelemetry/api: Attempted duplicate registration of API: ${e}`);return n.error(s.stack||s.message),!1}if(a.version!==uo.VERSION){let s=Error(`@opentelemetry/api: Registration of version v${a.version} for ${e} does not match previously registered API v${uo.VERSION}`);return n.error(s.stack||s.message),!1}return a[e]=t,n.debug(`@opentelemetry/api: Registered a global for ${e} v${uo.VERSION}.`),!0}Tf.registerGlobal=gA;function fA(e){var t,n;let o=(t=_i[bi])===null||t===void 0?void 0:t.version;if(!o||!(0,pA.isCompatible)(o))return;return(n=_i[bi])===null||n===void 0?void 0:n[e]}Tf.getGlobal=fA;function hA(e,t){t.debug(`@opentelemetry/api: Unregistering a global for ${e} v${uo.VERSION}.`);let n=_i[bi];if(n)delete n[e]}Tf.unregisterGlobal=hA});var Ef=ye(function(kf){Object.defineProperty(kf,"__esModule",{value:!0});kf.DiagComponentLogger=void 0;var bA=Nn();class Cf{constructor(e){this._namespace=e.namespace||"DiagComponentLogger"}debug(...e){return Si("debug",this._namespace,e)}error(...e){return Si("error",this._namespace,e)}info(...e){return Si("info",this._namespace,e)}warn(...e){return Si("warn",this._namespace,e)}verbose(...e){return Si("verbose",this._namespace,e)}}kf.DiagComponentLogger=Cf;function Si(e,t,n){let o=(0,bA.getGlobal)("diag");if(!o)return;return o[e](t,...n)}});var za=ye(function(Af){Object.defineProperty(Af,"__esModule",{value:!0});Af.DiagLogLevel=void 0;var _A;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(_A=Af.DiagLogLevel||(Af.DiagLogLevel={}))});var jf=ye(function(Pf){Object.defineProperty(Pf,"__esModule",{value:!0});Pf.createLogLevelDiagLogger=void 0;var Hr=za();function SA(e,t){if(e<Hr.DiagLogLevel.NONE)e=Hr.DiagLogLevel.NONE;else if(e>Hr.DiagLogLevel.ALL)e=Hr.DiagLogLevel.ALL;t=t||{};function n(o,i){let a=t[o];if(typeof a==="function"&&e>=i)return a.bind(t);return function(){}}return{error:n("error",Hr.DiagLogLevel.ERROR),warn:n("warn",Hr.DiagLogLevel.WARN),info:n("info",Hr.DiagLogLevel.INFO),debug:n("debug",Hr.DiagLogLevel.DEBUG),verbose:n("verbose",Hr.DiagLogLevel.VERBOSE)}}Pf.createLogLevelDiagLogger=SA});var Dn=ye(function(Nf){Object.defineProperty(Nf,"__esModule",{value:!0});Nf.DiagAPI=void 0;var wA=Ef(),xA=jf(),Of=za(),Ua=Nn(),TA="diag";class Ll{static instance(){if(!this._instance)this._instance=new Ll;return this._instance}constructor(){function e(o){return function(...i){let a=(0,Ua.getGlobal)("diag");if(!a)return;return a[o](...i)}}let t=this,n=(o,i={logLevel:Of.DiagLogLevel.INFO})=>{var a,s,l;if(o===t){let d=Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((a=d.stack)!==null&&a!==void 0?a:d.message),!1}if(typeof i==="number")i={logLevel:i};let c=(0,Ua.getGlobal)("diag"),u=(0,xA.createLogLevelDiagLogger)((s=i.logLevel)!==null&&s!==void 0?s:Of.DiagLogLevel.INFO,o);if(c&&!i.suppressOverrideMessage){let d=(l=Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";c.warn(`Current logger will be overwritten from ${d}`),u.warn(`Current logger will overwrite one already registered from ${d}`)}return(0,Ua.registerGlobal)("diag",u,t,!0)};t.setLogger=n,t.disable=()=>{(0,Ua.unregisterGlobal)(TA,t)},t.createComponentLogger=(o)=>new wA.DiagComponentLogger(o),t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}}Nf.DiagAPI=Ll});var $f=ye(function(zf){Object.defineProperty(zf,"__esModule",{value:!0});zf.BaggageImpl=void 0;class po{constructor(e){this._entries=e?new Map(e):new Map}getEntry(e){let t=this._entries.get(e);if(!t)return;return Object.assign({},t)}getAllEntries(){return Array.from(this._entries.entries())}setEntry(e,t){let n=new po(this._entries);return n._entries.set(e,t),n}removeEntry(e){let t=new po(this._entries);return t._entries.delete(e),t}removeEntries(...e){let t=new po(this._entries);for(let n of e)t._entries.delete(n);return t}clear(){return new po}}zf.BaggageImpl=po});var Ff=ye(function(Lf){Object.defineProperty(Lf,"__esModule",{value:!0});Lf.baggageEntryMetadataSymbol=void 0;Lf.baggageEntryMetadataSymbol=Symbol("BaggageEntryMetadata")});var ql=ye(function(Bf){Object.defineProperty(Bf,"__esModule",{value:!0});Bf.baggageEntryMetadataFromString=Bf.createBaggage=void 0;var IA=Dn(),CA=$f(),kA=Ff(),RA=IA.DiagAPI.instance();function EA(e={}){return new CA.BaggageImpl(new Map(Object.entries(e)))}Bf.createBaggage=EA;function AA(e){if(typeof e!=="string")RA.error(`Cannot create baggage metadata from unknown type: ${typeof e}`),e="";return{__TYPE__:kA.baggageEntryMetadataSymbol,toString(){return e}}}Bf.baggageEntryMetadataFromString=AA});var wi=ye(function(Jf){Object.defineProperty(Jf,"__esModule",{value:!0});Jf.ROOT_CONTEXT=Jf.createContextKey=void 0;function MA(e){return Symbol.for(e)}Jf.createContextKey=MA;class $a{constructor(e){let t=this;t._currentContext=e?new Map(e):new Map,t.getValue=(n)=>t._currentContext.get(n),t.setValue=(n,o)=>{let i=new $a(t._currentContext);return i._currentContext.set(n,o),i},t.deleteValue=(n)=>{let o=new $a(t._currentContext);return o._currentContext.delete(n),o}}}Jf.ROOT_CONTEXT=new $a});var Kf=ye(function(Vf){Object.defineProperty(Vf,"__esModule",{value:!0});Vf.DiagConsoleLogger=Vf._originalConsoleMethods=void 0;var Fl=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}];Vf._originalConsoleMethods={};if(typeof console<"u"){let e=["error","warn","info","debug","trace","log"];for(let t of e)if(typeof console[t]==="function")Vf._originalConsoleMethods[t]=console[t]}class Wf{constructor(){function e(t){return function(...n){let o=Vf._originalConsoleMethods[t];if(typeof o!=="function")o=Vf._originalConsoleMethods.log;if(typeof o!=="function"&&console){if(o=console[t],typeof o!=="function")o=console.log}if(typeof o==="function")return o.apply(console,n)}}for(let t=0;t<Fl.length;t++)this[Fl[t].n]=e(Fl[t].c)}}Vf.DiagConsoleLogger=Wf});var Yl=ye(function(Yf){Object.defineProperty(Yf,"__esModule",{value:!0});Yf.createNoopMeter=Yf.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=Yf.NOOP_OBSERVABLE_GAUGE_METRIC=Yf.NOOP_OBSERVABLE_COUNTER_METRIC=Yf.NOOP_UP_DOWN_COUNTER_METRIC=Yf.NOOP_HISTOGRAM_METRIC=Yf.NOOP_GAUGE_METRIC=Yf.NOOP_COUNTER_METRIC=Yf.NOOP_METER=Yf.NoopObservableUpDownCounterMetric=Yf.NoopObservableGaugeMetric=Yf.NoopObservableCounterMetric=Yf.NoopObservableMetric=Yf.NoopHistogramMetric=Yf.NoopGaugeMetric=Yf.NoopUpDownCounterMetric=Yf.NoopCounterMetric=Yf.NoopMetric=Yf.NoopMeter=void 0;class Bl{constructor(){}createGauge(e,t){return Yf.NOOP_GAUGE_METRIC}createHistogram(e,t){return Yf.NOOP_HISTOGRAM_METRIC}createCounter(e,t){return Yf.NOOP_COUNTER_METRIC}createUpDownCounter(e,t){return Yf.NOOP_UP_DOWN_COUNTER_METRIC}createObservableGauge(e,t){return Yf.NOOP_OBSERVABLE_GAUGE_METRIC}createObservableCounter(e,t){return Yf.NOOP_OBSERVABLE_COUNTER_METRIC}createObservableUpDownCounter(e,t){return Yf.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC}addBatchObservableCallback(e,t){}removeBatchObservableCallback(e){}}Yf.NoopMeter=Bl;class mo{}Yf.NoopMetric=mo;class Gl extends mo{add(e,t){}}Yf.NoopCounterMetric=Gl;class Jl extends mo{add(e,t){}}Yf.NoopUpDownCounterMetric=Jl;class Hl extends mo{record(e,t){}}Yf.NoopGaugeMetric=Hl;class Wl extends mo{record(e,t){}}Yf.NoopHistogramMetric=Wl;class xi{addCallback(e){}removeCallback(e){}}Yf.NoopObservableMetric=xi;class Vl extends xi{}Yf.NoopObservableCounterMetric=Vl;class Zl extends xi{}Yf.NoopObservableGaugeMetric=Zl;class Kl extends xi{}Yf.NoopObservableUpDownCounterMetric=Kl;Yf.NOOP_METER=new Bl;Yf.NOOP_COUNTER_METRIC=new Gl;Yf.NOOP_GAUGE_METRIC=new Hl;Yf.NOOP_HISTOGRAM_METRIC=new Wl;Yf.NOOP_UP_DOWN_COUNTER_METRIC=new Jl;Yf.NOOP_OBSERVABLE_COUNTER_METRIC=new Vl;Yf.NOOP_OBSERVABLE_GAUGE_METRIC=new Zl;Yf.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=new Kl;function OA(){return Yf.NOOP_METER}Yf.createNoopMeter=OA});var lh=ye(function(sh){Object.defineProperty(sh,"__esModule",{value:!0});sh.ValueType=void 0;var JA;(function(e){e[e.INT=0]="INT",e[e.DOUBLE=1]="DOUBLE"})(JA=sh.ValueType||(sh.ValueType={}))});var Xl=ye(function(ch){Object.defineProperty(ch,"__esModule",{value:!0});ch.defaultTextMapSetter=ch.defaultTextMapGetter=void 0;ch.defaultTextMapGetter={get(e,t){if(e==null)return;return e[t]},keys(e){if(e==null)return[];return Object.keys(e)}};ch.defaultTextMapSetter={set(e,t,n){if(e==null)return;e[t]=n}}});var gh=ye(function(ph){Object.defineProperty(ph,"__esModule",{value:!0});ph.NoopContextManager=void 0;var WA=wi();class dh{active(){return WA.ROOT_CONTEXT}with(e,t,n,...o){return t.call(n,...o)}bind(e,t){return t}enable(){return this}disable(){return this}}ph.NoopContextManager=dh});var Ti=ye(function(hh){Object.defineProperty(hh,"__esModule",{value:!0});hh.ContextAPI=void 0;var VA=gh(),ec=Nn(),fh=Dn(),tc="context",ZA=new VA.NoopContextManager;class rc{constructor(){}static getInstance(){if(!this._instance)this._instance=new rc;return this._instance}setGlobalContextManager(e){return(0,ec.registerGlobal)(tc,e,fh.DiagAPI.instance())}active(){return this._getContextManager().active()}with(e,t,n,...o){return this._getContextManager().with(e,t,n,...o)}bind(e,t){return this._getContextManager().bind(e,t)}_getContextManager(){return(0,ec.getGlobal)(tc)||ZA}disable(){this._getContextManager().disable(),(0,ec.unregisterGlobal)(tc,fh.DiagAPI.instance())}}hh.ContextAPI=rc});var oc=ye(function(vh){Object.defineProperty(vh,"__esModule",{value:!0});vh.TraceFlags=void 0;var KA;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(KA=vh.TraceFlags||(vh.TraceFlags={}))});var qa=ye(function(bh){Object.defineProperty(bh,"__esModule",{value:!0});bh.INVALID_SPAN_CONTEXT=bh.INVALID_TRACEID=bh.INVALID_SPANID=void 0;var YA=oc();bh.INVALID_SPANID="0000000000000000";bh.INVALID_TRACEID="00000000000000000000000000000000";bh.INVALID_SPAN_CONTEXT={traceId:bh.INVALID_TRACEID,spanId:bh.INVALID_SPANID,traceFlags:YA.TraceFlags.NONE}});var Fa=ye(function(Th){Object.defineProperty(Th,"__esModule",{value:!0});Th.NonRecordingSpan=void 0;var QA=qa();class xh{constructor(e=QA.INVALID_SPAN_CONTEXT){this._spanContext=e}spanContext(){return this._spanContext}setAttribute(e,t){return this}setAttributes(e){return this}addEvent(e,t){return this}addLink(e){return this}addLinks(e){return this}setStatus(e){return this}updateName(e){return this}end(e){}isRecording(){return!1}recordException(e,t){}}Th.NonRecordingSpan=xh});var sc=ye(function(kh){Object.defineProperty(kh,"__esModule",{value:!0});kh.getSpanContext=kh.setSpanContext=kh.deleteSpan=kh.setSpan=kh.getActiveSpan=kh.getSpan=void 0;var XA=wi(),eP=Fa(),tP=Ti(),ic=(0,XA.createContextKey)("OpenTelemetry Context Key SPAN");function ac(e){return e.getValue(ic)||void 0}kh.getSpan=ac;function rP(){return ac(tP.ContextAPI.getInstance().active())}kh.getActiveSpan=rP;function Ch(e,t){return e.setValue(ic,t)}kh.setSpan=Ch;function nP(e){return e.deleteValue(ic)}kh.deleteSpan=nP;function oP(e,t){return Ch(e,new eP.NonRecordingSpan(t))}kh.setSpanContext=oP;function iP(e){var t;return(t=ac(e))===null||t===void 0?void 0:t.spanContext()}kh.getSpanContext=iP});var Ga=ye(function(jh){Object.defineProperty(jh,"__esModule",{value:!0});jh.wrapSpanContext=jh.isSpanContextValid=jh.isValidSpanId=jh.isValidTraceId=void 0;var Eh=qa(),dP=Fa(),Ba=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1]);function Ah(e,t){if(typeof e!=="string"||e.length!==t)return!1;let n=0;for(let o=0;o<e.length;o+=4)n+=(Ba[e.charCodeAt(o)]|0)+(Ba[e.charCodeAt(o+1)]|0)+(Ba[e.charCodeAt(o+2)]|0)+(Ba[e.charCodeAt(o+3)]|0);return n===t}function Ph(e){return Ah(e,32)&&e!==Eh.INVALID_TRACEID}jh.isValidTraceId=Ph;function Mh(e){return Ah(e,16)&&e!==Eh.INVALID_SPANID}jh.isValidSpanId=Mh;function pP(e){return Ph(e.traceId)&&Mh(e.spanId)}jh.isSpanContextValid=pP;function mP(e){return new dP.NonRecordingSpan(e)}jh.wrapSpanContext=mP});var uc=ye(function(zh){Object.defineProperty(zh,"__esModule",{value:!0});zh.NoopTracer=void 0;var yP=Ti(),Nh=sc(),lc=Fa(),vP=Ga(),cc=yP.ContextAPI.getInstance();class Dh{startSpan(e,t,n=cc.active()){if(Boolean(t===null||t===void 0?void 0:t.root))return new lc.NonRecordingSpan;let i=n&&(0,Nh.getSpanContext)(n);if(bP(i)&&(0,vP.isSpanContextValid)(i))return new lc.NonRecordingSpan(i);else return new lc.NonRecordingSpan}startActiveSpan(e,t,n,o){let i,a,s;if(arguments.length<2)return;else if(arguments.length===2)s=t;else if(arguments.length===3)i=t,s=n;else i=t,a=n,s=o;let l=a!==null&&a!==void 0?a:cc.active(),c=this.startSpan(e,i,l),u=(0,Nh.setSpan)(l,c);return cc.with(u,s,void 0,c)}}zh.NoopTracer=Dh;function bP(e){return e!==null&&typeof e==="object"&&"spanId"in e&&typeof e.spanId==="string"&&"traceId"in e&&typeof e.traceId==="string"&&"traceFlags"in e&&typeof e.traceFlags==="number"}});var dc=ye(function(Lh){Object.defineProperty(Lh,"__esModule",{value:!0});Lh.ProxyTracer=void 0;var _P=uc(),SP=new _P.NoopTracer;class $h{constructor(e,t,n,o){this._provider=e,this.name=t,this.version=n,this.options=o}startSpan(e,t,n){return this._getTracer().startSpan(e,t,n)}startActiveSpan(e,t,n,o){let i=this._getTracer();return Reflect.apply(i.startActiveSpan,i,arguments)}_getTracer(){if(this._delegate)return this._delegate;let e=this._provider.getDelegateTracer(this.name,this.version,this.options);if(!e)return SP;return this._delegate=e,this._delegate}}Lh.ProxyTracer=$h});var Jh=ye(function(Bh){Object.defineProperty(Bh,"__esModule",{value:!0});Bh.NoopTracerProvider=void 0;var wP=uc();class Fh{getTracer(e,t,n){return new wP.NoopTracer}}Bh.NoopTracerProvider=Fh});var pc=ye(function(Wh){Object.defineProperty(Wh,"__esModule",{value:!0});Wh.ProxyTracerProvider=void 0;var xP=dc(),TP=Jh(),IP=new TP.NoopTracerProvider;class Hh{getTracer(e,t,n){var o;return(o=this.getDelegateTracer(e,t,n))!==null&&o!==void 0?o:new xP.ProxyTracer(this,e,t,n)}getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:IP}setDelegate(e){this._delegate=e}getDelegateTracer(e,t,n){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(e,t,n)}}Wh.ProxyTracerProvider=Hh});var Kh=ye(function(Zh){Object.defineProperty(Zh,"__esModule",{value:!0});Zh.SamplingDecision=void 0;var CP;(function(e){e[e.NOT_RECORD=0]="NOT_RECORD",e[e.RECORD=1]="RECORD",e[e.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(CP=Zh.SamplingDecision||(Zh.SamplingDecision={}))});var Qh=ye(function(Yh){Object.defineProperty(Yh,"__esModule",{value:!0});Yh.SpanKind=void 0;var kP;(function(e){e[e.INTERNAL=0]="INTERNAL",e[e.SERVER=1]="SERVER",e[e.CLIENT=2]="CLIENT",e[e.PRODUCER=3]="PRODUCER",e[e.CONSUMER=4]="CONSUMER"})(kP=Yh.SpanKind||(Yh.SpanKind={}))});var ey=ye(function(Xh){Object.defineProperty(Xh,"__esModule",{value:!0});Xh.SpanStatusCode=void 0;var RP;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(RP=Xh.SpanStatusCode||(Xh.SpanStatusCode={}))});var ny=ye(function(ty){Object.defineProperty(ty,"__esModule",{value:!0});ty.validateValue=ty.validateKey=void 0;var hc="[_0-9a-z-*/]",EP=`[a-z]${hc}{0,255}`,AP=`[a-z0-9]${hc}{0,240}@[a-z]${hc}{0,13}`,PP=new RegExp(`^(?:${EP}|${AP})$`),MP=/^[ -~]{0,255}[!-~]$/,jP=/,|=/;function OP(e){return PP.test(e)}ty.validateKey=OP;function NP(e){return MP.test(e)&&!jP.test(e)}ty.validateValue=NP});var uy=ye(function(ly){Object.defineProperty(ly,"__esModule",{value:!0});ly.TraceStateImpl=void 0;var oy=ny(),iy=32,zP=512,ay=",",sy="=";class yc{constructor(e){if(this._internalState=new Map,e)this._parse(e)}set(e,t){let n=this._clone();if(n._internalState.has(e))n._internalState.delete(e);return n._internalState.set(e,t),n}unset(e){let t=this._clone();return t._internalState.delete(e),t}get(e){return this._internalState.get(e)}serialize(){return Array.from(this._internalState.keys()).reduceRight((e,t)=>(e.push(t+sy+this.get(t)),e),[]).join(ay)}_parse(e){if(e.length>zP)return;if(this._internalState=e.split(ay).reduceRight((t,n)=>{let o=n.trim(),i=o.indexOf(sy);if(i!==-1){let a=o.slice(0,i),s=o.slice(i+1,n.length);if((0,oy.validateKey)(a)&&(0,oy.validateValue)(s))t.set(a,s)}return t},new Map),this._internalState.size>iy)this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,iy))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new yc;return e._internalState=new Map(this._internalState),e}}ly.TraceStateImpl=yc});var my=ye(function(dy){Object.defineProperty(dy,"__esModule",{value:!0});dy.createTraceState=void 0;var UP=uy();function $P(e){return new UP.TraceStateImpl(e)}dy.createTraceState=$P});var hy=ye(function(gy){Object.defineProperty(gy,"__esModule",{value:!0});gy.context=void 0;var LP=Ti();gy.context=LP.ContextAPI.getInstance()});var by=ye(function(yy){Object.defineProperty(yy,"__esModule",{value:!0});yy.diag=void 0;var qP=Dn();yy.diag=qP.DiagAPI.instance()});var wy=ye(function(_y){Object.defineProperty(_y,"__esModule",{value:!0});_y.NOOP_METER_PROVIDER=_y.NoopMeterProvider=void 0;var FP=Yl();class vc{getMeter(e,t,n){return FP.NOOP_METER}}_y.NoopMeterProvider=vc;_y.NOOP_METER_PROVIDER=new vc});var Cy=ye(function(Ty){Object.defineProperty(Ty,"__esModule",{value:!0});Ty.MetricsAPI=void 0;var GP=wy(),bc=Nn(),xy=Dn(),_c="metrics";class Sc{constructor(){}static getInstance(){if(!this._instance)this._instance=new Sc;return this._instance}setGlobalMeterProvider(e){return(0,bc.registerGlobal)(_c,e,xy.DiagAPI.instance())}getMeterProvider(){return(0,bc.getGlobal)(_c)||GP.NOOP_METER_PROVIDER}getMeter(e,t,n){return this.getMeterProvider().getMeter(e,t,n)}disable(){(0,bc.unregisterGlobal)(_c,xy.DiagAPI.instance())}}Ty.MetricsAPI=Sc});var Ey=ye(function(ky){Object.defineProperty(ky,"__esModule",{value:!0});ky.metrics=void 0;var JP=Cy();ky.metrics=JP.MetricsAPI.getInstance()});var jy=ye(function(Py){Object.defineProperty(Py,"__esModule",{value:!0});Py.NoopTextMapPropagator=void 0;class Ay{inject(e,t){}extract(e,t){return e}fields(){return[]}}Py.NoopTextMapPropagator=Ay});var zy=ye(function(Ny){Object.defineProperty(Ny,"__esModule",{value:!0});Ny.deleteBaggage=Ny.setBaggage=Ny.getActiveBaggage=Ny.getBaggage=void 0;var HP=Ti(),WP=wi(),wc=(0,WP.createContextKey)("OpenTelemetry Baggage Key");function Oy(e){return e.getValue(wc)||void 0}Ny.getBaggage=Oy;function VP(){return Oy(HP.ContextAPI.getInstance().active())}Ny.getActiveBaggage=VP;function ZP(e,t){return e.setValue(wc,t)}Ny.setBaggage=ZP;function KP(e){return e.deleteValue(wc)}Ny.deleteBaggage=KP});var Fy=ye(function(Ly){Object.defineProperty(Ly,"__esModule",{value:!0});Ly.PropagationAPI=void 0;var xc=Nn(),eM=jy(),Uy=Xl(),Ja=zy(),tM=ql(),$y=Dn(),Tc="propagation",rM=new eM.NoopTextMapPropagator;class Ic{constructor(){this.createBaggage=tM.createBaggage,this.getBaggage=Ja.getBaggage,this.getActiveBaggage=Ja.getActiveBaggage,this.setBaggage=Ja.setBaggage,this.deleteBaggage=Ja.deleteBaggage}static getInstance(){if(!this._instance)this._instance=new Ic;return this._instance}setGlobalPropagator(e){return(0,xc.registerGlobal)(Tc,e,$y.DiagAPI.instance())}inject(e,t,n=Uy.defaultTextMapSetter){return this._getGlobalPropagator().inject(e,t,n)}extract(e,t,n=Uy.defaultTextMapGetter){return this._getGlobalPropagator().extract(e,t,n)}fields(){return this._getGlobalPropagator().fields()}disable(){(0,xc.unregisterGlobal)(Tc,$y.DiagAPI.instance())}_getGlobalPropagator(){return(0,xc.getGlobal)(Tc)||rM}}Ly.PropagationAPI=Ic});var Jy=ye(function(By){Object.defineProperty(By,"__esModule",{value:!0});By.propagation=void 0;var nM=Fy();By.propagation=nM.PropagationAPI.getInstance()});var Yy=ye(function(Zy){Object.defineProperty(Zy,"__esModule",{value:!0});Zy.TraceAPI=void 0;var Cc=Nn(),Hy=pc(),Wy=Ga(),go=sc(),Vy=Dn(),kc="trace";class Rc{constructor(){this._proxyTracerProvider=new Hy.ProxyTracerProvider,this.wrapSpanContext=Wy.wrapSpanContext,this.isSpanContextValid=Wy.isSpanContextValid,this.deleteSpan=go.deleteSpan,this.getSpan=go.getSpan,this.getActiveSpan=go.getActiveSpan,this.getSpanContext=go.getSpanContext,this.setSpan=go.setSpan,this.setSpanContext=go.setSpanContext}static getInstance(){if(!this._instance)this._instance=new Rc;return this._instance}setGlobalTracerProvider(e){let t=(0,Cc.registerGlobal)(kc,this._proxyTracerProvider,Vy.DiagAPI.instance());if(t)this._proxyTracerProvider.setDelegate(e);return t}getTracerProvider(){return(0,Cc.getGlobal)(kc)||this._proxyTracerProvider}getTracer(e,t){return this.getTracerProvider().getTracer(e,t)}disable(){(0,Cc.unregisterGlobal)(kc,Vy.DiagAPI.instance()),this._proxyTracerProvider=new Hy.ProxyTracerProvider}}Zy.TraceAPI=Rc});var ev=ye(function(Qy){Object.defineProperty(Qy,"__esModule",{value:!0});Qy.trace=void 0;var oM=Yy();Qy.trace=oM.TraceAPI.getInstance()});var Pc=ye(function(Ze){Object.defineProperty(Ze,"__esModule",{value:!0});Ze.trace=Ze.propagation=Ze.metrics=Ze.diag=Ze.context=Ze.INVALID_SPAN_CONTEXT=Ze.INVALID_TRACEID=Ze.INVALID_SPANID=Ze.isValidSpanId=Ze.isValidTraceId=Ze.isSpanContextValid=Ze.createTraceState=Ze.TraceFlags=Ze.SpanStatusCode=Ze.SpanKind=Ze.SamplingDecision=Ze.ProxyTracerProvider=Ze.ProxyTracer=Ze.defaultTextMapSetter=Ze.defaultTextMapGetter=Ze.ValueType=Ze.createNoopMeter=Ze.DiagLogLevel=Ze.DiagConsoleLogger=Ze.ROOT_CONTEXT=Ze.createContextKey=Ze.baggageEntryMetadataFromString=void 0;var iM=ql();Object.defineProperty(Ze,"baggageEntryMetadataFromString",{enumerable:!0,get:function(){return iM.baggageEntryMetadataFromString}});var tv=wi();Object.defineProperty(Ze,"createContextKey",{enumerable:!0,get:function(){return tv.createContextKey}});Object.defineProperty(Ze,"ROOT_CONTEXT",{enumerable:!0,get:function(){return tv.ROOT_CONTEXT}});var aM=Kf();Object.defineProperty(Ze,"DiagConsoleLogger",{enumerable:!0,get:function(){return aM.DiagConsoleLogger}});var sM=za();Object.defineProperty(Ze,"DiagLogLevel",{enumerable:!0,get:function(){return sM.DiagLogLevel}});var lM=Yl();Object.defineProperty(Ze,"createNoopMeter",{enumerable:!0,get:function(){return lM.createNoopMeter}});var cM=lh();Object.defineProperty(Ze,"ValueType",{enumerable:!0,get:function(){return cM.ValueType}});var rv=Xl();Object.defineProperty(Ze,"defaultTextMapGetter",{enumerable:!0,get:function(){return rv.defaultTextMapGetter}});Object.defineProperty(Ze,"defaultTextMapSetter",{enumerable:!0,get:function(){return rv.defaultTextMapSetter}});var uM=dc();Object.defineProperty(Ze,"ProxyTracer",{enumerable:!0,get:function(){return uM.ProxyTracer}});var dM=pc();Object.defineProperty(Ze,"ProxyTracerProvider",{enumerable:!0,get:function(){return dM.ProxyTracerProvider}});var pM=Kh();Object.defineProperty(Ze,"SamplingDecision",{enumerable:!0,get:function(){return pM.SamplingDecision}});var mM=Qh();Object.defineProperty(Ze,"SpanKind",{enumerable:!0,get:function(){return mM.SpanKind}});var gM=ey();Object.defineProperty(Ze,"SpanStatusCode",{enumerable:!0,get:function(){return gM.SpanStatusCode}});var fM=oc();Object.defineProperty(Ze,"TraceFlags",{enumerable:!0,get:function(){return fM.TraceFlags}});var hM=my();Object.defineProperty(Ze,"createTraceState",{enumerable:!0,get:function(){return hM.createTraceState}});var Ec=Ga();Object.defineProperty(Ze,"isSpanContextValid",{enumerable:!0,get:function(){return Ec.isSpanContextValid}});Object.defineProperty(Ze,"isValidTraceId",{enumerable:!0,get:function(){return Ec.isValidTraceId}});Object.defineProperty(Ze,"isValidSpanId",{enumerable:!0,get:function(){return Ec.isValidSpanId}});var Ac=qa();Object.defineProperty(Ze,"INVALID_SPANID",{enumerable:!0,get:function(){return Ac.INVALID_SPANID}});Object.defineProperty(Ze,"INVALID_TRACEID",{enumerable:!0,get:function(){return Ac.INVALID_TRACEID}});Object.defineProperty(Ze,"INVALID_SPAN_CONTEXT",{enumerable:!0,get:function(){return Ac.INVALID_SPAN_CONTEXT}});var nv=hy();Object.defineProperty(Ze,"context",{enumerable:!0,get:function(){return nv.context}});var ov=by();Object.defineProperty(Ze,"diag",{enumerable:!0,get:function(){return ov.diag}});var iv=Ey();Object.defineProperty(Ze,"metrics",{enumerable:!0,get:function(){return iv.metrics}});var av=Jy();Object.defineProperty(Ze,"propagation",{enumerable:!0,get:function(){return av.propagation}});var sv=ev();Object.defineProperty(Ze,"trace",{enumerable:!0,get:function(){return sv.trace}});Ze.default={context:nv.context,diag:ov.diag,metrics:iv.metrics,propagation:av.propagation,trace:sv.trace}});var as=ye(function(LS){Object.defineProperty(LS,"__esModule",{value:!0});function US(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;console.warn("XState could not find a global object in this environment. Please let the maintainers know and raise an issue here: https://github.com/statelyai/xstate/issues")}function $S(){let e=US();if(e.__xstate__)return e.__xstate__;return}function Nz(e){if(typeof window>"u")return;let t=$S();if(t)t.register(e)}var Dz=(e)=>{if(typeof window>"u")return;let t=$S();if(t)t.register(e)};LS.devToolsAdapter=Dz;LS.getGlobal=US;LS.registerService=Nz});var Ao=ye(function(JU){var Lz=as();class Mu{constructor(e){this._process=e,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){if(this._current)this._current.next=null,this._last=this._current}enqueue(e){let t={value:e,next:null};if(this._current){this._last.next=t,this._last=t;return}if(this._current=t,this._last=t,this._active)this.flush()}flush(){while(this._current){let e=this._current;this._process(e.value),this._current=e.next}this._last=null}}var HS=".",qz="",WS="",Fz="#",ju="*",VS="xstate.init",Bz="xstate.error",ss="xstate.stop";function Gz(e,t){return{type:`xstate.after.${e}.${t}`}}function Ou(e,t){return{type:`xstate.done.state.${e}`,output:t}}function Jz(e,t){return{type:`xstate.done.actor.${e}`,output:t,actorId:e}}function ZS(e,t){return{type:`xstate.error.actor.${e}`,error:t,actorId:e}}function KS(e){return{type:VS,input:e}}function Pr(e){setTimeout(()=>{throw e})}var Hz=(()=>typeof Symbol==="function"&&Symbol.observable||"@@observable")();function Uu(e,t){let n=qS(e),o=qS(t);if(typeof o==="string"){if(typeof n==="string")return o===n;return!1}if(typeof n==="string")return n in o;return Object.keys(n).every((i)=>{if(!(i in o))return!1;return Uu(n[i],o[i])})}function $u(e){if(XS(e))return e;let t=[],n="";for(let o=0;o<e.length;o++){switch(e.charCodeAt(o)){case 92:n+=e[o+1],o++;continue;case 46:t.push(n),n="";continue}n+=e[o]}return t.push(n),t}function qS(e){if(yw(e))return e.value;if(typeof e!=="string")return e;let t=$u(e);return YS(t)}function YS(e){if(e.length===1)return e[0];let t={},n=t;for(let o=0;o<e.length-1;o++)if(o===e.length-2)n[e[o]]=e[o+1];else{let i=n;n={},i[e[o]]=n}return t}function Wz(e,t){let n={},o=Object.keys(e);for(let i=0;i<o.length;i++){let a=o[i];n[a]=t(e[a],a,e,i)}return n}function QS(e){if(XS(e))return e;return[e]}function Ji(e){if(e===void 0)return[];return QS(e)}function Nu(e,t,n,o){if(typeof e==="function")return e({context:t,event:n,self:o});if(!!e&&typeof e==="object"&&Object.values(e).some((i)=>typeof i==="function"))console.warn(`Dynamically mapping values to individual properties is deprecated. Use a single function that returns the mapped object instead.
4
+ Found object containing properties whose values are possibly mapping functions: ${Object.entries(e).filter(([,i])=>typeof i==="function").map(([i,a])=>`
5
+ - ${i}: ${a.toString().replace(/\n\s*/g,"")}`).join("")}`);return e}function XS(e){return Array.isArray(e)}function Vz(e){return e.type.startsWith("xstate.error.actor")}function xo(e){return QS(e).map((t)=>{if(typeof t>"u"||typeof t==="string")return{target:t};return t})}function ew(e){if(e===void 0||e===qz)return;return Ji(e)}function Bi(e,t,n){let o=typeof e==="object",i=o?e:void 0;return{next:(o?e.next:e)?.bind(i),error:(o?e.error:t)?.bind(i),complete:(o?e.complete:n)?.bind(i)}}function Zz(e,t){return`${t}.${e}`}function tw(e,t){let n=t.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!n)return e.implementations.actors[t];let[,o,i]=n,s=e.getStateNodeById(i).config.invoke;return(Array.isArray(s)?s[o]:s).src}function Kz(e){return[...new Set([...e._nodes.flatMap((t)=>t.ownEvents)])]}function rw(e,t){if(t===e)return!0;if(t===ju)return!0;if(!t.endsWith(".*"))return!1;if(/.*\*.+/.test(t))console.warn(`Wildcards can only be the last token of an event descriptor (e.g., "event.*") or the entire event descriptor ("*"). Check the "${t}" event.`);let n=t.split("."),o=e.split(".");for(let i=0;i<n.length;i++){let a=n[i],s=o[i];if(a==="*"){let l=i===n.length-1;if(!l)console.warn(`Infix wildcards in transition events are not allowed. Check the "${t}" transition.`);return l}if(a!==s)return!1}return!0}function FS(e,t){return`${e.sessionId}.${t}`}var Yz=0;function nw(e,t){let n=new Map,o=new Map,i=new WeakMap,a=new Set,s={},{clock:l,logger:c}=t,u={schedule:(p,f,g,h,v=Math.random().toString(36).slice(2))=>{let x={source:p,target:f,event:g,delay:h,id:v,startedAt:Date.now()},S=FS(p,v);m._snapshot._scheduledEvents[S]=x;let y=l.setTimeout(()=>{delete s[S],delete m._snapshot._scheduledEvents[S],m._relay(p,f,g)},h);s[S]=y},cancel:(p,f)=>{let g=FS(p,f),h=s[g];if(delete s[g],delete m._snapshot._scheduledEvents[g],h!==void 0)l.clearTimeout(h)},cancelAll:(p)=>{for(let f in m._snapshot._scheduledEvents){let g=m._snapshot._scheduledEvents[f];if(g.source===p)u.cancel(p,g.id)}}},d=(p)=>{if(!a.size)return;let f={...p,rootId:e.sessionId};a.forEach((g)=>g.next?.(f))},m={_snapshot:{_scheduledEvents:(t?.snapshot&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${Yz++}`,_register:(p,f)=>(n.set(p,f),p),_unregister:(p)=>{n.delete(p.sessionId);let f=i.get(p);if(f!==void 0)o.delete(f),i.delete(p)},get:(p)=>o.get(p),getAll:()=>Object.fromEntries(o.entries()),_set:(p,f)=>{let g=o.get(p);if(g&&g!==f)throw Error(`Actor with system ID '${p}' already exists.`);o.set(p,f),i.set(f,p)},inspect:(p)=>{let f=Bi(p);return a.add(f),{unsubscribe(){a.delete(f)}}},_sendInspectionEvent:d,_relay:(p,f,g)=>{m._sendInspectionEvent({type:"@xstate.event",sourceRef:p,actorRef:f,event:g}),f._send(g)},scheduler:u,getSnapshot:()=>({_scheduledEvents:{...m._snapshot._scheduledEvents}}),start:()=>{let p=m._snapshot._scheduledEvents;m._snapshot._scheduledEvents={};for(let f in p){let{source:g,target:h,event:v,delay:x,id:S}=p[f];u.schedule(g,h,v,x,S)}},_clock:l,_logger:c};return m}JU.executingCustomAction=!1;var Lu=1,Ht=function(e){return e[e.NotStarted=0]="NotStarted",e[e.Running=1]="Running",e[e.Stopped=2]="Stopped",e}({}),Qz={clock:{setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:(e)=>clearTimeout(e)},logger:console.log.bind(console),devTools:!1};class qu{constructor(e,t){this.logic=e,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new Mu(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=Ht.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this.systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];let n={...Qz,...t},{clock:o,logger:i,parent:a,syncSnapshot:s,id:l,systemId:c,inspect:u}=n;if(this.system=a?a.system:nw(this,{clock:o,logger:i}),u&&!a)this.system.inspect(Bi(u));if(this.sessionId=this.system._bookId(),this.id=l??this.sessionId,this.logger=t?.logger??this.system._logger,this.clock=t?.clock??this.system._clock,this._parent=a,this._syncSnapshot=s,this.options=n,this.src=n.src??e,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:(d)=>{this._deferred.push(d)},system:this.system,stopChild:(d)=>{if(d._parent!==this)throw Error(`Cannot stop child actor ${d.id} of ${this.id} because it is not a child`);d._stop()},emit:(d)=>{let m=this.eventListeners.get(d.type),p=this.eventListeners.get("*");if(!m&&!p)return;let f=[...m?m.values():[],...p?p.values():[]];for(let g of f)try{g(d)}catch(h){Pr(h)}},actionExecutor:(d)=>{let m=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:d.type,params:d.params}}),!d.exec)return;let p=JU.executingCustomAction;try{JU.executingCustomAction=!0,d.exec(d.info,d.params)}finally{JU.executingCustomAction=p}};if(this._processingStatus===Ht.Running)m();else this._deferred.push(m)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),c)this.systemId=c,this.system._set(c,this);if(this._initState(t?.snapshot??t?.state),c&&this._snapshot.status!=="active")this.system._unregister(this)}_initState(e){try{this._snapshot=e?this.logic.restoreSnapshot?this.logic.restoreSnapshot(e,this._actorScope):e:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(t){this._snapshot={status:"error",output:void 0,error:t}}}update(e,t){this._snapshot=e;let n;while(n=this._deferred.shift())try{n()}catch(o){this._deferred.length=0,this._snapshot={...e,status:"error",error:o}}switch(this._snapshot.status){case"active":for(let o of this.observers)try{o.next?.(e)}catch(i){Pr(i)}break;case"done":for(let o of this.observers)try{o.next?.(e)}catch(i){Pr(i)}if(this._stopProcedure(),this._complete(),this._doneEvent=Jz(this.id,this._snapshot.output),this._parent)this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error);break}this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:t,snapshot:e})}subscribe(e,t,n){let o=Bi(e,t,n);if(this._processingStatus!==Ht.Stopped)this.observers.add(o);else switch(this._snapshot.status){case"done":try{o.complete?.()}catch(i){Pr(i)}break;case"error":{let i=this._snapshot.error;if(!o.error)Pr(i);else try{o.error(i)}catch(a){Pr(a)}break}}return{unsubscribe:()=>{this.observers.delete(o)}}}on(e,t){let n=this.eventListeners.get(e);if(!n)n=new Set,this.eventListeners.set(e,n);let o=t.bind(void 0);return n.add(o),{unsubscribe:()=>{n.delete(o)}}}select(e,t=Object.is){return{subscribe:(n)=>{let o=Bi(n),i=this.getSnapshot(),a=e(i);return this.subscribe((s)=>{let l=e(s);if(!t(a,l))a=l,o.next?.(l)})},get:()=>e(this.getSnapshot())}}start(){if(this._processingStatus===Ht.Running)return this;if(this._syncSnapshot)this.subscribe({next:(n)=>{if(n.status==="active")this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:n})},error:()=>{}});if(this.system._register(this.sessionId,this),this.systemId)this.system._set(this.systemId,this);this._processingStatus=Ht.Running;let e=KS(this.options.input);switch(this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:e}),this._snapshot.status){case"done":return this.update(this._snapshot,e),this;case"error":return this._error(this._snapshot.error),this}if(!this._parent)this.system.start();if(this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(n){return this._snapshot={...this._snapshot,status:"error",error:n},this._error(n),this}if(this.update(this._snapshot,e),this.options.devTools)this.attachDevTools();return this.mailbox.start(),this}_process(e){let t,n;try{t=this.logic.transition(this._snapshot,e,this._actorScope)}catch(o){n={err:o}}if(n){let{err:o}=n;this._snapshot={...this._snapshot,status:"error",error:o},this._error(o);return}if(this.update(t,e),e.type===ss)this._stopProcedure(),this._complete()}_stop(){if(this._processingStatus===Ht.Stopped)return this;if(this.mailbox.clear(),this._processingStatus===Ht.NotStarted)return this._processingStatus=Ht.Stopped,this;return this.mailbox.enqueue({type:ss}),this}stop(){if(this._parent)throw Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(let e of this.observers)try{e.complete?.()}catch(t){Pr(t)}this.observers.clear(),this.eventListeners.clear()}_reportError(e){if(!this.observers.size){if(!this._parent)Pr(e);this.eventListeners.clear();return}let t=!1;for(let n of this.observers){let o=n.error;t||=!o;try{o?.(e)}catch(i){Pr(i)}}if(this.observers.clear(),this.eventListeners.clear(),t)Pr(e)}_error(e){if(this._stopProcedure(),this._reportError(e),this._parent)this.system._relay(this,this._parent,ZS(this.id,e))}_stopProcedure(){if(this._processingStatus!==Ht.Running)return this;return this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new Mu(this._process.bind(this)),this._processingStatus=Ht.Stopped,this.system._unregister(this),this}_send(e){if(this._processingStatus===Ht.Stopped){{let t=JSON.stringify(e);console.warn(`Event "${e.type}" was sent to stopped actor "${this.id} (${this.sessionId})". This actor has already reached its final state, and will not transition.
6
+ Event: ${t}`)}return}this.mailbox.enqueue(e)}send(e){if(typeof e==="string")throw Error(`Only event objects may be sent to actors; use .send({ type: "${e}" }) instead`);this.system._relay(void 0,this,e)}attachDevTools(){let{devTools:e}=this.options;if(e)(typeof e==="function"?e:Lz.devToolsAdapter)(this)}toJSON(){return{xstate$$type:Lu,id:this.id}}getPersistedSnapshot(e){return this.logic.getPersistedSnapshot(this._snapshot,e)}[Hz](){return this}getSnapshot(){if(!this._snapshot)throw Error("Snapshot can't be read while the actor initializes itself");return this._snapshot}}function Fu(e,...[t]){return new qu(e,t)}var Xz=Fu;function eU(e,t,n,o,{sendId:i}){let a=typeof i==="function"?i(n,o):i;return[t,{sendId:a},void 0]}function tU(e,t){e.defer(()=>{e.system.scheduler.cancel(e.self,t.sendId)})}function ow(e){function t(n,o){throw Error("This isn't supposed to be called")}return t.type="xstate.cancel",t.sendId=e,t.resolve=eU,t.execute=tU,t}function rU(e,t,n,o,{id:i,systemId:a,src:s,input:l,syncSnapshot:c}){let u=typeof s==="string"?tw(t.machine,s):s,d=typeof i==="function"?i(n):i,m,p=void 0;if(u)p=typeof l==="function"?l({context:t.context,event:n.event,self:e.self}):l,m=Fu(u,{id:d,src:s,parent:e.self,syncSnapshot:c,systemId:a,input:p});if(!m)console.warn(`Actor type '${s}' not found in machine '${e.id}'.`);return[qn(t,{children:{...t.children,[d]:m}}),{id:i,systemId:a,actorRef:m,src:s,input:p},void 0]}function nU(e,{actorRef:t}){if(!t)return;e.defer(()=>{if(t._processingStatus===Ht.Stopped)return;t.start()})}function iw(...[e,{id:t,systemId:n,input:o,syncSnapshot:i=!1}={}]){function a(s,l){throw Error("This isn't supposed to be called")}return a.type="xstate.spawnChild",a.id=t,a.systemId=n,a.src=e,a.input=o,a.syncSnapshot=i,a.resolve=rU,a.execute=nU,a}function oU(e,t,n,o,{actorRef:i}){let a=typeof i==="function"?i(n,o):i,s=typeof a==="string"?t.children[a]:a,l=t.children;if(s)l={...l},delete l[s.id];return[qn(t,{children:l}),s,void 0]}function aw(e,t){let n=t.getSnapshot();if(n&&"children"in n)for(let o of Object.values(n.children))aw(e,o);e.system._unregister(t)}function iU(e,t){if(!t)return;if(aw(e,t),t._processingStatus!==Ht.Running){e.stopChild(t);return}e.defer(()=>{e.stopChild(t)})}function cs(e){function t(n,o){throw Error("This isn't supposed to be called")}return t.type="xstate.stopChild",t.actorRef=e,t.resolve=oU,t.execute=iU,t}var aU=cs;function sU(e,t,{stateValue:n}){if(typeof n==="string"&&Hi(n)){let o=e.machine.getStateNodeById(n);return e._nodes.some((i)=>i===o)}return e.matches(n)}function lU(e){function t(){throw Error("This isn't supposed to be called")}return t.check=sU,t.stateValue=e,t}function cU(e,{context:t,event:n},{guards:o}){return!Ro(o[0],t,n,e)}function uU(e){function t(n,o){throw Error("This isn't supposed to be called")}return t.check=cU,t.guards=[e],t}function dU(e,{context:t,event:n},{guards:o}){return o.every((i)=>Ro(i,t,n,e))}function sw(e){function t(n,o){throw Error("This isn't supposed to be called")}return t.check=dU,t.guards=e,t}function pU(e,{context:t,event:n},{guards:o}){return o.some((i)=>Ro(i,t,n,e))}function mU(e){function t(n,o){throw Error("This isn't supposed to be called")}return t.check=pU,t.guards=e,t}function Ro(e,t,n,o){let{machine:i}=o,a=typeof e==="function",s=a?e:i.implementations.guards[typeof e==="string"?e:e.type];if(!a&&!s)throw Error(`Guard '${typeof e==="string"?e:e.type}' is not implemented.'.`);if(typeof s!=="function")return Ro(s,t,n,o);let l={context:t,event:n},c=a||typeof e==="string"?void 0:("params"in e)?typeof e.params==="function"?e.params({context:t,event:n}):e.params:void 0;if(!("check"in s))return s(l,c);return s.check(o,l,s)}function us(e){return e.type==="atomic"||e.type==="final"}function Io(e){return Object.values(e.states).filter((t)=>t.type!=="history")}function Eo(e,t){let n=[];if(t===e)return n;let o=e.parent;while(o&&o!==t)n.push(o),o=o.parent;return n}function Bu(e){let t=new Set(e),n=cw(t);for(let o of t)if(o.type==="compound"&&(!n.get(o)||!n.get(o).length))BS(o).forEach((i)=>t.add(i));else if(o.type==="parallel")for(let i of Io(o)){if(i.type==="history")continue;if(!t.has(i)){let a=BS(i);for(let s of a)t.add(s)}}for(let o of t){let i=o.parent;while(i)t.add(i),i=i.parent}return t}function lw(e,t){let n=t.get(e);if(!n)return{};if(e.type==="compound"){let i=n[0];if(i){if(us(i))return i.key}else return{}}let o={};for(let i of n)o[i.key]=lw(i,t);return o}function cw(e){let t=new Map;for(let n of e){if(!t.has(n))t.set(n,[]);if(n.parent){if(!t.has(n.parent))t.set(n.parent,[]);t.get(n.parent).push(n)}}return t}function uw(e,t){let n=Bu(t);return lw(e,cw(n))}function Gu(e,t){if(t.type==="compound")return Io(t).some((n)=>n.type==="final"&&e.has(n));if(t.type==="parallel")return Io(t).every((n)=>Gu(e,n));return t.type==="final"}var Hi=(e)=>e[0]===Fz;function gU(e,t){let n=e.transitions.get(t),o=[...e.transitions.keys()].filter((i)=>i!==t&&rw(t,i)).sort((i,a)=>a.length-i.length).flatMap((i)=>e.transitions.get(i));return n?[...n,...o]:o}function fU(e){let t=e.config.after;if(!t)return[];let n=(i)=>{let a=Gz(i,e.id),s=a.type;return e.entry.push(_w(a,{id:s,delay:i})),e.exit.push(ow(s)),s};return Object.keys(t).flatMap((i)=>{let a=t[i],s=typeof a==="string"?{target:a}:a,l=Number.isNaN(+i)?i:+i,c=n(l);return Ji(s).map((u)=>({...u,event:c,delay:l}))}).map((i)=>{let{delay:a}=i;return{...hn(e,i.event,i),delay:a}})}function hn(e,t,n){let o=ew(n.target),i=n.reenter??!1,a=bU(e,o);if(n.cond)throw Error(`State "${e.id}" has declared \`cond\` for one of its transitions. This property has been renamed to \`guard\`. Please update your code.`);let s={...n,actions:Ji(n.actions),guard:n.guard,target:a,source:e,reenter:i,eventType:t,toJSON:()=>({...s,source:`#${e.id}`,target:a?a.map((l)=>`#${l.id}`):void 0})};return s}function hU(e){let t=new Map;if(e.config.on)for(let n of Object.keys(e.config.on)){if(n===WS)throw Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');let o=e.config.on[n];t.set(n,xo(o).map((i)=>hn(e,n,i)))}if(e.config.onDone){let n=`xstate.done.state.${e.id}`;t.set(n,xo(e.config.onDone).map((o)=>hn(e,n,o)))}for(let n of e.invoke){if(n.onDone){let o=`xstate.done.actor.${n.id}`;t.set(o,xo(n.onDone).map((i)=>hn(e,o,i)))}if(n.onError){let o=`xstate.error.actor.${n.id}`;t.set(o,xo(n.onError).map((i)=>hn(e,o,i)))}if(n.onSnapshot){let o=`xstate.snapshot.${n.id}`;t.set(o,xo(n.onSnapshot).map((i)=>hn(e,o,i)))}}for(let n of e.after){let o=t.get(n.eventType);if(!o)o=[],t.set(n.eventType,o);o.push(n)}return t}function yU(e){let t=[],n=(o)=>{Object.values(o).forEach((i)=>{if(i.config.route&&i.config.id){let a=i.config.id,s=i.config.route.guard,l=({event:u})=>u.to===`#${a}`,c={...i.config.route,guard:s?sw([l,s]):l,target:`#${a}`};t.push(hn(e,"xstate.route",c))}if(i.states)n(i.states)})};if(n(e.states),t.length>0)e.transitions.set("xstate.route",t)}function vU(e,t){let n=typeof t==="string"?e.states[t]:t?e.states[t.target]:void 0;if(!n&&t)throw Error(`Initial state node "${t}" not found on parent state node #${e.id}`);let o={source:e,actions:!t||typeof t==="string"?[]:Ji(t.actions),eventType:null,reenter:!1,target:n?[n]:[],toJSON:()=>({...o,source:`#${e.id}`,target:n?[`#${n.id}`]:[]})};return o}function bU(e,t){if(t===void 0)return;return t.map((n)=>{if(typeof n!=="string")return n;if(Hi(n))return e.machine.getStateNodeById(n);let o=n[0]===HS;if(o&&!e.parent)return ls(e,n.slice(1));let i=o?e.key+n:n;if(e.parent)try{return ls(e.parent,i)}catch(a){throw Error(`Invalid transition definition for state node '${e.id}':
7
+ ${a.message}`)}else throw Error(`Invalid target: "${n}" is not a valid target from the root node. Did you mean ".${n}"?`)})}function dw(e){let t=ew(e.config.target);if(!t){if(e.parent.type==="parallel")return{target:[e.parent]};return e.parent.initial}return{target:t.map((n)=>typeof n==="string"?ls(e.parent,n):n)}}function Ln(e){return e.type==="history"}function BS(e){let t=pw(e);for(let n of t)for(let o of Eo(n,e))t.add(o);return t}function pw(e){let t=new Set;function n(o){if(t.has(o))return;if(t.add(o),o.type==="compound")n(o.initial.target[0]);else if(o.type==="parallel")for(let i of Io(o))n(i)}return n(e),t}function Co(e,t){if(Hi(t))return e.machine.getStateNodeById(t);if(!e.states)throw Error(`Unable to retrieve child state '${t}' from '${e.id}'; no child states exist.`);let n=e.states[t];if(!n)throw Error(`Child state '${t}' does not exist on '${e.id}'`);return n}function ls(e,t){if(typeof t==="string"&&Hi(t))try{return e.machine.getStateNodeById(t)}catch{}let n=$u(t).slice(),o=e;while(n.length){let i=n.shift();if(!i.length)break;o=Co(o,i)}return o}function Ju(e,t){if(typeof t==="string"){let i=e.states[t];if(!i)throw Error(`State '${t}' does not exist on '${e.id}'`);return[e,i]}let n=Object.keys(t),o=n.map((i)=>Co(e,i)).filter(Boolean);return[e.machine.root,e].concat(o,n.reduce((i,a)=>{let s=Co(e,a);if(!s)return i;let l=Ju(s,t[a]);return i.concat(l)},[]))}function _U(e,t,n,o){let a=Co(e,t).next(n,o);if(!a||!a.length)return e.next(n,o);return a}function SU(e,t,n,o){let i=Object.keys(t),a=Co(e,i[0]),s=Hu(a,t[i[0]],n,o);if(!s||!s.length)return e.next(n,o);return s}function wU(e,t,n,o){let i=[];for(let a of Object.keys(t)){let s=t[a];if(!s)continue;let l=Co(e,a),c=Hu(l,s,n,o);if(c)i.push(...c)}if(!i.length)return e.next(n,o);return i}function Hu(e,t,n,o){if(typeof t==="string")return _U(e,t,n,o);if(Object.keys(t).length===1)return SU(e,t,n,o);return wU(e,t,n,o)}function xU(e){return Object.keys(e.states).map((t)=>e.states[t]).filter((t)=>t.type==="history")}function yn(e,t){let n=e;while(n.parent&&n.parent!==t)n=n.parent;return n.parent===t}function TU(e,t){let n=new Set(e),o=new Set(t);for(let i of n)if(o.has(i))return!0;for(let i of o)if(n.has(i))return!0;return!1}function mw(e,t,n){let o=new Set;for(let i of e){let a=!1,s=new Set;for(let l of o)if(TU(Du([i],t,n),Du([l],t,n)))if(yn(i.source,l.source))s.add(l);else{a=!0;break}if(!a){for(let l of s)o.delete(l);o.add(i)}}return Array.from(o)}function IU(e){let[t,...n]=e;for(let o of Eo(t,void 0))if(n.every((i)=>yn(i,o)))return o}function Wu(e,t){if(!e.target)return[];let n=new Set;for(let o of e.target)if(Ln(o))if(t[o.id])for(let i of t[o.id])n.add(i);else for(let i of Wu(dw(o),t))n.add(i);else n.add(o);return[...n]}function gw(e,t){let n=Wu(e,t);if(!n)return;if(!e.reenter&&n.every((i)=>i===e.source||yn(i,e.source)))return e.source;let o=IU(n.concat(e.source));if(o)return o;if(e.reenter)return;return e.source.machine.root}function Du(e,t,n){let o=new Set;for(let i of e)if(i.target?.length){let a=gw(i,n);if(i.reenter&&i.source===a)o.add(a);for(let s of t)if(yn(s,a))o.add(s)}return[...o]}function CU(e,t){if(e.length!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function kU(e,t,n,o,i){return zu([{target:[...pw(e)],source:e,reenter:!0,actions:[],eventType:null,toJSON:null}],t,n,o,!0,i)}function zu(e,t,n,o,i,a){let s=[];if(!e.length)return[t,s];let l=n.actionExecutor;n.actionExecutor=(c)=>{s.push(c),l(c)};try{let c=new Set(t._nodes),u=t.historyValue,d=mw(e,c,u),m=t;if(!i)[m,u]=PU(m,o,n,d,c,u,a,n.actionExecutor);m=ko(m,o,n,d.flatMap((f)=>f.actions),a,void 0),m=EU(m,o,n,d,c,a,u,i);let p=[...c];if(m.status==="done")m=ko(m,o,n,p.sort((f,g)=>g.order-f.order).flatMap((f)=>f.exit),a,void 0);try{if(u===t.historyValue&&CU(t._nodes,c))return[m,s];return[qn(m,{_nodes:p,historyValue:u}),s]}catch(f){throw f}}finally{n.actionExecutor=l}}function RU(e,t,n,o,i){if(o.output===void 0)return;let a=Ou(i.id,i.output!==void 0&&i.parent?Nu(i.output,e.context,t,n.self):void 0);return Nu(o.output,e.context,a,n.self)}function EU(e,t,n,o,i,a,s,l){let c=e,u=new Set,d=new Set;if(AU(o,s,d,u),l)d.add(e.machine.root);let m=new Set;for(let p of[...u].sort((f,g)=>f.order-g.order)){i.add(p);let f=[];f.push(...p.entry);for(let g of p.invoke)f.push(iw(g.src,{...g,syncSnapshot:!!g.onSnapshot}));if(d.has(p)){let g=p.initial.actions;f.push(...g)}if(c=ko(c,t,n,f,a,p.invoke.map((g)=>g.id)),p.type==="final"){let g=p.parent,h=g?.type==="parallel"?g:g?.parent,v=h||p;if(g?.type==="compound")a.push(Ou(g.id,p.output!==void 0?Nu(p.output,c.context,t,n.self):void 0));while(h?.type==="parallel"&&!m.has(h)&&Gu(i,h))m.add(h),a.push(Ou(h.id)),v=h,h=h.parent;if(h)continue;c=qn(c,{status:"done",output:RU(c,t,n,c.machine.root,v)})}}return c}function AU(e,t,n,o){for(let i of e){let a=gw(i,t);for(let l of i.target||[]){if(!Ln(l)&&(i.source!==l||i.source!==a||i.reenter))o.add(l),n.add(l);To(l,t,n,o)}let s=Wu(i,t);for(let l of s){let c=Eo(l,a);if(a?.type==="parallel")c.push(a);fw(o,t,n,c,!i.source.parent&&i.reenter?void 0:a)}}}function To(e,t,n,o){if(Ln(e))if(t[e.id]){let i=t[e.id];for(let a of i)o.add(a),To(a,t,n,o);for(let a of i)Pu(a,e.parent,o,t,n)}else{let i=dw(e);for(let a of i.target){if(o.add(a),i===e.parent?.initial)n.add(e.parent);To(a,t,n,o)}for(let a of i.target)Pu(a,e.parent,o,t,n)}else if(e.type==="compound"){let[i]=e.initial.target;if(!Ln(i))o.add(i),n.add(i);To(i,t,n,o),Pu(i,e,o,t,n)}else if(e.type==="parallel"){for(let i of Io(e).filter((a)=>!Ln(a)))if(![...o].some((a)=>yn(a,i))){if(!Ln(i))o.add(i),n.add(i);To(i,t,n,o)}}}function fw(e,t,n,o,i){for(let a of o){if(!i||yn(a,i))e.add(a);if(a.type==="parallel"){for(let s of Io(a).filter((l)=>!Ln(l)))if(![...e].some((l)=>yn(l,s)))e.add(s),To(s,t,n,e)}}}function Pu(e,t,n,o,i){fw(n,o,i,Eo(e,t))}function PU(e,t,n,o,i,a,s,l){let c=e,u=Du(o,i,a);u.sort((m,p)=>p.order-m.order);let d;for(let m of u)for(let p of xU(m)){let f;if(p.history==="deep")f=(g)=>us(g)&&yn(g,m);else f=(g)=>g.parent===m;d??={...a},d[p.id]=Array.from(i).filter(f)}for(let m of u)c=ko(c,t,n,[...m.exit,...m.invoke.map((p)=>cs(p.id))],s,void 0),i.delete(m);return[c,d||a]}function MU(e,t){return e.implementations.actions[t]}function hw(e,t,n,o,i,a){let{machine:s}=e,l=e;for(let c of o){let u=typeof c==="function",d=u?c:MU(s,typeof c==="string"?c:c.type),m={context:l.context,event:t,self:n.self,system:n.system},p=u||typeof c==="string"?void 0:("params"in c)?typeof c.params==="function"?c.params({context:l.context,event:t}):c.params:void 0;if(!d||!("resolve"in d)){n.actionExecutor({type:typeof c==="string"?c:typeof c==="object"?c.type:c.name||"(anonymous)",info:m,params:p,exec:d});continue}let f=d,[g,h,v]=f.resolve(n,l,m,p,d,i);if(l=g,"retryResolve"in f)a?.push([f,h]);if("execute"in f)n.actionExecutor({type:f.type,info:m,params:h,exec:f.execute.bind(null,n,h)});if(v)l=hw(l,t,n,v,i,a)}return l}function ko(e,t,n,o,i,a){let s=a?[]:void 0,l=hw(e,t,n,o,{internalQueue:i,deferredActorIds:a},s);return s?.forEach(([c,u])=>{c.retryResolve(n,l,u)}),l}function jU(e,t,n,o){if(t.type===ju)throw Error(`An event cannot have the wildcard type ('${ju}')`);let i=e,a=[];function s(m,p,f){n.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:n.self,event:p,snapshot:m[0],_transitions:f}),a.push(m)}if(t.type===ss)return i=qn(GS(i,t,n),{status:"stopped"}),s([i,[]],t,[]),{snapshot:i,microsteps:a};let l=t;if(l.type!==VS){let m=l,p=Vz(m),f=JS(m,i);if(p&&!f.length)return i=qn(e,{status:"error",error:m.error}),s([i,[]],m,[]),{snapshot:i,microsteps:a};let g=zu(f,e,n,l,!1,o);i=g[0],s(g,m,f)}let c=!0,u=e.machine.options?.maxIterations??1/0,d=0;while(i.status==="active"){if(d++,d>u)throw Error(`Infinite loop detected: the machine has processed more than ${u} microsteps without reaching a stable state. This usually happens when there's a cycle of transitions (e.g., eventless transitions or raised events causing state A -> B -> C -> A).`);let m=c?OU(i,l):[],p=m.length?i:void 0;if(!m.length){if(!o.length)break;l=o.shift(),m=JS(l,i)}let f=zu(m,i,n,l,!1,o);i=f[0],c=i!==p,s(f,l,m)}if(i.status!=="active")GS(i,l,n);return{snapshot:i,microsteps:a}}function GS(e,t,n){return ko(e,t,n,Object.values(e.children).map((o)=>cs(o)),[],void 0)}function JS(e,t){return t.machine.getTransitionData(t,e)}function OU(e,t){let n=new Set,o=e._nodes.filter(us);for(let i of o)e:for(let a of[i].concat(Eo(i,void 0))){if(!a.always)continue;for(let s of a.always)if(s.guard===void 0||Ro(s.guard,e.context,t,e)){n.add(s);break e}}return mw(Array.from(n),new Set(e._nodes),e.historyValue)}function NU(e,t){let n=Bu(Ju(e,t));return uw(e,[...n])}function yw(e){return!!e&&typeof e==="object"&&"machine"in e&&"value"in e}var DU=function(t){return Uu(t,this.value)},zU=function(t){return this.tags.has(t)},UU=function(t){if(!this.machine)console.warn("state.can(...) used outside of a machine-created State object; this will always return false.");let n=this.machine.getTransitionData(this,t);return!!n?.length&&n.some((o)=>o.target!==void 0||o.actions.length)},$U=function(){let{_nodes:t,tags:n,machine:o,getMeta:i,toJSON:a,can:s,hasTag:l,matches:c,...u}=this;return{...u,tags:Array.from(n)}},LU=function(){return this._nodes.reduce((t,n)=>{if(n.meta!==void 0)t[n.id]=n.meta;return t},{})};function vw(e,t){return{status:e.status,output:e.output,error:e.error,machine:t,context:e.context,_nodes:e._nodes,value:uw(t.root,e._nodes),tags:new Set(e._nodes.flatMap((n)=>n.tags)),children:e.children,historyValue:e.historyValue||{},matches:DU,hasTag:zU,can:UU,getMeta:LU,toJSON:$U}}function qn(e,t={}){return vw({...e,...t},e.machine)}function qU(e){if(typeof e!=="object"||e===null)return{};let t={};for(let n in e){let o=e[n];if(Array.isArray(o))t[n]=o.map((i)=>({id:i.id}))}return t}function FU(e,t){let{_nodes:n,tags:o,machine:i,children:a,context:s,can:l,hasTag:c,matches:u,getMeta:d,toJSON:m,...p}=e,f={};for(let h in a){let v=a[h];if(typeof v.src!=="string"&&(!t||!("__unsafeAllowInlineActors"in t)))throw Error("An inline child actor cannot be persisted.");f[h]={snapshot:v.getPersistedSnapshot(t),src:v.src,systemId:v.systemId,syncSnapshot:v._syncSnapshot}}return{...p,context:bw(s),children:f,historyValue:qU(p.historyValue)}}function bw(e){let t;for(let n in e){let o=e[n];if(o&&typeof o==="object")if("sessionId"in o&&"send"in o&&"ref"in o)t??=Array.isArray(e)?e.slice():{...e},t[n]={xstate$$type:Lu,id:o.id};else{let i=bw(o);if(i!==o)t??=Array.isArray(e)?e.slice():{...e},t[n]=i}}return t??e}function BU(e,t,n,o,{event:i,id:a,delay:s},{internalQueue:l}){let c=t.machine.implementations.delays;if(typeof i==="string")throw Error(`Only event objects may be used with raise; use raise({ type: "${i}" }) instead`);let u=typeof i==="function"?i(n,o):i,d;if(typeof s==="string"){let m=c&&c[s];d=typeof m==="function"?m(n,o):m}else d=typeof s==="function"?s(n,o):s;if(typeof d!=="number")l.push(u);return[t,{event:u,id:a,delay:d},void 0]}function GU(e,t){let{event:n,delay:o,id:i}=t;if(typeof o==="number"){e.defer(()=>{let a=e.self;e.system.scheduler.schedule(a,a,n,o,i)});return}}function _w(e,t){if(JU.executingCustomAction)console.warn("Custom actions should not call `raise()` directly, as it is not imperative. See https://stately.ai/docs/actions#built-in-actions for more details.");function n(o,i){throw Error("This isn't supposed to be called")}return n.type="xstate.raise",n.event=e,n.id=t?.id,n.delay=t?.delay,n.resolve=BU,n.execute=GU,n}JU.$$ACTOR_TYPE=Lu;JU.Actor=qu;JU.NULL_EVENT=WS;JU.ProcessingStatus=Ht;JU.STATE_DELIMITER=HS;JU.XSTATE_ERROR=Bz;JU.XSTATE_STOP=ss;JU.and=sw;JU.cancel=ow;JU.cloneMachineSnapshot=qn;JU.createActor=Fu;JU.createErrorActorEvent=ZS;JU.createInitEvent=KS;JU.createInvokeId=Zz;JU.createMachineSnapshot=vw;JU.createSystem=nw;JU.evaluateGuard=Ro;JU.formatInitialTransition=vU;JU.formatRouteTransitions=yU;JU.formatTransition=hn;JU.formatTransitions=hU;JU.getAllOwnEventDescriptors=Kz;JU.getAllStateNodes=Bu;JU.getCandidates=gU;JU.getDelayedTransitions=fU;JU.getPersistedSnapshot=FU;JU.getProperAncestors=Eo;JU.getStateNodeByPath=ls;JU.getStateNodes=Ju;JU.initialMicrostep=kU;JU.interpret=Xz;JU.isAtomicStateNode=us;JU.isInFinalState=Gu;JU.isMachineSnapshot=yw;JU.isStateId=Hi;JU.macrostep=jU;JU.mapValues=Wz;JU.matchesEventDescriptor=rw;JU.matchesState=Uu;JU.not=uU;JU.or=mU;JU.pathToStateValue=YS;JU.raise=_w;JU.resolveActionsAndContext=ko;JU.resolveReferencedActor=tw;JU.resolveStateValue=NU;JU.spawnChild=iw;JU.stateIn=lU;JU.stop=aU;JU.stopChild=cs;JU.toArray=Ji;JU.toObserver=Bi;JU.toStatePath=$u;JU.toTransitionConfigArray=xo;JU.transitionNode=Hu});var Cw=ye(function(Iw){Object.defineProperty(Iw,"__esModule",{value:!0});var Vi=Ao();as();function Tw(e,t){return{config:e,transition:(n,o,i)=>({...n,context:e(n.context,o,i)}),getInitialSnapshot:(n,o)=>({status:"active",output:void 0,error:void 0,context:typeof t==="function"?t({input:o}):t}),getPersistedSnapshot:(n)=>n,restoreSnapshot:(n)=>n}}var Vu=new WeakMap;function W$(e){return{config:e,start:(n,o)=>{let{self:i,system:a,emit:s}=o,l={receivers:void 0,dispose:void 0};Vu.set(i,l),l.dispose=e({input:n.input,system:a,self:i,sendBack:(c)=>{if(i.getSnapshot().status==="stopped")return;if(i._parent)a._relay(i,i._parent,c)},receive:(c)=>{l.receivers??=new Set,l.receivers.add(c)},emit:s})},transition:(n,o,i)=>{let a=Vu.get(i.self);if(o.type===Vi.XSTATE_STOP)return n={...n,status:"stopped",error:void 0},Vu.delete(i.self),a.receivers?.clear(),a.dispose?.(),n;return a.receivers?.forEach((s)=>s(o)),n},getInitialSnapshot:(n,o)=>({status:"active",output:void 0,error:void 0,input:o}),getPersistedSnapshot:(n)=>n,restoreSnapshot:(n)=>n}}var Sw="xstate.observable.next",ds="xstate.observable.error",ps="xstate.observable.complete";function V$(e){return{config:e,transition:(n,o)=>{if(n.status!=="active")return n;switch(o.type){case Sw:return{...n,context:o.data};case ds:return{...n,status:"error",error:o.data,input:void 0,_subscription:void 0};case ps:return{...n,status:"done",input:void 0,_subscription:void 0};case Vi.XSTATE_STOP:return n._subscription.unsubscribe(),{...n,status:"stopped",input:void 0,_subscription:void 0};default:return n}},getInitialSnapshot:(n,o)=>({status:"active",output:void 0,error:void 0,context:void 0,input:o,_subscription:void 0}),start:(n,{self:o,system:i,emit:a})=>{if(n.status==="done")return;n._subscription=e({input:n.input,system:i,self:o,emit:a}).subscribe({next:(s)=>{i._relay(o,o,{type:Sw,data:s})},error:(s)=>{i._relay(o,o,{type:ds,data:s})},complete:()=>{i._relay(o,o,{type:ps})}})},getPersistedSnapshot:({_subscription:n,...o})=>o,restoreSnapshot:(n)=>({...n,_subscription:void 0})}}function Z$(e){return{config:e,transition:(n,o)=>{if(n.status!=="active")return n;switch(o.type){case ds:return{...n,status:"error",error:o.data,input:void 0,_subscription:void 0};case ps:return{...n,status:"done",input:void 0,_subscription:void 0};case Vi.XSTATE_STOP:return n._subscription.unsubscribe(),{...n,status:"stopped",input:void 0,_subscription:void 0};default:return n}},getInitialSnapshot:(n,o)=>({status:"active",output:void 0,error:void 0,context:void 0,input:o,_subscription:void 0}),start:(n,{self:o,system:i,emit:a})=>{if(n.status==="done")return;n._subscription=e({input:n.input,system:i,self:o,emit:a}).subscribe({next:(s)=>{if(o._parent)i._relay(o,o._parent,s)},error:(s)=>{i._relay(o,o,{type:ds,data:s})},complete:()=>{i._relay(o,o,{type:ps})}})},getPersistedSnapshot:({_subscription:n,...o})=>o,restoreSnapshot:(n)=>({...n,_subscription:void 0})}}var ww="xstate.promise.resolve",xw="xstate.promise.reject",Wi=new WeakMap;function K$(e){return{config:e,transition:(n,o,i)=>{if(n.status!=="active")return n;switch(o.type){case ww:{let a=o.data;return{...n,status:"done",output:a,input:void 0}}case xw:return{...n,status:"error",error:o.data,input:void 0};case Vi.XSTATE_STOP:return Wi.get(i.self)?.abort(),Wi.delete(i.self),{...n,status:"stopped",input:void 0};default:return n}},start:(n,{self:o,system:i,emit:a})=>{if(n.status!=="active")return;let s=new AbortController;Wi.set(o,s),Promise.resolve(e({input:n.input,system:i,self:o,signal:s.signal,emit:a})).then((c)=>{if(o.getSnapshot().status!=="active")return;Wi.delete(o),i._relay(o,o,{type:ww,data:c})},(c)=>{if(o.getSnapshot().status!=="active")return;Wi.delete(o),i._relay(o,o,{type:xw,data:c})})},getInitialSnapshot:(n,o)=>({status:"active",output:void 0,error:void 0,input:o}),getPersistedSnapshot:(n)=>n,restoreSnapshot:(n)=>n}}var Y$=Tw((e)=>{return},void 0);function Q$(){return Vi.createActor(Y$)}Iw.createEmptyActor=Q$;Iw.fromCallback=W$;Iw.fromEventObservable=Z$;Iw.fromObservable=V$;Iw.fromPromise=K$;Iw.fromTransition=Tw});var ms=ye(function(lL){var Po=Ao();function iL(e,{machine:t,context:n},o,i){let a=(s,l)=>{if(typeof s==="string"){let c=Po.resolveReferencedActor(t,s);if(!c)throw Error(`Actor logic '${s}' not implemented in machine '${t.id}'`);let u=Po.createActor(c,{id:l?.id,parent:e.self,syncSnapshot:l?.syncSnapshot,input:typeof l?.input==="function"?l.input({context:n,event:o,self:e.self}):l?.input,src:s,systemId:l?.systemId});return i[u.id]=u,u}else return Po.createActor(s,{id:l?.id,parent:e.self,syncSnapshot:l?.syncSnapshot,input:l?.input,src:s,systemId:l?.systemId})};return(s,l)=>{let c=a(s,l);return i[c.id]=c,e.defer(()=>{if(c._processingStatus===Po.ProcessingStatus.Stopped)return;c.start()}),c}}function aL(e,t,n,o,{assignment:i}){if(!t.context)throw Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");let a={},s={context:t.context,event:n.event,spawn:iL(e,t,n.event,a),self:e.self,system:e.system},l={};if(typeof i==="function")l=i(s,o);else for(let u of Object.keys(i)){let d=i[u];l[u]=typeof d==="function"?d(s,o):d}let c=Object.assign({},t.context,l);return[Po.cloneMachineSnapshot(t,{context:c,children:Object.keys(a).length?{...t.children,...a}:t.children}),void 0,void 0]}function sL(e){if(Po.executingCustomAction)console.warn("Custom actions should not call `assign()` directly, as it is not imperative. See https://stately.ai/docs/actions#built-in-actions for more details.");function t(n,o){throw Error("This isn't supposed to be called")}return t.type="xstate.assign",t.assignment=e,t.resolve=aL,t}lL.assign=sL});var Rw=ye(function(mL){var je=Ao(),uL=ms(),kw=new WeakMap;function Mo(e,t,n){let o=kw.get(e);if(!o)o={[t]:n()},kw.set(e,o);else if(!(t in o))o[t]=n();return o[t]}var dL={},Zi=(e)=>{if(typeof e==="string")return{type:e};if(typeof e==="function"){if("resolve"in e)return{type:e.type};return{type:e.name}}return e};class Ki{constructor(e,t){if(this.config=e,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=t._parent,this.key=t._key,this.machine=t._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(je.STATE_DELIMITER),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?je.mapValues(this.config.states,(n,o)=>new Ki(n,{_parent:this,_key:o,_machine:this.machine})):dL,this.type==="compound"&&!this.config.initial)throw Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);this.history=this.config.history===!0?"shallow":this.config.history||!1,this.entry=je.toArray(this.config.entry).slice(),this.exit=je.toArray(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=je.toArray(e.tags).slice()}_initialize(){if(this.transitions=je.formatTransitions(this),this.config.always)this.always=je.toTransitionConfigArray(this.config.always).map((e)=>je.formatTransition(this,je.NULL_EVENT,e));Object.keys(this.states).forEach((e)=>{this.states[e]._initialize()})}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(Zi),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map((e)=>`#${e.id}`),source:`#${this.id}`,actions:this.initial.actions.map(Zi),eventType:null})}:void 0,history:this.history,states:je.mapValues(this.states,(e)=>e.definition),on:this.on,transitions:[...this.transitions.values()].flat().map((e)=>({...e,actions:e.actions.map(Zi)})),entry:this.entry.map(Zi),exit:this.exit.map(Zi),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return Mo(this,"invoke",()=>je.toArray(this.config.invoke).map((e,t)=>{let{src:n,systemId:o}=e,i=e.id??je.createInvokeId(this.id,t),a=typeof n==="string"?n:`xstate.invoke.${je.createInvokeId(this.id,t)}`;return{...e,src:a,id:i,systemId:o,toJSON(){let{onDone:s,onError:l,...c}=e;return{...c,type:"xstate.invoke",src:a,id:i}}}}))}get on(){return Mo(this,"on",()=>[...this.transitions].flatMap(([t,n])=>n.map((o)=>[t,o])).reduce((t,[n,o])=>(t[n]=t[n]||[],t[n].push(o),t),{}))}get after(){return Mo(this,"delayedTransitions",()=>je.getDelayedTransitions(this))}get initial(){return Mo(this,"initial",()=>je.formatInitialTransition(this,this.config.initial))}next(e,t){let n=t.type,o=[],i,a=Mo(this,`candidates-${n}`,()=>je.getCandidates(this,n));for(let s of a){let{guard:l}=s,c=e.context,u=!1;try{u=!l||je.evaluateGuard(l,c,t,e)}catch(d){let m=typeof l==="string"?l:typeof l==="object"?l.type:void 0;throw Error(`Unable to evaluate guard ${m?`'${m}' `:""}in transition for event '${n}' in state node '${this.id}':
8
+ ${d.message}`)}if(u){o.push(...s.actions),i=s;break}}return i?[i]:void 0}get events(){return Mo(this,"events",()=>{let{states:e}=this,t=new Set(this.ownEvents);if(e)for(let n of Object.keys(e)){let o=e[n];if(o.states)for(let i of o.events)t.add(`${i}`)}return Array.from(t)})}get ownEvents(){let e=Object.keys(Object.fromEntries(this.transitions)),t=new Set(e.filter((n)=>this.transitions.get(n).some((o)=>!(!o.target&&!o.actions.length&&!o.reenter))));return Array.from(t)}}var pL="#";class Zu{constructor(e,t){if(this.config=e,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.options=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=e.id||"(machine)",this.implementations={actors:t?.actors??{},actions:t?.actions??{},delays:t?.delays??{},guards:t?.guards??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.options={maxIterations:1/0,...this.config.options},this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new Ki(e,{_key:this.id,_machine:this}),this.root._initialize(),je.formatRouteTransitions(this.root),this.states=this.root.states,this.events=this.root.events,!("output"in this.root)&&Object.values(this.states).some((n)=>n.type==="final"&&("output"in n)))console.warn("Missing `machine.output` declaration (top-level final state with output detected)")}provide(e){let{actions:t,guards:n,actors:o,delays:i}=this.implementations;return new Zu(this.config,{actions:{...t,...e.actions},guards:{...n,...e.guards},actors:{...o,...e.actors},delays:{...i,...e.delays}})}resolveState(e){let t=je.resolveStateValue(this.root,e.value),n=je.getAllStateNodes(je.getStateNodes(this.root,t));return je.createMachineSnapshot({_nodes:[...n],context:e.context||{},children:{},status:je.isInFinalState(n,this.root)?"done":e.status||"active",output:e.output,error:e.error,historyValue:e.historyValue},this)}transition(e,t,n){return je.macrostep(e,t,n,[]).snapshot}microstep(e,t,n){return je.macrostep(e,t,n,[]).microsteps.map(([o])=>o)}getTransitionData(e,t){return je.transitionNode(this.root,e.value,e,t)||[]}_getPreInitialState(e,t,n){let{context:o}=this.config,i=je.createMachineSnapshot({context:typeof o!=="function"&&o?o:{},_nodes:[this.root],children:{},status:"active"},this);if(typeof o==="function"){let a=({spawn:s,event:l,self:c})=>o({spawn:s,input:l.input,self:c});return je.resolveActionsAndContext(i,t,e,[uL.assign(a)],n,void 0)}return i}getInitialSnapshot(e,t){let n=je.createInitEvent(t),o=[],i=this._getPreInitialState(e,n,o),[a]=je.initialMicrostep(this.root,i,e,n,o),{snapshot:s}=je.macrostep(a,n,e,o);return s}start(e){Object.values(e.children).forEach((t)=>{if(t.getSnapshot().status==="active")t.start()})}getStateNodeById(e){let t=je.toStatePath(e),n=t.slice(1),o=je.isStateId(t[0])?t[0].slice(pL.length):t[0],i=this.idMap.get(o);if(!i)throw Error(`Child state node '#${o}' does not exist on machine '${this.id}'`);return je.getStateNodeByPath(i,n)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(e,t){return je.getPersistedSnapshot(e,t)}restoreSnapshot(e,t){let n={},o=e.children;Object.keys(o).forEach((d)=>{let m=o[d],p=m.snapshot,f=m.src,g=typeof f==="string"?je.resolveReferencedActor(this,f):f;if(!g)return;let h=je.createActor(g,{id:d,parent:t.self,syncSnapshot:m.syncSnapshot,snapshot:p,src:f,systemId:m.systemId});n[d]=h});function i(d,m){if(m instanceof Ki)return m;try{return d.machine.getStateNodeById(m.id)}catch{console.warn(`Could not resolve StateNode for id: ${m.id}`)}}function a(d,m){if(!m||typeof m!=="object")return{};let p={};for(let f in m){let g=m[f];for(let h of g){let v=i(d,h);if(!v)continue;p[f]??=[],p[f].push(v)}}return p}let s=a(this.root,e.historyValue),l=je.createMachineSnapshot({...e,children:n,_nodes:Array.from(je.getAllStateNodes(je.getStateNodes(this.root,e.value))),historyValue:s},this),c=new Set;function u(d,m){if(c.has(d))return;c.add(d);for(let p in d){let f=d[p];if(f&&typeof f==="object"){if("xstate$$type"in f&&f.xstate$$type===je.$$ACTOR_TYPE){d[p]=m[f.id];continue}u(f,m)}}}return u(l.context,n),l}}mL.StateMachine=Zu;mL.StateNode=Ki});var Pw=ye(function(RL){var Yr=Ao(),hL=ms();function yL(e,t,n,o,{event:i}){let a=typeof i==="function"?i(n,o):i;return[t,{event:a},void 0]}function vL(e,{event:t}){e.defer(()=>e.emit(t))}function Ew(e){if(Yr.executingCustomAction)console.warn("Custom actions should not call `emit()` directly, as it is not imperative. See https://stately.ai/docs/actions#built-in-actions for more details.");function t(n,o){throw Error("This isn't supposed to be called")}return t.type="xstate.emit",t.event=e,t.resolve=yL,t.execute=vL,t}var gs=function(e){return e.Parent="#_parent",e.Internal="#_internal",e}({});function bL(e,t,n,o,{to:i,event:a,id:s,delay:l},c){let u=t.machine.implementations.delays;if(typeof a==="string")throw Error(`Only event objects may be used with sendTo; use sendTo({ type: "${a}" }) instead`);let d=typeof a==="function"?a(n,o):a,m;if(typeof l==="string"){let g=u&&u[l];m=typeof g==="function"?g(n,o):g}else m=typeof l==="function"?l(n,o):l;let p=typeof i==="function"?i(n,o):i,f;if(typeof p==="string"){if(p===gs.Parent)f=e.self._parent;else if(p===gs.Internal)f=e.self;else if(p.startsWith("#_"))f=t.children[p.slice(2)];else f=c.deferredActorIds?.includes(p)?p:t.children[p];if(!f)throw Error(`Unable to send event to actor '${p}' from machine '${t.machine.id}'.`)}else f=p||e.self;return[t,{to:f,targetId:typeof p==="string"?p:void 0,event:d,id:s,delay:m},void 0]}function _L(e,t,n){if(typeof n.to==="string")n.to=t.children[n.to]}function SL(e,t){e.defer(()=>{let{to:n,event:o,delay:i,id:a}=t;if(typeof i==="number"){e.system.scheduler.schedule(e.self,n,o,i,a);return}e.system._relay(e.self,n,o.type===Yr.XSTATE_ERROR?Yr.createErrorActorEvent(e.self.id,o.data):o)})}function fs(e,t,n){if(Yr.executingCustomAction)console.warn("Custom actions should not call `sendTo()` directly, as it is not imperative. See https://stately.ai/docs/actions#built-in-actions for more details.");function o(i,a){throw Error("This isn't supposed to be called")}return o.type="xstate.sendTo",o.to=e,o.event=t,o.id=n?.id,o.delay=n?.delay,o.resolve=bL,o.retryResolve=_L,o.execute=SL,o}function Aw(e,t){return fs(gs.Parent,e,t)}function wL(e,t){if(!e||typeof e==="function"){let n=e;e=(...o)=>{let i=typeof n==="function"?n(...o):n;if(!i)throw Error("Attempted to forward event to undefined actor. This risks an infinite loop in the sender.");return i}}return fs(e,({event:n})=>n,t)}function xL(e,t,n,o,{collect:i}){let a=[],s=function(c){a.push(c)};return s.assign=(...l)=>{a.push(hL.assign(...l))},s.cancel=(...l)=>{a.push(Yr.cancel(...l))},s.raise=(...l)=>{a.push(Yr.raise(...l))},s.sendTo=(...l)=>{a.push(fs(...l))},s.sendParent=(...l)=>{a.push(Aw(...l))},s.spawnChild=(...l)=>{a.push(Yr.spawnChild(...l))},s.stopChild=(...l)=>{a.push(Yr.stopChild(...l))},s.emit=(...l)=>{a.push(Ew(...l))},i({context:n.context,event:n.event,enqueue:s,check:(l)=>Yr.evaluateGuard(l,t.context,n.event,t),self:e.self,system:e.system},o),[t,void 0,a]}function TL(e){function t(n,o){throw Error("This isn't supposed to be called")}return t.type="xstate.enqueueActions",t.collect=e,t.resolve=xL,t}function IL(e,t,n,o,{value:i,label:a}){return[t,{value:typeof i==="function"?i(n,o):i,label:a},void 0]}function CL({logger:e},{value:t,label:n}){if(n)e(n,t);else e(t)}function kL(e=({context:n,event:o})=>({context:n,event:o}),t){function n(o,i){throw Error("This isn't supposed to be called")}return n.type="xstate.log",n.value=e,n.label=t,n.resolve=IL,n.execute=CL,n}RL.SpecialTargets=gs;RL.emit=Ew;RL.enqueueActions=TL;RL.forwardTo=wL;RL.log=kL;RL.sendParent=Aw;RL.sendTo=fs});var zw=ye(function(Dw){Object.defineProperty(Dw,"__esModule",{value:!0});var jo=Cw(),He=Ao(),Ku=Rw(),Mw=ms(),hr=Pw();as();function DL(e,t){let n=He.toArray(t);if(!n.some((i)=>He.matchesEventDescriptor(e.type,i))){let i=n.length===1?`type matching "${n[0]}"`:`one of types matching "${n.join('", "')}"`;throw Error(`Expected event ${JSON.stringify(e)} to have ${i}`)}}function jw(e,t){return new Ku.StateMachine(e,t)}function zL(e,t){let n=[],o=(a,s)=>{let l=a;for(let c of s){if(!l?.states)return;let u=l.states;if(!(c in u))return;l=u[c]}return l},i=new Set;for(let a of e._nodes.filter(He.isAtomicStateNode)){let s=a;while(s&&!i.has(s)){i.add(s);let l=o(t,s.path);if(l?.map)n.push({stateNode:s,result:l.map(e)});s=s.parent}}return n}function Oo(e){let t=He.createActor(e),n=He.createSystem(t,{clock:t.system._clock,logger:t.system._logger});return t.system=n,{self:t,defer:()=>{},id:"",logger:()=>{},sessionId:"",stopChild:()=>{},system:n,emit:()=>{},actionExecutor:()=>{}}}function UL(e,...[t]){let n=Oo(e);return e.getInitialSnapshot(n,t)}function $L(e,t,n){let o=Oo(e);return o.self._snapshot=t,e.transition(t,n,o)}function Ow({schemas:e,actors:t,actions:n,guards:o,delays:i}){return{assign:Mw.assign,sendTo:hr.sendTo,raise:He.raise,log:hr.log,cancel:He.cancel,stopChild:He.stopChild,enqueueActions:hr.enqueueActions,emit:hr.emit,spawnChild:He.spawnChild,createStateConfig:(a)=>a,createAction:(a)=>a,createMachine:(a)=>jw({...a,schemas:e},{actors:t,actions:n,guards:o,delays:i}),extend:(a)=>Ow({schemas:e,actors:t,actions:{...n,...a.actions},guards:{...o,...a.guards},delays:{...i,...a.delays}})}}class Nw{constructor(){this.timeouts=new Map,this._now=0,this._id=0,this._flushing=!1,this._flushingInvalidated=!1}now(){return this._now}getId(){return this._id++}setTimeout(e,t){this._flushingInvalidated=this._flushing;let n=this.getId();return this.timeouts.set(n,{start:this.now(),timeout:t,fn:e}),n}clearTimeout(e){this._flushingInvalidated=this._flushing,this.timeouts.delete(e)}set(e){if(this._now>e)throw Error("Unable to travel back in time");this._now=e,this.flushTimeouts()}flushTimeouts(){if(this._flushing){this._flushingInvalidated=!0;return}this._flushing=!0;let e=[...this.timeouts].sort(([t,n],[o,i])=>{let a=n.start+n.timeout;return i.start+i.timeout>a?-1:1});for(let[t,n]of e){if(this._flushingInvalidated){this._flushingInvalidated=!1,this._flushing=!1,this.flushTimeouts();return}if(this.now()-n.start>=n.timeout)this.timeouts.delete(t),n.fn.call(null)}this._flushing=!1}increment(e){this._now+=e,this.flushTimeouts()}}function LL(e){return new Promise((t,n)=>{e.subscribe({complete:()=>{t(e.getSnapshot().output)},error:n})})}function qL(e,t,n){let o=[],i=Oo(e);return i.actionExecutor=(s)=>{o.push(s)},[e.transition(t,n,i),o]}function FL(e,...[t]){let n=[],o=Oo(e);return o.actionExecutor=(a)=>{n.push(a)},[e.getInitialSnapshot(o,t),n]}function BL(e,t,n){let o=Oo(e),{microsteps:i}=He.macrostep(t,n,o,[]);return i}function GL(e,...[t]){let n=Oo(e),o=He.createInitEvent(t),i=[],a=e._getPreInitialState(n,o,i),s=He.initialMicrostep(e.root,a,n,o,i),{microsteps:l}=He.macrostep(s[0],o,n,i);return[s,...l]}function JL(e){let t=[],n=e._nodes.filter(He.isAtomicStateNode),o=new Set;for(let i of n)for(let a of[i].concat(He.getProperAncestors(i,void 0))){if(o.has(a.id))continue;o.add(a.id);for(let[,s]of a.transitions)t.push(...s);if(a.always)t.push(...a.always)}return t}var HL={timeout:1/0};function WL(e,t,n){let o={...HL,...n};return new Promise((i,a)=>{let{signal:s}=o;if(s?.aborted){a(s.reason);return}let l=!1;if(o.timeout<0)console.error("`timeout` passed to `waitFor` is negative and it will reject its internal promise immediately.");let c=o.timeout===1/0?void 0:setTimeout(()=>{u(),a(Error(`Timeout of ${o.timeout} ms exceeded`))},o.timeout),u=()=>{if(clearTimeout(c),l=!0,p?.unsubscribe(),m)s.removeEventListener("abort",m)};function d(f){if(t(f))u(),i(f)}let m,p;if(d(e.getSnapshot()),l)return;if(s)m=()=>{u(),a(s.reason)},s.addEventListener("abort",m);if(p=e.subscribe({next:d,error:(f)=>{u(),a(f)},complete:()=>{u(),a(Error("Actor terminated without satisfying predicate"))}}),l)p.unsubscribe()})}Dw.createEmptyActor=jo.createEmptyActor;Dw.fromCallback=jo.fromCallback;Dw.fromEventObservable=jo.fromEventObservable;Dw.fromObservable=jo.fromObservable;Dw.fromPromise=jo.fromPromise;Dw.fromTransition=jo.fromTransition;Dw.Actor=He.Actor;Dw.__unsafe_getAllOwnEventDescriptors=He.getAllOwnEventDescriptors;Dw.and=He.and;Dw.cancel=He.cancel;Dw.createActor=He.createActor;Dw.getStateNodes=He.getStateNodes;Dw.interpret=He.interpret;Dw.isMachineSnapshot=He.isMachineSnapshot;Dw.matchesState=He.matchesState;Dw.not=He.not;Dw.or=He.or;Dw.pathToStateValue=He.pathToStateValue;Dw.raise=He.raise;Dw.spawnChild=He.spawnChild;Dw.stateIn=He.stateIn;Dw.stop=He.stop;Dw.stopChild=He.stopChild;Dw.toObserver=He.toObserver;Dw.StateMachine=Ku.StateMachine;Dw.StateNode=Ku.StateNode;Dw.assign=Mw.assign;Dw.SpecialTargets=hr.SpecialTargets;Dw.emit=hr.emit;Dw.enqueueActions=hr.enqueueActions;Dw.forwardTo=hr.forwardTo;Dw.log=hr.log;Dw.sendParent=hr.sendParent;Dw.sendTo=hr.sendTo;Dw.SimulatedClock=Nw;Dw.assertEvent=DL;Dw.createMachine=jw;Dw.getInitialMicrosteps=GL;Dw.getInitialSnapshot=UL;Dw.getMicrosteps=BL;Dw.getNextSnapshot=$L;Dw.getNextTransitions=JL;Dw.initialTransition=FL;Dw.mapState=zL;Dw.setup=Ow;Dw.toPromise=LL;Dw.transition=qL;Dw.waitFor=WL});function ol(e,t){let n=new Set(t.map((o)=>o.type));return e.byType.filter((o)=>(o.status==="pending"||o.status==="processing")&&!n.has(o.type))}function Ko(e,t){let n=e.workerSessions,o=n.active===0?"missing":n.stale>0?"stale":"active",i=e.duePending>0&&(e.oldestDuePendingAgeMs??0)>=120000&&e.totals.processing===0&&(e.latestClaimAgeMs===null||e.latestClaimAgeMs>=120000),a=[];if(o==="missing")a.push("No live worker session");else if(o==="stale")a.push(`${n.stale} stale worker session(s)`);if(i)a.push(`${e.duePending} due job(s) have remained unclaimed for at least 120000ms`);if(t){let s=ol(e,t).reduce((l,c)=>l+c.count,0);if(s>0)a.push(`${s} active job(s) have no declared executor`)}return{status:a.length===0?"operational":"degraded",reasons:a,worker:{state:o,activeSessions:n.active,staleSessions:n.stale,latestHeartbeatAgeMs:n.latestHeartbeatAgeMs},queue:{duePending:e.duePending,processing:e.totals.processing,oldestDuePendingAgeMs:e.oldestDuePendingAgeMs,latestClaimAgeMs:e.latestClaimAgeMs,stalled:i}}}async function bp(e){let{config:t,services:n,bootTime:o,endpoints:i,interactions:a}=e,[s,l,c,u]=await Promise.all([n.entityService.getEntityCounts(da("runtime app info reports operator-facing aggregate status")),n.entityService.countEmbeddings(),n.daemonRegistry.getStatuses(),n.jobQueueService.getDiagnostics()]),d=s.reduce((m,p)=>m+p.count,0);return{model:t.name||"brain-app",version:t.version||"1.0.0",uptime:Math.floor((Date.now()-o)/1000),entities:d,entityCounts:s,embeddings:l,backgroundWork:Ko(u,n.jobQueueService.getExecutionRegistrations()),ai:{model:t.ai.model,embeddingModel:"text-embedding-3-small"},daemons:c,endpoints:i(),interactions:a()}}import{readdir as _p,readFile as c0}from"fs/promises";var u0=10;async function d0(e="/proc"){let t=null;try{t=(await _p(`${e}/self/fd`)).length}catch{}try{let o=(await _p(e,{withFileTypes:!0})).filter((s)=>s.isDirectory()&&/^\d+$/.test(s.name)).map((s)=>s.name),i=0,a=0;return await Promise.all(o.map(async(s)=>{try{let l=await c0(`${e}/${s}/status`,"utf8");if(a++,/^State:\s+Z\b/m.test(l))i++}catch{}})),{fileDescriptors:t,processCount:a,zombieCount:i}}catch{return{fileDescriptors:t,processCount:null,zombieCount:null}}}function Sp(e,t,n){return t.status==="fulfilled"?{name:e,status:"healthy",message:n}:{name:e,status:"unhealthy",message:ke(t.reason)}}function p0(e){if(!e)return{name:"job-worker",status:"degraded",message:"Worker session state is unavailable"};let t=e.workerSessions,n=Ko(e).worker;if(n.state==="missing")return{name:"job-worker",status:"degraded",message:"No live worker session",details:{sessions:t}};if(n.state==="stale")return{name:"job-worker",status:"degraded",message:`${t.stale} stale worker session(s)`,details:{sessions:t}};return{name:"job-worker",status:"healthy",message:`${t.active} live worker session(s)`,details:{sessions:t}}}function m0(e){if(!e)return{name:"job-queue-progress",status:"degraded",message:"Queue progress state is unavailable"};let t=Ko(e).queue;return t.stalled?{name:"job-queue-progress",status:"degraded",message:`${t.duePending} due job(s) are not being claimed`,details:{queue:t}}:{name:"job-queue-progress",status:"healthy",message:"Due jobs are being claimed",details:{queue:t}}}function g0(e,t){if(!e||!t)return{name:"job-execution-inventory",status:"degraded",message:"Job execution inventory is unavailable"};let n=ol(e,t),o=n.reduce((i,a)=>i+a.count,0);return o===0?{name:"job-execution-inventory",status:"healthy",message:"Every active job type has a declared executor"}:{name:"job-execution-inventory",status:"degraded",message:`${o} active job(s) have no declared executor`,details:{jobs:n}}}function f0(e){if(!e)return{name:"attempt-leases",status:"degraded",message:"Lease state is unavailable"};return e.staleLeaseCount===0?{name:"attempt-leases",status:"healthy",message:"No stale processing leases"}:{name:"attempt-leases",status:"degraded",message:`${e.staleLeaseCount} processing lease(s) are stale`,details:{staleLeaseCount:e.staleLeaseCount}}}function h0(e){if(!e.initialized)return{name:"projection-circuits",status:"degraded",message:"Projection runtime supervisor is not initialized"};if(e.openCircuits.length===0)return{name:"projection-circuits",status:"healthy",message:"No projection circuits are open"};return{name:"projection-circuits",status:"degraded",message:`${e.openCircuits.length} projection circuit(s) open`,details:{circuits:e.openCircuits}}}async function y0(e){let t=e.entityService.getProjectionStore(),[n,o,i]=await Promise.all([t.getActiveWave(),t.getUnresolvedProjectionIncidentDiagnostics(u0),t.getProjectionBatchDiagnostics?.()??Promise.resolve({preparing:0,open:0,abandoned:0,expiredCallbackLeases:0,oldestActiveAgeMs:null,oldestProgressAgeMs:null})]);if(!n)return{waveId:null,batches:i,strandedRules:[],incidentCount:o.total,incidents:o.incidents};let s=(await t.listWaveRules(n.id)).filter((c)=>c.status==="queued"||c.status==="failed"),l=(await Promise.all(s.map(async(c)=>{let u=c.jobId?await e.jobQueueService.getStatus(c.jobId):null;if(c.status!=="failed"&&u&&(u.status==="pending"||u.status==="processing"))return null;return{ruleId:c.ruleId,jobId:c.jobId,jobStatus:u?.status??"missing"}}))).filter((c)=>c!==null);return{waveId:n.id,batches:i,strandedRules:l,incidentCount:o.total,incidents:o.incidents}}function v0(e){if(e.batches.abandoned>0)return{name:"projection-waves",status:"degraded",message:`${e.batches.abandoned} projection batch(es) await recovery`,details:{batches:e.batches}};if(e.batches.expiredCallbackLeases>0)return{name:"projection-waves",status:"degraded",message:"A callback projection batch lease has expired",details:{batches:e.batches}};if(e.incidentCount>0)return{name:"projection-waves",status:"degraded",message:`${e.incidentCount} unresolved terminal projection incident(s)`,details:{incidentCount:e.incidentCount,incidentsTruncated:e.incidentCount>e.incidents.length,incidents:e.incidents.map((t)=>({waveId:t.waveId,ruleId:t.ruleId,jobId:t.jobId,failureReason:t.failureReason,createdAt:t.createdAt}))}};if(!e.waveId)return{name:"projection-waves",status:"healthy",message:e.batches.open+e.batches.preparing>0?`${e.batches.open+e.batches.preparing} projection batch(es) active`:"No active projection wave",...e.batches.open+e.batches.preparing>0&&{details:{batches:e.batches}}};if(e.strandedRules.length===0)return{name:"projection-waves",status:"healthy",message:`Projection wave ${e.waveId} is progressing`};return{name:"projection-waves",status:"degraded",message:`Projection wave ${e.waveId} has ${e.strandedRules.length} stranded rule job(s)`,details:{waveId:e.waveId,strandedRules:e.strandedRules}}}function b0(e){let t=e.filter((n)=>n.status!=="running"||n.health?.status==="error");return t.length===0?{name:"daemons",status:"healthy",message:`${e.length} daemon(s) healthy`}:{name:"daemons",status:"degraded",message:`${t.length} daemon(s) unhealthy`,details:{daemons:t.map((n)=>({name:n.name,status:n.status,health:n.health?.status,message:n.health?.message}))}}}async function wp(e){let t=e.now?.()??Date.now(),n=(e.memoryUsage??process.memoryUsage)(),[o,i,a,s,l,c,u,d]=await Promise.allSettled([e.entityService.getEntityCounts(da("runtime readiness database probe")),e.jobQueueService.getDiagnostics(t),Promise.resolve().then(()=>e.jobQueueService.getExecutionRegistrations()),e.daemonRegistry.getStatuses(),(e.readProcessSignals??d0)(),e.projectionRuntimeSupervisor.getDiagnostics(),y0(e),e.operationalHealthRegistry.getChecks()]),m=i.status==="fulfilled"?i.value:null,p=a.status==="fulfilled"?a.value:null,f=s.status==="fulfilled"?s.value:[],g=l.status==="fulfilled"?l.value:{fileDescriptors:null,processCount:null,zombieCount:null},h=c.status==="fulfilled"?c.value:{status:"unhealthy",initialized:!1,trackedRoots:0,openCircuits:[]},v=[Sp("entity-database",o,"Entity database is accessible"),Sp("job-queue-database",i,"Job queue database is accessible"),p0(m),m0(m),g0(m,p),f0(m),c.status==="fulfilled"?h0(h):{name:"projection-circuits",status:"degraded",message:ke(c.reason)},u.status==="fulfilled"?v0(u.value):{name:"projection-waves",status:"degraded",message:ke(u.reason)},s.status==="fulfilled"?b0(f):{name:"daemons",status:"degraded",message:ke(s.reason)}],x=d.status==="fulfilled"?d.value:[{name:"plugin-operational-health",status:"degraded",message:"Plugin operational health is unavailable"}],S=[...v,...x];return{status:v.some((y)=>y.status==="unhealthy")?"not_ready":"ready",operationalStatus:S.some((y)=>y.status!=="healthy")?"degraded":"operational",checkedAt:new Date(t).toISOString(),checks:S,resources:{memory:{rssBytes:n.rss,heapUsedBytes:n.heapUsed,heapTotalBytes:n.heapTotal},fileDescriptors:g.fileDescriptors,processes:{total:g.processCount,zombies:g.zombieCount},queue:m,projection:{initialized:h.initialized,trackedRoots:h.trackedRoots,openCircuits:h.openCircuits},worker:m?.workerSessions??{total:0,active:0,stale:0,latestHeartbeatAgeMs:null}}}}function xp(){return{dataDir:"./data",cacheDir:"./cache",distDir:"./dist"}}function Cn(e){return{database:{url:`file:${e.dataDir}/brain.db`},jobQueueDatabase:{url:`file:${e.dataDir}/brain-jobs.db`},conversationDatabase:{url:`file:${e.dataDir}/conversations.db`},runtimeStateDatabase:{url:`file:${e.dataDir}/runtime-state.db`},embeddingDatabase:{url:`file:${e.dataDir}/embeddings.db`},embedding:{enabled:!0}}}var il=xp(),_0=r.looseObject({label:r.string().min(1),pluralName:r.string().optional(),layout:r.string().optional(),paginate:r.boolean().optional(),pageSize:r.number().optional(),navigation:r.object({show:r.boolean().optional(),slot:r.enum(["primary","secondary"]).optional(),priority:r.number().optional()}).optional()});function al(){return Cn(il)}var Qn=r.enum(["debug","info","warn","error"]),Xn=r.enum(["none","low","medium","high","xhigh","max"]),sl=r.object({name:r.string().default("brain-app"),version:r.string().default("1.0.0"),database:Yn,jobQueueDatabase:Yn,jobQueue:r.object({workerConcurrency:r.number().int().min(1).max(32).default(4)}).prefault({}),conversationDatabase:Yn,runtimeStateDatabase:Yn,embeddingDatabase:Yn,ai:r.object({apiKey:r.string().default(""),imageApiKey:r.string().optional(),model:r.string(),temperature:r.number().min(0).max(2).default(0.7),maxTokens:r.number().positive().default(1000),webSearch:r.boolean().default(!0),reasoningEffort:Xn.optional()}),embedding:r.object({enabled:r.boolean().default(!0)}),logging:r.object({level:Qn.default("info"),format:r.enum(["text","json"]).default("text"),file:r.string().optional(),context:r.string().default("shell")}).prefault({level:"info",context:"shell"}),features:r.object({}).default({}),plugins:r.array(pa).default([]),dataDir:r.string().default("./brain-data"),gitBrokerSocket:r.string().min(1).optional(),gitBrokerCheckout:r.string().min(1).optional(),spaces:r.array(r.string()).default([]),siteBaseUrl:r.string().optional(),localSiteUrl:r.string().optional(),preferLocalUrls:r.boolean().default(!1),themeCSS:r.string().default(""),entityDisplay:r.record(r.string(),_0).optional(),profileKind:r.string().trim().min(1).optional()});function ma(e={}){let{plugins:t=[],permissions:n={},identity:o,profile:i,agentInstructions:a,evalHandlerRegistry:s,ai:l,logging:c,embedding:u,jobQueue:d,...m}=e,{entityDisplay:p,...f}=sl.parse({...al(),...gt(m),ai:gt({...l}),logging:gt({...c}),embedding:gt({...u}),jobQueue:gt({...d}),plugins:[]});return{...f,plugins:t,permissions:n,...gt({entityDisplay:p,identity:o,profile:i,agentInstructions:a,evalHandlerRegistry:s})}}var Rt={NOTE:"note",BRAIN_CHARACTER:"brain-character",ANCHOR_PROFILE:"anchor-profile"},Yo={KNOWLEDGE_QUERY:"shell:knowledge-query",BASE_ENTITY_DISPLAY:"shell:base-entity-display",CONTENT_GENERATION:"shell:content-generation"},ll={ENTITIES:"shell:entities"};var S0=r.object({prompt:r.string().optional(),conversationHistory:r.string().optional(),data:r.record(r.string(),r.unknown()).optional(),representedIdentity:r.enum(["brain","anchor","none"]).optional(),styleGuide:r.object({voice:r.string().optional(),visual:r.string().optional()}).optional(),templateName:r.string()}),w0=r.object({slug:r.string()});function x0(e){return e instanceof r.ZodType}function T0(e){if(!e)return;return e.replace(/^https?:\/\//,"").replace(/\/$/,"")}class fa{aiService;entityService;templateRegistry;getIdentityContent;getProfileContent;id="ai-content";name="AI Content Generator";description="Generates content using AI based on templates and prompts";constructor(e,t,n,o,i,a){this.aiService=e,this.entityService=t,this.templateRegistry=n,this.getIdentityContent=o,this.getProfileContent=i,this.siteBaseUrl=T0(a)}siteBaseUrl;async generate(e,t,n){return this.generateWithContext(e,t,n)}async generateScoped(e,t,n){return this.generateWithContext(e,t,n.signal,n)}async generateWithContext(e,t,n,o){n?.throwIfAborted();let i=S0.parse(e),a=this.templateRegistry.get(i.templateName);if(!a)throw Error(`Template not found: ${i.templateName}`);if(!a.basePrompt)throw Error(`Template ${i.templateName} must have basePrompt for content generation`);let s=o?await Tp((v,x)=>o.getEntity(v,x),i.templateName,a.basePrompt):await ga(this.entityService,i.templateName,a.basePrompt);n?.throwIfAborted();let l=[s,i.prompt].filter(Boolean).join(" "),c=l.length>0&&a.useKnowledgeContext===!0,u=this.entityService.getWeightMap(),d=Object.keys(u).length>0,m=c?o?await o.search(l,{limit:5,...d&&{weight:u}}):await this.entityService.search({query:l,options:{limit:5,...d&&{weight:u},...n&&{signal:n}}}):[];n?.throwIfAborted();let p=await this.buildPrompt({basePrompt:s},i,m),f=o?await this.readIdentities(o,i.representedIdentity):void 0,g=this.buildSystemPrompt(s,i,f);if(!x0(a.schema))throw Error(`Template ${a.name} cannot be used for AI generation: schema is not an AI generation schema`);n?.throwIfAborted();let h=await this.aiService.generateObject(g,p,a.schema,n);return n?.throwIfAborted(),t.parse(h.object)}async readIdentities(e,t){let n=async(a)=>(await e.getEntity(a,a))?.content??"",[o,i]=await Promise.all([t!=="none"?n(Rt.BRAIN_CHARACTER):"",t===void 0||t==="anchor"?n(Rt.ANCHOR_PROFILE):""]);return{brain:o,anchor:i}}buildSystemPrompt(e,t,n){let o=[];if(t.representedIdentity===void 0||t.representedIdentity==="brain"||t.representedIdentity==="anchor")o.push("# Brain Identity",n?.brain??this.getIdentityContent(),"");if(t.representedIdentity===void 0||t.representedIdentity==="anchor")o.push("# Represented Anchor",n?.anchor??this.getProfileContent(),"");let i=this.selectStyleGuidance(t);if(i)o.push("# Style Guide",i,"");return o.push("# Instructions",e),o.join(`
9
+ `)}selectStyleGuidance(e){if(!e.styleGuide)return"";let t=[];if(e.styleGuide.voice)t.push("## Voice",e.styleGuide.voice);if(e.styleGuide.visual)t.push("## Visual",e.styleGuide.visual);return t.join(`
10
+ `)}async buildPrompt(e,t,n=[]){let o=e.basePrompt;if(t.conversationHistory)o+=`
11
+
12
+ Recent conversation context:
13
+ ${t.conversationHistory}`;if(n.length>0){let i=Qo.getInstance(),a=n.map((s)=>this.formatRelevantEntity(s,i)).join(`
14
+ `);o+=`
15
+
16
+ Relevant context from your knowledge base:
17
+ ${a}`}if(t.data)o+=`
18
+
19
+ Context data:
20
+ ${JSON.stringify(t.data,null,2)}`;if(t.prompt)o+=`
21
+
22
+ Additional instructions: ${t.prompt}`;return o}formatRelevantEntity(e,t){let{entity:n,excerpt:o}=e,i=n.entityType,a=w0.safeParse(n.metadata),s=a.success?a.data.slug:n.id;if(this.siteBaseUrl&&t.hasRoute(i)){let l=t.generateUrl(i,s),c=`https://${this.siteBaseUrl}${l}`;return`[${i}] ${n.id}: ${o} (${c})`}return`[${i}] ${n.id}: ${o}`}}var I0=r.object({entityType:r.string(),query:r.object({id:r.string()})});class ha{entityService;id=ll.ENTITIES;name="Entity DataSource";description="Fetches entity content from the entity service";constructor(e){this.entityService=e}async fetch(e,t,n){let o=I0.safeParse(e);if(!o.success){let l=o.error.issues.map((c)=>`${c.path.join(".")}: ${c.message}`).join(", ");throw Error(`EntityDataSource: Invalid query - ${l}`)}let i=o.data,s=await(n?.entityService??this.entityService).getEntity({entityType:i.entityType,id:i.query.id});if(!s)throw Error(`EntityDataSource: Entity not found (${i.entityType}:${i.query.id})`);return t.parse({markdown:s.content})}}function Ip(e,t){e.dataSourceRegistry.register(new fa(e.aiService,e.entityService,e.templateRegistry,()=>e.identityService.getCharacterContent(),()=>e.profileService.getProfileContent(),t.siteBaseUrl)),e.dataSourceRegistry.register(new ha(e.entityService)),e.logger.debug("Core DataSources registered")}async function Cp(e,t){let n=e.contentService.getTemplate(t.templateName);if(!n)throw Error(`Template not found: ${t.templateName}`);let o=t.interfacePermissionGrant??"public";if(!e.permissionService.hasPermission(o,n.requiredPermission))throw Error(`Insufficient permissions: ${n.requiredPermission} required, but interface granted ${o} for template: ${t.templateName}`);let i={prompt:t.prompt,...t.conversationHistory&&{conversationHistory:t.conversationHistory},...t.data&&{data:t.data},...t.representedIdentity&&{representedIdentity:t.representedIdentity},...t.styleGuide&&{styleGuide:t.styleGuide}};return e.contentService.generateContent(t.templateName,i)}var tm="vercel.ai.error",C0=Symbol.for(tm),kp,Rp,ie=class e extends(Rp=Error,kp=C0,Rp){constructor({name:t,message:n,cause:o}){super(n);this[kp]=!0,this.name=t,this.cause=o}static isInstance(t){return e.hasMarker(t,tm)}static hasMarker(t,n){let o=Symbol.for(n);return t!=null&&typeof t==="object"&&o in t&&typeof t[o]==="boolean"&&t[o]===!0}},rm="AI_APICallError",nm=`vercel.ai.error.${rm}`,k0=Symbol.for(nm),Ep,Ap,De=class extends(Ap=ie,Ep=k0,Ap){constructor({message:e,url:t,requestBodyValues:n,statusCode:o,responseHeaders:i,responseBody:a,cause:s,isRetryable:l=o!=null&&(o===408||o===409||o===429||o>=500),data:c}){super({name:rm,message:e,cause:s});this[Ep]=!0,this.url=t,this.requestBodyValues=n,this.statusCode=o,this.responseHeaders=i,this.responseBody=a,this.isRetryable=l,this.data=c}static isInstance(e){return ie.hasMarker(e,nm)}},om="AI_EmptyResponseBodyError",im=`vercel.ai.error.${om}`,R0=Symbol.for(im),Pp,Mp,am=class extends(Mp=ie,Pp=R0,Mp){constructor({message:e="Empty response body"}={}){super({name:om,message:e});this[Pp]=!0}static isInstance(e){return ie.hasMarker(e,im)}};function Tr(e){if(e==null)return"unknown error";if(typeof e==="string")return e;if(e instanceof Error)return e.message;return JSON.stringify(e)}var sm="AI_InvalidArgumentError",lm=`vercel.ai.error.${sm}`,E0=Symbol.for(lm),jp,Op,eo=class extends(Op=ie,jp=E0,Op){constructor({message:e,cause:t,argument:n}){super({name:sm,message:e,cause:t});this[jp]=!0,this.argument=n}static isInstance(e){return ie.hasMarker(e,lm)}},cm="AI_InvalidPromptError",um=`vercel.ai.error.${cm}`,A0=Symbol.for(um),Np,Dp,Ir=class extends(Dp=ie,Np=A0,Dp){constructor({prompt:e,message:t,cause:n}){super({name:cm,message:`Invalid prompt: ${t}`,cause:n});this[Np]=!0,this.prompt=e}static isInstance(e){return ie.hasMarker(e,um)}},dm="AI_InvalidResponseDataError",pm=`vercel.ai.error.${dm}`,P0=Symbol.for(pm),zp,Up,va=class extends(Up=ie,zp=P0,Up){constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:dm,message:t});this[zp]=!0,this.data=e}static isInstance(e){return ie.hasMarker(e,pm)}},mm="AI_JSONParseError",gm=`vercel.ai.error.${mm}`,M0=Symbol.for(gm),$p,Lp,kn=class extends(Lp=ie,$p=M0,Lp){constructor({text:e,cause:t}){super({name:mm,message:`JSON parsing failed: Text: ${e}.
23
+ Error message: ${Tr(t)}`,cause:t});this[$p]=!0,this.text=e}static isInstance(e){return ie.hasMarker(e,gm)}},fm="AI_LoadAPIKeyError",hm=`vercel.ai.error.${fm}`,j0=Symbol.for(hm),qp,Fp,Xo=class extends(Fp=ie,qp=j0,Fp){constructor({message:e}){super({name:fm,message:e});this[qp]=!0}static isInstance(e){return ie.hasMarker(e,hm)}},ym="AI_LoadSettingError",vm=`vercel.ai.error.${ym}`,O0=Symbol.for(vm),Bp,Gp,f4=class extends(Gp=ie,Bp=O0,Gp){constructor({message:e}){super({name:ym,message:e});this[Bp]=!0}static isInstance(e){return ie.hasMarker(e,vm)}},bm="AI_NoContentGeneratedError",_m=`vercel.ai.error.${bm}`,N0=Symbol.for(_m),Jp,Hp,h4=class extends(Hp=ie,Jp=N0,Hp){constructor({message:e="No content generated."}={}){super({name:bm,message:e});this[Jp]=!0}static isInstance(e){return ie.hasMarker(e,_m)}},Sm="AI_NoSuchModelError",wm=`vercel.ai.error.${Sm}`,D0=Symbol.for(wm),Wp,Vp,cl=class extends(Vp=ie,Wp=D0,Vp){constructor({errorName:e=Sm,modelId:t,modelType:n,message:o=`No such ${n}: ${t}`}){super({name:e,message:o});this[Wp]=!0,this.modelId=t,this.modelType=n}static isInstance(e){return ie.hasMarker(e,wm)}},xm="AI_TooManyEmbeddingValuesForCallError",Tm=`vercel.ai.error.${xm}`,z0=Symbol.for(Tm),Zp,Kp,ba=class extends(Kp=ie,Zp=z0,Kp){constructor(e){super({name:xm,message:`Too many values for a single embedding call. The ${e.provider} model "${e.modelId}" can only embed up to ${e.maxEmbeddingsPerCall} values per call, but ${e.values.length} values were provided.`});this[Zp]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return ie.hasMarker(e,Tm)}},Im="AI_TypeValidationError",Cm=`vercel.ai.error.${Im}`,U0=Symbol.for(Cm),Yp,Qp,vt=class e extends(Qp=ie,Yp=U0,Qp){constructor({value:t,cause:n,context:o}){let i="Type validation failed";if(o==null?void 0:o.field)i+=` for ${o.field}`;if((o==null?void 0:o.entityName)||(o==null?void 0:o.entityId)){i+=" (";let a=[];if(o.entityName)a.push(o.entityName);if(o.entityId)a.push(`id: "${o.entityId}"`);i+=a.join(", "),i+=")"}super({name:Im,message:`${i}: Value: ${JSON.stringify(t)}.
24
+ Error message: ${Tr(n)}`,cause:n});this[Yp]=!0,this.value=t,this.context=o}static isInstance(t){return ie.hasMarker(t,Cm)}static wrap({value:t,cause:n,context:o}){var i,a,s;if(e.isInstance(n)&&n.value===t&&((i=n.context)==null?void 0:i.field)===(o==null?void 0:o.field)&&((a=n.context)==null?void 0:a.entityName)===(o==null?void 0:o.entityName)&&((s=n.context)==null?void 0:s.entityId)===(o==null?void 0:o.entityId))return n;return new e({value:t,cause:n,context:o})}},km="AI_UnsupportedFunctionalityError",Rm=`vercel.ai.error.${km}`,$0=Symbol.for(Rm),Xp,em,We=class extends(em=ie,Xp=$0,em){constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:km,message:t});this[Xp]=!0,this.functionality=e}static isInstance(e){return ie.hasMarker(e,Rm)}};function ya(e){if(e===null||typeof e==="string"||typeof e==="number"||typeof e==="boolean")return!0;if(Array.isArray(e))return e.every(ya);if(typeof e==="object")return Object.entries(e).every(([t,n])=>typeof t==="string"&&(n===void 0||ya(n)));return!1}function ul(e){return Array.isArray(e)&&e.every(ya)}function ei(e){return e!=null&&typeof e==="object"&&Object.entries(e).every(([t,n])=>typeof t==="string"&&(n===void 0||ya(n)))}var $e;(function(e){e.assertEqual=(i)=>{};function t(i){}e.assertIs=t;function n(i){throw Error()}e.assertNever=n,e.arrayToEnum=(i)=>{let a={};for(let s of i)a[s]=s;return a},e.getValidEnumValues=(i)=>{let a=e.objectKeys(i).filter((l)=>typeof i[i[l]]!=="number"),s={};for(let l of a)s[l]=i[l];return e.objectValues(s)},e.objectValues=(i)=>e.objectKeys(i).map(function(a){return i[a]}),e.objectKeys=typeof Object.keys==="function"?(i)=>Object.keys(i):(i)=>{let a=[];for(let s in i)if(Object.prototype.hasOwnProperty.call(i,s))a.push(s);return a},e.find=(i,a)=>{for(let s of i)if(a(s))return s;return},e.isInteger=typeof Number.isInteger==="function"?(i)=>Number.isInteger(i):(i)=>typeof i==="number"&&Number.isFinite(i)&&Math.floor(i)===i;function o(i,a=" | "){return i.map((s)=>typeof s==="string"?`'${s}'`:s).join(a)}e.joinValues=o,e.jsonStringifyReplacer=(i,a)=>{if(typeof a==="bigint")return a.toString();return a}})($e||($e={}));var Em;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Em||(Em={}));var ae=$e.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Lr=(e)=>{switch(typeof e){case"undefined":return ae.undefined;case"string":return ae.string;case"number":return Number.isNaN(e)?ae.nan:ae.number;case"boolean":return ae.boolean;case"function":return ae.function;case"bigint":return ae.bigint;case"symbol":return ae.symbol;case"object":if(Array.isArray(e))return ae.array;if(e===null)return ae.null;if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return ae.promise;if(typeof Map<"u"&&e instanceof Map)return ae.map;if(typeof Set<"u"&&e instanceof Set)return ae.set;if(typeof Date<"u"&&e instanceof Date)return ae.date;return ae.object;default:return ae.unknown}};var ne=$e.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Kt extends Error{get errors(){return this.issues}constructor(e){super();this.issues=[],this.addIssue=(n)=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,t);else this.__proto__=t;this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},n={_errors:[]},o=(i)=>{for(let a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)n._errors.push(t(a));else{let s=n,l=0;while(l<a.path.length){let c=a.path[l];if(l!==a.path.length-1)s[c]=s[c]||{_errors:[]};else s[c]=s[c]||{_errors:[]},s[c]._errors.push(t(a));s=s[c],l++}}};return o(this),n}static assert(e){if(!(e instanceof Kt))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,$e.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=(t)=>t.message){let t=Object.create(null),n=[];for(let o of this.issues)if(o.path.length>0){let i=o.path[0];t[i]=t[i]||[],t[i].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}Kt.create=(e)=>new Kt(e);var L0=(e,t)=>{let n;switch(e.code){case ne.invalid_type:if(e.received===ae.undefined)n="Required";else n=`Expected ${e.expected}, received ${e.received}`;break;case ne.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,$e.jsonStringifyReplacer)}`;break;case ne.unrecognized_keys:n=`Unrecognized key(s) in object: ${$e.joinValues(e.keys,", ")}`;break;case ne.invalid_union:n="Invalid input";break;case ne.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${$e.joinValues(e.options)}`;break;case ne.invalid_enum_value:n=`Invalid enum value. Expected ${$e.joinValues(e.options)}, received '${e.received}'`;break;case ne.invalid_arguments:n="Invalid function arguments";break;case ne.invalid_return_type:n="Invalid function return type";break;case ne.invalid_date:n="Invalid date";break;case ne.invalid_string:if(typeof e.validation==="object")if("includes"in e.validation){if(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==="number")n=`${n} at one or more positions greater than or equal to ${e.validation.position}`}else if("startsWith"in e.validation)n=`Invalid input: must start with "${e.validation.startsWith}"`;else if("endsWith"in e.validation)n=`Invalid input: must end with "${e.validation.endsWith}"`;else $e.assertNever(e.validation);else if(e.validation!=="regex")n=`Invalid ${e.validation}`;else n="Invalid";break;case ne.too_small:if(e.type==="array")n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`;else if(e.type==="string")n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`;else if(e.type==="number")n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="bigint")n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="date")n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`;else n="Invalid input";break;case ne.too_big:if(e.type==="array")n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`;else if(e.type==="string")n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`;else if(e.type==="number")n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="bigint")n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="date")n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`;else n="Invalid input";break;case ne.custom:n="Invalid input";break;case ne.invalid_intersection_types:n="Intersection results could not be merged";break;case ne.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case ne.not_finite:n="Number must be finite";break;default:n=t.defaultError,$e.assertNever(e)}return{message:n}},dn=L0;var q0=dn;function ti(){return q0}var _a=(e)=>{let{data:t,path:n,errorMaps:o,issueData:i}=e,a=[...n,...i.path||[]],s={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let l="",c=o.filter((u)=>!!u).slice().reverse();for(let u of c)l=u(s,{data:t,defaultError:l}).message;return{...i,path:a,message:l}};function le(e,t){let n=ti(),o=_a({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===dn?void 0:dn].filter((i)=>!!i)});e.common.issues.push(o)}class Ot{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(e,t){let n=[];for(let o of t){if(o.status==="aborted")return we;if(o.status==="dirty")e.dirty();n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let o of t){let i=await o.key,a=await o.value;n.push({key:i,value:a})}return Ot.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let o of t){let{key:i,value:a}=o;if(i.status==="aborted")return we;if(a.status==="aborted")return we;if(i.status==="dirty")e.dirty();if(a.status==="dirty")e.dirty();if(i.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet))n[i.value]=a.value}return{status:e.value,value:n}}}var we=Object.freeze({status:"aborted"}),to=(e)=>({status:"dirty",value:e}),$t=(e)=>({status:"valid",value:e}),dl=(e)=>e.status==="aborted",pl=(e)=>e.status==="dirty",Rn=(e)=>e.status==="valid",ri=(e)=>typeof Promise<"u"&&e instanceof Promise;var ge;(function(e){e.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},e.toString=(t)=>typeof t==="string"?t:t?.message})(ge||(ge={}));class ur{constructor(e,t,n,o){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=o}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var Am=(e,t)=>{if(Rn(t))return{success:!0,data:t.value};else{if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new Kt(e.common.issues);return this._error=n,this._error}}}};function Pe(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:o,description:i}=e;if(t&&(n||o))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:i};return{errorMap:(s,l)=>{let{message:c}=e;if(s.code==="invalid_enum_value")return{message:c??l.defaultError};if(typeof l.data>"u")return{message:c??o??l.defaultError};if(s.code!=="invalid_type")return{message:l.defaultError};return{message:c??n??l.defaultError}},description:i}}class ze{get description(){return this._def.description}_getType(e){return Lr(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Lr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ot,ctx:{common:e.parent.common,data:e.data,parsedType:Lr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(ri(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Lr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Am(n,o)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Lr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return Rn(n)?{value:n.value}:{issues:t.common.issues}}catch(n){if(n?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((n)=>Rn(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Lr(e)},o=this._parse({data:e,path:n.path,parent:n}),i=await(ri(o)?o:Promise.resolve(o));return Am(n,i)}refine(e,t){let n=(o)=>{if(typeof t==="string"||typeof t>"u")return{message:t};else if(typeof t==="function")return t(o);else return t};return this._refinement((o,i)=>{let a=e(o),s=()=>i.addIssue({code:ne.custom,...n(o)});if(typeof Promise<"u"&&a instanceof Promise)return a.then((l)=>{if(!l)return s(),!1;else return!0});if(!a)return s(),!1;else return!0})}refinement(e,t){return this._refinement((n,o)=>{if(!e(n))return o.addIssue(typeof t==="function"?t(n,o):t),!1;else return!0})}_refinement(e){return new Rr({schema:this,typeName:oe.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(t)=>this["~validate"](t)}}optional(){return kr.create(this,this._def)}nullable(){return pn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Cr.create(this)}promise(){return ao.create(this,this._def)}or(e){return si.create([this,e],this._def)}and(e){return li.create(this,e,this._def)}transform(e){return new Rr({...Pe(this._def),schema:this,typeName:oe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e==="function"?e:()=>e;return new pi({...Pe(this._def),innerType:this,defaultValue:t,typeName:oe.ZodDefault})}brand(){return new hl({typeName:oe.ZodBranded,type:this,...Pe(this._def)})}catch(e){let t=typeof e==="function"?e:()=>e;return new mi({...Pe(this._def),innerType:this,catchValue:t,typeName:oe.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return Ra.create(this,e)}readonly(){return gi.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var F0=/^c[^\s-]{8,}$/i,B0=/^[0-9a-z]+$/,G0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,J0=/^[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}$/i,H0=/^[a-z0-9_-]{21}$/i,W0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,V0=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Z0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,K0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ml,Y0=/^(?:(?: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])$/,Q0=/^(?:(?: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])$/,X0=/^(([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]))$/,ek=/^(([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])$/,tk=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,rk=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Pm="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",nk=new RegExp(`^${Pm}$`);function Mm(e){let t="[0-5]\\d";if(e.precision)t=`${t}\\.\\d{${e.precision}}`;else if(e.precision==null)t=`${t}(\\.\\d+)?`;let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function ok(e){return new RegExp(`^${Mm(e)}$`)}function ik(e){let t=`${Pm}T${Mm(e)}`,n=[];if(n.push(e.local?"Z?":"Z"),e.offset)n.push("([+-]\\d{2}:?\\d{2})");return t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function ak(e,t){if((t==="v4"||!t)&&Y0.test(e))return!0;if((t==="v6"||!t)&&X0.test(e))return!0;return!1}function sk(e,t){if(!W0.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let o=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(o));if(typeof i!=="object"||i===null)return!1;if("typ"in i&&i?.typ!=="JWT")return!1;if(!i.alg)return!1;if(t&&i.alg!==t)return!1;return!0}catch{return!1}}function lk(e,t){if((t==="v4"||!t)&&Q0.test(e))return!0;if((t==="v6"||!t)&&ek.test(e))return!0;return!1}class Fr extends ze{_parse(e){if(this._def.coerce)e.data=String(e.data);if(this._getType(e)!==ae.string){let i=this._getOrReturnCtx(e);return le(i,{code:ne.invalid_type,expected:ae.string,received:i.parsedType}),we}let n=new Ot,o=void 0;for(let i of this._def.checks)if(i.kind==="min"){if(e.data.length<i.value)o=this._getOrReturnCtx(e,o),le(o,{code:ne.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty()}else if(i.kind==="max"){if(e.data.length>i.value)o=this._getOrReturnCtx(e,o),le(o,{code:ne.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty()}else if(i.kind==="length"){let a=e.data.length>i.value,s=e.data.length<i.value;if(a||s){if(o=this._getOrReturnCtx(e,o),a)le(o,{code:ne.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message});else if(s)le(o,{code:ne.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message});n.dirty()}}else if(i.kind==="email"){if(!Z0.test(e.data))o=this._getOrReturnCtx(e,o),le(o,{validation:"email",code:ne.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="emoji"){if(!ml)ml=new RegExp(K0,"u");if(!ml.test(e.data))o=this._getOrReturnCtx(e,o),le(o,{validation:"emoji",code:ne.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="uuid"){if(!J0.test(e.data))o=this._getOrReturnCtx(e,o),le(o,{validation:"uuid",code:ne.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="nanoid"){if(!H0.test(e.data))o=this._getOrReturnCtx(e,o),le(o,{validation:"nanoid",code:ne.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="cuid"){if(!F0.test(e.data))o=this._getOrReturnCtx(e,o),le(o,{validation:"cuid",code:ne.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="cuid2"){if(!B0.test(e.data))o=this._getOrReturnCtx(e,o),le(o,{validation:"cuid2",code:ne.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="ulid"){if(!G0.test(e.data))o=this._getOrReturnCtx(e,o),le(o,{validation:"ulid",code:ne.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),le(o,{validation:"url",code:ne.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="regex"){if(i.regex.lastIndex=0,!i.regex.test(e.data))o=this._getOrReturnCtx(e,o),le(o,{validation:"regex",code:ne.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="trim")e.data=e.data.trim();else if(i.kind==="includes"){if(!e.data.includes(i.value,i.position))o=this._getOrReturnCtx(e,o),le(o,{code:ne.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()}else if(i.kind==="toLowerCase")e.data=e.data.toLowerCase();else if(i.kind==="toUpperCase")e.data=e.data.toUpperCase();else if(i.kind==="startsWith"){if(!e.data.startsWith(i.value))o=this._getOrReturnCtx(e,o),le(o,{code:ne.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()}else if(i.kind==="endsWith"){if(!e.data.endsWith(i.value))o=this._getOrReturnCtx(e,o),le(o,{code:ne.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()}else if(i.kind==="datetime"){if(!ik(i).test(e.data))o=this._getOrReturnCtx(e,o),le(o,{code:ne.invalid_string,validation:"datetime",message:i.message}),n.dirty()}else if(i.kind==="date"){if(!nk.test(e.data))o=this._getOrReturnCtx(e,o),le(o,{code:ne.invalid_string,validation:"date",message:i.message}),n.dirty()}else if(i.kind==="time"){if(!ok(i).test(e.data))o=this._getOrReturnCtx(e,o),le(o,{code:ne.invalid_string,validation:"time",message:i.message}),n.dirty()}else if(i.kind==="duration"){if(!V0.test(e.data))o=this._getOrReturnCtx(e,o),le(o,{validation:"duration",code:ne.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="ip"){if(!ak(e.data,i.version))o=this._getOrReturnCtx(e,o),le(o,{validation:"ip",code:ne.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="jwt"){if(!sk(e.data,i.alg))o=this._getOrReturnCtx(e,o),le(o,{validation:"jwt",code:ne.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="cidr"){if(!lk(e.data,i.version))o=this._getOrReturnCtx(e,o),le(o,{validation:"cidr",code:ne.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="base64"){if(!tk.test(e.data))o=this._getOrReturnCtx(e,o),le(o,{validation:"base64",code:ne.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="base64url"){if(!rk.test(e.data))o=this._getOrReturnCtx(e,o),le(o,{validation:"base64url",code:ne.invalid_string,message:i.message}),n.dirty()}else $e.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement((o)=>e.test(o),{validation:t,code:ne.invalid_string,...ge.errToObj(n)})}_addCheck(e){return new Fr({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ge.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ge.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ge.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ge.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ge.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ge.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ge.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ge.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ge.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...ge.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...ge.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ge.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...ge.errToObj(e)})}datetime(e){if(typeof e==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e});return this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...ge.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){if(typeof e==="string")return this._addCheck({kind:"time",precision:null,message:e});return this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...ge.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...ge.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...ge.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...ge.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...ge.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...ge.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...ge.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...ge.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...ge.errToObj(t)})}nonempty(e){return this.min(1,ge.errToObj(e))}trim(){return new Fr({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Fr({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Fr({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e)=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find((e)=>e.kind==="date")}get isTime(){return!!this._def.checks.find((e)=>e.kind==="time")}get isDuration(){return!!this._def.checks.find((e)=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find((e)=>e.kind==="email")}get isURL(){return!!this._def.checks.find((e)=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find((e)=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find((e)=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((e)=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((e)=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((e)=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find((e)=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find((e)=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find((e)=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find((e)=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find((e)=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxLength(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}Fr.create=(e)=>new Fr({checks:[],typeName:oe.ZodString,coerce:e?.coerce??!1,...Pe(e)});function ck(e,t){let n=(e.toString().split(".")[1]||"").length,o=(t.toString().split(".")[1]||"").length,i=n>o?n:o,a=Number.parseInt(e.toFixed(i).replace(".","")),s=Number.parseInt(t.toFixed(i).replace(".",""));return a%s/10**i}class no extends ze{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce)e.data=Number(e.data);if(this._getType(e)!==ae.number){let i=this._getOrReturnCtx(e);return le(i,{code:ne.invalid_type,expected:ae.number,received:i.parsedType}),we}let n=void 0,o=new Ot;for(let i of this._def.checks)if(i.kind==="int"){if(!$e.isInteger(e.data))n=this._getOrReturnCtx(e,n),le(n,{code:ne.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()}else if(i.kind==="min"){if(i.inclusive?e.data<i.value:e.data<=i.value)n=this._getOrReturnCtx(e,n),le(n,{code:ne.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()}else if(i.kind==="max"){if(i.inclusive?e.data>i.value:e.data>=i.value)n=this._getOrReturnCtx(e,n),le(n,{code:ne.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()}else if(i.kind==="multipleOf"){if(ck(e.data,i.value)!==0)n=this._getOrReturnCtx(e,n),le(n,{code:ne.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()}else if(i.kind==="finite"){if(!Number.isFinite(e.data))n=this._getOrReturnCtx(e,n),le(n,{code:ne.not_finite,message:i.message}),o.dirty()}else $e.assertNever(i);return{status:o.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,ge.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ge.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ge.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ge.toString(t))}setLimit(e,t,n,o){return new no({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:ge.toString(o)}]})}_addCheck(e){return new no({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ge.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ge.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ge.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ge.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ge.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ge.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:ge.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ge.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ge.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}get isInt(){return!!this._def.checks.find((e)=>e.kind==="int"||e.kind==="multipleOf"&&$e.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;else if(n.kind==="min"){if(t===null||n.value>t)t=n.value}else if(n.kind==="max"){if(e===null||n.value<e)e=n.value}return Number.isFinite(t)&&Number.isFinite(e)}}no.create=(e)=>new no({checks:[],typeName:oe.ZodNumber,coerce:e?.coerce||!1,...Pe(e)});class oo extends ze{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ae.bigint)return this._getInvalidInput(e);let n=void 0,o=new Ot;for(let i of this._def.checks)if(i.kind==="min"){if(i.inclusive?e.data<i.value:e.data<=i.value)n=this._getOrReturnCtx(e,n),le(n,{code:ne.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()}else if(i.kind==="max"){if(i.inclusive?e.data>i.value:e.data>=i.value)n=this._getOrReturnCtx(e,n),le(n,{code:ne.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()}else if(i.kind==="multipleOf"){if(e.data%i.value!==BigInt(0))n=this._getOrReturnCtx(e,n),le(n,{code:ne.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()}else $e.assertNever(i);return{status:o.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return le(t,{code:ne.invalid_type,expected:ae.bigint,received:t.parsedType}),we}gte(e,t){return this.setLimit("min",e,!0,ge.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ge.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ge.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ge.toString(t))}setLimit(e,t,n,o){return new oo({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:ge.toString(o)}]})}_addCheck(e){return new oo({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ge.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ge.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ge.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ge.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ge.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}oo.create=(e)=>new oo({checks:[],typeName:oe.ZodBigInt,coerce:e?.coerce??!1,...Pe(e)});class Sa extends ze{_parse(e){if(this._def.coerce)e.data=Boolean(e.data);if(this._getType(e)!==ae.boolean){let n=this._getOrReturnCtx(e);return le(n,{code:ne.invalid_type,expected:ae.boolean,received:n.parsedType}),we}return $t(e.data)}}Sa.create=(e)=>new Sa({typeName:oe.ZodBoolean,coerce:e?.coerce||!1,...Pe(e)});class oi extends ze{_parse(e){if(this._def.coerce)e.data=new Date(e.data);if(this._getType(e)!==ae.date){let i=this._getOrReturnCtx(e);return le(i,{code:ne.invalid_type,expected:ae.date,received:i.parsedType}),we}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return le(i,{code:ne.invalid_date}),we}let n=new Ot,o=void 0;for(let i of this._def.checks)if(i.kind==="min"){if(e.data.getTime()<i.value)o=this._getOrReturnCtx(e,o),le(o,{code:ne.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()}else if(i.kind==="max"){if(e.data.getTime()>i.value)o=this._getOrReturnCtx(e,o),le(o,{code:ne.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()}else $e.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new oi({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:ge.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:ge.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e!=null?new Date(e):null}}oi.create=(e)=>new oi({checks:[],coerce:e?.coerce||!1,typeName:oe.ZodDate,...Pe(e)});class wa extends ze{_parse(e){if(this._getType(e)!==ae.symbol){let n=this._getOrReturnCtx(e);return le(n,{code:ne.invalid_type,expected:ae.symbol,received:n.parsedType}),we}return $t(e.data)}}wa.create=(e)=>new wa({typeName:oe.ZodSymbol,...Pe(e)});class ii extends ze{_parse(e){if(this._getType(e)!==ae.undefined){let n=this._getOrReturnCtx(e);return le(n,{code:ne.invalid_type,expected:ae.undefined,received:n.parsedType}),we}return $t(e.data)}}ii.create=(e)=>new ii({typeName:oe.ZodUndefined,...Pe(e)});class ai extends ze{_parse(e){if(this._getType(e)!==ae.null){let n=this._getOrReturnCtx(e);return le(n,{code:ne.invalid_type,expected:ae.null,received:n.parsedType}),we}return $t(e.data)}}ai.create=(e)=>new ai({typeName:oe.ZodNull,...Pe(e)});class xa extends ze{constructor(){super(...arguments);this._any=!0}_parse(e){return $t(e.data)}}xa.create=(e)=>new xa({typeName:oe.ZodAny,...Pe(e)});class En extends ze{constructor(){super(...arguments);this._unknown=!0}_parse(e){return $t(e.data)}}En.create=(e)=>new En({typeName:oe.ZodUnknown,...Pe(e)});class Br extends ze{_parse(e){let t=this._getOrReturnCtx(e);return le(t,{code:ne.invalid_type,expected:ae.never,received:t.parsedType}),we}}Br.create=(e)=>new Br({typeName:oe.ZodNever,...Pe(e)});class Ta extends ze{_parse(e){if(this._getType(e)!==ae.undefined){let n=this._getOrReturnCtx(e);return le(n,{code:ne.invalid_type,expected:ae.void,received:n.parsedType}),we}return $t(e.data)}}Ta.create=(e)=>new Ta({typeName:oe.ZodVoid,...Pe(e)});class Cr extends ze{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),o=this._def;if(t.parsedType!==ae.array)return le(t,{code:ne.invalid_type,expected:ae.array,received:t.parsedType}),we;if(o.exactLength!==null){let a=t.data.length>o.exactLength.value,s=t.data.length<o.exactLength.value;if(a||s)le(t,{code:a?ne.too_big:ne.too_small,minimum:s?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty()}if(o.minLength!==null){if(t.data.length<o.minLength.value)le(t,{code:ne.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()}if(o.maxLength!==null){if(t.data.length>o.maxLength.value)le(t,{code:ne.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()}if(t.common.async)return Promise.all([...t.data].map((a,s)=>o.type._parseAsync(new ur(t,a,t.path,s)))).then((a)=>Ot.mergeArray(n,a));let i=[...t.data].map((a,s)=>o.type._parseSync(new ur(t,a,t.path,s)));return Ot.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new Cr({...this._def,minLength:{value:e,message:ge.toString(t)}})}max(e,t){return new Cr({...this._def,maxLength:{value:e,message:ge.toString(t)}})}length(e,t){return new Cr({...this._def,exactLength:{value:e,message:ge.toString(t)}})}nonempty(e){return this.min(1,e)}}Cr.create=(e,t)=>new Cr({type:e,minLength:null,maxLength:null,exactLength:null,typeName:oe.ZodArray,...Pe(t)});function ro(e){if(e instanceof dt){let t={};for(let n in e.shape){let o=e.shape[n];t[n]=kr.create(ro(o))}return new dt({...e._def,shape:()=>t})}else if(e instanceof Cr)return new Cr({...e._def,type:ro(e.element)});else if(e instanceof kr)return kr.create(ro(e.unwrap()));else if(e instanceof pn)return pn.create(ro(e.unwrap()));else if(e instanceof Gr)return Gr.create(e.items.map((t)=>ro(t)));else return e}class dt extends ze{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=$e.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==ae.object){let c=this._getOrReturnCtx(e);return le(c,{code:ne.invalid_type,expected:ae.object,received:c.parsedType}),we}let{status:n,ctx:o}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),s=[];if(!(this._def.catchall instanceof Br&&this._def.unknownKeys==="strip")){for(let c in o.data)if(!a.includes(c))s.push(c)}let l=[];for(let c of a){let u=i[c],d=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new ur(o,d,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof Br){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of s)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict"){if(s.length>0)le(o,{code:ne.unrecognized_keys,keys:s}),n.dirty()}else if(c==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let u of s){let d=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new ur(o,d,o.path,u)),alwaysSet:u in o.data})}}if(o.common.async)return Promise.resolve().then(async()=>{let c=[];for(let u of l){let d=await u.key,m=await u.value;c.push({key:d,value:m,alwaysSet:u.alwaysSet})}return c}).then((c)=>Ot.mergeObjectSync(n,c));else return Ot.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return ge.errToObj,new dt({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let o=this._def.errorMap?.(t,n).message??n.defaultError;if(t.code==="unrecognized_keys")return{message:ge.errToObj(e).message??o};return{message:o}}}:{}})}strip(){return new dt({...this._def,unknownKeys:"strip"})}passthrough(){return new dt({...this._def,unknownKeys:"passthrough"})}extend(e){return new dt({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new dt({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:oe.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new dt({...this._def,catchall:e})}pick(e){let t={};for(let n of $e.objectKeys(e))if(e[n]&&this.shape[n])t[n]=this.shape[n];return new dt({...this._def,shape:()=>t})}omit(e){let t={};for(let n of $e.objectKeys(this.shape))if(!e[n])t[n]=this.shape[n];return new dt({...this._def,shape:()=>t})}deepPartial(){return ro(this)}partial(e){let t={};for(let n of $e.objectKeys(this.shape)){let o=this.shape[n];if(e&&!e[n])t[n]=o;else t[n]=o.optional()}return new dt({...this._def,shape:()=>t})}required(e){let t={};for(let n of $e.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];while(i instanceof kr)i=i._def.innerType;t[n]=i}return new dt({...this._def,shape:()=>t})}keyof(){return jm($e.objectKeys(this.shape))}}dt.create=(e,t)=>new dt({shape:()=>e,unknownKeys:"strip",catchall:Br.create(),typeName:oe.ZodObject,...Pe(t)});dt.strictCreate=(e,t)=>new dt({shape:()=>e,unknownKeys:"strict",catchall:Br.create(),typeName:oe.ZodObject,...Pe(t)});dt.lazycreate=(e,t)=>new dt({shape:e,unknownKeys:"strip",catchall:Br.create(),typeName:oe.ZodObject,...Pe(t)});class si extends ze{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function o(i){for(let s of i)if(s.result.status==="valid")return s.result;for(let s of i)if(s.result.status==="dirty")return t.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map((s)=>new Kt(s.ctx.common.issues));return le(t,{code:ne.invalid_union,unionErrors:a}),we}if(t.common.async)return Promise.all(n.map(async(i)=>{let a={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(o);else{let i=void 0,a=[];for(let l of n){let c={...t,common:{...t.common,issues:[]},parent:null},u=l._parseSync({data:t.data,path:t.path,parent:c});if(u.status==="valid")return u;else if(u.status==="dirty"&&!i)i={result:u,ctx:c};if(c.common.issues.length)a.push(c.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let s=a.map((l)=>new Kt(l));return le(t,{code:ne.invalid_union,unionErrors:s}),we}}get options(){return this._def.options}}si.create=(e,t)=>new si({options:e,typeName:oe.ZodUnion,...Pe(t)});var qr=(e)=>{if(e instanceof ci)return qr(e.schema);else if(e instanceof Rr)return qr(e.innerType());else if(e instanceof ui)return[e.value];else if(e instanceof An)return e.options;else if(e instanceof di)return $e.objectValues(e.enum);else if(e instanceof pi)return qr(e._def.innerType);else if(e instanceof ii)return[void 0];else if(e instanceof ai)return[null];else if(e instanceof kr)return[void 0,...qr(e.unwrap())];else if(e instanceof pn)return[null,...qr(e.unwrap())];else if(e instanceof hl)return qr(e.unwrap());else if(e instanceof gi)return qr(e.unwrap());else if(e instanceof mi)return qr(e._def.innerType);else return[]};class fl extends ze{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ae.object)return le(t,{code:ne.invalid_type,expected:ae.object,received:t.parsedType}),we;let n=this.discriminator,o=t.data[n],i=this.optionsMap.get(o);if(!i)return le(t,{code:ne.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),we;if(t.common.async)return i._parseAsync({data:t.data,path:t.path,parent:t});else return i._parseSync({data:t.data,path:t.path,parent:t})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let o=new Map;for(let i of t){let a=qr(i.shape[e]);if(!a.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let s of a){if(o.has(s))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);o.set(s,i)}}return new fl({typeName:oe.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:o,...Pe(n)})}}function gl(e,t){let n=Lr(e),o=Lr(t);if(e===t)return{valid:!0,data:e};else if(n===ae.object&&o===ae.object){let i=$e.objectKeys(t),a=$e.objectKeys(e).filter((l)=>i.indexOf(l)!==-1),s={...e,...t};for(let l of a){let c=gl(e[l],t[l]);if(!c.valid)return{valid:!1};s[l]=c.data}return{valid:!0,data:s}}else if(n===ae.array&&o===ae.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let a=0;a<e.length;a++){let s=e[a],l=t[a],c=gl(s,l);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else if(n===ae.date&&o===ae.date&&+e===+t)return{valid:!0,data:e};else return{valid:!1}}class li extends ze{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),o=(i,a)=>{if(dl(i)||dl(a))return we;let s=gl(i.value,a.value);if(!s.valid)return le(n,{code:ne.invalid_intersection_types}),we;if(pl(i)||pl(a))t.dirty();return{status:t.value,value:s.data}};if(n.common.async)return Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,a])=>o(i,a));else return o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}li.create=(e,t,n)=>new li({left:e,right:t,typeName:oe.ZodIntersection,...Pe(n)});class Gr extends ze{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==ae.array)return le(n,{code:ne.invalid_type,expected:ae.array,received:n.parsedType}),we;if(n.data.length<this._def.items.length)return le(n,{code:ne.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),we;if(!this._def.rest&&n.data.length>this._def.items.length)le(n,{code:ne.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty();let i=[...n.data].map((a,s)=>{let l=this._def.items[s]||this._def.rest;if(!l)return null;return l._parse(new ur(n,a,n.path,s))}).filter((a)=>!!a);if(n.common.async)return Promise.all(i).then((a)=>Ot.mergeArray(t,a));else return Ot.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new Gr({...this._def,rest:e})}}Gr.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new Gr({items:e,typeName:oe.ZodTuple,rest:null,...Pe(t)})};class Ia extends ze{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==ae.object)return le(n,{code:ne.invalid_type,expected:ae.object,received:n.parsedType}),we;let o=[],i=this._def.keyType,a=this._def.valueType;for(let s in n.data)o.push({key:i._parse(new ur(n,s,n.path,s)),value:a._parse(new ur(n,n.data[s],n.path,s)),alwaysSet:s in n.data});if(n.common.async)return Ot.mergeObjectAsync(t,o);else return Ot.mergeObjectSync(t,o)}get element(){return this._def.valueType}static create(e,t,n){if(t instanceof ze)return new Ia({keyType:e,valueType:t,typeName:oe.ZodRecord,...Pe(n)});return new Ia({keyType:Fr.create(),valueType:e,typeName:oe.ZodRecord,...Pe(t)})}}class Ca extends ze{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==ae.map)return le(n,{code:ne.invalid_type,expected:ae.map,received:n.parsedType}),we;let o=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([s,l],c)=>({key:o._parse(new ur(n,s,n.path,[c,"key"])),value:i._parse(new ur(n,l,n.path,[c,"value"]))}));if(n.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let l of a){let c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return we;if(c.status==="dirty"||u.status==="dirty")t.dirty();s.set(c.value,u.value)}return{status:t.value,value:s}})}else{let s=new Map;for(let l of a){let{key:c,value:u}=l;if(c.status==="aborted"||u.status==="aborted")return we;if(c.status==="dirty"||u.status==="dirty")t.dirty();s.set(c.value,u.value)}return{status:t.value,value:s}}}}Ca.create=(e,t,n)=>new Ca({valueType:t,keyType:e,typeName:oe.ZodMap,...Pe(n)});class io extends ze{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==ae.set)return le(n,{code:ne.invalid_type,expected:ae.set,received:n.parsedType}),we;let o=this._def;if(o.minSize!==null){if(n.data.size<o.minSize.value)le(n,{code:ne.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),t.dirty()}if(o.maxSize!==null){if(n.data.size>o.maxSize.value)le(n,{code:ne.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),t.dirty()}let i=this._def.valueType;function a(l){let c=new Set;for(let u of l){if(u.status==="aborted")return we;if(u.status==="dirty")t.dirty();c.add(u.value)}return{status:t.value,value:c}}let s=[...n.data.values()].map((l,c)=>i._parse(new ur(n,l,n.path,c)));if(n.common.async)return Promise.all(s).then((l)=>a(l));else return a(s)}min(e,t){return new io({...this._def,minSize:{value:e,message:ge.toString(t)}})}max(e,t){return new io({...this._def,maxSize:{value:e,message:ge.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}io.create=(e,t)=>new io({valueType:e,minSize:null,maxSize:null,typeName:oe.ZodSet,...Pe(t)});class ni extends ze{constructor(){super(...arguments);this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ae.function)return le(t,{code:ne.invalid_type,expected:ae.function,received:t.parsedType}),we;function n(s,l){return _a({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ti(),dn].filter((c)=>!!c),issueData:{code:ne.invalid_arguments,argumentsError:l}})}function o(s,l){return _a({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ti(),dn].filter((c)=>!!c),issueData:{code:ne.invalid_return_type,returnTypeError:l}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof ao){let s=this;return $t(async function(...l){let c=new Kt([]),u=await s._def.args.parseAsync(l,i).catch((p)=>{throw c.addIssue(n(l,p)),c}),d=await Reflect.apply(a,this,u);return await s._def.returns._def.type.parseAsync(d,i).catch((p)=>{throw c.addIssue(o(d,p)),c})})}else{let s=this;return $t(function(...l){let c=s._def.args.safeParse(l,i);if(!c.success)throw new Kt([n(l,c.error)]);let u=Reflect.apply(a,this,c.data),d=s._def.returns.safeParse(u,i);if(!d.success)throw new Kt([o(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ni({...this._def,args:Gr.create(e).rest(En.create())})}returns(e){return new ni({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new ni({args:e?e:Gr.create([]).rest(En.create()),returns:t||En.create(),typeName:oe.ZodFunction,...Pe(n)})}}class ci extends ze{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ci.create=(e,t)=>new ci({getter:e,typeName:oe.ZodLazy,...Pe(t)});class ui extends ze{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return le(t,{received:t.data,code:ne.invalid_literal,expected:this._def.value}),we}return{status:"valid",value:e.data}}get value(){return this._def.value}}ui.create=(e,t)=>new ui({value:e,typeName:oe.ZodLiteral,...Pe(t)});function jm(e,t){return new An({values:e,typeName:oe.ZodEnum,...Pe(t)})}class An extends ze{_parse(e){if(typeof e.data!=="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return le(t,{expected:$e.joinValues(n),received:t.parsedType,code:ne.invalid_type}),we}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return le(t,{received:t.data,code:ne.invalid_enum_value,options:n}),we}return $t(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return An.create(e,{...this._def,...t})}exclude(e,t=this._def){return An.create(this.options.filter((n)=>!e.includes(n)),{...this._def,...t})}}An.create=jm;class di extends ze{_parse(e){let t=$e.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==ae.string&&n.parsedType!==ae.number){let o=$e.objectValues(t);return le(n,{expected:$e.joinValues(o),received:n.parsedType,code:ne.invalid_type}),we}if(!this._cache)this._cache=new Set($e.getValidEnumValues(this._def.values));if(!this._cache.has(e.data)){let o=$e.objectValues(t);return le(n,{received:n.data,code:ne.invalid_enum_value,options:o}),we}return $t(e.data)}get enum(){return this._def.values}}di.create=(e,t)=>new di({values:e,typeName:oe.ZodNativeEnum,...Pe(t)});class ao extends ze{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ae.promise&&t.common.async===!1)return le(t,{code:ne.invalid_type,expected:ae.promise,received:t.parsedType}),we;let n=t.parsedType===ae.promise?t.data:Promise.resolve(t.data);return $t(n.then((o)=>this._def.type.parseAsync(o,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ao.create=(e,t)=>new ao({type:e,typeName:oe.ZodPromise,...Pe(t)});class Rr extends ze{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===oe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),o=this._def.effect||null,i={addIssue:(a)=>{if(le(n,a),a.fatal)t.abort();else t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){let a=o.transform(n.data,i);if(n.common.async)return Promise.resolve(a).then(async(s)=>{if(t.value==="aborted")return we;let l=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});if(l.status==="aborted")return we;if(l.status==="dirty")return to(l.value);if(t.value==="dirty")return to(l.value);return l});else{if(t.value==="aborted")return we;let s=this._def.schema._parseSync({data:a,path:n.path,parent:n});if(s.status==="aborted")return we;if(s.status==="dirty")return to(s.value);if(t.value==="dirty")return to(s.value);return s}}if(o.type==="refinement"){let a=(s)=>{let l=o.refinement(s,i);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(s.status==="aborted")return we;if(s.status==="dirty")t.dirty();return a(s.value),{status:t.value,value:s.value}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((s)=>{if(s.status==="aborted")return we;if(s.status==="dirty")t.dirty();return a(s.value).then(()=>({status:t.value,value:s.value}))})}if(o.type==="transform")if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Rn(a))return we;let s=o.transform(a.value,i);if(s instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:s}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((a)=>{if(!Rn(a))return we;return Promise.resolve(o.transform(a.value,i)).then((s)=>({status:t.value,value:s}))});$e.assertNever(o)}}Rr.create=(e,t,n)=>new Rr({schema:e,typeName:oe.ZodEffects,effect:t,...Pe(n)});Rr.createWithPreprocess=(e,t,n)=>new Rr({schema:t,effect:{type:"preprocess",transform:e},typeName:oe.ZodEffects,...Pe(n)});class kr extends ze{_parse(e){if(this._getType(e)===ae.undefined)return $t(void 0);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}kr.create=(e,t)=>new kr({innerType:e,typeName:oe.ZodOptional,...Pe(t)});class pn extends ze{_parse(e){if(this._getType(e)===ae.null)return $t(null);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}pn.create=(e,t)=>new pn({innerType:e,typeName:oe.ZodNullable,...Pe(t)});class pi extends ze{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;if(t.parsedType===ae.undefined)n=this._def.defaultValue();return this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}pi.create=(e,t)=>new pi({innerType:e,typeName:oe.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...Pe(t)});class mi extends ze{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});if(ri(o))return o.then((i)=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Kt(n.common.issues)},input:n.data})}));else return{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Kt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}mi.create=(e,t)=>new mi({innerType:e,typeName:oe.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...Pe(t)});class ka extends ze{_parse(e){if(this._getType(e)!==ae.nan){let n=this._getOrReturnCtx(e);return le(n,{code:ne.invalid_type,expected:ae.nan,received:n.parsedType}),we}return{status:"valid",value:e.data}}}ka.create=(e)=>new ka({typeName:oe.ZodNaN,...Pe(e)});var W4=Symbol("zod_brand");class hl extends ze{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class Ra extends ze{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});if(i.status==="aborted")return we;if(i.status==="dirty")return t.dirty(),to(i.value);else return this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();else{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});if(o.status==="aborted")return we;if(o.status==="dirty")return t.dirty(),{status:"dirty",value:o.value};else return this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,t){return new Ra({in:e,out:t,typeName:oe.ZodPipeline})}}class gi extends ze{_parse(e){let t=this._def.innerType._parse(e),n=(o)=>{if(Rn(o))o.value=Object.freeze(o.value);return o};return ri(t)?t.then((o)=>n(o)):n(t)}unwrap(){return this._def.innerType}}gi.create=(e,t)=>new gi({innerType:e,typeName:oe.ZodReadonly,...Pe(t)});var V4={object:dt.lazycreate},oe;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(oe||(oe={}));var Z4=Fr.create,K4=no.create,Y4=ka.create,Q4=oo.create,X4=Sa.create,eH=oi.create,tH=wa.create,rH=ii.create,nH=ai.create,oH=xa.create,iH=En.create,aH=Br.create,sH=Ta.create,lH=Cr.create,cH=dt.create,uH=dt.strictCreate,dH=si.create,pH=fl.create,mH=li.create,gH=Gr.create,fH=Ia.create,hH=Ca.create,yH=io.create,vH=ni.create,bH=ci.create,_H=ui.create,SH=An.create,wH=di.create,xH=ao.create,TH=Rr.create,IH=kr.create,CH=pn.create,kH=Rr.createWithPreprocess,RH=Ra.create;class Ea extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}var Om=10,uk=13,Pn=32;function yl(e){}function zm(e){if(typeof e=="function")throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=yl,onError:n=yl,onRetry:o=yl,onComment:i,maxBufferSize:a}=e,s=[],l=0,c=!0,u,d="",m=0,p,f=!1;function g(_){if(f)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,_.charCodeAt(0)===239&&_.charCodeAt(1)===187&&_.charCodeAt(2)===191&&(_=_.slice(3))),s.length===0){let b=v(_);b!==""&&(s.push(b),l=b.length),h();return}if(_.indexOf(`
25
+ `)===-1&&_.indexOf("\r")===-1){s.push(_),l+=_.length,h();return}s.push(_);let C=s.join("");s.length=0,l=0;let I=v(C);I!==""&&(s.push(I),l=I.length),h()}function h(){a!==void 0&&(l+d.length<=a||(f=!0,s.length=0,l=0,u=void 0,d="",m=0,p=void 0,n(new Ea(`Buffered data exceeded max buffer size of ${a} characters`,{type:"max-buffer-size-exceeded"}))))}function v(_){let C=0;if(_.indexOf("\r")===-1){let I=_.indexOf(`
26
+ `,C);for(;I!==-1;){if(C===I){m>0&&t({id:u,event:p,data:d}),u=void 0,d="",m=0,p=void 0,C=I+1,I=_.indexOf(`
27
+ `,C);continue}let b=_.charCodeAt(C);if(Nm(_,C,b)){let E=_.charCodeAt(C+5)===Pn?C+6:C+5,B=_.slice(E,I);if(m===0&&_.charCodeAt(I+1)===Om){t({id:u,event:p,data:B}),u=void 0,d="",p=void 0,C=I+2,I=_.indexOf(`
28
+ `,C);continue}d=m===0?B:`${d}
29
+ ${B}`,m++}else Dm(_,C,b)?p=_.slice(_.charCodeAt(C+6)===Pn?C+7:C+6,I)||void 0:x(_,C,I);C=I+1,I=_.indexOf(`
30
+ `,C)}return _.slice(C)}for(;C<_.length;){let I=_.indexOf("\r",C),b=_.indexOf(`
31
+ `,C),E=-1;if(I!==-1&&b!==-1?E=I<b?I:b:I!==-1?I===_.length-1?E=-1:E=I:b!==-1&&(E=b),E===-1)break;x(_,C,E),C=E+1,_.charCodeAt(C-1)===uk&&_.charCodeAt(C)===Om&&C++}return _.slice(C)}function x(_,C,I){if(C===I){y();return}let b=_.charCodeAt(C);if(Nm(_,C,b)){let N=_.charCodeAt(C+5)===Pn?C+6:C+5,re=_.slice(N,I);d=m===0?re:`${d}
32
+ ${re}`,m++;return}if(Dm(_,C,b)){p=_.slice(_.charCodeAt(C+6)===Pn?C+7:C+6,I)||void 0;return}if(b===105&&_.charCodeAt(C+1)===100&&_.charCodeAt(C+2)===58){let N=_.slice(_.charCodeAt(C+3)===Pn?C+4:C+3,I);u=N.includes("\x00")?void 0:N;return}if(b===58){if(i){let N=_.slice(C,I);i(N.slice(_.charCodeAt(C+1)===Pn?2:1))}return}let E=_.slice(C,I),B=E.indexOf(":");if(B===-1){S(E,"",E);return}let R=E.slice(0,B),U=E.charCodeAt(B+1)===Pn?2:1,z=E.slice(B+U);S(R,z,E)}function S(_,C,I){switch(_){case"event":p=C||void 0;break;case"data":d=m===0?C:`${d}
33
+ ${C}`,m++;break;case"id":u=C.includes("\x00")?void 0:C;break;case"retry":/^\d+$/.test(C)?o(parseInt(C,10)):n(new Ea(`Invalid \`retry\` value: "${C}"`,{type:"invalid-retry",value:C,line:I}));break;default:n(new Ea(`Unknown field "${_.length>20?`${_.slice(0,20)}\u2026`:_}"`,{type:"unknown-field",field:_,value:C,line:I}));break}}function y(){m>0&&t({id:u,event:p,data:d}),u=void 0,d="",m=0,p=void 0}function w(_={}){if(_.consume&&s.length>0){let C=s.join("");x(C,0,C.length)}c=!0,u=void 0,d="",m=0,p=void 0,s.length=0,l=0,f=!1}return{feed:g,reset:w}}function Nm(e,t,n){return n===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function Dm(e,t,n){return n===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}class vl extends TransformStream{constructor({onError:e,onRetry:t,onComment:n,maxBufferSize:o}={}){let i;super({start(a){i=zm({onEvent:(s)=>{a.enqueue(s)},onError(s){typeof e=="function"&&e(s),(e==="terminate"||s.type==="max-buffer-size-exceeded")&&a.error(s)},onRetry:t,onComment:n,maxBufferSize:o})},transform(a){i.feed(a)}})}}function _e(...e){return e.reduce((t,n)=>({...t,...n!=null?n:{}}),{})}function Aa({tools:e=[],providerToolNames:t,resolveProviderToolName:n}){var o;let i={},a={};for(let s of e)if(s.type==="provider"){let l=(o=n==null?void 0:n(s))!=null?o:(s.id in t)?t[s.id]:void 0;if(l==null)continue;i[s.name]=l,a[l]=s.name}return{toProviderToolName:(s)=>{var l;return(l=i[s])!=null?l:s},toCustomToolName:(s)=>{var l;return(l=a[s])!=null?l:s}}}async function Jr(e,t){if(e==null)return Promise.resolve();let n=t==null?void 0:t.abortSignal;return new Promise((o,i)=>{if(n==null?void 0:n.aborted){i(Um());return}let a=setTimeout(()=>{s(),o()},e),s=()=>{clearTimeout(a),n==null||n.removeEventListener("abort",l)},l=()=>{s(),i(Um())};n==null||n.addEventListener("abort",l)})}function Um(){return new DOMException("Delay was aborted","AbortError")}var jn=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){if(this._promise)return this._promise;return this._promise=new Promise((e,t)=>{if(this.status.type==="resolved")e(this.status.value);else if(this.status.type==="rejected")t(this.status.error);this._resolve=e,this._reject=t}),this._promise}resolve(e){var t;if(this.status={type:"resolved",value:e},this._promise)(t=this._resolve)==null||t.call(this,e)}reject(e){var t;if(this.status={type:"rejected",error:e},this._promise)(t=this._reject)==null||t.call(this,e)}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function so(e){return Object.fromEntries([...e.headers])}var{btoa:dk,atob:pk}=globalThis;function wt(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=pk(t);return Uint8Array.from(n,(o)=>o.codePointAt(0))}function Nt(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return dk(t)}function bt(e){return e instanceof Uint8Array?Nt(e):e}function Hm(e,t={}){let{useArrayBrackets:n=!0}=t,o=new FormData;for(let[i,a]of Object.entries(e)){if(a==null)continue;if(Array.isArray(a)){if(a.length===1){o.append(i,a[0]);continue}let s=n?`${i}[]`:i;for(let l of a)o.append(s,l);continue}o.append(i,a)}return o}async function fi(e){var t;try{await((t=e.body)==null?void 0:t.cancel())}catch(n){}}var Wm="AI_DownloadError",Vm=`vercel.ai.error.${Wm}`,mk=Symbol.for(Vm),$m,Lm,Et=class extends(Lm=ie,$m=mk,Lm){constructor({url:e,statusCode:t,statusText:n,cause:o,message:i=o==null?`Failed to download ${e}: ${t} ${n}`:`Failed to download ${e}: ${o}`}){super({name:Wm,message:i,cause:o});this[$m]=!0,this.url=e,this.statusCode=t,this.statusText=n}static isInstance(e){return ie.hasMarker(e,Vm)}};function gk(e=globalThis){return e.window!=null}function fk(e){let t;try{t=new URL(e)}catch(o){throw new Et({url:e,message:`Invalid URL: ${e}`})}if(t.protocol==="data:")return;if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Et({url:e,message:`URL scheme must be http, https, or data, got ${t.protocol}`});let n=t.hostname.toLowerCase().replace(/\.+$/,"");if(!n)throw new Et({url:e,message:"URL must have a hostname"});if(n==="localhost"||n.endsWith(".local")||n.endsWith(".localhost"))throw new Et({url:e,message:`URL with hostname ${n} is not allowed`});if(n.startsWith("[")&&n.endsWith("]")){let o=n.slice(1,-1);if(yk(o))throw new Et({url:e,message:`URL with IPv6 address ${n} is not allowed`});return}if(Zm(n)){if(Km(n))throw new Et({url:e,message:`URL with IP address ${n} is not allowed`});return}}function Zm(e){let t=e.split(".");if(t.length!==4)return!1;return t.every((n)=>{let o=Number(n);return Number.isInteger(o)&&o>=0&&o<=255&&String(o)===n})}function Km(e){let t=e.split(".").map(Number),[n,o,i]=t;if(n===0)return!0;if(n===10)return!0;if(n===100&&o>=64&&o<=127)return!0;if(n===127)return!0;if(n===169&&o===254)return!0;if(n===172&&o>=16&&o<=31)return!0;if(n===192&&o===0&&i===0)return!0;if(n===192&&o===168)return!0;if(n===198&&(o===18||o===19))return!0;if(n>=240)return!0;return!1}function hk(e){let t=e.toLowerCase(),n=t.indexOf("%");if(n!==-1)t=t.slice(0,n);let o=t.split("::");if(o.length>2)return null;let i=(s)=>{if(s==="")return[];let l=[],c=s.split(":");for(let u=0;u<c.length;u++){let d=c[u];if(d.includes(".")){if(u!==c.length-1||!Zm(d))return null;let[m,p,f,g]=d.split(".").map(Number);l.push(m<<8|p,f<<8|g);continue}if(!/^[0-9a-f]{1,4}$/.test(d))return null;l.push(parseInt(d,16))}return l},a=i(o[0]);if(a===null)return null;if(o.length===2){let s=i(o[1]);if(s===null)return null;let l=8-a.length-s.length;if(l<0)return null;return[...a,...Array(l).fill(0),...s]}return a.length===8?a:null}function yk(e){let t=hk(e);if(t===null)return!0;let n=(i)=>t.slice(0,i).every((a)=>a===0);if(n(7)&&(t[7]===0||t[7]===1))return!0;if((t[0]&65024)===64512)return!0;if((t[0]&65472)===65152)return!0;if((t[0]&65472)===65216)return!0;if((t[0]&65280)===65280)return!0;if(n(6)||n(5)&&t[5]===65535||n(4)&&t[4]===65535&&t[5]===0||t[0]===100&&t[1]===65435&&t[2]===0&&t[3]===0&&t[4]===0&&t[5]===0||t[0]===100&&t[1]===65435&&t[2]===1){let i=t[6]>>8&255,a=t[6]&255,s=t[7]>>8&255,l=t[7]&255;return Km(`${i}.${a}.${s}.${l}`)}return!1}var vk=10;async function xl({url:e,headers:t,abortSignal:n,maxRedirects:o=vk}){let i={signal:n};if(t!==void 0)i.headers=t;let a=e;for(let s=0;s<=o;s++){fk(a);let l=await fetch(a,{...i,redirect:"manual"});if(l.type==="opaqueredirect"){if(!gk())throw new Et({url:e,message:`Redirect from ${a} could not be validated and was blocked`});return await fetch(a,{...i,redirect:"follow"})}let c=l.headers.get("location");if(l.status>=300&&l.status<400&&c){await fi(l),a=new URL(c,a).toString();continue}return l}throw new Et({url:e,message:`Too many redirects (max ${o})`})}var Pa=2147483648;async function Ma({response:e,url:t,maxBytes:n=Pa}){let o=e.headers.get("content-length");if(o!=null){let d=parseInt(o,10);if(!isNaN(d)&&d>n)throw await fi(e),new Et({url:t,message:`Download of ${t} exceeded maximum size of ${n} bytes (Content-Length: ${d}).`})}let i=e.body;if(i==null)return new Uint8Array(0);let a=i.getReader(),s=[],l=0;try{while(!0){let{done:d,value:m}=await a.read();if(d)break;if(l+=m.length,l>n)throw new Et({url:t,message:`Download of ${t} exceeded maximum size of ${n} bytes.`});s.push(m)}}finally{try{await a.cancel()}finally{a.releaseLock()}}let c=new Uint8Array(l),u=0;for(let d of s)c.set(d,u),u+=d.length;return c}async function Tl(e,t){var n,o;try{let i=await xl({url:e,abortSignal:t==null?void 0:t.abortSignal});if(!i.ok)throw await fi(i),new Et({url:e,statusCode:i.status,statusText:i.statusText});let a=await Ma({response:i,url:e,maxBytes:(n=t==null?void 0:t.maxBytes)!=null?n:Pa}),s=(o=i.headers.get("content-type"))!=null?o:void 0;return new Blob([a],s?{type:s}:void 0)}catch(i){if(Et.isInstance(i))throw i;throw new Et({url:e,cause:i})}}var Er=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:o="-"}={})=>{let i=()=>{let a=n.length,s=Array(t);for(let l=0;l<t;l++)s[l]=n[Math.random()*a|0];return s.join("")};if(e==null)return i;if(n.includes(o))throw new eo({argument:"separator",message:`The separator "${o}" must not be part of the alphabet "${n}".`});return()=>`${e}${o}${i()}`},Le=Er();function hi(e){if(e==null)return"unknown error";if(typeof e==="string")return e;if(e instanceof Error)return e.message;return JSON.stringify(e)}function Yt(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var bk=["fetch failed","failed to fetch"],_k=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function Sk(e){if(!(e instanceof Error))return!1;let t=e.code;if(typeof t==="string"&&_k.includes(t))return!0;return!1}function Ym({error:e,url:t,requestBodyValues:n}){if(Yt(e))return e;if(e instanceof TypeError&&bk.includes(e.message.toLowerCase())){let o=e.cause;if(o!=null)return new De({message:`Cannot connect to API: ${o.message}`,cause:o,url:t,requestBodyValues:n,isRetryable:!0})}if(Sk(e))return new De({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:n,isRetryable:!0});return e}function lo(e=globalThis){var t,n,o;if(e.window)return"runtime/browser";if((t=e.navigator)==null?void 0:t.userAgent)return`runtime/${e.navigator.userAgent.toLowerCase()}`;if((o=(n=e.process)==null?void 0:n.versions)==null?void 0:o.node)return`runtime/node.js/${e.process.version.substring(0)}`;if(e.EdgeRuntime)return"runtime/vercel-edge";return"runtime/unknown"}function wk(e){if(e==null)return{};let t={};if(e instanceof Headers)e.forEach((n,o)=>{t[o.toLowerCase()]=n});else{if(!Array.isArray(e))e=Object.entries(e);for(let[n,o]of e)if(o!=null)t[n.toLowerCase()]=o}return t}function it(e,...t){let n=new Headers(wk(e)),o=n.get("user-agent")||"";return n.set("user-agent",[o,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}var Qm="4.0.37",xk=()=>globalThis.fetch,Xt=async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:o,abortSignal:i,fetch:a=xk()})=>{try{let s=await a(e,{method:"GET",headers:it(t,`ai-sdk/provider-utils/${Qm}`,lo()),signal:i}),l=so(s);if(!s.ok){let c;try{c=await o({response:s,url:e,requestBodyValues:{}})}catch(u){if(Yt(u)||De.isInstance(u))throw u;throw new De({message:"Failed to process error response",cause:u,statusCode:s.status,url:e,responseHeaders:l,requestBodyValues:{}})}throw c.value}try{return await n({response:s,url:e,requestBodyValues:{}})}catch(c){if(c instanceof Error){if(Yt(c)||De.isInstance(c))throw c}throw new De({message:"Failed to process successful response",cause:c,statusCode:s.status,url:e,responseHeaders:l,requestBodyValues:{}})}}catch(s){throw Ym({error:s,url:e,requestBodyValues:{}})}};function yi(e){return e!=null}function Xm(e,t){try{return new URL(e).origin===new URL(t).origin}catch(n){return!1}}function eg({mediaType:e,url:t,supportedUrls:n}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(n).map(([o,i])=>{let a=o.toLowerCase();return a==="*"||a==="*/*"?{mediaTypePrefix:"",regexes:i}:{mediaTypePrefix:a.replace(/\*/,""),regexes:i}}).filter(({mediaTypePrefix:o})=>e.startsWith(o)).flatMap(({regexes:o})=>o).some((o)=>o.test(t))}function co({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:o}){if(typeof e==="string")return e;if(e!=null)throw new Xo({message:`${o} API key must be a string.`});if(typeof process>"u")throw new Xo({message:`${o} API key is missing. Pass it using the '${n}' parameter. Environment variables are not supported in this environment.`});if(e=process.env[t],e==null)throw new Xo({message:`${o} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=="string")throw new Xo({message:`${o} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function Ar({settingValue:e,environmentVariableName:t}){if(typeof e==="string")return e;if(e!=null||typeof process>"u")return;if(e=process.env[t],e==null||typeof e!=="string")return;return e}function tg(e){var t;let[n,o=""]=e.toLowerCase().split("/");return(t={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[o])!=null?t:o}var Tk=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,Ik=/"(?: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 qm(e){let t=JSON.parse(e);if(t===null||typeof t!=="object")return t;if(Tk.test(e)===!1&&Ik.test(e)===!1)return t;return Ck(t)}function Ck(e){let t=[e];while(t.length){let n=t;t=[];for(let o of n){if(Object.prototype.hasOwnProperty.call(o,"__proto__"))throw SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(o,"constructor")&&o.constructor!==null&&typeof o.constructor==="object"&&Object.prototype.hasOwnProperty.call(o.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let i in o){let a=o[i];if(a&&typeof a==="object")t.push(a)}}}return e}function er(e){let{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch(n){return qm(e)}try{return qm(e)}finally{Error.stackTraceLimit=t}}function Il(e){if(e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")){e.additionalProperties=!1;let{properties:n}=e;if(n!=null)for(let o of Object.keys(n))n[o]=Mn(n[o])}if(e.items!=null)e.items=Array.isArray(e.items)?e.items.map(Mn):Mn(e.items);if(e.anyOf!=null)e.anyOf=e.anyOf.map(Mn);if(e.allOf!=null)e.allOf=e.allOf.map(Mn);if(e.oneOf!=null)e.oneOf=e.oneOf.map(Mn);let{definitions:t}=e;if(t!=null)for(let n of Object.keys(t))t[n]=Mn(t[n]);return e}function Mn(e){if(typeof e==="boolean")return e;return Il(e)}var kk=Symbol("Let zodToJsonSchema decide on which parser to use"),Fm={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"},Rk=(e)=>typeof e==="string"?{...Fm,name:e}:{...Fm,...e};function Qt(){return{}}function Ek(e,t){var n,o,i;let a={type:"array"};if(((n=e.type)==null?void 0:n._def)&&((i=(o=e.type)==null?void 0:o._def)==null?void 0:i.typeName)!==oe.ZodAny)a.items=Ve(e.type._def,{...t,currentPath:[...t.currentPath,"items"]});if(e.minLength)a.minItems=e.minLength.value;if(e.maxLength)a.maxItems=e.maxLength.value;if(e.exactLength)a.minItems=e.exactLength.value,a.maxItems=e.exactLength.value;return a}function Ak(e){let t={type:"integer",format:"int64"};if(!e.checks)return t;for(let n of e.checks)switch(n.kind){case"min":if(n.inclusive)t.minimum=n.value;else t.exclusiveMinimum=n.value;break;case"max":if(n.inclusive)t.maximum=n.value;else t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}function Pk(){return{type:"boolean"}}function rg(e,t){return Ve(e.type._def,t)}var Mk=(e,t)=>Ve(e.innerType._def,t);function ng(e,t,n){let o=n!=null?n:t.dateStrategy;if(Array.isArray(o))return{anyOf:o.map((i,a)=>ng(e,t,i))};switch(o){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return jk(e)}}var jk=(e)=>{let t={type:"integer",format:"unix-time"};for(let n of e.checks)switch(n.kind){case"min":t.minimum=n.value;break;case"max":t.maximum=n.value;break}return t};function Ok(e,t){return{...Ve(e.innerType._def,t),default:e.defaultValue()}}function Nk(e,t){return t.effectStrategy==="input"?Ve(e.schema._def,t):Qt()}function Dk(e){return{type:"string",enum:Array.from(e.values)}}var zk=(e)=>{if("type"in e&&e.type==="string")return!1;return"allOf"in e};function Uk(e,t){let n=[Ve(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Ve(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter((i)=>!!i),o=[];return n.forEach((i)=>{if(zk(i))o.push(...i.allOf);else{let a=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:s,...l}=i;a=l}o.push(a)}}),o.length?{allOf:o}:void 0}function $k(e){let t=typeof e.value;if(t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string")return{type:Array.isArray(e.value)?"array":"object"};return{type:t==="bigint"?"integer":t,const:e.value}}var bl=void 0,dr={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:()=>{if(bl===void 0)bl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return bl},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 og(e,t){let n={type:"string"};if(e.checks)for(let o of e.checks)switch(o.kind){case"min":n.minLength=typeof n.minLength==="number"?Math.max(n.minLength,o.value):o.value;break;case"max":n.maxLength=typeof n.maxLength==="number"?Math.min(n.maxLength,o.value):o.value;break;case"email":switch(t.emailStrategy){case"format:email":pr(n,"email",o.message,t);break;case"format:idn-email":pr(n,"idn-email",o.message,t);break;case"pattern:zod":Lt(n,dr.email,o.message,t);break}break;case"url":pr(n,"uri",o.message,t);break;case"uuid":pr(n,"uuid",o.message,t);break;case"regex":Lt(n,o.regex,o.message,t);break;case"cuid":Lt(n,dr.cuid,o.message,t);break;case"cuid2":Lt(n,dr.cuid2,o.message,t);break;case"startsWith":Lt(n,RegExp(`^${_l(o.value,t)}`),o.message,t);break;case"endsWith":Lt(n,RegExp(`${_l(o.value,t)}$`),o.message,t);break;case"datetime":pr(n,"date-time",o.message,t);break;case"date":pr(n,"date",o.message,t);break;case"time":pr(n,"time",o.message,t);break;case"duration":pr(n,"duration",o.message,t);break;case"length":n.minLength=typeof n.minLength==="number"?Math.max(n.minLength,o.value):o.value,n.maxLength=typeof n.maxLength==="number"?Math.min(n.maxLength,o.value):o.value;break;case"includes":{Lt(n,RegExp(_l(o.value,t)),o.message,t);break}case"ip":{if(o.version!=="v6")pr(n,"ipv4",o.message,t);if(o.version!=="v4")pr(n,"ipv6",o.message,t);break}case"base64url":Lt(n,dr.base64url,o.message,t);break;case"jwt":Lt(n,dr.jwt,o.message,t);break;case"cidr":{if(o.version!=="v6")Lt(n,dr.ipv4Cidr,o.message,t);if(o.version!=="v4")Lt(n,dr.ipv6Cidr,o.message,t);break}case"emoji":Lt(n,dr.emoji(),o.message,t);break;case"ulid":{Lt(n,dr.ulid,o.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{pr(n,"binary",o.message,t);break}case"contentEncoding:base64":{n.contentEncoding="base64";break}case"pattern:zod":{Lt(n,dr.base64,o.message,t);break}}break}case"nanoid":Lt(n,dr.nanoid,o.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function _l(e,t){return t.patternStrategy==="escape"?qk(e):e}var Lk=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function qk(e){let t="";for(let n=0;n<e.length;n++){if(!Lk.has(e[n]))t+="\\";t+=e[n]}return t}function pr(e,t,n,o){var i;if(e.format||((i=e.anyOf)==null?void 0:i.some((a)=>a.format))){if(!e.anyOf)e.anyOf=[];if(e.format)e.anyOf.push({format:e.format}),delete e.format;e.anyOf.push({format:t,...n&&o.errorMessages&&{errorMessage:{format:n}}})}else e.format=t}function Lt(e,t,n,o){var i;if(e.pattern||((i=e.allOf)==null?void 0:i.some((a)=>a.pattern))){if(!e.allOf)e.allOf=[];if(e.pattern)e.allOf.push({pattern:e.pattern}),delete e.pattern;e.allOf.push({pattern:Bm(t,o),...n&&o.errorMessages&&{errorMessage:{pattern:n}}})}else e.pattern=Bm(t,o)}function Bm(e,t){var n;if(!t.applyRegexFlags||!e.flags)return e.source;let o={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},i=o.i?e.source.toLowerCase():e.source,a="",s=!1,l=!1,c=!1;for(let u=0;u<i.length;u++){if(s){a+=i[u],s=!1;continue}if(o.i){if(l){if(i[u].match(/[a-z]/)){if(c)a+=i[u],a+=`${i[u-2]}-${i[u]}`.toUpperCase(),c=!1;else if(i[u+1]==="-"&&((n=i[u+2])==null?void 0:n.match(/[a-z]/)))a+=i[u],c=!0;else a+=`${i[u]}${i[u].toUpperCase()}`;continue}}else if(i[u].match(/[a-z]/)){a+=`[${i[u]}${i[u].toUpperCase()}]`;continue}}if(o.m){if(i[u]==="^"){a+=`(^|(?<=[\r
34
+ ]))`;continue}else if(i[u]==="$"){a+=`($|(?=[\r
35
+ ]))`;continue}}if(o.s&&i[u]==="."){a+=l?`${i[u]}\r
36
+ `:`[${i[u]}\r
37
+ ]`;continue}if(a+=i[u],i[u]==="\\")s=!0;else if(l&&i[u]==="]")l=!1;else if(!l&&i[u]==="[")l=!0}try{new RegExp(a)}catch(u){return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return a}function ig(e,t){var n,o,i,a,s,l;let c={type:"object",additionalProperties:(n=Ve(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?n:t.allowedAdditionalProperties};if(((o=e.keyType)==null?void 0:o._def.typeName)===oe.ZodString&&((i=e.keyType._def.checks)==null?void 0:i.length)){let{type:u,...d}=og(e.keyType._def,t);return{...c,propertyNames:d}}else if(((a=e.keyType)==null?void 0:a._def.typeName)===oe.ZodEnum)return{...c,propertyNames:{enum:e.keyType._def.values}};else if(((s=e.keyType)==null?void 0:s._def.typeName)===oe.ZodBranded&&e.keyType._def.type._def.typeName===oe.ZodString&&((l=e.keyType._def.type._def.checks)==null?void 0:l.length)){let{type:u,...d}=rg(e.keyType._def,t);return{...c,propertyNames:d}}return c}function Fk(e,t){if(t.mapStrategy==="record")return ig(e,t);let n=Ve(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Qt(),o=Ve(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Qt();return{type:"array",maxItems:125,items:{type:"array",items:[n,o],minItems:2,maxItems:2}}}function Bk(e){let t=e.values,o=Object.keys(e.values).filter((a)=>typeof t[t[a]]!=="number").map((a)=>t[a]),i=Array.from(new Set(o.map((a)=>typeof a)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:o}}function Gk(){return{not:Qt()}}function Jk(){return{type:"null"}}var Sl={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Hk(e,t){let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every((o)=>(o._def.typeName in Sl)&&(!o._def.checks||!o._def.checks.length))){let o=n.reduce((i,a)=>{let s=Sl[a._def.typeName];return s&&!i.includes(s)?[...i,s]:i},[]);return{type:o.length>1?o:o[0]}}else if(n.every((o)=>o._def.typeName==="ZodLiteral"&&!o.description)){let o=n.reduce((i,a)=>{let s=typeof a._def.value;switch(s){case"string":case"number":case"boolean":return[...i,s];case"bigint":return[...i,"integer"];case"object":if(a._def.value===null)return[...i,"null"];case"symbol":case"undefined":case"function":default:return i}},[]);if(o.length===n.length){let i=o.filter((a,s,l)=>l.indexOf(a)===s);return{type:i.length>1?i:i[0],enum:n.reduce((a,s)=>a.includes(s._def.value)?a:[...a,s._def.value],[])}}}else if(n.every((o)=>o._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((o,i)=>[...o,...i._def.values.filter((a)=>!o.includes(a))],[])};return Wk(e,t)}var Wk=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((o,i)=>Ve(o._def,{...t,currentPath:[...t.currentPath,"anyOf",`${i}`]})).filter((o)=>!!o&&(!t.strictUnions||typeof o==="object"&&Object.keys(o).length>0));return n.length?{anyOf:n}:void 0};function Vk(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Sl[e.innerType._def.typeName],"null"]};let n=Ve(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function Zk(e){let t={type:"number"};if(!e.checks)return t;for(let n of e.checks)switch(n.kind){case"int":t.type="integer";break;case"min":if(n.inclusive)t.minimum=n.value;else t.exclusiveMinimum=n.value;break;case"max":if(n.inclusive)t.maximum=n.value;else t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}function Kk(e,t){let n={type:"object",properties:{}},o=[],i=e.shape();for(let s in i){let l=i[s];if(l===void 0||l._def===void 0)continue;let c=Qk(l),u=Ve(l._def,{...t,currentPath:[...t.currentPath,"properties",s],propertyPath:[...t.currentPath,"properties",s]});if(u===void 0)continue;if(n.properties[s]=u,!c)o.push(s)}if(o.length)n.required=o;let a=Yk(e,t);if(a!==void 0)n.additionalProperties=a;return n}function Yk(e,t){if(e.catchall._def.typeName!=="ZodNever")return Ve(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function Qk(e){try{return e.isOptional()}catch(t){return!0}}var Xk=(e,t)=>{var n;if(t.currentPath.toString()===((n=t.propertyPath)==null?void 0:n.toString()))return Ve(e.innerType._def,t);let o=Ve(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return o?{anyOf:[{not:Qt()},o]}:Qt()},eR=(e,t)=>{if(t.pipeStrategy==="input")return Ve(e.in._def,t);else if(t.pipeStrategy==="output")return Ve(e.out._def,t);let n=Ve(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),o=Ve(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,o].filter((i)=>i!==void 0)}};function tR(e,t){return Ve(e.type._def,t)}function rR(e,t){let o={type:"array",uniqueItems:!0,items:Ve(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};if(e.minSize)o.minItems=e.minSize.value;if(e.maxSize)o.maxItems=e.maxSize.value;return o}function nR(e,t){if(e.rest)return{type:"array",minItems:e.items.length,items:e.items.map((n,o)=>Ve(n._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((n,o)=>o===void 0?n:[...n,o],[]),additionalItems:Ve(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})};else return{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,o)=>Ve(n._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((n,o)=>o===void 0?n:[...n,o],[])}}function oR(){return{not:Qt()}}function iR(){return Qt()}var aR=(e,t)=>Ve(e.innerType._def,t),sR=(e,t,n)=>{switch(t){case oe.ZodString:return og(e,n);case oe.ZodNumber:return Zk(e);case oe.ZodObject:return Kk(e,n);case oe.ZodBigInt:return Ak(e);case oe.ZodBoolean:return Pk();case oe.ZodDate:return ng(e,n);case oe.ZodUndefined:return oR();case oe.ZodNull:return Jk();case oe.ZodArray:return Ek(e,n);case oe.ZodUnion:case oe.ZodDiscriminatedUnion:return Hk(e,n);case oe.ZodIntersection:return Uk(e,n);case oe.ZodTuple:return nR(e,n);case oe.ZodRecord:return ig(e,n);case oe.ZodLiteral:return $k(e);case oe.ZodEnum:return Dk(e);case oe.ZodNativeEnum:return Bk(e);case oe.ZodNullable:return Vk(e,n);case oe.ZodOptional:return Xk(e,n);case oe.ZodMap:return Fk(e,n);case oe.ZodSet:return rR(e,n);case oe.ZodLazy:return()=>e.getter()._def;case oe.ZodPromise:return tR(e,n);case oe.ZodNaN:case oe.ZodNever:return Gk();case oe.ZodEffects:return Nk(e,n);case oe.ZodAny:return Qt();case oe.ZodUnknown:return iR();case oe.ZodDefault:return Ok(e,n);case oe.ZodBranded:return rg(e,n);case oe.ZodReadonly:return aR(e,n);case oe.ZodCatch:return Mk(e,n);case oe.ZodPipeline:return eR(e,n);case oe.ZodFunction:case oe.ZodVoid:case oe.ZodSymbol:return;default:return((o)=>{return})(t)}},lR=(e,t)=>{let n=0;for(;n<e.length&&n<t.length;n++)if(e[n]!==t[n])break;return[(e.length-n).toString(),...t.slice(n)].join("/")};function Ve(e,t,n=!1){var o;let i=t.seen.get(e);if(t.override){let c=(o=t.override)==null?void 0:o.call(t,e,t,i,n);if(c!==kk)return c}if(i&&!n){let c=cR(i,t);if(c!==void 0)return c}let a={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,a);let s=sR(e,e.typeName,t),l=typeof s==="function"?Ve(s(),t):s;if(l)uR(e,t,l);if(t.postProcess){let c=t.postProcess(l,e,t);return a.jsonSchema=l,c}return a.jsonSchema=l,l}var cR=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:lR(t.currentPath,e.path)};case"none":case"seen":{if(e.path.length<t.currentPath.length&&e.path.every((n,o)=>t.currentPath[o]===n))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Qt();return t.$refStrategy==="seen"?Qt():void 0}}},uR=(e,t,n)=>{if(e.description)n.description=e.description;return n},dR=(e)=>{let t=Rk(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([o,i])=>[i._def,{def:i._def,path:[...t.basePath,t.definitionPath,o],jsonSchema:void 0}]))}},pR=(e,t)=>{var n;let o=dR(t),i=typeof t==="object"&&t.definitions?Object.entries(t.definitions).reduce((u,[d,m])=>{var p;return{...u,[d]:(p=Ve(m._def,{...o,currentPath:[...o.basePath,o.definitionPath,d]},!0))!=null?p:Qt()}},{}):void 0,a=typeof t==="string"?t:(t==null?void 0:t.nameStrategy)==="title"?void 0:t==null?void 0:t.name,s=(n=Ve(e._def,a===void 0?o:{...o,currentPath:[...o.basePath,o.definitionPath,a]},!1))!=null?n:Qt(),l=typeof t==="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;if(l!==void 0)s.title=l;let c=a===void 0?i?{...s,[o.definitionPath]:i}:s:{$ref:[...o.$refStrategy==="relative"?[]:o.basePath,o.definitionPath,a].join("/"),[o.definitionPath]:{...i,[a]:s}};return c.$schema="http://json-schema.org/draft-07/schema#",c},wl=Symbol.for("vercel.ai.schema");function j(e){let t;return()=>{if(t==null)t=e();return t}}function vi(e,{validate:t}={}){return{[wl]:!0,_type:void 0,get jsonSchema(){if(typeof e==="function")e=e();return e},validate:t}}function mR(e){return typeof e==="object"&&e!==null&&wl in e&&e[wl]===!0&&"jsonSchema"in e&&"validate"in e}function qt(e){return e==null?vi({type:"object",properties:{},additionalProperties:!1}):mR(e)?e:("~standard"in e)?e["~standard"].vendor==="zod"?M(e):gR(e):e()}function gR(e){return vi(()=>Il(e["~standard"].jsonSchema.input({target:"draft-07"})),{validate:async(t)=>{let n=await e["~standard"].validate(t);return"value"in n?{success:!0,value:n.value}:{success:!1,error:new vt({value:t,cause:n.issues})}}})}function fR(e,t){var n;let o=(n=t==null?void 0:t.useReferences)!=null?n:!1;return vi(()=>pR(e,{$refStrategy:o?"root":"none"}),{validate:async(i)=>{let a=await e.safeParseAsync(i);return a.success?{success:!0,value:a.data}:{success:!1,error:a.error}}})}function hR(e,t){var n;let o=(n=t==null?void 0:t.useReferences)!=null?n:!1;return vi(()=>Il(Gm(e,{target:"draft-7",io:"input",reused:o?"ref":"inline"})),{validate:async(i)=>{let a=await Jm(e,i);return a.success?{success:!0,value:a.data}:{success:!1,error:a.error}}})}function yR(e){return"_zod"in e}function M(e,t){if(yR(e))return hR(e,t);else return fR(e,t)}async function Ee({value:e,schema:t,context:n}){let o=await pt({value:e,schema:t,context:n});if(!o.success)throw vt.wrap({value:e,cause:o.error,context:n});return o.value}async function pt({value:e,schema:t,context:n}){let o=qt(t);try{if(o.validate==null)return{success:!0,value:e,rawValue:e};let i=await o.validate(e);if(i.success)return{success:!0,value:i.value,rawValue:e};return{success:!1,error:vt.wrap({value:e,cause:i.error,context:n}),rawValue:e}}catch(i){return{success:!1,error:vt.wrap({value:e,cause:i,context:n}),rawValue:e}}}async function Cl({text:e,schema:t}){try{let n=er(e);if(t==null)return n;return Ee({value:n,schema:t})}catch(n){if(kn.isInstance(n)||vt.isInstance(n))throw n;throw new kn({text:e,cause:n})}}async function xt({text:e,schema:t}){try{let n=er(e);if(t==null)return{success:!0,value:n,rawValue:n};return await pt({value:n,schema:t})}catch(n){return{success:!1,error:kn.isInstance(n)?n:new kn({text:e,cause:n}),rawValue:void 0}}}function ja({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new vl).pipeThrough(new TransformStream({async transform({data:n},o){if(n==="[DONE]")return;o.enqueue(await xt({text:n,schema:t}))}}))}async function Ue({provider:e,providerOptions:t,schema:n}){if((t==null?void 0:t[e])==null)return;let o=await pt({value:t[e],schema:n});if(!o.success)throw new eo({argument:"providerOptions",message:`invalid ${e} provider options`,cause:o.error});return o.value}var vR=()=>globalThis.fetch,Ie=async({url:e,headers:t,body:n,failedResponseHandler:o,successfulResponseHandler:i,abortSignal:a,fetch:s})=>ag({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:o,successfulResponseHandler:i,abortSignal:a,fetch:s}),Oa=async({url:e,headers:t,formData:n,failedResponseHandler:o,successfulResponseHandler:i,abortSignal:a,fetch:s})=>ag({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:o,successfulResponseHandler:i,abortSignal:a,fetch:s}),ag=async({url:e,headers:t={},body:n,successfulResponseHandler:o,failedResponseHandler:i,abortSignal:a,fetch:s=vR()})=>{try{let l=await s(e,{method:"POST",headers:it(t,`ai-sdk/provider-utils/${Qm}`,lo()),body:n.content,signal:a}),c=so(l);if(!l.ok){let u;try{u=await i({response:l,url:e,requestBodyValues:n.values})}catch(d){if(Yt(d)||De.isInstance(d))throw d;throw new De({message:"Failed to process error response",cause:d,statusCode:l.status,url:e,responseHeaders:c,requestBodyValues:n.values})}throw u.value}try{return await o({response:l,url:e,requestBodyValues:n.values})}catch(u){if(u instanceof Error){if(Yt(u)||De.isInstance(u))throw u}throw new De({message:"Failed to process successful response",cause:u,statusCode:l.status,url:e,responseHeaders:c,requestBodyValues:n.values})}}catch(l){throw Ym({error:l,url:e,requestBodyValues:n.values})}};function kl(e){return e}function Rl(e){return{...e,type:"dynamic"}}function Ge({id:e,inputSchema:t}){return({execute:n,outputSchema:o,needsApproval:i,toModelOutput:a,onInputStart:s,onInputDelta:l,onInputAvailable:c,...u})=>kl({type:"provider",id:e,args:u,inputSchema:t,outputSchema:o,execute:n,needsApproval:i,toModelOutput:a,onInputStart:s,onInputDelta:l,onInputAvailable:c})}function Te({id:e,inputSchema:t,outputSchema:n,supportsDeferredResults:o}){return({execute:i,needsApproval:a,toModelOutput:s,onInputStart:l,onInputDelta:c,onInputAvailable:u,...d})=>kl({type:"provider",id:e,args:d,inputSchema:t,outputSchema:n,execute:i,needsApproval:a,toModelOutput:s,onInputStart:l,onInputDelta:c,onInputAvailable:u,supportsDeferredResults:o})}async function Se(e){if(typeof e==="function")e=e();return Promise.resolve(e)}var sg=({maxRetries:e=2,initialDelayInMs:t=2000,backoffFactor:n=2,abortSignal:o,shouldRetry:i,getDelayInMs:a=({exponentialBackoffDelay:l})=>l,createRetryError:s=({message:l})=>Error(l)})=>async(l)=>lg(l,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:o,shouldRetry:i,getDelayInMs:a,createRetryError:s});async function lg(e,{maxRetries:t,delayInMs:n,backoffFactor:o,abortSignal:i,shouldRetry:a,getDelayInMs:s,createRetryError:l},c=[]){try{return await e()}catch(u){if(Yt(u))throw u;if(t===0)throw u;let d=hi(u),m=[...c,u],p=m.length;if(p>t)throw l({message:`Failed after ${p} attempts. Last error: ${d}`,reason:"maxRetriesExceeded",errors:m});if(await a(u)&&p<=t)return await Jr(s({error:u,exponentialBackoffDelay:n}),{abortSignal:i}),lg(e,{maxRetries:t,delayInMs:o*n,backoffFactor:o,abortSignal:i,shouldRetry:a,getDelayInMs:s,createRetryError:l},m);if(p===1)throw u;throw l({message:`Failed after ${p} attempts with non-retryable error: '${d}'`,reason:"errorNotRetryable",errors:m})}}var bR=new TextDecoder;async function cg({response:e,url:t}){return bR.decode(await Ma({response:e,url:t}))}var Qe=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:o,url:i,requestBodyValues:a})=>{let s=await cg({response:o,url:i}),l=so(o);if(s.trim()==="")return{responseHeaders:l,value:new De({message:o.statusText,url:i,requestBodyValues:a,statusCode:o.status,responseHeaders:l,responseBody:s,isRetryable:n==null?void 0:n(o)})};try{let c=await Cl({text:s,schema:e});return{responseHeaders:l,value:new De({message:t(c),url:i,requestBodyValues:a,statusCode:o.status,responseHeaders:l,responseBody:s,data:c,isRetryable:n==null?void 0:n(o,c)})}}catch(c){return{responseHeaders:l,value:new De({message:o.statusText,url:i,requestBodyValues:a,statusCode:o.status,responseHeaders:l,responseBody:s,isRetryable:n==null?void 0:n(o)})}}},Dt=(e)=>async({response:t})=>{let n=so(t);if(t.body==null)throw new am({});return{responseHeaders:n,value:ja({stream:t.body,schema:e})}},xe=(e)=>async({response:t,url:n,requestBodyValues:o})=>{let i=await cg({response:t,url:n}),a=await xt({text:i,schema:e}),s=so(t);if(!a.success)throw new De({message:"Invalid JSON response",cause:a.error,statusCode:t.status,responseHeaders:s,responseBody:i,url:n,requestBodyValues:o});return{responseHeaders:s,value:a.value,rawValue:a.rawValue}},ug=()=>async({response:e,url:t,requestBodyValues:n})=>{let o=so(e);if(!e.body)throw new De({message:"Response body is empty",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:o,responseBody:void 0});try{let i=await e.arrayBuffer();return{responseHeaders:o,value:new Uint8Array(i)}}catch(i){throw new De({message:"Failed to read response as array buffer",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:o,responseBody:void 0,cause:i})}};function mn(e){return e==null?void 0:e.replace(/\/$/,"")}function _R(e){return e!=null&&typeof e[Symbol.asyncIterator]==="function"}async function*dg({execute:e,input:t,options:n}){let o=e(t,n);if(_R(o)){let i;for await(let a of o)i=a,yield{type:"preliminary",output:a};yield{type:"final",output:i}}else yield{type:"final",output:await o}}var gf=On(Nl(),1),ff=On(Nl(),1),VR="vercel.ai.gateway.error",Dl=Symbol.for(VR),wg,xg,ft=class e extends(xg=Error,wg=Dl,xg){constructor({message:t,statusCode:n=500,cause:o,generationId:i,isRetryable:a=n!=null&&(n===408||n===409||n===429||n>=500)}){super(i?`${t} [${i}]`:t);this[wg]=!0,this.statusCode=n,this.cause=o,this.generationId=i,this.isRetryable=a}static isInstance(t){return e.hasMarker(t)}static hasMarker(t){return typeof t==="object"&&t!==null&&Dl in t&&t[Dl]===!0}},nf="GatewayAuthenticationError",ZR=`vercel.ai.gateway.error.${nf}`,Tg=Symbol.for(ZR),Ig,Cg,Na=class e extends(Cg=ft,Ig=Tg,Cg){constructor({message:t="Authentication failed",statusCode:n=401,cause:o,generationId:i}={}){super({message:t,statusCode:n,cause:o,generationId:i});this[Ig]=!0,this.name=nf,this.type="authentication_error"}static isInstance(t){return ft.hasMarker(t)&&Tg in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:n,message:o="Authentication failed",statusCode:i=401,cause:a,generationId:s}){let l;if(t)l=`AI Gateway authentication failed: Invalid API key.
38
+
39
+ Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
40
+
41
+ Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`;else if(n)l=`AI Gateway authentication failed: Invalid OIDC token.
42
+
43
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
44
+
45
+ Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`;else l=`AI Gateway authentication failed: No authentication provided.
46
+
47
+ Option 1 - API key:
48
+ Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
49
+ Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
50
+
51
+ Option 2 - OIDC token:
52
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`;return new e({message:l,statusCode:i,cause:a,generationId:s})}},of="GatewayInvalidRequestError",KR=`vercel.ai.gateway.error.${of}`,kg=Symbol.for(KR),Rg,Eg,YR=class extends(Eg=ft,Rg=kg,Eg){constructor({message:e="Invalid request",statusCode:t=400,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o});this[Rg]=!0,this.name=of,this.type="invalid_request_error"}static isInstance(e){return ft.hasMarker(e)&&kg in e}},af="GatewayRateLimitError",QR=`vercel.ai.gateway.error.${af}`,Ag=Symbol.for(QR),Pg,Mg,XR=class extends(Mg=ft,Pg=Ag,Mg){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o});this[Pg]=!0,this.name=af,this.type="rate_limit_exceeded"}static isInstance(e){return ft.hasMarker(e)&&Ag in e}},sf="GatewayModelNotFoundError",eE=`vercel.ai.gateway.error.${sf}`,jg=Symbol.for(eE),tE=j(()=>M(r.object({modelId:r.string()}))),Og,Ng,rE=class extends(Ng=ft,Og=jg,Ng){constructor({message:e="Model not found",statusCode:t=404,modelId:n,cause:o,generationId:i}={}){super({message:e,statusCode:t,cause:o,generationId:i});this[Og]=!0,this.name=sf,this.type="model_not_found",this.modelId=n}static isInstance(e){return ft.hasMarker(e)&&jg in e}},lf="GatewayInternalServerError",nE=`vercel.ai.gateway.error.${lf}`,Dg=Symbol.for(nE),zg,Ug,$g=class extends(Ug=ft,zg=Dg,Ug){constructor({message:e="Internal server error",statusCode:t=500,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o});this[zg]=!0,this.name=lf,this.type="internal_server_error"}static isInstance(e){return ft.hasMarker(e)&&Dg in e}},cf="GatewayFailedDependencyError",oE=`vercel.ai.gateway.error.${cf}`,Lg=Symbol.for(oE),qg,Fg,iE=class extends(Fg=ft,qg=Lg,Fg){constructor({message:e="Failed dependency",statusCode:t=424,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o});this[qg]=!0,this.name=cf,this.type="failed_dependency"}static isInstance(e){return ft.hasMarker(e)&&Lg in e}},uf="GatewayForbiddenError",aE=`vercel.ai.gateway.error.${uf}`,Bg=Symbol.for(aE),Gg,Jg,sE=class extends(Jg=ft,Gg=Bg,Jg){constructor({message:e="Forbidden",statusCode:t=403,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o});this[Gg]=!0,this.name=uf,this.type="forbidden"}static isInstance(e){return ft.hasMarker(e)&&Bg in e}},df="GatewayResponseError",lE=`vercel.ai.gateway.error.${df}`,Hg=Symbol.for(lE),Wg,Vg,cE=class extends(Vg=ft,Wg=Hg,Vg){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:n,validationError:o,cause:i,generationId:a}={}){super({message:e,statusCode:t,cause:i,generationId:a});this[Wg]=!0,this.name=df,this.type="response_error",this.response=n,this.validationError=o}static isInstance(e){return ft.hasMarker(e)&&Hg in e}};async function Zg({response:e,statusCode:t,defaultMessage:n="Gateway request failed",cause:o,authMethod:i}){var a;let s=await pt({value:e,schema:uE});if(!s.success){let m=typeof e==="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new cE({message:`Invalid error response format: ${n}`,statusCode:t,response:e,validationError:s.error,cause:o,generationId:m})}let l=s.value,c=l.error.type,u=l.error.message,d=(a=l.generationId)!=null?a:void 0;switch(c){case"authentication_error":return Na.createContextualError({apiKeyProvided:i==="api-key",oidcTokenProvided:i==="oidc",statusCode:t,cause:o,generationId:d});case"invalid_request_error":return new YR({message:u,statusCode:t,cause:o,generationId:d});case"rate_limit_exceeded":return new XR({message:u,statusCode:t,cause:o,generationId:d});case"model_not_found":{let m=await pt({value:l.error.param,schema:tE});return new rE({message:u,statusCode:t,modelId:m.success?m.value.modelId:void 0,cause:o,generationId:d})}case"internal_server_error":return new $g({message:u,statusCode:t,cause:o,generationId:d});case"failed_dependency":return new iE({message:u,statusCode:t,cause:o,generationId:d});case"forbidden":return new sE({message:u,statusCode:t,cause:o,generationId:d});default:return new $g({message:u,statusCode:t,cause:o,generationId:d})}}var uE=j(()=>M(r.object({error:r.object({message:r.string(),type:r.string().nullish(),param:r.unknown().nullish(),code:r.union([r.string(),r.number()]).nullish()}),generationId:r.string().nullish()})));function dE(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return er(e.responseBody)}catch(t){return e.responseBody}return{}}var pf="GatewayTimeoutError",pE=`vercel.ai.gateway.error.${pf}`,Kg=Symbol.for(pE),Yg,Qg,Xg=class e extends(Qg=ft,Yg=Kg,Qg){constructor({message:t="Request timed out",statusCode:n=408,cause:o,generationId:i}={}){super({message:t,statusCode:n,cause:o,generationId:i});this[Yg]=!0,this.name=pf,this.type="timeout_error"}static isInstance(t){return ft.hasMarker(t)&&Kg in t}static createTimeoutError({originalMessage:t,statusCode:n=408,cause:o,generationId:i}){let a=`Gateway request timed out: ${t}
53
+
54
+ This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;return new e({message:a,statusCode:n,cause:o,generationId:i})}};function ef(e){if(!(e instanceof Error))return!1;let t=e.code;if(typeof t==="string")return["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"].includes(t);return!1}async function zt(e,t){var n;if(ft.isInstance(e))return e;if(ef(e))return Xg.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e});if(De.isInstance(e)){if(e.cause&&ef(e.cause))return Xg.createTimeoutError({originalMessage:e.message,cause:e});return await Zg({response:dE(e),statusCode:(n=e.statusCode)!=null?n:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t})}return await Zg({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}var mf="ai-gateway-auth-method";async function tr(e){let t=await pt({value:e[mf],schema:mE});return t.success?t.value:void 0}var mE=j(()=>M(r.union([r.literal("api-key"),r.literal("oidc")]))),gE=["embedding","image","language","reranking","speech","transcription","video"],tf=class{constructor(e){this.config=e}async getAvailableModels(){try{let{value:e}=await Xt({url:`${this.config.baseURL}/config`,headers:await Se(this.config.headers()),successfulResponseHandler:xe(fE),failedResponseHandler:Qe({errorSchema:r.any(),errorToMessage:(t)=>t}),fetch:this.config.fetch});return e}catch(e){throw await zt(e)}}async getCredits(){try{let e=new URL(this.config.baseURL),{value:t}=await Xt({url:`${e.origin}/v1/credits`,headers:await Se(this.config.headers()),successfulResponseHandler:xe(hE),failedResponseHandler:Qe({errorSchema:r.any(),errorToMessage:(n)=>n}),fetch:this.config.fetch});return t}catch(e){throw await zt(e)}}},fE=j(()=>M(r.object({models:r.array(r.object({id:r.string(),name:r.string(),description:r.string().nullish(),pricing:r.object({input:r.string(),output:r.string(),input_cache_read:r.string().nullish(),input_cache_write:r.string().nullish()}).transform(({input:e,output:t,input_cache_read:n,input_cache_write:o})=>({input:e,output:t,...n?{cachedInputTokens:n}:{},...o?{cacheCreationInputTokens:o}:{}})).nullish(),specification:r.object({specificationVersion:r.literal("v3"),provider:r.string(),modelId:r.string()}),modelType:r.string().nullish()})).transform((e)=>e.filter((t)=>t.modelType==null||gE.includes(t.modelType)))}))),hE=j(()=>M(r.object({balance:r.string(),total_used:r.string()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),yE=class{constructor(e){this.config=e}async getSpendReport(e){try{let t=new URL(this.config.baseURL),n=new URLSearchParams;if(n.set("start_date",e.startDate),n.set("end_date",e.endDate),e.groupBy)n.set("group_by",e.groupBy);if(e.datePart)n.set("date_part",e.datePart);if(e.userId)n.set("user_id",e.userId);if(e.model)n.set("model",e.model);if(e.provider)n.set("provider",e.provider);if(e.credentialType)n.set("credential_type",e.credentialType);if(e.tags&&e.tags.length>0)n.set("tags",e.tags.join(","));let{value:o}=await Xt({url:`${t.origin}/v1/report?${n.toString()}`,headers:await Se(this.config.headers()),successfulResponseHandler:xe(vE),failedResponseHandler:Qe({errorSchema:r.any(),errorToMessage:(i)=>i}),fetch:this.config.fetch});return o}catch(t){throw await zt(t)}}},vE=j(()=>M(r.object({results:r.array(r.object({day:r.string().optional(),hour:r.string().optional(),user:r.string().optional(),model:r.string().optional(),tag:r.string().optional(),provider:r.string().optional(),credential_type:r.enum(["byok","system"]).optional(),total_cost:r.number(),market_cost:r.number().optional(),input_tokens:r.number().optional(),output_tokens:r.number().optional(),cached_input_tokens:r.number().optional(),cache_creation_input_tokens:r.number().optional(),reasoning_tokens:r.number().optional(),request_count:r.number().optional()}).transform(({credential_type:e,total_cost:t,market_cost:n,input_tokens:o,output_tokens:i,cached_input_tokens:a,cache_creation_input_tokens:s,reasoning_tokens:l,request_count:c,...u})=>({...u,...e!==void 0?{credentialType:e}:{},totalCost:t,...n!==void 0?{marketCost:n}:{},...o!==void 0?{inputTokens:o}:{},...i!==void 0?{outputTokens:i}:{},...a!==void 0?{cachedInputTokens:a}:{},...s!==void 0?{cacheCreationInputTokens:s}:{},...l!==void 0?{reasoningTokens:l}:{},...c!==void 0?{requestCount:c}:{}})))}))),bE=class{constructor(e){this.config=e}async getGenerationInfo(e){try{let t=new URL(this.config.baseURL),{value:n}=await Xt({url:`${t.origin}/v1/generation?id=${encodeURIComponent(e.id)}`,headers:await Se(this.config.headers()),successfulResponseHandler:xe(_E),failedResponseHandler:Qe({errorSchema:r.any(),errorToMessage:(o)=>o}),fetch:this.config.fetch});return n}catch(t){throw await zt(t)}}},_E=j(()=>M(r.object({data:r.object({id:r.string(),total_cost:r.number(),upstream_inference_cost:r.number(),usage:r.number(),created_at:r.string(),model:r.string(),is_byok:r.boolean(),provider_name:r.string(),streamed:r.boolean(),finish_reason:r.string(),latency:r.number(),generation_time:r.number(),native_tokens_prompt:r.number(),native_tokens_completion:r.number(),native_tokens_reasoning:r.number(),native_tokens_cached:r.number(),native_tokens_cache_creation:r.number(),billable_web_search_calls:r.number()}).transform(({total_cost:e,upstream_inference_cost:t,created_at:n,is_byok:o,provider_name:i,finish_reason:a,generation_time:s,native_tokens_prompt:l,native_tokens_completion:c,native_tokens_reasoning:u,native_tokens_cached:d,native_tokens_cache_creation:m,billable_web_search_calls:p,...f})=>({...f,totalCost:e,upstreamInferenceCost:t,createdAt:n,isByok:o,providerName:i,finishReason:a,generationTime:s,promptTokens:l,completionTokens:c,reasoningTokens:u,cachedTokens:d,cacheCreationTokens:m,billableWebSearchCalls:p}))}).transform(({data:e})=>e))),SE=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){let{abortSignal:t,...n}=e;return{args:this.maybeEncodeFileParts(n),warnings:[]}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{abortSignal:o}=e,i=await Se(this.config.headers());try{let{responseHeaders:a,value:s,rawValue:l}=await Ie({url:this.getUrl(),headers:_e(i,e.headers,this.getModelConfigHeaders(this.modelId,!1),await Se(this.config.o11yHeaders)),body:t,successfulResponseHandler:xe(r.any()),failedResponseHandler:Qe({errorSchema:r.any(),errorToMessage:(c)=>c}),...o&&{abortSignal:o},fetch:this.config.fetch});return{...s,request:{body:t},response:{headers:a,body:l},warnings:n}}catch(a){throw await zt(a,await tr(i))}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),{abortSignal:o}=e,i=await Se(this.config.headers());try{let{value:a,responseHeaders:s}=await Ie({url:this.getUrl(),headers:_e(i,e.headers,this.getModelConfigHeaders(this.modelId,!0),await Se(this.config.o11yHeaders)),body:t,successfulResponseHandler:Dt(r.any()),failedResponseHandler:Qe({errorSchema:r.any(),errorToMessage:(l)=>l}),...o&&{abortSignal:o},fetch:this.config.fetch});return{stream:a.pipeThrough(new TransformStream({start(l){if(n.length>0)l.enqueue({type:"stream-start",warnings:n})},transform(l,c){if(l.success){let u=l.value;if(u.type==="raw"&&!e.includeRawChunks)return;if(u.type==="response-metadata"&&u.timestamp&&typeof u.timestamp==="string")u.timestamp=new Date(u.timestamp);c.enqueue(u)}else c.error(l.error)}})),request:{body:t},response:{headers:s}}}catch(a){throw await zt(a,await tr(i))}}isFilePart(e){return e&&typeof e==="object"&&"type"in e&&e.type==="file"}maybeEncodeFileParts(e){for(let t of e.prompt)for(let n of t.content)if(this.isFilePart(n)){let o=n;if(o.data instanceof Uint8Array){let i=Uint8Array.from(o.data),a=Buffer.from(i).toString("base64");o.data=new URL(`data:${o.mediaType||"application/octet-stream"};base64,${a}`)}}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":"3","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},wE=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:o}){var i,a;let s=await Se(this.config.headers());try{let{responseHeaders:l,value:c,rawValue:u}=await Ie({url:this.getUrl(),headers:_e(s,t!=null?t:{},this.getModelConfigHeaders(),await Se(this.config.o11yHeaders)),body:{values:e,...o?{providerOptions:o}:{}},successfulResponseHandler:xe(TE),failedResponseHandler:Qe({errorSchema:r.any(),errorToMessage:(d)=>d}),...n&&{abortSignal:n},fetch:this.config.fetch});return{embeddings:c.embeddings,usage:(i=c.usage)!=null?i:void 0,providerMetadata:c.providerMetadata,response:{headers:l,body:u},warnings:(a=c.warnings)!=null?a:[]}}catch(l){throw await zt(l,await tr(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},xE=r.discriminatedUnion("type",[r.object({type:r.literal("unsupported"),feature:r.string(),details:r.string().optional()}),r.object({type:r.literal("compatibility"),feature:r.string(),details:r.string().optional()}),r.object({type:r.literal("other"),message:r.string()})]),TE=j(()=>M(r.object({embeddings:r.array(r.array(r.number())),usage:r.object({tokens:r.number()}).nullish(),warnings:r.array(xE).optional(),providerMetadata:r.record(r.string(),r.record(r.string(),r.unknown())).optional()})));function Da(e){return(e!=null?e:[]).map((t)=>t.type==="deprecated"?{type:"other",message:t.message}:t)}var IE=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:o,seed:i,files:a,mask:s,providerOptions:l,headers:c,abortSignal:u}){var d,m,p;let f=await Se(this.config.headers());try{let{responseHeaders:g,value:h,rawValue:v}=await Ie({url:this.getUrl(),headers:_e(f,c!=null?c:{},this.getModelConfigHeaders(),await Se(this.config.o11yHeaders)),body:{prompt:e,n:t,...n&&{size:n},...o&&{aspectRatio:o},...i&&{seed:i},...l&&{providerOptions:l},...a&&{files:a.map((x)=>rf(x))},...s&&{mask:rf(s)}},successfulResponseHandler:xe(EE),failedResponseHandler:Qe({errorSchema:r.any(),errorToMessage:(x)=>x}),...u&&{abortSignal:u},fetch:this.config.fetch});return{images:h.images,warnings:Da(h.warnings),providerMetadata:h.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:g},...h.usage!=null&&{usage:{inputTokens:(d=h.usage.inputTokens)!=null?d:void 0,outputTokens:(m=h.usage.outputTokens)!=null?m:void 0,totalTokens:(p=h.usage.totalTokens)!=null?p:void 0}}}}catch(g){throw await zt(g,await tr(f))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function rf(e){if(e.type==="file"&&e.data instanceof Uint8Array)return{...e,data:Nt(e.data)};return e}var CE=r.object({images:r.array(r.unknown()).optional()}).catchall(r.unknown()),kE=r.discriminatedUnion("type",[r.object({type:r.literal("unsupported"),feature:r.string(),details:r.string().optional()}),r.object({type:r.literal("compatibility"),feature:r.string(),details:r.string().optional()}),r.object({type:r.literal("deprecated"),setting:r.string(),message:r.string()}),r.object({type:r.literal("other"),message:r.string()})]),RE=r.object({inputTokens:r.number().nullish(),outputTokens:r.number().nullish(),totalTokens:r.number().nullish()}),EE=r.object({images:r.array(r.string()),warnings:r.array(kE).optional(),providerMetadata:r.record(r.string(),CE).optional(),usage:RE.optional()}),AE=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxVideosPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,aspectRatio:n,resolution:o,duration:i,fps:a,seed:s,generateAudio:l,image:c,frameImages:u,inputReferences:d,providerOptions:m,headers:p,abortSignal:f}){let g=await Se(this.config.headers());try{let{responseHeaders:h,value:v}=await Ie({url:this.getUrl(),headers:_e(g,p!=null?p:{},this.getModelConfigHeaders(),await Se(this.config.o11yHeaders),{accept:"text/event-stream"}),body:{prompt:e,n:t,...n&&{aspectRatio:n},...o&&{resolution:o},...i&&{duration:i},...a&&{fps:a},...s&&{seed:s},...l!==void 0&&{generateAudio:l},...m&&{providerOptions:m},...c&&{image:zl(c)},...u&&{frameImages:u.map((x)=>({...x,image:zl(x.image)}))},...d&&{inputReferences:d.map((x)=>zl(x))}},successfulResponseHandler:async({response:x,url:S,requestBodyValues:y})=>{if(x.body==null)throw new De({message:"SSE response body is empty",url:S,requestBodyValues:y,statusCode:x.status});let _=ja({stream:x.body,schema:OE}).getReader(),{done:C,value:I}=await _.read();if(_.releaseLock(),C||!I)throw new De({message:"SSE stream ended without a data event",url:S,requestBodyValues:y,statusCode:x.status});if(!I.success)throw new De({message:"Failed to parse video SSE event",cause:I.error,url:S,requestBodyValues:y,statusCode:x.status});let b=I.value;if(b.type==="error")throw new De({message:b.message,statusCode:b.statusCode,url:S,requestBodyValues:y,responseHeaders:Object.fromEntries([...x.headers]),responseBody:JSON.stringify(b),data:{error:{message:b.message,type:b.errorType,param:b.param}}});return{value:{videos:b.videos,warnings:b.warnings,providerMetadata:b.providerMetadata},responseHeaders:Object.fromEntries([...x.headers])}},failedResponseHandler:Qe({errorSchema:r.any(),errorToMessage:(x)=>x}),...f&&{abortSignal:f},fetch:this.config.fetch});return{videos:v.videos,warnings:Da(v.warnings),providerMetadata:v.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:h}}}catch(h){throw await zt(h,await tr(g))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}};function zl(e){if(e.type==="file"&&e.data instanceof Uint8Array)return{...e,data:Nt(e.data)};return e}var PE=r.object({videos:r.array(r.unknown()).optional()}).catchall(r.unknown()),ME=r.union([r.object({type:r.literal("url"),url:r.string(),mediaType:r.string()}),r.object({type:r.literal("base64"),data:r.string(),mediaType:r.string()})]),jE=r.discriminatedUnion("type",[r.object({type:r.literal("unsupported"),feature:r.string(),details:r.string().optional()}),r.object({type:r.literal("compatibility"),feature:r.string(),details:r.string().optional()}),r.object({type:r.literal("deprecated"),setting:r.string(),message:r.string()}),r.object({type:r.literal("other"),message:r.string()})]),OE=r.discriminatedUnion("type",[r.object({type:r.literal("result"),videos:r.array(ME),warnings:r.array(jE).optional(),providerMetadata:r.record(r.string(),PE).optional()}),r.object({type:r.literal("error"),message:r.string(),errorType:r.string(),statusCode:r.number(),param:r.unknown().nullable()})]),NE=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async doRerank({documents:e,query:t,topN:n,headers:o,abortSignal:i,providerOptions:a}){var s;let l=await Se(this.config.headers());try{let{responseHeaders:c,value:u,rawValue:d}=await Ie({url:this.getUrl(),headers:_e(l,o!=null?o:{},this.getModelConfigHeaders(),await Se(this.config.o11yHeaders)),body:{documents:e,query:t,...n!=null?{topN:n}:{},...a?{providerOptions:a}:{}},successfulResponseHandler:xe(zE),failedResponseHandler:Qe({errorSchema:r.any(),errorToMessage:(m)=>m}),...i&&{abortSignal:i},fetch:this.config.fetch});return{ranking:u.ranking,providerMetadata:u.providerMetadata,response:{headers:c,body:d},warnings:(s=u.warnings)!=null?s:[]}}catch(c){throw await zt(c,await tr(l))}}getUrl(){return`${this.config.baseURL}/reranking-model`}getModelConfigHeaders(){return{"ai-reranking-model-specification-version":"3","ai-model-id":this.modelId}}},DE=r.discriminatedUnion("type",[r.object({type:r.literal("unsupported"),feature:r.string(),details:r.string().optional()}),r.object({type:r.literal("compatibility"),feature:r.string(),details:r.string().optional()}),r.object({type:r.literal("other"),message:r.string()})]),zE=j(()=>M(r.object({ranking:r.array(r.object({index:r.number(),relevanceScore:r.number()})),warnings:r.array(DE).optional(),providerMetadata:r.record(r.string(),r.record(r.string(),r.unknown())).optional()}))),UE=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async doGenerate({text:e,voice:t,outputFormat:n,instructions:o,speed:i,language:a,providerOptions:s,headers:l,abortSignal:c}){let u=await Se(this.config.headers());try{let{responseHeaders:d,value:m,rawValue:p}=await Ie({url:this.getUrl(),headers:_e(u,l!=null?l:{},this.getModelConfigHeaders(),await Se(this.config.o11yHeaders)),body:{text:e,...t&&{voice:t},...n&&{outputFormat:n},...o&&{instructions:o},...i!=null&&{speed:i},...a&&{language:a},...s&&{providerOptions:s}},successfulResponseHandler:xe(qE),failedResponseHandler:Qe({errorSchema:r.any(),errorToMessage:(f)=>f}),...c&&{abortSignal:c},fetch:this.config.fetch});return{audio:m.audio,warnings:Da(m.warnings),providerMetadata:m.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:d,body:p}}}catch(d){throw await zt(d,await tr(u!=null?u:{}))}}getUrl(){return`${this.config.baseURL}/speech-model`}getModelConfigHeaders(){return{"ai-speech-model-specification-version":"3","ai-model-id":this.modelId}}},$E=r.object({}).catchall(r.unknown()),LE=r.discriminatedUnion("type",[r.object({type:r.literal("unsupported"),feature:r.string(),details:r.string().optional()}),r.object({type:r.literal("compatibility"),feature:r.string(),details:r.string().optional()}),r.object({type:r.literal("deprecated"),setting:r.string(),message:r.string()}),r.object({type:r.literal("other"),message:r.string()})]),qE=r.object({audio:r.string(),warnings:r.array(LE).optional(),providerMetadata:r.record(r.string(),$E).optional()}),FE=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async doGenerate({audio:e,mediaType:t,providerOptions:n,headers:o,abortSignal:i}){var a,s,l;let c=await Se(this.config.headers());try{let{responseHeaders:u,value:d,rawValue:m}=await Ie({url:this.getUrl(),headers:_e(c,o!=null?o:{},this.getModelConfigHeaders(),await Se(this.config.o11yHeaders)),body:{audio:e instanceof Uint8Array?Nt(e):e,mediaType:t,...n&&{providerOptions:n}},successfulResponseHandler:xe(JE),failedResponseHandler:Qe({errorSchema:r.any(),errorToMessage:(p)=>p}),...i&&{abortSignal:i},fetch:this.config.fetch});return{text:d.text,segments:(a=d.segments)!=null?a:[],language:(s=d.language)!=null?s:void 0,durationInSeconds:(l=d.durationInSeconds)!=null?l:void 0,warnings:Da(d.warnings),providerMetadata:d.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:u,body:m}}}catch(u){throw await zt(u,await tr(c!=null?c:{}))}}getUrl(){return`${this.config.baseURL}/transcription-model`}getModelConfigHeaders(){return{"ai-transcription-model-specification-version":"3","ai-model-id":this.modelId}}},BE=r.object({}).catchall(r.unknown()),GE=r.discriminatedUnion("type",[r.object({type:r.literal("unsupported"),feature:r.string(),details:r.string().optional()}),r.object({type:r.literal("compatibility"),feature:r.string(),details:r.string().optional()}),r.object({type:r.literal("deprecated"),setting:r.string(),message:r.string()}),r.object({type:r.literal("other"),message:r.string()})]),JE=r.object({text:r.string(),segments:r.array(r.object({text:r.string(),startSecond:r.number(),endSecond:r.number()})).optional(),language:r.string().nullish(),durationInSeconds:r.number().nullish(),warnings:r.array(GE).optional(),providerMetadata:r.record(r.string(),BE).optional()}),HE=j(()=>M(r.object({query:r.string().describe("Natural-language web search query. This is required."),type:r.enum(["auto","fast","instant"]).optional().describe("Search method. Use auto for the default balance of speed and quality."),num_results:r.number().optional().describe("Maximum number of results to return (1-100, default: 10)."),category:r.enum(["company","people","research paper","news","personal site","financial report"]).optional().describe("Optional content category to focus results."),user_location:r.string().optional().describe("Two-letter ISO country code such as 'US'."),include_domains:r.array(r.string()).optional().describe("Only return results from these domains."),exclude_domains:r.array(r.string()).optional().describe("Exclude results from these domains."),start_published_date:r.string().optional().describe("Only return links published after this ISO 8601 date."),end_published_date:r.string().optional().describe("Only return links published before this ISO 8601 date."),contents:r.object({text:r.union([r.boolean(),r.object({max_characters:r.number().optional(),include_html_tags:r.boolean().optional(),verbosity:r.enum(["compact","standard","full"]).optional(),include_sections:r.array(r.enum(["header","navigation","banner","body","sidebar","footer","metadata"])).optional(),exclude_sections:r.array(r.enum(["header","navigation","banner","body","sidebar","footer","metadata"])).optional()})]).optional(),highlights:r.union([r.boolean(),r.object({query:r.string().optional(),max_characters:r.number().optional()})]).optional(),max_age_hours:r.number().optional(),livecrawl_timeout:r.number().optional(),subpages:r.number().optional(),subpage_target:r.union([r.string(),r.array(r.string())]).optional(),extras:r.object({links:r.number().optional(),image_links:r.number().optional()}).optional()}).optional().describe("Controls extracted page content and freshness.")}))),WE=j(()=>M(r.union([r.object({requestId:r.string(),searchType:r.string().optional(),resolvedSearchType:r.string().optional(),results:r.array(r.object({title:r.string(),url:r.string(),id:r.string(),publishedDate:r.string().nullable().optional(),author:r.string().nullable().optional(),image:r.string().nullable().optional(),favicon:r.string().nullable().optional(),text:r.string().optional(),highlights:r.array(r.string()).optional(),highlightScores:r.array(r.number()).optional(),summary:r.string().optional(),subpages:r.array(r.any()).optional(),extras:r.object({links:r.array(r.string()).optional(),imageLinks:r.array(r.string()).optional()}).optional()})),costDollars:r.object({total:r.number().optional(),search:r.record(r.number()).optional()}).optional()}),r.object({error:r.enum(["api_error","rate_limit","timeout","invalid_input","configuration_error","execution_error","unknown"]),statusCode:r.number().optional(),message:r.string()})]))),VE=Te({id:"gateway.exa_search",inputSchema:HE,outputSchema:WE}),ZE=(e={})=>VE(e),KE=j(()=>M(r.object({objective:r.string().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),search_queries:r.array(r.string()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:r.enum(["one-shot","agentic"]).optional().describe('Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'),max_results:r.number().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:r.object({include_domains:r.array(r.string()).optional().describe("Limit results to these domains. Use plain domain names only \u2014 e.g. example.com or sub.example.gov, or a bare extension like .edu. Do not include a scheme, path, or port (e.g. not https://example.com/page)."),exclude_domains:r.array(r.string()).optional().describe("Exclude results from these domains. Use plain domain names only \u2014 e.g. example.com or sub.example.gov, or a bare extension like .edu. Do not include a scheme, path, or port (e.g. not https://example.com/page)."),after_date:r.string().optional().describe("Only include results published after this date. Use an ISO 8601 calendar date formatted YYYY-MM-DD (e.g. 2025-01-01); do not include a time.")}).optional().describe("Source policy for controlling which domains to include/exclude and freshness."),excerpts:r.object({max_chars_per_result:r.number().optional().describe("Maximum characters per result."),max_chars_total:r.number().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:r.object({max_age_seconds:r.number().optional().describe("Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.")}).optional().describe("Fetch policy for controlling content freshness.")}))),YE=j(()=>M(r.union([r.object({searchId:r.string(),results:r.array(r.object({url:r.string(),title:r.string(),excerpt:r.string(),publishDate:r.string().nullable().optional(),relevanceScore:r.number().optional()}))}),r.object({error:r.enum(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:r.number().optional(),message:r.string()})]))),QE=Te({id:"gateway.parallel_search",inputSchema:KE,outputSchema:YE}),XE=(e={})=>QE(e),eA=j(()=>M(r.object({query:r.union([r.string(),r.array(r.string())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:r.number().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:r.number().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:r.number().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:r.string().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:r.array(r.string()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),search_language_filter:r.array(r.string()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:r.string().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),search_before_date:r.string().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),last_updated_after_filter:r.string().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),last_updated_before_filter:r.string().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),search_recency_filter:r.enum(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),tA=j(()=>M(r.union([r.object({results:r.array(r.object({title:r.string(),url:r.string(),snippet:r.string(),date:r.string().optional(),lastUpdated:r.string().optional()})),id:r.string()}),r.object({error:r.enum(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:r.number().optional(),message:r.string()})]))),rA=Te({id:"gateway.perplexity_search",inputSchema:eA,outputSchema:tA}),nA=(e={})=>rA(e),oA={exaSearch:ZE,parallelSearch:XE,perplexitySearch:nA};async function iA(){var e;return(e=gf.getContext().headers)==null?void 0:e["x-vercel-id"]}var aA="3.0.145",sA="0.0.1";function lA(e={}){var t,n;let o=null,i=null,a=(t=e.metadataCacheRefreshMillis)!=null?t:300000,s=0,l=(n=mn(e.baseURL))!=null?n:"https://ai-gateway.vercel.sh/v3/ai",c=async()=>{try{let w=await cA(e);return it({Authorization:`Bearer ${w.token}`,"ai-gateway-protocol-version":sA,[mf]:w.authMethod,...e.headers},`ai-sdk/gateway/${aA}`)}catch(w){throw Na.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:w})}},u=()=>{let w=Ar({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),_=Ar({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),C=Ar({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),I=Ar({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{let b=await iA();return{...w&&{"ai-o11y-deployment-id":w},..._&&{"ai-o11y-environment":_},...C&&{"ai-o11y-region":C},...b&&{"ai-o11y-request-id":b},...I&&{"ai-o11y-project-id":I}}}},d=(w)=>new SE(w,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:u()}),m=async()=>{var w,_,C;let I=(C=(_=(w=e._internal)==null?void 0:w.currentDate)==null?void 0:_.call(w).getTime())!=null?C:Date.now();if(!o||I-s>a)s=I,o=new tf({baseURL:l,headers:c,fetch:e.fetch}).getAvailableModels().then((b)=>(i=b,b)).catch(async(b)=>{throw await zt(b,await tr(await c()))});return i?Promise.resolve(i):o},p=async()=>new tf({baseURL:l,headers:c,fetch:e.fetch}).getCredits().catch(async(w)=>{throw await zt(w,await tr(await c()))}),f=async(w)=>new yE({baseURL:l,headers:c,fetch:e.fetch}).getSpendReport(w).catch(async(_)=>{throw await zt(_,await tr(await c()))}),g=async(w)=>new bE({baseURL:l,headers:c,fetch:e.fetch}).getGenerationInfo(w).catch(async(_)=>{throw await zt(_,await tr(await c()))}),h=function(w){if(new.target)throw Error("The Gateway Provider model function cannot be called with the new keyword.");return d(w)};h.specificationVersion="v3",h.getAvailableModels=m,h.getCredits=p,h.getSpendReport=f,h.getGenerationInfo=g,h.imageModel=(w)=>new IE(w,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:u()}),h.languageModel=d;let v=(w)=>new wE(w,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:u()});h.embeddingModel=v,h.textEmbeddingModel=v,h.videoModel=(w)=>new AE(w,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:u()});let x=(w)=>new NE(w,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:u()});h.rerankingModel=x,h.reranking=x;let S=(w)=>new UE(w,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:u()});h.speechModel=S,h.speech=S;let y=(w)=>new FE(w,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:u()});return h.transcriptionModel=y,h.transcription=y,h.chat=h.languageModel,h.embedding=h.embeddingModel,h.image=h.imageModel,h.video=h.videoModel,h.tools=oA,h}var hf=lA();async function cA(e){let t=Ar({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(t)return{token:t,authMethod:"api-key"};return{token:await ff.getVercelOidcToken(),authMethod:"oidc"}}var Cb=On(Pc(),1),yo=On(Pc(),1);var bM=Object.defineProperty,_M=(e,t)=>{for(var n in t)bM(e,n,{get:t[n],enumerable:!0})},Tv="AI_InvalidArgumentError",Iv=`vercel.ai.error.${Tv}`,SM=Symbol.for(Iv),Cv,at=class extends ie{constructor({parameter:e,value:t,message:n}){super({name:Tv,message:`Invalid argument for parameter ${e}: ${n}`});this[Cv]=!0,this.parameter=e,this.value=t}static isInstance(e){return ie.hasMarker(e,Iv)}};Cv=SM;var wM="AI_InvalidStreamPartError",xM=`vercel.ai.error.${wM}`,TM=Symbol.for(xM),IM;IM=TM;var kv="AI_InvalidToolApprovalError",Rv=`vercel.ai.error.${kv}`,CM=Symbol.for(Rv),Ev,kM=class extends ie{constructor({approvalId:e}){super({name:kv,message:`Tool approval response references unknown approvalId: "${e}". No matching tool-approval-request found in message history.`});this[Ev]=!0,this.approvalId=e}static isInstance(e){return ie.hasMarker(e,Rv)}};Ev=CM;var Av="AI_InvalidToolApprovalSignatureError",Pv=`vercel.ai.error.${Av}`,RM=Symbol.for(Pv),Mv,lv=class extends ie{constructor({approvalId:e,toolCallId:t,reason:n}){super({name:Av,message:`Tool approval signature verification failed for approval "${e}" (tool call "${t}"): ${n}`});this[Mv]=!0,this.approvalId=e,this.toolCallId=t}static isInstance(e){return ie.hasMarker(e,Pv)}};Mv=RM;var jv="AI_InvalidToolInputError",Ov=`vercel.ai.error.${jv}`,EM=Symbol.for(Ov),Nv,Qa=class extends ie{constructor({toolInput:e,toolName:t,cause:n,message:o=`Invalid input for tool ${t}: ${Tr(n)}`}){super({name:jv,message:o,cause:n});this[Nv]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return ie.hasMarker(e,Ov)}};Nv=EM;var Dv="AI_ToolCallNotFoundForApprovalError",zv=`vercel.ai.error.${Dv}`,AM=Symbol.for(zv),Uv,Fc=class extends ie{constructor({toolCallId:e,approvalId:t}){super({name:Dv,message:`Tool call "${e}" not found for approval request "${t}".`});this[Uv]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return ie.hasMarker(e,zv)}};Uv=AM;var $v="AI_MissingToolResultsError",Lv=`vercel.ai.error.${$v}`,PM=Symbol.for(Lv),qv,cv=class extends ie{constructor({toolCallIds:e}){super({name:$v,message:`Tool result${e.length>1?"s are":" is"} missing for tool call${e.length>1?"s":""} ${e.join(", ")}.`});this[qv]=!0,this.toolCallIds=e}static isInstance(e){return ie.hasMarker(e,Lv)}};qv=PM;var Fv="AI_NoImageGeneratedError",Bv=`vercel.ai.error.${Fv}`,MM=Symbol.for(Bv),Gv,jM=class extends ie{constructor({message:e="No image generated.",cause:t,responses:n}){super({name:Fv,message:e,cause:t});this[Gv]=!0,this.responses=n}static isInstance(e){return ie.hasMarker(e,Bv)}};Gv=MM;var Jv="AI_NoObjectGeneratedError",Hv=`vercel.ai.error.${Jv}`,OM=Symbol.for(Hv),Wv,Ft=class extends ie{constructor({message:e="No object generated.",cause:t,text:n,response:o,usage:i,finishReason:a}){super({name:Jv,message:e,cause:t});this[Wv]=!0,this.text=n,this.response=o,this.usage=i,this.finishReason=a}static isInstance(e){return ie.hasMarker(e,Hv)}};Wv=OM;var Vv="AI_NoOutputGeneratedError",Zv=`vercel.ai.error.${Vv}`,NM=Symbol.for(Zv),Kv,Wa=class extends ie{constructor({message:e="No output generated.",cause:t}={}){super({name:Vv,message:e,cause:t});this[Kv]=!0}static isInstance(e){return ie.hasMarker(e,Zv)}};Kv=NM;var DM="AI_NoSpeechGeneratedError",zM=`vercel.ai.error.${DM}`,UM=Symbol.for(zM),$M;$M=UM;var LM="AI_NoTranscriptGeneratedError",qM=`vercel.ai.error.${LM}`,FM=Symbol.for(qM),BM;BM=FM;var GM="AI_NoVideoGeneratedError",JM=`vercel.ai.error.${GM}`,HM=Symbol.for(JM),WM;WM=HM;var Yv="AI_NoSuchToolError",Qv=`vercel.ai.error.${Yv}`,VM=Symbol.for(Qv),Xv,Oc=class extends ie{constructor({toolName:e,availableTools:t=void 0,message:n=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:Yv,message:n});this[Xv]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return ie.hasMarker(e,Qv)}};Xv=VM;var eb="AI_ToolCallRepairError",tb=`vercel.ai.error.${eb}`,ZM=Symbol.for(tb),rb,KM=class extends ie{constructor({cause:e,originalError:t,message:n=`Error repairing tool call: ${Tr(e)}`}){super({name:eb,message:n,cause:e});this[rb]=!0,this.originalError=t}static isInstance(e){return ie.hasMarker(e,tb)}};rb=ZM;var Bc=class extends ie{constructor(e){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${e.version} for provider "${e.provider}" and model "${e.modelId}". AI SDK 5 only supports models that implement specification version "v2".`});this.version=e.version,this.provider=e.provider,this.modelId=e.modelId}},nb="AI_UIMessageStreamError",ob=`vercel.ai.error.${nb}`,YM=Symbol.for(ob),ib,fo=class extends ie{constructor({chunkType:e,chunkId:t,message:n}){super({name:nb,message:n});this[ib]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return ie.hasMarker(e,ob)}};ib=YM;var ab="AI_InvalidDataContentError",sb=`vercel.ai.error.${ab}`,QM=Symbol.for(sb),lb,uv=class extends ie{constructor({content:e,cause:t,message:n=`Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof e}.`}){super({name:ab,message:n,cause:t});this[lb]=!0,this.content=e}static isInstance(e){return ie.hasMarker(e,sb)}};lb=QM;var cb="AI_InvalidMessageRoleError",ub=`vercel.ai.error.${cb}`,XM=Symbol.for(ub),db,ej=class extends ie{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:cb,message:t});this[db]=!0,this.role=e}static isInstance(e){return ie.hasMarker(e,ub)}};db=XM;var tj="AI_MessageConversionError",rj=`vercel.ai.error.${tj}`,nj=Symbol.for(rj),oj;oj=nj;var pb="AI_RetryError",mb=`vercel.ai.error.${pb}`,ij=Symbol.for(mb),gb,aj=class extends ie{constructor({message:e,reason:t,errors:n}){super({name:pb,message:e});this[gb]=!0,this.reason=t,this.errors=n,this.lastError=n[n.length-1]}static isInstance(e){return ie.hasMarker(e,mb)}};gb=ij;function zn(e){return e===void 0?[]:Array.isArray(e)?e:[e]}async function mr(e){for(let t of zn(e.callbacks)){if(t==null)continue;try{await t(e.event)}catch(n){}}}function sj({warning:e,provider:t,model:n}){let o=`AI SDK Warning (${t} / ${n}):`;switch(e.type){case"unsupported":{let i=`${o} The feature "${e.feature}" is not supported.`;if(e.details)i+=` ${e.details}`;return i}case"compatibility":{let i=`${o} The feature "${e.feature}" is used in a compatibility mode.`;if(e.details)i+=` ${e.details}`;return i}case"other":return`${o} ${e.message}`;default:return`${o} ${JSON.stringify(e,null,2)}`}}var lj="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",dv=!1,gn=(e)=>{if(e.warnings.length===0)return;let t=globalThis.AI_SDK_LOG_WARNINGS;if(t===!1)return;if(typeof t==="function"){t(e);return}if(!dv)dv=!0,console.info(lj);for(let n of e.warnings)console.warn(sj({warning:n,provider:e.provider,model:e.model}))};function Gc({provider:e,modelId:t}){gn({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}function cj(e){if(e.specificationVersion==="v3")return e;return Gc({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,n){if(n==="specificationVersion")return"v3";return t[n]}})}function uj(e){if(e.specificationVersion==="v3")return e;return Gc({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,n){if(n==="specificationVersion")return"v3";return t[n]}})}function dj(e){if(e.specificationVersion==="v3")return e;return Gc({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,n){switch(n){case"specificationVersion":return"v3";case"doGenerate":return async(...o)=>{let i=await t.doGenerate(...o);return{...i,finishReason:fb(i.finishReason),usage:hb(i.usage)}};case"doStream":return async(...o)=>{let i=await t.doStream(...o);return{...i,stream:pj(i.stream)}};default:return t[n]}}})}function pj(e){return e.pipeThrough(new TransformStream({transform(t,n){switch(t.type){case"finish":n.enqueue({...t,finishReason:fb(t.finishReason),usage:hb(t.usage)});break;default:n.enqueue(t);break}}}))}function fb(e){return{unified:e==="unknown"?"other":e,raw:void 0}}function hb(e){return{inputTokens:{total:e.inputTokens,noCache:void 0,cacheRead:e.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:e.outputTokens,text:void 0,reasoning:e.reasoningTokens}}}function ki(e){if(typeof e!=="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){let t=e;throw new Bc({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return dj(e)}return Jc().languageModel(e)}function yb(e){if(typeof e!=="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){let t=e;throw new Bc({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return cj(e)}return Jc().embeddingModel(e)}function mj(e){if(typeof e!=="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){let t=e;throw new Bc({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return uj(e)}return Jc().imageModel(e)}function Jc(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:hf}function Hc(e){if(e==null)return;if(typeof e==="number")return e;return e.totalMs}function vb(e){if(e==null||typeof e==="number")return;return e.stepMs}function gj(e){if(e==null||typeof e==="number")return;return e.chunkMs}var Za=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}];var fj=(e)=>{let t=typeof e==="string"?wt(e):e,n=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(n+10)};function hj(e){return typeof e==="string"&&e.startsWith("SUQz")||typeof e!=="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?fj(e):e}function Ka({data:e,signatures:t}){let n=hj(e),o=typeof n==="string"?wt(n.substring(0,Math.min(n.length,24))):n;for(let i of t)if(o.length>=i.bytesPrefix.length&&i.bytesPrefix.every((a,s)=>a===null||o[s]===a))return i.mediaType;return}var vo="6.0.221",bb=async({url:e,maxBytes:t,abortSignal:n})=>{var o;let i=e.toString();try{let a=it({},`ai-sdk/${vo}`,lo()),s=await xl({url:i,headers:a,abortSignal:n});if(!s.ok)throw await fi(s),new Et({url:i,statusCode:s.status,statusText:s.statusText});return{data:await Ma({response:s,url:i,maxBytes:t!=null?t:Pa}),mediaType:(o=s.headers.get("content-type"))!=null?o:void 0}}catch(a){if(Et.isInstance(a))throw a;throw new Et({url:i,cause:a})}},yj=(e=bb)=>(t)=>Promise.all(t.map(async(n)=>n.isUrlSupportedByModel?null:e(n)));function _b(e){try{let[t,n]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:n}}catch(t){return{mediaType:void 0,base64Content:void 0}}}var Sb=r.union([r.string(),r.instanceof(Uint8Array),r.instanceof(ArrayBuffer),r.custom((e)=>{var t,n;return(n=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?n:!1},{message:"Must be a Buffer"})]);function Wc(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if(typeof e==="string")try{e=new URL(e)}catch(t){}if(e instanceof URL&&e.protocol==="data:"){let{mediaType:t,base64Content:n}=_b(e.toString());if(t==null||n==null)throw new ie({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:n,mediaType:t}}return{data:e,mediaType:void 0}}function Nc(e){if(typeof e==="string")return e;if(e instanceof ArrayBuffer)return Nt(new Uint8Array(e));return Nt(e)}function vj(e){if(e instanceof Uint8Array)return e;if(typeof e==="string")try{return wt(e)}catch(t){throw new uv({message:"Invalid data content. Content string is not a base64-encoded media.",content:e,cause:t})}if(e instanceof ArrayBuffer)return new Uint8Array(e);throw new uv({content:e})}async function Vc({prompt:e,supportedUrls:t,download:n=yj()}){let o=await _j(e.messages,n,t),i=new Map;for(let u of e.messages)if(u.role==="assistant"&&Array.isArray(u.content)){for(let d of u.content)if(d.type==="tool-approval-request"&&"approvalId"in d&&"toolCallId"in d)i.set(d.approvalId,d.toolCallId)}let a=new Set;for(let u of e.messages)if(u.role==="tool"){for(let d of u.content)if(d.type==="tool-approval-response"){let m=i.get(d.approvalId);if(m)a.add(m)}}let s=[...e.system!=null?typeof e.system==="string"?[{role:"system",content:e.system}]:zn(e.system).map((u)=>({role:"system",content:u.content,providerOptions:u.providerOptions})):[],...e.messages.map((u)=>bj({message:u,downloadedAssets:o}))],l=[];for(let u of s){if(u.role!=="tool"){l.push(u);continue}let d=l.at(-1);if((d==null?void 0:d.role)==="tool")d.content.push(...u.content);else l.push(u)}let c=new Set;for(let u of l)switch(u.role){case"assistant":{for(let d of u.content)if(d.type==="tool-call"&&!d.providerExecuted)c.add(d.toolCallId);break}case"tool":{for(let d of u.content)if(d.type==="tool-result")c.delete(d.toolCallId);break}case"user":case"system":for(let d of a)c.delete(d);if(c.size>0)throw new cv({toolCallIds:Array.from(c)});break}for(let u of a)c.delete(u);if(c.size>0)throw new cv({toolCallIds:Array.from(c)});return l.filter((u)=>u.role!=="tool"||u.content.length>0)}function bj({message:e,downloadedAssets:t}){let n=e.role;switch(n){case"system":return{role:"system",content:e.content,providerOptions:e.providerOptions};case"user":{if(typeof e.content==="string")return{role:"user",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions};return{role:"user",content:e.content.map((o)=>Sj(o,t)).filter((o)=>o.type!=="text"||o.text!==""),providerOptions:e.providerOptions}}case"assistant":{if(typeof e.content==="string")return{role:"assistant",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions};return{role:"assistant",content:e.content.filter((o)=>o.type!=="text"||o.text!==""||o.providerOptions!=null).filter((o)=>o.type!=="tool-approval-request").map((o)=>{let i=o.providerOptions;switch(o.type){case"file":{let{data:a,mediaType:s}=Wc(o.data);return{type:"file",data:a,filename:o.filename,mediaType:s!=null?s:o.mediaType,providerOptions:i}}case"reasoning":return{type:"reasoning",text:o.text,providerOptions:i};case"text":return{type:"text",text:o.text,providerOptions:i};case"tool-call":return{type:"tool-call",toolCallId:o.toolCallId,toolName:o.toolName,input:o.input,providerExecuted:o.providerExecuted,providerOptions:i};case"tool-result":return{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:pv({output:o.output,downloadedAssets:t}),providerOptions:i}}}),providerOptions:e.providerOptions}}case"tool":return{role:"tool",content:e.content.filter((o)=>o.type!=="tool-approval-response"||o.providerExecuted).map((o)=>{switch(o.type){case"tool-result":return{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:pv({output:o.output,downloadedAssets:t}),providerOptions:o.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:o.approvalId,approved:o.approved,reason:o.reason}}}),providerOptions:e.providerOptions};default:throw new ej({role:n})}}async function _j(e,t,n){var o;let i=[];for(let l of e){if(l.role==="user"&&Array.isArray(l.content)){for(let c of l.content)if(c.type==="image"||c.type==="file")i.push({data:c.type==="image"?c.image:c.data,mediaType:(o=c.mediaType)!=null?o:c.type==="image"?"image/*":void 0})}if(l.role==="tool"||l.role==="assistant"){if(!Array.isArray(l.content))continue;for(let c of l.content){if(c.type!=="tool-result")continue;if(c.output.type!=="content")continue;for(let u of c.output.value)if(u.type==="image-url"||u.type==="file-url")i.push({data:new URL(u.url),mediaType:u.type==="image-url"?"image/*":void 0})}}}let a=i.map((l)=>{let c=l.mediaType,{data:u}=Wc(l.data);return{mediaType:c,data:u}}).filter((l)=>l.data instanceof URL).map((l)=>({url:l.data,isUrlSupportedByModel:l.mediaType!=null&&eg({url:l.data.toString(),mediaType:l.mediaType,supportedUrls:n})})),s=await t(a);return Object.fromEntries(s.map((l,c)=>l==null?null:[a[c].url.toString(),{data:l.data,mediaType:l.mediaType}]).filter((l)=>l!=null))}function Sj(e,t){var n;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let o,i=e.type;switch(i){case"image":o=e.image;break;case"file":o=e.data;break;default:throw Error(`Unsupported part type: ${i}`)}let{data:a,mediaType:s}=Wc(o),l=s!=null?s:e.mediaType,c=a;if(c instanceof URL){let u=t[c.toString()];if(u)c=u.data,l!=null||(l=u.mediaType)}switch(i){case"image":{if(c instanceof Uint8Array||typeof c==="string")l=(n=Ka({data:c,signatures:Za}))!=null?n:l;return{type:"file",mediaType:l!=null?l:"image/*",filename:void 0,data:c,providerOptions:e.providerOptions}}case"file":{if(l==null)throw Error("Media type is missing for file part");return{type:"file",mediaType:l,filename:e.filename,data:c,providerOptions:e.providerOptions}}}}function pv({output:e,downloadedAssets:t}){if(e.type!=="content")return e;return{type:"content",value:e.value.map((n)=>{var o,i;if(n.type==="image-url"){let a=t[new URL(n.url).toString()];if(a)return{type:"image-data",data:Nc(a.data),mediaType:(o=a.mediaType)!=null?o:"image/*",providerOptions:n.providerOptions};return n}if(n.type==="file-url"){let a=t[new URL(n.url).toString()];if(a)return{type:"file-data",data:Nc(a.data),mediaType:(i=a.mediaType)!=null?i:"application/octet-stream",providerOptions:n.providerOptions};return n}if(n.type!=="media")return n;if(n.mediaType.startsWith("image/"))return{type:"image-data",data:n.data,mediaType:n.mediaType};return{type:"file-data",data:n.data,mediaType:n.mediaType}})}}async function Ci({toolCallId:e,input:t,output:n,tool:o,errorMode:i}){if(i==="text")return{type:"error-text",value:Tr(n)};else if(i==="json")return{type:"error-json",value:mv(n)};if(o==null?void 0:o.toModelOutput)return await o.toModelOutput({toolCallId:e,input:t,output:n});return typeof n==="string"?{type:"text",value:n}:{type:"json",value:mv(n)}}function mv(e){return e===void 0?null:e}function Ri({maxOutputTokens:e,temperature:t,topP:n,topK:o,presencePenalty:i,frequencyPenalty:a,seed:s,stopSequences:l}){if(e!=null){if(!Number.isInteger(e))throw new at({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new at({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null){if(typeof t!=="number")throw new at({parameter:"temperature",value:t,message:"temperature must be a number"})}if(n!=null){if(typeof n!=="number")throw new at({parameter:"topP",value:n,message:"topP must be a number"})}if(o!=null){if(typeof o!=="number")throw new at({parameter:"topK",value:o,message:"topK must be a number"})}if(i!=null){if(typeof i!=="number")throw new at({parameter:"presencePenalty",value:i,message:"presencePenalty must be a number"})}if(a!=null){if(typeof a!=="number")throw new at({parameter:"frequencyPenalty",value:a,message:"frequencyPenalty must be a number"})}if(s!=null){if(!Number.isInteger(s))throw new at({parameter:"seed",value:s,message:"seed must be an integer"})}return{maxOutputTokens:e,temperature:t,topP:n,topK:o,presencePenalty:i,frequencyPenalty:a,stopSequences:l,seed:s}}function wj(e){return e!=null&&Object.keys(e).length>0}async function wb({tools:e,toolChoice:t,activeTools:n}){if(!wj(e))return{tools:void 0,toolChoice:void 0};let o=n!=null?Object.entries(e).filter(([a])=>n.includes(a)):Object.entries(e),i=[];for(let[a,s]of o){let l=s.type;switch(l){case void 0:case"dynamic":case"function":i.push({type:"function",name:a,description:s.description,inputSchema:await qt(s.inputSchema).jsonSchema,...s.inputExamples!=null?{inputExamples:s.inputExamples}:{},providerOptions:s.providerOptions,...s.strict!=null?{strict:s.strict}:{}});break;case"provider":i.push({type:"provider",name:a,id:s.id,args:s.args});break;default:throw Error(`Unsupported tool type: ${l}`)}}return{tools:i,toolChoice:t==null?{type:"auto"}:typeof t==="string"?{type:t}:{type:"tool",toolName:t.toolName}}}var Un=r.lazy(()=>r.union([r.null(),r.string(),r.number(),r.boolean(),r.record(r.string(),Un.optional()),r.array(Un)])),fe=r.record(r.string(),r.record(r.string(),Un.optional())),xb=r.object({type:r.literal("text"),text:r.string(),providerOptions:fe.optional()}),xj=r.object({type:r.literal("image"),image:r.union([Sb,r.instanceof(URL)]),mediaType:r.string().optional(),providerOptions:fe.optional()}),Tb=r.object({type:r.literal("file"),data:r.union([Sb,r.instanceof(URL)]),filename:r.string().optional(),mediaType:r.string(),providerOptions:fe.optional()}),Tj=r.object({type:r.literal("reasoning"),text:r.string(),providerOptions:fe.optional()}),Ij=r.object({type:r.literal("tool-call"),toolCallId:r.string(),toolName:r.string(),input:r.unknown(),providerOptions:fe.optional(),providerExecuted:r.boolean().optional()}),Cj=r.discriminatedUnion("type",[r.object({type:r.literal("text"),value:r.string(),providerOptions:fe.optional()}),r.object({type:r.literal("json"),value:Un,providerOptions:fe.optional()}),r.object({type:r.literal("execution-denied"),reason:r.string().optional(),providerOptions:fe.optional()}),r.object({type:r.literal("error-text"),value:r.string(),providerOptions:fe.optional()}),r.object({type:r.literal("error-json"),value:Un,providerOptions:fe.optional()}),r.object({type:r.literal("content"),value:r.array(r.union([r.object({type:r.literal("text"),text:r.string(),providerOptions:fe.optional()}),r.object({type:r.literal("media"),data:r.string(),mediaType:r.string()}),r.object({type:r.literal("file-data"),data:r.string(),mediaType:r.string(),filename:r.string().optional(),providerOptions:fe.optional()}),r.object({type:r.literal("file-url"),url:r.string(),providerOptions:fe.optional()}),r.object({type:r.literal("file-id"),fileId:r.union([r.string(),r.record(r.string(),r.string())]),providerOptions:fe.optional()}),r.object({type:r.literal("image-data"),data:r.string(),mediaType:r.string(),providerOptions:fe.optional()}),r.object({type:r.literal("image-url"),url:r.string(),providerOptions:fe.optional()}),r.object({type:r.literal("image-file-id"),fileId:r.union([r.string(),r.record(r.string(),r.string())]),providerOptions:fe.optional()}),r.object({type:r.literal("custom"),providerOptions:fe.optional()})]))})]),Ib=r.object({type:r.literal("tool-result"),toolCallId:r.string(),toolName:r.string(),output:Cj,providerOptions:fe.optional()}),kj=r.object({type:r.literal("tool-approval-request"),approvalId:r.string(),toolCallId:r.string()}),Rj=r.object({type:r.literal("tool-approval-response"),approvalId:r.string(),approved:r.boolean(),reason:r.string().optional()}),Ej=r.object({role:r.literal("system"),content:r.string(),providerOptions:fe.optional()}),Aj=r.object({role:r.literal("user"),content:r.union([r.string(),r.array(r.union([xb,xj,Tb]))]),providerOptions:fe.optional()}),Pj=r.object({role:r.literal("assistant"),content:r.union([r.string(),r.array(r.union([xb,Tb,Tj,Ij,Ib,kj]))]),providerOptions:fe.optional()}),Mj=r.object({role:r.literal("tool"),content:r.array(r.union([Ib,Rj])),providerOptions:fe.optional()}),jj=r.union([Ej,Aj,Pj,Mj]);async function Zc({allowSystemInMessages:e,system:t,prompt:n,messages:o}){if(n==null&&o==null)throw new Ir({prompt:n,message:"prompt or messages must be defined"});if(n!=null&&o!=null)throw new Ir({prompt:n,message:"prompt and messages cannot be defined at the same time"});if(typeof t!=="string"&&!zn(t).every((a)=>a.role==="system"))throw new Ir({prompt:n,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});if(n!=null&&typeof n==="string")o=[{role:"user",content:n}];else if(n!=null&&Array.isArray(n))o=n;else if(o==null)throw new Ir({prompt:n,message:"prompt or messages must be defined"});if(o.length===0)throw new Ir({prompt:n,message:"messages must not be empty"});if(o.some((a)=>a.role==="system")){if(e===!1)throw new Ir({prompt:n,message:"System messages are not allowed in the prompt or messages fields. Use the system option instead."});if(e===void 0)console.warn("AI SDK Warning: System messages in the prompt or messages fields can be a security risk because they may enable prompt injection attacks. Use the system option instead when possible. Set allowSystemInMessages to true to suppress this warning, or false to throw an error.")}let i=await pt({value:o,schema:r.array(jj)});if(!i.success)throw new Ir({prompt:n,message:"The messages do not match the ModelMessage[] schema.",cause:i.error});return{messages:o,system:t}}function Kc(e){if(!Na.isInstance(e))return e;let t=(process==null?void 0:"development")==="production",n="https://ai-sdk.dev/unauthenticated-ai-gateway";if(t)return new ie({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${n}`});return Object.assign(Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
55
+
56
+ To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
57
+
58
+ Alternatively, you can use a provider module instead of the AI Gateway.
59
+
60
+ Learn more: \x1B[34m${n}\x1B[0m
61
+
62
+ `),{name:"GatewayAuthenticationError"})}function rr({operationId:e,telemetry:t}){return{"operation.name":`${e}${(t==null?void 0:t.functionId)!=null?` ${t.functionId}`:""}`,"resource.name":t==null?void 0:t.functionId,"ai.operationId":e,"ai.telemetry.functionId":t==null?void 0:t.functionId}}function Ai({model:e,settings:t,telemetry:n,headers:o}){var i;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((a,[s,l])=>{if(s==="timeout"){let c=Hc(l);if(c!=null)a[`ai.settings.${s}`]=c}else a[`ai.settings.${s}`]=l;return a},{}),...Object.entries((i=n==null?void 0:n.metadata)!=null?i:{}).reduce((a,[s,l])=>(a[`ai.telemetry.metadata.${s}`]=l,a),{}),...Object.entries(o!=null?o:{}).reduce((a,[s,l])=>{if(l!==void 0)a[`ai.request.headers.${s}`]=l;return a},{})}}var Oj={startSpan(){return Ha},startActiveSpan(e,t,n,o){if(typeof t==="function")return t(Ha);if(typeof n==="function")return n(Ha);if(typeof o==="function")return o(Ha)}},Ha={spanContext(){return Nj},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},Nj={traceId:"",spanId:"",traceFlags:0};function Pi({isEnabled:e=!1,tracer:t}={}){if(!e)return Oj;if(t)return t;return Cb.trace.getTracer("ai")}async function nr({name:e,tracer:t,attributes:n,fn:o,endWhenDone:i=!0}){return t.startActiveSpan(e,{attributes:await n},async(a)=>{let s=yo.context.active();try{let l=await yo.context.with(s,()=>o(a));if(i)a.end();return l}catch(l){try{kb(a,l)}finally{a.end()}throw l}})}function kb(e,t){if(t instanceof Error)e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:yo.SpanStatusCode.ERROR,message:t.message});else e.setStatus({code:yo.SpanStatusCode.ERROR})}function Dj(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"}function Mc(e){if(!Array.isArray(e))return e;let t=new Set(e.filter(Dj).map((o)=>typeof o));if(t.size!==1)return;let[n]=t;if(n==="string")return e.filter((o)=>typeof o==="string");if(n==="number")return e.filter((o)=>typeof o==="number");return e.filter((o)=>typeof o==="boolean")}async function et({telemetry:e,attributes:t}){if((e==null?void 0:e.isEnabled)!==!0)return{};let n={};for(let[o,i]of Object.entries(t)){if(i==null)continue;if(typeof i==="object"&&"input"in i&&typeof i.input==="function"){if((e==null?void 0:e.recordInputs)===!1)continue;let s=await i.input();if(s!=null){let l=Mc(s);if(l!=null)n[o]=l}continue}if(typeof i==="object"&&"output"in i&&typeof i.output==="function"){if((e==null?void 0:e.recordOutputs)===!1)continue;let s=await i.output();if(s!=null){let l=Mc(s);if(l!=null)n[o]=l}continue}let a=Mc(i);if(a!=null)n[o]=a}return n}function Yc(e){return JSON.stringify(e.map((t)=>({...t,content:typeof t.content==="string"?t.content:t.content.map((n)=>n.type==="file"?{...n,data:n.data instanceof Uint8Array?Nc(n.data):n.data}:n)})))}function zj(){var e;return(e=globalThis.AI_SDK_TELEMETRY_INTEGRATIONS)!=null?e:[]}function Rb(){let e=zj();return(t)=>{let n=zn(t),o=[...e,...n];function i(a){let s=o.map(a).filter(Boolean);return async(l)=>{for(let c of s)try{await c(l)}catch(u){}}}return{onStart:i((a)=>a.onStart),onStepStart:i((a)=>a.onStepStart),onToolCallStart:i((a)=>a.onToolCallStart),onToolCallFinish:i((a)=>a.onToolCallFinish),onStepFinish:i((a)=>a.onStepFinish),onFinish:i((a)=>a.onFinish)}}}function Ei(e){return{inputTokens:e.inputTokens.total,inputTokenDetails:{noCacheTokens:e.inputTokens.noCache,cacheReadTokens:e.inputTokens.cacheRead,cacheWriteTokens:e.inputTokens.cacheWrite},outputTokens:e.outputTokens.total,outputTokenDetails:{textTokens:e.outputTokens.text,reasoningTokens:e.outputTokens.reasoning},totalTokens:Jt(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}function jc(){return{inputTokens:void 0,inputTokenDetails:{noCacheTokens:void 0,cacheReadTokens:void 0,cacheWriteTokens:void 0},outputTokens:void 0,outputTokenDetails:{textTokens:void 0,reasoningTokens:void 0},totalTokens:void 0,raw:void 0}}function Eb(e,t){var n,o,i,a,s,l,c,u,d,m;return{inputTokens:Jt(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:Jt((n=e.inputTokenDetails)==null?void 0:n.noCacheTokens,(o=t.inputTokenDetails)==null?void 0:o.noCacheTokens),cacheReadTokens:Jt((i=e.inputTokenDetails)==null?void 0:i.cacheReadTokens,(a=t.inputTokenDetails)==null?void 0:a.cacheReadTokens),cacheWriteTokens:Jt((s=e.inputTokenDetails)==null?void 0:s.cacheWriteTokens,(l=t.inputTokenDetails)==null?void 0:l.cacheWriteTokens)},outputTokens:Jt(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:Jt((c=e.outputTokenDetails)==null?void 0:c.textTokens,(u=t.outputTokenDetails)==null?void 0:u.textTokens),reasoningTokens:Jt((d=e.outputTokenDetails)==null?void 0:d.reasoningTokens,(m=t.outputTokenDetails)==null?void 0:m.reasoningTokens)},totalTokens:Jt(e.totalTokens,t.totalTokens),reasoningTokens:Jt(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:Jt(e.cachedInputTokens,t.cachedInputTokens)}}function Jt(e,t){return e==null&&t==null?void 0:(e!=null?e:0)+(t!=null?t:0)}function Uj(e,t){return{inputTokens:Jt(e.inputTokens,t.inputTokens),outputTokens:Jt(e.outputTokens,t.outputTokens),totalTokens:Jt(e.totalTokens,t.totalTokens)}}function Xa(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;let n={...e};for(let o in t){if(o==="__proto__"||o==="constructor"||o==="prototype")continue;if(Object.prototype.hasOwnProperty.call(t,o)){let i=t[o];if(i===void 0)continue;let a=o in e?e[o]:void 0,s=i!==null&&typeof i==="object"&&!Array.isArray(i)&&!(i instanceof Date)&&!(i instanceof RegExp),l=a!==null&&a!==void 0&&typeof a==="object"&&!Array.isArray(a)&&!(a instanceof Date)&&!(a instanceof RegExp);if(s&&l)n[o]=Xa(a,i);else n[o]=i}}return n}function $j({error:e,exponentialBackoffDelay:t}){let n=De.isInstance(e)?e.responseHeaders:De.isInstance(e.cause)?e.cause.responseHeaders:void 0;if(!n)return t;let o,i=n["retry-after-ms"];if(i){let s=parseFloat(i);if(!Number.isNaN(s))o=s}let a=n["retry-after"];if(a&&o===void 0){let s=parseFloat(a);if(!Number.isNaN(s))o=s*1000;else o=Date.parse(a)-Date.now()}if(o!=null&&!Number.isNaN(o)&&0<=o&&(o<60000||o<t))return o;return t}var Lj=({maxRetries:e=2,initialDelayInMs:t=2000,backoffFactor:n=2,abortSignal:o}={})=>sg({maxRetries:e,initialDelayInMs:t,backoffFactor:n,abortSignal:o,shouldRetry:(i)=>i instanceof Error&&(De.isInstance(i)&&i.isRetryable===!0||ft.isInstance(i)&&i.isRetryable===!0),getDelayInMs:({error:i,exponentialBackoffDelay:a})=>$j({error:i,exponentialBackoffDelay:a}),createRetryError:({message:i,reason:a,errors:s})=>new aj({message:i,reason:a,errors:s})});function bo({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new at({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new at({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}let n=e!=null?e:2;return{maxRetries:n,retry:Lj({maxRetries:n,abortSignal:t})}}function Dc({abortController:e,label:t,timeoutMs:n}){if(e==null||n==null)return;return setTimeout(()=>e.abort(new DOMException(`${t} timeout of ${n}ms exceeded`,"TimeoutError")),n)}function Ab({messages:e}){let t=e.at(-1);if((t==null?void 0:t.role)!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};let n={};for(let c of e)if(c.role==="assistant"&&typeof c.content!=="string"){let u=c.content;for(let d of u)if(d.type==="tool-call")n[d.toolCallId]=d}let o={};for(let c of e)if(c.role==="assistant"&&typeof c.content!=="string"){let u=c.content;for(let d of u)if(d.type==="tool-approval-request")o[d.approvalId]=d}let i={};for(let c of t.content)if(c.type==="tool-result")i[c.toolCallId]=c;let a=[],s=[],l=t.content.filter((c)=>c.type==="tool-approval-response");for(let c of l){let u=o[c.approvalId];if(u==null)throw new kM({approvalId:c.approvalId});if(i[u.toolCallId]!=null)continue;let d=n[u.toolCallId];if(d==null)throw new Fc({toolCallId:u.toolCallId,approvalId:u.approvalId});let m={approvalRequest:u,approvalResponse:c,toolCall:d};if(c.approved)a.push(m);else s.push(m)}return{approvedToolApprovals:a,deniedToolApprovals:s}}function Va(){var e,t;return(t=(e=globalThis==null?void 0:globalThis.performance)==null?void 0:e.now())!=null?t:Date.now()}async function Qc({toolCall:e,tools:t,tracer:n,telemetry:o,messages:i,abortSignal:a,experimental_context:s,stepNumber:l,model:c,onPreliminaryToolResult:u,onToolCallStart:d,onToolCallFinish:m}){let{toolName:p,toolCallId:f,input:g}=e,h=t==null?void 0:t[p];if((h==null?void 0:h.execute)==null)return;let v={stepNumber:l,model:c,toolCall:e,messages:i,abortSignal:a,functionId:o==null?void 0:o.functionId,metadata:o==null?void 0:o.metadata,experimental_context:s};return nr({name:"ai.toolCall",attributes:et({telemetry:o,attributes:{...rr({operationId:"ai.toolCall",telemetry:o}),"ai.toolCall.name":p,"ai.toolCall.id":f,"ai.toolCall.args":{output:()=>JSON.stringify(g)}}}),tracer:n,fn:async(x)=>{let S;await mr({event:v,callbacks:d});let y=Va();try{let _=dg({execute:h.execute.bind(h),input:g,options:{toolCallId:f,messages:i,abortSignal:a,experimental_context:s}});for await(let C of _)if(C.type==="preliminary")u==null||u({...e,type:"tool-result",output:C.output,preliminary:!0});else S=C.output}catch(_){let C=Va()-y;return await mr({event:{...v,success:!1,error:_,durationMs:C},callbacks:m}),kb(x,_),{type:"tool-error",toolCallId:f,toolName:p,input:g,error:_,dynamic:h.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{},...e.toolMetadata!=null?{toolMetadata:e.toolMetadata}:{}}}let w=Va()-y;await mr({event:{...v,success:!0,output:S,durationMs:w},callbacks:m});try{x.setAttributes(await et({telemetry:o,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(S)}}}))}catch(_){}return{type:"tool-result",toolCallId:f,toolName:p,input:g,output:S,dynamic:h.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{},...e.toolMetadata!=null?{toolMetadata:e.toolMetadata}:{}}}})}function zc(e){let t=e.filter((n)=>n.type==="reasoning");return t.length===0?void 0:t.map((n)=>n.text).join(`
63
+ `)}function Uc(e){let t=e.filter((n)=>n.type==="text");if(t.length===0)return;return t.map((n)=>n.text).join("")}var Xc=class{constructor({data:e,mediaType:t}){let n=e instanceof Uint8Array;this.base64Data=n?void 0:e,this.uint8ArrayData=n?e:void 0,this.mediaType=t}get base64(){if(this.base64Data==null)this.base64Data=Nt(this.uint8ArrayData);return this.base64Data}get uint8Array(){if(this.uint8ArrayData==null)this.uint8ArrayData=wt(this.base64Data);return this.uint8ArrayData}},qj=class extends Xc{constructor(e){super(e);this.type="file"}};async function eu({tool:e,toolCall:t,messages:n,experimental_context:o}){if(e.needsApproval==null)return!1;if(typeof e.needsApproval==="boolean")return e.needsApproval;return await e.needsApproval(t.input,{toolCallId:t.toolCallId,messages:n,experimental_context:o})}var tu=new TextEncoder;function $c(e){if(e===null||e===void 0)return JSON.stringify(e);if(typeof e!=="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map($c).join(",")}]`;return`{${Object.keys(e).sort().map((o)=>`${JSON.stringify(o)}:${$c(e[o])}`).join(",")}}`}function Pb(e){return Nt(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Fj(e){return wt(e)}async function Mb(e){let t=typeof e==="string"?tu.encode(e):e;return crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}async function jb(e){let t=$c(e),n=await crypto.subtle.digest("SHA-256",tu.encode(t));return Pb(new Uint8Array(n))}function Ob(e,t,n,o){return tu.encode(`${e}
64
+ ${t}
65
+ ${n}
66
+ ${o}`)}async function Bj({secret:e,approvalId:t,toolCallId:n,toolName:o,input:i}){let a=await Mb(e),s=await jb(i),l=Ob(t,n,o,s),c=await crypto.subtle.sign("HMAC",a,l);return Pb(new Uint8Array(c))}async function Gj({secret:e,signature:t,approvalId:n,toolCallId:o,toolName:i,input:a}){let s=await Mb(e),l=await jb(a),c=Ob(n,o,i,l),u=Fj(t);return crypto.subtle.verify("HMAC",s,u,c)}async function Nb({secret:e,approvalId:t,toolCallId:n,toolName:o,input:i}){if(e==null)return;return Bj({secret:e,approvalId:t,toolCallId:n,toolName:o,input:i})}async function Db({approvedToolApprovals:e,tools:t,messages:n,experimental_context:o,toolApprovalSecret:i}){var a;let s=[],l=[];for(let c of e){let{toolCall:u,approvalRequest:d}=c,m=t==null?void 0:t[u.toolName];if(i!=null){if(d.signature==null)throw new lv({approvalId:d.approvalId,toolCallId:u.toolCallId,reason:"missing signature"});if(!await Gj({secret:i,signature:d.signature,approvalId:d.approvalId,toolCallId:u.toolCallId,toolName:u.toolName,input:u.input}))throw new lv({approvalId:d.approvalId,toolCallId:u.toolCallId,reason:"invalid signature"})}if(m!=null&&typeof m.execute==="function"&&m.inputSchema!=null){let f=await pt({value:u.input,schema:qt(m.inputSchema)});if(!f.success)throw new Qa({toolName:u.toolName,toolInput:JSON.stringify(u.input),cause:f.error})}if(m!=null&&await eu({tool:m,toolCall:u,messages:n,experimental_context:o}))s.push(c);else l.push({...c,approvalResponse:{...c.approvalResponse,approved:!1,reason:(a=c.approvalResponse.reason)!=null?a:`Tool "${u.toolName}" does not require approval`}})}return{approvedToolApprovals:s,deniedToolApprovals:l}}var Jj={};_M(Jj,{array:()=>Vj,choice:()=>Zj,json:()=>Kj,object:()=>Wj,text:()=>Ya});function Hj(e){let t=["ROOT"],n=-1,o=null,i=0;function a(d){return d>="0"&&d<="9"||d>="A"&&d<="F"||d>="a"&&d<="f"}function s(d,m,p){switch(d){case'"':{n=m,t.pop(),t.push(p),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=m,o=m,t.pop(),t.push(p),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(p),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=m,t.pop(),t.push(p),t.push("INSIDE_NUMBER");break}case"{":{n=m,t.pop(),t.push(p),t.push("INSIDE_OBJECT_START");break}case"[":{n=m,t.pop(),t.push(p),t.push("INSIDE_ARRAY_START");break}}}function l(d,m){switch(d){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=m,t.pop();break}}}function c(d,m){switch(d){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=m,t.pop();break}}}for(let d=0;d<e.length;d++){let m=e[d];switch(t[t.length-1]){case"ROOT":s(m,d,"FINISH");break;case"INSIDE_OBJECT_START":{switch(m){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=d,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(m){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(m){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(m){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(m,d,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{l(m,d);break}case"INSIDE_STRING":{switch(m){case'"':{t.pop(),n=d;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=d}break}case"INSIDE_ARRAY_START":{switch(m){case"]":{n=d,t.pop();break}default:{n=d,s(m,d,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(m){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=d,t.pop();break}default:{n=d;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(m,d,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{if(t.pop(),m==="u")i=0,t.push("INSIDE_STRING_UNICODE_ESCAPE");else n=d;break}case"INSIDE_STRING_UNICODE_ESCAPE":{if(a(m)){if(i++,i===4)t.pop(),n=d}break}case"INSIDE_NUMBER":{switch(m){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=d;break}case"e":case"E":case"-":case".":break;case",":{if(t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE")c(m,d);if(t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE")l(m,d);break}case"}":{if(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE")l(m,d);break}case"]":{if(t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE")c(m,d);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{let f=e.substring(o,d+1);if(!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)){if(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE")l(m,d);else if(t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE")c(m,d)}else n=d;break}}}let u=e.slice(0,n+1);for(let d=t.length-1;d>=0;d--)switch(t[d]){case"INSIDE_STRING":{u+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{u+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{u+="]";break}case"INSIDE_LITERAL":{let p=e.substring(o,e.length);if("true".startsWith(p))u+="true".slice(p.length);else if("false".startsWith(p))u+="false".slice(p.length);else if("null".startsWith(p))u+="null".slice(p.length)}}return u}async function Mi(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await xt({text:e});if(t.success)return{value:t.value,state:"successful-parse"};if(t=await xt({text:Hj(e)}),t.success)return{value:t.value,state:"repaired-parse"};return{value:void 0,state:"failed-parse"}}var Ya=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){return}}),Wj=({schema:e,name:t,description:n})=>{let o=qt(e);return{name:"object",responseFormat:Se(o.jsonSchema).then((i)=>({type:"json",schema:i,...t!=null&&{name:t},...n!=null&&{description:n}})),async parseCompleteOutput({text:i},a){let s=await xt({text:i});if(!s.success)throw new Ft({message:"No object generated: could not parse the response.",cause:s.error,text:i,response:a.response,usage:a.usage,finishReason:a.finishReason});let l=await pt({value:s.value,schema:o});if(!l.success)throw new Ft({message:"No object generated: response did not match schema.",cause:l.error,text:i,response:a.response,usage:a.usage,finishReason:a.finishReason});return l.value},async parsePartialOutput({text:i}){let a=await Mi(i);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:a.value}}},createElementStreamTransform(){return}}},Vj=({element:e,name:t,description:n})=>{let o=qt(e);return{name:"array",responseFormat:Se(o.jsonSchema).then((i)=>{let{$schema:a,...s}=i;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:s}},required:["elements"],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}}),async parseCompleteOutput({text:i},a){let s=await xt({text:i});if(!s.success)throw new Ft({message:"No object generated: could not parse the response.",cause:s.error,text:i,response:a.response,usage:a.usage,finishReason:a.finishReason});let l=s.value;if(l==null||typeof l!=="object"||!("elements"in l)||!Array.isArray(l.elements))throw new Ft({message:"No object generated: response did not match schema.",cause:new vt({value:l,cause:"response must be an object with an elements array"}),text:i,response:a.response,usage:a.usage,finishReason:a.finishReason});let c=[];for(let u of l.elements){let d=await pt({value:u,schema:o});if(!d.success)throw new Ft({message:"No object generated: response did not match schema.",cause:d.error,text:i,response:a.response,usage:a.usage,finishReason:a.finishReason});c.push(d.value)}return c},async parsePartialOutput({text:i}){let a=await Mi(i);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let s=a.value;if(s==null||typeof s!=="object"||!("elements"in s)||!Array.isArray(s.elements))return;let l=a.state==="repaired-parse"&&s.elements.length>0?s.elements.slice(0,-1):s.elements,c=[];for(let u of l){let d=await pt({value:u,schema:o});if(d.success)c.push(d.value)}return{partial:c}}}},createElementStreamTransform(){let i=0;return new TransformStream({transform({partialOutput:a},s){if(a!=null)for(;i<a.length;i++)s.enqueue(a[i])}})}}},Zj=({options:e,name:t,description:n})=>({name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:e}},required:["result"],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}),async parseCompleteOutput({text:o},i){let a=await xt({text:o});if(!a.success)throw new Ft({message:"No object generated: could not parse the response.",cause:a.error,text:o,response:i.response,usage:i.usage,finishReason:i.finishReason});let s=a.value;if(s==null||typeof s!=="object"||!("result"in s)||typeof s.result!=="string"||!e.includes(s.result))throw new Ft({message:"No object generated: response did not match schema.",cause:new vt({value:s,cause:"response must be an object that contains a choice value."}),text:o,response:i.response,usage:i.usage,finishReason:i.finishReason});return s.result},async parsePartialOutput({text:o}){let i=await Mi(o);switch(i.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let a=i.value;if(a==null||typeof a!=="object"||!("result"in a)||typeof a.result!=="string")return;let s=e.filter((l)=>l.startsWith(a.result));if(i.state==="successful-parse")return s.includes(a.result)?{partial:a.result}:void 0;else return s.length===1?{partial:s[0]}:void 0}}},createElementStreamTransform(){return}}),Kj=({name:e,description:t}={})=>({name:"json",responseFormat:Promise.resolve({type:"json",...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:n},o){let i=await xt({text:n});if(!i.success)throw new Ft({message:"No object generated: could not parse the response.",cause:i.error,text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});return i.value},async parsePartialOutput({text:n}){let o=await Mi(n);switch(o.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return o.value===void 0?void 0:{partial:o.value}}},createElementStreamTransform(){return}});async function zb({toolCall:e,tools:t,repairToolCall:n,system:o,messages:i}){try{if(t==null){if(e.providerExecuted&&e.dynamic)return await Ub(e);throw new Oc({toolName:e.toolName})}try{return await gv({toolCall:e,tools:t})}catch(a){if(n==null||!(Oc.isInstance(a)||Qa.isInstance(a)))throw a;let s=null;try{s=await n({toolCall:e,tools:t,inputSchema:async({toolName:l})=>{let{inputSchema:c}=t[l];return await qt(c).jsonSchema},system:o,messages:i,error:a})}catch(l){throw new KM({cause:l,originalError:a})}if(s==null)throw a;return await gv({toolCall:s,tools:t})}}catch(a){let s=await xt({text:e.input}),l=s.success?s.value:e.input,c=t==null?void 0:t[e.toolName];return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:l,dynamic:!0,invalid:!0,error:a,title:c==null?void 0:c.title,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,...(c==null?void 0:c.metadata)!=null?{toolMetadata:c.metadata}:{}}}}async function Ub(e){let t=e.input.trim()===""?{success:!0,value:{}}:await xt({text:e.input});if(t.success===!1)throw new Qa({toolName:e.toolName,toolInput:e.input,cause:t.error});return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:t.value,providerExecuted:!0,dynamic:!0,providerMetadata:e.providerMetadata}}async function gv({toolCall:e,tools:t}){let n=e.toolName,o=t[n];if(o==null){if(e.providerExecuted&&e.dynamic)return await Ub(e);throw new Oc({toolName:e.toolName,availableTools:Object.keys(t)})}let i=qt(o.inputSchema),a=e.input.trim()===""?await pt({value:{},schema:i}):await xt({text:e.input,schema:i});if(a.success===!1)throw new Qa({toolName:n,toolInput:e.input,cause:a.error});return o.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:a.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,...o.metadata!=null?{toolMetadata:o.metadata}:{},dynamic:!0,title:o.title}:{type:"tool-call",toolCallId:e.toolCallId,toolName:n,input:a.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,...o.metadata!=null?{toolMetadata:o.metadata}:{},title:o.title}}var $b=class{constructor({stepNumber:e,model:t,functionId:n,metadata:o,experimental_context:i,content:a,finishReason:s,rawFinishReason:l,usage:c,warnings:u,request:d,response:m,providerMetadata:p}){this.stepNumber=e,this.model=t,this.functionId=n,this.metadata=o,this.experimental_context=i,this.content=a,this.finishReason=s,this.rawFinishReason=l,this.usage=c,this.warnings=u,this.request=d,this.response=m,this.providerMetadata=p}get text(){return this.content.filter((e)=>e.type==="text").map((e)=>e.text).join("")}get reasoning(){return this.content.filter((e)=>e.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map((e)=>e.text).join("")}get files(){return this.content.filter((e)=>e.type==="file").map((e)=>e.file)}get sources(){return this.content.filter((e)=>e.type==="source")}get toolCalls(){return this.content.filter((e)=>e.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter((e)=>e.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter((e)=>e.dynamic===!0)}get toolResults(){return this.content.filter((e)=>e.type==="tool-result")}get staticToolResults(){return this.toolResults.filter((e)=>e.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter((e)=>e.dynamic===!0)}};function ji(e){return({steps:t})=>t.length===e}async function Lb({stopConditions:e,steps:t}){return(await Promise.all(e.map((n)=>n({steps:t})))).some((n)=>n)}async function Lc({content:e,tools:t}){let n=[],o=new Map,i=[];for(let s of e){if(s.type==="source")continue;if((s.type==="tool-result"||s.type==="tool-error")&&!s.providerExecuted)continue;if(s.type==="text"&&s.text.length===0)continue;switch(s.type){case"text":i.push({type:"text",text:s.text,providerOptions:s.providerMetadata});break;case"reasoning":i.push({type:"reasoning",text:s.text,providerOptions:s.providerMetadata});break;case"file":i.push({type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata});break;case"tool-call":if(!o.has(s.toolCallId))o.set(s.toolCallId,o.size);i.push({type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.invalid&&typeof s.input!=="object"?{}:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata});break;case"tool-result":{let l=await Ci({toolCallId:s.toolCallId,input:s.input,tool:t==null?void 0:t[s.toolName],output:s.output,errorMode:"none"});i.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:l,providerOptions:s.providerMetadata});break}case"tool-error":{let l=await Ci({toolCallId:s.toolCallId,input:s.input,tool:t==null?void 0:t[s.toolName],output:s.error,errorMode:"json"});i.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:l,providerOptions:s.providerMetadata});break}case"tool-approval-request":i.push({type:"tool-approval-request",approvalId:s.approvalId,toolCallId:s.toolCall.toolCallId,...s.signature!=null?{signature:s.signature}:{}});break}}if(i.length>0)n.push({role:"assistant",content:i});let a=[];for(let s of e){if(!(s.type==="tool-result"||s.type==="tool-error")||s.providerExecuted)continue;let l=await Ci({toolCallId:s.toolCallId,input:s.input,tool:t==null?void 0:t[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"});a.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:l,...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}})}if(a.length>0)n.push({role:"tool",content:Yj({toolResultContent:a,toolCallOrder:o})});return n}function Yj({toolResultContent:e,toolCallOrder:t}){let n=e.filter((i)=>i.type==="tool-result").map((i,a)=>({part:i,index:a})).sort((i,a)=>{let s=t.get(i.part.toolCallId),l=t.get(a.part.toolCallId);if(s==null&&l==null)return i.index-a.index;if(s==null)return 1;if(l==null)return-1;return s-l||i.index-a.index}).map(({part:i})=>i),o=0;return e.map((i)=>i.type==="tool-result"?n[o++]:i)}function qb(...e){let t=e.filter((o)=>o!=null);if(t.length===0)return;if(t.length===1)return t[0];let n=new AbortController;for(let o of t){if(o.aborted)return n.abort(o.reason),n.signal;o.addEventListener("abort",()=>{n.abort(o.reason)},{once:!0})}return n.signal}var Qj=Er({prefix:"aitxt",size:24});async function ru({model:e,tools:t,toolChoice:n,system:o,prompt:i,messages:a,allowSystemInMessages:s,maxRetries:l,abortSignal:c,timeout:u,headers:d,stopWhen:m=ji(1),experimental_output:p,output:f=p,experimental_telemetry:g,providerOptions:h,experimental_activeTools:v,activeTools:x=v,experimental_prepareStep:S,prepareStep:y=S,experimental_repairToolCall:w,experimental_download:_,experimental_context:C,experimental_toolApprovalSecret:I,experimental_include:b,_internal:{generateId:E=Qj}={},experimental_onStart:B,experimental_onStepStart:R,experimental_onToolCallStart:U,experimental_onToolCallFinish:z,onStepFinish:N,onFinish:re,...Y}){let V=ki(e),q=Rb(),ue=zn(m),ee=Hc(u),k=vb(u),X=k!=null?new AbortController:void 0,H=qb(c,ee!=null?AbortSignal.timeout(ee):void 0,X==null?void 0:X.signal),{maxRetries:J,retry:K}=bo({maxRetries:l,abortSignal:H}),D=Ri(Y),F=it(d!=null?d:{},`ai/${vo}`),G=Ai({model:V,telemetry:g,headers:F,settings:{...D,maxRetries:J}}),Z={provider:V.provider,modelId:V.modelId},A=await Zc({system:o,prompt:i,messages:a,allowSystemInMessages:s}),O=q(g==null?void 0:g.integrations);await mr({event:{model:Z,system:o,prompt:i,messages:a,tools:t,toolChoice:n,activeTools:x,maxOutputTokens:D.maxOutputTokens,temperature:D.temperature,topP:D.topP,topK:D.topK,presencePenalty:D.presencePenalty,frequencyPenalty:D.frequencyPenalty,stopSequences:D.stopSequences,seed:D.seed,maxRetries:J,timeout:u,headers:d,providerOptions:h,stopWhen:m,output:f,abortSignal:c,include:b,functionId:g==null?void 0:g.functionId,metadata:g==null?void 0:g.metadata,experimental_context:C},callbacks:[B,O.onStart]});let W=Pi(g);try{return await nr({name:"ai.generateText",attributes:et({telemetry:g,attributes:{...rr({operationId:"ai.generateText",telemetry:g}),...G,"ai.model.provider":V.provider,"ai.model.id":V.modelId,"ai.prompt":{input:()=>JSON.stringify({system:o,prompt:i,messages:a})}}}),tracer:W,fn:async(P)=>{var L,me,Q,de,Ae,Ke,nt,At,Dr,he,br,zr,rn,Tn,_r,st,nn,ut,T,te;let ve=A.messages,Re=[],{approvedToolApprovals:ht,deniedToolApprovals:Vt}=Ab({messages:ve}),{approvedToolApprovals:sr,deniedToolApprovals:lr}=await Db({approvedToolApprovals:ht.filter((It)=>!It.toolCall.providerExecuted),tools:t,messages:ve,experimental_context:C,toolApprovalSecret:I}),se=[...Vt,...lr];if(se.length>0||sr.length>0){let It=await fv({toolCalls:sr.map((Ne)=>Ne.toolCall),tools:t,tracer:W,telemetry:g,messages:ve,abortSignal:H,experimental_context:C,stepNumber:0,model:Z,onToolCallStart:[U,O.onToolCallStart],onToolCallFinish:[z,O.onToolCallFinish]}),Pt=[];for(let Ne of It){let Bt=await Ci({toolCallId:Ne.toolCallId,input:Ne.input,tool:t==null?void 0:t[Ne.toolName],output:Ne.type==="tool-result"?Ne.output:Ne.error,errorMode:Ne.type==="tool-error"?"text":"none"});Pt.push({type:"tool-result",toolCallId:Ne.toolCallId,toolName:Ne.toolName,output:Bt})}for(let Ne of se)Pt.push({type:"tool-result",toolCallId:Ne.toolCall.toolCallId,toolName:Ne.toolCall.toolName,output:{type:"execution-denied",reason:Ne.approvalResponse.reason,...Ne.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:Ne.approvalResponse.approvalId}}}}});Re.push({role:"tool",content:Pt})}let Je=Ri(Y),Fe,lt=[],Oe=[],Be=[],on=new Map;do{let It=Dc({abortController:X,label:"Step",timeoutMs:k});try{let Pt=[...ve,...Re],Ne=await(y==null?void 0:y({model:V,steps:Be,stepNumber:Be.length,messages:Pt,experimental_context:C})),Bt=ki((L=Ne==null?void 0:Ne.model)!=null?L:V),an={provider:Bt.provider,modelId:Bt.modelId},Ur=await Vc({prompt:{system:(me=Ne==null?void 0:Ne.system)!=null?me:A.system,messages:(Q=Ne==null?void 0:Ne.messages)!=null?Q:Pt},supportedUrls:await Bt.supportedUrls,download:_});C=(de=Ne==null?void 0:Ne.experimental_context)!=null?de:C;let sa=(Ae=Ne==null?void 0:Ne.activeTools)!=null?Ae:x,{toolChoice:$r,tools:sn}=await wb({tools:t,toolChoice:(Ke=Ne==null?void 0:Ne.toolChoice)!=null?Ke:n,activeTools:sa}),Sr=(nt=Ne==null?void 0:Ne.messages)!=null?nt:Pt,yt=(At=Ne==null?void 0:Ne.system)!=null?At:A.system,cr=Xa(h,Ne==null?void 0:Ne.providerOptions);await mr({event:{stepNumber:Be.length,model:an,system:yt,messages:Sr,tools:t,toolChoice:$r,activeTools:sa,steps:[...Be],providerOptions:cr,timeout:u,headers:d,stopWhen:m,output:f,abortSignal:c,include:b,functionId:g==null?void 0:g.functionId,metadata:g==null?void 0:g.metadata,experimental_context:C},callbacks:[R,O.onStepStart]}),Fe=await K(()=>{var Me;return nr({name:"ai.generateText.doGenerate",attributes:et({telemetry:g,attributes:{...rr({operationId:"ai.generateText.doGenerate",telemetry:g}),...G,"ai.model.provider":Bt.provider,"ai.model.id":Bt.modelId,"ai.prompt.messages":{input:()=>Yc(Ur)},"ai.prompt.tools":{input:()=>sn==null?void 0:sn.map((Mt)=>JSON.stringify(Mt))},"ai.prompt.toolChoice":{input:()=>$r!=null?JSON.stringify($r):void 0},"gen_ai.system":Bt.provider,"gen_ai.request.model":Bt.modelId,"gen_ai.request.frequency_penalty":Y.frequencyPenalty,"gen_ai.request.max_tokens":Y.maxOutputTokens,"gen_ai.request.presence_penalty":Y.presencePenalty,"gen_ai.request.stop_sequences":Y.stopSequences,"gen_ai.request.temperature":(Me=Y.temperature)!=null?Me:void 0,"gen_ai.request.top_k":Y.topK,"gen_ai.request.top_p":Y.topP}}),tracer:W,fn:async(Mt)=>{var wr,Ct,Bo,ca,ua,cn,un,Wn;let Ye=await Bt.doGenerate({...Je,tools:sn,toolChoice:$r,responseFormat:await(f==null?void 0:f.responseFormat),prompt:Ur,providerOptions:cr,abortSignal:H,headers:F}),Zt={id:(Ct=(wr=Ye.response)==null?void 0:wr.id)!=null?Ct:E(),timestamp:(ca=(Bo=Ye.response)==null?void 0:Bo.timestamp)!=null?ca:new Date,modelId:(cn=(ua=Ye.response)==null?void 0:ua.modelId)!=null?cn:Bt.modelId,headers:(un=Ye.response)==null?void 0:un.headers,body:(Wn=Ye.response)==null?void 0:Wn.body},Go=Ei(Ye.usage);return Mt.setAttributes(await et({telemetry:g,attributes:{"ai.response.finishReason":Ye.finishReason.unified,"ai.response.text":{output:()=>Uc(Ye.content)},"ai.response.reasoning":{output:()=>zc(Ye.content)},"ai.response.toolCalls":{output:()=>{let Vn=hv(Ye.content);return Vn==null?void 0:JSON.stringify(Vn)}},"ai.response.id":Zt.id,"ai.response.model":Zt.modelId,"ai.response.timestamp":Zt.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Ye.providerMetadata),"ai.usage.inputTokens":Ye.usage.inputTokens.total,"ai.usage.inputTokenDetails.noCacheTokens":Ye.usage.inputTokens.noCache,"ai.usage.inputTokenDetails.cacheReadTokens":Ye.usage.inputTokens.cacheRead,"ai.usage.inputTokenDetails.cacheWriteTokens":Ye.usage.inputTokens.cacheWrite,"ai.usage.outputTokens":Ye.usage.outputTokens.total,"ai.usage.outputTokenDetails.textTokens":Ye.usage.outputTokens.text,"ai.usage.outputTokenDetails.reasoningTokens":Ye.usage.outputTokens.reasoning,"ai.usage.totalTokens":Go.totalTokens,"ai.usage.reasoningTokens":Ye.usage.outputTokens.reasoning,"ai.usage.cachedInputTokens":Ye.usage.inputTokens.cacheRead,"gen_ai.response.finish_reasons":[Ye.finishReason.unified],"gen_ai.response.id":Zt.id,"gen_ai.response.model":Zt.modelId,"gen_ai.usage.input_tokens":Ye.usage.inputTokens.total,"gen_ai.usage.output_tokens":Ye.usage.outputTokens.total}})),{...Ye,response:Zt}}})});let ln=await Promise.all(Fe.content.filter((Me)=>Me.type==="tool-call").map((Me)=>zb({toolCall:Me,tools:t,repairToolCall:w,system:o,messages:Pt}))),Hn={};for(let Me of ln){if(Me.invalid)continue;let Mt=t==null?void 0:t[Me.toolName];if(Mt==null)continue;if((Mt==null?void 0:Mt.onInputAvailable)!=null)await Mt.onInputAvailable({input:Me.input,toolCallId:Me.toolCallId,messages:Pt,abortSignal:H,experimental_context:C});if(await eu({tool:Mt,toolCall:Me,messages:Pt,experimental_context:C})){let wr=E(),Ct=await Nb({secret:I,approvalId:wr,toolCallId:Me.toolCallId,toolName:Me.toolName,input:Me.input});Hn[Me.toolCallId]={type:"tool-approval-request",approvalId:wr,toolCall:Me,...Ct!=null?{signature:Ct}:{}}}}let la=ln.filter((Me)=>Me.invalid&&Me.dynamic);Oe=[];for(let Me of la)Oe.push({type:"tool-error",toolCallId:Me.toolCallId,toolName:Me.toolName,input:Me.input,error:hi(Me.error),dynamic:!0});if(lt=ln.filter((Me)=>!Me.providerExecuted),t!=null)Oe.push(...await fv({toolCalls:lt.filter((Me)=>!Me.invalid&&Hn[Me.toolCallId]==null),tools:t,tracer:W,telemetry:g,messages:Pt,abortSignal:H,experimental_context:C,stepNumber:Be.length,model:an,onToolCallStart:[U,O.onToolCallStart],onToolCallFinish:[z,O.onToolCallFinish]}));for(let Me of ln){if(!Me.providerExecuted)continue;let Mt=t==null?void 0:t[Me.toolName];if((Mt==null?void 0:Mt.type)==="provider"&&Mt.supportsDeferredResults){if(!Fe.content.some((Ct)=>Ct.type==="tool-result"&&Ct.toolCallId===Me.toolCallId))on.set(Me.toolCallId,{toolName:Me.toolName})}}for(let Me of Fe.content)if(Me.type==="tool-result")on.delete(Me.toolCallId);let In=eO({content:Fe.content,toolCalls:ln,toolOutputs:Oe,toolApprovalRequests:Object.values(Hn),tools:t});Re.push(...await Lc({content:In,tools:t}));let qo=((Dr=b==null?void 0:b.requestBody)!=null?Dr:!0)?(he=Fe.request)!=null?he:{}:{...Fe.request,body:void 0},Xs={...Fe.response,messages:structuredClone(Re),body:((br=b==null?void 0:b.responseBody)!=null?br:!0)?(zr=Fe.response)==null?void 0:zr.body:void 0},el=Be.length,Fo=new $b({stepNumber:el,model:an,functionId:g==null?void 0:g.functionId,metadata:g==null?void 0:g.metadata,experimental_context:C,content:In,finishReason:Fe.finishReason.unified,rawFinishReason:Fe.finishReason.raw,usage:Ei(Fe.usage),warnings:Fe.warnings,providerMetadata:Fe.providerMetadata,request:qo,response:Xs});gn({warnings:(rn=Fe.warnings)!=null?rn:[],provider:an.provider,model:an.modelId}),Be.push(Fo),await mr({event:Fo,callbacks:[N,O.onStepFinish]})}finally{if(It!=null)clearTimeout(It)}}while((lt.length>0&&Oe.length===lt.length||on.size>0)&&!await Lb({stopConditions:ue,steps:Be}));P.setAttributes(await et({telemetry:g,attributes:{"ai.response.finishReason":Fe.finishReason.unified,"ai.response.text":{output:()=>Uc(Fe.content)},"ai.response.reasoning":{output:()=>zc(Fe.content)},"ai.response.toolCalls":{output:()=>{let It=hv(Fe.content);return It==null?void 0:JSON.stringify(It)}},"ai.response.providerMetadata":JSON.stringify(Fe.providerMetadata)}}));let Ce=Be[Be.length-1],ot=Be.reduce((It,Pt)=>Eb(It,Pt.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});P.setAttributes(await et({telemetry:g,attributes:{"ai.usage.inputTokens":ot.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(Tn=ot.inputTokenDetails)==null?void 0:Tn.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(_r=ot.inputTokenDetails)==null?void 0:_r.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(st=ot.inputTokenDetails)==null?void 0:st.cacheWriteTokens,"ai.usage.outputTokens":ot.outputTokens,"ai.usage.outputTokenDetails.textTokens":(nn=ot.outputTokenDetails)==null?void 0:nn.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(ut=ot.outputTokenDetails)==null?void 0:ut.reasoningTokens,"ai.usage.totalTokens":ot.totalTokens,"ai.usage.reasoningTokens":(T=ot.outputTokenDetails)==null?void 0:T.reasoningTokens,"ai.usage.cachedInputTokens":(te=ot.inputTokenDetails)==null?void 0:te.cacheReadTokens}})),await mr({event:{stepNumber:Ce.stepNumber,model:Ce.model,functionId:Ce.functionId,metadata:Ce.metadata,experimental_context:Ce.experimental_context,finishReason:Ce.finishReason,rawFinishReason:Ce.rawFinishReason,usage:Ce.usage,content:Ce.content,text:Ce.text,reasoningText:Ce.reasoningText,reasoning:Ce.reasoning,files:Ce.files,sources:Ce.sources,toolCalls:Ce.toolCalls,staticToolCalls:Ce.staticToolCalls,dynamicToolCalls:Ce.dynamicToolCalls,toolResults:Ce.toolResults,staticToolResults:Ce.staticToolResults,dynamicToolResults:Ce.dynamicToolResults,request:Ce.request,response:Ce.response,warnings:Ce.warnings,providerMetadata:Ce.providerMetadata,steps:Be,totalUsage:ot},callbacks:[re,O.onFinish]});let ct;if(Ce.finishReason==="stop")ct=await(f!=null?f:Ya()).parseCompleteOutput({text:Ce.text},{response:Ce.response,usage:Ce.usage,finishReason:Ce.finishReason});return new Xj({steps:Be,totalUsage:ot,output:ct})}})}catch(P){throw Kc(P)}}async function fv({toolCalls:e,tools:t,tracer:n,telemetry:o,messages:i,abortSignal:a,experimental_context:s,stepNumber:l,model:c,onToolCallStart:u,onToolCallFinish:d}){return(await Promise.all(e.map(async(p)=>Qc({toolCall:p,tools:t,tracer:n,telemetry:o,messages:i,abortSignal:a,experimental_context:s,stepNumber:l,model:c,onToolCallStart:u,onToolCallFinish:d})))).filter((p)=>p!=null)}var Xj=class{constructor(e){this.steps=e.steps,this._output=e.output,this.totalUsage=e.totalUsage}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get rawFinishReason(){return this.finalStep.rawFinishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get experimental_output(){return this.output}get output(){if(this._output==null)throw new Wa;return this._output}};function hv(e){let t=e.filter((n)=>n.type==="tool-call");if(t.length===0)return;return t.map((n)=>({toolCallId:n.toolCallId,toolName:n.toolName,input:n.input}))}function eO({content:e,toolCalls:t,toolOutputs:n,toolApprovalRequests:o,tools:i}){let a=[];for(let s of e)switch(s.type){case"text":case"reasoning":case"source":a.push(s);break;case"file":{a.push({type:"file",file:new Xc(s),...s.providerMetadata!=null?{providerMetadata:s.providerMetadata}:{}});break}case"tool-call":{a.push(t.find((l)=>l.toolCallId===s.toolCallId));break}case"tool-result":{let l=t.find((c)=>c.toolCallId===s.toolCallId);if(l==null){let c=i==null?void 0:i[s.toolName];if(!((c==null?void 0:c.type)==="provider"&&c.supportsDeferredResults))throw Error(`Tool call ${s.toolCallId} not found.`);if(s.isError)a.push({type:"tool-error",toolCallId:s.toolCallId,toolName:s.toolName,input:void 0,error:s.result,providerExecuted:!0,dynamic:s.dynamic,...s.providerMetadata!=null?{providerMetadata:s.providerMetadata}:{},...(c==null?void 0:c.metadata)!=null?{toolMetadata:c.metadata}:{}});else a.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,input:void 0,output:s.result,providerExecuted:!0,dynamic:s.dynamic,...s.providerMetadata!=null?{providerMetadata:s.providerMetadata}:{},...(c==null?void 0:c.metadata)!=null?{toolMetadata:c.metadata}:{}});break}if(s.isError)a.push({type:"tool-error",toolCallId:s.toolCallId,toolName:s.toolName,input:l.input,error:s.result,providerExecuted:!0,dynamic:l.dynamic,...s.providerMetadata!=null?{providerMetadata:s.providerMetadata}:{},...l.toolMetadata!=null?{toolMetadata:l.toolMetadata}:{}});else a.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,input:l.input,output:s.result,providerExecuted:!0,dynamic:l.dynamic,...s.providerMetadata!=null?{providerMetadata:s.providerMetadata}:{},...l.toolMetadata!=null?{toolMetadata:l.toolMetadata}:{}});break}case"tool-approval-request":{let l=t.find((c)=>c.toolCallId===s.toolCallId);if(l==null)throw new Fc({toolCallId:s.toolCallId,approvalId:s.approvalId});a.push({type:"tool-approval-request",approvalId:s.approvalId,toolCall:l});break}}return[...a,...n,...o]}function Oi(e,t){let n=new Headers(e!=null?e:{});for(let[o,i]of Object.entries(t))if(!n.has(o))n.set(o,i);return n}function tO({status:e,statusText:t,headers:n,textStream:o}){return new Response(o.pipeThrough(new TextEncoderStream),{status:e!=null?e:200,statusText:t,headers:Oi(n,{"content-type":"text/plain; charset=utf-8"})})}function Fb({response:e,status:t,statusText:n,headers:o,stream:i}){let a=t!=null?t:200;if(n!==void 0)e.writeHead(a,n,o);else e.writeHead(a,o);let s=i.getReader();(async()=>{try{while(!0){let{done:c,value:u}=await s.read();if(c)break;if(!e.write(u))await new Promise((m)=>{e.once("drain",m)})}}catch(c){throw c}finally{e.end()}})()}function rO({response:e,status:t,statusText:n,headers:o,textStream:i}){Fb({response:e,status:t,statusText:n,headers:Object.fromEntries(Oi(o,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:i.pipeThrough(new TextEncoderStream)})}var Bb=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
67
+
68
+ `)},flush(e){e.enqueue(`data: [DONE]
69
+
70
+ `)}})}},Gb={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function nO({status:e,statusText:t,headers:n,stream:o,consumeSseStream:i}){let a=o.pipeThrough(new Bb);if(i){let[s,l]=a.tee();a=s,i({stream:l})}return new Response(a.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:Oi(n,Gb)})}function oO({originalMessages:e,responseMessageId:t}){if(e==null)return;let n=e[e.length-1];return(n==null?void 0:n.role)==="assistant"?n.id:typeof t==="function"?t():t}var Ii=r.record(r.string(),Un.optional()),v6=j(()=>M(r.union([r.strictObject({type:r.literal("text-start"),id:r.string(),providerMetadata:fe.optional()}),r.strictObject({type:r.literal("text-delta"),id:r.string(),delta:r.string(),providerMetadata:fe.optional()}),r.strictObject({type:r.literal("text-end"),id:r.string(),providerMetadata:fe.optional()}),r.strictObject({type:r.literal("error"),errorText:r.string()}),r.strictObject({type:r.literal("tool-input-start"),toolCallId:r.string(),toolName:r.string(),providerExecuted:r.boolean().optional(),providerMetadata:fe.optional(),toolMetadata:Ii.optional(),dynamic:r.boolean().optional(),title:r.string().optional()}),r.strictObject({type:r.literal("tool-input-delta"),toolCallId:r.string(),inputTextDelta:r.string()}),r.strictObject({type:r.literal("tool-input-available"),toolCallId:r.string(),toolName:r.string(),input:r.unknown(),providerExecuted:r.boolean().optional(),providerMetadata:fe.optional(),toolMetadata:Ii.optional(),dynamic:r.boolean().optional(),title:r.string().optional()}),r.strictObject({type:r.literal("tool-input-error"),toolCallId:r.string(),toolName:r.string(),input:r.unknown(),providerExecuted:r.boolean().optional(),providerMetadata:fe.optional(),toolMetadata:Ii.optional(),dynamic:r.boolean().optional(),errorText:r.string(),title:r.string().optional()}),r.strictObject({type:r.literal("tool-approval-request"),approvalId:r.string(),toolCallId:r.string(),signature:r.string().optional()}),r.strictObject({type:r.literal("tool-output-available"),toolCallId:r.string(),output:r.unknown(),providerExecuted:r.boolean().optional(),providerMetadata:fe.optional(),toolMetadata:Ii.optional(),dynamic:r.boolean().optional(),preliminary:r.boolean().optional()}),r.strictObject({type:r.literal("tool-output-error"),toolCallId:r.string(),errorText:r.string(),providerExecuted:r.boolean().optional(),providerMetadata:fe.optional(),toolMetadata:Ii.optional(),dynamic:r.boolean().optional()}),r.strictObject({type:r.literal("tool-output-denied"),toolCallId:r.string()}),r.strictObject({type:r.literal("reasoning-start"),id:r.string(),providerMetadata:fe.optional()}),r.strictObject({type:r.literal("reasoning-delta"),id:r.string(),delta:r.string(),providerMetadata:fe.optional()}),r.strictObject({type:r.literal("reasoning-end"),id:r.string(),providerMetadata:fe.optional()}),r.strictObject({type:r.literal("source-url"),sourceId:r.string(),url:r.string(),title:r.string().optional(),providerMetadata:fe.optional()}),r.strictObject({type:r.literal("source-document"),sourceId:r.string(),mediaType:r.string(),title:r.string(),filename:r.string().optional(),providerMetadata:fe.optional()}),r.strictObject({type:r.literal("file"),url:r.string(),mediaType:r.string(),providerMetadata:fe.optional()}),r.strictObject({type:r.custom((e)=>typeof e==="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:r.string().optional(),data:r.unknown(),transient:r.boolean().optional()}),r.strictObject({type:r.literal("start-step")}),r.strictObject({type:r.literal("finish-step")}),r.strictObject({type:r.literal("start"),messageId:r.string().optional(),messageMetadata:r.unknown().optional()}),r.strictObject({type:r.literal("finish"),finishReason:r.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:r.unknown().optional()}),r.strictObject({type:r.literal("abort"),reason:r.string().optional()}),r.strictObject({type:r.literal("message-metadata"),messageMetadata:r.unknown()})])));function iO(e){return e.type.startsWith("data-")}function Wr(){return Object.create(null)}function qc(e){return e.type.startsWith("tool-")}function aO(e){return e.type==="dynamic-tool"}function yv(e){return qc(e)||aO(e)}function vv(e){return e.type.split("-").slice(1).join("-")}function sO({lastMessage:e,messageId:t}){return{message:(e==null?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:Wr(),activeReasoningParts:Wr(),partialToolCalls:Wr()}}function lO({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:o,onError:i,onToolCall:a,onData:s}){return e.pipeThrough(new TransformStream({async transform(l,c){await o(async({state:u,write:d})=>{var m,p,f,g;function h(y){let _=u.message.parts.filter(yv).find((C)=>C.toolCallId===y);if(_==null)throw new fo({chunkType:"tool-invocation",chunkId:y,message:`No tool invocation found for tool call ID "${y}".`});return _}function v(y){var w;let _=u.message.parts.find((b)=>qc(b)&&b.toolCallId===y.toolCallId),C=y,I=_;if(_!=null){if(_.state=y.state,I.input=C.input,I.output=C.output,I.errorText=C.errorText,I.rawInput=C.rawInput,I.preliminary=C.preliminary,y.title!==void 0)I.title=y.title;if(y.toolMetadata!==void 0)I.toolMetadata=y.toolMetadata;I.providerExecuted=(w=C.providerExecuted)!=null?w:_.providerExecuted;let b=C.providerMetadata;if(b!=null)if(y.state==="output-available"||y.state==="output-error"){let E=_;E.resultProviderMetadata=b}else _.callProviderMetadata=b}else u.message.parts.push({type:`tool-${y.toolName}`,toolCallId:y.toolCallId,state:y.state,title:y.title,...y.toolMetadata!==void 0?{toolMetadata:y.toolMetadata}:{},input:C.input,output:C.output,rawInput:C.rawInput,errorText:C.errorText,providerExecuted:C.providerExecuted,preliminary:C.preliminary,...C.providerMetadata!=null&&(y.state==="output-available"||y.state==="output-error")?{resultProviderMetadata:C.providerMetadata}:{},...C.providerMetadata!=null&&!(y.state==="output-available"||y.state==="output-error")?{callProviderMetadata:C.providerMetadata}:{}})}function x(y){var w,_;let C=u.message.parts.find((E)=>E.type==="dynamic-tool"&&E.toolCallId===y.toolCallId),I=y,b=C;if(C!=null){if(C.state=y.state,b.toolName=y.toolName,b.input=I.input,b.output=I.output,b.errorText=I.errorText,b.rawInput=(w=I.rawInput)!=null?w:b.rawInput,b.preliminary=I.preliminary,y.title!==void 0)b.title=y.title;if(y.toolMetadata!==void 0)b.toolMetadata=y.toolMetadata;b.providerExecuted=(_=I.providerExecuted)!=null?_:C.providerExecuted;let E=I.providerMetadata;if(E!=null)if(y.state==="output-available"||y.state==="output-error"){let B=C;B.resultProviderMetadata=E}else C.callProviderMetadata=E}else u.message.parts.push({type:"dynamic-tool",toolName:y.toolName,toolCallId:y.toolCallId,state:y.state,input:I.input,output:I.output,errorText:I.errorText,preliminary:I.preliminary,providerExecuted:I.providerExecuted,title:y.title,...y.toolMetadata!==void 0?{toolMetadata:y.toolMetadata}:{},...I.providerMetadata!=null&&(y.state==="output-available"||y.state==="output-error")?{resultProviderMetadata:I.providerMetadata}:{},...I.providerMetadata!=null&&!(y.state==="output-available"||y.state==="output-error")?{callProviderMetadata:I.providerMetadata}:{}})}async function S(y){if(y!=null){let w=u.message.metadata!=null?Xa(u.message.metadata,y):y;if(t!=null)await Ee({value:w,schema:t,context:{field:"message.metadata",entityId:u.message.id}});u.message.metadata=w}}switch(l.type){case"text-start":{let y={type:"text",text:"",providerMetadata:l.providerMetadata,state:"streaming"};u.activeTextParts[l.id]=y,u.message.parts.push(y),d();break}case"text-delta":{let y=u.activeTextParts[l.id];if(y==null)throw new fo({chunkType:"text-delta",chunkId:l.id,message:`Received text-delta for missing text part with ID "${l.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});y.text+=l.delta,y.providerMetadata=(m=l.providerMetadata)!=null?m:y.providerMetadata,d();break}case"text-end":{let y=u.activeTextParts[l.id];if(y==null)throw new fo({chunkType:"text-end",chunkId:l.id,message:`Received text-end for missing text part with ID "${l.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});y.state="done",y.providerMetadata=(p=l.providerMetadata)!=null?p:y.providerMetadata,delete u.activeTextParts[l.id],d();break}case"reasoning-start":{let y={type:"reasoning",text:"",providerMetadata:l.providerMetadata,state:"streaming"};u.activeReasoningParts[l.id]=y,u.message.parts.push(y),d();break}case"reasoning-delta":{let y=u.activeReasoningParts[l.id];if(y==null)throw new fo({chunkType:"reasoning-delta",chunkId:l.id,message:`Received reasoning-delta for missing reasoning part with ID "${l.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});y.text+=l.delta,y.providerMetadata=(f=l.providerMetadata)!=null?f:y.providerMetadata,d();break}case"reasoning-end":{let y=u.activeReasoningParts[l.id];if(y==null)throw new fo({chunkType:"reasoning-end",chunkId:l.id,message:`Received reasoning-end for missing reasoning part with ID "${l.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});y.providerMetadata=(g=l.providerMetadata)!=null?g:y.providerMetadata,y.state="done",delete u.activeReasoningParts[l.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:l.mediaType,url:l.url,...l.providerMetadata!=null?{providerMetadata:l.providerMetadata}:{}}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:l.sourceId,url:l.url,title:l.title,providerMetadata:l.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:l.sourceId,mediaType:l.mediaType,title:l.title,filename:l.filename,providerMetadata:l.providerMetadata}),d();break}case"tool-input-start":{let y=u.message.parts.filter(qc);if(u.partialToolCalls[l.toolCallId]={text:"",toolName:l.toolName,index:y.length,dynamic:l.dynamic,title:l.title,toolMetadata:l.toolMetadata},l.dynamic)x({toolCallId:l.toolCallId,toolName:l.toolName,state:"input-streaming",input:void 0,providerExecuted:l.providerExecuted,title:l.title,toolMetadata:l.toolMetadata,providerMetadata:l.providerMetadata});else v({toolCallId:l.toolCallId,toolName:l.toolName,state:"input-streaming",input:void 0,providerExecuted:l.providerExecuted,title:l.title,toolMetadata:l.toolMetadata,providerMetadata:l.providerMetadata});d();break}case"tool-input-delta":{let y=u.partialToolCalls[l.toolCallId];if(y==null)throw new fo({chunkType:"tool-input-delta",chunkId:l.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${l.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});y.text+=l.inputTextDelta;let{value:w}=await Mi(y.text);if(y.dynamic)x({toolCallId:l.toolCallId,toolName:y.toolName,state:"input-streaming",input:w,title:y.title,toolMetadata:y.toolMetadata});else v({toolCallId:l.toolCallId,toolName:y.toolName,state:"input-streaming",input:w,title:y.title,toolMetadata:y.toolMetadata});d();break}case"tool-input-available":{if(l.dynamic)x({toolCallId:l.toolCallId,toolName:l.toolName,state:"input-available",input:l.input,providerExecuted:l.providerExecuted,providerMetadata:l.providerMetadata,title:l.title,toolMetadata:l.toolMetadata});else v({toolCallId:l.toolCallId,toolName:l.toolName,state:"input-available",input:l.input,providerExecuted:l.providerExecuted,providerMetadata:l.providerMetadata,title:l.title,toolMetadata:l.toolMetadata});if(d(),a&&!l.providerExecuted)await a({toolCall:l});break}case"tool-input-error":{let y=u.message.parts.filter(yv).find((_)=>_.toolCallId===l.toolCallId);if(y!=null?y.type==="dynamic-tool":!!l.dynamic)x({toolCallId:l.toolCallId,toolName:l.toolName,state:"output-error",input:l.input,errorText:l.errorText,providerExecuted:l.providerExecuted,providerMetadata:l.providerMetadata,toolMetadata:l.toolMetadata});else v({toolCallId:l.toolCallId,toolName:l.toolName,state:"output-error",input:void 0,rawInput:l.input,errorText:l.errorText,providerExecuted:l.providerExecuted,providerMetadata:l.providerMetadata,toolMetadata:l.toolMetadata});d();break}case"tool-approval-request":{let y=h(l.toolCallId);y.state="approval-requested",y.approval={id:l.approvalId,...l.signature!=null?{signature:l.signature}:{}},d();break}case"tool-output-denied":{let y=h(l.toolCallId);y.state="output-denied",d();break}case"tool-output-available":{let y=h(l.toolCallId);if(y.type==="dynamic-tool")x({toolCallId:l.toolCallId,toolName:y.toolName,state:"output-available",input:y.input,output:l.output,preliminary:l.preliminary,providerExecuted:l.providerExecuted,providerMetadata:l.providerMetadata,title:y.title,toolMetadata:y.toolMetadata});else v({toolCallId:l.toolCallId,toolName:vv(y),state:"output-available",input:y.input,output:l.output,providerExecuted:l.providerExecuted,preliminary:l.preliminary,providerMetadata:l.providerMetadata,title:y.title,toolMetadata:y.toolMetadata});d();break}case"tool-output-error":{let y=h(l.toolCallId);if(y.type==="dynamic-tool")x({toolCallId:l.toolCallId,toolName:y.toolName,state:"output-error",input:y.input,errorText:l.errorText,providerExecuted:l.providerExecuted,providerMetadata:l.providerMetadata,title:y.title,toolMetadata:y.toolMetadata});else v({toolCallId:l.toolCallId,toolName:vv(y),state:"output-error",input:y.input,rawInput:y.rawInput,errorText:l.errorText,providerExecuted:l.providerExecuted,providerMetadata:l.providerMetadata,title:y.title,toolMetadata:y.toolMetadata});d();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts=Wr(),u.activeReasoningParts=Wr();break}case"start":{if(l.messageId!=null)u.message.id=l.messageId;if(await S(l.messageMetadata),l.messageId!=null||l.messageMetadata!=null)d();break}case"finish":{if(l.finishReason!=null)u.finishReason=l.finishReason;if(await S(l.messageMetadata),l.messageMetadata!=null)d();break}case"message-metadata":{if(await S(l.messageMetadata),l.messageMetadata!=null)d();break}case"error":{i==null||i(Error(l.errorText));break}default:if(iO(l)){if((n==null?void 0:n[l.type])!=null){let _=u.message.parts.findIndex((I)=>("id"in I)&&("data"in I)&&I.id===l.id&&I.type===l.type),C=_>=0?_:u.message.parts.length;await Ee({value:l.data,schema:n[l.type],context:{field:`message.parts[${C}].data`,entityName:l.type,entityId:l.id}})}let y=l;if(y.transient){s==null||s(y);break}let w=y.id!=null?u.message.parts.find((_)=>y.type===_.type&&y.id===_.id):void 0;if(w!=null)w.data=y.data;else u.message.parts.push(y);s==null||s(y),d()}}c.enqueue(l)})}}))}function Jb({messageId:e,originalMessages:t=[],onStepFinish:n,onFinish:o,onError:i,stream:a}){let s=t==null?void 0:t[t.length-1];if((s==null?void 0:s.role)!=="assistant")s=void 0;else e=s.id;let l=!1,c=a.pipeThrough(new TransformStream({transform(g,h){if(g.type==="start"){let v=g;if(v.messageId==null&&e!=null)v.messageId=e}if(g.type==="abort")l=!0;h.enqueue(g)}}));if(o==null&&n==null)return c;let u=sO({lastMessage:s?structuredClone(s):void 0,messageId:e!=null?e:""}),d=async(g)=>{await g({state:u,write:()=>{}})},m=!1,p=async()=>{if(m||!o)return;m=!0;let g=u.message.id===(s==null?void 0:s.id);await o({isAborted:l,isContinuation:g,responseMessage:u.message,messages:[...g?t.slice(0,-1):t,u.message],finishReason:u.finishReason})},f=async()=>{if(!n)return;let g=u.message.id===(s==null?void 0:s.id);try{await n({isContinuation:g,responseMessage:structuredClone(u.message),messages:[...g?t.slice(0,-1):t,structuredClone(u.message)]})}catch(h){i(h)}};return lO({stream:c,runUpdateMessageJob:d,onError:i}).pipeThrough(new TransformStream({async transform(g,h){if(g.type==="finish-step")await f();h.enqueue(g)},async cancel(){await p()},async flush(){await p()}}))}function cO({response:e,status:t,statusText:n,headers:o,stream:i,consumeSseStream:a}){let s=i.pipeThrough(new Bb);if(a){let[l,c]=s.tee();s=l,a({stream:c})}Fb({response:e,status:t,statusText:n,headers:Object.fromEntries(Oi(o,Gb).entries()),stream:s.pipeThrough(new TextEncoderStream)})}function ho(e){let t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){let n=this.getReader(),o=!1;async function i(a){var s;if(o)return;o=!0;try{if(a)await((s=n.cancel)==null?void 0:s.call(n))}finally{try{n.releaseLock()}catch(l){}}}return{async next(){if(o)return{done:!0,value:void 0};let{done:a,value:s}=await n.read();if(a)return await i(!0),{done:!0,value:void 0};return{done:!1,value:s}},async return(){return await i(!0),{done:!0,value:void 0}},async throw(a){throw await i(!0),a}}},t}async function uO({stream:e,onError:t}){let n=e.getReader();try{while(!0){let{done:o}=await n.read();if(o)break}}catch(o){t==null||t(o)}finally{n.releaseLock()}}function bv(){let e,t;return{promise:new Promise((o,i)=>{e=o,t=i}),resolve:e,reject:t}}function dO(){let e=[],t=null,n=!1,o=bv(),i=()=>{n=!0,o.resolve(),e.forEach((s)=>s.cancel()),e=[],t==null||t.close()},a=async()=>{if(n&&e.length===0){t==null||t.close();return}if(e.length===0)return o=bv(),await o.promise,a();try{let{value:s,done:l}=await e[0].read();if(l)if(e.shift(),e.length===0&&n)t==null||t.close();else await a();else t==null||t.enqueue(s)}catch(s){t==null||t.error(s),e.shift(),i()}};return{stream:new ReadableStream({start(s){t=s},pull:a,async cancel(){for(let s of e)await s.cancel();e=[],n=!0}}),addStream:(s)=>{if(n)throw Error("Cannot add inner stream: outer stream is closed");e.push(s.getReader()),o.resolve()},close:()=>{if(n=!0,o.resolve(),e.length===0)t==null||t.close()},terminate:i}}function pO({tools:e,generatorStream:t,tracer:n,telemetry:o,system:i,messages:a,abortSignal:s,repairToolCall:l,experimental_context:c,toolApprovalSecret:u,generateId:d,stepNumber:m,model:p,onToolCallStart:f,onToolCallFinish:g}){let h=null,v=new ReadableStream({start(I){h=I}}),x=new Set,S=new Map,y=!1,w=void 0;function _(){if(y&&x.size===0){if(w!=null)h.enqueue(w);h.close()}}let C=new TransformStream({async transform(I,b){let E=I.type;switch(E){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{b.enqueue(I);break}case"file":{b.enqueue({type:"file",file:new qj({data:I.data,mediaType:I.mediaType}),...I.providerMetadata!=null?{providerMetadata:I.providerMetadata}:{}});break}case"finish":{w={type:"finish",finishReason:I.finishReason.unified,rawFinishReason:I.finishReason.raw,usage:Ei(I.usage),providerMetadata:I.providerMetadata};break}case"tool-approval-request":{let B=S.get(I.toolCallId);if(B==null){h.enqueue({type:"error",error:new Fc({toolCallId:I.toolCallId,approvalId:I.approvalId})});break}b.enqueue({type:"tool-approval-request",approvalId:I.approvalId,toolCall:B});break}case"tool-call":{try{let B=await zb({toolCall:I,tools:e,repairToolCall:l,system:i,messages:a});if(S.set(B.toolCallId,B),b.enqueue(B),B.invalid){h.enqueue({type:"tool-error",toolCallId:B.toolCallId,toolName:B.toolName,input:B.input,error:hi(B.error),dynamic:!0,title:B.title,...B.toolMetadata!=null?{toolMetadata:B.toolMetadata}:{}});break}let R=e==null?void 0:e[B.toolName];if(R==null)break;if(R.onInputAvailable!=null)await R.onInputAvailable({input:B.input,toolCallId:B.toolCallId,messages:a,abortSignal:s,experimental_context:c});if(await eu({tool:R,toolCall:B,messages:a,experimental_context:c})){let U=d(),z=await Nb({secret:u,approvalId:U,toolCallId:B.toolCallId,toolName:B.toolName,input:B.input});h.enqueue({type:"tool-approval-request",approvalId:U,toolCall:B,...z!=null?{signature:z}:{}});break}if(R.execute!=null&&B.providerExecuted!==!0){let U=d();x.add(U),Qc({toolCall:B,tools:e,tracer:n,telemetry:o,messages:a,abortSignal:s,experimental_context:c,stepNumber:m,model:p,onToolCallStart:f,onToolCallFinish:g,onPreliminaryToolResult:(z)=>{h.enqueue(z)}}).then((z)=>{h.enqueue(z)}).catch((z)=>{h.enqueue({type:"error",error:z})}).finally(()=>{x.delete(U),_()})}}catch(B){h.enqueue({type:"error",error:B})}break}case"tool-result":{let B=I.toolName,R=S.get(I.toolCallId);if(I.isError)h.enqueue({type:"tool-error",toolCallId:I.toolCallId,toolName:B,input:R==null?void 0:R.input,providerExecuted:!0,error:I.result,dynamic:I.dynamic,...I.providerMetadata!=null?{providerMetadata:I.providerMetadata}:{},...(R==null?void 0:R.toolMetadata)!=null?{toolMetadata:R.toolMetadata}:{}});else b.enqueue({type:"tool-result",toolCallId:I.toolCallId,toolName:B,input:R==null?void 0:R.input,output:I.result,providerExecuted:!0,dynamic:I.dynamic,...I.providerMetadata!=null?{providerMetadata:I.providerMetadata}:{},...(R==null?void 0:R.toolMetadata)!=null?{toolMetadata:R.toolMetadata}:{}});break}default:throw Error(`Unhandled chunk type: ${E}`)}},flush(){y=!0,_()}});return new ReadableStream({async start(I){return Promise.all([t.pipeThrough(C).pipeTo(new WritableStream({write(b){I.enqueue(b)},close(){}})),v.pipeTo(new WritableStream({write(b){I.enqueue(b)},close(){I.close()}}))])}})}var mO=Er({prefix:"aitxt",size:24}),gO={file:!0,source:!0,"text-start":!0,"text-end":!0,"text-delta":!0,"reasoning-start":!0,"reasoning-end":!0,"reasoning-delta":!0,"tool-input-start":!0,"tool-input-end":!0,"tool-input-delta":!0,"tool-approval-request":!0,"tool-call":!0,"tool-result":!0,"tool-error":!0,"stream-start":!1,"response-metadata":!1,finish:!1,error:!1,raw:!1};function fO({model:e,tools:t,toolChoice:n,system:o,prompt:i,messages:a,allowSystemInMessages:s,maxRetries:l,abortSignal:c,timeout:u,headers:d,stopWhen:m=ji(1),experimental_output:p,output:f=p,experimental_telemetry:g,prepareStep:h,providerOptions:v,experimental_activeTools:x,activeTools:S=x,experimental_repairToolCall:y,experimental_transform:w,experimental_download:_,includeRawChunks:C=!1,onChunk:I,onError:b=({error:X})=>{console.error(X)},onFinish:E,onAbort:B,onStepFinish:R,experimental_onStart:U,experimental_onStepStart:z,experimental_onToolCallStart:N,experimental_onToolCallFinish:re,experimental_context:Y,experimental_toolApprovalSecret:V,experimental_include:q,_internal:{now:ue=Va,generateId:ee=mO}={},...k}){let X=Hc(u),H=vb(u),J=gj(u),K=H!=null?new AbortController:void 0,D=J!=null?new AbortController:void 0;return new yO({model:ki(e),telemetry:g,headers:d,settings:k,maxRetries:l,abortSignal:qb(c,X!=null?AbortSignal.timeout(X):void 0,K==null?void 0:K.signal,D==null?void 0:D.signal),stepTimeoutMs:H,stepAbortController:K,chunkTimeoutMs:J,chunkAbortController:D,system:o,prompt:i,messages:a,allowSystemInMessages:s,tools:t,toolChoice:n,transforms:zn(w),activeTools:S,repairToolCall:y,stopConditions:zn(m),output:f,providerOptions:v,prepareStep:h,includeRawChunks:C,timeout:u,stopWhen:m,originalAbortSignal:c,onChunk:I,onError:b,onFinish:E,onAbort:B,onStepFinish:R,onStart:U,onStepStart:z,onToolCallStart:N,onToolCallFinish:re,now:ue,generateId:ee,experimental_context:Y,experimental_toolApprovalSecret:V,download:_,include:q})}function hO(e){let t=void 0,n="",o="",i=void 0,a="";function s({controller:l,partialOutput:c=void 0}){l.enqueue({part:{type:"text-delta",id:t,text:o,providerMetadata:i},partialOutput:c}),o=""}return new TransformStream({async transform(l,c){var u;if(l.type==="finish-step"&&o.length>0)s({controller:c});if(l.type!=="text-delta"&&l.type!=="text-start"&&l.type!=="text-end"){c.enqueue({part:l,partialOutput:void 0});return}if(t==null)t=l.id;else if(l.id!==t){c.enqueue({part:l,partialOutput:void 0});return}if(l.type==="text-start"){c.enqueue({part:l,partialOutput:void 0});return}if(l.type==="text-end"){if(o.length>0)s({controller:c});c.enqueue({part:l,partialOutput:void 0});return}n+=l.text,o+=l.text,i=(u=l.providerMetadata)!=null?u:i;let d=await e.parsePartialOutput({text:n});if(d!==void 0){let m=typeof d.partial==="string"?d.partial:JSON.stringify(d.partial);if(m!==a)s({controller:c,partialOutput:d.partial}),a=m}}})}var yO=class{constructor({model:e,telemetry:t,headers:n,settings:o,maxRetries:i,abortSignal:a,stepTimeoutMs:s,stepAbortController:l,chunkTimeoutMs:c,chunkAbortController:u,system:d,prompt:m,messages:p,allowSystemInMessages:f,tools:g,toolChoice:h,transforms:v,activeTools:x,repairToolCall:S,stopConditions:y,output:w,providerOptions:_,prepareStep:C,includeRawChunks:I,now:b,generateId:E,timeout:B,stopWhen:R,originalAbortSignal:U,onChunk:z,onError:N,onFinish:re,onAbort:Y,onStepFinish:V,onStart:q,onStepStart:ue,onToolCallStart:ee,onToolCallFinish:k,experimental_context:X,experimental_toolApprovalSecret:H,download:J,include:K}){this._totalUsage=new jn,this._finishReason=new jn,this._rawFinishReason=new jn,this._steps=new jn,this.outputSpecification=w,this.includeRawChunks=I,this.tools=g;let F=Rb()(t==null?void 0:t.integrations),G,Z=[],A=[],O=void 0,W=void 0,P=void 0,L={},me=[],Q=[],de,Ae=new Map,Ke,nt=Wr(),At=Wr(),Dr=new TransformStream({async transform(ve,Re){var ht,Vt,sr,lr;Re.enqueue(ve);let{part:se}=ve;if(se.type==="text-delta"||se.type==="reasoning-delta"||se.type==="source"||se.type==="tool-call"||se.type==="tool-result"||se.type==="tool-input-start"||se.type==="tool-input-delta"||se.type==="raw")await(z==null?void 0:z({chunk:se}));if(se.type==="error"){let Je=Kc(se.error);if(Wa.isInstance(Je))de=Je;await N({error:Je})}if(se.type==="text-start")nt[se.id]={type:"text",text:"",providerMetadata:se.providerMetadata},Z.push(nt[se.id]);if(se.type==="text-delta"){let Je=nt[se.id];if(Je==null){Re.enqueue({part:{type:"error",error:`text part ${se.id} not found`},partialOutput:void 0});return}Je.text+=se.text,Je.providerMetadata=(ht=se.providerMetadata)!=null?ht:Je.providerMetadata}if(se.type==="text-end"){let Je=nt[se.id];if(Je==null){Re.enqueue({part:{type:"error",error:`text part ${se.id} not found`},partialOutput:void 0});return}Je.providerMetadata=(Vt=se.providerMetadata)!=null?Vt:Je.providerMetadata,delete nt[se.id]}if(se.type==="reasoning-start")At[se.id]={type:"reasoning",text:"",providerMetadata:se.providerMetadata},Z.push(At[se.id]);if(se.type==="reasoning-delta"){let Je=At[se.id];if(Je==null){Re.enqueue({part:{type:"error",error:`reasoning part ${se.id} not found`},partialOutput:void 0});return}Je.text+=se.text,Je.providerMetadata=(sr=se.providerMetadata)!=null?sr:Je.providerMetadata}if(se.type==="reasoning-end"){let Je=At[se.id];if(Je==null){Re.enqueue({part:{type:"error",error:`reasoning part ${se.id} not found`},partialOutput:void 0});return}Je.providerMetadata=(lr=se.providerMetadata)!=null?lr:Je.providerMetadata,delete At[se.id]}if(se.type==="file")Z.push({type:"file",file:se.file,...se.providerMetadata!=null?{providerMetadata:se.providerMetadata}:{}});if(se.type==="source")Z.push(se);if(se.type==="tool-call")Z.push(se);if(se.type==="tool-result"&&!se.preliminary)Z.push(se);if(se.type==="tool-approval-request")Z.push(se);if(se.type==="tool-error")Z.push(se);if(se.type==="start-step")Z=[],At=Wr(),nt=Wr(),L=se.request,me=se.warnings;if(se.type==="finish-step"){let Je=await Lc({content:Z,tools:g}),Fe=new $b({stepNumber:Q.length,model:T,...te,experimental_context:X,content:Z,finishReason:se.finishReason,rawFinishReason:se.rawFinishReason,usage:se.usage,warnings:me,request:L,response:{...se.response,messages:[...A,...Je]},providerMetadata:se.providerMetadata});await mr({event:Fe,callbacks:[V,F.onStepFinish]}),gn({warnings:me,provider:T.provider,model:T.modelId}),Q.push(Fe),A.push(...Je),G.resolve()}if(se.type==="finish")P=se.totalUsage,O=se.finishReason,W=se.rawFinishReason},async flush(ve){var Re,ht,Vt,sr,lr,se,Je;try{if(Q.length===0||de!=null){let Be=(a==null?void 0:a.aborted)?a.reason:de!=null?de:new Wa({message:"No output generated. Check the stream for errors."});ut._finishReason.reject(Be),ut._rawFinishReason.reject(Be),ut._totalUsage.reject(Be),ut._steps.reject(Be);return}let Fe=O!=null?O:"other",lt=P!=null?P:jc();ut._finishReason.resolve(Fe),ut._rawFinishReason.resolve(W),ut._totalUsage.resolve(lt),ut._steps.resolve(Q);let Oe=Q[Q.length-1];await mr({event:{stepNumber:Oe.stepNumber,model:Oe.model,functionId:Oe.functionId,metadata:Oe.metadata,experimental_context:Oe.experimental_context,finishReason:Oe.finishReason,rawFinishReason:Oe.rawFinishReason,totalUsage:lt,usage:Oe.usage,content:Oe.content,text:Oe.text,reasoningText:Oe.reasoningText,reasoning:Oe.reasoning,files:Oe.files,sources:Oe.sources,toolCalls:Oe.toolCalls,staticToolCalls:Oe.staticToolCalls,dynamicToolCalls:Oe.dynamicToolCalls,toolResults:Oe.toolResults,staticToolResults:Oe.staticToolResults,dynamicToolResults:Oe.dynamicToolResults,request:Oe.request,response:Oe.response,warnings:Oe.warnings,providerMetadata:Oe.providerMetadata,steps:Q},callbacks:[re,F.onFinish]}),Ke.setAttributes(await et({telemetry:t,attributes:{"ai.response.finishReason":Fe,"ai.response.text":{output:()=>Oe.text},"ai.response.reasoning":{output:()=>Oe.reasoningText},"ai.response.toolCalls":{output:()=>{var Be;return((Be=Oe.toolCalls)==null?void 0:Be.length)?JSON.stringify(Oe.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(Oe.providerMetadata),"ai.usage.inputTokens":lt.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(Re=lt.inputTokenDetails)==null?void 0:Re.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(ht=lt.inputTokenDetails)==null?void 0:ht.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(Vt=lt.inputTokenDetails)==null?void 0:Vt.cacheWriteTokens,"ai.usage.outputTokens":lt.outputTokens,"ai.usage.outputTokenDetails.textTokens":(sr=lt.outputTokenDetails)==null?void 0:sr.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(lr=lt.outputTokenDetails)==null?void 0:lr.reasoningTokens,"ai.usage.totalTokens":lt.totalTokens,"ai.usage.reasoningTokens":(se=lt.outputTokenDetails)==null?void 0:se.reasoningTokens,"ai.usage.cachedInputTokens":(Je=lt.inputTokenDetails)==null?void 0:Je.cacheReadTokens}}))}catch(Fe){ve.error(Fe)}finally{Ke.end()}}}),he=dO();this.addStream=he.addStream,this.closeStream=he.close;let br=he.stream.getReader(),zr=new ReadableStream({async start(ve){ve.enqueue({type:"start"})},async pull(ve){function Re(){Y==null||Y({steps:Q}),ve.enqueue({type:"abort",...(a==null?void 0:a.reason)!==void 0?{reason:Tr(a.reason)}:{}}),ve.close()}try{let{done:ht,value:Vt}=await br.read();if(ht){ve.close();return}if(a==null?void 0:a.aborted){Re();return}ve.enqueue(Vt)}catch(ht){if(Yt(ht)&&(a==null?void 0:a.aborted))Re();else ve.error(ht)}},cancel(ve){return he.stream.cancel(ve)}});for(let ve of v)zr=zr.pipeThrough(ve({tools:g,stopStream(){he.terminate()}}));this.baseStream=zr.pipeThrough(hO(w!=null?w:Ya())).pipeThrough(Dr);let{maxRetries:rn,retry:Tn}=bo({maxRetries:i,abortSignal:a}),_r=Pi(t),st=Ri(o),nn=Ai({model:e,telemetry:t,headers:n,settings:{...st,maxRetries:rn}}),ut=this,T={provider:e.provider,modelId:e.modelId},te={functionId:t==null?void 0:t.functionId,metadata:t==null?void 0:t.metadata};nr({name:"ai.streamText",attributes:et({telemetry:t,attributes:{...rr({operationId:"ai.streamText",telemetry:t}),...nn,"ai.prompt":{input:()=>JSON.stringify({system:d,prompt:m,messages:p})}}}),tracer:_r,endWhenDone:!1,fn:async(ve)=>{Ke=ve;let Re=await Zc({system:d,prompt:m,messages:p,allowSystemInMessages:f});await mr({event:{model:T,system:d,prompt:m,messages:p,tools:g,toolChoice:h,activeTools:x,maxOutputTokens:st.maxOutputTokens,temperature:st.temperature,topP:st.topP,topK:st.topK,presencePenalty:st.presencePenalty,frequencyPenalty:st.frequencyPenalty,stopSequences:st.stopSequences,seed:st.seed,maxRetries:rn,timeout:B,headers:n,providerOptions:_,stopWhen:R,output:w,abortSignal:U,include:K,...te,experimental_context:X},callbacks:[q,F.onStart]});let ht=Re.messages,Vt=[],{approvedToolApprovals:sr,deniedToolApprovals:lr}=Ab({messages:ht});if(lr.length>0||sr.length>0){let{approvedToolApprovals:Je,deniedToolApprovals:Fe}=await Db({approvedToolApprovals:sr.filter((Ce)=>!Ce.toolCall.providerExecuted),tools:g,messages:ht,experimental_context:X,toolApprovalSecret:H}),lt=[...lr.filter((Ce)=>!Ce.toolCall.providerExecuted),...Fe],Oe=lr.filter((Ce)=>Ce.toolCall.providerExecuted),Be,on=new ReadableStream({start(Ce){Be=Ce}});ut.addStream(on);try{for(let ot of[...lt,...Oe])Be==null||Be.enqueue({type:"tool-output-denied",toolCallId:ot.toolCall.toolCallId,toolName:ot.toolCall.toolName});let Ce=[];if(await Promise.all(Je.map(async(ot)=>{let ct=await Qc({toolCall:ot.toolCall,tools:g,tracer:_r,telemetry:t,messages:ht,abortSignal:a,experimental_context:X,stepNumber:Q.length,model:T,onToolCallStart:[ee,F.onToolCallStart],onToolCallFinish:[k,F.onToolCallFinish],onPreliminaryToolResult:(It)=>{Be==null||Be.enqueue(It)}});if(ct!=null)Be==null||Be.enqueue(ct),Ce.push(ct)})),Ce.length>0||lt.length>0){let ot=[];for(let ct of Ce)ot.push({type:"tool-result",toolCallId:ct.toolCallId,toolName:ct.toolName,output:await Ci({toolCallId:ct.toolCallId,input:ct.input,tool:g==null?void 0:g[ct.toolName],output:ct.type==="tool-result"?ct.output:ct.error,errorMode:ct.type==="tool-error"?"text":"none"})});for(let ct of lt)ot.push({type:"tool-result",toolCallId:ct.toolCall.toolCallId,toolName:ct.toolCall.toolName,output:{type:"execution-denied",reason:ct.approvalResponse.reason}});Vt.push({role:"tool",content:ot})}}finally{Be==null||Be.close()}}A.push(...Vt);async function se({currentStep:Je,responseMessages:Fe,usage:lt}){var Oe,Be,on,Ce,ot,ct,It,Pt,Ne;let Bt=ut.includeRawChunks,an=Dc({abortController:l,label:"Step",timeoutMs:s}),Ur=void 0;function sa(){if(Ur!=null)clearTimeout(Ur);Ur=Dc({abortController:u,label:"Chunk",timeoutMs:c})}function $r(){if(Ur!=null)clearTimeout(Ur),Ur=void 0}function sn(){if(an!=null)clearTimeout(an)}a==null||a.addEventListener("abort",sn),a==null||a.addEventListener("abort",$r);try{G=new jn;let Sr=[...ht,...Fe],yt=await(C==null?void 0:C({model:e,steps:Q,stepNumber:Q.length,messages:Sr,experimental_context:X})),cr=ki((Oe=yt==null?void 0:yt.model)!=null?Oe:e),ln={provider:cr.provider,modelId:cr.modelId},Hn=await Vc({prompt:{system:(Be=yt==null?void 0:yt.system)!=null?Be:Re.system,messages:(on=yt==null?void 0:yt.messages)!=null?on:Sr},supportedUrls:await cr.supportedUrls,download:J}),la=(Ce=yt==null?void 0:yt.activeTools)!=null?Ce:x,{toolChoice:In,tools:qo}=await wb({tools:g,toolChoice:(ot=yt==null?void 0:yt.toolChoice)!=null?ot:h,activeTools:la});X=(ct=yt==null?void 0:yt.experimental_context)!=null?ct:X;let Xs=(It=yt==null?void 0:yt.messages)!=null?It:Sr,el=(Pt=yt==null?void 0:yt.system)!=null?Pt:Re.system,Fo=Xa(_,yt==null?void 0:yt.providerOptions);await mr({event:{stepNumber:Q.length,model:ln,system:el,messages:Xs,tools:g,toolChoice:In,activeTools:la,steps:[...Q],providerOptions:Fo,timeout:B,headers:n,stopWhen:R,output:w,abortSignal:U,include:K,...te,experimental_context:X},callbacks:[ue,F.onStepStart]});let{result:{stream:Me,response:Mt,request:wr},doStreamSpan:Ct,startTimestampMs:Bo}=await Tn(()=>nr({name:"ai.streamText.doStream",attributes:et({telemetry:t,attributes:{...rr({operationId:"ai.streamText.doStream",telemetry:t}),...nn,"ai.model.provider":cr.provider,"ai.model.id":cr.modelId,"ai.prompt.messages":{input:()=>Yc(Hn)},"ai.prompt.tools":{input:()=>qo==null?void 0:qo.map((be)=>JSON.stringify(be))},"ai.prompt.toolChoice":{input:()=>In!=null?JSON.stringify(In):void 0},"gen_ai.system":cr.provider,"gen_ai.request.model":cr.modelId,"gen_ai.request.frequency_penalty":st.frequencyPenalty,"gen_ai.request.max_tokens":st.maxOutputTokens,"gen_ai.request.presence_penalty":st.presencePenalty,"gen_ai.request.stop_sequences":st.stopSequences,"gen_ai.request.temperature":st.temperature,"gen_ai.request.top_k":st.topK,"gen_ai.request.top_p":st.topP}}),tracer:_r,endWhenDone:!1,fn:async(be)=>({startTimestampMs:b(),doStreamSpan:be,result:await cr.doStream({...st,tools:qo,toolChoice:In,responseFormat:await(w==null?void 0:w.responseFormat),prompt:Hn,providerOptions:Fo,abortSignal:a,headers:n,includeRawChunks:Bt})})})),ca=pO({tools:g,generatorStream:Me,tracer:_r,telemetry:t,system:d,messages:Sr,repairToolCall:S,abortSignal:a,experimental_context:X,toolApprovalSecret:H,generateId:E,stepNumber:Q.length,model:ln,onToolCallStart:[ee,F.onToolCallStart],onToolCallFinish:[k,F.onToolCallFinish]}),ua=((Ne=K==null?void 0:K.requestBody)!=null?Ne:!0)?wr!=null?wr:{}:{...wr,body:void 0},cn=[],un=[],Wn,Ye={},Zt="other",Go=void 0,Vn=!1,fp=!1,jt=jc(),hp,yp=!0,xr={id:E(),timestamp:new Date,modelId:T.modelId},s0="";ut.addStream(ca.pipeThrough(new TransformStream({async transform(be,_t){var Jo,Ho,Wo,Vo,Zo;if(sa(),be.type==="stream-start"){Wn=be.warnings;return}if(yp){let St=b()-Bo;yp=!1,Ct.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":St}),Ct.setAttributes({"ai.response.msToFirstChunk":St}),_t.enqueue({type:"start-step",request:ua,warnings:Wn!=null?Wn:[]})}let Zn=be.type;if(gO[Zn])fp=!0;switch(Zn){case"tool-approval-request":case"text-start":case"text-end":{_t.enqueue(be);break}case"text-delta":{if(be.delta.length>0)_t.enqueue({type:"text-delta",id:be.id,text:be.delta,providerMetadata:be.providerMetadata}),s0+=be.delta;break}case"reasoning-start":case"reasoning-end":{_t.enqueue(be);break}case"reasoning-delta":{_t.enqueue({type:"reasoning-delta",id:be.id,text:be.delta,providerMetadata:be.providerMetadata});break}case"tool-call":{_t.enqueue(be),cn.push(be);break}case"tool-result":{if(_t.enqueue(be),!be.preliminary)un.push(be);break}case"tool-error":{_t.enqueue(be),un.push(be);break}case"response-metadata":{xr={id:(Jo=be.id)!=null?Jo:xr.id,timestamp:(Ho=be.timestamp)!=null?Ho:xr.timestamp,modelId:(Wo=be.modelId)!=null?Wo:xr.modelId};break}case"finish":{Vn=!0,jt=be.usage,Zt=be.finishReason,Go=be.rawFinishReason,hp=be.providerMetadata;let St=b()-Bo;Ct.addEvent("ai.stream.finish"),Ct.setAttributes({"ai.response.msToFinish":St,"ai.response.avgOutputTokensPerSecond":1000*((Vo=jt.outputTokens)!=null?Vo:0)/St});break}case"file":{_t.enqueue(be);break}case"source":{_t.enqueue(be);break}case"tool-input-start":{Ye[be.id]=be.toolName;let St=g==null?void 0:g[be.toolName];if((St==null?void 0:St.onInputStart)!=null)await St.onInputStart({toolCallId:be.id,messages:Sr,abortSignal:a,experimental_context:X});_t.enqueue({...be,dynamic:(Zo=be.dynamic)!=null?Zo:(St==null?void 0:St.type)==="dynamic",title:St==null?void 0:St.title});break}case"tool-input-end":{delete Ye[be.id],_t.enqueue(be);break}case"tool-input-delta":{let St=Ye[be.id],Kn=g==null?void 0:g[St];if((Kn==null?void 0:Kn.onInputDelta)!=null)await Kn.onInputDelta({inputTextDelta:be.delta,toolCallId:be.id,messages:Sr,abortSignal:a,experimental_context:X});_t.enqueue(be);break}case"error":{Vn=!0,_t.enqueue(be),Zt="error";break}case"raw":{if(Bt)_t.enqueue(be);break}default:throw Error(`Unknown chunk type: ${Zn}`)}},async flush(be){var _t,Jo,Ho,Wo,Vo,Zo,Zn;if(!Vn&&!fp){be.enqueue({type:"error",error:new Wa({message:"No output generated. The model stream ended without a finish chunk."})}),Ct.end(),sn(),$r(),ut.closeStream();return}let St=cn.length>0?JSON.stringify(cn):void 0;try{Ct.setAttributes(await et({telemetry:t,attributes:{"ai.response.finishReason":Zt,"ai.response.toolCalls":{output:()=>St},"ai.response.id":xr.id,"ai.response.model":xr.modelId,"ai.response.timestamp":xr.timestamp.toISOString(),"ai.usage.inputTokens":jt.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(_t=jt.inputTokenDetails)==null?void 0:_t.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(Jo=jt.inputTokenDetails)==null?void 0:Jo.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(Ho=jt.inputTokenDetails)==null?void 0:Ho.cacheWriteTokens,"ai.usage.outputTokens":jt.outputTokens,"ai.usage.outputTokenDetails.textTokens":(Wo=jt.outputTokenDetails)==null?void 0:Wo.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(Vo=jt.outputTokenDetails)==null?void 0:Vo.reasoningTokens,"ai.usage.totalTokens":jt.totalTokens,"ai.usage.reasoningTokens":(Zo=jt.outputTokenDetails)==null?void 0:Zo.reasoningTokens,"ai.usage.cachedInputTokens":(Zn=jt.inputTokenDetails)==null?void 0:Zn.cacheReadTokens,"gen_ai.response.finish_reasons":[Zt],"gen_ai.response.id":xr.id,"gen_ai.response.model":xr.modelId,"gen_ai.usage.input_tokens":jt.inputTokens,"gen_ai.usage.output_tokens":jt.outputTokens}}))}catch(kt){}be.enqueue({type:"finish-step",finishReason:Zt,rawFinishReason:Go,usage:jt,providerMetadata:hp,response:{...xr,headers:Mt==null?void 0:Mt.headers}});let Kn=Eb(lt,jt);await G.promise;let tl=Q[Q.length-1];try{Ct.setAttributes(await et({telemetry:t,attributes:{"ai.response.text":{output:()=>tl.text},"ai.response.reasoning":{output:()=>tl.reasoningText},"ai.response.providerMetadata":JSON.stringify(tl.providerMetadata)}}))}catch(kt){}finally{Ct.end()}let vp=cn.filter((kt)=>kt.providerExecuted!==!0),l0=un.filter((kt)=>kt.providerExecuted!==!0);for(let kt of cn){if(kt.providerExecuted!==!0)continue;let rl=g==null?void 0:g[kt.toolName];if((rl==null?void 0:rl.type)==="provider"&&rl.supportsDeferredResults){if(!un.some((nl)=>(nl.type==="tool-result"||nl.type==="tool-error")&&nl.toolCallId===kt.toolCallId))Ae.set(kt.toolCallId,{toolName:kt.toolName})}}for(let kt of un)if(kt.type==="tool-result"||kt.type==="tool-error")Ae.delete(kt.toolCallId);if(sn(),$r(),(vp.length>0&&l0.length===vp.length||Ae.size>0)&&!await Lb({stopConditions:y,steps:Q})){Fe.push(...await Lc({content:Q[Q.length-1].content,tools:g}));try{await se({currentStep:Je+1,responseMessages:Fe,usage:Kn})}catch(kt){be.enqueue({type:"error",error:kt}),ut.closeStream()}}else be.enqueue({type:"finish",finishReason:Zt,rawFinishReason:Go,totalUsage:Kn}),ut.closeStream()}})))}catch(Sr){throw sn(),$r(),Sr}}await se({currentStep:0,responseMessages:Vt,usage:jc()})}}).catch((ve)=>{ut.addStream(new ReadableStream({start(Re){Re.enqueue({type:"error",error:ve}),Re.close()}})),ut.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then((e)=>e[e.length-1])}get content(){return this.finalStep.then((e)=>e.content)}get warnings(){return this.finalStep.then((e)=>e.warnings)}get providerMetadata(){return this.finalStep.then((e)=>e.providerMetadata)}get text(){return this.finalStep.then((e)=>e.text)}get reasoningText(){return this.finalStep.then((e)=>e.reasoningText)}get reasoning(){return this.finalStep.then((e)=>e.reasoning)}get sources(){return this.finalStep.then((e)=>e.sources)}get files(){return this.finalStep.then((e)=>e.files)}get toolCalls(){return this.finalStep.then((e)=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then((e)=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then((e)=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then((e)=>e.toolResults)}get staticToolResults(){return this.finalStep.then((e)=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then((e)=>e.dynamicToolResults)}get usage(){return this.finalStep.then((e)=>e.usage)}get request(){return this.finalStep.then((e)=>e.request)}get response(){return this.finalStep.then((e)=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}get rawFinishReason(){return this.consumeStream(),this._rawFinishReason.promise}teeStream(){let[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return ho(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){if(e.type==="text-delta")t.enqueue(e.text)}})))}get fullStream(){return ho(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}rejectResultPromises(e){if(this._finishReason.isPending())this._finishReason.reject(e);if(this._rawFinishReason.isPending())this._rawFinishReason.reject(e);if(this._totalUsage.isPending())this._totalUsage.reject(e);if(this._steps.isPending())this._steps.reject(e)}async consumeStream(e){var t;try{await uO({stream:this.fullStream,onError:(n)=>{var o;this.rejectResultPromises(n),(o=e==null?void 0:e.onError)==null||o.call(e,n)}})}catch(n){this.rejectResultPromises(n),(t=e==null?void 0:e.onError)==null||t.call(e,n)}}get experimental_partialOutputStream(){return this.partialOutputStream}get partialOutputStream(){return ho(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){if(e!=null)t.enqueue(e)}})))}get elementStream(){var e,t,n;let o=(e=this.outputSpecification)==null?void 0:e.createElementStreamTransform();if(o==null)throw new We({functionality:`element streams in ${(n=(t=this.outputSpecification)==null?void 0:t.name)!=null?n:"text"} mode`});return ho(this.teeStream().pipeThrough(o))}get output(){return this.finalStep.then((e)=>{var t;return((t=this.outputSpecification)!=null?t:Ya()).parseCompleteOutput({text:e.text},{response:e.response,usage:e.usage,finishReason:e.finishReason})})}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:o,sendReasoning:i=!0,sendSources:a=!1,sendStart:s=!0,sendFinish:l=!0,onError:c=()=>"An error occurred."}={}){let u=t!=null?oO({originalMessages:e,responseMessageId:t}):void 0,d=(p)=>{var f;let g=(f=this.tools)==null?void 0:f[p.toolName];if(g==null)return p.dynamic;return(g==null?void 0:g.type)==="dynamic"?!0:void 0},m=this.fullStream.pipeThrough(new TransformStream({transform:async(p,f)=>{let g=o==null?void 0:o({part:p}),h=p.type;switch(h){case"text-start":{f.enqueue({type:"text-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-delta":{f.enqueue({type:"text-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-end":{f.enqueue({type:"text-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-start":case"reasoning-end":{if(i)f.enqueue({type:h,id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-delta":{if(i)f.enqueue({type:"reasoning-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"file":{f.enqueue({type:"file",mediaType:p.file.mediaType,url:`data:${p.file.mediaType};base64,${p.file.base64}`,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"source":{if(a&&p.sourceType==="url")f.enqueue({type:"source-url",sourceId:p.id,url:p.url,title:p.title,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});if(a&&p.sourceType==="document")f.enqueue({type:"source-document",sourceId:p.id,mediaType:p.mediaType,title:p.title,filename:p.filename,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"tool-input-start":{let v=d(p);f.enqueue({type:"tool-input-start",toolCallId:p.id,toolName:p.toolName,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...p.toolMetadata!=null?{toolMetadata:p.toolMetadata}:{},...v!=null?{dynamic:v}:{},...p.title!=null?{title:p.title}:{}});break}case"tool-input-delta":{f.enqueue({type:"tool-input-delta",toolCallId:p.id,inputTextDelta:p.delta});break}case"tool-call":{let v=d(p);if(p.invalid)f.enqueue({type:"tool-input-error",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...p.toolMetadata!=null?{toolMetadata:p.toolMetadata}:{},...v!=null?{dynamic:v}:{},errorText:c(p.error),...p.title!=null?{title:p.title}:{}});else f.enqueue({type:"tool-input-available",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...p.toolMetadata!=null?{toolMetadata:p.toolMetadata}:{},...v!=null?{dynamic:v}:{},...p.title!=null?{title:p.title}:{}});break}case"tool-approval-request":{f.enqueue({type:"tool-approval-request",approvalId:p.approvalId,toolCallId:p.toolCall.toolCallId,...p.signature!=null?{signature:p.signature}:{}});break}case"tool-result":{let v=d(p);f.enqueue({type:"tool-output-available",toolCallId:p.toolCallId,output:p.output===void 0?null:p.output,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...p.toolMetadata!=null?{toolMetadata:p.toolMetadata}:{},...p.preliminary!=null?{preliminary:p.preliminary}:{},...v!=null?{dynamic:v}:{}});break}case"tool-error":{let v=d(p);f.enqueue({type:"tool-output-error",toolCallId:p.toolCallId,errorText:p.providerExecuted?typeof p.error==="string"?p.error:JSON.stringify(p.error):c(p.error),...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...p.toolMetadata!=null?{toolMetadata:p.toolMetadata}:{},...v!=null?{dynamic:v}:{}});break}case"tool-output-denied":{f.enqueue({type:"tool-output-denied",toolCallId:p.toolCallId});break}case"error":{f.enqueue({type:"error",errorText:c(p.error)});break}case"start-step":{f.enqueue({type:"start-step"});break}case"finish-step":{f.enqueue({type:"finish-step"});break}case"start":{if(s)f.enqueue({type:"start",...g!=null?{messageMetadata:g}:{},...u!=null?{messageId:u}:{}});break}case"finish":{if(l)f.enqueue({type:"finish",finishReason:p.finishReason,...g!=null?{messageMetadata:g}:{}});break}case"abort":{f.enqueue(p);break}case"tool-input-end":break;case"raw":break;default:throw Error(`Unknown chunk type: ${h}`)}if(g!=null&&h!=="start"&&h!=="finish")f.enqueue({type:"message-metadata",messageMetadata:g})}}));return ho(Jb({stream:m,messageId:u!=null?u:t==null?void 0:t(),originalMessages:e,onFinish:n,onError:c}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:n,onFinish:o,messageMetadata:i,sendReasoning:a,sendSources:s,sendFinish:l,sendStart:c,onError:u,...d}={}){cO({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:n,onFinish:o,messageMetadata:i,sendReasoning:a,sendSources:s,sendFinish:l,sendStart:c,onError:u}),...d})}pipeTextStreamToResponse(e,t){rO({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:o,sendReasoning:i,sendSources:a,sendFinish:s,sendStart:l,onError:c,...u}={}){return nO({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:o,sendReasoning:i,sendSources:a,sendFinish:s,sendStart:l,onError:c}),...u})}toTextStreamResponse(e){return tO({textStream:this.textStream,...e})}},Hb=class{constructor(e){this.version="agent-v1",this.settings=e}get id(){return this.settings.id}get tools(){return this.settings.tools}async prepareCall(e){var t,n,o,i;if(this.settings.callOptionsSchema!=null&&e.options!==void 0){let g=await Ee({value:e.options,schema:this.settings.callOptionsSchema,context:{field:"options"}});e={...e,options:g}}let{onStepFinish:a,...s}=this.settings,l={...s,stopWhen:(t=this.settings.stopWhen)!=null?t:ji(20),...e},c=(i=await((o=(n=this.settings).prepareCall)==null?void 0:o.call(n,l)))!=null?i:l,{instructions:u,allowSystemInMessages:d,messages:m,prompt:p,...f}=c;return{...f,...{system:u,allowSystemInMessages:d,messages:m,prompt:p}}}mergeOnStepFinishCallbacks(e){let t=this.settings.onStepFinish;if(e&&t)return async(n)=>{await t(n),await e(n)};return e!=null?e:t}async generate({abortSignal:e,timeout:t,onStepFinish:n,...o}){return ru({...await this.prepareCall(o),abortSignal:e,timeout:t,onStepFinish:this.mergeOnStepFinishCallbacks(n)})}async stream({abortSignal:e,timeout:t,experimental_transform:n,onStepFinish:o,...i}){return fO({...await this.prepareCall(i),abortSignal:e,timeout:t,experimental_transform:n,onStepFinish:this.mergeOnStepFinishCallbacks(o)})}};function S6({execute:e,onError:t=()=>"An error occurred.",originalMessages:n,onStepFinish:o,onFinish:i,generateId:a=Le}){let s,l=[],c=new ReadableStream({start(m){s=m}});function u(m){try{s.enqueue(m)}catch(p){}}try{let m=e({writer:{write(p){u(p)},merge(p){l.push((async()=>{let f=p.getReader();while(!0){let{done:g,value:h}=await f.read();if(g)break;u(h)}})().catch((f)=>{u({type:"error",errorText:t(f)})}))},onError:t}});if(m)l.push(m.catch((p)=>{u({type:"error",errorText:t(p)})}))}catch(m){u({type:"error",errorText:t(m)})}return new Promise(async(m)=>{while(l.length>0)await l.shift();m()}).finally(()=>{try{s.close()}catch(m){}}),Jb({stream:c,messageId:a(),originalMessages:n,onStepFinish:o,onFinish:i,onError:t})}var Gt=r.record(r.string(),Un.optional()),T6=j(()=>M(r.array(r.object({id:r.string(),role:r.enum(["system","user","assistant"]),metadata:r.unknown().optional(),parts:r.array(r.union([r.object({type:r.literal("text"),text:r.string(),state:r.enum(["streaming","done"]).optional(),providerMetadata:fe.optional()}),r.object({type:r.literal("reasoning"),text:r.string(),state:r.enum(["streaming","done"]).optional(),providerMetadata:fe.optional()}),r.object({type:r.literal("source-url"),sourceId:r.string(),url:r.string(),title:r.string().optional(),providerMetadata:fe.optional()}),r.object({type:r.literal("source-document"),sourceId:r.string(),mediaType:r.string(),title:r.string(),filename:r.string().optional(),providerMetadata:fe.optional()}),r.object({type:r.literal("file"),mediaType:r.string(),filename:r.string().optional(),url:r.string(),providerMetadata:fe.optional()}),r.object({type:r.literal("step-start")}),r.object({type:r.string().startsWith("data-"),id:r.string().optional(),data:r.unknown()}),r.object({type:r.literal("dynamic-tool"),toolName:r.string(),toolCallId:r.string(),toolMetadata:Gt.optional(),state:r.literal("input-streaming"),input:r.unknown().optional(),providerExecuted:r.boolean().optional(),callProviderMetadata:fe.optional(),output:r.never().optional(),errorText:r.never().optional(),approval:r.never().optional()}),r.object({type:r.literal("dynamic-tool"),toolName:r.string(),toolCallId:r.string(),toolMetadata:Gt.optional(),state:r.literal("input-available"),input:r.unknown(),providerExecuted:r.boolean().optional(),output:r.never().optional(),errorText:r.never().optional(),callProviderMetadata:fe.optional(),approval:r.never().optional()}),r.object({type:r.literal("dynamic-tool"),toolName:r.string(),toolCallId:r.string(),toolMetadata:Gt.optional(),state:r.literal("approval-requested"),input:r.unknown(),providerExecuted:r.boolean().optional(),output:r.never().optional(),errorText:r.never().optional(),callProviderMetadata:fe.optional(),approval:r.object({id:r.string(),approved:r.never().optional(),reason:r.never().optional(),signature:r.string().optional()})}),r.object({type:r.literal("dynamic-tool"),toolName:r.string(),toolCallId:r.string(),toolMetadata:Gt.optional(),state:r.literal("approval-responded"),input:r.unknown(),providerExecuted:r.boolean().optional(),output:r.never().optional(),errorText:r.never().optional(),callProviderMetadata:fe.optional(),approval:r.object({id:r.string(),approved:r.boolean(),reason:r.string().optional(),signature:r.string().optional()})}),r.object({type:r.literal("dynamic-tool"),toolName:r.string(),toolCallId:r.string(),toolMetadata:Gt.optional(),state:r.literal("output-available"),input:r.unknown(),providerExecuted:r.boolean().optional(),output:r.unknown(),errorText:r.never().optional(),callProviderMetadata:fe.optional(),resultProviderMetadata:fe.optional(),preliminary:r.boolean().optional(),approval:r.object({id:r.string(),approved:r.literal(!0),reason:r.string().optional(),signature:r.string().optional()}).optional()}),r.object({type:r.literal("dynamic-tool"),toolName:r.string(),toolCallId:r.string(),toolMetadata:Gt.optional(),state:r.literal("output-error"),input:r.unknown().optional(),rawInput:r.unknown().optional(),providerExecuted:r.boolean().optional(),output:r.never().optional(),errorText:r.string(),callProviderMetadata:fe.optional(),resultProviderMetadata:fe.optional(),approval:r.object({id:r.string(),approved:r.literal(!0),reason:r.string().optional(),signature:r.string().optional()}).optional()}),r.object({type:r.literal("dynamic-tool"),toolName:r.string(),toolCallId:r.string(),toolMetadata:Gt.optional(),state:r.literal("output-denied"),input:r.unknown(),providerExecuted:r.boolean().optional(),output:r.never().optional(),errorText:r.never().optional(),callProviderMetadata:fe.optional(),approval:r.object({id:r.string(),approved:r.literal(!1),reason:r.string().optional(),signature:r.string().optional()})}),r.object({type:r.string().startsWith("tool-"),toolCallId:r.string(),toolMetadata:Gt.optional(),state:r.literal("input-streaming"),providerExecuted:r.boolean().optional(),callProviderMetadata:fe.optional(),input:r.unknown().optional(),output:r.never().optional(),errorText:r.never().optional(),approval:r.never().optional()}),r.object({type:r.string().startsWith("tool-"),toolCallId:r.string(),toolMetadata:Gt.optional(),state:r.literal("input-available"),providerExecuted:r.boolean().optional(),input:r.unknown(),output:r.never().optional(),errorText:r.never().optional(),callProviderMetadata:fe.optional(),approval:r.never().optional()}),r.object({type:r.string().startsWith("tool-"),toolCallId:r.string(),toolMetadata:Gt.optional(),state:r.literal("approval-requested"),input:r.unknown(),providerExecuted:r.boolean().optional(),output:r.never().optional(),errorText:r.never().optional(),callProviderMetadata:fe.optional(),approval:r.object({id:r.string(),approved:r.never().optional(),reason:r.never().optional(),signature:r.string().optional()})}),r.object({type:r.string().startsWith("tool-"),toolCallId:r.string(),toolMetadata:Gt.optional(),state:r.literal("approval-responded"),input:r.unknown(),providerExecuted:r.boolean().optional(),output:r.never().optional(),errorText:r.never().optional(),callProviderMetadata:fe.optional(),approval:r.object({id:r.string(),approved:r.boolean(),reason:r.string().optional(),signature:r.string().optional()})}),r.object({type:r.string().startsWith("tool-"),toolCallId:r.string(),toolMetadata:Gt.optional(),state:r.literal("output-available"),providerExecuted:r.boolean().optional(),input:r.unknown(),output:r.unknown(),errorText:r.never().optional(),callProviderMetadata:fe.optional(),resultProviderMetadata:fe.optional(),preliminary:r.boolean().optional(),approval:r.object({id:r.string(),approved:r.literal(!0),reason:r.string().optional(),signature:r.string().optional()}).optional()}),r.object({type:r.string().startsWith("tool-"),toolCallId:r.string(),toolMetadata:Gt.optional(),state:r.literal("output-error"),providerExecuted:r.boolean().optional(),input:r.unknown().optional(),rawInput:r.unknown().optional(),output:r.never().optional(),errorText:r.string(),callProviderMetadata:fe.optional(),resultProviderMetadata:fe.optional(),approval:r.object({id:r.string(),approved:r.literal(!0),reason:r.string().optional(),signature:r.string().optional()}).optional()}),r.object({type:r.string().startsWith("tool-"),toolCallId:r.string(),toolMetadata:Gt.optional(),state:r.literal("output-denied"),providerExecuted:r.boolean().optional(),input:r.unknown(),output:r.never().optional(),errorText:r.never().optional(),callProviderMetadata:fe.optional(),approval:r.object({id:r.string(),approved:r.literal(!1),reason:r.string().optional(),signature:r.string().optional()})})])).nonempty("Message must contain at least one part")})).nonempty("Messages array must not be empty")));async function Wb({model:e,value:t,providerOptions:n,maxRetries:o,abortSignal:i,headers:a,experimental_telemetry:s}){let l=yb(e),{maxRetries:c,retry:u}=bo({maxRetries:o,abortSignal:i}),d=it(a!=null?a:{},`ai/${vo}`),m=Ai({model:l,telemetry:s,headers:d,settings:{maxRetries:c}}),p=Pi(s);return nr({name:"ai.embed",attributes:et({telemetry:s,attributes:{...rr({operationId:"ai.embed",telemetry:s}),...m,"ai.value":{input:()=>JSON.stringify(t)}}}),tracer:p,fn:async(f)=>{let{embedding:g,usage:h,warnings:v,response:x,providerMetadata:S}=await u(()=>nr({name:"ai.embed.doEmbed",attributes:et({telemetry:s,attributes:{...rr({operationId:"ai.embed.doEmbed",telemetry:s}),...m,"ai.values":{input:()=>[JSON.stringify(t)]}}}),tracer:p,fn:async(y)=>{var w,_;let C=await l.doEmbed({values:[t],abortSignal:i,headers:d,providerOptions:n}),I=C.embeddings[0],b=(w=C.usage)!=null?w:{tokens:NaN};return y.setAttributes(await et({telemetry:s,attributes:{"ai.embeddings":{output:()=>C.embeddings.map((E)=>JSON.stringify(E))},"ai.usage.tokens":b.tokens}})),{embedding:I,usage:b,warnings:(_=C.warnings)!=null?_:[],providerMetadata:C.providerMetadata,response:C.response}}}));return f.setAttributes(await et({telemetry:s,attributes:{"ai.embedding":{output:()=>JSON.stringify(g)},"ai.usage.tokens":h.tokens}})),gn({warnings:v,provider:l.provider,model:l.modelId}),new vO({value:t,embedding:g,usage:h,warnings:v,providerMetadata:S,response:x})}})}var vO=class{constructor(e){this.value=e.value,this.embedding=e.embedding,this.usage=e.usage,this.warnings=e.warnings,this.providerMetadata=e.providerMetadata,this.response=e.response}};function _v(e,t){if(t<=0)throw Error("chunkSize must be greater than 0");let n=[];for(let o=0;o<e.length;o+=t)n.push(e.slice(o,o+t));return n}async function Vb({model:e,values:t,maxParallelCalls:n=1/0,maxRetries:o,abortSignal:i,headers:a,providerOptions:s,experimental_telemetry:l}){let c=yb(e),{maxRetries:u,retry:d}=bo({maxRetries:o,abortSignal:i}),m=it(a!=null?a:{},`ai/${vo}`),p=Ai({model:c,telemetry:l,headers:m,settings:{maxRetries:u}}),f=Pi(l);return nr({name:"ai.embedMany",attributes:et({telemetry:l,attributes:{...rr({operationId:"ai.embedMany",telemetry:l}),...p,"ai.values":{input:()=>t.map((g)=>JSON.stringify(g))}}}),tracer:f,fn:async(g)=>{var h;let[v,x]=await Promise.all([c.maxEmbeddingsPerCall,c.supportsParallelCalls]);if(v==null||v===1/0){let{embeddings:E,usage:B,warnings:R,response:U,providerMetadata:z}=await d(()=>nr({name:"ai.embedMany.doEmbed",attributes:et({telemetry:l,attributes:{...rr({operationId:"ai.embedMany.doEmbed",telemetry:l}),...p,"ai.values":{input:()=>t.map((N)=>JSON.stringify(N))}}}),tracer:f,fn:async(N)=>{var re,Y;let V=await c.doEmbed({values:t,abortSignal:i,headers:m,providerOptions:s}),q=V.embeddings,ue=(re=V.usage)!=null?re:{tokens:NaN};return N.setAttributes(await et({telemetry:l,attributes:{"ai.embeddings":{output:()=>q.map((ee)=>JSON.stringify(ee))},"ai.usage.tokens":ue.tokens}})),{embeddings:q,usage:ue,warnings:(Y=V.warnings)!=null?Y:[],providerMetadata:V.providerMetadata,response:V.response}}}));return g.setAttributes(await et({telemetry:l,attributes:{"ai.embeddings":{output:()=>E.map((N)=>JSON.stringify(N))},"ai.usage.tokens":B.tokens}})),gn({warnings:R,provider:c.provider,model:c.modelId}),new Sv({values:t,embeddings:E,usage:B,warnings:R,providerMetadata:z,responses:[U]})}let S=_v(t,v),y=[],w=[],_=[],C=0,I,b=_v(S,x?n:1);for(let E of b){let B=await Promise.all(E.map((R)=>d(()=>nr({name:"ai.embedMany.doEmbed",attributes:et({telemetry:l,attributes:{...rr({operationId:"ai.embedMany.doEmbed",telemetry:l}),...p,"ai.values":{input:()=>R.map((U)=>JSON.stringify(U))}}}),tracer:f,fn:async(U)=>{var z,N;let re=await c.doEmbed({values:R,abortSignal:i,headers:m,providerOptions:s}),Y=re.embeddings,V=(z=re.usage)!=null?z:{tokens:NaN};return U.setAttributes(await et({telemetry:l,attributes:{"ai.embeddings":{output:()=>Y.map((q)=>JSON.stringify(q))},"ai.usage.tokens":V.tokens}})),{embeddings:Y,usage:V,warnings:(N=re.warnings)!=null?N:[],providerMetadata:re.providerMetadata,response:re.response}}}))));for(let R of B)if(y.push(...R.embeddings),w.push(...R.warnings),_.push(R.response),C+=R.usage.tokens,R.providerMetadata)if(!I)I={...R.providerMetadata};else for(let[U,z]of Object.entries(R.providerMetadata))I[U]={...(h=I[U])!=null?h:{},...z}}return g.setAttributes(await et({telemetry:l,attributes:{"ai.embeddings":{output:()=>y.map((E)=>JSON.stringify(E))},"ai.usage.tokens":C}})),gn({warnings:w,provider:c.provider,model:c.modelId}),new Sv({values:t,embeddings:y,usage:{tokens:C},warnings:w,providerMetadata:I,responses:_})}})}var Sv=class{constructor(e){this.values=e.values,this.embeddings=e.embeddings,this.usage=e.usage,this.warnings=e.warnings,this.providerMetadata=e.providerMetadata,this.responses=e.responses}};async function nu({model:e,prompt:t,n=1,maxImagesPerCall:o,size:i,aspectRatio:a,seed:s,providerOptions:l,maxRetries:c,abortSignal:u,headers:d}){var m,p;let f=mj(e),g=it(d!=null?d:{},`ai/${vo}`),{retry:h}=bo({maxRetries:c,abortSignal:u}),v=(m=o!=null?o:await _O(f))!=null?m:1,x=Math.ceil(n/v),S=Array.from({length:x},(E,B)=>{if(B<x-1)return v;let R=n%v;return R===0?v:R}),y=await Promise.all(S.map(async(E)=>h(()=>{let{prompt:B,files:R,mask:U}=SO(t);return f.doGenerate({prompt:B,files:R,mask:U,n:E,abortSignal:u,headers:g,size:i,aspectRatio:a,seed:s,providerOptions:l!=null?l:{}})}))),w=[],_=[],C=[],I={},b={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};for(let E of y){if(w.push(...E.images.map((B)=>{var R;return new Xc({data:B,mediaType:(R=Ka({data:B,signatures:Za}))!=null?R:"image/png"})})),_.push(...E.warnings),E.usage!=null)b=Uj(b,E.usage);if(E.providerMetadata)for(let[B,R]of Object.entries(E.providerMetadata))if(B==="gateway"){let U=I[B];if(U!=null&&typeof U==="object")I[B]={...U,...R};else I[B]=R;let z=I[B].images;if(Array.isArray(z)&&z.length===0)delete I[B].images}else(p=I[B])!=null||(I[B]={images:[]}),I[B].images.push(...E.providerMetadata[B].images);C.push(E.response)}if(gn({warnings:_,provider:f.provider,model:f.modelId}),!w.length)throw new jM({responses:C});return new bO({images:w,warnings:_,responses:C,providerMetadata:I,usage:b})}var bO=class{constructor(e){this.images=e.images,this.warnings=e.warnings,this.responses=e.responses,this.providerMetadata=e.providerMetadata,this.usage=e.usage}get image(){return this.images[0]}};async function _O(e){if(!(e.maxImagesPerCall instanceof Function))return e.maxImagesPerCall;return e.maxImagesPerCall({modelId:e.modelId})}function SO(e){if(typeof e==="string")return{prompt:e,files:void 0,mask:void 0};return{prompt:e.text,files:e.images.map(wv),mask:e.mask?wv(e.mask):void 0}}function wv(e){if(typeof e==="string"&&e.startsWith("http"))return{type:"url",url:e};if(typeof e==="string"&&e.startsWith("data:")){let{mediaType:n,base64Content:o}=_b(e);if(o!=null){let i=wt(o);return{type:"file",data:i,mediaType:n||Ka({data:i,signatures:Za})||"image/png"}}}let t=vj(e);return{type:"file",data:t,mediaType:Ka({data:t,signatures:Za})||"image/png"}}var wO={type:"no-schema",jsonSchema:async()=>{return},async validatePartialResult({value:e,textDelta:t}){return{success:!0,value:{partial:e,textDelta:t}}},async validateFinalResult(e,t){return e===void 0?{success:!1,error:new Ft({message:"No object generated: response did not match schema.",text:t.text,response:t.response,usage:t.usage,finishReason:t.finishReason})}:{success:!0,value:e}},createElementStream(){throw new We({functionality:"element streams in no-schema mode"})}},xO=(e)=>({type:"object",jsonSchema:async()=>await e.jsonSchema,async validatePartialResult({value:t,textDelta:n}){return{success:!0,value:{partial:t,textDelta:n}}},async validateFinalResult(t){return pt({value:t,schema:e})},createElementStream(){throw new We({functionality:"element streams in object mode"})}}),TO=(e)=>({type:"array",jsonSchema:async()=>{let{$schema:t,...n}=await e.jsonSchema;return{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:n}},required:["elements"],additionalProperties:!1}},async validatePartialResult({value:t,latestObject:n,isFirstDelta:o,isFinalDelta:i}){var a;if(!ei(t)||!ul(t.elements))return{success:!1,error:new vt({value:t,cause:"value must be an object that contains an array of elements"})};let s=t.elements,l=[];for(let d=0;d<s.length;d++){let m=s[d],p=await pt({value:m,schema:e});if(d===s.length-1&&!i)continue;if(!p.success)return p;l.push(p.value)}let c=(a=n==null?void 0:n.length)!=null?a:0,u="";if(o)u+="[";if(c>0)u+=",";if(u+=l.slice(c).map((d)=>JSON.stringify(d)).join(","),i)u+="]";return{success:!0,value:{partial:l,textDelta:u}}},async validateFinalResult(t){if(!ei(t)||!ul(t.elements))return{success:!1,error:new vt({value:t,cause:"value must be an object that contains an array of elements"})};let n=t.elements,o=[];for(let i of n){let a=await pt({value:i,schema:e});if(!a.success)return a;o.push(a.value)}return{success:!0,value:o}},createElementStream(t){let n=0;return ho(t.pipeThrough(new TransformStream({transform(o,i){switch(o.type){case"object":{let a=o.object;for(;n<a.length;n++)i.enqueue(a[n]);break}case"text-delta":case"finish":case"error":break;default:throw Error(`Unsupported chunk type: ${o}`)}}})))}}),IO=(e)=>({type:"enum",jsonSchema:async()=>({$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:e}},required:["result"],additionalProperties:!1}),async validateFinalResult(t){if(!ei(t)||typeof t.result!=="string")return{success:!1,error:new vt({value:t,cause:'value must be an object that contains a string in the "result" property.'})};let n=t.result;return e.includes(n)?{success:!0,value:n}:{success:!1,error:new vt({value:t,cause:"value must be a string in the enum"})}},async validatePartialResult({value:t,textDelta:n}){if(!ei(t)||typeof t.result!=="string")return{success:!1,error:new vt({value:t,cause:'value must be an object that contains a string in the "result" property.'})};let o=t.result,i=e.filter((a)=>a.startsWith(o));if(t.result.length===0||i.length===0)return{success:!1,error:new vt({value:t,cause:"value must be a string in the enum"})};return{success:!0,value:{partial:i.length>1?o:i[0],textDelta:n}}},createElementStream(){throw new We({functionality:"element streams in enum mode"})}});function CO({output:e,schema:t,enumValues:n}){switch(e){case"object":return xO(qt(t));case"array":return TO(qt(t));case"enum":return IO(n);case"no-schema":return wO;default:throw Error(`Unsupported output: ${e}`)}}async function xv(e,t,n){let o=await xt({text:e});if(!o.success)throw new Ft({message:"No object generated: could not parse the response.",cause:o.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});let i=await t.validateFinalResult(o.value,{text:e,response:n.response,usage:n.usage});if(!i.success)throw new Ft({message:"No object generated: response did not match schema.",cause:i.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});return i.value}async function kO(e,t,n,o){try{return await xv(e,t,o)}catch(i){if(n!=null&&Ft.isInstance(i)&&(kn.isInstance(i.cause)||vt.isInstance(i.cause))){let a=await n({text:e,error:i.cause});if(a===null)throw i;return await xv(a,t,o)}throw i}}function RO({output:e,schema:t,schemaName:n,schemaDescription:o,enumValues:i}){if(e!=null&&e!=="object"&&e!=="array"&&e!=="enum"&&e!=="no-schema")throw new at({parameter:"output",value:e,message:"Invalid output type."});if(e==="no-schema"){if(t!=null)throw new at({parameter:"schema",value:t,message:"Schema is not supported for no-schema output."});if(o!=null)throw new at({parameter:"schemaDescription",value:o,message:"Schema description is not supported for no-schema output."});if(n!=null)throw new at({parameter:"schemaName",value:n,message:"Schema name is not supported for no-schema output."});if(i!=null)throw new at({parameter:"enumValues",value:i,message:"Enum values are not supported for no-schema output."})}if(e==="object"){if(t==null)throw new at({parameter:"schema",value:t,message:"Schema is required for object output."});if(i!=null)throw new at({parameter:"enumValues",value:i,message:"Enum values are not supported for object output."})}if(e==="array"){if(t==null)throw new at({parameter:"schema",value:t,message:"Element schema is required for array output."});if(i!=null)throw new at({parameter:"enumValues",value:i,message:"Enum values are not supported for array output."})}if(e==="enum"){if(t!=null)throw new at({parameter:"schema",value:t,message:"Schema is not supported for enum output."});if(o!=null)throw new at({parameter:"schemaDescription",value:o,message:"Schema description is not supported for enum output."});if(n!=null)throw new at({parameter:"schemaName",value:n,message:"Schema name is not supported for enum output."});if(i==null)throw new at({parameter:"enumValues",value:i,message:"Enum values are required for enum output."});for(let a of i)if(typeof a!=="string")throw new at({parameter:"enumValues",value:a,message:"Enum values must be strings."})}}var EO=Er({prefix:"aiobj",size:24});async function Zb(e){let{model:t,output:n="object",system:o,prompt:i,messages:a,allowSystemInMessages:s,maxRetries:l,abortSignal:c,headers:u,experimental_repairText:d,experimental_telemetry:m,experimental_download:p,providerOptions:f,_internal:{generateId:g=EO,currentDate:h=()=>new Date}={},...v}=e,x=ki(t),S="enum"in e?e.enum:void 0,{schema:y,schemaDescription:w,schemaName:_}="schema"in e?e:{};RO({output:n,schema:y,schemaName:_,schemaDescription:w,enumValues:S});let{maxRetries:C,retry:I}=bo({maxRetries:l,abortSignal:c}),b=CO({output:n,schema:y,enumValues:S}),E=Ri(v),B=it(u!=null?u:{},`ai/${vo}`),R=Ai({model:x,telemetry:m,headers:B,settings:{...E,maxRetries:C}}),U=Pi(m),z=await b.jsonSchema();try{return await nr({name:"ai.generateObject",attributes:et({telemetry:m,attributes:{...rr({operationId:"ai.generateObject",telemetry:m}),...R,"ai.prompt":{input:()=>JSON.stringify({system:o,prompt:i,messages:a})},"ai.schema":z!=null?{input:()=>JSON.stringify(z)}:void 0,"ai.schema.name":_,"ai.schema.description":w,"ai.settings.output":b.type}}),tracer:U,fn:async(N)=>{var re;let Y,V,q,ue,ee,k,X,H,J=await Zc({system:o,prompt:i,messages:a,allowSystemInMessages:s}),K=await Vc({prompt:J,supportedUrls:await x.supportedUrls,download:p}),D=await I(()=>nr({name:"ai.generateObject.doGenerate",attributes:et({telemetry:m,attributes:{...rr({operationId:"ai.generateObject.doGenerate",telemetry:m}),...R,"ai.prompt.messages":{input:()=>Yc(K)},"gen_ai.system":x.provider,"gen_ai.request.model":x.modelId,"gen_ai.request.frequency_penalty":E.frequencyPenalty,"gen_ai.request.max_tokens":E.maxOutputTokens,"gen_ai.request.presence_penalty":E.presencePenalty,"gen_ai.request.temperature":E.temperature,"gen_ai.request.top_k":E.topK,"gen_ai.request.top_p":E.topP}}),tracer:U,fn:async(G)=>{var Z,A,O,W,P,L,me,Q;let de=await x.doGenerate({responseFormat:{type:"json",schema:z,name:_,description:w},...Ri(v),prompt:K,providerOptions:f,abortSignal:c,headers:B}),Ae={id:(A=(Z=de.response)==null?void 0:Z.id)!=null?A:g(),timestamp:(W=(O=de.response)==null?void 0:O.timestamp)!=null?W:h(),modelId:(L=(P=de.response)==null?void 0:P.modelId)!=null?L:x.modelId,headers:(me=de.response)==null?void 0:me.headers,body:(Q=de.response)==null?void 0:Q.body},Ke=Uc(de.content),nt=zc(de.content);if(Ke===void 0)throw new Ft({message:"No object generated: the model did not return a response.",response:Ae,usage:Ei(de.usage),finishReason:de.finishReason.unified});return G.setAttributes(await et({telemetry:m,attributes:{"ai.response.finishReason":de.finishReason.unified,"ai.response.object":{output:()=>Ke},"ai.response.id":Ae.id,"ai.response.model":Ae.modelId,"ai.response.timestamp":Ae.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(de.providerMetadata),"ai.usage.promptTokens":de.usage.inputTokens.total,"ai.usage.completionTokens":de.usage.outputTokens.total,"gen_ai.response.finish_reasons":[de.finishReason.unified],"gen_ai.response.id":Ae.id,"gen_ai.response.model":Ae.modelId,"gen_ai.usage.input_tokens":de.usage.inputTokens.total,"gen_ai.usage.output_tokens":de.usage.outputTokens.total}})),{...de,objectText:Ke,reasoning:nt,responseData:Ae}}}));Y=D.objectText,V=D.finishReason.unified,q=Ei(D.usage),ue=D.warnings,X=D.providerMetadata,k=(re=D.request)!=null?re:{},ee=D.responseData,H=D.reasoning,gn({warnings:ue,provider:x.provider,model:x.modelId});let F=await kO(Y,b,d,{response:ee,usage:q,finishReason:V});return N.setAttributes(await et({telemetry:m,attributes:{"ai.response.finishReason":V,"ai.response.object":{output:()=>JSON.stringify(F)},"ai.response.providerMetadata":JSON.stringify(X),"ai.usage.promptTokens":q.inputTokens,"ai.usage.completionTokens":q.outputTokens}})),new AO({object:F,reasoning:H,finishReason:V,usage:q,warnings:ue,request:k,response:ee,providerMetadata:X})}})}catch(N){throw Kc(N)}}var AO=class{constructor(e){this.object=e.object,this.finishReason=e.finishReason,this.usage=e.usage,this.warnings=e.warnings,this.providerMetadata=e.providerMetadata,this.response=e.response,this.request=e.request,this.reasoning=e.reasoning}toJsonResponse(e){var t;return new Response(JSON.stringify(this.object),{status:(t=e==null?void 0:e.status)!=null?t:200,headers:Oi(e==null?void 0:e.headers,{"content-type":"application/json; charset=utf-8"})})}};function Kb(e){return({url:t,abortSignal:n})=>bb({url:t,maxBytes:e==null?void 0:e.maxBytes,abortSignal:n})}var O6=Er({prefix:"aiobj",size:24});var N6=Kb();var PO="AI_NoSuchProviderError",MO=`vercel.ai.error.${PO}`,jO=Symbol.for(MO),OO;OO=jO;var D6=Kb();class es extends Error{constructor(e){super("AI object generation failed: invalid structured output",{cause:e});this.name="AIOutputValidationError"}}var NO=[[/^claude/,"anthropic"],[/^gpt-/,"openai"],[/^o[13]-/,"openai"],[/^gemini/,"google"],[/^llama/,"ollama"],[/^mistral/,"ollama"],[/^phi-/,"ollama"],[/^qwen/,"ollama"]];function Yb(e){let t=e.indexOf(":");if(t>0)return{provider:e.slice(0,t),modelId:e.slice(t+1)};return null}function Ni(e){let t=Yb(e);if(t)return t;for(let[n,o]of NO)if(n.test(e))return{provider:o,modelId:e};return{provider:"anthropic",modelId:e}}function ou(e){if(!e)return"anthropic";return Ni(e).provider}var DO=[[/^gpt-image/,"openai"],[/^dall-e/,"openai"],[/^gemini/,"google"]],zO="gpt-image-1.5";function iu(e){if(!e)return{provider:"openai",modelId:zO};let t=Yb(e);if(t)return t;for(let[n,o]of DO)if(n.test(e))return{provider:o,modelId:e};return{provider:"openai",modelId:e}}var UO=/^(gpt-5|o[1-9])(?:[.-]|$)/;function $O(e){if(e.provider!=="openai")return!0;return!UO.test(e.modelId)}function Di(e){if(!e)return{provider:"anthropic",supportsTemperature:!0};let t=Ni(e);return{provider:t.provider,supportsTemperature:$O(t)}}var LO="3.0.95",qO=j(()=>M(r.object({type:r.literal("error"),error:r.object({type:r.string(),message:r.string()})}))),Qb=Qe({errorSchema:qO,errorToMessage:(e)=>e.error.message}),l_=r.object({type:r.string(),category:r.string().nullish(),explanation:r.string().nullish(),recommended_model:r.string().nullish()}),FO=j(()=>M(r.object({type:r.literal("message"),id:r.string().nullish(),model:r.string().nullish(),content:r.array(r.discriminatedUnion("type",[r.object({type:r.literal("text"),text:r.string(),citations:r.array(r.discriminatedUnion("type",[r.object({type:r.literal("web_search_result_location"),cited_text:r.string(),url:r.string(),title:r.string(),encrypted_index:r.string()}),r.object({type:r.literal("page_location"),cited_text:r.string(),document_index:r.number(),document_title:r.string().nullable(),start_page_number:r.number(),end_page_number:r.number()}),r.object({type:r.literal("char_location"),cited_text:r.string(),document_index:r.number(),document_title:r.string().nullable(),start_char_index:r.number(),end_char_index:r.number()})])).optional()}),r.object({type:r.literal("thinking"),thinking:r.string(),signature:r.string()}),r.object({type:r.literal("redacted_thinking"),data:r.string()}),r.object({type:r.literal("compaction"),content:r.string()}),r.object({type:r.literal("tool_use"),id:r.string(),name:r.string(),input:r.unknown(),caller:r.union([r.object({type:r.literal("code_execution_20250825"),tool_id:r.string()}),r.object({type:r.literal("code_execution_20260120"),tool_id:r.string()}),r.object({type:r.literal("direct")})]).optional()}),r.object({type:r.literal("server_tool_use"),id:r.string(),name:r.string(),input:r.record(r.string(),r.unknown()).nullish(),caller:r.union([r.object({type:r.literal("code_execution_20260120"),tool_id:r.string()}),r.object({type:r.literal("direct")})]).optional()}),r.object({type:r.literal("mcp_tool_use"),id:r.string(),name:r.string(),input:r.unknown(),server_name:r.string()}),r.object({type:r.literal("mcp_tool_result"),tool_use_id:r.string(),is_error:r.boolean(),content:r.array(r.union([r.string(),r.object({type:r.literal("text"),text:r.string()})]))}),r.object({type:r.literal("web_fetch_tool_result"),tool_use_id:r.string(),content:r.union([r.object({type:r.literal("web_fetch_result"),url:r.string(),retrieved_at:r.string(),content:r.object({type:r.literal("document"),title:r.string().nullable(),citations:r.object({enabled:r.boolean()}).optional(),source:r.union([r.object({type:r.literal("base64"),media_type:r.literal("application/pdf"),data:r.string()}),r.object({type:r.literal("text"),media_type:r.literal("text/plain"),data:r.string()})])})}),r.object({type:r.literal("web_fetch_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("web_search_tool_result"),tool_use_id:r.string(),content:r.union([r.array(r.object({type:r.literal("web_search_result"),url:r.string(),title:r.string(),encrypted_content:r.string(),page_age:r.string().nullish()})),r.object({type:r.literal("web_search_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("code_execution_tool_result"),tool_use_id:r.string(),content:r.union([r.object({type:r.literal("code_execution_result"),stdout:r.string(),stderr:r.string(),return_code:r.number(),content:r.array(r.object({type:r.literal("code_execution_output"),file_id:r.string()})).optional().default([])}),r.object({type:r.literal("encrypted_code_execution_result"),encrypted_stdout:r.string(),stderr:r.string(),return_code:r.number(),content:r.array(r.object({type:r.literal("code_execution_output"),file_id:r.string()})).optional().default([])}),r.object({type:r.literal("code_execution_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("bash_code_execution_tool_result"),tool_use_id:r.string(),content:r.discriminatedUnion("type",[r.object({type:r.literal("bash_code_execution_result"),content:r.array(r.object({type:r.literal("bash_code_execution_output"),file_id:r.string()})),stdout:r.string(),stderr:r.string(),return_code:r.number()}),r.object({type:r.literal("bash_code_execution_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("text_editor_code_execution_tool_result"),tool_use_id:r.string(),content:r.discriminatedUnion("type",[r.object({type:r.literal("text_editor_code_execution_tool_result_error"),error_code:r.string()}),r.object({type:r.literal("text_editor_code_execution_view_result"),content:r.string(),file_type:r.string(),num_lines:r.number().nullable(),start_line:r.number().nullable(),total_lines:r.number().nullable()}),r.object({type:r.literal("text_editor_code_execution_create_result"),is_file_update:r.boolean()}),r.object({type:r.literal("text_editor_code_execution_str_replace_result"),lines:r.array(r.string()).nullable(),new_lines:r.number().nullable(),new_start:r.number().nullable(),old_lines:r.number().nullable(),old_start:r.number().nullable()})])}),r.object({type:r.literal("tool_search_tool_result"),tool_use_id:r.string(),content:r.union([r.object({type:r.literal("tool_search_tool_search_result"),tool_references:r.array(r.object({type:r.literal("tool_reference"),tool_name:r.string()}))}),r.object({type:r.literal("tool_search_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("advisor_tool_result"),tool_use_id:r.string(),content:r.discriminatedUnion("type",[r.object({type:r.literal("advisor_result"),text:r.string()}),r.object({type:r.literal("advisor_redacted_result"),encrypted_content:r.string()}),r.object({type:r.literal("advisor_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("fallback")})])),stop_reason:r.string().nullish(),stop_sequence:r.string().nullish(),stop_details:l_.nullish(),usage:r.looseObject({input_tokens:r.number(),output_tokens:r.number(),cache_creation_input_tokens:r.number().nullish(),cache_read_input_tokens:r.number().nullish(),iterations:r.array(r.object({type:r.union([r.literal("compaction"),r.literal("message"),r.literal("advisor_message"),r.literal("fallback_message")]),model:r.string().nullish(),input_tokens:r.number(),output_tokens:r.number(),cache_creation_input_tokens:r.number().nullish(),cache_read_input_tokens:r.number().nullish()})).nullish()}),container:r.object({expires_at:r.string(),id:r.string(),skills:r.array(r.object({type:r.union([r.literal("anthropic"),r.literal("custom")]),skill_id:r.string(),version:r.string()})).nullish()}).nullish(),context_management:r.object({applied_edits:r.array(r.union([r.object({type:r.literal("clear_tool_uses_20250919"),cleared_tool_uses:r.number(),cleared_input_tokens:r.number()}),r.object({type:r.literal("clear_thinking_20251015"),cleared_thinking_turns:r.number(),cleared_input_tokens:r.number()}),r.object({type:r.literal("compact_20260112")})]))}).nullish()}))),BO=j(()=>M(r.discriminatedUnion("type",[r.object({type:r.literal("message_start"),message:r.object({id:r.string().nullish(),model:r.string().nullish(),role:r.string().nullish(),usage:r.looseObject({input_tokens:r.number(),cache_creation_input_tokens:r.number().nullish(),cache_read_input_tokens:r.number().nullish()}),content:r.array(r.discriminatedUnion("type",[r.object({type:r.literal("tool_use"),id:r.string(),name:r.string(),input:r.unknown(),caller:r.union([r.object({type:r.literal("code_execution_20250825"),tool_id:r.string()}),r.object({type:r.literal("code_execution_20260120"),tool_id:r.string()}),r.object({type:r.literal("direct")})]).optional()})])).nullish(),stop_reason:r.string().nullish(),container:r.object({expires_at:r.string(),id:r.string()}).nullish()})}),r.object({type:r.literal("content_block_start"),index:r.number(),content_block:r.discriminatedUnion("type",[r.object({type:r.literal("text"),text:r.string()}),r.object({type:r.literal("thinking"),thinking:r.string()}),r.object({type:r.literal("tool_use"),id:r.string(),name:r.string(),input:r.record(r.string(),r.unknown()).optional(),caller:r.union([r.object({type:r.literal("code_execution_20250825"),tool_id:r.string()}),r.object({type:r.literal("code_execution_20260120"),tool_id:r.string()}),r.object({type:r.literal("direct")})]).optional()}),r.object({type:r.literal("redacted_thinking"),data:r.string()}),r.object({type:r.literal("compaction"),content:r.string().nullish()}),r.object({type:r.literal("server_tool_use"),id:r.string(),name:r.string(),input:r.record(r.string(),r.unknown()).nullish(),caller:r.union([r.object({type:r.literal("code_execution_20260120"),tool_id:r.string()}),r.object({type:r.literal("direct")})]).optional()}),r.object({type:r.literal("mcp_tool_use"),id:r.string(),name:r.string(),input:r.unknown(),server_name:r.string()}),r.object({type:r.literal("mcp_tool_result"),tool_use_id:r.string(),is_error:r.boolean(),content:r.array(r.union([r.string(),r.object({type:r.literal("text"),text:r.string()})]))}),r.object({type:r.literal("web_fetch_tool_result"),tool_use_id:r.string(),content:r.union([r.object({type:r.literal("web_fetch_result"),url:r.string(),retrieved_at:r.string(),content:r.object({type:r.literal("document"),title:r.string().nullable(),citations:r.object({enabled:r.boolean()}).optional(),source:r.union([r.object({type:r.literal("base64"),media_type:r.literal("application/pdf"),data:r.string()}),r.object({type:r.literal("text"),media_type:r.literal("text/plain"),data:r.string()})])})}),r.object({type:r.literal("web_fetch_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("web_search_tool_result"),tool_use_id:r.string(),content:r.union([r.array(r.object({type:r.literal("web_search_result"),url:r.string(),title:r.string(),encrypted_content:r.string(),page_age:r.string().nullish()})),r.object({type:r.literal("web_search_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("code_execution_tool_result"),tool_use_id:r.string(),content:r.union([r.object({type:r.literal("code_execution_result"),stdout:r.string(),stderr:r.string(),return_code:r.number(),content:r.array(r.object({type:r.literal("code_execution_output"),file_id:r.string()})).optional().default([])}),r.object({type:r.literal("encrypted_code_execution_result"),encrypted_stdout:r.string(),stderr:r.string(),return_code:r.number(),content:r.array(r.object({type:r.literal("code_execution_output"),file_id:r.string()})).optional().default([])}),r.object({type:r.literal("code_execution_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("bash_code_execution_tool_result"),tool_use_id:r.string(),content:r.discriminatedUnion("type",[r.object({type:r.literal("bash_code_execution_result"),content:r.array(r.object({type:r.literal("bash_code_execution_output"),file_id:r.string()})),stdout:r.string(),stderr:r.string(),return_code:r.number()}),r.object({type:r.literal("bash_code_execution_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("text_editor_code_execution_tool_result"),tool_use_id:r.string(),content:r.discriminatedUnion("type",[r.object({type:r.literal("text_editor_code_execution_tool_result_error"),error_code:r.string()}),r.object({type:r.literal("text_editor_code_execution_view_result"),content:r.string(),file_type:r.string(),num_lines:r.number().nullable(),start_line:r.number().nullable(),total_lines:r.number().nullable()}),r.object({type:r.literal("text_editor_code_execution_create_result"),is_file_update:r.boolean()}),r.object({type:r.literal("text_editor_code_execution_str_replace_result"),lines:r.array(r.string()).nullable(),new_lines:r.number().nullable(),new_start:r.number().nullable(),old_lines:r.number().nullable(),old_start:r.number().nullable()})])}),r.object({type:r.literal("tool_search_tool_result"),tool_use_id:r.string(),content:r.union([r.object({type:r.literal("tool_search_tool_search_result"),tool_references:r.array(r.object({type:r.literal("tool_reference"),tool_name:r.string()}))}),r.object({type:r.literal("tool_search_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("advisor_tool_result"),tool_use_id:r.string(),content:r.discriminatedUnion("type",[r.object({type:r.literal("advisor_result"),text:r.string()}),r.object({type:r.literal("advisor_redacted_result"),encrypted_content:r.string()}),r.object({type:r.literal("advisor_tool_result_error"),error_code:r.string()})])}),r.object({type:r.literal("fallback")})])}),r.object({type:r.literal("content_block_delta"),index:r.number(),delta:r.discriminatedUnion("type",[r.object({type:r.literal("input_json_delta"),partial_json:r.string()}),r.object({type:r.literal("text_delta"),text:r.string()}),r.object({type:r.literal("thinking_delta"),thinking:r.string()}),r.object({type:r.literal("signature_delta"),signature:r.string()}),r.object({type:r.literal("compaction_delta"),content:r.string().nullish()}),r.object({type:r.literal("citations_delta"),citation:r.discriminatedUnion("type",[r.object({type:r.literal("web_search_result_location"),cited_text:r.string(),url:r.string(),title:r.string(),encrypted_index:r.string()}),r.object({type:r.literal("page_location"),cited_text:r.string(),document_index:r.number(),document_title:r.string().nullable(),start_page_number:r.number(),end_page_number:r.number()}),r.object({type:r.literal("char_location"),cited_text:r.string(),document_index:r.number(),document_title:r.string().nullable(),start_char_index:r.number(),end_char_index:r.number()})])})])}),r.object({type:r.literal("content_block_stop"),index:r.number()}),r.object({type:r.literal("error"),error:r.object({type:r.string(),message:r.string()})}),r.object({type:r.literal("message_delta"),delta:r.object({stop_reason:r.string().nullish(),stop_sequence:r.string().nullish(),stop_details:l_.nullish(),container:r.object({expires_at:r.string(),id:r.string(),skills:r.array(r.object({type:r.union([r.literal("anthropic"),r.literal("custom")]),skill_id:r.string(),version:r.string()})).nullish()}).nullish()}),usage:r.looseObject({input_tokens:r.number().nullish(),output_tokens:r.number(),cache_creation_input_tokens:r.number().nullish(),cache_read_input_tokens:r.number().nullish(),iterations:r.array(r.object({type:r.union([r.literal("compaction"),r.literal("message"),r.literal("advisor_message"),r.literal("fallback_message")]),model:r.string().nullish(),input_tokens:r.number(),output_tokens:r.number(),cache_creation_input_tokens:r.number().nullish(),cache_read_input_tokens:r.number().nullish()})).nullish()}),context_management:r.object({applied_edits:r.array(r.union([r.object({type:r.literal("clear_tool_uses_20250919"),cleared_tool_uses:r.number(),cleared_input_tokens:r.number()}),r.object({type:r.literal("clear_thinking_20251015"),cleared_thinking_turns:r.number(),cleared_input_tokens:r.number()}),r.object({type:r.literal("compact_20260112")})]))}).nullish()}),r.object({type:r.literal("message_stop")}),r.object({type:r.literal("ping")})]))),GO=j(()=>M(r.object({signature:r.string().optional(),redactedData:r.string().optional()}))),Xb=r.object({citations:r.object({enabled:r.boolean()}).optional(),title:r.string().optional(),context:r.string().optional()}),e_=r.object({sendReasoning:r.boolean().optional(),structuredOutputMode:r.enum(["outputFormat","jsonTool","auto"]).optional(),thinking:r.discriminatedUnion("type",[r.object({type:r.literal("adaptive"),display:r.enum(["omitted","summarized"]).optional()}),r.object({type:r.literal("enabled"),budgetTokens:r.number().optional()}),r.object({type:r.literal("disabled")})]).optional(),disableParallelToolUse:r.boolean().optional(),cacheControl:r.object({type:r.literal("ephemeral"),ttl:r.union([r.literal("5m"),r.literal("1h")]).optional()}).optional(),metadata:r.object({userId:r.string().optional()}).optional(),mcpServers:r.array(r.object({type:r.literal("url"),name:r.string(),url:r.string(),authorizationToken:r.string().nullish(),toolConfiguration:r.object({enabled:r.boolean().nullish(),allowedTools:r.array(r.string()).nullish()}).nullish()})).optional(),container:r.object({id:r.string().optional(),skills:r.array(r.object({type:r.union([r.literal("anthropic"),r.literal("custom")]),skillId:r.string(),version:r.string().optional()})).optional()}).optional(),toolStreaming:r.boolean().optional(),effort:r.enum(["low","medium","high","xhigh","max"]).optional(),taskBudget:r.object({type:r.literal("tokens"),total:r.number().int().min(20000),remaining:r.number().int().min(0).optional()}).optional(),speed:r.enum(["fast","standard"]).optional(),inferenceGeo:r.enum(["us","global"]).optional(),fallbacks:r.array(r.object({model:r.string(),max_tokens:r.number().int().optional(),thinking:r.record(r.string(),r.unknown()).optional(),output_config:r.record(r.string(),r.unknown()).optional(),speed:r.enum(["fast","standard"]).optional()})).optional(),anthropicBeta:r.array(r.string()).optional(),contextManagement:r.object({edits:r.array(r.discriminatedUnion("type",[r.object({type:r.literal("clear_tool_uses_20250919"),trigger:r.discriminatedUnion("type",[r.object({type:r.literal("input_tokens"),value:r.number()}),r.object({type:r.literal("tool_uses"),value:r.number()})]).optional(),keep:r.object({type:r.literal("tool_uses"),value:r.number()}).optional(),clearAtLeast:r.object({type:r.literal("input_tokens"),value:r.number()}).optional(),clearToolInputs:r.boolean().optional(),excludeTools:r.array(r.string()).optional()}),r.object({type:r.literal("clear_thinking_20251015"),keep:r.union([r.literal("all"),r.object({type:r.literal("thinking_turns"),value:r.number()})]).optional()}),r.object({type:r.literal("compact_20260112"),trigger:r.object({type:r.literal("input_tokens"),value:r.number()}).optional(),pauseAfterCompaction:r.boolean().optional(),instructions:r.string().optional()})]))}).optional()}),t_=4;function JO(e){var t;let n=e==null?void 0:e.anthropic;return(t=n==null?void 0:n.cacheControl)!=null?t:n==null?void 0:n.cache_control}var cu=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(e,t){let n=JO(e);if(!n)return;if(!t.canCache){this.warnings.push({type:"unsupported",feature:"cache_control on non-cacheable context",details:`cache_control cannot be set on ${t.type}. It will be ignored.`});return}if(this.breakpointCount++,this.breakpointCount>t_){this.warnings.push({type:"unsupported",feature:"cacheControl breakpoint limit",details:`Maximum ${t_} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return n}getWarnings(){return this.warnings}},HO=j(()=>M(r.object({model:r.string(),maxUses:r.number().optional(),caching:r.object({type:r.literal("ephemeral"),ttl:r.union([r.literal("5m"),r.literal("1h")])}).optional()}))),c_=j(()=>M(r.discriminatedUnion("type",[r.object({type:r.literal("advisor_result"),text:r.string()}),r.object({type:r.literal("advisor_redacted_result"),encryptedContent:r.string()}),r.object({type:r.literal("advisor_tool_result_error"),errorCode:r.string()})]))),WO=j(()=>M(r.object({}).strict())),VO=Te({id:"anthropic.advisor_20260301",inputSchema:WO,outputSchema:c_,supportsDeferredResults:!0}),ZO=(e)=>VO(e),KO=j(()=>M(r.object({maxCharacters:r.number().optional()}))),YO=j(()=>M(r.object({command:r.enum(["view","create","str_replace","insert"]),path:r.string(),file_text:r.string().optional(),insert_line:r.number().int().optional(),new_str:r.string().optional(),insert_text:r.string().optional(),old_str:r.string().optional(),view_range:r.array(r.number().int()).optional()}))),QO=Ge({id:"anthropic.text_editor_20250728",inputSchema:YO}),XO=(e={})=>QO(e),eN=j(()=>M(r.object({maxUses:r.number().optional(),allowedDomains:r.array(r.string()).optional(),blockedDomains:r.array(r.string()).optional(),userLocation:r.object({type:r.literal("approximate"),city:r.string().optional(),region:r.string().optional(),country:r.string().optional(),timezone:r.string().optional()}).optional()}))),tN=j(()=>M(r.array(r.object({url:r.string(),title:r.string().nullable(),pageAge:r.string().nullable(),encryptedContent:r.string(),type:r.literal("web_search_result")})))),rN=j(()=>M(r.object({query:r.string()}))),nN=Te({id:"anthropic.web_search_20260209",inputSchema:rN,outputSchema:tN,supportsDeferredResults:!0}),oN=(e={})=>nN(e),iN=j(()=>M(r.object({maxUses:r.number().optional(),allowedDomains:r.array(r.string()).optional(),blockedDomains:r.array(r.string()).optional(),userLocation:r.object({type:r.literal("approximate"),city:r.string().optional(),region:r.string().optional(),country:r.string().optional(),timezone:r.string().optional()}).optional()}))),u_=j(()=>M(r.array(r.object({url:r.string(),title:r.string().nullable(),pageAge:r.string().nullable(),encryptedContent:r.string(),type:r.literal("web_search_result")})))),aN=j(()=>M(r.object({query:r.string()}))),sN=Te({id:"anthropic.web_search_20250305",inputSchema:aN,outputSchema:u_,supportsDeferredResults:!0}),lN=(e={})=>sN(e),cN=j(()=>M(r.object({maxUses:r.number().optional(),allowedDomains:r.array(r.string()).optional(),blockedDomains:r.array(r.string()).optional(),citations:r.object({enabled:r.boolean()}).optional(),maxContentTokens:r.number().optional()}))),uN=j(()=>M(r.object({type:r.literal("web_fetch_result"),url:r.string(),content:r.object({type:r.literal("document"),title:r.string().nullable(),citations:r.object({enabled:r.boolean()}).optional(),source:r.union([r.object({type:r.literal("base64"),mediaType:r.literal("application/pdf"),data:r.string()}),r.object({type:r.literal("text"),mediaType:r.literal("text/plain"),data:r.string()})])}),retrievedAt:r.string().nullable()}))),dN=j(()=>M(r.object({url:r.string()}))),pN=Te({id:"anthropic.web_fetch_20260209",inputSchema:dN,outputSchema:uN,supportsDeferredResults:!0}),mN=(e={})=>pN(e),gN=j(()=>M(r.object({maxUses:r.number().optional(),allowedDomains:r.array(r.string()).optional(),blockedDomains:r.array(r.string()).optional(),citations:r.object({enabled:r.boolean()}).optional(),maxContentTokens:r.number().optional()}))),d_=j(()=>M(r.object({type:r.literal("web_fetch_result"),url:r.string(),content:r.object({type:r.literal("document"),title:r.string().nullable(),citations:r.object({enabled:r.boolean()}).optional(),source:r.union([r.object({type:r.literal("base64"),mediaType:r.literal("application/pdf"),data:r.string()}),r.object({type:r.literal("text"),mediaType:r.literal("text/plain"),data:r.string()})])}),retrievedAt:r.string().nullable()}))),fN=j(()=>M(r.object({url:r.string()}))),hN=Te({id:"anthropic.web_fetch_20250910",inputSchema:fN,outputSchema:d_,supportsDeferredResults:!0}),yN=(e={})=>hN(e);async function vN({tools:e,toolChoice:t,disableParallelToolUse:n,cacheControlValidator:o,supportsStructuredOutput:i,supportsStrictTools:a,defaultEagerInputStreaming:s=!1}){var l,c;e=(e==null?void 0:e.length)?e:void 0;let u=[],d=new Set,m=o||new cu;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:u,betas:d};let p=[];for(let g of e)switch(g.type){case"function":{let h=m.getCacheControl(g.providerOptions,{type:"tool definition",canCache:!0}),v=(l=g.providerOptions)==null?void 0:l.anthropic,x=(c=v==null?void 0:v.eagerInputStreaming)!=null?c:s,S=v==null?void 0:v.deferLoading,y=v==null?void 0:v.allowedCallers;if(!a&&g.strict!=null)u.push({type:"unsupported",feature:"strict",details:`Tool '${g.name}' has strict: ${g.strict}, but strict mode is not supported by this provider. The strict property will be ignored.`});if(p.push({name:g.name,description:g.description,input_schema:g.inputSchema,cache_control:h,...x?{eager_input_streaming:!0}:{},...a===!0&&g.strict!=null?{strict:g.strict}:{},...S!=null?{defer_loading:S}:{},...y!=null?{allowed_callers:y}:{},...g.inputExamples!=null?{input_examples:g.inputExamples.map((w)=>w.input)}:{}}),i===!0)d.add("structured-outputs-2025-11-13");if(g.inputExamples!=null||y!=null)d.add("advanced-tool-use-2025-11-20");break}case"provider":{switch(g.id){case"anthropic.code_execution_20250522":{d.add("code-execution-2025-05-22"),p.push({type:"code_execution_20250522",name:"code_execution",cache_control:void 0});break}case"anthropic.code_execution_20250825":{d.add("code-execution-2025-08-25"),p.push({type:"code_execution_20250825",name:"code_execution"});break}case"anthropic.code_execution_20260120":{p.push({type:"code_execution_20260120",name:"code_execution"});break}case"anthropic.computer_20250124":{d.add("computer-use-2025-01-24"),p.push({name:"computer",type:"computer_20250124",display_width_px:g.args.displayWidthPx,display_height_px:g.args.displayHeightPx,display_number:g.args.displayNumber,cache_control:void 0});break}case"anthropic.computer_20251124":{d.add("computer-use-2025-11-24"),p.push({name:"computer",type:"computer_20251124",display_width_px:g.args.displayWidthPx,display_height_px:g.args.displayHeightPx,display_number:g.args.displayNumber,enable_zoom:g.args.enableZoom,cache_control:void 0});break}case"anthropic.computer_20241022":{d.add("computer-use-2024-10-22"),p.push({name:"computer",type:"computer_20241022",display_width_px:g.args.displayWidthPx,display_height_px:g.args.displayHeightPx,display_number:g.args.displayNumber,cache_control:void 0});break}case"anthropic.text_editor_20250124":{d.add("computer-use-2025-01-24"),p.push({name:"str_replace_editor",type:"text_editor_20250124",cache_control:void 0});break}case"anthropic.text_editor_20241022":{d.add("computer-use-2024-10-22"),p.push({name:"str_replace_editor",type:"text_editor_20241022",cache_control:void 0});break}case"anthropic.text_editor_20250429":{d.add("computer-use-2025-01-24"),p.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429",cache_control:void 0});break}case"anthropic.text_editor_20250728":{let h=await Ee({value:g.args,schema:KO});p.push({name:"str_replace_based_edit_tool",type:"text_editor_20250728",max_characters:h.maxCharacters,cache_control:void 0});break}case"anthropic.bash_20250124":{d.add("computer-use-2025-01-24"),p.push({name:"bash",type:"bash_20250124",cache_control:void 0});break}case"anthropic.bash_20241022":{d.add("computer-use-2024-10-22"),p.push({name:"bash",type:"bash_20241022",cache_control:void 0});break}case"anthropic.memory_20250818":{d.add("context-management-2025-06-27"),p.push({name:"memory",type:"memory_20250818"});break}case"anthropic.web_fetch_20250910":{d.add("web-fetch-2025-09-10");let h=await Ee({value:g.args,schema:gN});p.push({type:"web_fetch_20250910",name:"web_fetch",max_uses:h.maxUses,allowed_domains:h.allowedDomains,blocked_domains:h.blockedDomains,citations:h.citations,max_content_tokens:h.maxContentTokens,cache_control:void 0});break}case"anthropic.web_fetch_20260209":{d.add("code-execution-web-tools-2026-02-09");let h=await Ee({value:g.args,schema:cN});p.push({type:"web_fetch_20260209",name:"web_fetch",max_uses:h.maxUses,allowed_domains:h.allowedDomains,blocked_domains:h.blockedDomains,citations:h.citations,max_content_tokens:h.maxContentTokens,cache_control:void 0});break}case"anthropic.web_search_20250305":{let h=await Ee({value:g.args,schema:iN});p.push({type:"web_search_20250305",name:"web_search",max_uses:h.maxUses,allowed_domains:h.allowedDomains,blocked_domains:h.blockedDomains,user_location:h.userLocation,cache_control:void 0});break}case"anthropic.web_search_20260209":{d.add("code-execution-web-tools-2026-02-09");let h=await Ee({value:g.args,schema:eN});p.push({type:"web_search_20260209",name:"web_search",max_uses:h.maxUses,allowed_domains:h.allowedDomains,blocked_domains:h.blockedDomains,user_location:h.userLocation,cache_control:void 0});break}case"anthropic.tool_search_regex_20251119":{p.push({type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"});break}case"anthropic.tool_search_bm25_20251119":{p.push({type:"tool_search_tool_bm25_20251119",name:"tool_search_tool_bm25"});break}case"anthropic.advisor_20260301":{d.add("advisor-tool-2026-03-01");let h=await Ee({value:g.args,schema:HO});p.push({type:"advisor_20260301",name:"advisor",model:h.model,...h.maxUses!==void 0&&{max_uses:h.maxUses},...h.caching!==void 0&&{caching:h.caching}});break}default:{u.push({type:"unsupported",feature:`provider-defined tool ${g.id}`});break}}break}default:{u.push({type:"unsupported",feature:`tool ${g}`});break}}if(t==null)return{tools:p,toolChoice:n?{type:"auto",disable_parallel_tool_use:n}:void 0,toolWarnings:u,betas:d};let f=t.type;switch(f){case"auto":return{tools:p,toolChoice:{type:"auto",disable_parallel_tool_use:n},toolWarnings:u,betas:d};case"required":return{tools:p,toolChoice:{type:"any",disable_parallel_tool_use:n},toolWarnings:u,betas:d};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:u,betas:d};case"tool":return{tools:p,toolChoice:{type:"tool",name:t.toolName,disable_parallel_tool_use:n},toolWarnings:u,betas:d};default:throw new We({functionality:`tool choice type: ${f}`})}}function r_({usage:e,rawUsage:t}){var n,o,i;let a=(n=e.cache_creation_input_tokens)!=null?n:0,s=(o=e.cache_read_input_tokens)!=null?o:0,l,c,u=(i=e.iterations)==null?void 0:i.some((d)=>d.type==="fallback_message");if(e.iterations&&e.iterations.length>0&&!u){let d=e.iterations.filter((m)=>m.type==="compaction"||m.type==="message");if(d.length>0){let m=d.reduce((p,f)=>({input:p.input+f.input_tokens,output:p.output+f.output_tokens}),{input:0,output:0});l=m.input,c=m.output}else l=e.input_tokens,c=e.output_tokens}else l=e.input_tokens,c=e.output_tokens;return{inputTokens:{total:l+a+s,noCache:l,cacheRead:s,cacheWrite:a},outputTokens:{total:c,text:void 0,reasoning:void 0},raw:t!=null?t:e}}var p_=j(()=>M(r.object({type:r.literal("code_execution_result"),stdout:r.string(),stderr:r.string(),return_code:r.number(),content:r.array(r.object({type:r.literal("code_execution_output"),file_id:r.string()})).optional().default([])}))),bN=j(()=>M(r.object({code:r.string()}))),_N=Te({id:"anthropic.code_execution_20250522",inputSchema:bN,outputSchema:p_}),SN=(e={})=>_N(e),m_=j(()=>M(r.discriminatedUnion("type",[r.object({type:r.literal("code_execution_result"),stdout:r.string(),stderr:r.string(),return_code:r.number(),content:r.array(r.object({type:r.literal("code_execution_output"),file_id:r.string()})).optional().default([])}),r.object({type:r.literal("bash_code_execution_result"),content:r.array(r.object({type:r.literal("bash_code_execution_output"),file_id:r.string()})),stdout:r.string(),stderr:r.string(),return_code:r.number()}),r.object({type:r.literal("bash_code_execution_tool_result_error"),error_code:r.string()}),r.object({type:r.literal("text_editor_code_execution_tool_result_error"),error_code:r.string()}),r.object({type:r.literal("text_editor_code_execution_view_result"),content:r.string(),file_type:r.string(),num_lines:r.number().nullable(),start_line:r.number().nullable(),total_lines:r.number().nullable()}),r.object({type:r.literal("text_editor_code_execution_create_result"),is_file_update:r.boolean()}),r.object({type:r.literal("text_editor_code_execution_str_replace_result"),lines:r.array(r.string()).nullable(),new_lines:r.number().nullable(),new_start:r.number().nullable(),old_lines:r.number().nullable(),old_start:r.number().nullable()})]))),wN=j(()=>M(r.discriminatedUnion("type",[r.object({type:r.literal("programmatic-tool-call"),code:r.string()}),r.object({type:r.literal("bash_code_execution"),command:r.string()}),r.discriminatedUnion("command",[r.object({type:r.literal("text_editor_code_execution"),command:r.literal("view"),path:r.string()}),r.object({type:r.literal("text_editor_code_execution"),command:r.literal("create"),path:r.string(),file_text:r.string().nullish()}),r.object({type:r.literal("text_editor_code_execution"),command:r.literal("str_replace"),path:r.string(),old_str:r.string(),new_str:r.string()})])]))),xN=Te({id:"anthropic.code_execution_20250825",inputSchema:wN,outputSchema:m_,supportsDeferredResults:!0}),TN=(e={})=>xN(e),g_=j(()=>M(r.discriminatedUnion("type",[r.object({type:r.literal("code_execution_result"),stdout:r.string(),stderr:r.string(),return_code:r.number(),content:r.array(r.object({type:r.literal("code_execution_output"),file_id:r.string()})).optional().default([])}),r.object({type:r.literal("encrypted_code_execution_result"),encrypted_stdout:r.string(),stderr:r.string(),return_code:r.number(),content:r.array(r.object({type:r.literal("code_execution_output"),file_id:r.string()})).optional().default([])}),r.object({type:r.literal("bash_code_execution_result"),content:r.array(r.object({type:r.literal("bash_code_execution_output"),file_id:r.string()})),stdout:r.string(),stderr:r.string(),return_code:r.number()}),r.object({type:r.literal("bash_code_execution_tool_result_error"),error_code:r.string()}),r.object({type:r.literal("text_editor_code_execution_tool_result_error"),error_code:r.string()}),r.object({type:r.literal("text_editor_code_execution_view_result"),content:r.string(),file_type:r.string(),num_lines:r.number().nullable(),start_line:r.number().nullable(),total_lines:r.number().nullable()}),r.object({type:r.literal("text_editor_code_execution_create_result"),is_file_update:r.boolean()}),r.object({type:r.literal("text_editor_code_execution_str_replace_result"),lines:r.array(r.string()).nullable(),new_lines:r.number().nullable(),new_start:r.number().nullable(),old_lines:r.number().nullable(),old_start:r.number().nullable()})]))),IN=j(()=>M(r.discriminatedUnion("type",[r.object({type:r.literal("programmatic-tool-call"),code:r.string()}),r.object({type:r.literal("bash_code_execution"),command:r.string()}),r.discriminatedUnion("command",[r.object({type:r.literal("text_editor_code_execution"),command:r.literal("view"),path:r.string()}),r.object({type:r.literal("text_editor_code_execution"),command:r.literal("create"),path:r.string(),file_text:r.string().nullish()}),r.object({type:r.literal("text_editor_code_execution"),command:r.literal("str_replace"),path:r.string(),old_str:r.string(),new_str:r.string()})])]))),CN=Te({id:"anthropic.code_execution_20260120",inputSchema:IN,outputSchema:g_,supportsDeferredResults:!0}),kN=(e={})=>CN(e),f_=j(()=>M(r.array(r.object({type:r.literal("tool_reference"),toolName:r.string()})))),RN=j(()=>M(r.object({pattern:r.string(),limit:r.number().optional()}))),EN=Te({id:"anthropic.tool_search_regex_20251119",inputSchema:RN,outputSchema:f_,supportsDeferredResults:!0}),AN=(e={})=>EN(e);function PN(e){if(typeof e==="string")return new TextDecoder().decode(wt(e));if(e instanceof Uint8Array)return new TextDecoder().decode(e);if(e instanceof URL)throw new We({functionality:"URL-based text documents are not supported for citations"});throw new We({functionality:`unsupported data type for text documents: ${typeof e}`})}function au(e){return e instanceof URL||MN(e)}function MN(e){return typeof e==="string"&&/^https?:\/\//i.test(e)}function su(e){return e instanceof URL?e.toString():e}async function n_(e){if(typeof e==="string"){let t=await xt({text:e});if(t.success&&typeof t.value==="object"&&t.value!==null)return t.value;return{errorCode:"unavailable"}}if(typeof e==="object"&&e!==null)return e;return{}}async function jN({prompt:e,sendReasoning:t,warnings:n,cacheControlValidator:o,toolNameMapping:i}){var a,s,l,c,u,d,m,p,f,g,h,v,x,S,y,w,_,C,I,b,E;let B=new Set,R=ON(e),U=o||new cu,z=void 0,N=[];async function re(V){var q,ue;let ee=await Ue({provider:"anthropic",providerOptions:V,schema:Xb});return(ue=(q=ee==null?void 0:ee.citations)==null?void 0:q.enabled)!=null?ue:!1}async function Y(V){let q=await Ue({provider:"anthropic",providerOptions:V,schema:Xb});return{title:q==null?void 0:q.title,context:q==null?void 0:q.context}}for(let V=0;V<R.length;V++){let q=R[V],ue=V===R.length-1,ee=q.type;switch(ee){case"system":{let k=q.messages.map(({content:X,providerOptions:H})=>({type:"text",text:X,cache_control:U.getCacheControl(H,{type:"system message",canCache:!0})}));if(z==null)z=k;else N.push({role:"system",content:k}),B.add("mid-conversation-system-2026-04-07");break}case"user":{let k=[];for(let X of q.messages){let{role:H,content:J}=X;switch(H){case"user":{for(let K=0;K<J.length;K++){let D=J[K],F=K===J.length-1,G=(a=U.getCacheControl(D.providerOptions,{type:"user message part",canCache:!0}))!=null?a:F?U.getCacheControl(X.providerOptions,{type:"user message",canCache:!0}):void 0;switch(D.type){case"text":{k.push({type:"text",text:D.text,cache_control:G});break}case"file":{if(D.mediaType.startsWith("image/"))k.push({type:"image",source:au(D.data)?{type:"url",url:su(D.data)}:{type:"base64",media_type:D.mediaType==="image/*"?"image/jpeg":D.mediaType,data:bt(D.data)},cache_control:G});else if(D.mediaType==="application/pdf"){B.add("pdfs-2024-09-25");let Z=await re(D.providerOptions),A=await Y(D.providerOptions);k.push({type:"document",source:au(D.data)?{type:"url",url:su(D.data)}:{type:"base64",media_type:"application/pdf",data:bt(D.data)},title:(s=A.title)!=null?s:D.filename,...A.context&&{context:A.context},...Z&&{citations:{enabled:!0}},cache_control:G})}else if(D.mediaType==="text/plain"){let Z=await re(D.providerOptions),A=await Y(D.providerOptions);k.push({type:"document",source:au(D.data)?{type:"url",url:su(D.data)}:{type:"text",media_type:"text/plain",data:PN(D.data)},title:(l=A.title)!=null?l:D.filename,...A.context&&{context:A.context},...Z&&{citations:{enabled:!0}},cache_control:G})}else throw new We({functionality:`media type: ${D.mediaType}`});break}}}break}case"tool":{for(let K=0;K<J.length;K++){let D=J[K];if(D.type==="tool-approval-response")continue;let F=D.output,G="providerOptions"in F?F.providerOptions:F.type==="content"?(c=F.value.find((W)=>W.providerOptions!=null))==null?void 0:c.providerOptions:void 0,Z=K===J.length-1,A=(d=(u=U.getCacheControl(D.providerOptions,{type:"tool result part",canCache:!0}))!=null?u:U.getCacheControl(G,{type:"tool result output",canCache:!0}))!=null?d:Z?U.getCacheControl(X.providerOptions,{type:"tool result message",canCache:!0}):void 0,O;switch(F.type){case"content":O=F.value.map((W)=>{var P;switch(W.type){case"text":return{type:"text",text:W.text};case"image-data":return{type:"image",source:{type:"base64",media_type:W.mediaType,data:W.data}};case"image-url":return{type:"image",source:{type:"url",url:W.url}};case"file-url":return{type:"document",source:{type:"url",url:W.url}};case"file-data":{if(W.mediaType==="application/pdf")return B.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:W.mediaType,data:W.data}};n.push({type:"other",message:`unsupported tool content part type: ${W.type} with media type: ${W.mediaType}`});return}case"custom":{let L=(P=W.providerOptions)==null?void 0:P.anthropic;if((L==null?void 0:L.type)==="tool-reference")return{type:"tool_reference",tool_name:L.toolName};n.push({type:"other",message:"unsupported custom tool content part"});return}default:{n.push({type:"other",message:`unsupported tool content part type: ${W.type}`});return}}}).filter(yi);break;case"text":case"error-text":O=F.value;break;case"execution-denied":O=(m=F.reason)!=null?m:"Tool call execution denied.";break;case"json":case"error-json":default:O=JSON.stringify(F.value);break}k.push({type:"tool_result",tool_use_id:D.toolCallId,content:O,is_error:F.type==="error-text"||F.type==="error-json"?!0:void 0,cache_control:A})}break}default:throw Error(`Unsupported role: ${H}`)}}N.push({role:"user",content:k});break}case"assistant":{let k=[],X=new Set;for(let H=0;H<q.messages.length;H++){let J=q.messages[H],K=H===q.messages.length-1,{content:D}=J;for(let F=0;F<D.length;F++){let G=D[F],Z=F===D.length-1,A=(p=U.getCacheControl(G.providerOptions,{type:"assistant message part",canCache:!0}))!=null?p:Z?U.getCacheControl(J.providerOptions,{type:"assistant message",canCache:!0}):void 0;switch(G.type){case"text":{let O=(f=G.providerOptions)==null?void 0:f.anthropic;if((O==null?void 0:O.type)==="compaction")k.push({type:"compaction",content:G.text,cache_control:A});else k.push({type:"text",text:ue&&K&&Z?G.text.trim():G.text,cache_control:A});break}case"reasoning":{if(t){let O=await Ue({provider:"anthropic",providerOptions:G.providerOptions,schema:GO});if(O!=null)if(O.signature!=null)U.getCacheControl(G.providerOptions,{type:"thinking block",canCache:!1}),k.push({type:"thinking",thinking:G.text,signature:O.signature});else if(O.redactedData!=null)U.getCacheControl(G.providerOptions,{type:"redacted thinking block",canCache:!1}),k.push({type:"redacted_thinking",data:O.redactedData});else n.push({type:"other",message:"unsupported reasoning metadata"});else n.push({type:"other",message:"unsupported reasoning metadata"})}else n.push({type:"other",message:"sending reasoning content is disabled for this model"});break}case"tool-call":{if(G.providerExecuted){let P=i.toProviderToolName(G.toolName);if(((h=(g=G.providerOptions)==null?void 0:g.anthropic)==null?void 0:h.type)==="mcp-tool-use"){X.add(G.toolCallId);let me=(x=(v=G.providerOptions)==null?void 0:v.anthropic)==null?void 0:x.serverName;if(me==null||typeof me!=="string"){n.push({type:"other",message:"mcp tool use server name is required and must be a string"});break}k.push({type:"mcp_tool_use",id:G.toolCallId,name:G.toolName,input:G.input,server_name:me,cache_control:A})}else if(P==="code_execution"&&G.input!=null&&typeof G.input==="object"&&"type"in G.input&&typeof G.input.type==="string"&&(G.input.type==="bash_code_execution"||G.input.type==="text_editor_code_execution"))k.push({type:"server_tool_use",id:G.toolCallId,name:G.input.type,input:G.input,cache_control:A});else if(P==="code_execution"&&G.input!=null&&typeof G.input==="object"&&"type"in G.input&&G.input.type==="programmatic-tool-call"){let{type:me,...Q}=G.input;k.push({type:"server_tool_use",id:G.toolCallId,name:"code_execution",input:Q,cache_control:A})}else if(P==="code_execution"||P==="web_fetch"||P==="web_search")k.push({type:"server_tool_use",id:G.toolCallId,name:P,input:G.input,cache_control:A});else if(P==="tool_search_tool_regex"||P==="tool_search_tool_bm25")k.push({type:"server_tool_use",id:G.toolCallId,name:P,input:G.input,cache_control:A});else if(P==="advisor")k.push({type:"server_tool_use",id:G.toolCallId,name:"advisor",input:{},cache_control:A});else n.push({type:"other",message:`provider executed tool call for tool ${G.toolName} is not supported`});break}let O=(S=G.providerOptions)==null?void 0:S.anthropic,W=(O==null?void 0:O.caller)?(O.caller.type==="code_execution_20250825"||O.caller.type==="code_execution_20260120")&&O.caller.toolId?{type:O.caller.type,tool_id:O.caller.toolId}:O.caller.type==="direct"?{type:"direct"}:void 0:void 0;k.push({type:"tool_use",id:G.toolCallId,name:G.toolName,input:G.input,...W&&{caller:W},cache_control:A});break}case"tool-result":{let O=i.toProviderToolName(G.toolName);if(X.has(G.toolCallId)){let W=G.output;if(W.type!=="json"&&W.type!=="error-json"){n.push({type:"other",message:`provider executed tool result output type ${W.type} for tool ${G.toolName} is not supported`});break}k.push({type:"mcp_tool_result",tool_use_id:G.toolCallId,is_error:W.type==="error-json",content:W.value,cache_control:A})}else if(O==="code_execution"){let W=G.output;if(W.type==="error-text"||W.type==="error-json"){let P={};try{if(typeof W.value==="string")P=er(W.value);else if(typeof W.value==="object"&&W.value!==null)P=W.value}catch(L){}if(P.type==="code_execution_tool_result_error")k.push({type:"code_execution_tool_result",tool_use_id:G.toolCallId,content:{type:"code_execution_tool_result_error",error_code:(y=P.errorCode)!=null?y:"unknown"},cache_control:A});else k.push({type:"bash_code_execution_tool_result",tool_use_id:G.toolCallId,cache_control:A,content:{type:"bash_code_execution_tool_result_error",error_code:(w=P.errorCode)!=null?w:"unknown"}});break}if(W.type!=="json"){n.push({type:"other",message:`provider executed tool result output type ${W.type} for tool ${G.toolName} is not supported`});break}if(W.value==null||typeof W.value!=="object"||!("type"in W.value)||typeof W.value.type!=="string"){n.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${G.toolName}`});break}if(W.value.type==="code_execution_result"){let P=await Ee({value:W.value,schema:p_});k.push({type:"code_execution_tool_result",tool_use_id:G.toolCallId,content:{type:P.type,stdout:P.stdout,stderr:P.stderr,return_code:P.return_code,content:(_=P.content)!=null?_:[]},cache_control:A})}else if(W.value.type==="encrypted_code_execution_result"){let P=await Ee({value:W.value,schema:g_});if(P.type==="encrypted_code_execution_result")k.push({type:"code_execution_tool_result",tool_use_id:G.toolCallId,content:{type:P.type,encrypted_stdout:P.encrypted_stdout,stderr:P.stderr,return_code:P.return_code,content:(C=P.content)!=null?C:[]},cache_control:A})}else{let P=await Ee({value:W.value,schema:m_});if(P.type==="code_execution_result")k.push({type:"code_execution_tool_result",tool_use_id:G.toolCallId,content:{type:P.type,stdout:P.stdout,stderr:P.stderr,return_code:P.return_code,content:(I=P.content)!=null?I:[]},cache_control:A});else if(P.type==="bash_code_execution_result"||P.type==="bash_code_execution_tool_result_error")k.push({type:"bash_code_execution_tool_result",tool_use_id:G.toolCallId,cache_control:A,content:P});else k.push({type:"text_editor_code_execution_tool_result",tool_use_id:G.toolCallId,cache_control:A,content:P})}break}if(O==="web_fetch"){let W=G.output;if(W.type==="error-json"){k.push({type:"web_fetch_tool_result",tool_use_id:G.toolCallId,content:{type:"web_fetch_tool_result_error",error_code:(b=(await n_(W.value)).errorCode)!=null?b:"unavailable"},cache_control:A});break}if(W.type!=="json"){n.push({type:"other",message:`provider executed tool result output type ${W.type} for tool ${G.toolName} is not supported`});break}let P=await Ee({value:W.value,schema:d_});k.push({type:"web_fetch_tool_result",tool_use_id:G.toolCallId,content:{type:"web_fetch_result",url:P.url,retrieved_at:P.retrievedAt,content:{type:"document",title:P.content.title,citations:P.content.citations,source:{type:P.content.source.type,media_type:P.content.source.mediaType,data:P.content.source.data}}},cache_control:A});break}if(O==="web_search"){let W=G.output;if(W.type==="error-json"){k.push({type:"web_search_tool_result",tool_use_id:G.toolCallId,content:{type:"web_search_tool_result_error",error_code:(E=(await n_(W.value)).errorCode)!=null?E:"unavailable"},cache_control:A});break}if(W.type!=="json"){n.push({type:"other",message:`provider executed tool result output type ${W.type} for tool ${G.toolName} is not supported`});break}let P=await Ee({value:W.value,schema:u_});k.push({type:"web_search_tool_result",tool_use_id:G.toolCallId,content:P.map((L)=>({url:L.url,title:L.title,page_age:L.pageAge,encrypted_content:L.encryptedContent,type:L.type})),cache_control:A});break}if(O==="tool_search_tool_regex"||O==="tool_search_tool_bm25"){let W=G.output;if(W.type!=="json"){n.push({type:"other",message:`provider executed tool result output type ${W.type} for tool ${G.toolName} is not supported`});break}let L=(await Ee({value:W.value,schema:f_})).map((me)=>({type:"tool_reference",tool_name:me.toolName}));k.push({type:"tool_search_tool_result",tool_use_id:G.toolCallId,content:{type:"tool_search_tool_search_result",tool_references:L},cache_control:A});break}if(O==="advisor"){let W=G.output;if(W.type!=="json"&&W.type!=="error-json"){n.push({type:"other",message:`provider executed tool result output type ${W.type} for tool ${G.toolName} is not supported`});break}let P=await Ee({value:W.value,schema:c_});if(P.type==="advisor_result")k.push({type:"advisor_tool_result",tool_use_id:G.toolCallId,content:{type:"advisor_result",text:P.text},cache_control:A});else if(P.type==="advisor_redacted_result")k.push({type:"advisor_tool_result",tool_use_id:G.toolCallId,content:{type:"advisor_redacted_result",encrypted_content:P.encryptedContent},cache_control:A});else k.push({type:"advisor_tool_result",tool_use_id:G.toolCallId,content:{type:"advisor_tool_result_error",error_code:P.errorCode},cache_control:A});break}n.push({type:"other",message:`provider executed tool result for tool ${G.toolName} is not supported`});break}}}}N.push({role:"assistant",content:NN(k)});break}default:throw Error(`content type: ${ee}`)}}return{prompt:{system:z,messages:N},betas:B}}function ON(e){let t=[],n=void 0;for(let o of e){let{role:i}=o;switch(i){case"system":{if((n==null?void 0:n.type)!=="system")n={type:"system",messages:[]},t.push(n);n.messages.push(o);break}case"assistant":{if((n==null?void 0:n.type)!=="assistant")n={type:"assistant",messages:[]},t.push(n);n.messages.push(o);break}case"user":{if((n==null?void 0:n.type)!=="user")n={type:"user",messages:[]},t.push(n);n.messages.push(o);break}case"tool":{if((n==null?void 0:n.type)!=="user")n={type:"user",messages:[]},t.push(n);n.messages.push(o);break}default:throw Error(`Unsupported role: ${i}`)}}return t}function NN(e){let t=[],n=[];function o(){t.push(...n.filter((i)=>i.type!=="tool_use"),...n.filter((i)=>i.type==="tool_use")),n=[]}for(let i of e)if(i.type==="thinking"||i.type==="redacted_thinking")o(),t.push(i);else n.push(i);return o(),t}function lu({finishReason:e,isJsonResponseFromTool:t}){switch(e){case"pause_turn":case"end_turn":case"stop_sequence":return"stop";case"refusal":return"content-filter";case"tool_use":return t?"stop":"tool-calls";case"max_tokens":case"model_context_window_exceeded":return"length";case"compaction":return"other";default:return"other"}}var h_=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),DN=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","minItems","maxItems","uniqueItems","minProperties","maxProperties","not"];function zN(e){return y_(e)}function fn(e){if(typeof e==="boolean"||!qN(e))return e;return y_(e)}function y_(e){let t={},n=e;if(e.$ref!=null)return{$ref:e.$ref};if(e.$schema!=null)t.$schema=e.$schema;if(e.$id!=null)t.$id=e.$id;if(e.title!=null)t.title=e.title;if(e.description!=null)t.description=e.description;if(e.default!==void 0)t.default=e.default;if(e.const!==void 0)t.const=e.const;if(e.enum!=null)t.enum=e.enum;if(e.type!=null)t.type=e.type;if(e.anyOf!=null)t.anyOf=e.anyOf.map(fn);else if(e.oneOf!=null)t.anyOf=e.oneOf.map(fn);if(e.allOf!=null)t.allOf=e.allOf.map(fn);if(e.definitions!=null)t.definitions=Object.fromEntries(Object.entries(e.definitions).map(([i,a])=>[i,fn(a)]));if(n.$defs!=null){let i=t;i.$defs=Object.fromEntries(Object.entries(n.$defs).map(([a,s])=>[a,fn(s)]))}if(e.type==="object"||e.properties!=null){if(e.properties!=null)t.properties=Object.fromEntries(Object.entries(e.properties).map(([i,a])=>[i,fn(a)]));if(t.additionalProperties=!1,e.required!=null)t.required=e.required}if(e.items!=null)t.items=Array.isArray(e.items)?e.items.map(fn):fn(e.items);if(typeof e.format==="string"&&h_.has(e.format))t.format=e.format;let o=UN(e);if(o!=null)t.description=t.description==null?o:`${t.description}
71
+ ${o}`;return t}function UN(e){let t=DN.flatMap((n)=>{let o=e[n];if(o==null||o===!1)return[];return`${$N(n)}: ${LN(o)}`});if(typeof e.format==="string"&&!h_.has(e.format))t.push(`format: ${e.format}`);return t.length===0?void 0:`${t.join("; ")}.`}function $N(e){return e.replace(/[A-Z]/g,(t)=>` ${t.toLowerCase()}`)}function LN(e){if(typeof e==="string")return e;return JSON.stringify(e)}function qN(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function o_(e,t,n){var o;if(e.type==="web_search_result_location")return{type:"source",sourceType:"url",id:n(),url:e.url,title:e.title,providerMetadata:{anthropic:{citedText:e.cited_text,encryptedIndex:e.encrypted_index}}};if(e.type!=="page_location"&&e.type!=="char_location")return;let i=t[e.document_index];if(!i)return;return{type:"source",sourceType:"document",id:n(),mediaType:i.mediaType,title:(o=e.document_title)!=null?o:i.title,filename:i.filename,providerMetadata:{anthropic:e.type==="page_location"?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index}}}}var FN=class{constructor(e,t){this.specificationVersion="v3";var n;this.modelId=e,this.config=t,this.generateId=(n=t.generateId)!=null?n:Le}supportsUrl(e){return e.protocol==="https:"}get provider(){return this.config.provider}get providerOptionsName(){let e=this.config.provider,t=e.indexOf(".");return t===-1?e:e.substring(0,t)}get supportedUrls(){var e,t,n;return(n=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?n:{}}async getArgs({userSuppliedBetas:e,prompt:t,maxOutputTokens:n,temperature:o,topP:i,topK:a,frequencyPenalty:s,presencePenalty:l,stopSequences:c,responseFormat:u,seed:d,tools:m,toolChoice:p,providerOptions:f,stream:g}){var h,v,x,S,y,w,_,C,I,b;let E=[];if(s!=null)E.push({type:"unsupported",feature:"frequencyPenalty"});if(l!=null)E.push({type:"unsupported",feature:"presencePenalty"});if(d!=null)E.push({type:"unsupported",feature:"seed"});if(o!=null&&o>1)E.push({type:"unsupported",feature:"temperature",details:`${o} exceeds anthropic maximum of 1.0. clamped to 1.0`}),o=1;else if(o!=null&&o<0)E.push({type:"unsupported",feature:"temperature",details:`${o} is below anthropic minimum of 0. clamped to 0`}),o=0;if((u==null?void 0:u.type)==="json"){if(u.schema==null)E.push({type:"unsupported",feature:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."})}let B=this.providerOptionsName,R=await Ue({provider:"anthropic",providerOptions:f,schema:e_}),U=B!=="anthropic"?await Ue({provider:B,providerOptions:f,schema:e_}):null,z=U!=null,N=Object.assign({},R!=null?R:{},U!=null?U:{}),{maxOutputTokens:re,supportsStructuredOutput:Y,rejectsSamplingParameters:V,isKnownModel:q}=BN(this.modelId);if(V){if(o!=null)E.push({type:"unsupported",feature:"temperature",details:`temperature is not supported by ${this.modelId} and will be ignored`}),o=void 0;if(a!=null)E.push({type:"unsupported",feature:"topK",details:`topK is not supported by ${this.modelId} and will be ignored`}),a=void 0;if(i!=null)E.push({type:"unsupported",feature:"topP",details:`topP is not supported by ${this.modelId} and will be ignored`}),i=void 0}let ue=q||this.modelId.startsWith("claude-"),ee=((h=this.config.supportsNativeStructuredOutput)!=null?h:!0)&&Y,k=((v=this.config.supportsStrictTools)!=null?v:!0)&&Y,X=(x=N==null?void 0:N.structuredOutputMode)!=null?x:"auto",H=X==="outputFormat"||X==="auto"&&ee,J=(u==null?void 0:u.type)==="json"&&u.schema!=null&&!H?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:u.schema}:void 0,K=N==null?void 0:N.contextManagement,D=new cu,F=Aa({tools:m,providerToolNames:{"anthropic.code_execution_20250522":"code_execution","anthropic.code_execution_20250825":"code_execution","anthropic.code_execution_20260120":"code_execution","anthropic.computer_20241022":"computer","anthropic.computer_20250124":"computer","anthropic.text_editor_20241022":"str_replace_editor","anthropic.text_editor_20250124":"str_replace_editor","anthropic.text_editor_20250429":"str_replace_based_edit_tool","anthropic.text_editor_20250728":"str_replace_based_edit_tool","anthropic.bash_20241022":"bash","anthropic.bash_20250124":"bash","anthropic.memory_20250818":"memory","anthropic.web_search_20250305":"web_search","anthropic.web_search_20260209":"web_search","anthropic.web_fetch_20250910":"web_fetch","anthropic.web_fetch_20260209":"web_fetch","anthropic.tool_search_regex_20251119":"tool_search_tool_regex","anthropic.tool_search_bm25_20251119":"tool_search_tool_bm25","anthropic.advisor_20260301":"advisor"}}),{prompt:G,betas:Z}=await jN({prompt:t,sendReasoning:(S=N==null?void 0:N.sendReasoning)!=null?S:!0,warnings:E,cacheControlValidator:D,toolNameMapping:F}),A=(y=N==null?void 0:N.thinking)==null?void 0:y.type,O=A==="enabled"||A==="adaptive",W=O||A==="disabled",P=A==="enabled"?(w=N==null?void 0:N.thinking)==null?void 0:w.budgetTokens:void 0,L=A==="adaptive"?(_=N==null?void 0:N.thinking)==null?void 0:_.display:void 0,me=n!=null?n:re,Q={model:this.modelId,max_tokens:me,temperature:o,top_k:a,top_p:i,stop_sequences:c,...W&&{thinking:{type:A,...P!=null&&{budget_tokens:P},...L!=null&&{display:L}}},...((N==null?void 0:N.effort)||(N==null?void 0:N.taskBudget)||H&&(u==null?void 0:u.type)==="json"&&u.schema!=null)&&{output_config:{...(N==null?void 0:N.effort)&&{effort:N.effort},...(N==null?void 0:N.taskBudget)&&{task_budget:{type:N.taskBudget.type,total:N.taskBudget.total,...N.taskBudget.remaining!=null&&{remaining:N.taskBudget.remaining}}},...H&&(u==null?void 0:u.type)==="json"&&u.schema!=null&&{format:{type:"json_schema",schema:zN(u.schema)}}}},...(N==null?void 0:N.speed)&&{speed:N.speed},...(N==null?void 0:N.inferenceGeo)&&{inference_geo:N.inferenceGeo},...(N==null?void 0:N.fallbacks)&&N.fallbacks.length>0&&{fallbacks:N.fallbacks},...(N==null?void 0:N.cacheControl)&&{cache_control:N.cacheControl},...((C=N==null?void 0:N.metadata)==null?void 0:C.userId)!=null&&{metadata:{user_id:N.metadata.userId}},...(N==null?void 0:N.mcpServers)&&N.mcpServers.length>0&&{mcp_servers:N.mcpServers.map((he)=>({type:he.type,name:he.name,url:he.url,authorization_token:he.authorizationToken,tool_configuration:he.toolConfiguration?{allowed_tools:he.toolConfiguration.allowedTools,enabled:he.toolConfiguration.enabled}:void 0}))},...(N==null?void 0:N.container)&&{container:N.container.skills&&N.container.skills.length>0?{id:N.container.id,skills:N.container.skills.map((he)=>({type:he.type,skill_id:he.skillId,version:he.version}))}:N.container.id},system:G.system,messages:G.messages,...K&&{context_management:{edits:K.edits.map((he)=>{let br=he.type;switch(br){case"clear_tool_uses_20250919":return{type:he.type,...he.trigger!==void 0&&{trigger:he.trigger},...he.keep!==void 0&&{keep:he.keep},...he.clearAtLeast!==void 0&&{clear_at_least:he.clearAtLeast},...he.clearToolInputs!==void 0&&{clear_tool_inputs:he.clearToolInputs},...he.excludeTools!==void 0&&{exclude_tools:he.excludeTools}};case"clear_thinking_20251015":return{type:he.type,...he.keep!==void 0&&{keep:he.keep}};case"compact_20260112":return{type:he.type,...he.trigger!==void 0&&{trigger:he.trigger},...he.pauseAfterCompaction!==void 0&&{pause_after_compaction:he.pauseAfterCompaction},...he.instructions!==void 0&&{instructions:he.instructions}};default:E.push({type:"other",message:`Unknown context management strategy: ${br}`});return}}).filter((he)=>he!==void 0)}}};if(O){if(A==="enabled"&&P==null)E.push({type:"compatibility",feature:"extended thinking",details:"thinking budget is required when thinking is enabled. using default budget of 1024 tokens."}),Q.thinking={type:"enabled",budget_tokens:1024},P=1024;if(Q.temperature!=null)Q.temperature=void 0,E.push({type:"unsupported",feature:"temperature",details:"temperature is not supported when thinking is enabled"});if(a!=null)Q.top_k=void 0,E.push({type:"unsupported",feature:"topK",details:"topK is not supported when thinking is enabled"});if(i!=null)Q.top_p=void 0,E.push({type:"unsupported",feature:"topP",details:"topP is not supported when thinking is enabled"});Q.max_tokens=me+(P!=null?P:0)}else if(ue&&i!=null&&o!=null)E.push({type:"unsupported",feature:"topP",details:"topP is not supported when temperature is set. topP is ignored."}),Q.top_p=void 0;if(q&&Q.max_tokens>re){if(n!=null)E.push({type:"unsupported",feature:"maxOutputTokens",details:`${Q.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${re} max output tokens. The max output tokens have been limited to ${re}.`});Q.max_tokens=re}if((N==null?void 0:N.mcpServers)&&N.mcpServers.length>0)Z.add("mcp-client-2025-04-04");if(K){if(Z.add("context-management-2025-06-27"),K.edits.some((he)=>he.type==="compact_20260112"))Z.add("compact-2026-01-12")}if((N==null?void 0:N.container)&&N.container.skills&&N.container.skills.length>0){if(Z.add("code-execution-2025-08-25"),Z.add("skills-2025-10-02"),Z.add("files-api-2025-04-14"),!(m==null?void 0:m.some((he)=>he.type==="provider"&&(he.id==="anthropic.code_execution_20250825"||he.id==="anthropic.code_execution_20260120"))))E.push({type:"other",message:"code execution tool is required when using skills"})}if(N==null?void 0:N.taskBudget)Z.add("task-budgets-2026-03-13");if((N==null?void 0:N.speed)==="fast")Z.add("fast-mode-2026-02-01");if((N==null?void 0:N.fallbacks)&&N.fallbacks.length>0)Z.add("server-side-fallback-2026-06-01");let de=g&&((I=N==null?void 0:N.toolStreaming)!=null?I:!0),{tools:Ae,toolChoice:Ke,toolWarnings:nt,betas:At}=await vN(J!=null?{tools:[...m!=null?m:[],J],toolChoice:{type:"required"},disableParallelToolUse:!0,cacheControlValidator:D,supportsStructuredOutput:!1,supportsStrictTools:k,defaultEagerInputStreaming:de}:{tools:m!=null?m:[],toolChoice:p,disableParallelToolUse:N==null?void 0:N.disableParallelToolUse,cacheControlValidator:D,supportsStructuredOutput:ee,supportsStrictTools:k,defaultEagerInputStreaming:de}),Dr=D.getWarnings();return{args:{...Q,tools:Ae,tool_choice:Ke,stream:g===!0?!0:void 0},warnings:[...E,...nt,...Dr],betas:new Set([...Z,...At,...e,...(b=N==null?void 0:N.anthropicBeta)!=null?b:[]]),usesJsonResponseTool:J!=null,toolNameMapping:F,providerOptionsName:B,usedCustomProviderKey:z}}async getHeaders({betas:e,headers:t}){return _e(await Se(this.config.headers),t,e.size>0?{"anthropic-beta":Array.from(e).join(",")}:{})}async getBetasFromHeaders(e){var t,n;let i=(t=(await Se(this.config.headers))["anthropic-beta"])!=null?t:"",a=(n=e==null?void 0:e["anthropic-beta"])!=null?n:"";return new Set([...i.toLowerCase().split(","),...a.toLowerCase().split(",")].map((s)=>s.trim()).filter((s)=>s!==""))}buildRequestUrl(e){var t,n,o;return(o=(n=(t=this.config).buildRequestUrl)==null?void 0:n.call(t,this.config.baseURL,e))!=null?o:`${this.config.baseURL}/messages`}transformRequestBody(e,t){var n,o,i;return(i=(o=(n=this.config).transformRequestBody)==null?void 0:o.call(n,e,t))!=null?i:e}extractCitationDocuments(e){let t=(n)=>{var o,i;if(n.type!=="file")return!1;if(n.mediaType!=="application/pdf"&&n.mediaType!=="text/plain")return!1;let a=(o=n.providerOptions)==null?void 0:o.anthropic,s=a==null?void 0:a.citations;return(i=s==null?void 0:s.enabled)!=null?i:!1};return e.filter((n)=>n.role==="user").flatMap((n)=>n.content).filter(t).map((n)=>{var o;let i=n;return{title:(o=i.filename)!=null?o:"Untitled Document",filename:i.filename,mediaType:i.mediaType}})}async doGenerate(e){var t,n,o,i,a,s,l;let{args:c,warnings:u,betas:d,usesJsonResponseTool:m,toolNameMapping:p,providerOptionsName:f,usedCustomProviderKey:g}=await this.getArgs({...e,stream:!1,userSuppliedBetas:await this.getBetasFromHeaders(e.headers)}),h=[...this.extractCitationDocuments(e.prompt)],v=i_(c.tools),{responseHeaders:x,value:S,rawValue:y}=await Ie({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:d,headers:e.headers}),body:this.transformRequestBody(c,d),failedResponseHandler:Qb,successfulResponseHandler:xe(FO),abortSignal:e.abortSignal,fetch:this.config.fetch}),w=[],_={},C={},I=!1;for(let b of S.content)switch(b.type){case"text":{if(!m){if(w.push({type:"text",text:b.text}),b.citations)for(let E of b.citations){let B=o_(E,h,this.generateId);if(B)w.push(B)}}break}case"thinking":{w.push({type:"reasoning",text:b.thinking,providerMetadata:{anthropic:{signature:b.signature}}});break}case"redacted_thinking":{w.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:b.data}}});break}case"compaction":{w.push({type:"text",text:b.content,providerMetadata:{anthropic:{type:"compaction"}}});break}case"tool_use":{if(m&&b.name==="json")I=!0,w.push({type:"text",text:JSON.stringify(b.input)});else{let B=b.caller,R=B?{type:B.type,toolId:"tool_id"in B?B.tool_id:void 0}:void 0;w.push({type:"tool-call",toolCallId:b.id,toolName:b.name,input:JSON.stringify(b.input),...R&&{providerMetadata:{anthropic:{caller:R}}}})}break}case"server_tool_use":{if(b.name==="text_editor_code_execution"||b.name==="bash_code_execution")w.push({type:"tool-call",toolCallId:b.id,toolName:p.toCustomToolName("code_execution"),input:JSON.stringify({type:b.name,...b.input}),providerExecuted:!0,...v?{dynamic:!0}:{}});else if(b.name==="web_search"||b.name==="code_execution"||b.name==="web_fetch"){let E=b.name==="code_execution"&&b.input!=null&&typeof b.input==="object"&&"code"in b.input&&!("type"in b.input)?{type:"programmatic-tool-call",...b.input}:b.input;w.push({type:"tool-call",toolCallId:b.id,toolName:p.toCustomToolName(b.name),input:JSON.stringify(E),providerExecuted:!0,...v&&b.name==="code_execution"?{dynamic:!0}:{}})}else if(b.name==="tool_search_tool_regex"||b.name==="tool_search_tool_bm25")C[b.id]=b.name,w.push({type:"tool-call",toolCallId:b.id,toolName:p.toCustomToolName(b.name),input:JSON.stringify(b.input),providerExecuted:!0});else if(b.name==="advisor")w.push({type:"tool-call",toolCallId:b.id,toolName:p.toCustomToolName("advisor"),input:JSON.stringify(b.input),providerExecuted:!0});break}case"mcp_tool_use":{_[b.id]={type:"tool-call",toolCallId:b.id,toolName:b.name,input:JSON.stringify(b.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:b.server_name}}},w.push(_[b.id]);break}case"mcp_tool_result":{w.push({type:"tool-result",toolCallId:b.tool_use_id,toolName:_[b.tool_use_id].toolName,isError:b.is_error,result:b.content,dynamic:!0,providerMetadata:_[b.tool_use_id].providerMetadata});break}case"web_fetch_tool_result":{if(b.content.type==="web_fetch_result")h.push({title:(t=b.content.content.title)!=null?t:b.content.url,mediaType:b.content.content.source.media_type}),w.push({type:"tool-result",toolCallId:b.tool_use_id,toolName:p.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:b.content.url,retrievedAt:b.content.retrieved_at,content:{type:b.content.content.type,title:b.content.content.title,citations:b.content.content.citations,source:{type:b.content.content.source.type,mediaType:b.content.content.source.media_type,data:b.content.content.source.data}}}});else if(b.content.type==="web_fetch_tool_result_error")w.push({type:"tool-result",toolCallId:b.tool_use_id,toolName:p.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:b.content.error_code}});break}case"web_search_tool_result":{if(Array.isArray(b.content)){w.push({type:"tool-result",toolCallId:b.tool_use_id,toolName:p.toCustomToolName("web_search"),result:b.content.map((E)=>{var B;return{url:E.url,title:E.title,pageAge:(B=E.page_age)!=null?B:null,encryptedContent:E.encrypted_content,type:E.type}})});for(let E of b.content)w.push({type:"source",sourceType:"url",id:this.generateId(),url:E.url,title:E.title,providerMetadata:{anthropic:{pageAge:(n=E.page_age)!=null?n:null}}})}else w.push({type:"tool-result",toolCallId:b.tool_use_id,toolName:p.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:b.content.error_code}});break}case"code_execution_tool_result":{if(b.content.type==="code_execution_result")w.push({type:"tool-result",toolCallId:b.tool_use_id,toolName:p.toCustomToolName("code_execution"),result:{type:b.content.type,stdout:b.content.stdout,stderr:b.content.stderr,return_code:b.content.return_code,content:(o=b.content.content)!=null?o:[]}});else if(b.content.type==="encrypted_code_execution_result")w.push({type:"tool-result",toolCallId:b.tool_use_id,toolName:p.toCustomToolName("code_execution"),result:{type:b.content.type,encrypted_stdout:b.content.encrypted_stdout,stderr:b.content.stderr,return_code:b.content.return_code,content:(i=b.content.content)!=null?i:[]}});else if(b.content.type==="code_execution_tool_result_error")w.push({type:"tool-result",toolCallId:b.tool_use_id,toolName:p.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:b.content.error_code}});break}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{w.push({type:"tool-result",toolCallId:b.tool_use_id,toolName:p.toCustomToolName("code_execution"),result:b.content});break}case"tool_search_tool_result":{let E=C[b.tool_use_id];if(E==null){let B=p.toCustomToolName("tool_search_tool_bm25"),R=p.toCustomToolName("tool_search_tool_regex");if(B!=="tool_search_tool_bm25")E="tool_search_tool_bm25";else if(R!=="tool_search_tool_regex")E="tool_search_tool_regex";else E="tool_search_tool_regex"}if(b.content.type==="tool_search_tool_search_result")w.push({type:"tool-result",toolCallId:b.tool_use_id,toolName:p.toCustomToolName(E),result:b.content.tool_references.map((B)=>({type:B.type,toolName:B.tool_name}))});else w.push({type:"tool-result",toolCallId:b.tool_use_id,toolName:p.toCustomToolName(E),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:b.content.error_code}});break}case"advisor_tool_result":{let E=p.toCustomToolName("advisor");if(b.content.type==="advisor_result")w.push({type:"tool-result",toolCallId:b.tool_use_id,toolName:E,result:{type:"advisor_result",text:b.content.text}});else if(b.content.type==="advisor_redacted_result")w.push({type:"tool-result",toolCallId:b.tool_use_id,toolName:E,result:{type:"advisor_redacted_result",encryptedContent:b.content.encrypted_content}});else w.push({type:"tool-result",toolCallId:b.tool_use_id,toolName:E,isError:!0,result:{type:"advisor_tool_result_error",errorCode:b.content.error_code}});break}case"fallback":break}return{content:w,finishReason:{unified:lu({finishReason:S.stop_reason,isJsonResponseFromTool:I}),raw:(a=S.stop_reason)!=null?a:void 0},usage:r_({usage:S.usage}),request:{body:c},response:{id:(s=S.id)!=null?s:void 0,modelId:(l=S.model)!=null?l:void 0,headers:x,body:y},warnings:u,providerMetadata:(()=>{var b,E,B,R,U;let z=s_(S.stop_details),N={usage:S.usage,cacheCreationInputTokens:(b=S.usage.cache_creation_input_tokens)!=null?b:null,stopSequence:(E=S.stop_sequence)!=null?E:null,...z!=null?{stopDetails:z}:{},iterations:S.usage.iterations?S.usage.iterations.map((Y)=>({type:Y.type,...Y.model!=null?{model:Y.model}:{},inputTokens:Y.input_tokens,outputTokens:Y.output_tokens,...Y.cache_creation_input_tokens?{cacheCreationInputTokens:Y.cache_creation_input_tokens}:{},...Y.cache_read_input_tokens?{cacheReadInputTokens:Y.cache_read_input_tokens}:{}})):null,container:S.container?{expiresAt:S.container.expires_at,id:S.container.id,skills:(R=(B=S.container.skills)==null?void 0:B.map((Y)=>({type:Y.type,skillId:Y.skill_id,version:Y.version})))!=null?R:null}:null,contextManagement:(U=a_(S.context_management))!=null?U:null},re={anthropic:N};if(g&&f!=="anthropic")re[f]=N;return re})()}}async doStream(e){var t,n;let{args:o,warnings:i,betas:a,usesJsonResponseTool:s,toolNameMapping:l,providerOptionsName:c,usedCustomProviderKey:u}=await this.getArgs({...e,stream:!0,userSuppliedBetas:await this.getBetasFromHeaders(e.headers)}),d=[...this.extractCitationDocuments(e.prompt)],m=i_(o.tools),p=this.buildRequestUrl(!0),{responseHeaders:f,value:g}=await Ie({url:p,headers:await this.getHeaders({betas:a,headers:e.headers}),body:this.transformRequestBody(o,a),failedResponseHandler:Qb,successfulResponseHandler:Dt(BO),abortSignal:e.abortSignal,fetch:this.config.fetch}),h={unified:"other",raw:void 0},v={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0,iterations:null},x={},S={},y={},w=null,_=void 0,C=null,I=null,b=void 0,E=null,B=!1,R=void 0,U=this.generateId,z=g.pipeThrough(new TransformStream({start(V){V.enqueue({type:"stream-start",warnings:i})},transform(V,q){var ue,ee,k,X,H,J,K,D,F,G,Z,A,O,W;if(e.includeRawChunks)q.enqueue({type:"raw",rawValue:V.rawValue});if(!V.success){q.enqueue({type:"error",error:V.error});return}let P=V.value;switch(P.type){case"ping":return;case"content_block_start":{let L=P.content_block,me=L.type;if(me==="fallback")return;switch(R=me,me){case"text":{if(s)return;x[P.index]={type:"text"},q.enqueue({type:"text-start",id:String(P.index)});return}case"thinking":{x[P.index]={type:"reasoning"},q.enqueue({type:"reasoning-start",id:String(P.index)});return}case"redacted_thinking":{x[P.index]={type:"reasoning"},q.enqueue({type:"reasoning-start",id:String(P.index),providerMetadata:{anthropic:{redactedData:L.data}}});return}case"compaction":{x[P.index]={type:"text"},q.enqueue({type:"text-start",id:String(P.index),providerMetadata:{anthropic:{type:"compaction"}}});return}case"tool_use":{if(s&&L.name==="json")B=!0,x[P.index]={type:"text"},q.enqueue({type:"text-start",id:String(P.index)});else{let de=L.caller,Ae=de?{type:de.type,toolId:"tool_id"in de?de.tool_id:void 0}:void 0,nt=L.input&&Object.keys(L.input).length>0?JSON.stringify(L.input):"";x[P.index]={type:"tool-call",toolCallId:L.id,toolName:L.name,input:nt,firstDelta:nt.length===0,...Ae&&{caller:Ae}},q.enqueue({type:"tool-input-start",id:L.id,toolName:L.name})}return}case"server_tool_use":{if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(L.name)){let Q=L.name==="text_editor_code_execution"||L.name==="bash_code_execution"?"code_execution":L.name,de=L.name==="text_editor_code_execution"||L.name==="bash_code_execution"?L.name:L.name==="code_execution"?"programmatic-tool-call":void 0,Ae=l.toCustomToolName(Q),Ke=L.input!=null&&typeof L.input==="object"&&Object.keys(L.input).length>0?JSON.stringify(L.input):"";x[P.index]={type:"tool-call",toolCallId:L.id,toolName:Ae,input:Ke,providerExecuted:!0,...m&&Q==="code_execution"?{dynamic:!0}:{},firstDelta:Ke.length===0,providerToolName:Q,providerToolInputType:de},q.enqueue({type:"tool-input-start",id:L.id,toolName:Ae,providerExecuted:!0,...m&&Q==="code_execution"?{dynamic:!0}:{}})}else if(L.name==="tool_search_tool_regex"||L.name==="tool_search_tool_bm25"){y[L.id]=L.name;let Q=l.toCustomToolName(L.name);x[P.index]={type:"tool-call",toolCallId:L.id,toolName:Q,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:L.name},q.enqueue({type:"tool-input-start",id:L.id,toolName:Q,providerExecuted:!0})}else if(L.name==="advisor"){let Q=l.toCustomToolName("advisor");x[P.index]={type:"tool-call",toolCallId:L.id,toolName:Q,input:"{}",providerExecuted:!0,firstDelta:!0,providerToolName:L.name},q.enqueue({type:"tool-input-start",id:L.id,toolName:Q,providerExecuted:!0})}return}case"web_fetch_tool_result":{if(L.content.type==="web_fetch_result")d.push({title:(ue=L.content.content.title)!=null?ue:L.content.url,mediaType:L.content.content.source.media_type}),q.enqueue({type:"tool-result",toolCallId:L.tool_use_id,toolName:l.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:L.content.url,retrievedAt:L.content.retrieved_at,content:{type:L.content.content.type,title:L.content.content.title,citations:L.content.content.citations,source:{type:L.content.content.source.type,mediaType:L.content.content.source.media_type,data:L.content.content.source.data}}}});else if(L.content.type==="web_fetch_tool_result_error")q.enqueue({type:"tool-result",toolCallId:L.tool_use_id,toolName:l.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:L.content.error_code}});return}case"web_search_tool_result":{if(Array.isArray(L.content)){q.enqueue({type:"tool-result",toolCallId:L.tool_use_id,toolName:l.toCustomToolName("web_search"),result:L.content.map((Q)=>{var de;return{url:Q.url,title:Q.title,pageAge:(de=Q.page_age)!=null?de:null,encryptedContent:Q.encrypted_content,type:Q.type}})});for(let Q of L.content)q.enqueue({type:"source",sourceType:"url",id:U(),url:Q.url,title:Q.title,providerMetadata:{anthropic:{pageAge:(ee=Q.page_age)!=null?ee:null}}})}else q.enqueue({type:"tool-result",toolCallId:L.tool_use_id,toolName:l.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:L.content.error_code}});return}case"code_execution_tool_result":{if(L.content.type==="code_execution_result")q.enqueue({type:"tool-result",toolCallId:L.tool_use_id,toolName:l.toCustomToolName("code_execution"),result:{type:L.content.type,stdout:L.content.stdout,stderr:L.content.stderr,return_code:L.content.return_code,content:(k=L.content.content)!=null?k:[]}});else if(L.content.type==="encrypted_code_execution_result")q.enqueue({type:"tool-result",toolCallId:L.tool_use_id,toolName:l.toCustomToolName("code_execution"),result:{type:L.content.type,encrypted_stdout:L.content.encrypted_stdout,stderr:L.content.stderr,return_code:L.content.return_code,content:(X=L.content.content)!=null?X:[]}});else if(L.content.type==="code_execution_tool_result_error")q.enqueue({type:"tool-result",toolCallId:L.tool_use_id,toolName:l.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:L.content.error_code}});return}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{q.enqueue({type:"tool-result",toolCallId:L.tool_use_id,toolName:l.toCustomToolName("code_execution"),result:L.content});return}case"tool_search_tool_result":{let Q=y[L.tool_use_id];if(Q==null){let de=l.toCustomToolName("tool_search_tool_bm25"),Ae=l.toCustomToolName("tool_search_tool_regex");if(de!=="tool_search_tool_bm25")Q="tool_search_tool_bm25";else if(Ae!=="tool_search_tool_regex")Q="tool_search_tool_regex";else Q="tool_search_tool_regex"}if(L.content.type==="tool_search_tool_search_result")q.enqueue({type:"tool-result",toolCallId:L.tool_use_id,toolName:l.toCustomToolName(Q),result:L.content.tool_references.map((de)=>({type:de.type,toolName:de.tool_name}))});else q.enqueue({type:"tool-result",toolCallId:L.tool_use_id,toolName:l.toCustomToolName(Q),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:L.content.error_code}});return}case"advisor_tool_result":{let Q=l.toCustomToolName("advisor");if(L.content.type==="advisor_result")q.enqueue({type:"tool-result",toolCallId:L.tool_use_id,toolName:Q,result:{type:"advisor_result",text:L.content.text}});else if(L.content.type==="advisor_redacted_result")q.enqueue({type:"tool-result",toolCallId:L.tool_use_id,toolName:Q,result:{type:"advisor_redacted_result",encryptedContent:L.content.encrypted_content}});else q.enqueue({type:"tool-result",toolCallId:L.tool_use_id,toolName:Q,isError:!0,result:{type:"advisor_tool_result_error",errorCode:L.content.error_code}});return}case"mcp_tool_use":{S[L.id]={type:"tool-call",toolCallId:L.id,toolName:L.name,input:JSON.stringify(L.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:L.server_name}}},q.enqueue(S[L.id]);return}case"mcp_tool_result":{q.enqueue({type:"tool-result",toolCallId:L.tool_use_id,toolName:S[L.tool_use_id].toolName,isError:L.is_error,result:L.content,dynamic:!0,providerMetadata:S[L.tool_use_id].providerMetadata});return}default:throw Error(`Unsupported content block type: ${me}`)}}case"content_block_stop":{if(x[P.index]!=null){let L=x[P.index];switch(L.type){case"text":{q.enqueue({type:"text-end",id:String(P.index)});break}case"reasoning":{q.enqueue({type:"reasoning-end",id:String(P.index)});break}case"tool-call":if(!(s&&L.toolName==="json")){q.enqueue({type:"tool-input-end",id:L.toolCallId});let Q=L.input===""?"{}":L.input;if(L.providerToolName==="code_execution")try{let de=er(Q);if(de!=null&&typeof de==="object"&&"code"in de&&!("type"in de))Q=JSON.stringify({type:"programmatic-tool-call",...de})}catch(de){}q.enqueue({type:"tool-call",toolCallId:L.toolCallId,toolName:L.toolName,input:Q,providerExecuted:L.providerExecuted,...m&&L.providerToolName==="code_execution"?{dynamic:!0}:{},...L.caller&&{providerMetadata:{anthropic:{caller:L.caller}}}})}break}delete x[P.index]}R=void 0;return}case"content_block_delta":{let L=P.delta.type;switch(L){case"text_delta":{if(s)return;q.enqueue({type:"text-delta",id:String(P.index),delta:P.delta.text});return}case"thinking_delta":{q.enqueue({type:"reasoning-delta",id:String(P.index),delta:P.delta.thinking});return}case"signature_delta":{if(R==="thinking")q.enqueue({type:"reasoning-delta",id:String(P.index),delta:"",providerMetadata:{anthropic:{signature:P.delta.signature}}});return}case"compaction_delta":{if(P.delta.content!=null)q.enqueue({type:"text-delta",id:String(P.index),delta:P.delta.content});return}case"input_json_delta":{let me=x[P.index],Q=P.delta.partial_json;if(Q.length===0)return;if(B){if((me==null?void 0:me.type)!=="text")return;q.enqueue({type:"text-delta",id:String(P.index),delta:Q})}else{if((me==null?void 0:me.type)!=="tool-call")return;if(me.firstDelta&&me.providerToolInputType!=null)Q=`{"type": "${me.providerToolInputType}",${Q.substring(1)}`;q.enqueue({type:"tool-input-delta",id:me.toolCallId,delta:Q}),me.input+=Q,me.firstDelta=!1}return}case"citations_delta":{let me=P.delta.citation,Q=o_(me,d,U);if(Q)q.enqueue(Q);return}default:throw Error(`Unsupported delta type: ${L}`)}}case"message_start":{if(v.input_tokens=P.message.usage.input_tokens,v.cache_read_input_tokens=(H=P.message.usage.cache_read_input_tokens)!=null?H:0,v.cache_creation_input_tokens=(J=P.message.usage.cache_creation_input_tokens)!=null?J:0,_={...P.message.usage},C=(K=P.message.usage.cache_creation_input_tokens)!=null?K:null,P.message.container!=null)E={expiresAt:P.message.container.expires_at,id:P.message.container.id,skills:null};if(P.message.stop_reason!=null)h={unified:lu({finishReason:P.message.stop_reason,isJsonResponseFromTool:B}),raw:P.message.stop_reason};if(q.enqueue({type:"response-metadata",id:(D=P.message.id)!=null?D:void 0,modelId:(F=P.message.model)!=null?F:void 0}),P.message.content!=null)for(let L=0;L<P.message.content.length;L++){let me=P.message.content[L];if(me.type==="tool_use"){let Q=me.caller,de=Q?{type:Q.type,toolId:"tool_id"in Q?Q.tool_id:void 0}:void 0;q.enqueue({type:"tool-input-start",id:me.id,toolName:me.name});let Ae=JSON.stringify((G=me.input)!=null?G:{});q.enqueue({type:"tool-input-delta",id:me.id,delta:Ae}),q.enqueue({type:"tool-input-end",id:me.id}),q.enqueue({type:"tool-call",toolCallId:me.id,toolName:me.name,input:Ae,...de&&{providerMetadata:{anthropic:{caller:de}}}})}}return}case"message_delta":{if(P.usage.input_tokens!=null&&v.input_tokens!==P.usage.input_tokens)v.input_tokens=P.usage.input_tokens;if(v.output_tokens=P.usage.output_tokens,P.usage.cache_read_input_tokens!=null)v.cache_read_input_tokens=P.usage.cache_read_input_tokens;if(P.usage.cache_creation_input_tokens!=null)v.cache_creation_input_tokens=P.usage.cache_creation_input_tokens,C=P.usage.cache_creation_input_tokens;if(P.usage.iterations!=null)v.iterations=P.usage.iterations;if(h={unified:lu({finishReason:P.delta.stop_reason,isJsonResponseFromTool:B}),raw:(Z=P.delta.stop_reason)!=null?Z:void 0},I=(A=P.delta.stop_sequence)!=null?A:null,b=s_(P.delta.stop_details),E=P.delta.container!=null?{expiresAt:P.delta.container.expires_at,id:P.delta.container.id,skills:(W=(O=P.delta.container.skills)==null?void 0:O.map((L)=>({type:L.type,skillId:L.skill_id,version:L.version})))!=null?W:null}:null,P.context_management)w=a_(P.context_management);_={..._,...P.usage};return}case"message_stop":{let L={usage:_!=null?_:null,cacheCreationInputTokens:C,stopSequence:I,...b!=null?{stopDetails:b}:{},iterations:v.iterations?v.iterations.map((Q)=>({type:Q.type,...Q.model!=null?{model:Q.model}:{},inputTokens:Q.input_tokens,outputTokens:Q.output_tokens,...Q.cache_creation_input_tokens?{cacheCreationInputTokens:Q.cache_creation_input_tokens}:{},...Q.cache_read_input_tokens?{cacheReadInputTokens:Q.cache_read_input_tokens}:{}})):null,container:E,contextManagement:w},me={anthropic:L};if(u&&c!=="anthropic")me[c]=L;q.enqueue({type:"finish",finishReason:h,usage:r_({usage:v,rawUsage:_}),providerMetadata:me});return}case"error":{q.enqueue({type:"error",error:P.error});return}default:throw Error(`Unsupported chunk type: ${P}`)}}})),[N,re]=z.tee(),Y=N.getReader();try{await Y.read();let V=await Y.read();if(((t=V.value)==null?void 0:t.type)==="raw")V=await Y.read();if(((n=V.value)==null?void 0:n.type)==="error"){let q=V.value.error;throw new De({message:q.message,url:p,requestBodyValues:o,statusCode:q.type==="overloaded_error"?529:500,responseHeaders:f,responseBody:JSON.stringify(q),isRetryable:q.type==="overloaded_error"})}}finally{Y.cancel().catch(()=>{}),Y.releaseLock()}return{stream:re,request:{body:o},response:{headers:f}}}};function BN(e){if(e.includes("claude-opus-4-8")||e.includes("claude-opus-4-7")||e.includes("claude-fable-5")||e.includes("claude-sonnet-5"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,rejectsSamplingParameters:!0,isKnownModel:!0};else if(e.includes("claude-sonnet-4-6")||e.includes("claude-opus-4-6"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,isKnownModel:!0};else if(e.includes("claude-sonnet-4-5")||e.includes("claude-opus-4-5")||e.includes("claude-haiku-4-5"))return{maxOutputTokens:64000,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,isKnownModel:!0};else if(e.includes("claude-opus-4-1"))return{maxOutputTokens:32000,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,isKnownModel:!0};else if(e.includes("claude-sonnet-4-"))return{maxOutputTokens:64000,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0};else if(e.includes("claude-opus-4-"))return{maxOutputTokens:32000,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0};else if(e.includes("claude-3-haiku"))return{maxOutputTokens:4096,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0};else return{maxOutputTokens:4096,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!1}}function i_(e){if(!e)return!1;let t=!1,n=!1;for(let o of e){if("type"in o&&(o.type==="web_fetch_20260209"||o.type==="web_search_20260209")){t=!0;continue}if(o.name==="code_execution"){n=!0;break}}return t&&!n}function a_(e){return e?{appliedEdits:e.applied_edits.map((t)=>{switch(t.type){case"clear_tool_uses_20250919":return{type:t.type,clearedToolUses:t.cleared_tool_uses,clearedInputTokens:t.cleared_input_tokens};case"clear_thinking_20251015":return{type:t.type,clearedThinkingTurns:t.cleared_thinking_turns,clearedInputTokens:t.cleared_input_tokens};case"compact_20260112":return{type:t.type}}}).filter((t)=>t!==void 0)}:null}function s_(e){if(e==null)return;return{type:e.type,...e.category!=null?{category:e.category}:{},...e.explanation!=null?{explanation:e.explanation}:{},...e.recommended_model!=null?{recommendedModel:e.recommended_model}:{}}}var GN=j(()=>M(r.object({command:r.string(),restart:r.boolean().optional()}))),JN=Ge({id:"anthropic.bash_20241022",inputSchema:GN}),HN=j(()=>M(r.object({command:r.string(),restart:r.boolean().optional()}))),WN=Ge({id:"anthropic.bash_20250124",inputSchema:HN}),VN=j(()=>M(r.object({action:r.enum(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:r.array(r.number().int()).optional(),text:r.string().optional()}))),ZN=Ge({id:"anthropic.computer_20241022",inputSchema:VN}),KN=j(()=>M(r.object({action:r.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:r.tuple([r.number().int(),r.number().int()]).optional(),duration:r.number().optional(),scroll_amount:r.number().optional(),scroll_direction:r.enum(["up","down","left","right"]).optional(),start_coordinate:r.tuple([r.number().int(),r.number().int()]).optional(),text:r.string().optional()}))),YN=Ge({id:"anthropic.computer_20250124",inputSchema:KN}),QN=j(()=>M(r.object({action:r.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot","zoom"]),coordinate:r.tuple([r.number().int(),r.number().int()]).optional(),duration:r.number().optional(),region:r.tuple([r.number().int(),r.number().int(),r.number().int(),r.number().int()]).optional(),scroll_amount:r.number().optional(),scroll_direction:r.enum(["up","down","left","right"]).optional(),start_coordinate:r.tuple([r.number().int(),r.number().int()]).optional(),text:r.string().optional()}))),XN=Ge({id:"anthropic.computer_20251124",inputSchema:QN}),eD=j(()=>M(r.discriminatedUnion("command",[r.object({command:r.literal("view"),path:r.string(),view_range:r.tuple([r.number(),r.number()]).optional()}),r.object({command:r.literal("create"),path:r.string(),file_text:r.string()}),r.object({command:r.literal("str_replace"),path:r.string(),old_str:r.string(),new_str:r.string()}),r.object({command:r.literal("insert"),path:r.string(),insert_line:r.number(),insert_text:r.string()}),r.object({command:r.literal("delete"),path:r.string()}),r.object({command:r.literal("rename"),old_path:r.string(),new_path:r.string()})]))),tD=Ge({id:"anthropic.memory_20250818",inputSchema:eD}),rD=j(()=>M(r.object({command:r.enum(["view","create","str_replace","insert","undo_edit"]),path:r.string(),file_text:r.string().optional(),insert_line:r.number().int().optional(),new_str:r.string().optional(),insert_text:r.string().optional(),old_str:r.string().optional(),view_range:r.array(r.number().int()).optional()}))),nD=Ge({id:"anthropic.text_editor_20241022",inputSchema:rD}),oD=j(()=>M(r.object({command:r.enum(["view","create","str_replace","insert","undo_edit"]),path:r.string(),file_text:r.string().optional(),insert_line:r.number().int().optional(),new_str:r.string().optional(),insert_text:r.string().optional(),old_str:r.string().optional(),view_range:r.array(r.number().int()).optional()}))),iD=Ge({id:"anthropic.text_editor_20250124",inputSchema:oD}),aD=j(()=>M(r.object({command:r.enum(["view","create","str_replace","insert"]),path:r.string(),file_text:r.string().optional(),insert_line:r.number().int().optional(),new_str:r.string().optional(),insert_text:r.string().optional(),old_str:r.string().optional(),view_range:r.array(r.number().int()).optional()}))),sD=Ge({id:"anthropic.text_editor_20250429",inputSchema:aD}),lD=j(()=>M(r.array(r.object({type:r.literal("tool_reference"),toolName:r.string()})))),cD=j(()=>M(r.object({query:r.string(),limit:r.number().optional()}))),uD=Te({id:"anthropic.tool_search_bm25_20251119",inputSchema:cD,outputSchema:lD,supportsDeferredResults:!0}),dD=(e={})=>uD(e),pD={advisor_20260301:ZO,bash_20241022:JN,bash_20250124:WN,codeExecution_20250522:SN,codeExecution_20250825:TN,codeExecution_20260120:kN,computer_20241022:ZN,computer_20250124:YN,computer_20251124:XN,memory_20250818:tD,textEditor_20241022:nD,textEditor_20250124:iD,textEditor_20250429:sD,textEditor_20250728:XO,webFetch_20250910:yN,webFetch_20260209:mN,webSearch_20250305:lN,webSearch_20260209:oN,toolSearchRegex_20251119:AN,toolSearchBm25_20251119:dD},v_="https://api.anthropic.com",b_=`${v_}/v1`;function mD(e){let t=mn(e);return t===v_?b_:t}function uu(e={}){var t,n;let o=(t=mD(Ar({settingValue:e.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"})))!=null?t:b_,i=(n=e.name)!=null?n:"anthropic.messages";if(e.apiKey&&e.authToken)throw new eo({argument:"apiKey/authToken",message:"Both apiKey and authToken were provided. Please use only one authentication method."});let a=()=>{let c=e.authToken?{Authorization:`Bearer ${e.authToken}`}:{"x-api-key":co({apiKey:e.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"})};return it({"anthropic-version":"2023-06-01",...c,...e.headers},`ai-sdk/anthropic/${LO}`)},s=(c)=>{var u;return new FN(c,{provider:i,baseURL:o,headers:a,fetch:e.fetch,generateId:(u=e.generateId)!=null?u:Le,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]})})},l=function(c){if(new.target)throw Error("The Anthropic model function cannot be called with the new keyword.");return s(c)};return l.specificationVersion="v3",l.languageModel=s,l.chat=s,l.messages=s,l.embeddingModel=(c)=>{throw new cl({modelId:c,modelType:"embeddingModel"})},l.textEmbeddingModel=l.embeddingModel,l.imageModel=(c)=>{throw new cl({modelId:c,modelType:"imageModel"})},l.tools=pD,l}var __=uu();var yu=r.object({error:r.object({message:r.string(),type:r.string().nullish(),param:r.any().nullish(),code:r.union([r.string(),r.number()]).nullish()})}),gr=Qe({errorSchema:yu,errorToMessage:(e)=>e.error.message});function L_(e){let t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),n=e.startsWith("gpt-4")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")&&!e.startsWith("gpt-5.4-nano")||e.startsWith("o3")||e.startsWith("o4-mini"),o=e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),i=e.startsWith("gpt-5.1")||e.startsWith("gpt-5.2")||e.startsWith("gpt-5.3")||e.startsWith("gpt-5.4")||e.startsWith("gpt-5.5");return{supportsFlexProcessing:t,supportsPriorityProcessing:n,isReasoningModel:o,systemMessageMode:o?"developer":"system",supportsNonReasoningParameters:i}}async function vu({stream:e,getError:t,isOutputChunk:n,url:o,requestBodyValues:i,responseHeaders:a}){let[s,l]=e.tee(),c=s.getReader();try{while(!0){let u=await c.read();if(u.done)return l;let d=u.value;if(!d.success)return l;let m=t(d.value);if(m!=null)throw l.cancel().catch(()=>{}),gD({frame:m,url:o,requestBodyValues:i,responseHeaders:a});if(n(d.value))return l}}finally{c.cancel().catch(()=>{}),c.releaseLock()}}function gD({frame:e,url:t,requestBodyValues:n,responseHeaders:o}){var i;let a=fD(e);return new De({message:(i=a==null?void 0:a.message)!=null?i:"OpenAI stream failed before any output was generated",url:t,requestBodyValues:n,statusCode:a==null?500:hD(a),responseHeaders:o,responseBody:JSON.stringify(e),data:e})}function fD(e){var t;let n=zi(e);if(n==null)return;if(n.type==="response.failed"){let i=zi(n.response),a=zi(i==null?void 0:i.error);return typeof(a==null?void 0:a.message)==="string"?{message:a.message,code:S_(a.code),type:"response.failed",frame:e}:void 0}let o=(t=zi(n.error))!=null?t:n;return typeof o.message==="string"&&(zi(n.error)!=null||typeof o.type==="string"||("code"in o)||("param"in o))?{message:o.message,code:S_(o.code),type:typeof o.type==="string"?o.type:void 0,frame:e}:void 0}function hD(e){if(typeof e.code==="number"&&w_(e.code))return e.code;if(typeof e.code==="string"&&/^\d{3}$/.test(e.code)){let n=Number(e.code);if(w_(n))return n}let t=[e.code,e.type].filter((n)=>typeof n==="string"||typeof n==="number").join(" ").toLowerCase();if(["insufficient_quota","rate_limit"].some((n)=>t.includes(n)))return 429;if(t.includes("authentication"))return 401;if(t.includes("permission"))return 403;if(t.includes("not_found"))return 404;if(["invalid","bad_request","context_length"].some((n)=>t.includes(n)))return 400;if(t.includes("overload"))return 503;if(t.includes("timeout"))return 504;return 500}function zi(e){return typeof e==="object"&&e!=null?e:void 0}function S_(e){return typeof e==="string"||typeof e==="number"?e:void 0}function w_(e){return Number.isInteger(e)&&e>=400&&e<=599}function x_(e){var t,n,o,i,a,s;if(e==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};let l=(t=e.prompt_tokens)!=null?t:0,c=(n=e.completion_tokens)!=null?n:0,u=(i=(o=e.prompt_tokens_details)==null?void 0:o.cached_tokens)!=null?i:0,d=(s=(a=e.completion_tokens_details)==null?void 0:a.reasoning_tokens)!=null?s:0;return{inputTokens:{total:l,noCache:l-u,cacheRead:u,cacheWrite:void 0},outputTokens:{total:c,text:c-d,reasoning:d},raw:e}}function yD(e){return JSON.stringify(e===void 0?{}:e)}function vD({prompt:e,systemMessageMode:t="system"}){var n;let o=[],i=[];for(let{role:a,content:s}of e)switch(a){case"system":{switch(t){case"system":{o.push({role:"system",content:s});break}case"developer":{o.push({role:"developer",content:s});break}case"remove":{i.push({type:"other",message:"system messages are removed for this model"});break}default:throw Error(`Unsupported system message mode: ${t}`)}break}case"user":{if(s.length===1&&s[0].type==="text"){o.push({role:"user",content:s[0].text});break}o.push({role:"user",content:s.map((l,c)=>{var u,d,m;switch(l.type){case"text":return{type:"text",text:l.text};case"file":if(l.mediaType.startsWith("image/")){let p=l.mediaType==="image/*"?"image/jpeg":l.mediaType;return{type:"image_url",image_url:{url:l.data instanceof URL?l.data.toString():`data:${p};base64,${bt(l.data)}`,detail:(d=(u=l.providerOptions)==null?void 0:u.openai)==null?void 0:d.imageDetail}}}else if(l.mediaType.startsWith("audio/")){if(l.data instanceof URL)throw new We({functionality:"audio file parts with URLs"});switch(l.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:bt(l.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:bt(l.data),format:"mp3"}};default:throw new We({functionality:`audio content parts with media type ${l.mediaType}`})}}else if(l.mediaType==="application/pdf"){if(l.data instanceof URL)throw new We({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof l.data==="string"&&l.data.startsWith("file-")?{file_id:l.data}:{filename:(m=l.filename)!=null?m:`part-${c}.pdf`,file_data:`data:application/pdf;base64,${bt(l.data)}`}}}else throw new We({functionality:`file part media type ${l.mediaType}`})}})});break}case"assistant":{let l="",c=[];for(let u of s)switch(u.type){case"text":{l+=u.text;break}case"tool-call":{c.push({id:u.toolCallId,type:"function",function:{name:u.toolName,arguments:yD(u.input)}});break}}o.push({role:"assistant",content:c.length>0?l||null:l,tool_calls:c.length>0?c:void 0});break}case"tool":{for(let l of s){if(l.type==="tool-approval-response")continue;let c=l.output,u;switch(c.type){case"text":case"error-text":u=c.value;break;case"execution-denied":u=(n=c.reason)!=null?n:"Tool call execution denied.";break;case"content":case"json":case"error-json":u=JSON.stringify(c.value);break}o.push({role:"tool",tool_call_id:l.toolCallId,content:u})}break}default:throw Error(`Unsupported role: ${a}`)}return{messages:o,warnings:i}}function du({id:e,model:t,created:n}){return{id:e!=null?e:void 0,modelId:t!=null?t:void 0,timestamp:n?new Date(n*1000):void 0}}function T_(e){switch(e){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 bD=j(()=>M(r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({message:r.object({role:r.literal("assistant").nullish(),content:r.string().nullish(),tool_calls:r.array(r.object({id:r.string().nullish(),type:r.literal("function"),function:r.object({name:r.string(),arguments:r.string()})})).nullish(),annotations:r.array(r.object({type:r.literal("url_citation"),url_citation:r.object({start_index:r.number(),end_index:r.number(),url:r.string(),title:r.string()})})).nullish()}),index:r.number(),logprobs:r.object({content:r.array(r.object({token:r.string(),logprob:r.number(),top_logprobs:r.array(r.object({token:r.string(),logprob:r.number()}))})).nullish()}).nullish(),finish_reason:r.string().nullish()})),usage:r.object({prompt_tokens:r.number().nullish(),completion_tokens:r.number().nullish(),total_tokens:r.number().nullish(),prompt_tokens_details:r.object({cached_tokens:r.number().nullish()}).nullish(),completion_tokens_details:r.object({reasoning_tokens:r.number().nullish(),accepted_prediction_tokens:r.number().nullish(),rejected_prediction_tokens:r.number().nullish()}).nullish()}).nullish()}))),_D=j(()=>M(r.union([r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({delta:r.object({role:r.enum(["assistant"]).nullish(),content:r.string().nullish(),tool_calls:r.array(r.object({index:r.number(),id:r.string().nullish(),type:r.literal("function").nullish(),function:r.object({name:r.string().nullish(),arguments:r.string().nullish()})})).nullish(),annotations:r.array(r.object({type:r.literal("url_citation"),url_citation:r.object({start_index:r.number(),end_index:r.number(),url:r.string(),title:r.string()})})).nullish()}).nullish(),logprobs:r.object({content:r.array(r.object({token:r.string(),logprob:r.number(),top_logprobs:r.array(r.object({token:r.string(),logprob:r.number()}))})).nullish()}).nullish(),finish_reason:r.string().nullish(),index:r.number()})),usage:r.object({prompt_tokens:r.number().nullish(),completion_tokens:r.number().nullish(),total_tokens:r.number().nullish(),prompt_tokens_details:r.object({cached_tokens:r.number().nullish()}).nullish(),completion_tokens_details:r.object({reasoning_tokens:r.number().nullish(),accepted_prediction_tokens:r.number().nullish(),rejected_prediction_tokens:r.number().nullish()}).nullish()}).nullish()}),yu]))),SD=j(()=>M(r.object({logitBias:r.record(r.coerce.number(),r.number()).optional(),logprobs:r.union([r.boolean(),r.number()]).optional(),parallelToolCalls:r.boolean().optional(),user:r.string().optional(),reasoningEffort:r.enum(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:r.number().optional(),store:r.boolean().optional(),metadata:r.record(r.string().max(64),r.string().max(512)).optional(),prediction:r.record(r.string(),r.any()).optional(),serviceTier:r.enum(["auto","flex","priority","default"]).optional(),strictJsonSchema:r.boolean().optional(),textVerbosity:r.enum(["low","medium","high"]).optional(),promptCacheKey:r.string().optional(),promptCacheRetention:r.enum(["in_memory","24h"]).optional(),safetyIdentifier:r.string().optional(),systemMessageMode:r.enum(["system","developer","remove"]).optional(),forceReasoning:r.boolean().optional()})));function wD({tools:e,toolChoice:t}){e=(e==null?void 0:e.length)?e:void 0;let n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let o=[];for(let a of e)switch(a.type){case"function":o.push({type:"function",function:{name:a.name,description:a.description,parameters:a.inputSchema,...a.strict!=null?{strict:a.strict}:{}}});break;default:n.push({type:"unsupported",feature:`tool type: ${a.type}`});break}if(t==null)return{tools:o,toolChoice:void 0,toolWarnings:n};let i=t.type;switch(i){case"auto":case"none":case"required":return{tools:o,toolChoice:i,toolWarnings:n};case"tool":return{tools:o,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:n};default:throw new We({functionality:`tool choice type: ${i}`})}}var xD=class{constructor(e,t){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:o,topK:i,frequencyPenalty:a,presencePenalty:s,stopSequences:l,responseFormat:c,seed:u,tools:d,toolChoice:m,providerOptions:p}){var f,g,h,v,x;let S=[],y=(f=await Ue({provider:"openai",providerOptions:p,schema:SD}))!=null?f:{},w=L_(this.modelId),_=(g=y.forceReasoning)!=null?g:w.isReasoningModel;if(i!=null)S.push({type:"unsupported",feature:"topK"});let{messages:C,warnings:I}=vD({prompt:e,systemMessageMode:(h=y.systemMessageMode)!=null?h:_?"developer":w.systemMessageMode});S.push(...I);let b=(v=y.strictJsonSchema)!=null?v:!0,E={model:this.modelId,logit_bias:y.logitBias,logprobs:y.logprobs===!0||typeof y.logprobs==="number"?!0:void 0,top_logprobs:typeof y.logprobs==="number"?y.logprobs:typeof y.logprobs==="boolean"?y.logprobs?0:void 0:void 0,user:y.user,parallel_tool_calls:y.parallelToolCalls,max_tokens:t,temperature:n,top_p:o,frequency_penalty:a,presence_penalty:s,response_format:(c==null?void 0:c.type)==="json"?c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,strict:b,name:(x=c.name)!=null?x:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:u,verbosity:y.textVerbosity,max_completion_tokens:y.maxCompletionTokens,store:y.store,metadata:y.metadata,prediction:y.prediction,reasoning_effort:y.reasoningEffort,service_tier:y.serviceTier,prompt_cache_key:y.promptCacheKey,prompt_cache_retention:y.promptCacheRetention,safety_identifier:y.safetyIdentifier,messages:C};if(_){if(y.reasoningEffort!=="none"||!w.supportsNonReasoningParameters){if(E.temperature!=null)E.temperature=void 0,S.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"});if(E.top_p!=null)E.top_p=void 0,S.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"});if(E.logprobs!=null)E.logprobs=void 0,S.push({type:"other",message:"logprobs is not supported for reasoning models"})}if(E.frequency_penalty!=null)E.frequency_penalty=void 0,S.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"});if(E.presence_penalty!=null)E.presence_penalty=void 0,S.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"});if(E.logit_bias!=null)E.logit_bias=void 0,S.push({type:"other",message:"logitBias is not supported for reasoning models"});if(E.top_logprobs!=null)E.top_logprobs=void 0,S.push({type:"other",message:"topLogprobs is not supported for reasoning models"});if(E.max_tokens!=null){if(E.max_completion_tokens==null)E.max_completion_tokens=E.max_tokens;E.max_tokens=void 0}}else if(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview")){if(E.temperature!=null)E.temperature=void 0,S.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})}if(y.serviceTier==="flex"&&!w.supportsFlexProcessing)S.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),E.service_tier=void 0;if(y.serviceTier==="priority"&&!w.supportsPriorityProcessing)S.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"}),E.service_tier=void 0;let{tools:B,toolChoice:R,toolWarnings:U}=wD({tools:d,toolChoice:m});return{args:{...E,tools:B,tool_choice:R},warnings:[...S,...U]}}async doGenerate(e){var t,n,o,i,a,s,l;let{args:c,warnings:u}=await this.getArgs(e),{responseHeaders:d,value:m,rawValue:p}=await Ie({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:_e(this.config.headers(),e.headers),body:c,failedResponseHandler:gr,successfulResponseHandler:xe(bD),abortSignal:e.abortSignal,fetch:this.config.fetch}),f=m.choices[0],g=[],h=f.message.content;if(h!=null&&h.length>0)g.push({type:"text",text:h});for(let y of(t=f.message.tool_calls)!=null?t:[])g.push({type:"tool-call",toolCallId:(n=y.id)!=null?n:Le(),toolName:y.function.name,input:y.function.arguments});for(let y of(o=f.message.annotations)!=null?o:[])g.push({type:"source",sourceType:"url",id:Le(),url:y.url_citation.url,title:y.url_citation.title});let v=(i=m.usage)==null?void 0:i.completion_tokens_details,x=(a=m.usage)==null?void 0:a.prompt_tokens_details,S={openai:{}};if((v==null?void 0:v.accepted_prediction_tokens)!=null)S.openai.acceptedPredictionTokens=v==null?void 0:v.accepted_prediction_tokens;if((v==null?void 0:v.rejected_prediction_tokens)!=null)S.openai.rejectedPredictionTokens=v==null?void 0:v.rejected_prediction_tokens;if(((s=f.logprobs)==null?void 0:s.content)!=null)S.openai.logprobs=f.logprobs.content;return{content:g,finishReason:{unified:T_(f.finish_reason),raw:(l=f.finish_reason)!=null?l:void 0},usage:x_(m.usage),request:{body:c},response:{...du(m),headers:d,body:p},warnings:u,providerMetadata:S}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),o={...t,stream:!0,stream_options:{include_usage:!0}},i=this.config.url({path:"/chat/completions",modelId:this.modelId}),{responseHeaders:a,value:s}=await Ie({url:i,headers:_e(this.config.headers(),e.headers),body:o,failedResponseHandler:gr,successfulResponseHandler:Dt(_D),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=await vu({stream:s,getError:(h)=>("error"in h)?h.error:void 0,isOutputChunk:TD,url:i,requestBodyValues:o,responseHeaders:a}),c=[],u={unified:"other",raw:void 0},d=void 0,m=!1,p=!1,f={openai:{}};return{stream:l.pipeThrough(new TransformStream({start(h){h.enqueue({type:"stream-start",warnings:n})},transform(h,v){var x,S,y,w,_,C,I,b,E,B,R,U,z;if(e.includeRawChunks)v.enqueue({type:"raw",rawValue:h.rawValue});if(!h.success){u={unified:"error",raw:void 0},v.enqueue({type:"error",error:h.error});return}let N=h.value;if("error"in N){u={unified:"error",raw:void 0},v.enqueue({type:"error",error:N.error});return}if(!m){let V=du(N);if(Object.values(V).some(Boolean))m=!0,v.enqueue({type:"response-metadata",...du(N)})}if(N.usage!=null){if(d=N.usage,((x=N.usage.completion_tokens_details)==null?void 0:x.accepted_prediction_tokens)!=null)f.openai.acceptedPredictionTokens=(S=N.usage.completion_tokens_details)==null?void 0:S.accepted_prediction_tokens;if(((y=N.usage.completion_tokens_details)==null?void 0:y.rejected_prediction_tokens)!=null)f.openai.rejectedPredictionTokens=(w=N.usage.completion_tokens_details)==null?void 0:w.rejected_prediction_tokens}let re=N.choices[0];if((re==null?void 0:re.finish_reason)!=null)u={unified:T_(re.finish_reason),raw:re.finish_reason};if(((_=re==null?void 0:re.logprobs)==null?void 0:_.content)!=null)f.openai.logprobs=re.logprobs.content;if((re==null?void 0:re.delta)==null)return;let Y=re.delta;if(Y.content!=null){if(!p)v.enqueue({type:"text-start",id:"0"}),p=!0;v.enqueue({type:"text-delta",id:"0",delta:Y.content})}if(Y.tool_calls!=null)for(let V of Y.tool_calls){let q=V.index;if(c[q]==null){if(V.type!=null&&V.type!=="function")throw new va({data:V,message:"Expected 'function' type."});if(V.id==null)throw new va({data:V,message:"Expected 'id' to be a string."});if(((C=V.function)==null?void 0:C.name)==null)throw new va({data:V,message:"Expected 'function.name' to be a string."});v.enqueue({type:"tool-input-start",id:V.id,toolName:V.function.name}),c[q]={id:V.id,type:"function",function:{name:V.function.name,arguments:(I=V.function.arguments)!=null?I:""},hasFinished:!1};let ee=c[q];if(((b=ee.function)==null?void 0:b.name)!=null&&((E=ee.function)==null?void 0:E.arguments)!=null){if(ee.function.arguments.length>0)v.enqueue({type:"tool-input-delta",id:ee.id,delta:ee.function.arguments})}continue}let ue=c[q];if(ue.hasFinished)continue;if(((B=V.function)==null?void 0:B.arguments)!=null)ue.function.arguments+=(U=(R=V.function)==null?void 0:R.arguments)!=null?U:"";v.enqueue({type:"tool-input-delta",id:ue.id,delta:(z=V.function.arguments)!=null?z:""})}if(Y.annotations!=null)for(let V of Y.annotations)v.enqueue({type:"source",sourceType:"url",id:Le(),url:V.url_citation.url,title:V.url_citation.title})},flush(h){var v;if(p)h.enqueue({type:"text-end",id:"0"});for(let x of c)if(!x.hasFinished)h.enqueue({type:"tool-input-end",id:x.id}),h.enqueue({type:"tool-call",toolCallId:(v=x.id)!=null?v:Le(),toolName:x.function.name,input:x.function.arguments}),x.hasFinished=!0;h.enqueue({type:"finish",finishReason:u,usage:x_(d),...f!=null?{providerMetadata:f}:{}})}})),request:{body:o},response:{headers:a}}}};function TD(e){if("error"in e)return!1;return e.choices.some((t)=>{let n=t.delta;return(n==null?void 0:n.content)!=null&&n.content.length>0||(n==null?void 0:n.tool_calls)!=null&&n.tool_calls.length>0||(n==null?void 0:n.annotations)!=null&&n.annotations.length>0})}function I_(e){var t,n,o,i;if(e==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};let a=(t=e.prompt_tokens)!=null?t:0,s=(n=e.completion_tokens)!=null?n:0;return{inputTokens:{total:(o=e.prompt_tokens)!=null?o:void 0,noCache:a,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:(i=e.completion_tokens)!=null?i:void 0,text:s,reasoning:void 0},raw:e}}function ID({prompt:e,user:t="user",assistant:n="assistant"}){let o="";if(e[0].role==="system")o+=`${e[0].content}
72
+
73
+ `,e=e.slice(1);for(let{role:i,content:a}of e)switch(i){case"system":throw new Ir({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{let s=a.map((l)=>{switch(l.type){case"text":return l.text}}).filter(Boolean).join("");o+=`${t}:
74
+ ${s}
75
+
76
+ `;break}case"assistant":{let s=a.map((l)=>{switch(l.type){case"text":return l.text;case"tool-call":throw new We({functionality:"tool-call messages"})}}).join("");o+=`${n}:
77
+ ${s}
78
+
79
+ `;break}case"tool":throw new We({functionality:"tool messages"});default:throw Error(`Unsupported role: ${i}`)}return o+=`${n}:
80
+ `,{prompt:o,stopSequences:[`
81
+ ${t}:`]}}function C_({id:e,model:t,created:n}){return{id:e!=null?e:void 0,modelId:t!=null?t:void 0,timestamp:n!=null?new Date(n*1000):void 0}}function k_(e){switch(e){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 CD=j(()=>M(r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({text:r.string(),finish_reason:r.string(),logprobs:r.object({tokens:r.array(r.string()),token_logprobs:r.array(r.number()),top_logprobs:r.array(r.record(r.string(),r.number())).nullish()}).nullish()})),usage:r.object({prompt_tokens:r.number(),completion_tokens:r.number(),total_tokens:r.number()}).nullish()}))),kD=j(()=>M(r.union([r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({text:r.string(),finish_reason:r.string().nullish(),index:r.number(),logprobs:r.object({tokens:r.array(r.string()),token_logprobs:r.array(r.number()),top_logprobs:r.array(r.record(r.string(),r.number())).nullish()}).nullish()})),usage:r.object({prompt_tokens:r.number(),completion_tokens:r.number(),total_tokens:r.number()}).nullish()}),yu]))),R_=j(()=>M(r.object({echo:r.boolean().optional(),logitBias:r.record(r.string(),r.number()).optional(),suffix:r.string().optional(),user:r.string().optional(),logprobs:r.union([r.boolean(),r.number()]).optional()}))),RD=class{constructor(e,t){this.specificationVersion="v3",this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:o,topK:i,frequencyPenalty:a,presencePenalty:s,stopSequences:l,responseFormat:c,tools:u,toolChoice:d,seed:m,providerOptions:p}){let f=[],g={...await Ue({provider:"openai",providerOptions:p,schema:R_}),...await Ue({provider:this.providerOptionsName,providerOptions:p,schema:R_})};if(i!=null)f.push({type:"unsupported",feature:"topK"});if(u==null?void 0:u.length)f.push({type:"unsupported",feature:"tools"});if(d!=null)f.push({type:"unsupported",feature:"toolChoice"});if(c!=null&&c.type!=="text")f.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});let{prompt:h,stopSequences:v}=ID({prompt:e}),x=[...v!=null?v:[],...l!=null?l:[]];return{args:{model:this.modelId,echo:g.echo,logit_bias:g.logitBias,logprobs:(g==null?void 0:g.logprobs)===!0?0:(g==null?void 0:g.logprobs)===!1?void 0:g==null?void 0:g.logprobs,suffix:g.suffix,user:g.user,max_tokens:t,temperature:n,top_p:o,frequency_penalty:a,presence_penalty:s,seed:m,prompt:h,stop:x.length>0?x:void 0},warnings:f}}async doGenerate(e){var t;let{args:n,warnings:o}=await this.getArgs(e),{responseHeaders:i,value:a,rawValue:s}=await Ie({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:_e(this.config.headers(),e.headers),body:n,failedResponseHandler:gr,successfulResponseHandler:xe(CD),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=a.choices[0],c={openai:{}};if(l.logprobs!=null)c.openai.logprobs=l.logprobs;return{content:[{type:"text",text:l.text}],usage:I_(a.usage),finishReason:{unified:k_(l.finish_reason),raw:(t=l.finish_reason)!=null?t:void 0},request:{body:n},response:{...C_(a),headers:i,body:s},providerMetadata:c,warnings:o}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),o={...t,stream:!0,stream_options:{include_usage:!0}},i=this.config.url({path:"/completions",modelId:this.modelId}),{responseHeaders:a,value:s}=await Ie({url:i,headers:_e(this.config.headers(),e.headers),body:o,failedResponseHandler:gr,successfulResponseHandler:Dt(kD),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=await vu({stream:s,getError:(f)=>("error"in f)?f.error:void 0,isOutputChunk:ED,url:i,requestBodyValues:o,responseHeaders:a}),c={unified:"other",raw:void 0},u={openai:{}},d=void 0,m=!0;return{stream:l.pipeThrough(new TransformStream({start(f){f.enqueue({type:"stream-start",warnings:n})},transform(f,g){if(e.includeRawChunks)g.enqueue({type:"raw",rawValue:f.rawValue});if(!f.success){c={unified:"error",raw:void 0},g.enqueue({type:"error",error:f.error});return}let h=f.value;if("error"in h){c={unified:"error",raw:void 0},g.enqueue({type:"error",error:h.error});return}if(m)m=!1,g.enqueue({type:"response-metadata",...C_(h)}),g.enqueue({type:"text-start",id:"0"});if(h.usage!=null)d=h.usage;let v=h.choices[0];if((v==null?void 0:v.finish_reason)!=null)c={unified:k_(v.finish_reason),raw:v.finish_reason};if((v==null?void 0:v.logprobs)!=null)u.openai.logprobs=v.logprobs;if((v==null?void 0:v.text)!=null&&v.text.length>0)g.enqueue({type:"text-delta",id:"0",delta:v.text})},flush(f){if(!m)f.enqueue({type:"text-end",id:"0"});f.enqueue({type:"finish",finishReason:c,providerMetadata:u,usage:I_(d)})}})),request:{body:o},response:{headers:a}}}};function ED(e){return!("error"in e)&&e.choices.some((t)=>t.text.length>0)}var AD=j(()=>M(r.object({dimensions:r.number().optional(),user:r.string().optional()}))),PD=j(()=>M(r.object({data:r.array(r.object({embedding:r.array(r.number())})),usage:r.object({prompt_tokens:r.number()}).nullish()}))),MD=class{constructor(e,t){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:o}){var i;if(e.length>this.maxEmbeddingsPerCall)throw new ba({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=(i=await Ue({provider:"openai",providerOptions:o,schema:AD}))!=null?i:{},{responseHeaders:s,value:l,rawValue:c}=await Ie({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:_e(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:a.dimensions,user:a.user},failedResponseHandler:gr,successfulResponseHandler:xe(PD),abortSignal:n,fetch:this.config.fetch});return{warnings:[],embeddings:l.data.map((u)=>u.embedding),usage:l.usage?{tokens:l.usage.prompt_tokens}:void 0,response:{headers:s,body:c}}}},E_=j(()=>M(r.object({created:r.number().nullish(),data:r.array(r.object({b64_json:r.string(),revised_prompt:r.string().nullish()})),background:r.string().nullish(),output_format:r.string().nullish(),size:r.string().nullish(),quality:r.string().nullish(),usage:r.object({input_tokens:r.number().nullish(),output_tokens:r.number().nullish(),total_tokens:r.number().nullish(),input_tokens_details:r.object({image_tokens:r.number().nullish(),text_tokens:r.number().nullish()}).nullish()}).nullish()}))),jD={"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},OD=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1","gpt-image-2"];function ND(e){return OD.some((t)=>e.startsWith(t))}var bu=r.object({quality:r.enum(["standard","hd","low","medium","high","auto"]).optional(),background:r.enum(["transparent","opaque","auto"]).optional(),outputFormat:r.enum(["png","jpeg","webp"]).optional(),outputCompression:r.number().int().min(0).max(100).optional(),user:r.string().optional()}),J3=j(()=>M(bu)),DD=j(()=>M(bu.extend({style:r.enum(["vivid","natural"]).optional(),moderation:r.enum(["auto","low"]).optional()}))),zD=j(()=>M(bu.extend({inputFidelity:r.enum(["high","low"]).optional()}))),UD=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get maxImagesPerCall(){var e;return(e=jD[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,files:t,mask:n,n:o,size:i,aspectRatio:a,seed:s,providerOptions:l,headers:c,abortSignal:u}){var d,m,p,f,g,h,v,x,S,y,w;let _=[];if(a!=null)_.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."});if(s!=null)_.push({type:"unsupported",feature:"seed"});let C=(p=(m=(d=this.config._internal)==null?void 0:d.currentDate)==null?void 0:m.call(d))!=null?p:new Date;if(t!=null){let B=(f=await Ue({provider:"openai",providerOptions:l,schema:zD}))!=null?f:{},{value:R,responseHeaders:U}=await Oa({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:_e(this.config.headers(),c),formData:Hm({model:this.modelId,prompt:e,image:await Promise.all(t.map((z)=>z.type==="file"?new Blob([z.data instanceof Uint8Array?new Blob([z.data],{type:z.mediaType}):new Blob([wt(z.data)],{type:z.mediaType})],{type:z.mediaType}):Tl(z.url))),mask:n!=null?await $D(n):void 0,n:o,size:i,quality:B.quality,background:B.background,output_format:B.outputFormat,output_compression:B.outputCompression,input_fidelity:B.inputFidelity,user:B.user}),failedResponseHandler:gr,successfulResponseHandler:xe(E_),abortSignal:u,fetch:this.config.fetch});return{images:R.data.map((z)=>z.b64_json),warnings:_,usage:R.usage!=null?{inputTokens:(g=R.usage.input_tokens)!=null?g:void 0,outputTokens:(h=R.usage.output_tokens)!=null?h:void 0,totalTokens:(v=R.usage.total_tokens)!=null?v:void 0}:void 0,response:{timestamp:C,modelId:this.modelId,headers:U},providerMetadata:{openai:{images:R.data.map((z,N)=>{var re,Y,V,q,ue,ee;return{...z.revised_prompt?{revisedPrompt:z.revised_prompt}:{},created:(re=R.created)!=null?re:void 0,size:(Y=R.size)!=null?Y:void 0,quality:(V=R.quality)!=null?V:void 0,background:(q=R.background)!=null?q:void 0,outputFormat:(ue=R.output_format)!=null?ue:void 0,...A_((ee=R.usage)==null?void 0:ee.input_tokens_details,N,R.data.length)}})}}}}let I=(x=await Ue({provider:"openai",providerOptions:l,schema:DD}))!=null?x:{},{value:b,responseHeaders:E}=await Ie({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:_e(this.config.headers(),c),body:{model:this.modelId,prompt:e,n:o,size:i,quality:I.quality,style:I.style,background:I.background,moderation:I.moderation,output_format:I.outputFormat,output_compression:I.outputCompression,user:I.user,...!ND(this.modelId)?{response_format:"b64_json"}:{}},failedResponseHandler:gr,successfulResponseHandler:xe(E_),abortSignal:u,fetch:this.config.fetch});return{images:b.data.map((B)=>B.b64_json),warnings:_,usage:b.usage!=null?{inputTokens:(S=b.usage.input_tokens)!=null?S:void 0,outputTokens:(y=b.usage.output_tokens)!=null?y:void 0,totalTokens:(w=b.usage.total_tokens)!=null?w:void 0}:void 0,response:{timestamp:C,modelId:this.modelId,headers:E},providerMetadata:{openai:{images:b.data.map((B,R)=>{var U,z,N,re,Y,V;return{...B.revised_prompt?{revisedPrompt:B.revised_prompt}:{},created:(U=b.created)!=null?U:void 0,size:(z=b.size)!=null?z:void 0,quality:(N=b.quality)!=null?N:void 0,background:(re=b.background)!=null?re:void 0,outputFormat:(Y=b.output_format)!=null?Y:void 0,...A_((V=b.usage)==null?void 0:V.input_tokens_details,R,b.data.length)}})}}}}};function A_(e,t,n){if(e==null)return{};let o={};if(e.image_tokens!=null){let i=Math.floor(e.image_tokens/n),a=e.image_tokens-i*(n-1);o.imageTokens=t===n-1?a:i}if(e.text_tokens!=null){let i=Math.floor(e.text_tokens/n),a=e.text_tokens-i*(n-1);o.textTokens=t===n-1?a:i}return o}async function $D(e){if(!e)return;if(e.type==="url")return Tl(e.url);let t=e.data instanceof Uint8Array?e.data:wt(e.data);return new Blob([t],{type:e.mediaType})}var q_=j(()=>M(r.object({callId:r.string(),operation:r.discriminatedUnion("type",[r.object({type:r.literal("create_file"),path:r.string(),diff:r.string()}),r.object({type:r.literal("delete_file"),path:r.string()}),r.object({type:r.literal("update_file"),path:r.string(),diff:r.string()})])}))),F_=j(()=>M(r.object({status:r.enum(["completed","failed"]),output:r.string().optional()}))),V3=j(()=>M(r.object({}))),LD=Te({id:"openai.apply_patch",inputSchema:q_,outputSchema:F_}),qD=LD,FD=j(()=>M(r.object({code:r.string().nullish(),containerId:r.string()}))),BD=j(()=>M(r.object({outputs:r.array(r.discriminatedUnion("type",[r.object({type:r.literal("logs"),logs:r.string()}),r.object({type:r.literal("image"),url:r.string()})])).nullish()}))),GD=j(()=>M(r.object({container:r.union([r.string(),r.object({fileIds:r.array(r.string()).optional()})]).optional()}))),JD=Te({id:"openai.code_interpreter",inputSchema:FD,outputSchema:BD}),HD=(e={})=>JD(e),WD=j(()=>M(r.object({name:r.string(),description:r.string().optional(),format:r.union([r.object({type:r.literal("grammar"),syntax:r.enum(["regex","lark"]),definition:r.string()}),r.object({type:r.literal("text")})]).optional()}))),VD=j(()=>M(r.string())),ZD=Ge({id:"openai.custom",inputSchema:VD}),KD=(e)=>ZD(e),B_=r.object({key:r.string(),type:r.enum(["eq","ne","gt","gte","lt","lte","in","nin"]),value:r.union([r.string(),r.number(),r.boolean(),r.array(r.string())])}),G_=r.object({type:r.enum(["and","or"]),filters:r.array(r.union([B_,r.lazy(()=>G_)]))}),YD=j(()=>M(r.object({vectorStoreIds:r.array(r.string()),maxNumResults:r.number().optional(),ranking:r.object({ranker:r.string().optional(),scoreThreshold:r.number().optional()}).optional(),filters:r.union([B_,G_]).optional()}))),QD=j(()=>M(r.object({queries:r.array(r.string()),results:r.array(r.object({attributes:r.record(r.string(),r.unknown()),fileId:r.string(),filename:r.string(),score:r.number(),text:r.string()})).nullable()}))),XD=Te({id:"openai.file_search",inputSchema:r.object({}),outputSchema:QD}),e1=j(()=>M(r.object({background:r.enum(["auto","opaque","transparent"]).optional(),inputFidelity:r.enum(["low","high"]).optional(),inputImageMask:r.object({fileId:r.string().optional(),imageUrl:r.string().optional()}).optional(),model:r.string().optional(),moderation:r.enum(["auto"]).optional(),outputCompression:r.number().int().min(0).max(100).optional(),outputFormat:r.enum(["png","jpeg","webp"]).optional(),partialImages:r.number().int().min(0).max(3).optional(),quality:r.enum(["auto","low","medium","high"]).optional(),size:r.enum(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),t1=j(()=>M(r.object({}))),r1=j(()=>M(r.object({result:r.string()}))),n1=Te({id:"openai.image_generation",inputSchema:t1,outputSchema:r1}),o1=(e={})=>n1(e),J_=j(()=>M(r.object({action:r.object({type:r.literal("exec"),command:r.array(r.string()),timeoutMs:r.number().optional(),user:r.string().optional(),workingDirectory:r.string().optional(),env:r.record(r.string(),r.string()).optional()})}))),H_=j(()=>M(r.object({output:r.string()}))),i1=Te({id:"openai.local_shell",inputSchema:J_,outputSchema:H_}),W_=j(()=>M(r.object({action:r.object({commands:r.array(r.string()),timeoutMs:r.number().optional(),maxOutputLength:r.number().optional()})}))),mu=j(()=>M(r.object({output:r.array(r.object({stdout:r.string(),stderr:r.string(),outcome:r.discriminatedUnion("type",[r.object({type:r.literal("timeout")}),r.object({type:r.literal("exit"),exitCode:r.number()})])}))}))),a1=r.array(r.discriminatedUnion("type",[r.object({type:r.literal("skillReference"),skillId:r.string(),version:r.string().optional()}),r.object({type:r.literal("inline"),name:r.string(),description:r.string(),source:r.object({type:r.literal("base64"),mediaType:r.literal("application/zip"),data:r.string()})})])).optional(),s1=j(()=>M(r.object({environment:r.union([r.object({type:r.literal("containerAuto"),fileIds:r.array(r.string()).optional(),memoryLimit:r.enum(["1g","4g","16g","64g"]).optional(),networkPolicy:r.discriminatedUnion("type",[r.object({type:r.literal("disabled")}),r.object({type:r.literal("allowlist"),allowedDomains:r.array(r.string()),domainSecrets:r.array(r.object({domain:r.string(),name:r.string(),value:r.string()})).optional()})]).optional(),skills:a1}),r.object({type:r.literal("containerReference"),containerId:r.string()}),r.object({type:r.literal("local").optional(),skills:r.array(r.object({name:r.string(),description:r.string(),path:r.string()})).optional()})]).optional()}))),l1=Te({id:"openai.shell",inputSchema:W_,outputSchema:mu}),c1=j(()=>M(r.object({execution:r.enum(["server","client"]).optional(),description:r.string().optional(),parameters:r.record(r.string(),r.unknown()).optional()}))),gu=j(()=>M(r.object({arguments:r.unknown().optional(),call_id:r.string().nullish()}))),fu=j(()=>M(r.object({tools:r.array(r.record(r.string(),r.unknown()))}))),u1=Te({id:"openai.tool_search",inputSchema:gu,outputSchema:fu}),d1=(e={})=>u1(e),p1=j(()=>M(r.object({externalWebAccess:r.boolean().optional(),filters:r.object({allowedDomains:r.array(r.string()).optional()}).optional(),searchContextSize:r.enum(["low","medium","high"]).optional(),userLocation:r.object({type:r.literal("approximate"),country:r.string().optional(),city:r.string().optional(),region:r.string().optional(),timezone:r.string().optional()}).optional()}))),m1=j(()=>M(r.object({}))),g1=j(()=>M(r.object({action:r.discriminatedUnion("type",[r.object({type:r.literal("search"),query:r.string().optional(),queries:r.array(r.string()).optional()}),r.object({type:r.literal("openPage"),url:r.string().nullish()}),r.object({type:r.literal("findInPage"),url:r.string().nullish(),pattern:r.string().nullish()})]).optional(),sources:r.array(r.discriminatedUnion("type",[r.object({type:r.literal("url"),url:r.string()}),r.object({type:r.literal("api"),name:r.string()})])).optional()}))),f1=Te({id:"openai.web_search",inputSchema:m1,outputSchema:g1}),h1=(e={})=>f1(e),y1=j(()=>M(r.object({searchContextSize:r.enum(["low","medium","high"]).optional(),userLocation:r.object({type:r.literal("approximate"),country:r.string().optional(),city:r.string().optional(),region:r.string().optional(),timezone:r.string().optional()}).optional()}))),v1=j(()=>M(r.object({}))),b1=j(()=>M(r.object({action:r.discriminatedUnion("type",[r.object({type:r.literal("search"),query:r.string().optional()}),r.object({type:r.literal("openPage"),url:r.string().nullish()}),r.object({type:r.literal("findInPage"),url:r.string().nullish(),pattern:r.string().nullish()})]).optional()}))),_1=Te({id:"openai.web_search_preview",inputSchema:v1,outputSchema:b1}),hu=r.lazy(()=>r.union([r.string(),r.number(),r.boolean(),r.null(),r.array(hu),r.record(r.string(),hu)])),S1=j(()=>M(r.object({serverLabel:r.string(),allowedTools:r.union([r.array(r.string()),r.object({readOnly:r.boolean().optional(),toolNames:r.array(r.string()).optional()})]).optional(),authorization:r.string().optional(),connectorId:r.string().optional(),headers:r.record(r.string(),r.string()).optional(),requireApproval:r.union([r.enum(["always","never"]),r.object({never:r.object({toolNames:r.array(r.string()).optional()}).optional()})]).optional(),serverDescription:r.string().optional(),serverUrl:r.string().optional()}).refine((e)=>e.serverUrl!=null||e.connectorId!=null,"One of serverUrl or connectorId must be provided."))),w1=j(()=>M(r.object({}))),x1=j(()=>M(r.object({type:r.literal("call"),serverLabel:r.string(),name:r.string(),arguments:r.string(),output:r.string().nullish(),error:r.union([r.string(),hu]).optional()}))),T1=Te({id:"openai.mcp",inputSchema:w1,outputSchema:x1}),I1=(e)=>T1(e),C1={applyPatch:qD,customTool:KD,codeInterpreter:HD,fileSearch:XD,imageGeneration:o1,localShell:i1,shell:l1,webSearchPreview:_1,webSearch:h1,mcp:I1,toolSearch:d1};function P_(e){var t,n,o,i;if(e==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};let{input_tokens:a,output_tokens:s}=e,l=(n=(t=e.input_tokens_details)==null?void 0:t.cached_tokens)!=null?n:0,c=(i=(o=e.output_tokens_details)==null?void 0:o.reasoning_tokens)!=null?i:0;return{inputTokens:{total:a,noCache:a-l,cacheRead:l,cacheWrite:void 0},outputTokens:{total:s,text:s-c,reasoning:c},raw:e}}function k1(e){return JSON.stringify(e===void 0?{}:e)}function M_(e,t){if(!t)return!1;return t.some((n)=>e.startsWith(n))}async function R1({prompt:e,toolNameMapping:t,systemMessageMode:n,providerOptionsName:o,fileIdPrefixes:i,passThroughUnsupportedFiles:a=!1,store:s,hasConversation:l=!1,hasPreviousResponseId:c=!1,hasLocalShellTool:u=!1,hasShellTool:d=!1,hasApplyPatchTool:m=!1,customProviderToolNames:p}){var f,g,h,v,x,S,y,w,_,C,I,b,E,B,R,U,z,N,re,Y,V,q,ue;let ee=[],k=[],X=new Set;for(let{role:H,content:J}of e)switch(H){case"system":{switch(n){case"system":{ee.push({role:"system",content:J});break}case"developer":{ee.push({role:"developer",content:J});break}case"remove":{k.push({type:"other",message:"system messages are removed for this model"});break}default:throw Error(`Unsupported system message mode: ${n}`)}break}case"user":{ee.push({role:"user",content:J.map((K,D)=>{var F,G,Z;switch(K.type){case"text":return{type:"input_text",text:K.text};case"file":{let A=K.mediaType==="image/*"?"image/jpeg":K.mediaType;if(A.startsWith("image/"))return{type:"input_image",...K.data instanceof URL?{image_url:K.data.toString()}:typeof K.data==="string"&&M_(K.data,i)?{file_id:K.data}:{image_url:`data:${A};base64,${bt(K.data)}`},detail:(G=(F=K.providerOptions)==null?void 0:F[o])==null?void 0:G.imageDetail};if(K.data instanceof URL)return{type:"input_file",file_url:K.data.toString()};if(A!=="application/pdf"&&!a)throw new We({functionality:`file part media type ${A}`});return{type:"input_file",...typeof K.data==="string"&&M_(K.data,i)?{file_id:K.data}:{filename:(Z=K.filename)!=null?Z:A==="application/pdf"?`part-${D}.pdf`:`part-${D}`,file_data:`data:${A};base64,${bt(K.data)}`}}}}})});break}case"assistant":{let K={};for(let D of J)switch(D.type){case"text":{let F=(f=D.providerOptions)==null?void 0:f[o],G=F==null?void 0:F.itemId,Z=F==null?void 0:F.phase;if(l&&G!=null)break;if(s&&G!=null){ee.push({type:"item_reference",id:G});break}ee.push({role:"assistant",content:[{type:"output_text",text:D.text}],id:G,...Z!=null&&{phase:Z}});break}case"tool-call":{let F=(S=(h=(g=D.providerOptions)==null?void 0:g[o])==null?void 0:h.itemId)!=null?S:(x=(v=D.providerMetadata)==null?void 0:v[o])==null?void 0:x.itemId,G=(I=(w=(y=D.providerOptions)==null?void 0:y[o])==null?void 0:w.namespace)!=null?I:(C=(_=D.providerMetadata)==null?void 0:_[o])==null?void 0:C.namespace;if(l&&F!=null)break;let Z=t.toProviderToolName(D.toolName);if(Z==="tool_search"){if(s&&F!=null){ee.push({type:"item_reference",id:F});break}let O=typeof D.input==="string"?await Cl({text:D.input,schema:gu}):await Ee({value:D.input,schema:gu}),W=O.call_id!=null?"client":"server";ee.push({type:"tool_search_call",id:F!=null?F:D.toolCallId,execution:W,call_id:(b=O.call_id)!=null?b:null,status:"completed",arguments:O.arguments});break}if(D.providerExecuted){if(s&&F!=null)ee.push({type:"item_reference",id:F});break}if(c&&s&&F!=null)break;let A=u&&Z==="local_shell"||d&&Z==="shell"||m&&Z==="apply_patch"||((E=p==null?void 0:p.has(Z))!=null?E:!1);if(s&&F!=null&&A){ee.push({type:"item_reference",id:F});break}if(u&&Z==="local_shell"){let O=await Ee({value:D.input,schema:J_});ee.push({type:"local_shell_call",call_id:D.toolCallId,id:F,action:{type:"exec",command:O.action.command,timeout_ms:O.action.timeoutMs,user:O.action.user,working_directory:O.action.workingDirectory,env:O.action.env}});break}if(d&&Z==="shell"){let O=await Ee({value:D.input,schema:W_});ee.push({type:"shell_call",call_id:D.toolCallId,id:F,status:"completed",action:{commands:O.action.commands,timeout_ms:O.action.timeoutMs,max_output_length:O.action.maxOutputLength}});break}if(m&&Z==="apply_patch"){let O=await Ee({value:D.input,schema:q_});ee.push({type:"apply_patch_call",call_id:O.callId,id:F,status:"completed",operation:O.operation});break}if(p==null?void 0:p.has(Z)){ee.push({type:"custom_tool_call",call_id:D.toolCallId,name:Z,input:typeof D.input==="string"?D.input:JSON.stringify(D.input),id:F});break}ee.push({type:"function_call",call_id:D.toolCallId,name:Z,arguments:k1(D.input),...G!=null&&{namespace:G}});break}case"tool-result":{if(D.output.type==="execution-denied"||D.output.type==="json"&&typeof D.output.value==="object"&&D.output.value!=null&&"type"in D.output.value&&D.output.value.type==="execution-denied")break;if(l)break;let F=t.toProviderToolName(D.toolName);if(F==="tool_search"){let G=(U=(R=(B=D.providerOptions)==null?void 0:B[o])==null?void 0:R.itemId)!=null?U:D.toolCallId;if(s)ee.push({type:"item_reference",id:G});else if(D.output.type==="json"){let Z=await Ee({value:D.output.value,schema:fu});ee.push({type:"tool_search_output",id:G,execution:"server",call_id:null,status:"completed",tools:Z.tools})}break}if(d&&F==="shell"){if(D.output.type==="json"){let G=await Ee({value:D.output.value,schema:mu});ee.push({type:"shell_call_output",call_id:D.toolCallId,output:G.output.map((Z)=>({stdout:Z.stdout,stderr:Z.stderr,outcome:Z.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:Z.outcome.exitCode}}))})}break}if(s){let G=(re=(N=(z=D.providerOptions)==null?void 0:z[o])==null?void 0:N.itemId)!=null?re:D.toolCallId;ee.push({type:"item_reference",id:G})}else k.push({type:"other",message:`Results for OpenAI tool ${D.toolName} are not sent to the API when store is false`});break}case"reasoning":{let F=await Ue({provider:o,providerOptions:D.providerOptions,schema:E1}),G=F==null?void 0:F.itemId;if((l||c)&&G!=null)break;if(G!=null){let Z=K[G];if(s){if(Z===void 0)ee.push({type:"item_reference",id:G}),K[G]={type:"reasoning",id:G,summary:[]}}else{let A=[];if(D.text.length>0)A.push({type:"summary_text",text:D.text});else if(Z!==void 0)k.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(D)}.`});if(Z===void 0)K[G]={type:"reasoning",id:G,encrypted_content:F==null?void 0:F.reasoningEncryptedContent,summary:A},ee.push(K[G]);else if(Z.summary.push(...A),(F==null?void 0:F.reasoningEncryptedContent)!=null)Z.encrypted_content=F.reasoningEncryptedContent}}else{let Z=F==null?void 0:F.reasoningEncryptedContent;if(Z!=null){let A=[];if(D.text.length>0)A.push({type:"summary_text",text:D.text});ee.push({type:"reasoning",encrypted_content:Z,summary:A})}else k.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(D)}.`})}break}}break}case"tool":{for(let K of J){if(K.type==="tool-approval-response"){let Z=K;if(X.has(Z.approvalId))continue;if(X.add(Z.approvalId),s)ee.push({type:"item_reference",id:Z.approvalId});ee.push({type:"mcp_approval_response",approval_request_id:Z.approvalId,approve:Z.approved});continue}let D=K.output;if(D.type==="execution-denied"){if((V=(Y=D.providerOptions)==null?void 0:Y.openai)==null?void 0:V.approvalId)continue}let F=t.toProviderToolName(K.toolName);if(F==="tool_search"&&D.type==="json"){let Z=await Ee({value:D.value,schema:fu});ee.push({type:"tool_search_output",execution:"client",call_id:K.toolCallId,status:"completed",tools:Z.tools});continue}if(u&&F==="local_shell"&&D.type==="json"){let Z=await Ee({value:D.value,schema:H_});ee.push({type:"local_shell_call_output",call_id:K.toolCallId,output:Z.output});continue}if(d&&F==="shell"&&D.type==="json"){let Z=await Ee({value:D.value,schema:mu});ee.push({type:"shell_call_output",call_id:K.toolCallId,output:Z.output.map((A)=>({stdout:A.stdout,stderr:A.stderr,outcome:A.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:A.outcome.exitCode}}))});continue}if(m&&K.toolName==="apply_patch"&&D.type==="json"){let Z=await Ee({value:D.value,schema:F_});ee.push({type:"apply_patch_call_output",call_id:K.toolCallId,status:Z.status,output:Z.output});continue}if(p==null?void 0:p.has(F)){let Z;switch(D.type){case"text":case"error-text":Z=D.value;break;case"execution-denied":Z=(q=D.reason)!=null?q:"Tool call execution denied.";break;case"json":case"error-json":Z=JSON.stringify(D.value);break;case"content":Z=D.value.map((A)=>{var O,W,P,L,me;switch(A.type){case"text":return{type:"input_text",text:A.text};case"image-data":return{type:"input_image",image_url:`data:${A.mediaType};base64,${A.data}`,detail:(W=(O=A.providerOptions)==null?void 0:O[o])==null?void 0:W.imageDetail};case"image-url":return{type:"input_image",image_url:A.url,detail:(L=(P=A.providerOptions)==null?void 0:P[o])==null?void 0:L.imageDetail};case"file-data":return{type:"input_file",filename:(me=A.filename)!=null?me:"data",file_data:`data:${A.mediaType};base64,${A.data}`};case"file-url":return{type:"input_file",file_url:A.url};default:k.push({type:"other",message:`unsupported custom tool content part type: ${A.type}`});return}}).filter(yi);break;default:Z=""}ee.push({type:"custom_tool_call_output",call_id:K.toolCallId,output:Z});continue}let G;switch(D.type){case"text":case"error-text":G=D.value;break;case"execution-denied":G=(ue=D.reason)!=null?ue:"Tool call execution denied.";break;case"json":case"error-json":G=JSON.stringify(D.value);break;case"content":G=D.value.map((Z)=>{var A,O,W,P,L;switch(Z.type){case"text":return{type:"input_text",text:Z.text};case"image-data":return{type:"input_image",image_url:`data:${Z.mediaType};base64,${Z.data}`,detail:(O=(A=Z.providerOptions)==null?void 0:A[o])==null?void 0:O.imageDetail};case"image-url":return{type:"input_image",image_url:Z.url,detail:(P=(W=Z.providerOptions)==null?void 0:W[o])==null?void 0:P.imageDetail};case"file-data":return{type:"input_file",filename:(L=Z.filename)!=null?L:"data",file_data:`data:${Z.mediaType};base64,${Z.data}`};case"file-url":return{type:"input_file",file_url:Z.url};default:{k.push({type:"other",message:`unsupported tool content part type: ${Z.type}`});return}}}).filter(yi);break}ee.push({type:"function_call_output",call_id:K.toolCallId,output:G})}break}default:throw Error(`Unsupported role: ${H}`)}if(!s&&ee.some((H)=>("type"in H)&&H.type==="reasoning"&&H.encrypted_content==null))k.push({type:"other",message:"Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts."}),ee=ee.filter((H)=>!("type"in H)||H.type!=="reasoning"||H.encrypted_content!=null);return{input:ee,warnings:k}}var E1=r.object({itemId:r.string().nullish(),reasoningEncryptedContent:r.string().nullish()});function pu({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return t?"tool-calls":"other"}}var Ui=r.lazy(()=>r.union([r.string(),r.number(),r.boolean(),r.null(),r.array(Ui),r.record(r.string(),Ui.optional())])),A1=r.object({type:r.literal("error"),sequence_number:r.number(),error:r.object({type:r.string(),code:r.string(),message:r.string(),param:r.string().nullish()})}),P1=r.object({type:r.literal("error"),sequence_number:r.number(),code:r.string().nullish(),message:r.string(),param:r.string().nullish()}),M1=j(()=>M(r.union([r.object({type:r.literal("response.output_text.delta"),item_id:r.string(),delta:r.string(),logprobs:r.array(r.object({token:r.string(),logprob:r.number(),top_logprobs:r.array(r.object({token:r.string(),logprob:r.number()}))})).nullish()}),r.object({type:r.enum(["response.completed","response.incomplete"]),response:r.object({incomplete_details:r.object({reason:r.string()}).nullish(),usage:r.object({input_tokens:r.number(),input_tokens_details:r.object({cached_tokens:r.number().nullish(),orchestration_input_tokens:r.number().nullish(),orchestration_input_cached_tokens:r.number().nullish()}).nullish(),output_tokens:r.number(),output_tokens_details:r.object({reasoning_tokens:r.number().nullish(),orchestration_output_tokens:r.number().nullish()}).nullish()}),service_tier:r.string().nullish()})}),r.object({type:r.literal("response.failed"),sequence_number:r.number(),response:r.object({error:r.object({code:r.string().nullish(),message:r.string()}).nullish(),incomplete_details:r.object({reason:r.string()}).nullish(),usage:r.object({input_tokens:r.number(),input_tokens_details:r.object({cached_tokens:r.number().nullish(),orchestration_input_tokens:r.number().nullish(),orchestration_input_cached_tokens:r.number().nullish()}).nullish(),output_tokens:r.number(),output_tokens_details:r.object({reasoning_tokens:r.number().nullish(),orchestration_output_tokens:r.number().nullish()}).nullish()}).nullish(),service_tier:r.string().nullish()})}),r.object({type:r.literal("response.created"),response:r.object({id:r.string(),created_at:r.number(),model:r.string(),service_tier:r.string().nullish()})}),r.object({type:r.literal("response.output_item.added"),output_index:r.number(),item:r.discriminatedUnion("type",[r.object({type:r.literal("message"),id:r.string(),phase:r.enum(["commentary","final_answer"]).nullish()}),r.object({type:r.literal("reasoning"),id:r.string(),encrypted_content:r.string().nullish()}),r.object({type:r.literal("function_call"),id:r.string(),call_id:r.string(),name:r.string(),arguments:r.string(),namespace:r.string().nullish()}),r.object({type:r.literal("web_search_call"),id:r.string(),status:r.string()}),r.object({type:r.literal("computer_call"),id:r.string(),status:r.string()}),r.object({type:r.literal("file_search_call"),id:r.string()}),r.object({type:r.literal("image_generation_call"),id:r.string()}),r.object({type:r.literal("code_interpreter_call"),id:r.string(),container_id:r.string(),code:r.string().nullable(),outputs:r.array(r.discriminatedUnion("type",[r.object({type:r.literal("logs"),logs:r.string()}),r.object({type:r.literal("image"),url:r.string()})])).nullable(),status:r.string()}),r.object({type:r.literal("mcp_call"),id:r.string(),status:r.string(),approval_request_id:r.string().nullish()}),r.object({type:r.literal("mcp_list_tools"),id:r.string()}),r.object({type:r.literal("mcp_approval_request"),id:r.string()}),r.object({type:r.literal("apply_patch_call"),id:r.string(),call_id:r.string(),status:r.enum(["in_progress","completed"]),operation:r.discriminatedUnion("type",[r.object({type:r.literal("create_file"),path:r.string(),diff:r.string()}),r.object({type:r.literal("delete_file"),path:r.string()}),r.object({type:r.literal("update_file"),path:r.string(),diff:r.string()})])}),r.object({type:r.literal("custom_tool_call"),id:r.string(),call_id:r.string(),name:r.string(),input:r.string()}),r.object({type:r.literal("shell_call"),id:r.string(),call_id:r.string(),status:r.enum(["in_progress","completed","incomplete"]),action:r.object({commands:r.array(r.string())})}),r.object({type:r.literal("shell_call_output"),id:r.string(),call_id:r.string(),status:r.enum(["in_progress","completed","incomplete"]),output:r.array(r.object({stdout:r.string(),stderr:r.string(),outcome:r.discriminatedUnion("type",[r.object({type:r.literal("timeout")}),r.object({type:r.literal("exit"),exit_code:r.number()})])}))}),r.object({type:r.literal("tool_search_call"),id:r.string(),execution:r.enum(["server","client"]),call_id:r.string().nullable(),status:r.enum(["in_progress","completed","incomplete"]),arguments:r.unknown()}),r.object({type:r.literal("tool_search_output"),id:r.string(),execution:r.enum(["server","client"]),call_id:r.string().nullable(),status:r.enum(["in_progress","completed","incomplete"]),tools:r.array(r.record(r.string(),Ui.optional()))})])}),r.object({type:r.literal("response.output_item.done"),output_index:r.number(),item:r.discriminatedUnion("type",[r.object({type:r.literal("message"),id:r.string(),phase:r.enum(["commentary","final_answer"]).nullish()}),r.object({type:r.literal("reasoning"),id:r.string(),encrypted_content:r.string().nullish()}),r.object({type:r.literal("function_call"),id:r.string(),call_id:r.string(),name:r.string(),arguments:r.string(),status:r.literal("completed"),namespace:r.string().nullish()}),r.object({type:r.literal("custom_tool_call"),id:r.string(),call_id:r.string(),name:r.string(),input:r.string(),status:r.literal("completed")}),r.object({type:r.literal("code_interpreter_call"),id:r.string(),code:r.string().nullable(),container_id:r.string(),outputs:r.array(r.discriminatedUnion("type",[r.object({type:r.literal("logs"),logs:r.string()}),r.object({type:r.literal("image"),url:r.string()})])).nullable()}),r.object({type:r.literal("image_generation_call"),id:r.string(),result:r.string()}),r.object({type:r.literal("web_search_call"),id:r.string(),status:r.string(),action:r.discriminatedUnion("type",[r.object({type:r.literal("search"),query:r.string().nullish(),queries:r.array(r.string()).nullish(),sources:r.array(r.discriminatedUnion("type",[r.object({type:r.literal("url"),url:r.string()}),r.object({type:r.literal("api"),name:r.string()})])).nullish()}),r.object({type:r.literal("open_page"),url:r.string().nullish()}),r.object({type:r.literal("find_in_page"),url:r.string().nullish(),pattern:r.string().nullish()})]).nullish()}),r.object({type:r.literal("file_search_call"),id:r.string(),queries:r.array(r.string()),results:r.array(r.object({attributes:r.record(r.string(),r.union([r.string(),r.number(),r.boolean()])),file_id:r.string(),filename:r.string(),score:r.number(),text:r.string()})).nullish()}),r.object({type:r.literal("local_shell_call"),id:r.string(),call_id:r.string(),action:r.object({type:r.literal("exec"),command:r.array(r.string()),timeout_ms:r.number().optional(),user:r.string().optional(),working_directory:r.string().optional(),env:r.record(r.string(),r.string()).optional()})}),r.object({type:r.literal("computer_call"),id:r.string(),status:r.literal("completed")}),r.object({type:r.literal("mcp_call"),id:r.string(),status:r.string(),arguments:r.string(),name:r.string(),server_label:r.string(),output:r.string().nullish(),error:r.union([r.string(),r.object({type:r.string().optional(),code:r.union([r.number(),r.string()]).optional(),message:r.string().optional()}).loose()]).nullish(),approval_request_id:r.string().nullish()}),r.object({type:r.literal("mcp_list_tools"),id:r.string(),server_label:r.string(),tools:r.array(r.object({name:r.string(),description:r.string().optional(),input_schema:r.any(),annotations:r.record(r.string(),r.unknown()).optional()})),error:r.union([r.string(),r.object({type:r.string().optional(),code:r.union([r.number(),r.string()]).optional(),message:r.string().optional()}).loose()]).optional()}),r.object({type:r.literal("mcp_approval_request"),id:r.string(),server_label:r.string(),name:r.string(),arguments:r.string(),approval_request_id:r.string().optional()}),r.object({type:r.literal("apply_patch_call"),id:r.string(),call_id:r.string(),status:r.enum(["in_progress","completed"]),operation:r.discriminatedUnion("type",[r.object({type:r.literal("create_file"),path:r.string(),diff:r.string()}),r.object({type:r.literal("delete_file"),path:r.string()}),r.object({type:r.literal("update_file"),path:r.string(),diff:r.string()})])}),r.object({type:r.literal("shell_call"),id:r.string(),call_id:r.string(),status:r.enum(["in_progress","completed","incomplete"]),action:r.object({commands:r.array(r.string())})}),r.object({type:r.literal("shell_call_output"),id:r.string(),call_id:r.string(),status:r.enum(["in_progress","completed","incomplete"]),output:r.array(r.object({stdout:r.string(),stderr:r.string(),outcome:r.discriminatedUnion("type",[r.object({type:r.literal("timeout")}),r.object({type:r.literal("exit"),exit_code:r.number()})])}))}),r.object({type:r.literal("tool_search_call"),id:r.string(),execution:r.enum(["server","client"]),call_id:r.string().nullable(),status:r.enum(["in_progress","completed","incomplete"]),arguments:r.unknown()}),r.object({type:r.literal("tool_search_output"),id:r.string(),execution:r.enum(["server","client"]),call_id:r.string().nullable(),status:r.enum(["in_progress","completed","incomplete"]),tools:r.array(r.record(r.string(),Ui.optional()))})])}),r.object({type:r.literal("response.function_call_arguments.delta"),item_id:r.string(),output_index:r.number(),delta:r.string()}),r.object({type:r.literal("response.custom_tool_call_input.delta"),item_id:r.string(),output_index:r.number(),delta:r.string()}),r.object({type:r.literal("response.image_generation_call.partial_image"),item_id:r.string(),output_index:r.number(),partial_image_b64:r.string()}),r.object({type:r.literal("response.code_interpreter_call_code.delta"),item_id:r.string(),output_index:r.number(),delta:r.string()}),r.object({type:r.literal("response.code_interpreter_call_code.done"),item_id:r.string(),output_index:r.number(),code:r.string()}),r.object({type:r.literal("response.output_text.annotation.added"),annotation:r.discriminatedUnion("type",[r.object({type:r.literal("url_citation"),start_index:r.number(),end_index:r.number(),url:r.string(),title:r.string()}),r.object({type:r.literal("file_citation"),file_id:r.string(),filename:r.string(),index:r.number()}),r.object({type:r.literal("container_file_citation"),container_id:r.string(),file_id:r.string(),filename:r.string(),start_index:r.number(),end_index:r.number()}),r.object({type:r.literal("file_path"),file_id:r.string(),index:r.number()})])}),r.object({type:r.literal("response.reasoning_summary_part.added"),item_id:r.string(),summary_index:r.number()}),r.object({type:r.literal("response.reasoning_summary_text.delta"),item_id:r.string(),summary_index:r.number(),delta:r.string()}),r.object({type:r.literal("response.reasoning_summary_part.done"),item_id:r.string(),summary_index:r.number()}),r.object({type:r.literal("response.apply_patch_call_operation_diff.delta"),item_id:r.string(),output_index:r.number(),delta:r.string(),obfuscation:r.string().nullish()}),r.object({type:r.literal("response.apply_patch_call_operation_diff.done"),item_id:r.string(),output_index:r.number(),diff:r.string()}),A1,P1,r.object({type:r.string()}).loose().transform((e)=>({type:"unknown_chunk",message:e.type}))]))),j1=j(()=>M(r.object({id:r.string().optional(),created_at:r.number().optional(),error:r.object({message:r.string(),type:r.string(),param:r.string().nullish(),code:r.string()}).nullish(),model:r.string().optional(),output:r.array(r.discriminatedUnion("type",[r.object({type:r.literal("message"),role:r.literal("assistant"),id:r.string(),phase:r.enum(["commentary","final_answer"]).nullish(),content:r.array(r.object({type:r.literal("output_text"),text:r.string(),logprobs:r.array(r.object({token:r.string(),logprob:r.number(),top_logprobs:r.array(r.object({token:r.string(),logprob:r.number()}))})).nullish(),annotations:r.array(r.discriminatedUnion("type",[r.object({type:r.literal("url_citation"),start_index:r.number(),end_index:r.number(),url:r.string(),title:r.string()}),r.object({type:r.literal("file_citation"),file_id:r.string(),filename:r.string(),index:r.number()}),r.object({type:r.literal("container_file_citation"),container_id:r.string(),file_id:r.string(),filename:r.string(),start_index:r.number(),end_index:r.number()}),r.object({type:r.literal("file_path"),file_id:r.string(),index:r.number()})]))}))}),r.object({type:r.literal("web_search_call"),id:r.string(),status:r.string(),action:r.discriminatedUnion("type",[r.object({type:r.literal("search"),query:r.string().nullish(),queries:r.array(r.string()).nullish(),sources:r.array(r.discriminatedUnion("type",[r.object({type:r.literal("url"),url:r.string()}),r.object({type:r.literal("api"),name:r.string()})])).nullish()}),r.object({type:r.literal("open_page"),url:r.string().nullish()}),r.object({type:r.literal("find_in_page"),url:r.string().nullish(),pattern:r.string().nullish()})]).nullish()}),r.object({type:r.literal("file_search_call"),id:r.string(),queries:r.array(r.string()),results:r.array(r.object({attributes:r.record(r.string(),r.union([r.string(),r.number(),r.boolean()])),file_id:r.string(),filename:r.string(),score:r.number(),text:r.string()})).nullish()}),r.object({type:r.literal("code_interpreter_call"),id:r.string(),code:r.string().nullable(),container_id:r.string(),outputs:r.array(r.discriminatedUnion("type",[r.object({type:r.literal("logs"),logs:r.string()}),r.object({type:r.literal("image"),url:r.string()})])).nullable()}),r.object({type:r.literal("image_generation_call"),id:r.string(),result:r.string()}),r.object({type:r.literal("local_shell_call"),id:r.string(),call_id:r.string(),action:r.object({type:r.literal("exec"),command:r.array(r.string()),timeout_ms:r.number().optional(),user:r.string().optional(),working_directory:r.string().optional(),env:r.record(r.string(),r.string()).optional()})}),r.object({type:r.literal("function_call"),call_id:r.string(),name:r.string(),arguments:r.string(),id:r.string(),namespace:r.string().nullish()}),r.object({type:r.literal("custom_tool_call"),call_id:r.string(),name:r.string(),input:r.string(),id:r.string()}),r.object({type:r.literal("computer_call"),id:r.string(),status:r.string().optional()}),r.object({type:r.literal("reasoning"),id:r.string(),encrypted_content:r.string().nullish(),summary:r.array(r.object({type:r.literal("summary_text"),text:r.string()}))}),r.object({type:r.literal("mcp_call"),id:r.string(),status:r.string(),arguments:r.string(),name:r.string(),server_label:r.string(),output:r.string().nullish(),error:r.union([r.string(),r.object({type:r.string().optional(),code:r.union([r.number(),r.string()]).optional(),message:r.string().optional()}).loose()]).nullish(),approval_request_id:r.string().nullish()}),r.object({type:r.literal("mcp_list_tools"),id:r.string(),server_label:r.string(),tools:r.array(r.object({name:r.string(),description:r.string().optional(),input_schema:r.any(),annotations:r.record(r.string(),r.unknown()).optional()})),error:r.union([r.string(),r.object({type:r.string().optional(),code:r.union([r.number(),r.string()]).optional(),message:r.string().optional()}).loose()]).optional()}),r.object({type:r.literal("mcp_approval_request"),id:r.string(),server_label:r.string(),name:r.string(),arguments:r.string(),approval_request_id:r.string().optional()}),r.object({type:r.literal("apply_patch_call"),id:r.string(),call_id:r.string(),status:r.enum(["in_progress","completed"]),operation:r.discriminatedUnion("type",[r.object({type:r.literal("create_file"),path:r.string(),diff:r.string()}),r.object({type:r.literal("delete_file"),path:r.string()}),r.object({type:r.literal("update_file"),path:r.string(),diff:r.string()})])}),r.object({type:r.literal("shell_call"),id:r.string(),call_id:r.string(),status:r.enum(["in_progress","completed","incomplete"]),action:r.object({commands:r.array(r.string())})}),r.object({type:r.literal("shell_call_output"),id:r.string(),call_id:r.string(),status:r.enum(["in_progress","completed","incomplete"]),output:r.array(r.object({stdout:r.string(),stderr:r.string(),outcome:r.discriminatedUnion("type",[r.object({type:r.literal("timeout")}),r.object({type:r.literal("exit"),exit_code:r.number()})])}))}),r.object({type:r.literal("tool_search_call"),id:r.string(),execution:r.enum(["server","client"]),call_id:r.string().nullable(),status:r.enum(["in_progress","completed","incomplete"]),arguments:r.unknown()}),r.object({type:r.literal("tool_search_output"),id:r.string(),execution:r.enum(["server","client"]),call_id:r.string().nullable(),status:r.enum(["in_progress","completed","incomplete"]),tools:r.array(r.record(r.string(),Ui.optional()))})])).optional(),service_tier:r.string().nullish(),incomplete_details:r.object({reason:r.string()}).nullish(),usage:r.object({input_tokens:r.number(),input_tokens_details:r.object({cached_tokens:r.number().nullish(),orchestration_input_tokens:r.number().nullish(),orchestration_input_cached_tokens:r.number().nullish()}).nullish(),output_tokens:r.number(),output_tokens_details:r.object({reasoning_tokens:r.number().nullish(),orchestration_output_tokens:r.number().nullish()}).nullish()}).optional()}))),V_=20,O1=["o1","o1-2024-12-17","o3","o3-2025-04-16","o3-mini","o3-mini-2025-01-31","o4-mini","o4-mini-2025-04-16","gpt-5","gpt-5-2025-08-07","gpt-5-codex","gpt-5-mini","gpt-5-mini-2025-08-07","gpt-5-nano","gpt-5-nano-2025-08-07","gpt-5-pro","gpt-5-pro-2025-10-06","gpt-5.1","gpt-5.1-chat-latest","gpt-5.1-codex-mini","gpt-5.1-codex","gpt-5.1-codex-max","gpt-5.2","gpt-5.2-chat-latest","gpt-5.2-pro","gpt-5.2-codex","gpt-5.3-chat-latest","gpt-5.3-codex","gpt-5.4","gpt-5.4-2026-03-05","gpt-5.4-mini","gpt-5.4-mini-2026-03-17","gpt-5.4-nano","gpt-5.4-nano-2026-03-17","gpt-5.4-pro","gpt-5.4-pro-2026-03-05","gpt-5.5","gpt-5.5-2026-04-23"],T9=["gpt-4.1","gpt-4.1-2025-04-14","gpt-4.1-mini","gpt-4.1-mini-2025-04-14","gpt-4.1-nano","gpt-4.1-nano-2025-04-14","gpt-4o","gpt-4o-2024-05-13","gpt-4o-2024-08-06","gpt-4o-2024-11-20","gpt-4o-audio-preview","gpt-4o-audio-preview-2024-12-17","gpt-4o-search-preview","gpt-4o-search-preview-2025-03-11","gpt-4o-mini-search-preview","gpt-4o-mini-search-preview-2025-03-11","gpt-4o-mini","gpt-4o-mini-2024-07-18","gpt-3.5-turbo-0125","gpt-3.5-turbo","gpt-3.5-turbo-1106","gpt-5-chat-latest",...O1],j_=j(()=>M(r.object({conversation:r.string().nullish(),include:r.array(r.enum(["reasoning.encrypted_content","file_search_call.results","web_search_call.results","message.output_text.logprobs"])).nullish(),instructions:r.string().nullish(),logprobs:r.union([r.boolean(),r.number().min(1).max(V_)]).optional(),maxToolCalls:r.number().nullish(),metadata:r.any().nullish(),parallelToolCalls:r.boolean().nullish(),previousResponseId:r.string().nullish(),promptCacheKey:r.string().nullish(),promptCacheRetention:r.enum(["in_memory","24h"]).nullish(),reasoningEffort:r.string().nullish(),reasoningSummary:r.string().nullish(),safetyIdentifier:r.string().nullish(),serviceTier:r.enum(["auto","flex","priority","default"]).nullish(),store:r.boolean().nullish(),passThroughUnsupportedFiles:r.boolean().optional(),strictJsonSchema:r.boolean().nullish(),textVerbosity:r.enum(["low","medium","high"]).nullish(),truncation:r.enum(["auto","disabled"]).nullish(),user:r.string().nullish(),systemMessageMode:r.enum(["system","developer","remove"]).optional(),forceReasoning:r.boolean().optional(),allowedTools:r.object({toolNames:r.array(r.string()).min(1),mode:r.enum(["auto","required"]).optional()}).optional()})));async function N1({tools:e,toolChoice:t,allowedTools:n,toolNameMapping:o,customProviderToolNames:i}){var a,s,l;e=(e==null?void 0:e.length)?e:void 0;let c=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:c};let u=[],d=new Map,m=i!=null?i:new Set;for(let f of e)switch(f.type){case"function":{let g=(a=f.providerOptions)==null?void 0:a.openai,h=D1({tool:f,options:g}),v=g==null?void 0:g.namespace;if(v==null)u.push(h);else{let x=d.get(v.name);if(x==null)x={type:"namespace",name:v.name,description:v.description,tools:[]},d.set(v.name,x),u.push(x);else if(x.description!==v.description)throw new We({functionality:`conflicting descriptions for OpenAI tool namespace "${v.name}"`});x.tools.push(h)}break}case"provider":{switch(f.id){case"openai.file_search":{let g=await Ee({value:f.args,schema:YD});u.push({type:"file_search",vector_store_ids:g.vectorStoreIds,max_num_results:g.maxNumResults,ranking_options:g.ranking?{ranker:g.ranking.ranker,score_threshold:g.ranking.scoreThreshold}:void 0,filters:g.filters});break}case"openai.local_shell":{u.push({type:"local_shell"});break}case"openai.shell":{let g=await Ee({value:f.args,schema:s1});u.push({type:"shell",...g.environment&&{environment:z1(g.environment)}});break}case"openai.apply_patch":{u.push({type:"apply_patch"});break}case"openai.web_search_preview":{let g=await Ee({value:f.args,schema:y1});u.push({type:"web_search_preview",search_context_size:g.searchContextSize,user_location:g.userLocation});break}case"openai.web_search":{let g=await Ee({value:f.args,schema:p1});u.push({type:"web_search",filters:g.filters!=null?{allowed_domains:g.filters.allowedDomains}:void 0,external_web_access:g.externalWebAccess,search_context_size:g.searchContextSize,user_location:g.userLocation});break}case"openai.code_interpreter":{let g=await Ee({value:f.args,schema:GD});u.push({type:"code_interpreter",container:g.container==null?{type:"auto",file_ids:void 0}:typeof g.container==="string"?g.container:{type:"auto",file_ids:g.container.fileIds}});break}case"openai.image_generation":{let g=await Ee({value:f.args,schema:e1});u.push({type:"image_generation",background:g.background,input_fidelity:g.inputFidelity,input_image_mask:g.inputImageMask?{file_id:g.inputImageMask.fileId,image_url:g.inputImageMask.imageUrl}:void 0,model:g.model,moderation:g.moderation,partial_images:g.partialImages,quality:g.quality,output_compression:g.outputCompression,output_format:g.outputFormat,size:g.size});break}case"openai.mcp":{let g=await Ee({value:f.args,schema:S1}),h=(S)=>({tool_names:S.toolNames}),v=g.requireApproval,x=v==null?void 0:typeof v==="string"?v:v.never!=null?{never:h(v.never)}:void 0;u.push({type:"mcp",server_label:g.serverLabel,allowed_tools:Array.isArray(g.allowedTools)?g.allowedTools:g.allowedTools?{read_only:g.allowedTools.readOnly,tool_names:g.allowedTools.toolNames}:void 0,authorization:g.authorization,connector_id:g.connectorId,headers:g.headers,require_approval:x!=null?x:"never",server_description:g.serverDescription,server_url:g.serverUrl});break}case"openai.custom":{let g=await Ee({value:f.args,schema:WD});u.push({type:"custom",name:g.name,description:g.description,format:g.format}),m.add(g.name);break}case"openai.tool_search":{let g=await Ee({value:f.args,schema:c1});u.push({type:"tool_search",...g.execution!=null?{execution:g.execution}:{},...g.description!=null?{description:g.description}:{},...g.parameters!=null?{parameters:g.parameters}:{}});break}}break}default:c.push({type:"unsupported",feature:`function tool ${f}`});break}if(n!=null)return{tools:u,toolChoice:{type:"allowed_tools",mode:(s=n.mode)!=null?s:"auto",tools:n.toolNames.map((f)=>{var g;return{type:"function",name:(g=o==null?void 0:o.toProviderToolName(f))!=null?g:f}})},toolWarnings:c};if(t==null)return{tools:u,toolChoice:void 0,toolWarnings:c};let p=t.type;switch(p){case"auto":case"none":case"required":return{tools:u,toolChoice:p,toolWarnings:c};case"tool":{let f=(l=o==null?void 0:o.toProviderToolName(t.toolName))!=null?l:t.toolName;return{tools:u,toolChoice:f==="code_interpreter"||f==="file_search"||f==="image_generation"||f==="web_search_preview"||f==="web_search"||f==="mcp"||f==="apply_patch"?{type:f}:m.has(f)?{type:"custom",name:f}:{type:"function",name:f},toolWarnings:c}}default:throw new We({functionality:`tool choice type: ${p}`})}}function D1({tool:e,options:t}){let n=t==null?void 0:t.deferLoading;return{type:"function",name:e.name,description:e.description,parameters:e.inputSchema,...e.strict!=null?{strict:e.strict}:{},...n!=null?{defer_loading:n}:{}}}function z1(e){if(e.type==="containerReference")return{type:"container_reference",container_id:e.containerId};if(e.type==="containerAuto"){let n=e;return{type:"container_auto",file_ids:n.fileIds,memory_limit:n.memoryLimit,network_policy:n.networkPolicy==null?void 0:n.networkPolicy.type==="disabled"?{type:"disabled"}:{type:"allowlist",allowed_domains:n.networkPolicy.allowedDomains,domain_secrets:n.networkPolicy.domainSecrets},skills:U1(n.skills)}}return{type:"local",skills:e.skills}}function U1(e){return e==null?void 0:e.map((t)=>t.type==="skillReference"?{type:"skill_reference",skill_id:t.skillId,version:t.version}:{type:"inline",name:t.name,description:t.description,source:{type:"base64",media_type:t.source.mediaType,data:t.source.data}})}function O_(e){var t,n;let o={};for(let i of e){if(i.role!=="assistant")continue;for(let a of i.content){if(a.type!=="tool-call")continue;let s=(n=(t=a.providerOptions)==null?void 0:t.openai)==null?void 0:n.approvalRequestId;if(s!=null)o[s]=a.toolCallId}}return o}var $1=class{constructor(e,t){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:o,topK:i,presencePenalty:a,frequencyPenalty:s,seed:l,prompt:c,providerOptions:u,tools:d,toolChoice:m,responseFormat:p}){var f,g,h,v,x,S,y,w,_,C,I;let b=[],E=L_(this.modelId);if(i!=null)b.push({type:"unsupported",feature:"topK"});if(l!=null)b.push({type:"unsupported",feature:"seed"});if(a!=null)b.push({type:"unsupported",feature:"presencePenalty"});if(s!=null)b.push({type:"unsupported",feature:"frequencyPenalty"});if(n!=null)b.push({type:"unsupported",feature:"stopSequences"});let B=this.config.provider.includes("azure")?"azure":"openai",R=await Ue({provider:B,providerOptions:u,schema:j_});if(R==null&&B!=="openai")R=await Ue({provider:"openai",providerOptions:u,schema:j_});let U=(f=R==null?void 0:R.forceReasoning)!=null?f:E.isReasoningModel;if((R==null?void 0:R.conversation)&&(R==null?void 0:R.previousResponseId))b.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});let z=Aa({tools:d,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:(A)=>A.id==="openai.custom"?A.args.name:void 0}),N=new Set,{tools:re,toolChoice:Y,toolWarnings:V}=await N1({tools:d,toolChoice:m,allowedTools:(g=R==null?void 0:R.allowedTools)!=null?g:void 0,toolNameMapping:z,customProviderToolNames:N}),{input:q,warnings:ue}=await R1({prompt:c,toolNameMapping:z,systemMessageMode:(h=R==null?void 0:R.systemMessageMode)!=null?h:U?"developer":E.systemMessageMode,providerOptionsName:B,fileIdPrefixes:this.config.fileIdPrefixes,passThroughUnsupportedFiles:(v=R==null?void 0:R.passThroughUnsupportedFiles)!=null?v:!1,store:(x=R==null?void 0:R.store)!=null?x:!0,hasConversation:(R==null?void 0:R.conversation)!=null,hasPreviousResponseId:(R==null?void 0:R.previousResponseId)!=null,hasLocalShellTool:H("openai.local_shell"),hasShellTool:H("openai.shell"),hasApplyPatchTool:H("openai.apply_patch"),customProviderToolNames:N.size>0?N:void 0});b.push(...ue);let ee=(S=R==null?void 0:R.strictJsonSchema)!=null?S:!0,k=R==null?void 0:R.include;function X(A){if(k==null)k=[A];else if(!k.includes(A))k=[...k,A]}function H(A){return(d==null?void 0:d.find((O)=>O.type==="provider"&&O.id===A))!=null}let J=typeof(R==null?void 0:R.logprobs)==="number"?R==null?void 0:R.logprobs:(R==null?void 0:R.logprobs)===!0?V_:void 0;if(J)X("message.output_text.logprobs");let K=(y=d==null?void 0:d.find((A)=>A.type==="provider"&&(A.id==="openai.web_search"||A.id==="openai.web_search_preview")))==null?void 0:y.name;if(K)X("web_search_call.action.sources");if(H("openai.code_interpreter"))X("code_interpreter_call.outputs");let D=R==null?void 0:R.store;if(D===!1&&U)X("reasoning.encrypted_content");let F={model:this.modelId,input:q,temperature:t,top_p:o,max_output_tokens:e,...((p==null?void 0:p.type)==="json"||(R==null?void 0:R.textVerbosity))&&{text:{...(p==null?void 0:p.type)==="json"&&{format:p.schema!=null?{type:"json_schema",strict:ee,name:(w=p.name)!=null?w:"response",description:p.description,schema:p.schema}:{type:"json_object"}},...(R==null?void 0:R.textVerbosity)&&{verbosity:R.textVerbosity}}},conversation:R==null?void 0:R.conversation,max_tool_calls:R==null?void 0:R.maxToolCalls,metadata:R==null?void 0:R.metadata,parallel_tool_calls:R==null?void 0:R.parallelToolCalls,previous_response_id:R==null?void 0:R.previousResponseId,store:D,user:R==null?void 0:R.user,instructions:R==null?void 0:R.instructions,service_tier:R==null?void 0:R.serviceTier,include:k,prompt_cache_key:R==null?void 0:R.promptCacheKey,prompt_cache_retention:R==null?void 0:R.promptCacheRetention,safety_identifier:R==null?void 0:R.safetyIdentifier,top_logprobs:J,truncation:R==null?void 0:R.truncation,...U&&((R==null?void 0:R.reasoningEffort)!=null||(R==null?void 0:R.reasoningSummary)!=null)&&{reasoning:{...(R==null?void 0:R.reasoningEffort)!=null&&{effort:R.reasoningEffort},...(R==null?void 0:R.reasoningSummary)!=null&&{summary:R.reasoningSummary}}}};if(U){if(!((R==null?void 0:R.reasoningEffort)==="none"&&E.supportsNonReasoningParameters)){if(F.temperature!=null)F.temperature=void 0,b.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"});if(F.top_p!=null)F.top_p=void 0,b.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})}}else{if((R==null?void 0:R.reasoningEffort)!=null)b.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"});if((R==null?void 0:R.reasoningSummary)!=null)b.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})}if((R==null?void 0:R.serviceTier)==="flex"&&!E.supportsFlexProcessing)b.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete F.service_tier;if((R==null?void 0:R.serviceTier)==="priority"&&!E.supportsPriorityProcessing)b.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 F.service_tier;let G=(I=(C=(_=d==null?void 0:d.find((A)=>A.type==="provider"&&A.id==="openai.shell"))==null?void 0:_.args)==null?void 0:C.environment)==null?void 0:I.type,Z=G==="containerAuto"||G==="containerReference";return{webSearchToolName:K,args:{...F,tools:re,tool_choice:Y},warnings:[...b,...V],store:D,toolNameMapping:z,providerOptionsName:B,isShellProviderExecuted:Z}}async doGenerate(e){var t,n,o,i,a,s,l,c,u,d,m,p,f,g,h,v,x,S,y,w,_,C,I,b,E,B,R,U;let{args:z,warnings:N,webSearchToolName:re,toolNameMapping:Y,providerOptionsName:V,isShellProviderExecuted:q}=await this.getArgs(e),ue=this.config.url({path:"/responses",modelId:this.modelId}),ee=O_(e.prompt),{responseHeaders:k,value:X,rawValue:H}=await Ie({url:ue,headers:_e(this.config.headers(),e.headers),body:z,failedResponseHandler:gr,successfulResponseHandler:xe(j1),abortSignal:e.abortSignal,fetch:this.config.fetch});if(X.error)throw new De({message:X.error.message,url:ue,requestBodyValues:z,statusCode:400,responseHeaders:k,responseBody:H,isRetryable:!1});let J=[],K=[],D=!1,F=[];for(let A of X.output)switch(A.type){case"reasoning":{if(A.summary.length===0)A.summary.push({type:"summary_text",text:""});for(let O of A.summary)J.push({type:"reasoning",text:O.text,providerMetadata:{[V]:{itemId:A.id,reasoningEncryptedContent:(t=A.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{J.push({type:"tool-call",toolCallId:A.id,toolName:Y.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),J.push({type:"tool-result",toolCallId:A.id,toolName:Y.toCustomToolName("image_generation"),result:{result:A.result}});break}case"tool_search_call":{let O=(n=A.call_id)!=null?n:A.id,W=A.execution==="server";if(W)F.push(O);J.push({type:"tool-call",toolCallId:O,toolName:Y.toCustomToolName("tool_search"),input:JSON.stringify({arguments:A.arguments,call_id:A.call_id}),...W?{providerExecuted:!0}:{},providerMetadata:{[V]:{itemId:A.id}}});break}case"tool_search_output":{let O=(i=(o=A.call_id)!=null?o:F.shift())!=null?i:A.id;J.push({type:"tool-result",toolCallId:O,toolName:Y.toCustomToolName("tool_search"),result:{tools:A.tools},providerMetadata:{[V]:{itemId:A.id}}});break}case"local_shell_call":{J.push({type:"tool-call",toolCallId:A.call_id,toolName:Y.toCustomToolName("local_shell"),input:JSON.stringify({action:A.action}),providerMetadata:{[V]:{itemId:A.id}}});break}case"shell_call":{J.push({type:"tool-call",toolCallId:A.call_id,toolName:Y.toCustomToolName("shell"),input:JSON.stringify({action:{commands:A.action.commands}}),...q&&{providerExecuted:!0},providerMetadata:{[V]:{itemId:A.id}}});break}case"shell_call_output":{J.push({type:"tool-result",toolCallId:A.call_id,toolName:Y.toCustomToolName("shell"),result:{output:A.output.map((O)=>({stdout:O.stdout,stderr:O.stderr,outcome:O.outcome.type==="exit"?{type:"exit",exitCode:O.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(let O of A.content){if(((s=(a=e.providerOptions)==null?void 0:a[V])==null?void 0:s.logprobs)&&O.logprobs)K.push(O.logprobs);let W={itemId:A.id,...A.phase!=null&&{phase:A.phase},...O.annotations.length>0&&{annotations:O.annotations}};J.push({type:"text",text:O.text,providerMetadata:{[V]:W}});for(let P of O.annotations)if(P.type==="url_citation")J.push({type:"source",sourceType:"url",id:(u=(c=(l=this.config).generateId)==null?void 0:c.call(l))!=null?u:Le(),url:P.url,title:P.title});else if(P.type==="file_citation")J.push({type:"source",sourceType:"document",id:(p=(m=(d=this.config).generateId)==null?void 0:m.call(d))!=null?p:Le(),mediaType:"text/plain",title:P.filename,filename:P.filename,providerMetadata:{[V]:{type:P.type,fileId:P.file_id,index:P.index}}});else if(P.type==="container_file_citation")J.push({type:"source",sourceType:"document",id:(h=(g=(f=this.config).generateId)==null?void 0:g.call(f))!=null?h:Le(),mediaType:"text/plain",title:P.filename,filename:P.filename,providerMetadata:{[V]:{type:P.type,fileId:P.file_id,containerId:P.container_id}}});else if(P.type==="file_path")J.push({type:"source",sourceType:"document",id:(S=(x=(v=this.config).generateId)==null?void 0:x.call(v))!=null?S:Le(),mediaType:"application/octet-stream",title:P.file_id,filename:P.file_id,providerMetadata:{[V]:{type:P.type,fileId:P.file_id,index:P.index}}})}break}case"function_call":{D=!0,J.push({type:"tool-call",toolCallId:A.call_id,toolName:A.name,input:A.arguments,providerMetadata:{[V]:{itemId:A.id,...A.namespace!=null&&{namespace:A.namespace}}}});break}case"custom_tool_call":{D=!0;let O=Y.toCustomToolName(A.name);J.push({type:"tool-call",toolCallId:A.call_id,toolName:O,input:JSON.stringify(A.input),providerMetadata:{[V]:{itemId:A.id}}});break}case"web_search_call":{J.push({type:"tool-call",toolCallId:A.id,toolName:Y.toCustomToolName(re!=null?re:"web_search"),input:JSON.stringify({}),providerExecuted:!0}),J.push({type:"tool-result",toolCallId:A.id,toolName:Y.toCustomToolName(re!=null?re:"web_search"),result:U_(A.action)});break}case"mcp_call":{let O=A.approval_request_id!=null?(y=ee[A.approval_request_id])!=null?y:A.id:A.id,W=`mcp.${A.name}`;J.push({type:"tool-call",toolCallId:O,toolName:W,input:A.arguments,providerExecuted:!0,dynamic:!0}),J.push({type:"tool-result",toolCallId:O,toolName:W,result:{type:"call",serverLabel:A.server_label,name:A.name,arguments:A.arguments,...A.output!=null?{output:A.output}:{},...A.error!=null?{error:A.error}:{}},providerMetadata:{[V]:{itemId:A.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{let O=(w=A.approval_request_id)!=null?w:A.id,W=(I=(C=(_=this.config).generateId)==null?void 0:C.call(_))!=null?I:Le(),P=`mcp.${A.name}`;J.push({type:"tool-call",toolCallId:W,toolName:P,input:A.arguments,providerExecuted:!0,dynamic:!0}),J.push({type:"tool-approval-request",approvalId:O,toolCallId:W});break}case"computer_call":{J.push({type:"tool-call",toolCallId:A.id,toolName:Y.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),J.push({type:"tool-result",toolCallId:A.id,toolName:Y.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:A.status||"completed"}});break}case"file_search_call":{J.push({type:"tool-call",toolCallId:A.id,toolName:Y.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),J.push({type:"tool-result",toolCallId:A.id,toolName:Y.toCustomToolName("file_search"),result:{queries:A.queries,results:(E=(b=A.results)==null?void 0:b.map((O)=>({attributes:O.attributes,fileId:O.file_id,filename:O.filename,score:O.score,text:O.text})))!=null?E:null}});break}case"code_interpreter_call":{J.push({type:"tool-call",toolCallId:A.id,toolName:Y.toCustomToolName("code_interpreter"),input:JSON.stringify({code:A.code,containerId:A.container_id}),providerExecuted:!0}),J.push({type:"tool-result",toolCallId:A.id,toolName:Y.toCustomToolName("code_interpreter"),result:{outputs:A.outputs}});break}case"apply_patch_call":{J.push({type:"tool-call",toolCallId:A.call_id,toolName:Y.toCustomToolName("apply_patch"),input:JSON.stringify({callId:A.call_id,operation:A.operation}),providerMetadata:{[V]:{itemId:A.id}}});break}}let G={[V]:{responseId:X.id,...K.length>0?{logprobs:K}:{},...typeof X.service_tier==="string"?{serviceTier:X.service_tier}:{}}},Z=X.usage;return{content:J,finishReason:{unified:pu({finishReason:(B=X.incomplete_details)==null?void 0:B.reason,hasFunctionCall:D}),raw:(U=(R=X.incomplete_details)==null?void 0:R.reason)!=null?U:void 0},usage:P_(Z),request:{body:z},response:{id:X.id,timestamp:new Date(X.created_at*1000),modelId:X.model,headers:k,body:H},providerMetadata:G,warnings:N}}async doStream(e){let{args:t,warnings:n,webSearchToolName:o,toolNameMapping:i,store:a,providerOptionsName:s,isShellProviderExecuted:l}=await this.getArgs(e),c=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:u,value:d}=await Ie({url:c,headers:_e(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:gr,successfulResponseHandler:Dt(M1),abortSignal:e.abortSignal,fetch:this.config.fetch}),m=await vu({stream:d,getError:(U)=>z_(U)||N_(U)&&U.response.error!=null?U:void 0,isOutputChunk:t2,url:c,requestBodyValues:t,responseHeaders:u}),p=this,f=O_(e.prompt),g=new Map,h={unified:"other",raw:void 0},v=void 0,x=[],S=null,y={},w=[],_,C=!1,I={},b,E=[],B=!1;return{stream:m.pipeThrough(new TransformStream({start(U){U.enqueue({type:"stream-start",warnings:n})},transform(U,z){var N,re,Y,V,q,ue,ee,k,X,H,J,K,D,F,G,Z,A,O,W,P,L,me,Q,de,Ae,Ke,nt,At,Dr,he,br,zr,rn,Tn,_r,st,nn,ut;if(e.includeRawChunks)z.enqueue({type:"raw",rawValue:U.rawValue});if(!U.success){let te=q1(U.rawValue)?F1({value:U.rawValue,cause:U.error,url:c,requestBodyValues:t,responseHeaders:u}):U.error;h={unified:"error",raw:void 0},z.enqueue({type:"error",error:te});return}let T=U.value;if(D_(T)){if(T.item.type==="function_call")y[T.output_index]={toolName:T.item.name,toolCallId:T.item.call_id},z.enqueue({type:"tool-input-start",id:T.item.call_id,toolName:T.item.name});else if(T.item.type==="custom_tool_call"){let te=i.toCustomToolName(T.item.name);y[T.output_index]={toolName:te,toolCallId:T.item.call_id},z.enqueue({type:"tool-input-start",id:T.item.call_id,toolName:te})}else if(T.item.type==="web_search_call")y[T.output_index]={toolName:i.toCustomToolName(o!=null?o:"web_search"),toolCallId:T.item.id},z.enqueue({type:"tool-input-start",id:T.item.id,toolName:i.toCustomToolName(o!=null?o:"web_search"),providerExecuted:!0}),z.enqueue({type:"tool-input-end",id:T.item.id}),z.enqueue({type:"tool-call",toolCallId:T.item.id,toolName:i.toCustomToolName(o!=null?o:"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(T.item.type==="computer_call")y[T.output_index]={toolName:i.toCustomToolName("computer_use"),toolCallId:T.item.id},z.enqueue({type:"tool-input-start",id:T.item.id,toolName:i.toCustomToolName("computer_use"),providerExecuted:!0});else if(T.item.type==="code_interpreter_call")y[T.output_index]={toolName:i.toCustomToolName("code_interpreter"),toolCallId:T.item.id,codeInterpreter:{containerId:T.item.container_id}},z.enqueue({type:"tool-input-start",id:T.item.id,toolName:i.toCustomToolName("code_interpreter"),providerExecuted:!0}),z.enqueue({type:"tool-input-delta",id:T.item.id,delta:`{"containerId":"${T.item.container_id}","code":"`});else if(T.item.type==="file_search_call")z.enqueue({type:"tool-call",toolCallId:T.item.id,toolName:i.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(T.item.type==="image_generation_call")z.enqueue({type:"tool-call",toolCallId:T.item.id,toolName:i.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(T.item.type==="tool_search_call"){let te=T.item.id,ve=i.toCustomToolName("tool_search"),Re=T.item.execution==="server";if(y[T.output_index]={toolName:ve,toolCallId:te,toolSearchExecution:(N=T.item.execution)!=null?N:"server"},Re)z.enqueue({type:"tool-input-start",id:te,toolName:ve,providerExecuted:!0})}else if(T.item.type==="tool_search_output");else if(T.item.type==="mcp_call"||T.item.type==="mcp_list_tools"||T.item.type==="mcp_approval_request");else if(T.item.type==="apply_patch_call"){let{call_id:te,operation:ve}=T.item;if(y[T.output_index]={toolName:i.toCustomToolName("apply_patch"),toolCallId:te,applyPatch:{hasDiff:ve.type==="delete_file",endEmitted:ve.type==="delete_file"}},z.enqueue({type:"tool-input-start",id:te,toolName:i.toCustomToolName("apply_patch")}),ve.type==="delete_file"){let Re=JSON.stringify({callId:te,operation:ve});z.enqueue({type:"tool-input-delta",id:te,delta:Re}),z.enqueue({type:"tool-input-end",id:te})}else z.enqueue({type:"tool-input-delta",id:te,delta:`{"callId":"${$n(te)}","operation":{"type":"${$n(ve.type)}","path":"${$n(ve.path)}","diff":"`})}else if(T.item.type==="shell_call")y[T.output_index]={toolName:i.toCustomToolName("shell"),toolCallId:T.item.call_id};else if(T.item.type==="shell_call_output");else if(T.item.type==="message")w.splice(0,w.length),_=(re=T.item.phase)!=null?re:void 0,z.enqueue({type:"text-start",id:T.item.id,providerMetadata:{[s]:{itemId:T.item.id,...T.item.phase!=null&&{phase:T.item.phase}}}});else if(D_(T)&&T.item.type==="reasoning")I[T.item.id]={encryptedContent:T.item.encrypted_content,summaryParts:{0:"active"}},z.enqueue({type:"reasoning-start",id:`${T.item.id}:0`,providerMetadata:{[s]:{itemId:T.item.id,reasoningEncryptedContent:(Y=T.item.encrypted_content)!=null?Y:null}}})}else if(G1(T)){if(T.item.type==="message"){let te=(V=T.item.phase)!=null?V:_;_=void 0,z.enqueue({type:"text-end",id:T.item.id,providerMetadata:{[s]:{itemId:T.item.id,...te!=null&&{phase:te},...w.length>0&&{annotations:w}}}})}else if(T.item.type==="function_call")y[T.output_index]=void 0,C=!0,z.enqueue({type:"tool-input-end",id:T.item.call_id,...T.item.namespace!=null&&{providerMetadata:{[s]:{namespace:T.item.namespace}}}}),z.enqueue({type:"tool-call",toolCallId:T.item.call_id,toolName:T.item.name,input:T.item.arguments,providerMetadata:{[s]:{itemId:T.item.id,...T.item.namespace!=null&&{namespace:T.item.namespace}}}});else if(T.item.type==="custom_tool_call"){y[T.output_index]=void 0,C=!0;let te=i.toCustomToolName(T.item.name);z.enqueue({type:"tool-input-end",id:T.item.call_id}),z.enqueue({type:"tool-call",toolCallId:T.item.call_id,toolName:te,input:JSON.stringify(T.item.input),providerMetadata:{[s]:{itemId:T.item.id}}})}else if(T.item.type==="web_search_call")y[T.output_index]=void 0,z.enqueue({type:"tool-result",toolCallId:T.item.id,toolName:i.toCustomToolName(o!=null?o:"web_search"),result:U_(T.item.action)});else if(T.item.type==="computer_call")y[T.output_index]=void 0,z.enqueue({type:"tool-input-end",id:T.item.id}),z.enqueue({type:"tool-call",toolCallId:T.item.id,toolName:i.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),z.enqueue({type:"tool-result",toolCallId:T.item.id,toolName:i.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:T.item.status||"completed"}});else if(T.item.type==="file_search_call")y[T.output_index]=void 0,z.enqueue({type:"tool-result",toolCallId:T.item.id,toolName:i.toCustomToolName("file_search"),result:{queries:T.item.queries,results:(ue=(q=T.item.results)==null?void 0:q.map((te)=>({attributes:te.attributes,fileId:te.file_id,filename:te.filename,score:te.score,text:te.text})))!=null?ue:null}});else if(T.item.type==="code_interpreter_call")y[T.output_index]=void 0,z.enqueue({type:"tool-result",toolCallId:T.item.id,toolName:i.toCustomToolName("code_interpreter"),result:{outputs:T.item.outputs}});else if(T.item.type==="image_generation_call")z.enqueue({type:"tool-result",toolCallId:T.item.id,toolName:i.toCustomToolName("image_generation"),result:{result:T.item.result}});else if(T.item.type==="tool_search_call"){let te=y[T.output_index],ve=T.item.execution==="server";if(te!=null){let Re=ve?te.toolCallId:(ee=T.item.call_id)!=null?ee:T.item.id;if(ve)E.push(Re);else z.enqueue({type:"tool-input-start",id:Re,toolName:te.toolName});z.enqueue({type:"tool-input-end",id:Re}),z.enqueue({type:"tool-call",toolCallId:Re,toolName:te.toolName,input:JSON.stringify({arguments:T.item.arguments,call_id:ve?null:Re}),...ve?{providerExecuted:!0}:{},providerMetadata:{[s]:{itemId:T.item.id}}})}y[T.output_index]=void 0}else if(T.item.type==="tool_search_output"){let te=(X=(k=T.item.call_id)!=null?k:E.shift())!=null?X:T.item.id;z.enqueue({type:"tool-result",toolCallId:te,toolName:i.toCustomToolName("tool_search"),result:{tools:T.item.tools},providerMetadata:{[s]:{itemId:T.item.id}}})}else if(T.item.type==="mcp_call"){y[T.output_index]=void 0;let te=(H=T.item.approval_request_id)!=null?H:void 0,ve=te!=null?(K=(J=g.get(te))!=null?J:f[te])!=null?K:T.item.id:T.item.id,Re=`mcp.${T.item.name}`;z.enqueue({type:"tool-call",toolCallId:ve,toolName:Re,input:T.item.arguments,providerExecuted:!0,dynamic:!0}),z.enqueue({type:"tool-result",toolCallId:ve,toolName:Re,result:{type:"call",serverLabel:T.item.server_label,name:T.item.name,arguments:T.item.arguments,...T.item.output!=null?{output:T.item.output}:{},...T.item.error!=null?{error:T.item.error}:{}},providerMetadata:{[s]:{itemId:T.item.id}}})}else if(T.item.type==="mcp_list_tools")y[T.output_index]=void 0;else if(T.item.type==="apply_patch_call"){let te=y[T.output_index];if((te==null?void 0:te.applyPatch)&&!te.applyPatch.endEmitted&&T.item.operation.type!=="delete_file"){if(!te.applyPatch.hasDiff)z.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:$n(T.item.operation.diff)});z.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:'"}}'}),z.enqueue({type:"tool-input-end",id:te.toolCallId}),te.applyPatch.endEmitted=!0}if(te&&T.item.status==="completed")z.enqueue({type:"tool-call",toolCallId:te.toolCallId,toolName:i.toCustomToolName("apply_patch"),input:JSON.stringify({callId:T.item.call_id,operation:T.item.operation}),providerMetadata:{[s]:{itemId:T.item.id}}});y[T.output_index]=void 0}else if(T.item.type==="mcp_approval_request"){y[T.output_index]=void 0;let te=(G=(F=(D=p.config).generateId)==null?void 0:F.call(D))!=null?G:Le(),ve=(Z=T.item.approval_request_id)!=null?Z:T.item.id;g.set(ve,te);let Re=`mcp.${T.item.name}`;z.enqueue({type:"tool-call",toolCallId:te,toolName:Re,input:T.item.arguments,providerExecuted:!0,dynamic:!0}),z.enqueue({type:"tool-approval-request",approvalId:ve,toolCallId:te})}else if(T.item.type==="local_shell_call")y[T.output_index]=void 0,z.enqueue({type:"tool-call",toolCallId:T.item.call_id,toolName:i.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:T.item.action.command,timeoutMs:T.item.action.timeout_ms,user:T.item.action.user,workingDirectory:T.item.action.working_directory,env:T.item.action.env}}),providerMetadata:{[s]:{itemId:T.item.id}}});else if(T.item.type==="shell_call")y[T.output_index]=void 0,z.enqueue({type:"tool-call",toolCallId:T.item.call_id,toolName:i.toCustomToolName("shell"),input:JSON.stringify({action:{commands:T.item.action.commands}}),...l&&{providerExecuted:!0},providerMetadata:{[s]:{itemId:T.item.id}}});else if(T.item.type==="shell_call_output")z.enqueue({type:"tool-result",toolCallId:T.item.call_id,toolName:i.toCustomToolName("shell"),result:{output:T.item.output.map((te)=>({stdout:te.stdout,stderr:te.stderr,outcome:te.outcome.type==="exit"?{type:"exit",exitCode:te.outcome.exit_code}:{type:"timeout"}}))}});else if(T.item.type==="reasoning"){let te=I[T.item.id],ve=Object.entries(te.summaryParts).filter(([Re,ht])=>ht==="active"||ht==="can-conclude").map(([Re])=>Re);for(let Re of ve)z.enqueue({type:"reasoning-end",id:`${T.item.id}:${Re}`,providerMetadata:{[s]:{itemId:T.item.id,reasoningEncryptedContent:(A=T.item.encrypted_content)!=null?A:null}}});delete I[T.item.id]}}else if(W1(T)){let te=y[T.output_index];if(te!=null)z.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:T.delta})}else if(V1(T)){let te=y[T.output_index];if(te!=null)z.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:T.delta})}else if(Q1(T)){let te=y[T.output_index];if(te==null?void 0:te.applyPatch)z.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:$n(T.delta)}),te.applyPatch.hasDiff=!0}else if(X1(T)){let te=y[T.output_index];if((te==null?void 0:te.applyPatch)&&!te.applyPatch.endEmitted){if(!te.applyPatch.hasDiff)z.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:$n(T.diff)}),te.applyPatch.hasDiff=!0;z.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:'"}}'}),z.enqueue({type:"tool-input-end",id:te.toolCallId}),te.applyPatch.endEmitted=!0}}else if(Z1(T))z.enqueue({type:"tool-result",toolCallId:T.item_id,toolName:i.toCustomToolName("image_generation"),result:{result:T.partial_image_b64},preliminary:!0});else if(K1(T)){let te=y[T.output_index];if(te!=null)z.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:$n(T.delta)})}else if(Y1(T)){let te=y[T.output_index];if(te!=null)z.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:'"}'}),z.enqueue({type:"tool-input-end",id:te.toolCallId}),z.enqueue({type:"tool-call",toolCallId:te.toolCallId,toolName:i.toCustomToolName("code_interpreter"),input:JSON.stringify({code:T.code,containerId:te.codeInterpreter.containerId}),providerExecuted:!0})}else if(H1(T))S=T.response.id,z.enqueue({type:"response-metadata",id:T.response.id,timestamp:new Date(T.response.created_at*1000),modelId:T.response.model});else if(L1(T)){if(z.enqueue({type:"text-delta",id:T.item_id,delta:T.delta}),((W=(O=e.providerOptions)==null?void 0:O[s])==null?void 0:W.logprobs)&&T.logprobs)x.push(T.logprobs)}else if(T.type==="response.reasoning_summary_part.added"){if(T.summary_index>0){let te=I[T.item_id];te.summaryParts[T.summary_index]="active";for(let ve of Object.keys(te.summaryParts))if(te.summaryParts[ve]==="can-conclude")z.enqueue({type:"reasoning-end",id:`${T.item_id}:${ve}`,providerMetadata:{[s]:{itemId:T.item_id}}}),te.summaryParts[ve]="concluded";z.enqueue({type:"reasoning-start",id:`${T.item_id}:${T.summary_index}`,providerMetadata:{[s]:{itemId:T.item_id,reasoningEncryptedContent:(L=(P=I[T.item_id])==null?void 0:P.encryptedContent)!=null?L:null}}})}}else if(T.type==="response.reasoning_summary_text.delta")z.enqueue({type:"reasoning-delta",id:`${T.item_id}:${T.summary_index}`,delta:T.delta,providerMetadata:{[s]:{itemId:T.item_id}}});else if(T.type==="response.reasoning_summary_part.done")if(a)z.enqueue({type:"reasoning-end",id:`${T.item_id}:${T.summary_index}`,providerMetadata:{[s]:{itemId:T.item_id}}}),I[T.item_id].summaryParts[T.summary_index]="concluded";else I[T.item_id].summaryParts[T.summary_index]="can-conclude";else if(J1(T)){if(h={unified:pu({finishReason:(me=T.response.incomplete_details)==null?void 0:me.reason,hasFunctionCall:C}),raw:(de=(Q=T.response.incomplete_details)==null?void 0:Q.reason)!=null?de:void 0},v=T.response.usage,typeof T.response.service_tier==="string")b=T.response.service_tier}else if(N_(T)){let te=(Ae=T.response.incomplete_details)==null?void 0:Ae.reason;if(h={unified:te?pu({finishReason:te,hasFunctionCall:C}):"error",raw:te!=null?te:"error"},v=(Ke=T.response.usage)!=null?Ke:void 0,!B&&T.response.error!=null)B=!0,z.enqueue({type:"error",error:{type:"response.failed",sequence_number:T.sequence_number,response:{error:T.response.error,incomplete_details:T.response.incomplete_details,service_tier:T.response.service_tier}}})}else if(e2(T)){if(w.push(T.annotation),T.annotation.type==="url_citation")z.enqueue({type:"source",sourceType:"url",id:(Dr=(At=(nt=p.config).generateId)==null?void 0:At.call(nt))!=null?Dr:Le(),url:T.annotation.url,title:T.annotation.title});else if(T.annotation.type==="file_citation")z.enqueue({type:"source",sourceType:"document",id:(zr=(br=(he=p.config).generateId)==null?void 0:br.call(he))!=null?zr:Le(),mediaType:"text/plain",title:T.annotation.filename,filename:T.annotation.filename,providerMetadata:{[s]:{type:T.annotation.type,fileId:T.annotation.file_id,index:T.annotation.index}}});else if(T.annotation.type==="container_file_citation")z.enqueue({type:"source",sourceType:"document",id:(_r=(Tn=(rn=p.config).generateId)==null?void 0:Tn.call(rn))!=null?_r:Le(),mediaType:"text/plain",title:T.annotation.filename,filename:T.annotation.filename,providerMetadata:{[s]:{type:T.annotation.type,fileId:T.annotation.file_id,containerId:T.annotation.container_id}}});else if(T.annotation.type==="file_path")z.enqueue({type:"source",sourceType:"document",id:(ut=(nn=(st=p.config).generateId)==null?void 0:nn.call(st))!=null?ut:Le(),mediaType:"application/octet-stream",title:T.annotation.file_id,filename:T.annotation.file_id,providerMetadata:{[s]:{type:T.annotation.type,fileId:T.annotation.file_id,index:T.annotation.index}}})}else if(z_(T))B=!0,h={unified:"error",raw:"error"},z.enqueue({type:"error",error:T})},flush(U){let z={[s]:{responseId:S,...x.length>0?{logprobs:x}:{},...b!==void 0?{serviceTier:b}:{}}};U.enqueue({type:"finish",finishReason:h,usage:P_(v),providerMetadata:z})}})),request:{body:t},response:{headers:u}}}};function L1(e){return e.type==="response.output_text.delta"}function q1(e){let t=B1(e);return t!=null&&Array.isArray(t.choices)&&typeof t.type!=="string"}function F1({value:e,cause:t,url:n,requestBodyValues:o,responseHeaders:i}){return new De({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:n,requestBodyValues:o,responseHeaders:i,responseBody:JSON.stringify(e),cause:t,data:e,isRetryable:!1})}function B1(e){return typeof e==="object"&&e!=null?e:void 0}function G1(e){return e.type==="response.output_item.done"}function J1(e){return e.type==="response.completed"||e.type==="response.incomplete"}function N_(e){return e.type==="response.failed"}function H1(e){return e.type==="response.created"}function W1(e){return e.type==="response.function_call_arguments.delta"}function V1(e){return e.type==="response.custom_tool_call_input.delta"}function Z1(e){return e.type==="response.image_generation_call.partial_image"}function K1(e){return e.type==="response.code_interpreter_call_code.delta"}function Y1(e){return e.type==="response.code_interpreter_call_code.done"}function Q1(e){return e.type==="response.apply_patch_call_operation_diff.delta"}function X1(e){return e.type==="response.apply_patch_call_operation_diff.done"}function D_(e){return e.type==="response.output_item.added"}function e2(e){return e.type==="response.output_text.annotation.added"}function z_(e){return e.type==="error"}function t2(e){return!(e.type==="response.created"||e.type==="response.failed"||e.type==="error"||e.type==="unknown_chunk")}function U_(e){var t;if(e==null)return{};switch(e.type){case"search":return{action:{type:"search",query:(t=e.query)!=null?t:void 0,...e.queries!=null&&{queries:e.queries}},...e.sources!=null&&{sources:e.sources}};case"open_page":return{action:{type:"openPage",url:e.url}};case"find_in_page":return{action:{type:"findInPage",url:e.url,pattern:e.pattern}}}}function $n(e){return JSON.stringify(e).slice(1,-1)}var r2=j(()=>M(r.object({instructions:r.string().nullish(),speed:r.number().min(0.25).max(4).default(1).nullish()}))),n2=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({text:e,voice:t="alloy",outputFormat:n="mp3",speed:o,instructions:i,language:a,providerOptions:s}){let l=[],c=await Ue({provider:"openai",providerOptions:s,schema:r2}),u={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:o,instructions:i};if(n)if(["mp3","opus","aac","flac","wav","pcm"].includes(n))u.response_format=n;else l.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${n}. Using mp3 instead.`});if(c){let d={};for(let m in d){let p=d[m];if(p!==void 0)u[m]=p}}if(a)l.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${a}" was ignored.`});return{requestBody:u,warnings:l}}async doGenerate(e){var t,n,o;let i=(o=(n=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:n.call(t))!=null?o:new Date,{requestBody:a,warnings:s}=await this.getArgs(e),{value:l,responseHeaders:c,rawValue:u}=await Ie({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:_e(this.config.headers(),e.headers),body:a,failedResponseHandler:gr,successfulResponseHandler:ug(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:l,warnings:s,request:{body:JSON.stringify(a)},response:{timestamp:i,modelId:this.modelId,headers:c,body:u}}}},o2=j(()=>M(r.object({text:r.string(),language:r.string().nullish(),duration:r.number().nullish(),words:r.array(r.object({word:r.string(),start:r.number(),end:r.number()})).nullish(),segments:r.array(r.object({id:r.number(),seek:r.number(),start:r.number(),end:r.number(),text:r.string(),tokens:r.array(r.number()),temperature:r.number(),avg_logprob:r.number(),compression_ratio:r.number(),no_speech_prob:r.number()})).nullish()}))),i2=j(()=>M(r.object({include:r.array(r.string()).optional(),language:r.string().optional(),prompt:r.string().optional(),temperature:r.number().min(0).max(1).default(0).optional(),timestampGranularities:r.array(r.enum(["word","segment"])).default(["segment"]).optional()}))),$_={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"},a2=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){let o=[],i=await Ue({provider:"openai",providerOptions:n,schema:i2}),a=new FormData,s=e instanceof Uint8Array?new Blob([e]):new Blob([wt(e)]);a.append("model",this.modelId);let l=tg(t);if(a.append("file",new File([s],"audio",{type:t}),`audio.${l}`),i){let c={include:i.include,language:i.language,prompt:i.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:i.temperature,timestamp_granularities:i.timestampGranularities};for(let[u,d]of Object.entries(c))if(d!=null)if(Array.isArray(d))for(let m of d)a.append(`${u}[]`,String(m));else a.append(u,String(d))}return{formData:a,warnings:o}}async doGenerate(e){var t,n,o,i,a,s,l,c;let u=(o=(n=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:n.call(t))!=null?o:new Date,{formData:d,warnings:m}=await this.getArgs(e),{value:p,responseHeaders:f,rawValue:g}=await Oa({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:_e(this.config.headers(),e.headers),formData:d,failedResponseHandler:gr,successfulResponseHandler:xe(o2),abortSignal:e.abortSignal,fetch:this.config.fetch}),h=p.language!=null&&p.language in $_?$_[p.language]:void 0;return{text:p.text,segments:(l=(s=(i=p.segments)==null?void 0:i.map((v)=>({text:v.text,startSecond:v.start,endSecond:v.end})))!=null?s:(a=p.words)==null?void 0:a.map((v)=>({text:v.word,startSecond:v.start,endSecond:v.end})))!=null?l:[],language:h,durationInSeconds:(c=p.duration)!=null?c:void 0,warnings:m,response:{timestamp:u,modelId:this.modelId,headers:f,body:g}}}},s2="3.0.82";function _o(e={}){var t,n;let o=(t=mn(Ar({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",i=(n=e.name)!=null?n:"openai",a=()=>it({Authorization:`Bearer ${co({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${s2}`),s=(h)=>new xD(h,{provider:`${i}.chat`,url:({path:v})=>`${o}${v}`,headers:a,fetch:e.fetch}),l=(h)=>new RD(h,{provider:`${i}.completion`,url:({path:v})=>`${o}${v}`,headers:a,fetch:e.fetch}),c=(h)=>new MD(h,{provider:`${i}.embedding`,url:({path:v})=>`${o}${v}`,headers:a,fetch:e.fetch}),u=(h)=>new UD(h,{provider:`${i}.image`,url:({path:v})=>`${o}${v}`,headers:a,fetch:e.fetch}),d=(h)=>new a2(h,{provider:`${i}.transcription`,url:({path:v})=>`${o}${v}`,headers:a,fetch:e.fetch}),m=(h)=>new n2(h,{provider:`${i}.speech`,url:({path:v})=>`${o}${v}`,headers:a,fetch:e.fetch}),p=(h)=>{if(new.target)throw Error("The OpenAI model function cannot be called with the new keyword.");return f(h)},f=(h)=>new $1(h,{provider:`${i}.responses`,url:({path:v})=>`${o}${v}`,headers:a,fetch:e.fetch,fileIdPrefixes:["file-"]}),g=function(h){return p(h)};return g.specificationVersion="v3",g.languageModel=p,g.chat=s,g.completion=l,g.responses=f,g.embedding=c,g.embeddingModel=c,g.textEmbedding=c,g.textEmbeddingModel=c,g.image=u,g.imageModel=u,g.transcription=d,g.transcriptionModel=d,g.speech=m,g.speechModel=m,g.tools=C1,g}var N9=_o();var l2="3.0.90",c2=j(()=>M(r.object({error:r.object({code:r.number().nullable(),message:r.string(),status:r.string()})}))),or=Qe({errorSchema:c2,errorToMessage:(e)=>e.error.message}),u2=r.union([r.object({text:r.string()}),r.object({inlineData:r.object({mimeType:r.string(),data:r.string()})}),r.object({fileData:r.object({fileUri:r.string(),mimeType:r.string()})})]),d2=j(()=>M(r.object({outputDimensionality:r.number().optional(),taskType:r.enum(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional(),content:r.array(r.array(u2).min(1).nullable()).optional()}))),p2=class{constructor(e,t){this.specificationVersion="v3",this.maxEmbeddingsPerCall=100,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:o}){let i=await Ue({provider:"google",providerOptions:o,schema:d2});if(e.length>this.maxEmbeddingsPerCall)throw new ba({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=_e(await Se(this.config.headers),t),s=i==null?void 0:i.content;if(s!=null&&s.length!==e.length)throw Error(`The number of multimodal content entries (${s.length}) must match the number of values (${e.length}).`);if(e.length===1){let d=s==null?void 0:s[0],m=e[0]?[{text:e[0]}]:[],p=d!=null?[...m,...d]:[{text:e[0]}],{responseHeaders:f,value:g,rawValue:h}=await Ie({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:a,body:{model:`models/${this.modelId}`,content:{parts:p},outputDimensionality:i==null?void 0:i.outputDimensionality,taskType:i==null?void 0:i.taskType},failedResponseHandler:or,successfulResponseHandler:xe(g2),abortSignal:n,fetch:this.config.fetch});return{warnings:[],embeddings:[g.embedding.values],usage:void 0,response:{headers:f,body:h}}}let{responseHeaders:l,value:c,rawValue:u}=await Ie({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:a,body:{requests:e.map((d,m)=>{let p=s==null?void 0:s[m],f=d?[{text:d}]:[];return{model:`models/${this.modelId}`,content:{role:"user",parts:p!=null?[...f,...p]:[{text:d}]},outputDimensionality:i==null?void 0:i.outputDimensionality,taskType:i==null?void 0:i.taskType}})},failedResponseHandler:or,successfulResponseHandler:xe(m2),abortSignal:n,fetch:this.config.fetch});return{warnings:[],embeddings:c.embeddings.map((d)=>d.values),usage:void 0,response:{headers:l,body:u}}}},m2=j(()=>M(r.object({embeddings:r.array(r.object({values:r.array(r.number())}))}))),g2=j(()=>M(r.object({embedding:r.object({values:r.array(r.number())})})));function Z_(e){var t,n,o,i;if(e==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};let a=(t=e.promptTokenCount)!=null?t:0,s=(n=e.candidatesTokenCount)!=null?n:0,l=(o=e.cachedContentTokenCount)!=null?o:0,c=(i=e.thoughtsTokenCount)!=null?i:0;return{inputTokens:{total:a,noCache:a-l,cacheRead:l,cacheWrite:void 0},outputTokens:{total:s+c,text:s,reasoning:c},raw:e}}function fr(e,t=!0){if(e==null)return;if(f2(e)){if(t)return;if(typeof e==="object"&&e.description)return{type:"object",description:e.description};return{type:"object"}}if(typeof e==="boolean")return{type:"boolean",properties:{}};let{type:n,description:o,required:i,properties:a,items:s,allOf:l,anyOf:c,oneOf:u,format:d,const:m,minLength:p,enum:f}=e,g={};if(o)g.description=o;if(i)g.required=i;if(d)g.format=d;if(m!==void 0)g.enum=[m];if(n)if(Array.isArray(n)){let h=n.includes("null"),v=n.filter((x)=>x!=="null");if(v.length===0)g.type="null";else if(g.anyOf=v.map((x)=>({type:x})),h)g.nullable=!0}else g.type=n;if(f!==void 0)g.enum=f;if(a!=null)g.properties=Object.entries(a).reduce((h,[v,x])=>(h[v]=fr(x,!1),h),{});if(s)g.items=Array.isArray(s)?s.map((h)=>fr(h,!1)):fr(s,!1);if(l)g.allOf=l.map((h)=>fr(h,!1));if(c)if(c.some((h)=>typeof h==="object"&&(h==null?void 0:h.type)==="null")){let h=c.filter((v)=>!(typeof v==="object"&&(v==null?void 0:v.type)==="null"));if(h.length===1){let v=fr(h[0],!1);if(typeof v==="object")g.nullable=!0,Object.assign(g,v)}else g.anyOf=h.map((v)=>fr(v,!1)),g.nullable=!0}else g.anyOf=c.map((h)=>fr(h,!1));if(u)g.oneOf=u.map((h)=>fr(h,!1));if(p!==void 0)g.minLength=p;return g}function f2(e){return e!=null&&typeof e==="object"&&e.type==="object"&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}var h2="skip_thought_signature_validator";function K_(e,t){let n=[t,"google","googleVertex","vertex"].filter((o,i,a)=>a.indexOf(o)===i);for(let o of n){let i=e==null?void 0:e[o];if(i!=null)return i}}var y2=/^data:([^;,]+);base64,(.+)$/s;function v2(e){let t=y2.exec(e);if(t==null)return;return{mediaType:t[1],data:t[2]}}function b2(e){let t=v2(e);if(t==null)return;return{inlineData:{mimeType:t.mediaType,data:t.data}}}function _2(e,t,n,o){let i=[],a=[];for(let s of n)switch(s.type){case"text":{a.push(s.text);break}case"image-data":case"file-data":{i.push({inlineData:{mimeType:s.mediaType,data:s.data}});break}case"image-url":case"file-url":{let l=b2(s.url);if(l!=null)i.push(l);else a.push(JSON.stringify(s));break}default:{a.push(JSON.stringify(s));break}}e.push({functionResponse:{...o!=null?{id:o}:{},name:t,response:{name:t,content:a.length>0?a.join(`
82
+ `):"Tool executed successfully."},...i.length>0?{parts:i}:{}}})}function S2(e,t,n,o){for(let i of n)switch(i.type){case"text":e.push({functionResponse:{...o!=null?{id:o}:{},name:t,response:{name:t,content:i.text}}});break;case"image-data":e.push({inlineData:{mimeType:String(i.mediaType),data:String(i.data)}},{text:"Tool executed successfully and returned this image as a response"});break;default:e.push({text:JSON.stringify(i)});break}}function w2(e,t){var n,o,i,a,s;let l=[],c=[],u=!0,d=(n=t==null?void 0:t.isGemmaModel)!=null?n:!1,m=(o=t==null?void 0:t.isGemini3Model)!=null?o:!1,p=(i=t==null?void 0:t.providerOptionsName)!=null?i:"google",f=(a=t==null?void 0:t.supportsFunctionResponseParts)!=null?a:!0,g=t==null?void 0:t.onWarning,h=!1,v=[],x=(S)=>(v.push(S),h=!0,h2);for(let{role:S,content:y}of e)switch(S){case"system":{if(!u)throw new We({functionality:"system messages are only supported at the beginning of the conversation"});l.push({text:y});break}case"user":{u=!1;let w=[];for(let _ of y)switch(_.type){case"text":{w.push({text:_.text});break}case"file":{let C=_.mediaType==="image/*"?"image/jpeg":_.mediaType;w.push(_.data instanceof URL?{fileData:{mimeType:C,fileUri:_.data.toString()}}:{inlineData:{mimeType:C,data:bt(_.data)}});break}}c.push({role:"user",parts:w});break}case"assistant":{u=!1,c.push({role:"model",parts:y.map((w)=>{let _=K_(w.providerOptions,p),C=(_==null?void 0:_.thoughtSignature)!=null?String(_.thoughtSignature):void 0;switch(w.type){case"text":return w.text.length===0?void 0:{text:w.text,thoughtSignature:C};case"reasoning":return w.text.length===0?void 0:{text:w.text,thought:!0,thoughtSignature:C};case"file":{if(w.data instanceof URL)throw new We({functionality:"File data URLs in assistant messages are not supported"});return{inlineData:{mimeType:w.mediaType,data:bt(w.data)},...(_==null?void 0:_.thought)===!0?{thought:!0}:{},thoughtSignature:C}}case"tool-call":{let I=(_==null?void 0:_.serverToolCallId)!=null?String(_.serverToolCallId):void 0,b=(_==null?void 0:_.serverToolType)!=null?String(_.serverToolType):void 0,E=C!=null?C:m?x(w.toolName):void 0;if(I&&b)return{toolCall:{toolType:b,args:typeof w.input==="string"?er(w.input):w.input,id:I},thoughtSignature:E};return{functionCall:{...w.toolCallId!=null?{id:w.toolCallId}:{},name:w.toolName,args:w.input},thoughtSignature:E}}case"tool-result":{let I=(_==null?void 0:_.serverToolCallId)!=null?String(_.serverToolCallId):void 0,b=(_==null?void 0:_.serverToolType)!=null?String(_.serverToolType):void 0;if(I&&b)return{toolResponse:{toolType:b,response:w.output.type==="json"?w.output.value:{},id:I},thoughtSignature:C};return}}}).filter((w)=>w!==void 0)});break}case"tool":{u=!1;let w=[];for(let _ of y){if(_.type==="tool-approval-response")continue;let C=K_(_.providerOptions,p),I=(C==null?void 0:C.serverToolCallId)!=null?String(C.serverToolCallId):void 0,b=(C==null?void 0:C.serverToolType)!=null?String(C.serverToolType):void 0;if(I&&b){let B=(C==null?void 0:C.thoughtSignature)!=null?String(C.thoughtSignature):void 0;if(c.length>0){let R=c[c.length-1];if(R.role==="model"){R.parts.push({toolResponse:{toolType:b,response:_.output.type==="json"?_.output.value:{},id:I},thoughtSignature:B});continue}}}let E=_.output;if(E.type==="content")if(f)_2(w,_.toolName,E.value,_.toolCallId);else S2(w,_.toolName,E.value,_.toolCallId);else w.push({functionResponse:{..._.toolCallId!=null?{id:_.toolCallId}:{},name:_.toolName,response:{name:_.toolName,content:E.type==="execution-denied"?(s=E.reason)!=null?s:"Tool call execution denied.":E.value}}})}c.push({role:"user",parts:w});break}}if(d&&l.length>0&&c.length>0&&c[0].role==="user"){let S=l.map((y)=>y.text).join(`
83
+
84
+ `);c[0].parts.unshift({text:S+`
85
+
86
+ `})}if(h&&g!=null){let S=Array.from(new Set(v));g({type:"other",message:`Replayed ${v.length} \`functionCall\` part(s) for a Gemini 3 model without a \`thoughtSignature\` (tools: ${S.map((y)=>`\`${y}\``).join(", ")}). Injected the documented \`skip_thought_signature_validator\` sentinel to keep the request from failing with HTTP 400. The likely cause is application code that drops \`providerOptions.google.thoughtSignature\` when persisting or serializing assistant tool-call messages. See https://ai.google.dev/gemini-api/docs/thought-signatures.`})}return{systemInstruction:l.length>0&&!d?{parts:l}:void 0,contents:c}}function Y_(e){return e.includes("/")?e:`models/${e}`}var Q_=j(()=>M(r.object({responseModalities:r.array(r.enum(["TEXT","IMAGE"])).optional(),thinkingConfig:r.object({thinkingBudget:r.number().optional(),includeThoughts:r.boolean().optional(),thinkingLevel:r.enum(["minimal","low","medium","high"]).optional()}).optional(),cachedContent:r.string().optional(),structuredOutputs:r.boolean().optional(),safetySettings:r.array(r.object({category:r.enum(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:r.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:r.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:r.boolean().optional(),labels:r.record(r.string(),r.string()).optional(),mediaResolution:r.enum(["MEDIA_RESOLUTION_UNSPECIFIED","MEDIA_RESOLUTION_LOW","MEDIA_RESOLUTION_MEDIUM","MEDIA_RESOLUTION_HIGH"]).optional(),imageConfig:r.object({aspectRatio:r.enum(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).optional(),imageSize:r.enum(["1K","2K","4K","512"]).optional()}).optional(),retrievalConfig:r.object({latLng:r.object({latitude:r.number(),longitude:r.number()}).optional()}).optional(),streamFunctionCallArguments:r.boolean().optional(),serviceTier:r.enum(["standard","flex","priority"]).optional(),sharedRequestType:r.enum(["priority","flex","standard"]).optional(),requestType:r.enum(["shared"]).optional()})));function x2({tools:e,toolChoice:t,modelId:n,isVertexProvider:o=!1}){var i,a;e=(e==null?void 0:e.length)?e:void 0;let s=[],l=["gemini-flash-latest","gemini-flash-lite-latest","gemini-pro-latest"].some((v)=>v===n),c=n.includes("gemini-2")||n.includes("gemini-3")||n.includes("nano-banana")||l,u=n.includes("gemini-3"),d=n.includes("gemini-2.5")||n.includes("gemini-3");if(e==null)return{tools:void 0,toolConfig:void 0,toolWarnings:s};let m=e.some((v)=>v.type==="function"),p=e.some((v)=>v.type==="provider");if(m&&p&&!u)s.push({type:"unsupported",feature:"combination of function and provider-defined tools"});if(p){let v=[];if(e.filter((S)=>S.type==="provider").forEach((S)=>{switch(S.id){case"google.google_search":if(c)v.push({googleSearch:{...S.args}});else s.push({type:"unsupported",feature:`provider-defined tool ${S.id}`,details:"Google Search requires Gemini 2.0 or newer."});break;case"google.enterprise_web_search":if(c)v.push({enterpriseWebSearch:{}});else s.push({type:"unsupported",feature:`provider-defined tool ${S.id}`,details:"Enterprise Web Search requires Gemini 2.0 or newer."});break;case"google.url_context":if(c)v.push({urlContext:{}});else s.push({type:"unsupported",feature:`provider-defined tool ${S.id}`,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":if(c)v.push({codeExecution:{}});else s.push({type:"unsupported",feature:`provider-defined tool ${S.id}`,details:"The code execution tool is not supported with other Gemini models than Gemini 2."});break;case"google.file_search":if(d)v.push({fileSearch:{...S.args}});else s.push({type:"unsupported",feature:`provider-defined tool ${S.id}`,details:"The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."});break;case"google.vertex_rag_store":if(c)v.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:S.args.ragCorpus},similarity_top_k:S.args.topK}}});else s.push({type:"unsupported",feature:`provider-defined tool ${S.id}`,details:"The RAG store tool is not supported with other Gemini models than Gemini 2."});break;case"google.google_maps":if(c)v.push({googleMaps:{}});else s.push({type:"unsupported",feature:`provider-defined tool ${S.id}`,details:"The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."});break;default:s.push({type:"unsupported",feature:`provider-defined tool ${S.id}`});break}}),m&&u&&v.length>0){let S=[];for(let w of e)if(w.type==="function")S.push({name:w.name,description:(i=w.description)!=null?i:"",parameters:fr(w.inputSchema)});let y={functionCallingConfig:{mode:"VALIDATED"},...!o&&{includeServerSideToolInvocations:!0}};if(t!=null)switch(t.type){case"auto":break;case"none":y.functionCallingConfig={mode:"NONE"};break;case"required":y.functionCallingConfig={mode:"ANY"};break;case"tool":y.functionCallingConfig={mode:"ANY",allowedFunctionNames:[t.toolName]};break}return{tools:[...v,{functionDeclarations:S}],toolConfig:y,toolWarnings:s}}return{tools:v.length>0?v:void 0,toolConfig:void 0,toolWarnings:s}}let f=[],g=!1;for(let v of e)switch(v.type){case"function":if(f.push({name:v.name,description:(a=v.description)!=null?a:"",parameters:fr(v.inputSchema)}),v.strict===!0)g=!0;break;default:s.push({type:"unsupported",feature:`function tool ${v.name}`});break}if(t==null)return{tools:[{functionDeclarations:f}],toolConfig:g?{functionCallingConfig:{mode:"VALIDATED"}}:void 0,toolWarnings:s};let h=t.type;switch(h){case"auto":return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:g?"VALIDATED":"AUTO"}},toolWarnings:s};case"none":return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:s};case"required":return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:g?"VALIDATED":"ANY"}},toolWarnings:s};case"tool":return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:g?"VALIDATED":"ANY",allowedFunctionNames:[t.toolName]}},toolWarnings:s};default:throw new We({functionality:`tool choice type: ${h}`})}}var T2=class{constructor(){this.accumulatedArgs={},this.jsonText="",this.pathStack=[],this.stringOpen=!1}processPartialArgs(e){let t="";for(let n of e){let o=n.jsonPath.replace(/^\$\./,"");if(!o)continue;let i=I2(o),a=k2(this.accumulatedArgs,i);if(n.stringValue!=null&&a!==void 0){let c=JSON.stringify(n.stringValue).slice(1,-1);eS(this.accumulatedArgs,i,a+n.stringValue),t+=c;continue}let l=R2(n);if(l==null)continue;eS(this.accumulatedArgs,i,l.value),t+=this.emitNavigationTo(i,n,l.json)}return this.jsonText+=t,{currentJSON:this.accumulatedArgs,textDelta:t}}finalize(){let e=JSON.stringify(this.accumulatedArgs),t=e.slice(this.jsonText.length);return{finalJSON:e,closingDelta:t}}ensureRoot(){if(this.pathStack.length===0)return this.pathStack.push({segment:"",isArray:!1,childCount:0}),"{";return""}emitNavigationTo(e,t,n){let o="";if(this.stringOpen)o+='"',this.stringOpen=!1;o+=this.ensureRoot();let i=e.slice(0,-1),a=e[e.length-1],s=this.findCommonStackDepth(i);return o+=this.closeDownTo(s),o+=this.openDownTo(i,a),o+=this.emitLeaf(a,t,n),o}findCommonStackDepth(e){let t=Math.min(this.pathStack.length-1,e.length),n=0;for(let o=0;o<t;o++)if(this.pathStack[o+1].segment===e[o])n++;else break;return n+1}closeDownTo(e){let t="";while(this.pathStack.length>e){let n=this.pathStack.pop();t+=n.isArray?"]":"}"}return t}openDownTo(e,t){let n="",o=this.pathStack.length-1;for(let i=o;i<e.length;i++){let a=e[i],s=this.pathStack[this.pathStack.length-1];if(s.childCount>0)n+=",";if(s.childCount++,typeof a==="string")n+=`${JSON.stringify(a)}:`;let c=typeof(i+1<e.length?e[i+1]:t)==="number";n+=c?"[":"{",this.pathStack.push({segment:a,isArray:c,childCount:0})}return n}emitLeaf(e,t,n){let o="",i=this.pathStack[this.pathStack.length-1];if(i.childCount>0)o+=",";if(i.childCount++,typeof e==="string")o+=`${JSON.stringify(e)}:`;if(t.stringValue!=null&&t.willContinue)o+=n.slice(0,-1),this.stringOpen=!0;else o+=n;return o}};function I2(e){let t=[];for(let n of e.split(".")){let o=n.indexOf("[");if(o===-1)t.push(n);else{if(o>0)t.push(n.slice(0,o));for(let i of n.matchAll(/\[(\d+)\]/g))t.push(parseInt(i[1],10))}}return t}var C2=Object.prototype.hasOwnProperty;function dS(e,t){return C2.call(e,t)}function X_(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})}function k2(e,t){let n=e;for(let o of t){if(n==null||typeof n!=="object")return;let i=n;if(!dS(i,o))return;n=i[o]}return n}function eS(e,t,n){let o=e;for(let i=0;i<t.length-1;i++){let a=t[i],s=t[i+1];if(!dS(o,a)||o[a]==null)X_(o,a,typeof s==="number"?[]:{});o=o[a]}X_(o,t[t.length-1],n)}function R2(e){var t,n;let o=(n=(t=e.stringValue)!=null?t:e.numberValue)!=null?n:e.boolValue;if(o!=null)return{value:o,json:JSON.stringify(o)};if("nullValue"in e)return{value:null,json:"null"};return}function tS({finishReason:e,hasToolCalls:t}){switch(e){case"STOP":return t?"tool-calls":"stop";case"MAX_TOKENS":return"length";case"IMAGE_SAFETY":case"RECITATION":case"SAFETY":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":return"content-filter";case"MALFORMED_FUNCTION_CALL":return"error";case"FINISH_REASON_UNSPECIFIED":case"OTHER":default:return"other"}}var pS=class{constructor(e,t){this.specificationVersion="v3";var n;this.modelId=e,this.config=t,this.generateId=(n=t.generateId)!=null?n:Le}get provider(){return this.config.provider}get supportedUrls(){var e,t,n;return(n=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?n:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:o,topK:i,frequencyPenalty:a,presencePenalty:s,stopSequences:l,responseFormat:c,seed:u,tools:d,toolChoice:m,providerOptions:p},{isStreaming:f=!1}={}){var g,h;let v=[],x=this.config.provider.includes("vertex")?"vertex":"google",S=await Ue({provider:x,providerOptions:p,schema:Q_});if(S==null&&x!=="google")S=await Ue({provider:"google",providerOptions:p,schema:Q_});let y=this.config.provider.startsWith("google.vertex.");if((d==null?void 0:d.some((Y)=>Y.type==="provider"&&Y.id==="google.vertex_rag_store"))&&!y)v.push({type:"other",message:`The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`});if((S==null?void 0:S.streamFunctionCallArguments)&&!y)v.push({type:"other",message:`'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${this.config.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc`});if((S==null?void 0:S.serviceTier)&&y)v.push({type:"other",message:"'serviceTier' is a Gemini API option and is not supported on Vertex AI. Use 'sharedRequestType' (and optionally 'requestType') instead. See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/priority-paygo"});if(((S==null?void 0:S.sharedRequestType)||(S==null?void 0:S.requestType))&&!y)v.push({type:"other",message:`'sharedRequestType' and 'requestType' are Vertex AI options and are ignored with the current Google provider (${this.config.provider}).`});let w=y&&((S==null?void 0:S.sharedRequestType)||(S==null?void 0:S.requestType))?{...S.sharedRequestType&&{"X-Vertex-AI-LLM-Shared-Request-Type":S.sharedRequestType},...S.requestType&&{"X-Vertex-AI-LLM-Request-Type":S.requestType}}:void 0,_=y?void 0:S==null?void 0:S.serviceTier,C=this.modelId.toLowerCase().startsWith("gemma-"),I=/^gemini-3[.-]/.test(this.modelId),b=I,{contents:E,systemInstruction:B}=w2(e,{isGemmaModel:C,isGemini3Model:I,providerOptionsName:x,supportsFunctionResponseParts:b,onWarning:(Y)=>v.push(Y)}),{tools:R,toolConfig:U,toolWarnings:z}=x2({tools:d,toolChoice:m,modelId:this.modelId,isVertexProvider:y}),N=f&&y?(g=S==null?void 0:S.streamFunctionCallArguments)!=null?g:!1:void 0,re=U||N||(S==null?void 0:S.retrievalConfig)?{...U,...N&&{functionCallingConfig:{...U==null?void 0:U.functionCallingConfig,streamFunctionCallArguments:!0}},...(S==null?void 0:S.retrievalConfig)&&{retrievalConfig:S.retrievalConfig}}:void 0;return{args:{generationConfig:{maxOutputTokens:t,temperature:n,topK:i,topP:o,frequencyPenalty:a,presencePenalty:s,stopSequences:l,seed:u,responseMimeType:(c==null?void 0:c.type)==="json"?"application/json":void 0,responseSchema:(c==null?void 0:c.type)==="json"&&c.schema!=null&&((h=S==null?void 0:S.structuredOutputs)!=null?h:!0)?fr(c.schema):void 0,...(S==null?void 0:S.audioTimestamp)&&{audioTimestamp:S.audioTimestamp},responseModalities:S==null?void 0:S.responseModalities,thinkingConfig:S==null?void 0:S.thinkingConfig,...(S==null?void 0:S.mediaResolution)&&{mediaResolution:S.mediaResolution},...(S==null?void 0:S.imageConfig)&&{imageConfig:S.imageConfig}},contents:E,systemInstruction:C?void 0:B,safetySettings:S==null?void 0:S.safetySettings,tools:R,toolConfig:re,cachedContent:S==null?void 0:S.cachedContent,labels:S==null?void 0:S.labels,serviceTier:_},warnings:[...v,...z],providerOptionsName:x,extraHeaders:w}}async doGenerate(e){var t,n,o,i,a,s,l,c,u,d,m,p,f,g,h,v,x,S;let{args:y,warnings:w,providerOptionsName:_,extraHeaders:C}=await this.getArgs(e),I=_e(await Se(this.config.headers),e.headers,C),{responseHeaders:b,value:E,rawValue:B}=await Ie({url:`${this.config.baseURL}/${Y_(this.modelId)}:generateContent`,headers:I,body:y,failedResponseHandler:or,successfulResponseHandler:xe(A2),abortSignal:e.abortSignal,fetch:this.config.fetch}),R=E.candidates[0],U=[],z=(n=(t=R.content)==null?void 0:t.parts)!=null?n:[],N=E.usageMetadata,re,Y;for(let q of z)if("executableCode"in q&&((o=q.executableCode)==null?void 0:o.code)){let ue=this.config.generateId();re=ue,U.push({type:"tool-call",toolCallId:ue,toolName:"code_execution",input:JSON.stringify(q.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in q&&q.codeExecutionResult)U.push({type:"tool-result",toolCallId:re,toolName:"code_execution",result:{outcome:q.codeExecutionResult.outcome,output:(i=q.codeExecutionResult.output)!=null?i:""}}),re=void 0;else if("text"in q&&q.text!=null){let ue=q.thoughtSignature?{[_]:{thoughtSignature:q.thoughtSignature}}:void 0;if(q.text.length===0){if(ue!=null&&U.length>0){let ee=U[U.length-1];ee.providerMetadata=ue}}else U.push({type:q.thought===!0?"reasoning":"text",text:q.text,providerMetadata:ue})}else if("functionCall"in q&&q.functionCall.name!=null)U.push({type:"tool-call",toolCallId:(a=q.functionCall.id)!=null?a:this.config.generateId(),toolName:q.functionCall.name,input:JSON.stringify((s=q.functionCall.args)!=null?s:{}),providerMetadata:q.thoughtSignature?{[_]:{thoughtSignature:q.thoughtSignature}}:void 0});else if("inlineData"in q){let ue=q.thought===!0,ee=!!q.thoughtSignature;U.push({type:"file",data:q.inlineData.data,mediaType:q.inlineData.mimeType,providerMetadata:ue||ee?{[_]:{...ue?{thought:!0}:{},...ee?{thoughtSignature:q.thoughtSignature}:{}}}:void 0})}else if("toolCall"in q&&q.toolCall){let ue=(l=q.toolCall.id)!=null?l:this.config.generateId();Y=ue,U.push({type:"tool-call",toolCallId:ue,toolName:`server:${q.toolCall.toolType}`,input:JSON.stringify((c=q.toolCall.args)!=null?c:{}),providerExecuted:!0,dynamic:!0,providerMetadata:q.thoughtSignature?{[_]:{thoughtSignature:q.thoughtSignature,serverToolCallId:ue,serverToolType:q.toolCall.toolType}}:{[_]:{serverToolCallId:ue,serverToolType:q.toolCall.toolType}}})}else if("toolResponse"in q&&q.toolResponse){let ue=(u=Y!=null?Y:q.toolResponse.id)!=null?u:this.config.generateId();U.push({type:"tool-result",toolCallId:ue,toolName:`server:${q.toolResponse.toolType}`,result:(d=q.toolResponse.response)!=null?d:{},providerMetadata:q.thoughtSignature?{[_]:{thoughtSignature:q.thoughtSignature,serverToolCallId:ue,serverToolType:q.toolResponse.toolType}}:{[_]:{serverToolCallId:ue,serverToolType:q.toolResponse.toolType}}}),Y=void 0}let V=(m=rS({groundingMetadata:R.groundingMetadata,generateId:this.config.generateId}))!=null?m:[];for(let q of V)U.push(q);return{content:U,finishReason:{unified:tS({finishReason:R.finishReason,hasToolCalls:U.some((q)=>q.type==="tool-call"&&!q.providerExecuted)}),raw:(p=R.finishReason)!=null?p:void 0},usage:Z_(N),warnings:w,providerMetadata:{[_]:{promptFeedback:(f=E.promptFeedback)!=null?f:null,groundingMetadata:(g=R.groundingMetadata)!=null?g:null,urlContextMetadata:(h=R.urlContextMetadata)!=null?h:null,safetyRatings:(v=R.safetyRatings)!=null?v:null,usageMetadata:N!=null?N:null,finishMessage:(x=R.finishMessage)!=null?x:null,serviceTier:(S=N==null?void 0:N.serviceTier)!=null?S:null}},request:{body:y},response:{headers:b,body:B}}}async doStream(e){let{args:t,warnings:n,providerOptionsName:o,extraHeaders:i}=await this.getArgs(e,{isStreaming:!0}),a=_e(await Se(this.config.headers),e.headers,i),{responseHeaders:s,value:l}=await Ie({url:`${this.config.baseURL}/${Y_(this.modelId)}:streamGenerateContent?alt=sse`,headers:a,body:t,failedResponseHandler:or,successfulResponseHandler:Dt(P2),abortSignal:e.abortSignal,fetch:this.config.fetch}),c={unified:"other",raw:void 0},u=void 0,d=void 0,m=null,p=null,f=this.config.generateId,g=!1,h=null,v=null,x=0,S=new Set,y,w,_=[],C=(I)=>{let b=_.pop();if(b==null)return;let{finalJSON:E,closingDelta:B}=b.accumulator.finalize();if(B.length>0)I.enqueue({type:"tool-input-delta",id:b.toolCallId,delta:B,providerMetadata:b.providerMetadata});I.enqueue({type:"tool-input-end",id:b.toolCallId,providerMetadata:b.providerMetadata}),I.enqueue({type:"tool-call",toolCallId:b.toolCallId,toolName:b.toolName,input:E,providerMetadata:b.providerMetadata}),g=!0};return{stream:l.pipeThrough(new TransformStream({start(I){I.enqueue({type:"stream-start",warnings:n})},transform(I,b){var E,B,R,U,z,N,re,Y,V,q,ue,ee,k,X,H,J;if(e.includeRawChunks)b.enqueue({type:"raw",rawValue:I.rawValue});if(!I.success){b.enqueue({type:"error",error:I.error});return}let K=I.value,D=K.usageMetadata;if(D!=null)u=D;let F=(E=K.candidates)==null?void 0:E[0];if(F==null)return;let G=F.content;if(F.groundingMetadata!=null)m=F.groundingMetadata;if(F.urlContextMetadata!=null)p=F.urlContextMetadata;let Z=rS({groundingMetadata:F.groundingMetadata,generateId:f});if(Z!=null){for(let A of Z)if(A.sourceType==="url"&&!S.has(A.url))S.add(A.url),b.enqueue(A)}if(G!=null){let A=(B=G.parts)!=null?B:[];for(let O of A)if("executableCode"in O&&((R=O.executableCode)==null?void 0:R.code)){let W=f();y=W,b.enqueue({type:"tool-call",toolCallId:W,toolName:"code_execution",input:JSON.stringify(O.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in O&&O.codeExecutionResult){let W=y;if(W)b.enqueue({type:"tool-result",toolCallId:W,toolName:"code_execution",result:{outcome:O.codeExecutionResult.outcome,output:(U=O.codeExecutionResult.output)!=null?U:""}}),y=void 0}else if("text"in O&&O.text!=null){let W=O.thoughtSignature?{[o]:{thoughtSignature:O.thoughtSignature}}:void 0;if(O.text.length===0){if(W!=null&&h!==null)b.enqueue({type:"text-delta",id:h,delta:"",providerMetadata:W})}else if(O.thought===!0){if(h!==null)b.enqueue({type:"text-end",id:h}),h=null;if(v===null)v=String(x++),b.enqueue({type:"reasoning-start",id:v,providerMetadata:W});b.enqueue({type:"reasoning-delta",id:v,delta:O.text,providerMetadata:W})}else{if(v!==null)b.enqueue({type:"reasoning-end",id:v}),v=null;if(h===null)h=String(x++),b.enqueue({type:"text-start",id:h,providerMetadata:W});b.enqueue({type:"text-delta",id:h,delta:O.text,providerMetadata:W})}}else if("inlineData"in O){if(h!==null)b.enqueue({type:"text-end",id:h}),h=null;if(v!==null)b.enqueue({type:"reasoning-end",id:v}),v=null;let W=O.thought===!0,P=!!O.thoughtSignature,L=W||P?{[o]:{...W?{thought:!0}:{},...P?{thoughtSignature:O.thoughtSignature}:{}}}:void 0;b.enqueue({type:"file",mediaType:O.inlineData.mimeType,data:O.inlineData.data,providerMetadata:L})}else if("toolCall"in O&&O.toolCall){let W=(z=O.toolCall.id)!=null?z:f();w=W;let P={[o]:{...O.thoughtSignature?{thoughtSignature:O.thoughtSignature}:{},serverToolCallId:W,serverToolType:O.toolCall.toolType}};b.enqueue({type:"tool-call",toolCallId:W,toolName:`server:${O.toolCall.toolType}`,input:JSON.stringify((N=O.toolCall.args)!=null?N:{}),providerExecuted:!0,dynamic:!0,providerMetadata:P})}else if("toolResponse"in O&&O.toolResponse){let W=(re=w!=null?w:O.toolResponse.id)!=null?re:f(),P={[o]:{...O.thoughtSignature?{thoughtSignature:O.thoughtSignature}:{},serverToolCallId:W,serverToolType:O.toolResponse.toolType}};b.enqueue({type:"tool-result",toolCallId:W,toolName:`server:${O.toolResponse.toolType}`,result:(Y=O.toolResponse.response)!=null?Y:{},providerMetadata:P}),w=void 0}for(let O of A){if(!("functionCall"in O))continue;let W=O.thoughtSignature?{[o]:{thoughtSignature:O.thoughtSignature}}:void 0,P=O.functionCall.partialArgs!=null||O.functionCall.name!=null&&O.functionCall.willContinue===!0,L=O.functionCall.name==null&&O.functionCall.args==null&&O.functionCall.partialArgs==null&&O.functionCall.willContinue==null,me=O.functionCall.name!=null&&O.functionCall.args!=null&&O.functionCall.partialArgs==null,Q=O.functionCall.name!=null&&O.functionCall.args==null&&O.functionCall.partialArgs==null&&O.functionCall.willContinue!==!0;if(P){if(O.functionCall.name!=null){let de=(V=O.functionCall.id)!=null?V:f(),Ae=new T2;if(_.push({toolCallId:de,toolName:O.functionCall.name,accumulator:Ae,providerMetadata:W}),b.enqueue({type:"tool-input-start",id:de,toolName:O.functionCall.name,providerMetadata:W}),O.functionCall.partialArgs!=null){let Ke=O.functionCall.partialArgs,{textDelta:nt}=Ae.processPartialArgs(Ke);if(nt.length>0)b.enqueue({type:"tool-input-delta",id:de,delta:nt,providerMetadata:W});if(O.functionCall.willContinue!==!0&&Ke.every((At)=>At.willContinue!==!0))C(b)}}else if(O.functionCall.partialArgs!=null&&_.length>0){let de=_[_.length-1],Ae=O.functionCall.partialArgs,{textDelta:Ke}=de.accumulator.processPartialArgs(Ae);if(Ke.length>0)b.enqueue({type:"tool-input-delta",id:de.toolCallId,delta:Ke,providerMetadata:W});if(O.functionCall.willContinue!==!0&&Ae.every((nt)=>nt.willContinue!==!0))C(b)}}else if(L&&_.length>0)C(b);else if(me){let de=(q=O.functionCall.id)!=null?q:f(),Ae=O.functionCall.name,Ke=typeof O.functionCall.args==="string"?O.functionCall.args:JSON.stringify((ue=O.functionCall.args)!=null?ue:{});b.enqueue({type:"tool-input-start",id:de,toolName:Ae,providerMetadata:W}),b.enqueue({type:"tool-input-delta",id:de,delta:Ke,providerMetadata:W}),b.enqueue({type:"tool-input-end",id:de,providerMetadata:W}),b.enqueue({type:"tool-call",toolCallId:de,toolName:Ae,input:Ke,providerMetadata:W}),g=!0}else if(Q){let de=(ee=O.functionCall.id)!=null?ee:f(),Ae=O.functionCall.name;b.enqueue({type:"tool-input-start",id:de,toolName:Ae,providerMetadata:W}),b.enqueue({type:"tool-input-end",id:de,providerMetadata:W}),b.enqueue({type:"tool-call",toolCallId:de,toolName:Ae,input:"{}",providerMetadata:W}),g=!0}}}if(F.finishReason!=null)c={unified:tS({finishReason:F.finishReason,hasToolCalls:g}),raw:F.finishReason},d={[o]:{promptFeedback:(k=K.promptFeedback)!=null?k:null,groundingMetadata:m,urlContextMetadata:p,safetyRatings:(X=F.safetyRatings)!=null?X:null,usageMetadata:D!=null?D:null,finishMessage:(H=F.finishMessage)!=null?H:null,serviceTier:(J=u==null?void 0:u.serviceTier)!=null?J:null}}},flush(I){if(h!==null)I.enqueue({type:"text-end",id:h});if(v!==null)I.enqueue({type:"reasoning-end",id:v});I.enqueue({type:"finish",finishReason:c,usage:Z_(u),providerMetadata:d})}})),response:{headers:s},request:{body:t}}}};function rS({groundingMetadata:e,generateId:t}){var n,o,i,a,s,l;if(!(e==null?void 0:e.groundingChunks))return;let c=[];for(let u of e.groundingChunks)if(u.web!=null)c.push({type:"source",sourceType:"url",id:t(),url:u.web.uri,title:(n=u.web.title)!=null?n:void 0});else if(u.image!=null)c.push({type:"source",sourceType:"url",id:t(),url:u.image.sourceUri,title:(o=u.image.title)!=null?o:void 0});else if(u.retrievedContext!=null){let d=u.retrievedContext.uri,m=u.retrievedContext.fileSearchStore;if(d&&(d.startsWith("http://")||d.startsWith("https://")))c.push({type:"source",sourceType:"url",id:t(),url:d,title:(i=u.retrievedContext.title)!=null?i:void 0});else if(d){let p=(a=u.retrievedContext.title)!=null?a:"Unknown Document",f="application/octet-stream",g=void 0;if(d.endsWith(".pdf"))f="application/pdf",g=d.split("/").pop();else if(d.endsWith(".txt"))f="text/plain",g=d.split("/").pop();else if(d.endsWith(".docx"))f="application/vnd.openxmlformats-officedocument.wordprocessingml.document",g=d.split("/").pop();else if(d.endsWith(".doc"))f="application/msword",g=d.split("/").pop();else if(d.match(/\.(md|markdown)$/))f="text/markdown",g=d.split("/").pop();else g=d.split("/").pop();c.push({type:"source",sourceType:"document",id:t(),mediaType:f,title:p,filename:g})}else if(m){let p=(s=u.retrievedContext.title)!=null?s:"Unknown Document";c.push({type:"source",sourceType:"document",id:t(),mediaType:"application/octet-stream",title:p,filename:m.split("/").pop()})}}else if(u.maps!=null){if(u.maps.uri)c.push({type:"source",sourceType:"url",id:t(),url:u.maps.uri,title:(l=u.maps.title)!=null?l:void 0})}return c.length>0?c:void 0}var mS=()=>r.object({webSearchQueries:r.array(r.string()).nullish(),imageSearchQueries:r.array(r.string()).nullish(),retrievalQueries:r.array(r.string()).nullish(),searchEntryPoint:r.object({renderedContent:r.string()}).nullish(),groundingChunks:r.array(r.object({web:r.object({uri:r.string(),title:r.string().nullish()}).nullish(),image:r.object({sourceUri:r.string(),imageUri:r.string(),title:r.string().nullish(),domain:r.string().nullish()}).nullish(),retrievedContext:r.object({uri:r.string().nullish(),title:r.string().nullish(),text:r.string().nullish(),fileSearchStore:r.string().nullish()}).nullish(),maps:r.object({uri:r.string().nullish(),title:r.string().nullish(),text:r.string().nullish(),placeId:r.string().nullish()}).nullish()})).nullish(),groundingSupports:r.array(r.object({segment:r.object({startIndex:r.number().nullish(),endIndex:r.number().nullish(),text:r.string().nullish()}).nullish(),segment_text:r.string().nullish(),groundingChunkIndices:r.array(r.number()).nullish(),supportChunkIndices:r.array(r.number()).nullish(),confidenceScores:r.array(r.number()).nullish(),confidenceScore:r.array(r.number()).nullish()})).nullish(),retrievalMetadata:r.union([r.object({webDynamicRetrievalScore:r.number()}),r.object({})]).nullish()}),E2=r.object({jsonPath:r.string(),stringValue:r.string().nullish(),numberValue:r.number().nullish(),boolValue:r.boolean().nullish(),nullValue:r.unknown().nullish(),willContinue:r.boolean().nullish()}),gS=()=>r.object({parts:r.array(r.union([r.object({functionCall:r.object({id:r.string().nullish(),name:r.string().nullish(),args:r.unknown().nullish(),partialArgs:r.array(E2).nullish(),willContinue:r.boolean().nullish()}),thoughtSignature:r.string().nullish()}),r.object({inlineData:r.object({mimeType:r.string(),data:r.string()}),thought:r.boolean().nullish(),thoughtSignature:r.string().nullish()}),r.object({toolCall:r.object({toolType:r.string(),args:r.unknown().nullish(),id:r.string()}),thoughtSignature:r.string().nullish()}),r.object({toolResponse:r.object({toolType:r.string(),response:r.unknown().nullish(),id:r.string()}),thoughtSignature:r.string().nullish()}),r.object({executableCode:r.object({language:r.string(),code:r.string()}).nullish(),codeExecutionResult:r.object({outcome:r.string(),output:r.string().nullish()}).nullish(),text:r.string().nullish(),thought:r.boolean().nullish(),thoughtSignature:r.string().nullish()})])).nullish()}),rs=()=>r.object({category:r.string().nullish(),probability:r.string().nullish(),probabilityScore:r.number().nullish(),severity:r.string().nullish(),severityScore:r.number().nullish(),blocked:r.boolean().nullish()}),nS=r.array(r.object({modality:r.string(),tokenCount:r.number()})).nullish(),fS=r.object({cachedContentTokenCount:r.number().nullish(),thoughtsTokenCount:r.number().nullish(),promptTokenCount:r.number().nullish(),candidatesTokenCount:r.number().nullish(),totalTokenCount:r.number().nullish(),trafficType:r.string().nullish(),serviceTier:r.string().nullish(),promptTokensDetails:nS,candidatesTokensDetails:nS}),hS=()=>r.object({urlMetadata:r.array(r.object({retrievedUrl:r.string(),urlRetrievalStatus:r.string()})).nullish()}),A2=j(()=>M(r.object({candidates:r.array(r.object({content:gS().nullish().or(r.object({}).strict()),finishReason:r.string().nullish(),finishMessage:r.string().nullish(),safetyRatings:r.array(rs()).nullish(),groundingMetadata:mS().nullish(),urlContextMetadata:hS().nullish()})),usageMetadata:fS.nullish(),promptFeedback:r.object({blockReason:r.string().nullish(),safetyRatings:r.array(rs()).nullish()}).nullish()}))),P2=j(()=>M(r.object({candidates:r.array(r.object({content:gS().nullish(),finishReason:r.string().nullish(),finishMessage:r.string().nullish(),safetyRatings:r.array(rs()).nullish(),groundingMetadata:mS().nullish(),urlContextMetadata:hS().nullish()})).nullish(),usageMetadata:fS.nullish(),promptFeedback:r.object({blockReason:r.string().nullish(),safetyRatings:r.array(rs()).nullish()}).nullish()}))),M2=Te({id:"google.code_execution",inputSchema:r.object({language:r.string().describe("The programming language of the code."),code:r.string().describe("The code to be executed.")}),outputSchema:r.object({outcome:r.string().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:r.string().describe("The output from the code execution.")})}),j2=Ge({id:"google.enterprise_web_search",inputSchema:j(()=>M(r.object({})))}),O2=r.object({fileSearchStoreNames:r.array(r.string()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:r.number().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),metadataFilter:r.string().describe("Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression.").optional()}).passthrough(),N2=j(()=>M(O2)),D2=Ge({id:"google.file_search",inputSchema:N2}),z2=Ge({id:"google.google_maps",inputSchema:j(()=>M(r.object({})))}),yS=r.object({searchTypes:r.object({webSearch:r.object({}).optional(),imageSearch:r.object({}).optional()}).optional(),timeRangeFilter:r.object({startTime:r.string(),endTime:r.string()}).optional()}).passthrough(),U2=j(()=>M(yS)),$2=Ge({id:"google.google_search",inputSchema:U2}),L2=Ge({id:"google.url_context",inputSchema:j(()=>M(r.object({})))}),q2=Ge({id:"google.vertex_rag_store",inputSchema:r.object({ragCorpus:r.string(),topK:r.number().optional()})}),F2={googleSearch:$2,enterpriseWebSearch:j2,googleMaps:z2,urlContext:L2,fileSearch:D2,codeExecution:M2,vertexRagStore:q2},B2=class{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion="v3"}get maxImagesPerCall(){if(this.settings.maxImagesPerCall!=null)return this.settings.maxImagesPerCall;if(oS(this.modelId))return 10;return 4}get provider(){return this.config.provider}async doGenerate(e){if(oS(this.modelId))return this.doGenerateGemini(e);return this.doGenerateImagen(e)}async doGenerateImagen(e){var t,n,o;let{prompt:i,n:a=1,size:s,aspectRatio:l="1:1",seed:c,providerOptions:u,headers:d,abortSignal:m,files:p,mask:f}=e,g=[];if(p!=null&&p.length>0)throw Error("Google Generative AI does not support image editing with Imagen models. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.");if(f!=null)throw Error("Google Generative AI does not support image editing with masks. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.");if(s!=null)g.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."});if(c!=null)g.push({type:"unsupported",feature:"seed",details:"This model does not support the `seed` option through this provider."});let h=await Ue({provider:"google",providerOptions:u,schema:iS}),v=(o=(n=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:n.call(t))!=null?o:new Date,x={sampleCount:a};if(l!=null)x.aspectRatio=l;if(h){let{googleSearch:_,...C}=h;if(_!=null)g.push({type:"unsupported",feature:"googleSearch",details:"Google Search grounding is only supported on Gemini image models."});Object.assign(x,C)}let S={instances:[{prompt:i}],parameters:x},{responseHeaders:y,value:w}=await Ie({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:_e(await Se(this.config.headers),d),body:S,failedResponseHandler:or,successfulResponseHandler:xe(G2),abortSignal:m,fetch:this.config.fetch});return{images:w.predictions.map((_)=>_.bytesBase64Encoded),warnings:g,providerMetadata:{google:{images:w.predictions.map(()=>({}))}},response:{timestamp:v,modelId:this.modelId,headers:y}}}async doGenerateGemini(e){var t,n,o,i,a,s,l,c,u,d,m;let{prompt:p,n:f,size:g,aspectRatio:h,seed:v,providerOptions:x,headers:S,abortSignal:y,files:w,mask:_}=e,C=[];if(_!=null)throw Error("Gemini image models do not support mask-based image editing.");if(f!=null&&f>1)throw Error("Gemini image models do not support generating a set number of images per call. Use n=1 or omit the n parameter.");if(g!=null)C.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."});let I=[];if(p!=null)I.push({type:"text",text:p});if(w!=null&&w.length>0)for(let V of w)if(V.type==="url")I.push({type:"file",data:new URL(V.url),mediaType:"image/*"});else I.push({type:"file",data:typeof V.data==="string"?V.data:new Uint8Array(V.data),mediaType:V.mediaType});let b=[{role:"user",content:I}],E=await Ue({provider:"google",providerOptions:x,schema:iS}),{googleSearch:B,...R}=(t=x==null?void 0:x.google)!=null?t:{},z=await new pS(this.modelId,{provider:this.config.provider,baseURL:this.config.baseURL,headers:(n=this.config.headers)!=null?n:{},fetch:this.config.fetch,generateId:(o=this.config.generateId)!=null?o:Le}).doGenerate({prompt:b,seed:v,providerOptions:{google:{responseModalities:["IMAGE"],imageConfig:h?{aspectRatio:h}:void 0,...R}},tools:(E==null?void 0:E.googleSearch)!=null?[{type:"provider",id:"google.google_search",name:"google_search",args:E.googleSearch}]:void 0,headers:S,abortSignal:y}),N=(s=(a=(i=this.config._internal)==null?void 0:i.currentDate)==null?void 0:a.call(i))!=null?s:new Date,re=[];for(let V of z.content)if(V.type==="file"&&V.mediaType.startsWith("image/"))re.push(bt(V.data));let Y=(c=(l=z.providerMetadata)==null?void 0:l.google)!=null?c:{};return{images:re,warnings:C,providerMetadata:{google:{...Y,images:re.map(()=>({}))}},response:{timestamp:N,modelId:this.modelId,headers:(u=z.response)==null?void 0:u.headers},usage:z.usage?{inputTokens:z.usage.inputTokens.total,outputTokens:z.usage.outputTokens.total,totalTokens:((d=z.usage.inputTokens.total)!=null?d:0)+((m=z.usage.outputTokens.total)!=null?m:0)}:void 0}}};function oS(e){return e.startsWith("gemini-")}var G2=j(()=>M(r.object({predictions:r.array(r.object({bytesBase64Encoded:r.string()})).default([])}))),iS=j(()=>M(r.object({personGeneration:r.enum(["dont_allow","allow_adult","allow_all"]).nullish(),aspectRatio:r.enum(["1:1","3:4","4:3","9:16","16:9"]).nullish(),googleSearch:yS.optional()})));function J2(e){var t,n;return(n=(t=e.frameImages)==null?void 0:t.find((o)=>o.frameType==="first_frame"))==null?void 0:n.image}function H2(e){var t;return(t=J2(e))!=null?t:e.image}function W2(e){var t,n;return(n=(t=e.frameImages)==null?void 0:t.find((o)=>o.frameType==="last_frame"))==null?void 0:n.image}function V2(e){if(e.frameImages!=null&&e.frameImages.length>0)return;return e.inputReferences!=null&&e.inputReferences.length>0?e.inputReferences:void 0}function Su(e,t){if(e.type==="url"){if(e.url.startsWith("gs://"))return{gcsUri:e.url,mimeType:"image/png"};t.push({type:"unsupported",feature:"URL-based image input",details:"Google Generative AI video models require base64-encoded images or GCS URIs. URL will be ignored."});return}let n=typeof e.data==="string"?e.data:Nt(e.data);return{inlineData:{mimeType:e.mediaType||"image/png",data:n}}}function Z2(e){if(e.bytesBase64Encoded)return{inlineData:{mimeType:"image/png",data:e.bytesBase64Encoded}};if(e.gcsUri)return{gcsUri:e.gcsUri};return e}function K2(e,t){let n=Su(e,t);return n!=null?{image:n,referenceType:"asset"}:void 0}var Y2=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}get maxVideosPerCall(){return 4}async doGenerate(e){var t,n,o,i,a,s,l,c;let u=(o=(n=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:n.call(t))!=null?o:new Date,d=[],m=await Ue({provider:"google",providerOptions:e.providerOptions,schema:Q2}),p=[{}],f=p[0];if(e.prompt!=null)f.prompt=e.prompt;let g=H2(e);if(g!=null){let N=Su(g,d);if(N!=null)f.image=N}let h=W2(e);if(h!=null){let N=Su(h,d);if(N!=null)f.lastFrame=N}let v=V2(e);if(v!=null)f.referenceImages=v.flatMap((N)=>{let re=K2(N,d);return re!=null?[re]:[]});else if((m==null?void 0:m.referenceImages)!=null)f.referenceImages=m.referenceImages.map((N)=>Z2(N));let x={sampleCount:e.n};if(e.aspectRatio)x.aspectRatio=e.aspectRatio;if(e.resolution){let N={"1280x720":"720p","1920x1080":"1080p","3840x2160":"4k"};x.resolution=N[e.resolution]||e.resolution}if(e.duration)x.durationSeconds=e.duration;if(e.seed)x.seed=e.seed;if(m!=null){let N=m;if(N.personGeneration!==void 0&&N.personGeneration!==null)x.personGeneration=N.personGeneration;if(N.negativePrompt!==void 0&&N.negativePrompt!==null)x.negativePrompt=N.negativePrompt;for(let[re,Y]of Object.entries(N))if(!["pollIntervalMs","pollTimeoutMs","personGeneration","negativePrompt","referenceImages"].includes(re))x[re]=Y}let{value:S}=await Ie({url:`${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,headers:_e(await Se(this.config.headers),e.headers),body:{instances:p,parameters:x},successfulResponseHandler:xe(aS),failedResponseHandler:or,abortSignal:e.abortSignal,fetch:this.config.fetch}),y=S.name;if(!y)throw new ie({name:"GOOGLE_VIDEO_GENERATION_ERROR",message:"No operation name returned from API"});let w=(i=m==null?void 0:m.pollIntervalMs)!=null?i:1e4,_=(a=m==null?void 0:m.pollTimeoutMs)!=null?a:600000,C=Date.now(),I=S,b;while(!I.done){if(Date.now()-C>_)throw new ie({name:"GOOGLE_VIDEO_GENERATION_TIMEOUT",message:`Video generation timed out after ${_}ms`});if(await Jr(w),(s=e.abortSignal)==null?void 0:s.aborted)throw new ie({name:"GOOGLE_VIDEO_GENERATION_ABORTED",message:"Video generation request was aborted"});let{value:N,responseHeaders:re}=await Xt({url:`${this.config.baseURL}/${y}`,headers:_e(await Se(this.config.headers),e.headers),successfulResponseHandler:xe(aS),failedResponseHandler:or,abortSignal:e.abortSignal,fetch:this.config.fetch});I=N,b=re}if(I.error)throw new ie({name:"GOOGLE_VIDEO_GENERATION_FAILED",message:`Video generation failed: ${I.error.message}`});let E=I.response;if(!((l=E==null?void 0:E.generateVideoResponse)==null?void 0:l.generatedSamples)||E.generateVideoResponse.generatedSamples.length===0)throw new ie({name:"GOOGLE_VIDEO_GENERATION_ERROR",message:`No videos in response. Response: ${JSON.stringify(I)}`});let B=[],R=[],U=await Se(this.config.headers),z=U==null?void 0:U["x-goog-api-key"];for(let N of E.generateVideoResponse.generatedSamples)if((c=N.video)==null?void 0:c.uri){let re=z&&Xm(N.video.uri,this.config.baseURL)?`${N.video.uri}${N.video.uri.includes("?")?"&":"?"}key=${z}`:N.video.uri;B.push({type:"url",url:re,mediaType:"video/mp4"}),R.push({uri:N.video.uri})}if(B.length===0)throw new ie({name:"GOOGLE_VIDEO_GENERATION_ERROR",message:"No valid videos in response"});return{videos:B,warnings:d,response:{timestamp:u,modelId:this.modelId,headers:b},providerMetadata:{google:{videos:R}}}}},aS=r.object({name:r.string().nullish(),done:r.boolean().nullish(),error:r.object({code:r.number().nullish(),message:r.string(),status:r.string().nullish()}).nullish(),response:r.object({generateVideoResponse:r.object({generatedSamples:r.array(r.object({video:r.object({uri:r.string().nullish()}).nullish()})).nullish()}).nullish()}).nullish()}),Q2=j(()=>M(r.object({pollIntervalMs:r.number().positive().nullish(),pollTimeoutMs:r.number().positive().nullish(),personGeneration:r.enum(["dont_allow","allow_adult","allow_all"]).nullish(),negativePrompt:r.string().nullish(),referenceImages:r.array(r.object({bytesBase64Encoded:r.string().nullish(),gcsUri:r.string().nullish()})).nullish()}).passthrough()));function Iu(e){var t,n,o,i,a,s,l,c;if(e==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};let u=(t=e.total_input_tokens)!=null?t:0,d=(n=e.total_output_tokens)!=null?n:0,m=(o=e.total_thought_tokens)!=null?o:0,p=(i=e.total_cached_tokens)!=null?i:0;return{inputTokens:{total:(a=e.total_input_tokens)!=null?a:void 0,noCache:e.total_input_tokens==null?void 0:u-p,cacheRead:(s=e.total_cached_tokens)!=null?s:void 0,cacheWrite:void 0},outputTokens:{total:e.total_output_tokens==null&&e.total_thought_tokens==null?void 0:d+m,text:(l=e.total_output_tokens)!=null?l:void 0,reasoning:(c=e.total_thought_tokens)!=null?c:void 0},raw:e}}function vS(e){let t=e==null?void 0:e.output_tokens_by_modality;if(t==null)return;let n={};for(let o of t)if((o==null?void 0:o.modality)!=null&&o.tokens!=null)n[o.modality]=o.tokens;return Object.keys(n).length>0?n:void 0}var X2={pdf:"application/pdf",txt:"text/plain",md:"text/markdown",markdown:"text/markdown",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function bS(e){let t=e.toLowerCase();for(let[n,o]of Object.entries(X2))if(t.endsWith(`.${n}`))return o;return"application/octet-stream"}function _S(e){let t=e.split("/"),n=t[t.length-1];return n&&n.length>0?n:void 0}function ez({annotation:e,generateId:t}){var n,o,i,a,s;switch(e.type){case"url_citation":{let l=e;if(l.url==null||l.url.length===0)return;return{type:"source",sourceType:"url",id:t(),url:l.url,...l.title!=null?{title:l.title}:{}}}case"file_citation":{let l=e,c=(o=(n=l.url)!=null?n:l.document_uri)!=null?o:l.file_name;if(c==null||c.length===0)return;if(c.startsWith("http://")||c.startsWith("https://"))return{type:"source",sourceType:"url",id:t(),url:c,...l.file_name!=null?{title:l.file_name}:{}};let u=(i=l.file_name)!=null?i:_S(c),d=bS(c);return{type:"source",sourceType:"document",id:t(),mediaType:d,title:(s=(a=l.file_name)!=null?a:u)!=null?s:c,...u!=null?{filename:u}:{}}}case"place_citation":{let l=e;if(l.url==null||l.url.length===0)return;return{type:"source",sourceType:"url",id:t(),url:l.url,...l.name!=null?{title:l.name}:{}}}default:return}}function SS({block:e,generateId:t}){var n,o,i,a,s,l,c,u,d,m,p;let f=[];switch(e.type){case"url_context_result":{let g=(n=e.result)!=null?n:[];for(let h of g){if((h==null?void 0:h.url)==null||h.url.length===0)continue;if(h.status!=null&&h.status!=="success")continue;f.push({type:"source",sourceType:"url",id:t(),url:h.url})}break}case"google_search_result":{let g=(o=e.result)!=null?o:[];for(let h of g){let v=h==null?void 0:h.url;if(v==null||v.length===0)continue;f.push({type:"source",sourceType:"url",id:t(),url:v,...h.title!=null?{title:h.title}:{}})}break}case"google_maps_result":{let g=(i=e.result)!=null?i:[];for(let h of g)for(let v of(a=h.places)!=null?a:[]){if(v.url==null||v.url.length===0)continue;f.push({type:"source",sourceType:"url",id:t(),url:v.url,...v.name!=null?{title:v.name}:{}})}break}case"file_search_result":{let g=(s=e.result)!=null?s:[];for(let h of g){if(h==null||typeof h!=="object")continue;let v=h,x=(c=(l=v.url)!=null?l:v.document_uri)!=null?c:v.file_name;if(x==null||x.length===0)continue;if(x.startsWith("http://")||x.startsWith("https://")){f.push({type:"source",sourceType:"url",id:t(),url:x,...v.title!=null?{title:v.title}:{}});continue}let S=(u=v.file_name)!=null?u:_S(x),y=bS(x);f.push({type:"source",sourceType:"document",id:t(),mediaType:y,title:(p=(m=(d=v.title)!=null?d:v.file_name)!=null?m:S)!=null?p:x,...S!=null?{filename:S}:{}})}break}default:break}return f}function wu({annotations:e,generateId:t}){var n;if(e==null)return[];let o=new Set,i=[];for(let a of e){let s=ez({annotation:a,generateId:t});if(s==null)continue;let l=s.sourceType==="url"?`url:${s.url}`:`doc:${(n=s.filename)!=null?n:s.title}`;if(o.has(l))continue;o.add(l),i.push(s)}return i}function Cu({status:e,hasFunctionCall:t}){switch(e){case"completed":return t?"tool-calls":"stop";case"requires_action":return"tool-calls";case"failed":return"error";case"incomplete":return"length";case"cancelled":return"other";case"in_progress":default:return"other"}}var tz=new Set(["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"]),rz=new Set(["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"]);function nz(e){return e.replace(/_call$/,"")}function oz(e){return e.replace(/_result$/,"")}function sS({warnings:e,generateId:t,includeRawChunks:n,serviceTier:o}){let i,a,s=o,l,c=!1,u=new Map,d=new Set;function m(p){var f;return p.sourceType==="url"?`url:${p.url}`:`doc:${(f=p.filename)!=null?f:p.title}`}return new TransformStream({start(p){p.enqueue({type:"stream-start",warnings:e})},transform(p,f){var g,h,v,x,S,y,w,_,C,I,b,E,B,R,U,z,N,re,Y,V;if(n)f.enqueue({type:"raw",rawValue:p.rawValue});if(!p.success){l="failed",f.enqueue({type:"error",error:p.error});return}let q=p.value,ue=q.event_type;switch(ue){case"interaction.created":{let k=q.interaction;i=(k==null?void 0:k.id)!=null&&k.id.length>0?k.id:void 0;let X=k==null?void 0:k.created,H;if(typeof X==="string"){let J=new Date(X);if(!Number.isNaN(J.getTime()))H=J}f.enqueue({type:"response-metadata",...i!=null?{id:i}:{},modelId:k==null?void 0:k.model,...H?{timestamp:H}:{}});break}case"step.start":{let ee=q,k=ee.step,X=ee.index,H=`${i!=null?i:"interaction"}:${X}`,J=k==null?void 0:k.type;if(J==="model_output"){let K=(g=k==null?void 0:k.content)==null?void 0:g[0];if((K==null?void 0:K.type)==="text"){u.set(X,{kind:"text",id:H,emittedSourceKeys:new Set}),f.enqueue({type:"text-start",id:H});let D=wu({annotations:K.annotations,generateId:t});for(let F of D){let G=m(F);if(d.has(G))continue;d.add(G),f.enqueue(F)}}else if((K==null?void 0:K.type)==="image")u.set(X,{kind:"image",id:H,...K.data!=null?{data:K.data}:{},...K.mime_type!=null?{mimeType:K.mime_type}:{},...K.uri!=null?{uri:K.uri}:{}});else u.set(X,{kind:"pending_model_output",id:H})}else if(J==="thought"){let K=k==null?void 0:k.signature;if(u.set(X,{kind:"reasoning",id:H,...K!=null?{signature:K}:{}}),f.enqueue({type:"reasoning-start",id:H}),Array.isArray(k==null?void 0:k.summary)){for(let D of k.summary)if((D==null?void 0:D.type)==="text"&&typeof D.text==="string")f.enqueue({type:"reasoning-delta",id:H,delta:D.text})}}else if(J==="function_call"){let K=(h=k==null?void 0:k.id)!=null?h:H,D=(v=k==null?void 0:k.name)!=null?v:"unknown";c=!0;let F={kind:"function_call",id:H,toolCallId:K,toolName:D,argumentsAccum:"",...(k==null?void 0:k.signature)!=null?{signature:k.signature}:{}};u.set(X,F),f.enqueue({type:"tool-input-start",id:K,toolName:D})}else if(J!=null&&tz.has(J)){let K=J==="mcp_server_tool_call"?(x=k==null?void 0:k.name)!=null?x:"mcp_server_tool":nz(J),D=(S=k==null?void 0:k.id)!=null?S:H,F={kind:"builtin_tool_call",id:H,blockType:J,toolCallId:D,toolName:K,arguments:(y=k==null?void 0:k.arguments)!=null?y:{},callEmitted:!1};u.set(X,F)}else if(J!=null&&rz.has(J)){let K=J==="mcp_server_tool_result"?(w=k==null?void 0:k.name)!=null?w:"mcp_server_tool":oz(J),D=(_=k==null?void 0:k.call_id)!=null?_:H,F={kind:"builtin_tool_result",id:H,blockType:J,callId:D,toolName:K,result:(C=k==null?void 0:k.result)!=null?C:null,...(k==null?void 0:k.is_error)!=null?{isError:k.is_error}:{},resultEmitted:!1};u.set(X,F)}else u.set(X,{kind:"unknown",id:H});break}case"step.delta":{let ee=q,k=u.get(ee.index);if(k==null)break;let X=(I=ee.delta)==null?void 0:I.type;if(k.kind==="pending_model_output"){if(X==="text"||X==="text_annotation"||X==="text_annotation_delta"){let J={kind:"text",id:k.id,emittedSourceKeys:new Set};u.set(ee.index,J),k=J,f.enqueue({type:"text-start",id:J.id})}}if(X==="image"&&(k.kind==="pending_model_output"||k.kind==="text"||k.kind==="image")){let J=ee.delta,K={};if(i!=null)K.interactionId=i;let D=Object.keys(K).length>0?{google:K}:void 0;if((J==null?void 0:J.data)!=null&&J.data.length>0)f.enqueue({type:"file",mediaType:(b=J.mime_type)!=null?b:"image/png",data:J.data,...D?{providerMetadata:D}:{}});else if((J==null?void 0:J.uri)!=null&&J.uri.length>0){let F={google:{...i!=null?{interactionId:i}:{},imageUri:J.uri}};f.enqueue({type:"file",mediaType:(E=J.mime_type)!=null?E:"image/png",data:"",providerMetadata:F})}if(k.kind==="image")k.data=void 0,k.uri=void 0;break}if(X==="video"&&(k.kind==="pending_model_output"||k.kind==="text")){let J=ee.delta,K={};if(i!=null)K.interactionId=i;let D=Object.keys(K).length>0?{google:K}:void 0;if((J==null?void 0:J.data)!=null&&J.data.length>0)f.enqueue({type:"file",mediaType:(B=J.mime_type)!=null?B:"video/mp4",data:J.data,...D?{providerMetadata:D}:{}});else if((J==null?void 0:J.uri)!=null&&J.uri.length>0){let F={google:{...i!=null?{interactionId:i}:{},videoUri:J.uri}};f.enqueue({type:"file",mediaType:(R=J.mime_type)!=null?R:"video/mp4",data:"",providerMetadata:F})}break}let H=ee.delta;if(k.kind==="text"&&(H==null?void 0:H.type)==="text"){let J=(U=H.text)!=null?U:"";if(J.length>0)f.enqueue({type:"text-delta",id:k.id,delta:J})}else if(k.kind==="text"&&((H==null?void 0:H.type)==="text_annotation"||(H==null?void 0:H.type)==="text_annotation_delta")){let J=wu({annotations:H.annotations,generateId:t});for(let K of J){let D=m(K);if(d.has(D))continue;d.add(D),k.emittedSourceKeys.add(D),f.enqueue(K)}}else if(k.kind==="image"&&(H==null?void 0:H.type)==="image"){if(H.data!=null)k.data=H.data;if(H.mime_type!=null)k.mimeType=H.mime_type;if(H.uri!=null)k.uri=H.uri}else if(k.kind==="reasoning"){if((H==null?void 0:H.type)==="thought_summary"){let J=H.content;if((J==null?void 0:J.type)==="text"&&typeof J.text==="string")f.enqueue({type:"reasoning-delta",id:k.id,delta:J.text})}else if((H==null?void 0:H.type)==="thought_signature"){let J=H.signature;if(J!=null)k.signature=J}}else if(k.kind==="function_call"&&(H==null?void 0:H.type)==="arguments_delta"){let J=typeof H.arguments==="string"?H.arguments:"";if(J.length>0)k.argumentsAccum+=J,f.enqueue({type:"tool-input-delta",id:k.toolCallId,delta:J});if(H.id!=null)k.toolCallId=H.id;if(H.signature!=null)k.signature=H.signature;c=!0}else if(k.kind==="builtin_tool_call"&&(H==null?void 0:H.type)===k.blockType){if(H.id!=null)k.toolCallId=H.id;if(H.arguments!=null&&typeof H.arguments==="object")k.arguments=H.arguments;if(H.name!=null&&k.blockType==="mcp_server_tool_call")k.toolName=H.name}else if(k.kind==="builtin_tool_result"&&(H==null?void 0:H.type)===k.blockType){if(H.call_id!=null)k.callId=H.call_id;if(H.result!==void 0)k.result=H.result;if(H.is_error!=null)k.isError=H.is_error;if(H.name!=null&&k.blockType==="mcp_server_tool_result")k.toolName=H.name}break}case"step.stop":{let ee=q,k=u.get(ee.index);if(k==null)break;if(k.kind==="text"){let X=i!=null?{google:{interactionId:i}}:void 0;f.enqueue({type:"text-end",id:k.id,...X?{providerMetadata:X}:{}})}else if(k.kind==="reasoning"){let X={};if(k.signature!=null)X.signature=k.signature;if(i!=null)X.interactionId=i;let H=Object.keys(X).length>0?{google:X}:void 0;f.enqueue({type:"reasoning-end",id:k.id,...H?{providerMetadata:H}:{}})}else if(k.kind==="image"){let X={};if(i!=null)X.interactionId=i;let H=Object.keys(X).length>0?{google:X}:void 0;if(k.data!=null&&k.data.length>0)f.enqueue({type:"file",mediaType:(z=k.mimeType)!=null?z:"image/png",data:k.data,...H?{providerMetadata:H}:{}});else if(k.uri!=null&&k.uri.length>0){let J={google:{...i!=null?{interactionId:i}:{},imageUri:k.uri}};f.enqueue({type:"file",mediaType:(N=k.mimeType)!=null?N:"image/png",data:"",providerMetadata:J})}}else if(k.kind==="function_call"){let X=k.argumentsAccum.length>0?k.argumentsAccum:"{}";f.enqueue({type:"tool-input-end",id:k.toolCallId});let H={};if(k.signature!=null)H.signature=k.signature;if(i!=null)H.interactionId=i;let J=Object.keys(H).length>0?{google:H}:void 0;f.enqueue({type:"tool-call",toolCallId:k.toolCallId,toolName:k.toolName,input:X,...J?{providerMetadata:J}:{}})}else if(k.kind==="builtin_tool_call"&&!k.callEmitted)f.enqueue({type:"tool-call",toolCallId:k.toolCallId,toolName:k.toolName,input:JSON.stringify((re=k.arguments)!=null?re:{}),providerExecuted:!0}),k.callEmitted=!0;else if(k.kind==="builtin_tool_result"&&!k.resultEmitted){f.enqueue({type:"tool-result",toolCallId:k.callId,toolName:k.toolName,result:(Y=k.result)!=null?Y:null}),k.resultEmitted=!0;let X=SS({block:{type:k.blockType,call_id:k.callId,result:k.result},generateId:t});for(let H of X){let J=m(H);if(d.has(J))continue;d.add(J),f.enqueue(H)}}u.delete(ee.index);break}case"interaction.status_update":case"interaction.in_progress":case"interaction.requires_action":{let ee=q;if(ee.status!=null)l=ee.status;else if(ue==="interaction.requires_action")l="requires_action";else l="in_progress";break}case"interaction.completed":{let k=q.interaction;if((k==null?void 0:k.id)!=null&&k.id.length>0)i=k.id;if((k==null?void 0:k.status)!=null)l=k.status;if((k==null?void 0:k.usage)!=null)a=k.usage;if((k==null?void 0:k.service_tier)!=null)s=k.service_tier;break}case"error":{let ee=q;l="failed";let k=(V=ee.error)!=null?V:{message:"Unknown interaction error"};f.enqueue({type:"error",error:k});break}default:break}},flush(p){let f={unified:Cu({status:l,hasFunctionCall:c}),raw:l},g=vS(a),h={google:{...i!=null?{interactionId:i}:{},...s!=null?{serviceTier:s}:{},...g!=null?{outputTokensByModality:g}:{}}};p.enqueue({type:"finish",finishReason:f,usage:Iu(a),providerMetadata:h})}})}function wS(e){let t=e.indexOf("/");return t===-1?e:e.substring(0,t)}function ns(e){let t=e.indexOf("/");if(t===-1)return!1;let n=e.substring(t+1);return n.length>0&&n!=="*"}function iz({prompt:e,previousInteractionId:t,store:n,mediaResolution:o}){var i,a,s,l,c,u,d;let m=[],p=t!=null&&n===!1,f=t!=null&&n!==!1;if(p)m.push({type:"other",message:"google.interactions: providerOptions.google.previousInteractionId was set together with store: false. These are incoherent (the prior interaction cannot be referenced when nothing was stored on the server); the full history will be sent and previous_interaction_id will still be emitted."});let g=f?az({prompt:e,previousInteractionId:t}):e,h=[],v=[];for(let S of g)switch(S.role){case"system":{h.push(S.content);break}case"user":{let y=[];for(let _ of S.content)if(_.type==="text")y.push({type:"text",text:_.text});else if(_.type==="file"){let C=lS({part:_,warnings:m,mediaResolution:o});if(C!=null)y.push(C)}let w=cz(y);if(w.length>0)v.push({type:"user_input",content:w});break}case"assistant":{let y=[],w=()=>{if(y.length>0)v.push({type:"model_output",content:y}),y=[]};for(let _ of S.content)if(_.type==="text")y.push({type:"text",text:_.text});else if(_.type==="reasoning"){w();let C=(a=(i=_.providerOptions)==null?void 0:i.google)==null?void 0:a.signature;v.push({type:"thought",...C!=null?{signature:C}:{},summary:_.text.length>0?[{type:"text",text:_.text}]:void 0})}else if(_.type==="file"){let C=lS({part:_,warnings:m,mediaResolution:o});if(C!=null)y.push(C)}else if(_.type==="tool-call"){w();let C=(l=(s=_.providerOptions)==null?void 0:s.google)==null?void 0:l.signature,I=typeof _.input==="string"?sz(_.input):(c=_.input)!=null?c:{};v.push({type:"function_call",id:_.toolCallId,name:_.toolName,arguments:I,...C!=null?{signature:C}:{}})}else m.push({type:"other",message:`google.interactions: unsupported assistant content part type "${_.type}"; part dropped.`});w();break}case"tool":{let y=[];for(let w of S.content){if(w.type!=="tool-result"){m.push({type:"other",message:`google.interactions: unsupported tool message part type "${w.type}"; part dropped.`});continue}let _=lz({toolCallId:w.toolCallId,toolName:w.toolName,output:w.output,signature:(d=(u=w.providerOptions)==null?void 0:u.google)==null?void 0:d.signature,warnings:m});y.push(_)}if(y.length>0)v.push({type:"user_input",content:y});break}}let x=h.length>0?h.join(`
87
+
88
+ `):void 0;return{input:v,systemInstruction:x,warnings:m}}function lS({part:e,warnings:t,mediaResolution:n}){let o=wS(e.mediaType),i;switch(o){case"image":i="image";break;case"audio":i="audio";break;case"video":i="video";break;case"application":i="document";break;default:i=void 0}if(i==null){t.push({type:"other",message:`google.interactions: unsupported file media type "${e.mediaType}"; part dropped.`});return}let a=n!=null&&(i==="image"||i==="video")?{resolution:n}:{};if(e.data instanceof URL)return{type:i,uri:e.data.toString(),...ns(e.mediaType)?{mime_type:e.mediaType}:{},...a};if(!ns(e.mediaType)){t.push({type:"other",message:`google.interactions: inline file data requires a full IANA media type (e.g. "image/png"), got "${e.mediaType}"; part dropped.`});return}return{type:i,data:bt(e.data),mime_type:e.mediaType,...a}}function az({prompt:e,previousInteractionId:t}){let n=[],o=new Set;for(let i of e){if(i.role==="assistant"){if(i.content.some((s)=>{var l,c;return((c=(l=s.providerOptions)==null?void 0:l.google)==null?void 0:c.interactionId)===t})){for(let s of i.content)if(s.type==="tool-call")o.add(s.toolCallId);continue}n.push(i);continue}if(i.role==="tool"){let a=i.content.filter((s)=>{if(s.type!=="tool-result")return!0;return!o.has(s.toolCallId)});if(a.length===0)continue;n.push({...i,content:a});continue}n.push(i)}return n}function sz(e){try{let t=er(e);if(t!=null&&typeof t==="object"&&!Array.isArray(t))return t;return{value:t}}catch(t){return{value:e}}}function lz({toolCallId:e,toolName:t,output:n,signature:o,warnings:i}){var a;let s={type:"function_result",call_id:e,name:t,...o!=null?{signature:o}:{}};switch(n.type){case"text":return{...s,result:n.value};case"json":return{...s,result:JSON.stringify(n.value)};case"error-text":return{...s,is_error:!0,result:n.value};case"error-json":return{...s,is_error:!0,result:JSON.stringify(n.value)};case"execution-denied":return{...s,is_error:!0,result:(a=n.reason)!=null?a:"Tool execution denied by user."};case"content":{let l=[];for(let c of n.value)if(c.type==="text")l.push({type:"text",text:c.text});else if(c.type==="image-data"){let u=_u({part:{type:"file",mediaType:c.mediaType,data:c.data},warnings:i});if(u!=null)l.push(u)}else if(c.type==="image-url"){let u=_u({part:{type:"file",mediaType:"image/*",data:new URL(c.url)},warnings:i});if(u!=null)l.push(u)}else if(c.type==="file-data"||c.type==="file-url"){let u=c.type==="file-data"?c.mediaType:"application/*";if(wS(u)!=="image"){i.push({type:"other",message:`google.interactions: tool-result file with mediaType "${u}" is not supported (Interactions \`function_result.result\` accepts only text and image content); part dropped.`});continue}let m=_u({part:c.type==="file-data"?{type:"file",mediaType:c.mediaType,data:c.data}:{type:"file",mediaType:u,data:new URL(c.url)},warnings:i});if(m!=null)l.push(m)}else i.push({type:"other",message:`google.interactions: tool-result content part type "${c.type}" is not supported; part dropped.`});return{...s,result:l}}}}function _u({part:e,warnings:t}){if(e.data instanceof URL)return{type:"image",uri:e.data.toString(),...ns(e.mediaType)?{mime_type:e.mediaType}:{}};if(!ns(e.mediaType)){t.push({type:"other",message:`google.interactions: tool-result image part requires a full IANA media type (e.g. "image/png"), got "${e.mediaType}"; part dropped.`});return}return{type:"image",data:bt(e.data),mime_type:e.mediaType}}function cz(e){if(e.length<2)return e;let t=[];for(let n of e){let o=t[t.length-1];if(n.type==="text"&&o!=null&&o.type==="text"&&o.annotations==null&&n.annotations==null){let i={type:"text",text:`${o.text}
89
+
90
+ ${n.text}`};t[t.length-1]=i;continue}t.push(n)}return t}var ts=()=>r.object({modality:r.string().nullish(),tokens:r.number().nullish()}).loose(),xS=()=>r.object({total_input_tokens:r.number().nullish(),total_output_tokens:r.number().nullish(),total_thought_tokens:r.number().nullish(),total_cached_tokens:r.number().nullish(),total_tool_use_tokens:r.number().nullish(),total_tokens:r.number().nullish(),input_tokens_by_modality:r.array(ts()).nullish(),output_tokens_by_modality:r.array(ts()).nullish(),cached_tokens_by_modality:r.array(ts()).nullish(),tool_use_tokens_by_modality:r.array(ts()).nullish(),grounding_tool_count:r.array(r.object({type:r.string().nullish(),count:r.number().nullish()}).loose()).nullish()}).loose(),TS=()=>r.enum(["in_progress","requires_action","completed","failed","cancelled","incomplete"]),IS=()=>{let e=r.object({type:r.literal("url_citation"),url:r.string().nullish(),title:r.string().nullish(),start_index:r.number().nullish(),end_index:r.number().nullish()}).loose(),t=r.object({type:r.literal("file_citation"),file_name:r.string().nullish(),document_uri:r.string().nullish(),url:r.string().nullish(),page_number:r.number().nullish(),media_id:r.string().nullish(),start_index:r.number().nullish(),end_index:r.number().nullish(),custom_metadata:r.record(r.string(),r.unknown()).nullish()}).loose(),n=r.object({type:r.literal("place_citation"),name:r.string().nullish(),url:r.string().nullish(),place_id:r.string().nullish(),start_index:r.number().nullish(),end_index:r.number().nullish()}).loose();return r.union([e,t,n,r.object({type:r.string()}).loose()])},CS=()=>r.object({type:r.string(),text:r.string().nullish(),data:r.string().nullish(),mime_type:r.string().nullish()}).loose(),cS=()=>{let e=r.object({type:r.literal("text"),text:r.string(),annotations:r.array(IS()).nullish()}).loose(),t=r.object({type:r.literal("image"),data:r.string().nullish(),mime_type:r.string().nullish(),resolution:r.enum(["low","medium","high","ultra_high"]).nullish(),uri:r.string().nullish()}).loose(),n=r.object({type:r.literal("video"),data:r.string().nullish(),mime_type:r.string().nullish(),uri:r.string().nullish()}).loose();return r.union([e,t,n,r.object({type:r.string()}).loose()])},kS=["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"],RS=["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"],ES=()=>{let e=r.object({type:r.literal("user_input"),content:r.array(cS()).nullish()}).loose(),t=r.object({type:r.literal("model_output"),content:r.array(cS()).nullish()}).loose(),n=r.object({type:r.literal("function_call"),id:r.string(),name:r.string(),arguments:r.record(r.string(),r.unknown()).nullish(),signature:r.string().nullish()}).loose(),o=r.object({type:r.literal("thought"),signature:r.string().nullish(),summary:r.array(CS()).nullish()}).loose(),i=r.object({type:r.enum(kS),id:r.string(),arguments:r.record(r.string(),r.unknown()).nullish(),name:r.string().nullish(),server_name:r.string().nullish(),search_type:r.string().nullish(),signature:r.string().nullish()}).loose(),a=r.object({type:r.enum(RS),call_id:r.string(),result:r.unknown().nullish(),is_error:r.boolean().nullish(),name:r.string().nullish(),server_name:r.string().nullish(),signature:r.string().nullish()}).loose();return r.union([e,t,n,o,i,a,r.object({type:r.string()}).loose()])},xu=j(()=>M(r.object({id:r.string().nullish(),created:r.string().nullish(),updated:r.string().nullish(),status:TS(),model:r.string().nullish(),agent:r.string().nullish(),steps:r.array(ES()).nullish(),usage:xS().nullish(),service_tier:r.string().nullish(),previous_interaction_id:r.string().nullish(),response_modalities:r.array(r.string()).nullish()}).loose())),AS=j(()=>M((()=>{let e=TS(),t=IS(),n=CS(),o=r.object({event_type:r.literal("interaction.created"),event_id:r.string().nullish(),interaction:r.object({id:r.string().nullish(),created:r.string().nullish(),model:r.string().nullish(),agent:r.string().nullish(),status:e.nullish()}).loose()}).loose(),i=r.object({event_type:r.literal("step.start"),event_id:r.string().nullish(),index:r.number(),step:ES()}).loose(),a=r.object({type:r.literal("text"),text:r.string()}).loose(),s=r.object({type:r.literal("thought_summary"),content:n.nullish()}).loose(),l=r.object({type:r.literal("thought_signature"),signature:r.string().nullish()}).loose(),c=r.object({type:r.literal("arguments_delta"),arguments:r.string().nullish(),id:r.string().nullish(),signature:r.string().nullish()}).loose(),u=r.object({type:r.enum(["text_annotation_delta","text_annotation"]),annotations:r.array(t).nullish()}).loose(),d=r.object({type:r.literal("image"),data:r.string().nullish(),mime_type:r.string().nullish(),resolution:r.enum(["low","medium","high","ultra_high"]).nullish(),uri:r.string().nullish()}).loose(),m=r.object({type:r.literal("video"),data:r.string().nullish(),mime_type:r.string().nullish(),uri:r.string().nullish()}).loose(),p=r.object({type:r.enum(kS),id:r.string().nullish(),arguments:r.record(r.string(),r.unknown()).nullish(),name:r.string().nullish(),server_name:r.string().nullish(),search_type:r.string().nullish(),signature:r.string().nullish()}).loose(),f=r.object({type:r.enum(RS),call_id:r.string().nullish(),result:r.unknown().nullish(),is_error:r.boolean().nullish(),name:r.string().nullish(),server_name:r.string().nullish(),signature:r.string().nullish()}).loose(),g=r.object({type:r.string()}).loose(),h=r.union([a,d,m,s,l,c,u,p,f,g]),v=r.object({event_type:r.literal("step.delta"),event_id:r.string().nullish(),index:r.number(),delta:h}).loose(),x=r.object({event_type:r.literal("step.stop"),event_id:r.string().nullish(),index:r.number()}).loose(),S=r.object({event_type:r.literal("interaction.status_update"),event_id:r.string().nullish(),interaction_id:r.string().nullish(),status:e.nullish()}).loose(),y=r.object({event_type:r.literal("interaction.in_progress"),event_id:r.string().nullish(),interaction_id:r.string().nullish(),status:e.nullish()}).loose(),w=r.object({event_type:r.literal("interaction.requires_action"),event_id:r.string().nullish(),interaction_id:r.string().nullish(),status:e.nullish()}).loose(),_=r.object({event_type:r.literal("interaction.completed"),event_id:r.string().nullish(),interaction:r.object({id:r.string().nullish(),status:e.nullish(),usage:xS().nullish(),service_tier:r.string().nullish()}).loose()}).loose(),C=r.object({event_type:r.literal("error"),event_id:r.string().nullish(),error:r.object({code:r.string().nullish(),message:r.string().nullish()}).loose().nullish()}).loose(),I=r.object({event_type:r.string()}).loose();return r.union([o,i,v,x,S,y,w,_,C,I])})())),uz=j(()=>M(r.object({previousInteractionId:r.string().nullish(),store:r.boolean().nullish(),agent:r.string().nullish(),agentConfig:r.union([r.object({type:r.literal("dynamic")}).loose(),r.object({type:r.literal("deep-research"),thinkingSummaries:r.enum(["auto","none"]).nullish(),visualization:r.enum(["off","auto"]).nullish(),collaborativePlanning:r.boolean().nullish()})]).nullish(),thinkingLevel:r.enum(["minimal","low","medium","high"]).nullish(),thinkingSummaries:r.enum(["auto","none"]).nullish(),responseFormat:r.array(r.union([r.object({type:r.literal("text"),mimeType:r.string().nullish(),schema:r.unknown().nullish()}).loose(),r.object({type:r.literal("image"),mimeType:r.string().nullish(),aspectRatio:r.enum(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).nullish(),imageSize:r.enum(["1K","2K","4K","512"]).nullish()}).loose(),r.object({type:r.literal("audio"),mimeType:r.string().nullish()}).loose()])).nullish(),imageConfig:r.object({aspectRatio:r.enum(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).nullish(),imageSize:r.enum(["1K","2K","4K","512"]).nullish()}).nullish(),mediaResolution:r.enum(["low","medium","high","ultra_high"]).nullish(),responseModalities:r.array(r.enum(["text","image","audio","video","document"])).nullish(),serviceTier:r.enum(["flex","standard","priority"]).nullish(),systemInstruction:r.string().nullish(),signature:r.string().nullish(),interactionId:r.string().nullish(),pollingTimeoutMs:r.number().int().positive().nullish(),background:r.boolean().nullish(),environment:r.union([r.string(),r.object({type:r.literal("remote"),sources:r.array(r.union([r.object({type:r.literal("gcs"),source:r.string(),target:r.string().nullish()}),r.object({type:r.literal("repository"),source:r.string(),target:r.string().nullish()}),r.object({type:r.literal("inline"),content:r.string(),target:r.string()})])).nullish(),network:r.union([r.literal("disabled"),r.object({allowlist:r.array(r.object({domain:r.string(),transform:r.array(r.record(r.string(),r.string())).nullish()}))})]).nullish()})]).nullish()})));function $i({signature:e,interactionId:t}){let n={};if(e!=null)n.signature=e;if(t!=null)n.interactionId=t;return Object.keys(n).length>0?{providerMetadata:{google:n}}:{}}var dz=new Set(["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"]),pz=new Set(["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"]);function mz(e){return e.replace(/_call$/,"")}function gz(e){return e.replace(/_result$/,"")}function PS({steps:e,generateId:t,interactionId:n}){var o,i,a,s,l,c,u,d,m,p,f,g,h;let v=[],x=!1;if(e==null)return{content:v,hasFunctionCall:x};for(let S of e){if(S==null||typeof S!=="object")continue;let y=S.type;if(typeof y!=="string")continue;switch(y){case"user_input":break;case"model_output":{let w=(o=S.content)!=null?o:[];for(let _ of w){if(_==null||typeof _!=="object")continue;let C=_.type;if(C==="text"){let I=(i=_.text)!=null?i:"",b=_.annotations;v.push({type:"text",text:I,...$i({interactionId:n})});let E=wu({annotations:b,generateId:t});for(let B of E)v.push(B)}else if(C==="image"){let I=_;if(I.data!=null&&I.data.length>0)v.push({type:"file",mediaType:(a=I.mime_type)!=null?a:"image/png",data:I.data,...$i({interactionId:n})});else if(I.uri!=null&&I.uri.length>0)v.push({type:"file",mediaType:(s=I.mime_type)!=null?s:"image/png",data:"",providerMetadata:{google:{...n!=null?{interactionId:n}:{},imageUri:I.uri}}})}else if(C==="video"){let I=_;if(I.data!=null&&I.data.length>0)v.push({type:"file",mediaType:(l=I.mime_type)!=null?l:"video/mp4",data:I.data,...$i({interactionId:n})});else if(I.uri!=null&&I.uri.length>0)v.push({type:"file",mediaType:(c=I.mime_type)!=null?c:"video/mp4",data:"",providerMetadata:{google:{...n!=null?{interactionId:n}:{},videoUri:I.uri}}})}}break}case"thought":{let w=S,C=(Array.isArray(w.summary)?w.summary:[]).filter((I)=>(I==null?void 0:I.type)==="text"&&typeof I.text==="string").map((I)=>I.text).join(`
91
+ `);v.push({type:"reasoning",text:C,...$i({signature:w.signature,interactionId:n})});break}case"function_call":{x=!0;let w=S;v.push({type:"tool-call",toolCallId:w.id,toolName:w.name,input:JSON.stringify((u=w.arguments)!=null?u:{}),...$i({signature:w.signature,interactionId:n})});break}default:{if(dz.has(y)){let w=S,_=y==="mcp_server_tool_call"?(d=w.name)!=null?d:"mcp_server_tool":mz(y),C=JSON.stringify((m=w.arguments)!=null?m:{});v.push({type:"tool-call",toolCallId:(p=w.id)!=null?p:t(),toolName:_,input:C,providerExecuted:!0})}else if(pz.has(y)){let w=S,_=y==="mcp_server_tool_result"?(f=w.name)!=null?f:"mcp_server_tool":gz(y);v.push({type:"tool-result",toolCallId:(g=w.call_id)!=null?g:t(),toolName:_,result:(h=w.result)!=null?h:null});let C=SS({block:S,generateId:t});for(let I of C)v.push(I)}break}}}return{content:v,hasFunctionCall:x}}var fz=()=>globalThis.fetch;async function MS({baseURL:e,interactionId:t,headers:n,fetch:o=fz()}){if(t==null||t.length===0)return;let i=`${e}/interactions/${encodeURIComponent(t)}/cancel`;try{let a=await o(i,{method:"POST",headers:it(_e({"Content-Type":"application/json"},n),lo()),body:"{}"});try{await a.text()}catch(s){}}catch(a){}}var hz=new Set(["completed","failed","cancelled","incomplete"]);function Tu(e){return e!=null&&hz.has(e)}var yz=1000,vz=1e4,bz=1800000;async function _z({baseURL:e,interactionId:t,headers:n,fetch:o,abortSignal:i,initialDelayMs:a=yz,maxDelayMs:s=vz,timeoutMs:l=bz}){if(t==null||t.length===0)throw Error("google.interactions: cannot poll a background interaction without an id. The POST response did not include an interaction id.");let c=Date.now(),u=a,d=`${e}/interactions/${encodeURIComponent(t)}`,m=()=>MS({baseURL:e,interactionId:t,headers:n,fetch:o});try{while(!0){if(i==null?void 0:i.aborted)throw await m(),new DOMException("Polling was aborted","AbortError");if(Date.now()-c>l)throw Error(`google.interactions: timed out polling interaction ${t} after ${l}ms.`);await Jr(u,{abortSignal:i});let{value:p,rawValue:f,responseHeaders:g}=await Xt({url:d,headers:n,failedResponseHandler:or,successfulResponseHandler:xe(xu),abortSignal:i,fetch:o});if(Tu(p.status))return{response:p,rawResponse:f,responseHeaders:g};u=Math.min(u*2,s)}}catch(p){if(Yt(p))await m();throw p}}function Sz({tools:e,toolChoice:t}){var n,o,i,a;let s=[],l=(e==null?void 0:e.length)?e:void 0;if(l==null)return{tools:void 0,toolChoice:void 0,toolWarnings:s};let c=[];for(let m of l){if(m.type==="function"){c.push({type:"function",name:m.name,description:(n=m.description)!=null?n:"",parameters:m.inputSchema});continue}if(m.type==="provider"){let p=(o=m.args)!=null?o:{};switch(m.id){case"google.google_search":{let f=p.searchTypes,g;if(f!=null&&typeof f==="object"){let h=[];if(f.webSearch!=null)h.push("web_search");if(f.imageSearch!=null)h.push("image_search");if(h.length>0)g=h}c.push({type:"google_search",...g!=null?{search_types:g}:{}});break}case"google.code_execution":{c.push({type:"code_execution"});break}case"google.url_context":{c.push({type:"url_context"});break}case"google.file_search":{c.push({type:"file_search",...p.fileSearchStoreNames!=null?{file_search_store_names:p.fileSearchStoreNames}:{},...p.topK!=null?{top_k:p.topK}:{},...p.metadataFilter!=null?{metadata_filter:p.metadataFilter}:{}});break}case"google.google_maps":{c.push({type:"google_maps",...p.latitude!=null?{latitude:p.latitude}:{},...p.longitude!=null?{longitude:p.longitude}:{},...p.enableWidget!=null?{enable_widget:p.enableWidget}:{}});break}case"google.computer_use":{c.push({type:"computer_use",environment:(i=p.environment)!=null?i:"browser",...p.excludedPredefinedFunctions!=null?{excludedPredefinedFunctions:p.excludedPredefinedFunctions}:{}});break}case"google.mcp_server":{c.push({type:"mcp_server",...p.name!=null?{name:p.name}:{},...p.url!=null?{url:p.url}:{},...p.headers!=null?{headers:p.headers}:{},...p.allowedTools!=null?{allowed_tools:p.allowedTools}:{}});break}case"google.retrieval":{let f=(a=p.vertexAiSearchConfig)!=null?a:void 0;c.push({type:"retrieval",...p.retrievalTypes!=null?{retrieval_types:p.retrievalTypes}:{retrieval_types:["vertex_ai_search"]},...f!=null?{vertex_ai_search_config:f}:{}});break}default:{s.push({type:"unsupported",feature:`provider-defined tool ${m.id}`,details:`provider-defined tool ${m.id} is not supported by google.interactions; tool dropped.`});break}}continue}s.push({type:"unsupported",feature:`tool of type ${m.type}`,details:"Only function tools and google.* provider-defined tools are supported by google.interactions; tool dropped."})}let u=c.some((m)=>m.type==="function"),d;if(t!=null&&u)switch(t.type){case"auto":d="auto";break;case"required":d="any";break;case"none":d="none";break;case"tool":d={allowed_tools:{mode:"validated",tools:[t.toolName]}};break}return{tools:c.length>0?c:void 0,toolChoice:d,toolWarnings:s}}var wz=3,xz=500;function Tz({baseURL:e,interactionId:t,headers:n,fetch:o,abortSignal:i,maxRetries:a=wz,retryDelayMs:s=xz}){if(t.length===0)throw Error("google.interactions: cannot stream a background interaction without an id.");let l={...n,accept:"text/event-stream"},c,u=!1,d=0,m=!1,p,f=new AbortController,g=()=>f.abort();if(i!=null)if(i.aborted)f.abort();else i.addEventListener("abort",g,{once:!0});let h=f.signal;function v(){let S=`${e}/interactions/${encodeURIComponent(t)}`,y=new URLSearchParams({stream:"true"});if(c!=null)y.set("last_event_id",c);return`${S}?${y.toString()}`}async function x(){let{value:S}=await Xt({url:v(),headers:l,failedResponseHandler:or,successfulResponseHandler:Dt(AS),abortSignal:h,fetch:o});return S.getReader()}return new ReadableStream({async start(S){try{while(!u&&!h.aborted){if(p==null)try{p=await x(),m=!1}catch(y){if(Yt(y)||h.aborted){S.error(y);return}if(d++,d>=a){S.error(y);return}await Jr(s*d,{abortSignal:h});continue}try{let{done:y,value:w}=await p.read();if(y){if(p=void 0,u)break;if(!m){if(d++,d>=a){S.error(Error("google.interactions: SSE stream closed without producing any events."));return}await Jr(s*d,{abortSignal:h})}else d=0;continue}if(m=!0,w.success){let _=w.value;if(typeof _.event_id==="string"&&_.event_id.length>0)c=_.event_id;if(_.event_type==="interaction.completed"||_.event_type==="error")u=!0}S.enqueue(w)}catch(y){if(Yt(y)||h.aborted){S.error(y);return}if(p=void 0,d++,d>=a){S.error(y);return}await Jr(s*d,{abortSignal:h})}}S.close()}catch(y){S.error(y)}finally{if(i!=null)i.removeEventListener("abort",g);if(p==null||p.cancel().catch(()=>{}),p=void 0,h.aborted&&!u)await MS({baseURL:e,interactionId:t,headers:n,fetch:o})}},cancel(){f.abort(),p==null||p.cancel().catch(()=>{}),p=void 0}})}function Iz({response:e,warnings:t,generateId:n,includeRawChunks:o,headerServiceTier:i}){return new ReadableStream({start(a){var s,l,c;a.enqueue({type:"stream-start",warnings:t});let u=typeof e.id==="string"&&e.id.length>0?e.id:void 0,d,m=e.created;if(typeof m==="string"){let y=new Date(m);if(!Number.isNaN(y.getTime()))d=y}if(a.enqueue({type:"response-metadata",...u!=null?{id:u}:{},modelId:(s=e.model)!=null?s:void 0,...d?{timestamp:d}:{}}),o)a.enqueue({type:"raw",rawValue:e});let{content:p,hasFunctionCall:f}=PS({steps:(l=e.steps)!=null?l:null,generateId:n,interactionId:u}),g=0,h=()=>`${u!=null?u:"agent"}:${g++}`;for(let y of p)switch(y.type){case"text":{let w=h(),_=y.providerMetadata;if(a.enqueue({type:"text-start",id:w}),y.text.length>0)a.enqueue({type:"text-delta",id:w,delta:y.text});a.enqueue({type:"text-end",id:w,..._?{providerMetadata:_}:{}});break}case"reasoning":{let w=h(),_=y.providerMetadata;if(a.enqueue({type:"reasoning-start",id:w}),y.text.length>0)a.enqueue({type:"reasoning-delta",id:w,delta:y.text});a.enqueue({type:"reasoning-end",id:w,..._?{providerMetadata:_}:{}});break}case"tool-call":{let w=y.providerMetadata;a.enqueue({type:"tool-input-start",id:y.toolCallId,toolName:y.toolName,...y.providerExecuted?{providerExecuted:y.providerExecuted}:{}}),a.enqueue({type:"tool-input-delta",id:y.toolCallId,delta:y.input}),a.enqueue({type:"tool-input-end",id:y.toolCallId}),a.enqueue({type:"tool-call",toolCallId:y.toolCallId,toolName:y.toolName,input:y.input,...y.providerExecuted?{providerExecuted:y.providerExecuted}:{},...w?{providerMetadata:w}:{}});break}case"tool-result":{a.enqueue({type:"tool-result",toolCallId:y.toolCallId,toolName:y.toolName,result:y.result});break}case"source":case"file":{a.enqueue(y);break}default:break}let v=(c=e.service_tier)!=null?c:i,x={unified:Cu({status:e.status,hasFunctionCall:f}),raw:e.status},S={google:{...u!=null?{interactionId:u}:{},...v!=null?{serviceTier:v}:{}}};a.enqueue({type:"finish",finishReason:x,usage:Iu(e.usage),providerMetadata:S}),a.close()}})}var Cz=class{constructor(e,t){if(this.specificationVersion="v3",typeof e==="string")this.modelId=e,this.agent=void 0;else if("managedAgent"in e)this.modelId=e.managedAgent,this.agent=e.managedAgent;else this.modelId=e.agent,this.agent=e.agent;this.config=t}get provider(){return this.config.provider}get supportedUrls(){if(this.config.supportedUrls)return this.config.supportedUrls();return{"image/*":[/^https?:\/\/.+/],"application/pdf":[/^https?:\/\/.+/],"audio/*":[/^https?:\/\/.+/],"video/*":[/^https?:\/\/(www\.)?youtube\.com\/watch\?v=.+/,/^https?:\/\/youtu\.be\/.+/,/^gs:\/\/.+/]}}async getArgs(e){var t,n,o,i,a,s,l,c,u,d,m,p,f,g,h,v,x,S,y,w,_,C,I,b,E,B;let R=[],U=await Ue({provider:"google",providerOptions:e.providerOptions,schema:uz}),z=this.agent!=null,N=e.tools!=null&&e.tools.length>0,re,Y;if(N&&z)R.push({type:"other",message:"google.interactions: tools are not supported when an agent is set; tools will be omitted from the request body."});else if(N){let F=Sz({tools:e.tools,toolChoice:e.toolChoice});re=F.tools,Y=F.toolChoice,R.push(...F.toolWarnings)}let V=[];if(((t=e.responseFormat)==null?void 0:t.type)==="json")if(z)R.push({type:"other",message:"google.interactions: structured output (responseFormat) is not supported when an agent is set; responseFormat will be ignored."});else{let F={type:"text",mime_type:"application/json",...e.responseFormat.schema!=null?{schema:e.responseFormat.schema}:{}};V.push(F)}if((U==null?void 0:U.responseFormat)!=null){for(let F of U.responseFormat)if(F.type==="text")V.push(Vr({type:"text",mime_type:(n=F.mimeType)!=null?n:void 0,schema:(o=F.schema)!=null?o:void 0}));else if(F.type==="image")V.push(Vr({type:"image",mime_type:(i=F.mimeType)!=null?i:void 0,aspect_ratio:(a=F.aspectRatio)!=null?a:void 0,image_size:(s=F.imageSize)!=null?s:void 0}));else if(F.type==="audio")V.push(Vr({type:"audio",mime_type:(l=F.mimeType)!=null?l:void 0}))}let{input:q,systemInstruction:ue,warnings:ee}=iz({prompt:e.prompt,previousInteractionId:(c=U==null?void 0:U.previousInteractionId)!=null?c:void 0,store:(u=U==null?void 0:U.store)!=null?u:void 0,mediaResolution:(d=U==null?void 0:U.mediaResolution)!=null?d:void 0});R.push(...ee);let k=ue,X=(m=U==null?void 0:U.systemInstruction)!=null?m:void 0;if(k!=null&&X!=null)R.push({type:"other",message:"google.interactions: both AI SDK system message and providerOptions.google.systemInstruction were set; using the AI SDK system message."});else if(k==null&&X!=null)k=X;let H;if(z){let F=[];if(e.temperature!=null)F.push("temperature");if(e.topP!=null)F.push("topP");if(e.seed!=null)F.push("seed");if(e.stopSequences!=null&&e.stopSequences.length>0)F.push("stopSequences");if(e.maxOutputTokens!=null)F.push("maxOutputTokens");if((U==null?void 0:U.thinkingLevel)!=null)F.push("thinkingLevel");if((U==null?void 0:U.thinkingSummaries)!=null)F.push("thinkingSummaries");if((U==null?void 0:U.imageConfig)!=null)F.push("imageConfig");if(F.length>0)R.push({type:"other",message:`google.interactions: ${F.join(", ")} ${F.length===1?"is":"are"} not supported when an agent is set; use providerOptions.google.agentConfig instead. Dropped from the request body.`});H=void 0}else if(H=Vr({temperature:(p=e.temperature)!=null?p:void 0,top_p:(f=e.topP)!=null?f:void 0,seed:(g=e.seed)!=null?g:void 0,stop_sequences:e.stopSequences!=null&&e.stopSequences.length>0?e.stopSequences:void 0,max_output_tokens:(h=e.maxOutputTokens)!=null?h:void 0,thinking_level:(v=U==null?void 0:U.thinkingLevel)!=null?v:void 0,thinking_summaries:(x=U==null?void 0:U.thinkingSummaries)!=null?x:void 0,tool_choice:Y}),(U==null?void 0:U.imageConfig)!=null){let F=V.some((G)=>G.type==="image");if(R.push({type:"other",message:F?"google.interactions: providerOptions.google.imageConfig is deprecated and was ignored because providerOptions.google.responseFormat already supplies an image entry. Use responseFormat exclusively.":'google.interactions: providerOptions.google.imageConfig is deprecated. Use providerOptions.google.responseFormat with a { type: "image", ... } entry instead.'}),!F)V.push({type:"image",mime_type:"image/png",...U.imageConfig.aspectRatio!=null?{aspect_ratio:U.imageConfig.aspectRatio}:{},...U.imageConfig.imageSize!=null?{image_size:U.imageConfig.imageSize}:{}})}let J;if(z&&(U==null?void 0:U.agentConfig)!=null){let F=U.agentConfig;if(F.type==="deep-research")J=Vr({type:"deep-research",thinking_summaries:(S=F.thinkingSummaries)!=null?S:void 0,visualization:(y=F.visualization)!=null?y:void 0,collaborative_planning:(w=F.collaborativePlanning)!=null?w:void 0});else if(F.type==="dynamic")J={type:"dynamic"}}let K;if((U==null?void 0:U.environment)!=null)if(!z)R.push({type:"other",message:"google.interactions: environment is only supported when an agent is set; environment will be omitted from the request body."});else if(typeof U.environment==="string")K=U.environment;else{let F=U.environment,G=(_=F.sources)==null?void 0:_.map((A)=>{var O;if(A.type==="inline")return{type:"inline",content:A.content,target:A.target};return Vr({type:A.type,source:A.source,target:(O=A.target)!=null?O:void 0})}),Z;if(F.network==="disabled")Z="disabled";else if(F.network!=null)Z={allowlist:F.network.allowlist.map((A)=>{var O;return Vr({domain:A.domain,transform:(O=A.transform)!=null?O:void 0})})};K=Vr({type:"remote",sources:G!=null&&G.length>0?G:void 0,network:Z})}return{args:Vr({...z?{agent:this.agent}:{model:this.modelId},input:q,system_instruction:k,tools:re,response_format:V.length>0?V:void 0,response_modalities:(U==null?void 0:U.responseModalities)!=null?U.responseModalities:void 0,previous_interaction_id:(C=U==null?void 0:U.previousInteractionId)!=null?C:void 0,service_tier:(I=U==null?void 0:U.serviceTier)!=null?I:void 0,store:(b=U==null?void 0:U.store)!=null?b:void 0,generation_config:H!=null&&Object.keys(H).length>0?H:void 0,agent_config:J,environment:K,background:(E=U==null?void 0:U.background)!=null?E:void 0}),warnings:R,isAgent:z,isBackground:(U==null?void 0:U.background)===!0,pollingTimeoutMs:(B=U==null?void 0:U.pollingTimeoutMs)!=null?B:void 0}}async doGenerate(e){var t,n,o,i,a,s;let{args:l,warnings:c,isAgent:u,pollingTimeoutMs:d}=await this.getArgs(e),m=`${this.config.baseURL}/interactions`,p=_e(uS,this.config.headers?await Se(this.config.headers):void 0,e.headers),f=await Ie({url:m,headers:p,body:l,failedResponseHandler:or,successfulResponseHandler:xe(xu),abortSignal:e.abortSignal,fetch:this.config.fetch}),{responseHeaders:g,value:h,rawValue:v}=f;if(u&&!Tu(h.status)){let E=await _z({baseURL:this.config.baseURL,interactionId:h.id,headers:p,fetch:this.config.fetch,abortSignal:e.abortSignal,timeoutMs:d});h=E.response,v=E.rawResponse,g=(t=E.responseHeaders)!=null?t:g}let x=typeof h.id==="string"&&h.id.length>0?h.id:void 0,{content:S,hasFunctionCall:y}=PS({steps:(n=h.steps)!=null?n:null,generateId:(o=this.config.generateId)!=null?o:Le,interactionId:x}),w={unified:Cu({status:h.status,hasFunctionCall:y}),raw:h.status},_=(a=(i=h.service_tier)!=null?i:g==null?void 0:g["x-gemini-service-tier"])!=null?a:void 0,C=vS(h.usage),I={google:{...x!=null?{interactionId:x}:{},..._!=null?{serviceTier:_}:{},...C!=null?{outputTokensByModality:C}:{}}},b;if(typeof h.created==="string"){let E=new Date(h.created);if(!Number.isNaN(E.getTime()))b=E}return{content:S,finishReason:w,usage:Iu(h.usage),warnings:c,providerMetadata:I,request:{body:l},response:{headers:g,body:v,...x!=null?{id:x}:{},...b?{timestamp:b}:{},modelId:(s=h.model)!=null?s:void 0}}}async doStream(e){var t;let{args:n,warnings:o,isBackground:i,pollingTimeoutMs:a}=await this.getArgs(e),s=`${this.config.baseURL}/interactions`,l=_e(uS,this.config.headers?await Se(this.config.headers):void 0,e.headers);if(i)return this.doStreamBackground({args:n,warnings:o,url:s,mergedHeaders:l,options:e,pollingTimeoutMs:a});let c={...n,stream:!0},{responseHeaders:u,value:d}=await Ie({url:s,headers:l,body:c,failedResponseHandler:or,successfulResponseHandler:Dt(AS),abortSignal:e.abortSignal,fetch:this.config.fetch}),m=u==null?void 0:u["x-gemini-service-tier"],p=sS({warnings:o,generateId:(t=this.config.generateId)!=null?t:Le,includeRawChunks:e.includeRawChunks,serviceTier:m});return{stream:d.pipeThrough(p),request:{body:c},response:{headers:u}}}async doStreamBackground({args:e,warnings:t,url:n,mergedHeaders:o,options:i,pollingTimeoutMs:a}){var s,l;let c=await Ie({url:n,headers:o,body:e,failedResponseHandler:or,successfulResponseHandler:xe(xu),abortSignal:i.abortSignal,fetch:this.config.fetch}),{responseHeaders:u,value:d}=c,m=d.id;if(m==null||m.length===0)throw Error("google.interactions: background POST response did not include an interaction id; cannot stream the result.");let p=u==null?void 0:u["x-gemini-service-tier"];if(Tu(d.status))return{stream:Iz({response:d,warnings:t,generateId:(s=this.config.generateId)!=null?s:Le,includeRawChunks:i.includeRawChunks,headerServiceTier:p}),request:{body:e},response:{headers:u}};let f=Tz({baseURL:this.config.baseURL,interactionId:m,headers:o,fetch:this.config.fetch,abortSignal:i.abortSignal}),g=sS({warnings:t,generateId:(l=this.config.generateId)!=null?l:Le,includeRawChunks:i.includeRawChunks,serviceTier:p});return{stream:f.pipeThrough(g),request:{body:e},response:{headers:u}}}},uS={"Api-Revision":"2026-05-20"};function Vr(e){let t={};for(let[n,o]of Object.entries(e)){if(o===void 0)continue;t[n]=o}return t}var kz=["text/html","text/css","text/plain","text/xml","text/csv","text/rtf","text/javascript","application/json","application/pdf","image/bmp","image/jpeg","image/png","image/webp","video/mp4","video/mpeg","video/quicktime","video/avi","video/x-flv","video/mpg","video/webm","video/wmv","video/3gpp"],Rz=/^https:\/\/.*$/;function Ez(e){return/(^|\/)gemini-/.test(e)&&!/(^|\/)gemini-2\.0/.test(e)}function os(e={}){var t,n;let o=(t=mn(e.baseURL))!=null?t:"https://generativelanguage.googleapis.com/v1beta",i=(n=e.name)!=null?n:"google.generative-ai",a=()=>it({"x-goog-api-key":co({apiKey:e.apiKey,environmentVariableName:"GOOGLE_GENERATIVE_AI_API_KEY",description:"Google Generative AI"}),...e.headers},`ai-sdk/google/${l2}`),s=(p)=>{var f;return new pS(p,{provider:i,baseURL:o,headers:a,generateId:(f=e.generateId)!=null?f:Le,supportedUrls:()=>({"*":[new RegExp(`^${o}/files/.*$`),new RegExp("^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$"),new RegExp("^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$")],...Ez(p)?Object.fromEntries(kz.map((g)=>[g,[Rz]])):{}}),fetch:e.fetch})},l=(p)=>new p2(p,{provider:i,baseURL:o,headers:a,fetch:e.fetch}),c=(p,f={})=>new B2(p,f,{provider:i,baseURL:o,headers:a,fetch:e.fetch}),u=(p)=>{var f;return new Y2(p,{provider:i,baseURL:o,headers:a,fetch:e.fetch,generateId:(f=e.generateId)!=null?f:Le})},d=(p)=>{var f;return new Cz(p,{provider:`${i}.interactions`,baseURL:o,headers:a,generateId:(f=e.generateId)!=null?f:Le,fetch:e.fetch})},m=function(p){if(new.target)throw Error("The Google Generative AI model function cannot be called with the new keyword.");return s(p)};return m.specificationVersion="v3",m.languageModel=s,m.chat=s,m.generativeAI=s,m.embedding=l,m.embeddingModel=l,m.textEmbedding=l,m.textEmbeddingModel=l,m.image=c,m.imageModel=c,m.video=u,m.videoModel=u,m.interactions=d,m.tools=F2,m}var jK=os();function ku(e){let t=e.model?ou(e.model):void 0,n=e.apiKey,o=e.imageApiKey??e.apiKey;return{anthropicProvider:n?uu({apiKey:n}):__,openaiProvider:t==="openai"&&n?_o({apiKey:n}):o?_o({apiKey:o}):null,googleProvider:t==="google"&&n?os({apiKey:n}):o?os({apiKey:o}):null}}function jS(e,t){let n=Ni(t);if(n.provider==="openai"&&e.openaiProvider)return e.openaiProvider(n.modelId);if(n.provider==="google"&&e.googleProvider)return e.googleProvider(n.modelId);return e.anthropicProvider(n.modelId)}function OS(e){return e.openaiProvider!==null||e.googleProvider!==null}function NS(e,t,n){if(t==="openai"){if(!e.openaiProvider)throw Error("Image generation not available: no OpenAI API key configured");return e.openaiProvider.image(n)}if(t==="google"){if(!e.googleProvider)throw Error("Image generation not available: no Google API key configured");return e.googleProvider.image(n)}throw Error(`Image generation not supported for provider: ${t}`)}async function DS(e,t,n,o,i){let a=n?.signal;a?.throwIfAborted();let{provider:s,modelId:l}=iu(t),c=NS(o,s,l);i.debug("Generating image",{prompt:e.slice(0,100),provider:s,model:l});try{let u=n?.aspectRatio??"16:9",m=(s==="google"?await nu({model:c,prompt:e,aspectRatio:u,...a?{abortSignal:a}:{}}):await nu({model:c,prompt:e,size:Az[u],...a?{abortSignal:a}:{},providerOptions:{openai:{quality:"medium"}}})).image.base64,p=`data:image/png;base64,${m}`;return i.debug("Image generated successfully",{provider:s,model:l}),{base64:m,dataUrl:p}}catch(u){throw a?.throwIfAborted(),i.error("Failed to generate image",u),Error("Image generation failed",{cause:u})}}var Az={"1:1":"1024x1024","16:9":"1536x1024","9:16":"1024x1536","4:3":"1536x1024","3:4":"1024x1536"};function Ru(e){return{...e,temperature:e.temperature??0.7,maxTokens:e.maxTokens??1000,webSearch:e.webSearch??!0}}function Eu(e,t,n){let o={};if(e.temperature!==void 0&&n)o.temperature=e.temperature;if(e.maxTokens!==void 0)o.maxTokens=e.maxTokens;if(e.webSearch)o.webSearch=!0;if(t==="openai"&&e.reasoningEffort)o.providerOptions={openai:{reasoningEffort:e.reasoningEffort}};return o}function So(e){return{promptTokens:e.inputTokens??0,completionTokens:e.outputTokens??0,totalTokens:e.totalTokens??0}}class Li{config;logger;providers;capabilities;cachedModel=null;static createFresh(e,t){return new Li(e,t)}constructor(e,t){this.config=Ru(e),this.logger=t.child("AIService"),this.providers=ku(this.config),this.capabilities=Di(this.config.model)}getModel(){return this.cachedModel??=jS(this.providers,this.requireTextModel()),this.cachedModel}async generateText(e,t,n){n?.throwIfAborted(),this.logger.debug("Generating text response",{model:this.config.model});try{let o=await ru({model:this.getModel(),system:e,prompt:t,...n?{abortSignal:n}:{},...Eu(this.config,this.capabilities.provider,this.capabilities.supportsTemperature)}),i=So(o.usage);return this.logUsage("text_generation",i),{text:o.text,usage:i}}catch(o){throw n?.throwIfAborted(),this.logger.error("Failed to generate text",o),Error("AI text generation failed",{cause:o})}}async generateObject(e,t,n,o){o?.throwIfAborted(),this.logger.debug("Generating structured response",{model:this.config.model});try{let i=Eu(this.config,this.capabilities.provider,this.capabilities.supportsTemperature),a=await Zb({model:this.getModel(),system:e,prompt:t,schema:n,...o?{abortSignal:o}:{},...i,providerOptions:{...i.providerOptions,anthropic:{structuredOutputMode:"jsonTool"}}}),s=So(a.usage);return this.logUsage("object_generation",s),{object:a.object,usage:s}}catch(i){if(o?.throwIfAborted(),this.logger.error("Failed to generate object",i),Ft.isInstance(i))throw new es(i);throw Error("AI object generation failed",{cause:i})}}async judge(e){let{object:t,usage:n}=await this.generateObject("You are a careful judge. Answer only by filling the requested verdict schema. Do not author new source material; evaluate only the supplied material against the instruction.",["## Judgment instruction",e.instruction,"","## Material",e.material].join(`
92
+ `),e.schema,e.signal);return{verdict:t,usage:n}}updateConfig(e){let t=this.config.model;this.config=Ru({...this.config,...e});let n=this.config.model!==t;if(e.apiKey!==void 0||e.imageApiKey!==void 0||n)this.providers=ku(this.config),this.cachedModel=null;if(n)this.capabilities=Di(this.config.model);this.logger.info("AI configuration updated",{model:this.config.model})}getConfig(){return{...this.config}}canGenerateImages(){return OS(this.providers)}async generateImage(e,t){return DS(e,this.config.imageModel,t,this.providers,this.logger)}logUsage(e,t){this.logger.info("ai:usage",{operation:e,provider:this.capabilities.provider,model:this.config.model,inputTokens:t.promptTokens,outputTokens:t.completionTokens})}requireTextModel(){if(!this.config.model)throw Error("AI text model is not configured. Set a model in the brain definition or brain.yaml.");return this.config.model}}var Pz="text-embedding-3-small",Mz=1536;class qi{model;dimensions;openai;logger;usage;static createFresh(e){return new qi(e)}constructor(e){if(!e.apiKey)throw Error("API key is required for online embedding provider");this.model=e.model??Pz,this.dimensions=e.dimensions??Mz,this.logger=e.logger.child("OnlineEmbeddingProvider"),this.usage=e.usage,this.openai=_o({apiKey:e.apiKey,...e.fetch?{fetch:e.fetch}:{}})}async generateEmbedding(e,t){t?.throwIfAborted(),this.logger.debug(`Generating embedding for text (${e.length} chars)`);let{embedding:n,usage:o}=await Wb({model:this.openai.embedding(this.model),value:e,...t?{abortSignal:t}:{},providerOptions:{openai:{dimensions:this.dimensions}}});return this.usage?.record(this.model,o.tokens),{embedding:new Float32Array(n),usage:{tokens:o.tokens}}}async generateEmbeddings(e,t){if(t?.throwIfAborted(),e.length===0)return{embeddings:[],usage:{tokens:0}};this.logger.debug(`Generating embeddings for ${e.length} texts`);let{embeddings:n,usage:o}=await Vb({model:this.openai.embedding(this.model),values:e,...t?{abortSignal:t}:{},providerOptions:{openai:{dimensions:this.dimensions}}});return this.usage?.record(this.model,o.tokens),{embeddings:n.map((i)=>new Float32Array(i)),usage:{tokens:o.tokens}}}}import{AsyncLocalStorage as jz}from"async_hooks";class Fi{storage=new jz;static createFresh(){return new Fi}constructor(){}record(e,t){this.storage.getStore()?.push({model:e,tokens:t})}async measure(e){let t=[];return{value:await this.storage.run(t,e),usage:t}}}var Oz=new Set(["system_search","system_get","system_list"]);function Zr(e){return Oz.has(e.name)&&e.visibility==="public"&&e.sideEffects==="none"&&e.agentTool!==!1}function Kr(e){if(e.interfaceType===mt&&((e.userPermissionLevel??"public")!=="public"||e.isAnchor===!0))throw Error("Guest execution denied")}function wo(e){if(e.interfaceType!==mt){if(e.guestExecution!==void 0)throw Error("Guest execution scope mismatch");return}let t=is.safeParse(e.guestExecution);if(!t.success)throw Error("Guest execution limits required");return t.data}function Au(e){if(!e)throw Error("Guest execution denied");return e.map((t)=>{if(t.role!=="user"&&t.role!=="assistant")throw Error("Guest execution denied");let n=typeof t.content==="string"?t.content:t.content.map((o)=>{if(o.type!=="text")throw Error("Guest execution denied");return o.text}).join(`
93
+ `);return{role:t.role,content:n}})}var zS=`## Public Visitor
94
+ You are answering a visitor on this brain's public website. They came to explore this brain's work.
95
+ Answer from this brain's public content: search it before answering, including for general questions, and relate the answer to what the brain holds.
96
+ Cite what you found. When the brain holds nothing relevant, say so briefly before any general answer.
97
+ The visitor is not your anchor: speak of the anchor in the third person, as the person or organization behind this site, never as "your anchor".`;var ce=On(zw(),1);var Tt={promptTokens:0,completionTokens:0,totalTokens:0},Fq=r.record(r.string(),r.unknown());function Bq(e){let t=Fq.safeParse(e);return t.success?t.data:void 0}function Gq(e){return e?hs(e.identity):void 0}function Uw(e,t){let n=Gq(t.actor);return e.map((o)=>({...o,requester:{...n?{actorKey:n}:{},userPermissionLevel:t.userPermissionLevel}}))}function Yu(e,t){return e.pendingConfirmations.find((n)=>n.id===t)??null}function Qu(e,t){return e.pendingConfirmations.filter((n)=>n.id!==t)}function Jq({context:e,event:t}){if(t.type!=="CONFIRM"&&t.type!=="CANCEL")return!1;return Qu(e,t.approvalId).length>0}function $w(e){let t=e?.summary??"unknown action",n=Bq(e?.args);return{text:`Action cancelled: ${t}`,...e?{cards:[{kind:"tool-approval",id:e.id,...e.toolCallId?{toolCallId:e.toolCallId}:{},toolName:e.toolName,...n?{input:n}:{},summary:t,state:"output-denied"}]}:{},usage:Tt}}var Lw=ce.setup({types:{context:{},events:{}},actors:{processMessage:ce.fromPromise(async()=>{throw Error("processMessage actor not provided")}),executeConfirmedAction:ce.fromPromise(async()=>{throw Error("executeConfirmedAction actor not provided")})}}).createMachine({id:"agent",initial:"idle",context:{guestExecution:void 0,conversationId:"",message:"",interfaceType:"agent",channelId:void 0,channelName:"",userPermissionLevel:"public",isAnchor:!1,actor:null,source:null,attachments:[],signal:void 0,response:null,pendingConfirmations:[],activeConfirmation:null,error:null},states:{idle:{on:{RECEIVE_MESSAGE:{target:"processing",actions:ce.assign(({event:e})=>({message:e.message,conversationId:e.conversationId,interfaceType:e.interfaceType,channelId:e.channelId,channelName:e.channelName,userPermissionLevel:e.userPermissionLevel,isAnchor:e.isAnchor,actor:e.actor,source:e.source,attachments:e.attachments,guestExecution:e.guestExecution,signal:e.signal,response:null,pendingConfirmations:[],activeConfirmation:null,error:null}))}}},processing:{invoke:{src:"processMessage",input:({context:e})=>({conversationId:e.conversationId,message:e.message,interfaceType:e.interfaceType,channelId:e.channelId,channelName:e.channelName,userPermissionLevel:e.userPermissionLevel,isAnchor:e.isAnchor,actor:e.actor,source:e.source,attachments:e.attachments,guestExecution:e.guestExecution,signal:e.signal}),onDone:[{guard:({event:e})=>(e.output.pendingConfirmations??[]).length>0,target:"awaitingConfirmation",actions:ce.assign(({context:e,event:t})=>({response:t.output,pendingConfirmations:Uw(t.output.pendingConfirmations??[],e),activeConfirmation:null,attachments:[],signal:void 0}))},{target:"idle",actions:ce.assign(({event:e})=>({response:e.output,attachments:[],signal:void 0}))}],onError:{target:"idle",actions:ce.assign(({event:e})=>({error:ke(e.error,"Unknown error"),response:{error:ke(e.error,"Unknown error"),text:e.error instanceof Error?`Error: ${e.error.message}`:"An unexpected error occurred.",usage:Tt},attachments:[],signal:void 0}))}}},awaitingConfirmation:{on:{CONFIRM:{target:"executing",actions:ce.assign(({context:e,event:t})=>({interfaceType:t.interfaceType,channelId:t.channelId,channelName:t.channelName,userPermissionLevel:t.userPermissionLevel,isAnchor:t.isAnchor,actor:t.actor,source:t.source,signal:t.signal,activeConfirmation:Yu(e,t.approvalId),pendingConfirmations:Qu(e,t.approvalId)}))},CANCEL:[{guard:Jq,target:"awaitingConfirmation",actions:ce.assign(({context:e,event:t})=>({interfaceType:t.interfaceType,channelId:t.channelId,channelName:t.channelName,userPermissionLevel:t.userPermissionLevel,isAnchor:t.isAnchor,actor:t.actor,source:t.source,response:$w(Yu(e,t.approvalId)),pendingConfirmations:Qu(e,t.approvalId),activeConfirmation:null,signal:void 0}))},{target:"idle",actions:ce.assign(({context:e,event:t})=>({interfaceType:t.interfaceType,channelId:t.channelId,channelName:t.channelName,userPermissionLevel:t.userPermissionLevel,isAnchor:t.isAnchor,actor:t.actor,source:t.source,response:$w(Yu(e,t.approvalId)),pendingConfirmations:[],activeConfirmation:null,signal:void 0}))}]}},executing:{invoke:{src:"executeConfirmedAction",input:({context:e})=>{if(!e.activeConfirmation)throw Error("No pending confirmation in executing state");return{conversationId:e.conversationId,pendingConfirmation:e.activeConfirmation,interfaceType:e.interfaceType,channelId:e.channelId,channelName:e.channelName,userPermissionLevel:e.userPermissionLevel,isAnchor:e.isAnchor,actor:e.actor,signal:e.signal}},onDone:[{guard:({context:e,event:t})=>e.pendingConfirmations.length>0||(t.output.pendingConfirmations??[]).length>0,target:"awaitingConfirmation",actions:ce.assign(({context:e,event:t})=>({response:t.output,pendingConfirmations:[...e.pendingConfirmations,...Uw(t.output.pendingConfirmations??[],e)],activeConfirmation:null,signal:void 0}))},{target:"idle",actions:ce.assign(({event:e})=>({response:e.output,pendingConfirmations:[],activeConfirmation:null,signal:void 0}))}],onError:[{guard:({context:e})=>e.pendingConfirmations.length>0,target:"awaitingConfirmation",actions:ce.assign(({context:e,event:t})=>({error:ke(t.error,"Unknown error"),response:{error:ke(t.error,"Unknown error"),text:`Error executing ${e.activeConfirmation?.toolName??"action"}: ${ke(t.error,"Unknown error")}`,usage:Tt},activeConfirmation:null,signal:void 0}))},{target:"idle",actions:ce.assign(({context:e,event:t})=>({error:ke(t.error,"Unknown error"),response:{error:ke(t.error,"Unknown error"),text:`Error executing ${e.activeConfirmation?.toolName??"action"}: ${ke(t.error,"Unknown error")}`,usage:Tt},pendingConfirmations:[],activeConfirmation:null,signal:void 0}))}]}}}});var Hq=10;function Wq(e,t){if(t.aborted)return Promise.reject(t.reason);return new Promise((n,o)=>{let i=()=>{o(t.reason)};t.addEventListener("abort",i,{once:!0}),e.then((a)=>{t.removeEventListener("abort",i),n(a)},(a)=>{t.removeEventListener("abort",i),o(a)})})}class Xu{createActor;isEvictable;idleTtlMs;maxOperations;actors=new Map;operations=new Map;operationCounts=new Map;evictionRevisions=new Map;evictionGeneration=0;evictionSupervisor;lifecycleController=new AbortController;closePromise=null;closeReason;closed=!1;clock;constructor(e,t){this.createActor=e.createActor,this.isEvictable=e.isEvictable,this.idleTtlMs=e.idleTtlMs,this.maxOperations=e.maxOperationsPerConversation??Hq,this.clock=t?.clock,this.evictionSupervisor=this.createEvictionSupervisor()}acquire(e){this.assertOpen(),this.cancelEviction(e);let t=this.actors.get(e);if(!t)t=this.createActor(),this.actors.set(e,t);return t}peek(e){return this.actors.get(e)}get size(){return this.actors.size}enqueue(e,t,n){if(this.closed)return Promise.reject(this.closeReason);let o=n?AbortSignal.any([this.lifecycleController.signal,n]):this.lifecycleController.signal;if(o.aborted)return Promise.reject(o.reason);let i=this.operationCounts.get(e)??0;if(i>=this.maxOperations)return Promise.reject(Error("Conversation is busy. Please wait for earlier messages to finish."));this.operationCounts.set(e,i+1);let a=this.evictionGeneration,l=(this.operations.get(e)??Promise.resolve()).catch(()=>{return}).then(()=>(o.throwIfAborted(),t(o))),c=l.catch(()=>{return}).then(()=>{return});return this.operations.set(e,c),c.then(()=>{if(a!==this.evictionGeneration)return;let u=(this.operationCounts.get(e)??1)-1;if(u<=0)this.operationCounts.delete(e);else this.operationCounts.set(e,u);if(this.operations.get(e)===c)this.operations.delete(e);this.scheduleEviction(e)}),Wq(l,o)}scheduleEviction(e){if(this.closed)return;let t=this.cancelEviction(e);if(this.idleTtlMs<=0)return;let n=this.evictionGeneration,o=pe.sleep(this.idleTtlMs).pipe(pe.andThen(pe.sync(()=>{if(n!==this.evictionGeneration)return;if(this.evictionRevisions.get(e)!==t)return;this.evictionRevisions.delete(e);let s=this.actors.get(e);if(!s)return;if((this.operationCounts.get(e)??0)>0)return;if(!this.isEvictable(s))return;s.stop(),this.actors.delete(e)}))),i=this.clock?pe.withClock(o,this.clock):o,a=pe.runFork(i);ys.unsafeSet(this.evictionSupervisor.fibers,e,a)}close(e=Error("Conversation actor registry closed")){if(this.closePromise)return this.closePromise;this.closed=!0,this.closeReason=e,this.evictionGeneration++,this.lifecycleController.abort(e);let t=[...this.operations.values()];return this.closePromise=this.closeRegistry(t),this.closePromise}async closeRegistry(e){let t=await Promise.allSettled([pe.runPromise(Xe.close(this.evictionSupervisor.scope,tt.void)),...e]),n=[];for(let i of this.actors.values())try{i.stop()}catch(a){n.push(a)}this.actors.clear(),this.operations.clear(),this.operationCounts.clear(),this.evictionRevisions.clear();let o=t.find((i)=>i.status==="rejected");if(o)throw o.reason;if(n.length>0)throw n[0]}cancelEviction(e){let t=(this.evictionRevisions.get(e)??0)+1;this.evictionRevisions.set(e,t);let n=ys.unsafeGet(this.evictionSupervisor.fibers,e);if(qw.isSome(n))pe.runSync(Yi.interruptFork(n.value));return t}assertOpen(){if(this.closed)throw this.closeReason}createEvictionSupervisor(){let e=pe.runSync(Xe.make()),t=pe.runSync(Xe.extend(ys.make(),e));return{scope:e,fibers:t}}}function Vq(e){return e?hs(e.identity):void 0}function ed(e,t){if(t.userPermissionLevel==="admin")return!0;let n=e.requester.actorKey;if(n){if(Vq(t.actor)!==n)return!1}return vs.hasPermission(t.userPermissionLevel,e.requester.userPermissionLevel)}function Zq(e,t){if(!e?.userPermissionLevel)return null;return{interfaceType:e.interfaceType??t.interfaceType,channelId:e.channelId??t.channelId,channelName:e.channelName??t.channelName,userPermissionLevel:e.userPermissionLevel,isAnchor:e.isAnchor??!1,actor:e.actor??null,source:e.source??null}}class td{actors;persistCancelledAction;constructor(e,t){this.actors=e,this.persistCancelledAction=t}async run(e,t,n,o,i){i?.throwIfAborted();let a=this.actors.peek(e);if(!a)return{text:"No pending action to confirm.",usage:Tt};let s=a.getSnapshot();if(!s.matches("awaitingConfirmation"))return{text:"No pending action to confirm.",usage:Tt};let l=s.context.pendingConfirmations.find((u)=>u.id===n)??null;if(!l)return{text:`No pending action matches approval id '${n}'.`,usage:Tt};let c=Zq(o,s.context);if(!c)return{text:"Confirmation requires caller context.",usage:Tt};if(!ed(l,c))return{text:"You are not authorized to confirm this pending action.",pendingConfirmations:s.context.pendingConfirmations,usage:Tt};return this.resolve(e,a,l,t,c,i)}async resolve(e,t,n,o,i,a){a?.throwIfAborted();try{let s={approvalId:n.id,interfaceType:i.interfaceType,channelId:i.channelId,channelName:i.channelName,userPermissionLevel:i.userPermissionLevel,isAnchor:i.isAnchor,actor:i.actor,source:i.source,...a?{signal:a}:{}};if(o)t.send({type:"CONFIRM",...s});else t.send({type:"CANCEL",...s});let l=await ce.waitFor(t,(u)=>(u.matches("idle")||u.matches("awaitingConfirmation"))&&!u.context.pendingConfirmations.some((d)=>d.id===n.id));if(o)a?.throwIfAborted();let c=l.context.response??{text:"Action completed.",usage:Tt};if(!o)await this.persistCancelledAction(e,c,i),a?.throwIfAborted();return c}finally{this.actors.scheduleEviction(e)}}}var Fw={standard:{input:20,cacheRead:2,cacheWrite:25,output:120},long:{input:40,cacheRead:void 0,cacheWrite:50,output:180}};function Kq(e){if(e.cacheRead===void 0)return{state:"unknown",reason:"missing-usage"};let t=e.cacheWrite??0,n=e.input-e.cacheRead-t;if(n<0)return{state:"unknown",reason:"missing-usage"};let o=e.input>272000?Fw.long:Fw.standard;if(e.cacheRead>0&&o.cacheRead===void 0)return{state:"unknown",reason:"unsupported-pricing"};return{centi:n*o.input+e.cacheRead*(o.cacheRead??0)+t*o.cacheWrite+e.output*o.output}}function rd(e){let t=e.calls.map(Kq),n=t.find((i)=>("state"in i));if(n)return n;let o=t.reduce((i,a)=>i+("centi"in a?a.centi:0),0);return{state:"known",microUsd:Math.ceil(o/100),pricing:"openai-gpt-5.6-luna-2026-09-26"}}function Bw(e,t){let n=e.flatMap(({usage:a})=>a?.inputTokens===void 0||a.outputTokens===void 0?[]:[{input:a.inputTokens,cacheRead:a.inputTokenDetails.cacheReadTokens,cacheWrite:a.inputTokenDetails.cacheWriteTokens,output:a.outputTokens,reasoning:a.outputTokenDetails.reasoningTokens??0}]),o=(a)=>a.reduce((s,l)=>s+(l??0),0),i=n.length!==e.length;return{usage:{modelCalls:e.length,inputTokens:o(n.map((a)=>a.input)),cachedInputTokens:o(n.map((a)=>a.cacheRead)),outputTokens:o(n.map((a)=>a.output)),reasoningTokens:o(n.map((a)=>a.reasoning)),embeddingTokens:0},cost:i?{state:"unknown",reason:"missing-usage"}:t?t({calls:n}):{state:"unknown",reason:"unsupported-pricing"}}}var Yq="openai-text-embedding-3-small-2026-09-30",Qq={"text-embedding-3-small":2};function Gw(e,t){if(t.length===0)return e;let n=t.reduce((s,l)=>s+l.tokens,0),o={...e.usage,embeddingTokens:e.usage.embeddingTokens+n};if(e.cost.state==="unknown")return{usage:o,cost:e.cost};let i=t.map((s)=>{let l=Qq[s.model];return l===void 0?void 0:s.tokens*l});if(i.includes(void 0))return{usage:o,cost:{state:"unknown",reason:"unsupported-pricing"}};let a=i.reduce((s,l)=>s+(l??0),0);return{usage:o,cost:{state:"known",microUsd:e.cost.microUsd+Math.ceil(a/100),pricing:`${e.cost.pricing}+${Yq}`}}}var Xq=r.object({success:r.literal(!0),data:r.object({status:r.literal("generating"),entityId:r.string().min(1).optional(),jobId:r.string().min(1).optional()}).passthrough()}).passthrough();function Jw(e){if(!Xq.safeParse(e).success)return;return"The draft is generating now. Once it is ready, I can review it with you, refine it, or turn it into another format."}function Hw(e){let t=e.map((o)=>o.filename);return`I got ${t.length===1?`\`${t[0]}\``:t.map((o)=>`\`${o}\``).join(", ")}. What would you like me to do with ${t.length===1?"it":"these files"}?`}function eF(e){return e.mediaType.startsWith("image/")}function tF(e){return e.mediaType==="application/pdf"}function rF(e){return e.kind==="text"||e.mediaType.startsWith("text/")}function Ww(e){if(e.length===0)return;if(e.length>1)return{kind:"actions",id:"actions:upload-intent",title:"Try next",defaultOpen:!0,actions:[{type:"prompt",id:"summarize-uploads",label:"Summarize uploads",prompt:"Summarize the uploaded files."}]};let[t]=e;if(t===void 0)return;if(eF(t))return{kind:"actions",id:"actions:upload-intent",title:"Try next",defaultOpen:!0,actions:[{type:"prompt",id:"describe-image",label:"Describe image",prompt:"Describe the uploaded image."},{type:"prompt",id:"save-image",label:"Save image",prompt:"Save the uploaded image."}]};if(tF(t))return{kind:"actions",id:"actions:upload-intent",title:"Try next",defaultOpen:!0,actions:[{type:"prompt",id:"summarize-pdf",label:"Summarize PDF",prompt:"Summarize the uploaded PDF."},{type:"prompt",id:"save-document",label:"Save document",prompt:"Save the uploaded PDF as a document."}]};if(rF(t))return{kind:"actions",id:"actions:upload-intent",title:"Try next",defaultOpen:!0,actions:[{type:"prompt",id:"summarize-upload",label:"Summarize upload",prompt:"Summarize the uploaded file."},{type:"prompt",id:"save-upload-note",label:"Save as note",prompt:"Save the uploaded file as a note."}]};return{kind:"actions",id:"actions:upload-intent",title:"Try next",defaultOpen:!0,actions:[{type:"prompt",id:"summarize-upload",label:"Summarize upload",prompt:"Summarize the uploaded file."}]}}async function Vw(e){let{refs:t,resolver:n,logger:o}=e;if(t.length===0)return[];if(!n)return[];let i=[];for(let a of t)try{let s=await n(a.source);if(!s)continue;i.push({filename:s.filename,mediaType:s.mediaType,source:a.source})}catch(s){o.debug("Skipped unavailable prior upload ref",{uploadKind:a.source.kind,uploadId:a.source.id,error:ke(s)})}return i}async function Zw(e){let{currentAttachments:t,uploadRefs:n,resolver:o,logger:i}=e;if(t.length>0)return t;if(!o)return t;if(n.length!==1)return t;let a=[];for(let s of n.slice().reverse()){try{let l=await o(s.source);if(l)a.push(l)}catch(l){i.debug("Skipped unavailable prior upload attachment",{uploadKind:s.source.kind,uploadId:s.source.id,error:ke(l)})}if(a.length>0)break}return a.length>0?a:t}var nF=r.record(r.string(),r.unknown()),rx=r.looseObject({jobId:r.string()}),ad=r.looseObject({id:r.string().min(1),entityType:r.string().min(1),content:r.string().optional(),metadata:r.record(r.string(),r.unknown()).default({})}),oF=r.looseObject({entity:ad,score:r.number().finite().optional(),excerpt:r.string().optional()}),iF=r.object({results:r.array(oF)}),aF=r.object({entity:ad}),sF=r.custom((e)=>Xw.safeParse(e).success,"expected structured chat card"),lF=r.object({cards:r.array(sF)}),cF=r.object({currentState:r.object({prompt:r.string().min(1).optional()})}),uF=r.object({entities:r.array(ad)}),dF=r.object({documentId:r.string().min(1).optional(),entityId:r.string().min(1).optional(),attachment:r.object({mediaType:r.string().min(1),url:r.string().min(1),downloadUrl:r.string().min(1).optional(),previewUrl:r.string().min(1).optional(),filename:r.string().min(1).optional(),sizeBytes:r.number().nonnegative().optional(),source:r.object({entityType:r.string().optional(),entityId:r.string().optional(),attachmentType:r.string().optional()}).optional()})}).transform((e,t)=>{let n=e.documentId??e.entityId;if(n===void 0)return t.addIssue({code:"custom",message:"attachment needs a documentId or entityId"}),r.NEVER;return{attachmentId:n,attachment:e.attachment}});function pF(e){if(e==="application/pdf")return"PDF";let[t,n]=e.split("/");if(t==="image")return"image";if(n)return n.toUpperCase();return"artifact"}function mF(e,t){if(t==="uploaded")return`Uploaded ${e} save has been queued. This artifact will open once the job completes.`;return`${e} generation has been queued. This artifact will open once the job completes.`}function nx(e){for(let t of e){let n=cF.safeParse(t.data);if(n.success&&n.data.currentState.prompt)return n.data.currentState.prompt}return}function sd(e){let t=rx.safeParse(e),n=dF.safeParse(e);if(!n.success)return;let{attachmentId:o,attachment:i}=n.data,a=i.source,s=pF(i.mediaType),l=mF(s,a?.attachmentType);return{kind:"attachment",id:`attachment:${o}`,title:i.filename??`Generated ${s}`,...gt({jobId:t.success?t.data.jobId:void 0,description:t.success?l:void 0}),attachment:{mediaType:i.mediaType,url:i.url,...gt({downloadUrl:i.downloadUrl,previewUrl:i.previewUrl,filename:i.filename,sizeBytes:i.sizeBytes,source:a&&gt(a)})}}}var Kw=500,gF=3;function id(e){let t=e.trim();if(t.length<=Kw)return t;return`${t.slice(0,Kw-1).trimEnd()}\u2026`}function nd(e,t){let n=e?.[t];return typeof n==="string"&&n.length>0?n:void 0}function ox(e){if(!e||e.length===0)return;return{kind:"sources",id:"sources:agent-context",title:"Retrieved context",sources:e.map((t)=>({id:t.id,source:t.source,excerpt:id(t.content),...gt({title:t.title,url:nd(t.provenance,"url"),entityType:nd(t.provenance,"entityType"),entityId:nd(t.provenance,"entityId"),provenance:t.provenance})}))}}function Fn(e,t){let n=e[t];return typeof n==="string"&&n.trim().length>0?n.trim():void 0}function ix(e){return Fn(e.metadata,"title")??Fn(e.metadata,"name")??Fn(e.metadata,"slug")??e.id}function fF(e){return Fn(e.metadata,"url")??Fn(e.metadata,"permalink")??Fn(e.metadata,"canonicalUrl")}function Yw(e){let{entity:t,toolName:n,score:o}=e,i=e.excerpt!==void 0?id(e.excerpt):t.content!==void 0?id(t.content):void 0,a=fF(t);return{id:`${t.entityType}:${t.id}`,title:ix(t),source:t.entityType,entityType:t.entityType,entityId:t.id,...gt({url:a,excerpt:i}),provenance:{toolName:n,...gt({score:o})}}}function hF(e){if(e.toolName==="system_search"){let t=iF.safeParse(e.data);if(!t.success)return[];return[...t.data.results].sort((n,o)=>(o.score??Number.NEGATIVE_INFINITY)-(n.score??Number.NEGATIVE_INFINITY)).map((n,o)=>({rank:o,citation:Yw({toolName:e.toolName,entity:n.entity,excerpt:n.excerpt,score:n.score})}))}if(e.toolName==="system_get"){let t=aF.safeParse(e.data);if(!t.success)return[];return[{citation:Yw({toolName:e.toolName,entity:t.data.entity})}]}return[]}function Qw(e){return` ${e.toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").trim()} `}function yF(e,t){let n=t===void 0?"":Qw(t),o=e.filter((s)=>s.rank!==void 0),i=o.filter((s)=>{let l=s.citation.title;if(l===void 0)return!1;let c=Qw(l);return c.trim().length>=4&&n.includes(c)});return[...i.length>0?i:o.filter((s)=>(s.rank??0)<gF),...e.filter((s)=>s.rank===void 0)].map((s)=>s.citation)}function ax(e){if(e.length===0)return;let t=[],n=new Set;for(let o of e){if(n.has(o.id))continue;n.add(o.id),t.push(o)}return{kind:"sources",id:"sources:tool-results",title:"Retrieved sources",sources:t}}function sx(e,t){let n=ax(t);if(!n)return e;return[...e.filter((o)=>o.kind!=="sources"||o.id!==n.id),n]}function ld(e,t){let n=[],o=[],i=[],a=[],s=0;for(let c of e){s+=c.toolCalls.length;let u=new Map;for(let p of c.toolCalls)if(p.toolCallId){let f=nF.safeParse(p.input);if(f.success)u.set(p.toolCallId,f.data)}let d=!1,m=new Set;for(let p of c.toolResults){if(p.output===null)continue;let f=_s.safeParse(p.output);if(f.success){if(m.has(f.data.toolName))continue;m.add(f.data.toolName);let y=p.toolCallId?`approval:${p.toolCallId}`:`approval:${p.toolName}:${s}`,w=p.toolCallId?u.get(p.toolCallId):void 0,_={id:y,toolName:f.data.toolName,summary:f.data.summary,args:f.data.args,...gt({toolCallId:p.toolCallId,completionSummary:f.data.completionSummary,preview:f.data.preview})};a.push(_),d=!0,o.push({kind:"tool-approval",id:y,toolName:f.data.toolName,summary:f.data.summary,state:"approval-requested",...gt({toolCallId:p.toolCallId,input:w,completionSummary:f.data.completionSummary,preview:f.data.preview})});continue}let g=tx.safeParse(p.output);if(!g.success){n.push({toolName:p.toolName});continue}let h=bs.safeParse(g.data);if(h.success&&h.data.cached===!0)continue;let v=p.toolCallId?u.get(p.toolCallId):void 0,x={toolName:p.toolName};if(v!==void 0)x.args=v;let S=ex.safeParse(g.data);if(S.success)x.error={message:S.data.error,...gt({code:S.data.code})};if(h.success&&h.data.data!=null){x.data=h.data.data;let y=rx.safeParse(h.data.data);if(y.success)x.jobId=y.data.jobId;let w=lF.safeParse(h.data.data);if(w.success)o.push(...w.data.cards);let _=sd(h.data.data);if(_)o.push(_);i.push(...hF({toolName:p.toolName,data:h.data.data}))}n.push(x)}if(d)break}let l=ax(yF(i,t));if(l)o.push(l);return{toolResults:n,pendingConfirmations:a,cards:o,totalToolCalls:s}}var vF=r.object({entityId:r.string().min(1).optional(),updated:r.string().min(1).optional(),deleted:r.string().min(1).optional(),status:r.string().optional()});function od(e){return e===void 0||e===""?void 0:e}var bF=r.object({entityType:r.string().optional(),id:r.string().optional(),title:r.string().optional()}),lx=r.object({entityType:r.string().min(1).optional(),entityId:r.string().min(1),operation:r.string().min(1).optional(),title:r.string().min(1).optional(),status:r.string().min(1).optional(),listIndex:r.number().int().positive().optional()}),cd=r.object({source:r.object({kind:r.literal("url"),url:r.string().min(1)})}),_F=r.object({agent:r.string().min(1)}),SF=r.object({agentContactCandidate:cd});function cx(e){let t=new Set,n=[];for(let o of e){if(o.toolName!=="agent_call")continue;let i=SF.safeParse(o.data);if(i.success){let{url:l}=i.data.agentContactCandidate.source;if(t.has(l))continue;t.add(l),n.push(i.data.agentContactCandidate);continue}if(o.error?.code!=="agent_not_saved"&&o.error?.code!=="agent_card_unavailable")continue;let a=_F.safeParse(o.args??{});if(!a.success)continue;let s=a.data.agent;if(t.has(s))continue;t.add(s),n.push({source:{kind:"url",url:s}})}return n}function ux(e){if(e.length===0)return"";return`
98
+
99
+ Internal agent contact candidates from previous assistant turns for follow-up resolution. These are typed runtime candidates, not visible user text. If the user confirms saving/adding/connecting one of these contacts, call agent_connect without confirmed using the exact candidate args. Do not auto-save from an agent_call; saving/connecting is explicit through agent_connect.
100
+ ${e.map((n)=>`- agent_connect candidate args: { source: { kind: "url", url: "${n.source.url}" } }`).join(`
101
+ `)}`}function Qi(e){let t=new Set,n=[];for(let o of e){let i=vF.safeParse(o.data),a=i.success?i.data.entityId??i.data.updated??i.data.deleted:void 0;if(i.success&&a!==void 0){let{status:l}=i.data;if(t.has(a))continue;t.add(a);let c=bF.safeParse(o.args??{}),u=c.success?c.data.entityType:void 0,d=c.success?c.data.title:void 0,m=i.data.updated?"updated":i.data.deleted?"deleted":"created";n.push({entityId:a,operation:m,...gt({entityType:od(u),title:od(d),status:od(l)})});continue}if(o.toolName!=="system_list")continue;let s=uF.safeParse(o.data);if(!s.success)continue;for(let l of s.data.entities){if(t.has(l.id))continue;t.add(l.id);let c=ix(l),u=Fn(l.metadata,"status");n.push({entityType:l.entityType,entityId:l.id,operation:"listed",listIndex:n.filter((d)=>d.operation==="listed").length+1,...gt({title:c!==l.id?c:void 0,status:u})})}}return n}function dx(e){if(e.length===0)return"";return`
102
+
103
+ Internal entity refs from previous assistant turns for follow-up resolution. These are typed runtime references, not visible user text. Use the canonical entityId when a follow-up refers to the same item (for example \u201Cit\u201D, \u201Cthat\u201D, \u201Cthat post\u201D, \u201Cthe draft\u201D, \u201Cpublish it\u201D, or \u201Ca cover image to go with that\u201D). Do not derive or rewrite IDs from titles; copy the exact entityId value from the matching ref. A ref with operation created and status generating/draft is already a valid target for follow-up operations such as cover-image generation; do not ask the user for its slug again.
104
+ ${e.map((n)=>`- ${[n.entityType!==void 0?`entityType: ${n.entityType}`:void 0,`entityId: ${n.entityId}`,n.operation!==void 0?`operation: ${n.operation}`:void 0,n.listIndex!==void 0?`item ${n.listIndex}`:void 0,n.title!==void 0?`title: ${n.title}`:void 0,n.status!==void 0?`status: ${n.status}`:void 0].filter((i)=>i!==void 0&&i.length>0).join("; ")}`).join(`
105
+ `)}`}function wF(e){return e.map((t)=>t.role==="user"?{role:"user",content:t.content}:{role:"assistant",content:[{type:"text",text:t.content+xF(t.metadata)+TF(t.metadata)}]})}function xF(e){let t=No(e),n=CF(t?.entityMemoryRefs);return dx(n)}function TF(e){let t=No(e),n=IF(t?.agentContactCandidates);return ux(n)}function IF(e){if(!Array.isArray(e))return[];return e.flatMap((t)=>{let n=cd.safeParse(t);return n.success?[n.data]:[]})}function CF(e){if(!Array.isArray(e))return[];return e.flatMap((t)=>{let n=lx.safeParse(t);return n.success?[n.data]:[]})}function No(e){if(yr(e))return e;if(typeof e!=="string")return null;try{let t=JSON.parse(e);return yr(t)?t:null}catch{return null}}var px={public:0,trusted:1,admin:2};function ud(e,t){if(t==="admin")return e;return e.filter((n)=>{let i=No(n.metadata)?.userPermissionLevel;if(i!=="public"&&i!=="trusted"&&i!=="admin")return!1;return px[i]<=px[t]})}function dd(e,t){return[...wF(e),{role:"user",content:t}]}function kF(e){return`${e.source.kind}:${e.source.id}`}function mx(e){if(e.source===void 0)return null;return{filename:e.filename,mediaType:e.mediaType,source:e.source}}function RF(e){if(!yr(e))return null;let t=e.source;if(!yr(t))return null;let{kind:n,id:o}=t,i=e.filename,a=e.mediaType;if(typeof n!=="string"||typeof o!=="string"||typeof i!=="string"||typeof a!=="string")return null;return{filename:i,mediaType:a,source:{kind:n,id:o}}}function pd(e){return e!==null}function EF(e){let t=e.flatMap((n)=>{let i=No(n.metadata)?.attachments;if(!Array.isArray(i))return[];return i.map(RF).filter(pd)});return md(t)}var AF=6;function gx(e){let t=PF({message:e.message,currentAttachments:e.currentAttachments,historyMessages:e.historyMessages}),n=t.length>0?OF(e.historyMessages):void 0;return{kind:"selected",message:e.message,refs:t,attachments:e.currentAttachments,...n?{priorResponseRef:n}:{}}}function PF(e){let t=e.currentAttachments.map(mx).filter(pd),n=EF(e.historyMessages).slice(-AF).reverse(),o=md([...t,...n]),i=MF(e.message);if(i===void 0)return o;return o.filter((a)=>jF(a,i)).slice(0,1)}function MF(e){let t=e.toLowerCase();if(t.includes("uploaded image"))return"image";if(t.includes("uploaded pdf"))return"pdf";return}function jF(e,t){if(t==="image")return e.mediaType.startsWith("image/");return e.mediaType==="application/pdf"}function md(e){let t=new Set,n=[];for(let o of e){let i=kF(o);if(t.has(i))continue;t.add(i),n.push(o)}return n}function OF(e){for(let t=e.length-1;t>=0;t-=1){let n=e[t];if(n?.role!=="assistant")continue;if(n.content.trim().length===0)continue;if(NF(n))continue;if(DF(n))continue;return{messageId:n.id}}return}function NF(e){let t=No(e.metadata);return Array.isArray(t?.entityMemoryRefs)}function DF(e){let n=No(e.metadata)?.cards;if(!Array.isArray(n))return!1;return n.some((o)=>yr(o)&&o.kind==="actions")}function fx(e,t,n={}){let o=t??[],i=o.filter((l)=>l.kind==="text").map(zF),a=[e,...i,UF(o,n.uploadRefs??[],n.priorResponseRef)].map((l)=>l.trim()).filter((l)=>l.length>0).join(`
106
+
107
+ `),s=o.filter((l)=>l.kind==="file");if(s.length===0)return a;return[...a.length>0?[{type:"text",text:a}]:[],...s.map((l)=>({type:"file",data:l.data,mediaType:l.mediaType,filename:l.filename}))]}function zF(e){return`User uploaded a file "${e.filename}":
108
+
109
+ ${e.content}`}function UF(e,t,n){let o=e.map(mx).filter(pd),i=md([...t,...o]).map($F),a=n?["Available system_create candidate for saving the prior assistant response (call without confirmed to request confirmation):",`{ entityType: "note", source: { kind: "prior-response", messageId: "${n.messageId}" } }`].join(" "):"";if(i.length===0)return a;return['Available upload refs from this conversation. Refs are ordered newest-first. Treat this as structured candidate data; resolve any user reference to a specific upload in typed tool arguments, or ask a clarification if the candidates are insufficient. For phrases like "the uploaded image" or "the uploaded PDF" without a filename, use the newest ref matching that media type; do not ask for clarification just because older uploads exist. Describe, summarize, analyze, or discuss uploads directly from the file bytes as read-only chat responses; do not call system_create unless the user explicitly asks to save, import, preserve, or create an entity. In read-only upload summaries, answer the request directly and do not offer to save/import/create unless asked. Upload candidates are file bytes; previous assistant answers are saved separately. If the user says "save it" after your summary/answer about an upload, save the prior assistant response as a note with source.kind "prior-response" unless they explicitly ask to save the uploaded file/document itself. Use system_create source.kind upload with transform "preserve" for preserving raw file bytes as a document/image, or transform "extract-markdown" for extracting/importing upload text as a note. Choose exactly one transform for the user request.',a,...i].filter((l)=>l.length>0).join(`
110
+ `)}function $F(e){return[`- ${e.filename}`,`upload: { kind: "${e.source.kind}", id: "${e.source.id}" }`,`mediaType: ${e.mediaType}`].join("; ")}function gd(e){if(e===void 0)return;return e.length===0?LF():qF(e)}function LF(){return"No relevant conversation memory was retrieved for this turn. If the user asks about conversation memory available in this turn, say none was retrieved rather than inferring from general instructions or other background knowledge."}function qF(e){return["Relevant conversation memory retrieved for this turn.",'Use it only when it helps answer the user. If the user asks what conversation memory says, explicitly ground the answer in the retrieved memory (for example, "According to conversation memory...") rather than general background knowledge. Preserve source/provenance when referencing memory. Ignore unrelated memory; when memory conflicts, prefer the most specific or newest source and mention uncertainty if the conflict remains unresolved.',"",e.map((n,o)=>FF(n,o)).join(`
111
+
112
+ `)].join(`
113
+ `)}function FF(e,t){let n=e.title??e.id,o=BF(e.provenance);return[`${t+1}. ${n} [${e.source}]`,e.content.trim(),...o?[`Provenance: ${o}`]:[]].join(`
114
+ `)}function BF(e){if(!e)return;let t=Object.entries(e).filter(([,n])=>n!==void 0&&n!==null&&n!=="").map(([n,o])=>`${n}=${GF(o)}`);return t.length>0?t.join(", "):void 0}function GF(e){if(typeof e==="string")return e;if(typeof e==="number"||typeof e==="boolean")return String(e);return JSON.stringify(e)}var JF="brain:assistant",HF="Assistant";function fd(e){if(!e)return;let t=Qr(e);return t?`brain:${t}`:void 0}function hd(e){let t=e.character.name.trim()||HF;return{identity:{kind:"agent",agentId:e.agentId??JF},interfaceType:"agent",role:"assistant",displayName:t,isBot:!0}}function hx(e){return{userPermissionLevel:e.userPermissionLevel,...e.isAnchor!==void 0?{isAnchor:e.isAnchor}:{},conversationId:e.conversationId,...e.channelId?{channelId:e.channelId}:{},channelName:e.channelName,interfaceType:e.interfaceType,...e.guestExecution?{guestExecution:e.guestExecution}:{},...e.actor?{actor:e.actor.identity,...e.actor.displayName?{displayName:e.actor.displayName}:{}}:{},...e.hasAccessibleUploads?{enableCreateUpload:!0,enableCreateTransform:!0}:{},...e.hasPriorResponseCandidate!==void 0?{hasPriorResponseCandidate:e.hasPriorResponseCandidate}:{},...e.agentContextInstructions?{agentContextInstructions:e.agentContextInstructions}:{}}}var WF=r.record(r.string(),r.unknown()),VF=r.looseObject({success:r.literal(!1)});function vd(e){let t=WF.safeParse(e);return t.success?t.data:void 0}function yd(e,t){let o=vd(e)?.[t];return typeof o==="string"?o:void 0}function ZF(e){return VF.safeParse(e).success}function KF(e){return e.trim().replace(/[?\uFF1F]+$/u,"")}var YF=new Set(["confirmed","confirmationToken","contentHash"]);function QF(e){let t=vd(e);if(!t)return;return Object.fromEntries(Object.entries(t).filter(([n])=>!YF.has(n)))}function yx(e,t){let n=ZF(t),o=n?"Failed":"Completed",i=n?yd(t,"error")??yd(t,"message"):void 0,a=KF(n?e.summary:e.completionSummary??e.summary),s=i?`${o}: ${a}
115
+
116
+ ${i}`:`${o}: ${a}`,l=vd(e.args),c={toolName:e.toolName,data:t,...l?{args:l}:{}},u=QF(e.args),d={kind:"tool-approval",id:e.id,...e.toolCallId?{toolCallId:e.toolCallId}:{},toolName:e.toolName,...u?{input:u}:{},summary:e.summary,...e.completionSummary!==void 0?{completionSummary:e.completionSummary}:{},state:n?"output-error":"output-available",output:t,...n?{error:yd(t,"error")??"Action failed"}:{}},m=bs.safeParse(t),p=m.success?sd(m.data.data):void 0,f=[d,...p?[p]:[]],g=m.success?Qi([{...c,data:m.data.data}]):[];return{resultText:s,toolResult:c,cards:f,entityMemoryRefs:g}}function XF(e){return{kind:e.kind,filename:e.filename,mediaType:e.mediaType,...e.sizeBytes!==void 0&&{sizeBytes:e.sizeBytes},...e.source!==void 0&&{source:e.source}}}async function vx(e){let{actor:t,source:n,userPermissionLevel:o,attachments:i=[],cards:a=[],entityMemoryRefs:s=[],agentContactCandidates:l=[],canonicalIdentityResolver:c}=e,u=t?await c?.enrichActor(t)??t:null;return{...u?{actor:u}:{},...n?{source:n}:{},...o?{userPermissionLevel:o}:{},...i.length>0?{attachments:i.map((d)=>XF(d))}:{},...a.length>0?{cards:a}:{},...s.length>0?{entityMemoryRefs:s}:{},...l.length>0?{agentContactCandidates:l}:{}}}function bx(e){return Object.keys(e).length>0?{metadata:e}:{}}class bd{deps;constructor(e){this.deps=e}async processMessage(e,t){t?.throwIfAborted();let n=await this.admitTurn(e);if(e.message.trim().length===0&&e.attachments.length>0)return this.answerAttachmentsOnly(n);let o=await this.prepareModelTurn(n,t);this.logAvailableTools(n),await this.recordQuestion(n,o);let i=async()=>{let c=await this.deps.getAgent(e.interfaceType).generate({messages:o.messages,options:this.callOptions(n,o),...t?{abortSignal:t}:{}});return t?.throwIfAborted(),this.recordResponse(n,o,c)},a=this.deps.embeddingUsage;if(!n.guest||!a)return i();let{value:s,usage:l}=await a.measure(i);return s.guestSettlement?{...s,guestSettlement:Gw(s.guestSettlement,l)}:s}async admitTurn(e){let{conversationId:t,message:n,interfaceType:o,channelId:i,channelName:a,actor:s,source:l,attachments:c}=e,u=o===mt;Kr(e);let d=wo(e);if(d&&(!n.trim()||n.length>d.limits.messageCharacters))throw Error("Guest input limit exceeded");if(u){if(s||l||c.length)throw Error("Guest execution denied");let f=await this.deps.conversationService.getConversation(t);if(f?.interfaceType!==mt||f.personId)throw Error("Guest conversation unavailable")}let m=u?null:await this.enrichActor(s),p=i??t;if(!u)await this.deps.conversationService.startConversation({sessionId:t,interfaceType:o,channelId:p,metadata:{channelName:a,interfaceType:o,channelId:p}});return{input:e,guest:u,guestExecution:d,attributedActor:m}}async answerAttachmentsOnly(e){let{conversationId:t,message:n,channelId:o,channelName:i,userPermissionLevel:a,source:s,attachments:l}=e.input;await this.deps.conversationService.addMessage({conversationId:t,role:"user",content:n,...await this.messageMetadata({actor:e.attributedActor,source:s,userPermissionLevel:a,attachments:l,actorAlreadyEnriched:!0})});let c=Hw(l),u=Ww(l),d=u?[u]:[];return await this.deps.conversationService.addMessage({conversationId:t,role:"assistant",content:c,...await this.messageMetadata({actor:this.getAssistantActor(),source:this.buildAssistantSource(o,i),userPermissionLevel:a,cards:d})}),{text:c,toolResults:[],...d.length>0?{cards:d}:{},usage:Tt}}async prepareModelTurn(e,t){let{conversationId:n,message:o,interfaceType:i,channelId:a,channelName:s,userPermissionLevel:l,attachments:c}=e.input,u=await this.deps.conversationService.getMessages(n,{limit:50}),d=ud(u,l).map((x)=>e.guest?{...x,metadata:null}:x),m=gx({message:o,currentAttachments:c,historyMessages:d}),p=await Vw({refs:m.refs,resolver:this.deps.uploadAttachmentResolver,logger:this.deps.logger}),f=m.message,g=await Zw({currentAttachments:m.attachments,uploadRefs:p,resolver:this.deps.uploadAttachmentResolver,logger:this.deps.logger}),h=await this.fetchAgentContext({conversationId:n,message:f,interfaceType:i,channelId:a,channelName:s,userPermissionLevel:l});t?.throwIfAborted();let v=fx(f,g,{uploadRefs:p,...m.priorResponseRef?{priorResponseRef:m.priorResponseRef}:{}});return{effectiveMessage:f,effectiveAttachments:g,uploadRefs:p,hasPriorResponseCandidate:m.priorResponseRef!==void 0,contextItems:h,messages:dd(d,v),agentContextInstructions:gd(h)}}logAvailableTools(e){let t=this.deps.mcpService.listAgentToolsForPermissionLevel(e.input.userPermissionLevel).filter(({tool:n})=>!e.guest||Zr(n)).map((n)=>n.tool.name);this.deps.logger.debug("Available tools for this call",{toolCount:t.length,tools:t})}async recordQuestion(e,t){let{conversationId:n,source:o,userPermissionLevel:i}=e.input;await this.deps.conversationService.addMessage({conversationId:n,role:"user",content:t.effectiveMessage,...await this.messageMetadata({actor:e.attributedActor,source:o,userPermissionLevel:i,attachments:t.effectiveAttachments,actorAlreadyEnriched:!0,guest:e.guest})})}callOptions(e,t){let{conversationId:n,interfaceType:o,channelId:i,channelName:a,userPermissionLevel:s,isAnchor:l}=e.input,c=t.effectiveAttachments.some((u)=>u.source!==void 0);return hx({hasAccessibleUploads:c||t.uploadRefs.length>0,guestExecution:e.guestExecution,userPermissionLevel:s,isAnchor:l,conversationId:n,channelId:i,channelName:a,interfaceType:o,...e.attributedActor?{actor:e.attributedActor}:{},hasPriorResponseCandidate:t.hasPriorResponseCandidate,...t.agentContextInstructions?{agentContextInstructions:t.agentContextInstructions}:{}})}async withGuestAnswerSources(e,t){let n=this.deps.guestAnswerSources;if(!n||t.trim().length===0)return e;try{return sx(e,await n({answer:t}))}catch(o){return this.deps.logger.warn("Guest answer sources unavailable",{error:ke(o)}),e}}async recordResponse(e,t,n){let{conversationId:o,channelId:i,channelName:a,userPermissionLevel:s}=e.input,{guest:l}=e,c=ld(n.steps,n.text),{toolResults:u,pendingConfirmations:d,totalToolCalls:m}=c;if(l&&d.length>0)throw Error("Guest execution denied");let p=l?await this.withGuestAnswerSources(c.cards,n.text):c.cards,f=ox(t.contextItems),g=f?[...p,f]:p,h=d.length>0?"Confirmation required.":n.text.trim().length>0?n.text:nx(u)??n.text,v=l||d.length>0?[]:Qi(u),x=l||d.length>0?[]:cx(u);if(h.trim())await this.deps.conversationService.addMessage({conversationId:o,role:"assistant",content:h,...await this.messageMetadata({actor:l?null:this.getAssistantActor(),source:this.buildAssistantSource(i,a),userPermissionLevel:s,cards:g,entityMemoryRefs:v,agentContactCandidates:x,guest:l})});if(!l)this.deps.logger.debug("Chat completed",{conversationId:o,responseLength:h.length,toolCalls:m,stepCount:n.steps.length,usage:n.usage});return{text:h,toolResults:u,...g.length>0?{cards:g}:{},usage:So(n.usage),...l&&n.guestSettlement?{guestSettlement:n.guestSettlement}:{},...d.length>0?{pendingConfirmations:d}:{}}}async persistCancelledAction(e,t,n){let o=n.channelName??n.channelId??e;await this.deps.conversationService.addMessage({conversationId:e,role:"assistant",content:t.text,...await this.messageMetadata({actor:this.getAssistantActor(),source:this.buildAssistantSource(n.channelId,o),userPermissionLevel:n.userPermissionLevel??"public",cards:t.cards??[]})})}async executeConfirmedAction(e,t){if(t?.throwIfAborted(),e.interfaceType===mt)throw Error("Guest execution denied");let{conversationId:n,pendingConfirmation:o,interfaceType:i,channelId:a,channelName:s,userPermissionLevel:l,isAnchor:c,actor:u}=e,d=await this.enrichActor(u),p=this.deps.mcpService.listAgentToolsForPermissionLevel(l).find((I)=>I.tool.name===o.toolName),f;if(!p)f={success:!1,error:`Tool '${o.toolName}' not found.`};else{let I={interfaceType:i,actor:d?.identity??this.getAssistantActor().identity,...d?.displayName?{displayName:d.displayName}:{},conversationId:n,...a?{channelId:a}:{},channelName:s,userPermissionLevel:l,...t?{signal:t}:{}};try{f=await p.tool.handler(o.args,I)}catch(b){t?.throwIfAborted(),f={success:!1,error:ke(b)}}}t?.throwIfAborted();let g=yx(o,f),v=g.cards.some((I)=>I.kind==="tool-approval"&&I.state==="output-error")?void 0:await this.generatePostConfirmationFollowUp({conversationId:n,resultText:g.resultText,interfaceType:i,channelId:a,channelName:s,userPermissionLevel:l,isAnchor:c,signal:t}),x=Jw(g.toolResult.data),S=v?.text.trim()?`${g.resultText}
117
+
118
+ ${v.text}`:x?`${g.resultText}
119
+
120
+ ${x}`:g.resultText,y=[...g.cards,...v?.cards??[]],w=[g.toolResult,...v?.toolResults??[]],_=v?Qi(v.toolResults??[]):[],C=[...g.entityMemoryRefs,..._];return t?.throwIfAborted(),await this.deps.conversationService.addMessage({conversationId:n,role:"assistant",content:S,...await this.messageMetadata({actor:this.getAssistantActor(),source:this.buildAssistantSource(a,s),userPermissionLevel:l,cards:y,entityMemoryRefs:C})}),{text:S,toolResults:w,cards:y,...v?.pendingConfirmations?{pendingConfirmations:v.pendingConfirmations}:{},usage:v?.usage??{promptTokens:0,completionTokens:0,totalTokens:0}}}async fetchAgentContext(e){if(e.interfaceType===mt||!this.deps.agentContextProvider)return;try{return await this.deps.agentContextProvider({conversationId:e.conversationId,message:e.message,interfaceType:e.interfaceType,channelId:e.channelId,channelName:e.channelName,userPermissionLevel:e.userPermissionLevel??"public"})}catch(t){this.deps.logger.warn("Agent context provider failed",{conversationId:e.conversationId,error:ke(t)});return}}async generatePostConfirmationFollowUp(e){if(e.signal?.throwIfAborted(),!this.deps.agentContextProvider)return;let t=`The operator approved the pending action. The system executed it successfully: ${e.resultText} Continue the conversation naturally. If an active playbook is underway, use the current playbook context as the source of truth, ask only for what is missing in the current playbook state, and give the next immediate action or question. Do not skip ahead or imply uncompleted playbook steps are done. Do not ask for the same confirmation again. Do not suggest repeating the same collection, save, or create task unless the current playbook context explicitly asks for another item. If the approved action saved, created, or updated an item for a completed playbook collection step, do not ask for another item; follow the refreshed current state instead. Do not offer a completed prior-state task as an alternative to the current playbook task. Do not say you found, retrieved, or showed an entity unless the approved action or latest tool result actually performed retrieval or display; after a save or update, say it was saved or updated.`,n=await this.fetchAgentContext({conversationId:e.conversationId,message:t,interfaceType:e.interfaceType,channelId:e.channelId,channelName:e.channelName,userPermissionLevel:e.userPermissionLevel});if(e.signal?.throwIfAborted(),!n||n.length===0)return;let o=await this.deps.conversationService.getMessages(e.conversationId,{limit:50}),i=ud(o,e.userPermissionLevel),a=dd(i,t),s=gd(n),l=await this.deps.getAgent(e.interfaceType).generate({messages:a,options:{userPermissionLevel:e.userPermissionLevel,isAnchor:e.isAnchor,conversationId:e.conversationId,...e.channelId?{channelId:e.channelId}:{},channelName:e.channelName,interfaceType:e.interfaceType,...s?{agentContextInstructions:s}:{},disableTools:!0},...e.signal?{abortSignal:e.signal}:{}});e.signal?.throwIfAborted();let{toolResults:c,pendingConfirmations:u,cards:d}=ld(l.steps,l.text);return{text:u.length>0?"Confirmation required.":l.text,toolResults:c,...d.length>0?{cards:d}:{},...u.length>0?{pendingConfirmations:u}:{},usage:So(l.usage)}}async messageMetadata(e){if(e.guest){let i=_x(e.cards);return{metadata:{userPermissionLevel:"public",...i.length?{cards:i}:{}}}}let{actorAlreadyEnriched:t=!1,guest:n,...o}=e;return bx(await vx({...o,...!t&&this.deps.canonicalIdentityResolver?{canonicalIdentityResolver:this.deps.canonicalIdentityResolver}:{}}))}async enrichActor(e){if(!e||!this.deps.canonicalIdentityResolver)return e;return this.deps.canonicalIdentityResolver.enrichActor(e)}getAssistantActor(){return hd({character:this.deps.identityService.getCharacter(),...this.deps.assistantAgentId?{agentId:this.deps.assistantAgentId}:{}})}buildAssistantSource(e,t){return{...e?{channelId:e}:{},channelName:t}}}class Sd{runtime;closePromise=null;closed=!1;constructor(){let e=pe.runSync(Xe.make()),t=pe.runSync(Xe.extend(_d.make(),e));this.runtime={scope:e,fibers:t}}async run(e,t){if(this.closed)throw Error("Agent service has been shut down");t?.throwIfAborted();let n=pe.runFork(pe.tryPromise({try:e,catch:(i)=>i}));_d.unsafeAdd(this.runtime.fibers,n);let o=()=>{pe.runSync(Yi.interruptFork(n))};if(t?.addEventListener("abort",o,{once:!0}),t?.aborted)o();try{let i=await pe.runPromise(Yi.await(n));if(tt.isSuccess(i))return i.value;if(t?.aborted)throw t.reason;throw ir.squash(i.cause)}finally{t?.removeEventListener("abort",o)}}close(){return this.closed=!0,this.closePromise??=pe.runPromise(Xe.close(this.runtime.scope,tt.void)),this.closePromise}}var eB=10,tB=1800000;function Sx(e,t){return t?AbortSignal.any([e,t]):e}function rB(e){let{email:t,...n}=e;return n}class Xi{get guestReady(){return!this.indexReadiness||this.indexReadiness.isIndexReady()}mcpService;identityService;profileService;logger;stepLimit;agentFactory;agentInstructions;indexReadiness;conversationService;activeTurns=new Sd;shutdownPromise=null;providedMachine=Lw.provide({actors:{processMessage:ce.fromPromise(async({input:e,signal:t})=>this.activeTurns.run((n)=>this.turns.processMessage(e,n),Sx(t,e.signal))),executeConfirmedAction:ce.fromPromise(async({input:e,signal:t})=>this.activeTurns.run((n)=>this.turns.executeConfirmedAction(e,n),Sx(t,e.signal)))}});conversationActors;confirmations;turns;agent=null;guestAgent=null;static createFresh(e,t,n,o,i,a){return new Xi(e,t,n,o,i,a)}constructor(e,t,n,o,i,a){this.mcpService=e,this.conversationService=t,this.identityService=n,this.profileService=o,this.logger=i.child("AgentService"),this.stepLimit=a.stepLimit??eB,this.agentFactory=a.agentFactory,this.agentInstructions=a.agentInstructions,this.indexReadiness=a.indexReadiness,this.turns=new bd({logger:this.logger,conversationService:t,mcpService:e,identityService:n,getAgent:(s)=>this.getAgent(s),assistantAgentId:a.assistantAgentId,canonicalIdentityResolver:a.canonicalIdentityResolver,agentContextProvider:a.agentContextProvider,uploadAttachmentResolver:a.uploadAttachmentResolver,guestAnswerSources:a.guestAnswerSources,embeddingUsage:a.embeddingUsage}),this.conversationActors=new Xu({createActor:()=>{let s=ce.createActor(this.providedMachine);return s.start(),s},isEvictable:(s)=>s.getSnapshot().matches("idle"),idleTtlMs:a.conversationActorIdleTtlMs??tB}),this.confirmations=new td(this.conversationActors,(s,l,c)=>this.turns.persistCancelledAction(s,l,c))}getConversationActors(){return this.conversationActors}getAgent(e){let t=()=>this.mcpService.listAgentToolsForPermissionLevel("public").map(({tool:i})=>i).filter(Zr),n=e===mt,o=(n?this.guestAgent:this.agent)??this.agentFactory({identity:this.identityService.getCharacter(),profile:n?rB(this.profileService.getProfile()):this.profileService.getProfile(),tools:n?t():this.mcpService.listAgentToolsForPermissionLevel("admin").map((i)=>i.tool),pluginInstructions:this.mcpService.getInstructions(),...this.agentInstructions&&{agentInstructions:this.agentInstructions},stepLimit:this.stepLimit,getToolsForPermission:n?t:(i)=>this.mcpService.listAgentToolsForPermissionLevel(i).map((a)=>a.tool)});if(n)this.guestAgent=o;else this.agent=o;return o}invalidateAgent(){this.agent=null,this.guestAgent=null,this.logger.debug("Agent invalidated, will be recreated on next chat")}async chat(e,t,n,o){if(o?.throwIfAborted(),this.indexReadiness&&!this.indexReadiness.isIndexReady())return{text:"I'm still getting the knowledge base ready. Please try again in a moment.",usage:Tt};let i=n?.userPermissionLevel??"public",a=n?.interfaceType??"agent",s=n?.channelId,l=n?.channelName??s??t,c=a===mt;if(Kr({interfaceType:a,userPermissionLevel:i,isAnchor:n?.isAnchor??!1}),c&&(n?.actor||n?.source||n?.attachments?.length))throw Error("Guest execution denied");let u=wo({interfaceType:a,guestExecution:n?.guestExecution});if(u){if(!e.trim()||e.length>u.limits.messageCharacters)throw Error("Guest input limit exceeded");let m=AbortSignal.timeout(u.limits.requestTimeoutSeconds*1000);o=o?AbortSignal.any([o,m]):m}let d=await this.conversationService.getConversation(t);if(c&&(d?.interfaceType!==mt||d.personId)||!c&&d?.interfaceType===mt)throw Error("Guest conversation unavailable");if(!c)this.logger.debug("Processing chat message",{conversationId:t,messageLength:e.length,userPermissionLevel:i});return this.conversationActors.enqueue(t,async(m)=>{m.throwIfAborted();let p=this.conversationActors.acquire(t),f=p.getSnapshot();if(f.matches("awaitingConfirmation")){if(c)throw Error("Guest execution denied");let h={interfaceType:a,channelId:s,channelName:l,userPermissionLevel:i,isAnchor:n?.isAnchor??!1,actor:n?.actor??null,source:n?.source??null},v=f.context.pendingConfirmations,x=wx(e),S=v.filter((y)=>ed(y,h));if(x){let[y]=S;if(S.length!==1||!y)return{text:S.length===0?"You are not authorized to confirm this pending action.":"Multiple approvals are pending; include one approval id with yes or no/cancel.",pendingConfirmations:v,usage:Tt};return this.confirmations.resolve(t,p,y,x.confirmed,h,m)}if(S.length>0)for(let y of S)await this.confirmations.resolve(t,p,y,!1,h,m);else return{text:"A pending action is awaiting confirmation. Please try again once it has been resolved.",pendingConfirmations:v,usage:Tt}}p.send({type:"RECEIVE_MESSAGE",message:e,conversationId:t,interfaceType:a,channelId:s,channelName:l,userPermissionLevel:i,isAnchor:n?.isAnchor??!1,actor:n?.actor??null,source:n?.source??null,attachments:n?.attachments??[],...u?{guestExecution:u}:{},signal:m});let g=await ce.waitFor(p,(h)=>h.matches("idle")||h.matches("awaitingConfirmation"));if(m.throwIfAborted(),u&&g.context.error)throw this.logger.error("Guest turn failed",{conversationId:t,error:g.context.error}),Error("Guest execution unavailable");if(u&&!g.context.response?.text.trim())this.logger.warn("Guest turn produced no answer",{conversationId:t});return g.context.response??{text:"No response generated.",usage:Tt}},o)}async confirmPendingAction(e,t,n,o,i){if(i?.throwIfAborted(),yr(o)&&o.interfaceType===mt||(await this.conversationService.getConversation(e))?.interfaceType===mt)throw Error("Guest execution denied");return this.conversationActors.enqueue(e,(a)=>this.confirmations.run(e,t,n,o,a),i)}shutdown(){return this.shutdownPromise??=this.shutdownActiveTurns(),this.shutdownPromise}async shutdownActiveTurns(){let e=Error("Agent service has been shut down"),n=(await Promise.allSettled([this.conversationActors.close(e),this.activeTurns.close()])).find((o)=>o.status==="rejected");if(n)throw n.reason}}var Tx=r.object({userPermissionLevel:r.enum(["admin","trusted","public"]),isAnchor:r.boolean().optional(),conversationId:r.string(),channelId:r.string().optional(),channelName:r.string().optional(),interfaceType:r.string(),actor:xx.optional(),displayName:r.string().optional(),agentContextInstructions:r.string().optional(),disableTools:r.boolean().optional(),enableCreateUpload:r.boolean().optional(),enableCreateTransform:r.boolean().optional(),hasPriorResponseCandidate:r.boolean().optional(),guestExecution:is.optional()});function Ix(e,t,n,o,i,a,s=!1){let u=`
121
+ ## Current User
122
+ ${t==="admin"?"The current caller's canonical permission level is **Admin**. This authorizes administrative actions and reading restricted/private content returned by tools. If asked to show/read a restricted record and the tool returns content, display it.":t==="trusted"?"The current caller's canonical permission level is **Trusted**.":"The current caller's canonical permission level is **Public**. Public access is limited and read-oriented and generally cannot create, update, delete, publish, sync, or otherwise mutate content."}
123
+ ${s?"The current caller is the brain's configured Anchor identity. This identity fact does not grant Admin permission; authorization comes only from the permission level above.":"The current caller is not the brain's configured Anchor identity. This is a definitive account-relationship fact for the current request, not an unknown or unverified state. Their permission level must not be treated as proof that they are the Anchor, owner, or profile person."}`,d="";if(o){let m=[o.name&&`**Name:** ${o.name}`,o.email&&`**Email:** ${o.email}`,o.website&&`**Website:** ${o.website}`,o.description&&`**Bio:** ${o.description}`].filter(Boolean);if(m.length>0)d=`
124
+ ## Your Anchor
125
+ ${m.join(`
126
+ `)}`}return`# ${e.name}
127
+
128
+ **Role:** ${e.role}
129
+ **Purpose:** ${e.purpose}
130
+ **Values:** ${e.values.join(", ")}
131
+ ${d}
132
+ ${u}
133
+
134
+ ## Identity and Permissions
135
+ - **Identity**: This is YOU \u2014 the brain's persona, role, purpose, and values (shown above).
136
+ - **Profile**: This is your ANCHOR \u2014 the person or team that owns and manages this brain (shown above, when configured).
137
+ - When someone asks "who are you?", describe yourself using your identity.
138
+ - When someone asks "who owns this?", describe your anchor using the profile if available.
139
+ - Answer identity/profile requests in at most 40 words, no headings/bullets.
140
+ - For direct identity/profile requests, phrase the brain identity as "I am {identity name}" or "I'm {identity name}" and the profile as "Your anchor/profile is {profile name}"; never say "{identity name} is my identity".
141
+ - Use the top heading as your identity name and the "Your Anchor" section as the profile/owner/team, never substituting the anchor/profile name as your own identity name.
142
+ - Do not infer that the current caller is your anchor, owner, or the profile person from the profile itself or from Admin permission. The profile describes the owner; it does not identify the caller.
143
+ - If asked "am I your anchor?", answer directly from the explicit Anchor identity status in the Current User section, never from the permission level: begin with "Yes." when the caller is the configured Anchor and "No." when the caller is not. Do not weaken a definite "No" to "cannot verify," "not established," or similar ambiguity. Do not name, volunteer, or disclose the configured anchor/profile identity in that answer unless the user explicitly asks who owns the brain.
144
+ - If asked "what is my permission level?" or an equivalent question, answer directly with the exact canonical label **Admin**, **Trusted**, or **Public** shown in the Current User section. Do not substitute generic descriptions such as "elevated access," and do not infer Anchor identity from permission.
145
+ - If asked "am I {profile name}?", use the explicit Anchor identity status only to answer whether the caller is the configured Anchor; do not claim broader real-world identity verification. Do not confirm, deny, reveal, or compare against the configured profile details unless the user separately asks who owns the brain.
146
+ - When your anchor is talking to you, address them personally only when the Current User section explicitly establishes that identity; otherwise address them as the current user/operator.
147
+ - The caller's permission level controls available tools and content access. Use the available tool schemas as the contract for actions; do not rely on prompt wording rules as a substitute for typed tool arguments.
148
+ - For create, update, delete, extract, publish, sync, and other durable actions, call the relevant tool first instead of asking for confirmation in prose. Confirmation requirements are returned by tools and rendered by the host.
149
+ - Durable write tools may require built-in confirmation. Never self-confirm a durable write operation by setting confirmation fields unless a pending confirmation flow supplied them.
150
+ - If a tool returns a permission denial, report it concisely and do not retry the same denied action.`+(i&&i.length>0?`
151
+
152
+ ### Brain-Specific Behavior (MANDATORY)
153
+
154
+ ${i.join(`
155
+
156
+ `)}`:"")+(n&&n.length>0?`
157
+
158
+ ### Plugin-Specific Behavior (MANDATORY)
159
+
160
+ ${n.join(`
161
+
162
+ `)}`:"")+(a?`
163
+
164
+ ### Retrieved Conversation Memory (CONTEXT)
165
+
166
+ ${a}`:"")}function wd(e,t,n,o){let i=n.actor??{kind:"agent",agentId:"brain-agent"};return async(a,s)=>{if(o){let l={toolName:e,args:a,conversationId:n.conversationId,interfaceType:n.interfaceType,actor:i,...n.displayName!==void 0&&{displayName:n.displayName},...n.channelId!==void 0&&{channelId:n.channelId},...n.channelName!==void 0&&{channelName:n.channelName},...s?.toolCallId!==void 0&&{toolCallId:s.toolCallId}};await o.emit("tool:invoking",l)}try{let l=s?await t(a,s):await t(a);if(o){let c={toolName:e,conversationId:n.conversationId,interfaceType:n.interfaceType,actor:i,...n.displayName!==void 0&&{displayName:n.displayName},...n.channelId!==void 0&&{channelId:n.channelId},...n.channelName!==void 0&&{channelName:n.channelName},...s?.toolCallId!==void 0&&{toolCallId:s.toolCallId}};await o.emit("tool:completed",c)}return l}catch(l){if(o){let c={toolName:e,error:ke(l),conversationId:n.conversationId,interfaceType:n.interfaceType,actor:i,...n.displayName!==void 0&&{displayName:n.displayName},...n.channelId!==void 0&&{channelId:n.channelId},...n.channelName!==void 0&&{channelName:n.channelName},...s?.toolCallId!==void 0&&{toolCallId:s.toolCallId}};await o.emit("tool:failed",c)}throw l}}}function xd(e,t="brain-agent"){return{emit:async(n,o)=>{await e.send({type:n,payload:o,sender:t,broadcast:!0}).catch(()=>{return})}}}var Td={success:!1,error:"Public retrieval unavailable"},nB=500;function oB(e){if(!Ss(e))return Td;if(e.success===!0)return e;let t=e.error;return{success:!1,error:typeof t==="string"&&t.trim()?t.slice(0,nB):"Nothing public matches that request."}}var iB=new Set(["confirmed","confirmationToken","contentHash"]),aB=new Set(["content","prompt","url","from","upload","transform","sourceAttachment"]),sB=r.looseObject({success:r.literal(!0),data:r.looseObject({documentId:r.string().min(1).optional(),entityId:r.string().min(1).optional(),attachment:r.looseObject({mediaType:r.string().min(1),url:r.string().min(1),downloadUrl:r.string().min(1).optional(),previewUrl:r.string().min(1).optional(),filename:r.string().min(1).optional(),sizeBytes:r.number().nonnegative().optional(),source:r.object({entityType:r.string().optional(),entityId:r.string().optional(),attachmentType:r.string().optional()}).optional()})})});function lB(e){return typeof e==="object"&&e!==null&&"safeParse"in e&&typeof e.safeParse==="function"}function cB(e,t={}){let n={};for(let[o,i]of Object.entries(e)){if(iB.has(o))continue;if(t.toolName==="system_create"&&aB.has(o))continue;if(lB(i))n[o]=i}return n}function uB(e){let t=sB.safeParse(e);if(!t.success)return{type:"json",value:Cx(e)};let{attachment:n}=t.data.data,o={mediaType:n.mediaType,...n.filename!==void 0?{filename:n.filename}:{},...n.sizeBytes!==void 0?{sizeBytes:n.sizeBytes}:{},...gt({source:n.source})};return{type:"json",value:Cx({...t.data,data:{...t.data.data,attachment:o,artifactCard:{rendered:!0,message:"The UI has rendered this artifact as an attachment card with Open and Download controls. Do not print raw attachment URLs in the assistant response."}}})}}function dB(e){if(!Ss(e))return e;if(e.success!==!0)return e;return{...e,cached:!0}}function Cx(e){if(e===void 0)return null;return kx.parse(JSON.parse(JSON.stringify(e)))}function Id(e,t,n){Kr(t);let o=t.interfaceType===mt;if(o&&(t.actor||t.displayName||t.enableCreateUpload||t.enableCreateTransform))throw Error("Guest execution denied");let i={},a=new Map;for(let s of e){if(o&&!Zr(s))continue;let l=wd(s.name,async(c,u)=>{if(o&&!Zr(s))throw Error("Guest execution denied");let d=u?.abortSignal,m={interfaceType:t.interfaceType,actor:t.actor??{kind:"agent",agentId:"brain-agent"},...t.displayName?{displayName:t.displayName}:{},conversationId:t.conversationId,...t.channelId&&{channelId:t.channelId},...u?.toolCallId&&{toolCallId:u.toolCallId},...d&&{signal:d},...t.channelName&&{channelName:t.channelName},...t.userPermissionLevel&&{userPermissionLevel:t.userPermissionLevel},...t.isAnchor!==void 0&&{isAnchor:t.isAnchor},...o&&{userPermissionLevel:"public",isAnchor:!1}};if(s.sideEffects!=="none"){if(s.sideEffects==="writes"||s.sideEffects==="external")a.clear();return s.handler(c,m)}let p=`${s.name}:${JSON.stringify(c)}`;if(!o&&a.has(p))return dB(a.get(p));let f;try{f=o?oB(await s.handler(c,m)):await s.handler(c,m)}catch(g){if(!o)throw g;f=Td}if(o&&!Ss(f))f=Td;if(!o)a.set(p,f);return f},t,o?void 0:n);i[s.name]=Rl({description:s.description,inputSchema:r.object(cB(s.inputSchema,{toolName:s.name,...t.enableCreateUpload!==void 0&&{enableCreateUpload:t.enableCreateUpload},...t.enableCreateTransform!==void 0&&{enableCreateTransform:t.enableCreateTransform}})),execute:l,toModelOutput:({output:c})=>uB(c)})}return i}function pB(e,t){return t.interfaceType===mt?e.filter(Zr):e}function mB(e){return typeof e==="object"&&e!==null&&"action"in e&&e.action==="start"}function gB(e){let t=e.steps.at(-1),n=t?.toolResults?.some((i)=>_s.safeParse(i.output).success)??!1,o=t?.toolCalls?.some((i)=>i.toolName==="playbook_manage"&&mB(i.input))??!1;return n||o}function Cd(e){let{model:t,modelId:n,webSearch:o,temperature:i,maxTokens:a,reasoningEffort:s,messageBus:l}=e,c=Di(n),u=xd(l);return function(p){let f=Id(p.tools,{conversationId:"",interfaceType:"agent"},u),g=new Hb({model:t,callOptionsSchema:Tx,prepareCall:({options:h,...v})=>{Kr(h);let x=h.interfaceType===mt;if(x&&(h.actor||h.agentContextInstructions||h.enableCreateUpload||h.enableCreateTransform))throw Error("Guest execution denied");let S=h.disableTools?[]:pB(p.getToolsForPermission(h.userPermissionLevel),h),y=S.map((_)=>_.name),w=Id(S,{conversationId:h.conversationId,channelId:h.channelId,channelName:h.channelName,interfaceType:h.interfaceType,actor:h.actor,displayName:h.displayName,userPermissionLevel:h.userPermissionLevel,isAnchor:h.isAnchor,enableCreateUpload:h.enableCreateUpload,enableCreateTransform:h.enableCreateTransform},u);return{...v,...x&&{messages:Au(v.messages),allowSystemInMessages:!1,providerOptions:{}},instructions:Ix(p.identity,h.userPermissionLevel,p.pluginInstructions,p.profile,p.agentInstructions,h.agentContextInstructions,h.isAnchor)+(x?`
167
+
168
+ ${zS}`:""),tools:w,activeTools:y,...i!==void 0&&c.supportsTemperature&&{temperature:i},...a!==void 0&&{maxTokens:a},...(c.provider==="openai"&&s!==void 0?!0:o&&!x)&&{providerOptions:{...c.provider==="openai"&&s&&{openai:{reasoningEffort:s}},...o&&!x&&{anthropic:{webSearch:!0}}}}}},tools:f,stopWhen:[gB,ji(p.stepLimit??10)]});return{generate:async(h)=>{Kr(h.options);let v=wo(h.options);if(!v)return g.generate(h);let x=Au(h.messages).at(-1);if(x?.role!=="user"||typeof x.content!=="string"||!x.content.trim()||x.content.length>v.limits.messageCharacters)throw Error("Guest input limit exceeded");let S=await g.generate(h);return Object.assign(S,{guestSettlement:Bw(S.steps,e.guestPricing)})}}}}async function ws(e,t,n){let o=await e.send({type:Rx,sender:t,payload:{actor:n}});if("noop"in o)return null;if(!o.success)throw Error("Principal resolution unavailable");return Ex.parse(o.data).principal}function Px(e,t){return new Ax(e,(n)=>ws(t,"shell:content-service",n))}var kd=rt.GenericTag("@brains/conversation-service/ConversationService");function hB(e){if(e.service){let n=e.service;return{service:n,close:()=>n.close()}}let t=Mx.createFreshFromConfig(e.logger,e.messageBus,e.dbConfig,e.config);try{return{service:t,close:()=>t.close()}}catch(n){throw t.close(),n}}function jx(e){return vn(kd,()=>hB(e))}var Rd=rt.GenericTag("@brains/entity-service/EntityService");function yB(e){return"close"in e&&typeof e.close==="function"}function Nx(e){return vn(Rd,()=>{let t=e.service??Ox.createFresh(e);return{service:t,close:()=>{if(yB(t))t.close()}}})}var ea=r.strictObject({dedupeKey:r.string().min(1).max(512),title:r.string().min(1),body:r.string().min(1),html:r.string().min(1).optional(),sensitivity:r.enum(["normal","secret"]).optional(),includeInInbox:r.boolean().optional()}),Ed=r.strictObject({alerts:r.array(ea).optional()});var xs="shell:recurring-check",Pd=86400000,vB=7*Pd,bB=3*Pd,_B=r.strictObject({checkId:r.string().min(1)}),SB=r.discriminatedUnion("kind",[r.strictObject({kind:r.literal("last-success"),checkId:r.string(),at:r.string().datetime()}),r.strictObject({kind:r.literal("alert"),checkId:r.string(),dedupeKey:r.string(),status:r.enum(["pending","suppressed","delivered","resolved"]),alert:ea,observedAt:r.string().datetime(),includeInInbox:r.boolean().optional(),deliveredAt:r.string().datetime().optional(),resolvedAt:r.string().datetime().optional()})]);class Ts{brainId;scheduler;state;jobQueue;delivery;logger;clock;nowFallback;checks=new Map;pluginChecks=new Map;alertOperations=new zx;handlerRegistered=!1;started=!1;stopPromise=null;constructor(e){this.brainId=e.brainId,this.scheduler=e.scheduler,this.jobQueue=e.jobQueue,this.delivery=e.delivery,this.logger=e.logger.child("RecurringCheckService"),this.clock=e.clock,this.nowFallback=e.now??(()=>new Date),this.state=e.runtimeState.scoped({namespace:"shell.recurring-checks",schema:SB});let t={validateAndParse:(n)=>{let o=_B.safeParse(n);return o.success?o.data:null},process:async(n)=>{await this.runNow(n.checkId)}};this.jobQueue.registerHandler(xs,t,"shell"),this.handlerRegistered=!0}abandon(){if(this.started)throw Error("Cannot abandon a running recurring check service");if(!this.handlerRegistered)return;this.jobQueue.unregisterHandler(xs),this.handlerRegistered=!1}namespace(e){return{register:(t)=>this.register(e,t)}}register(e,t){Dx(e,"plugin ID"),Dx(t.id,"check ID");let n=`${e}:${t.id}`;if(this.checks.has(n))throw Error(`Recurring check already registered: ${n}`);let o={pluginId:e,definition:{...t,id:n},catchUpTasks:new Set};this.checks.set(n,o);let i=this.pluginChecks.get(e)??new Set;if(i.add(o),this.pluginChecks.set(e,i),this.started)this.schedule(o),this.trackCatchUp(o).catch((a)=>{this.logger.error(`Failed to enqueue recurring check ${n}`,a)});return()=>{this.releaseRegisteredCheck(o,Error(`Recurring check unregistered: ${n}`)).catch((a)=>{this.logger.error(`Failed to unregister recurring check ${n}`,a)})}}async unregisterPlugin(e){let t=[...this.pluginChecks.get(e)??[]];await Promise.all(t.map((n)=>this.releaseRegisteredCheck(n,Error(`Recurring check plugin unregistered: ${e}`))))}async start(){if(this.started)return;if(this.stopPromise)await this.stopPromise,this.stopPromise=null;this.started=!0;for(let e of this.checks.values())this.schedule(e);await Promise.all([...this.checks.values()].map((e)=>this.trackCatchUp(e)))}stop(){return this.stopPromise??=this.stopChecks(),this.stopPromise}async stopChecks(){this.started=!1;let e=Error("Recurring check service stopped"),t=[...this.pluginChecks.values()].flatMap((n)=>[...n]);await Promise.all(t.map((n)=>n.releasePromise??this.settleRegisteredCheck(n,e)))}async runNow(e,t){t?.throwIfAborted();let n=this.checks.get(e);if(!n)throw Error(`Unknown recurring check: ${e}`);if(n.activeCheck)return this.logger.debug(`Skipping overlapping recurring check: ${e}`),!1;let o=new AbortController,i=t?AbortSignal.any([o.signal,t]):o.signal,a=this.executeRegisteredCheck(n,i),s={controller:o,settled:Promise.resolve()};n.activeCheck=s;let l=()=>{if(n.activeCheck===s)delete n.activeCheck};return s.settled=a.then(l,l),a}async executeRegisteredCheck(e,t){let n=e.definition.id,o=pe.tryPromise({try:async(a)=>{let s=AbortSignal.any([t,a]),l=e.definition.deliverAlerts!==!1;if(l)await this.flushPendingAlerts(n);else await this.suppressPendingAlerts(n);s.throwIfAborted();let c=await e.definition.run({signal:s});s.throwIfAborted();let u=Ed.parse(c);for(let d of u.alerts??[])s.throwIfAborted(),await this.recordAlert(n,d,{deliver:l,includeInInbox:d.includeInInbox??e.definition.includeInInbox!==!1});await this.state.set(this.lastSuccessKey(n),{kind:"last-success",checkId:n,at:this.currentTime().toISOString()})},catch:(a)=>a}),i=await pe.runPromiseExit(o,{signal:t});if(tt.isSuccess(i))return!0;if(t.aborted)throw t.reason;throw ir.squash(i.cause)}getRegisteredCheckIds(){return[...this.checks.keys()]}trackCatchUp(e){let t=this.enqueueCatchUpIfNeeded(e.definition);e.catchUpTasks.add(t);let n=()=>{e.catchUpTasks.delete(t)};return t.then(n,n),t}releaseRegisteredCheck(e,t){if(e.releasePromise)return e.releasePromise;let n=e.definition.id;if(this.checks.get(n)===e)this.checks.delete(n);let o=this.releaseRegisteredCheckOnce(e,t);return e.releasePromise=o,o}async releaseRegisteredCheckOnce(e,t){try{await this.settleRegisteredCheck(e,t)}finally{let n=this.pluginChecks.get(e.pluginId);if(n?.delete(e),n?.size===0)this.pluginChecks.delete(e.pluginId)}}async settleRegisteredCheck(e,t){let n=[];if(e.scheduledJob)n.push(e.scheduledJob.stop()),delete e.scheduledJob;if(e.activeCheck)e.activeCheck.controller.abort(t),n.push(e.activeCheck.settled);n.push(...e.catchUpTasks);let i=(await Promise.allSettled(n)).find((a)=>a.status==="rejected");if(i)throw i.reason}schedule(e){let t=e.definition,n=Ad(this.brainId,t.id,t.cadence);e.scheduledJob=this.scheduler.scheduleCron(n.expression,async()=>{try{await this.enqueue(t.id)}catch(o){this.logger.error(`Failed to enqueue scheduled recurring check ${t.id}`,o)}},{timezone:"UTC"})}async enqueueCatchUpIfNeeded(e){let t=this.currentTime(),n=Ad(this.brainId,e.id,e.cadence),o=Ux(t,n),i=await this.state.get(this.lastSuccessKey(e.id));if(i?.kind==="last-success"&&new Date(i.at)>=o)return;await this.enqueue(e.id)}enqueue(e){let t={source:"shell",metadata:{operationType:"data_processing",operationTarget:e,silent:!0},maxRetries:3,deduplication:"skip",deduplicationKey:e};return this.jobQueue.enqueue({type:xs,data:{checkId:e},options:t})}async listOpenAlerts(){return(await this.state.list({keyPrefix:"alert:"})).flatMap((t)=>{let n=t.value;if(n.kind!=="alert"||n.status==="resolved")return[];if(!(n.includeInInbox??this.checks.get(n.checkId)?.definition.includeInInbox!==!1))return[];return[{id:t.key,checkId:n.checkId,title:n.alert.title,body:n.alert.body,observedAt:n.observedAt}]}).sort((t,n)=>t.observedAt.localeCompare(n.observedAt)||t.id.localeCompare(n.id))}async resolveOpenAlert(e){await this.alertOperations.run(e,async()=>{let t=await this.state.get(e),n=t?.kind==="alert"&&(t.includeInInbox??this.checks.get(t.checkId)?.definition.includeInInbox!==!1);if(t?.kind!=="alert"||t.status==="resolved"||!n)throw Error("Recurring-check inbox item is not open");await this.state.set(e,{...t,status:"resolved",resolvedAt:this.currentTime().toISOString()})})}async flushPendingAlerts(e){let t=await this.state.list({keyPrefix:this.alertKeyPrefix(e)});for(let n of t)await this.alertOperations.run(n.key,async()=>{let o=await this.state.get(n.key);if(o?.kind==="alert"&&(o.status==="pending"||o.status==="suppressed"))await this.deliverStoredAlert(n.key,o)})}async suppressPendingAlerts(e){let t=await this.state.list({keyPrefix:this.alertKeyPrefix(e)});for(let n of t)await this.alertOperations.run(n.key,async()=>{let o=await this.state.get(n.key);if(o?.kind==="alert"&&o.status==="pending")await this.state.set(n.key,{...o,status:"suppressed"})})}async recordAlert(e,t,n){let o=ea.parse(t),i=this.alertKey(e,o.dedupeKey);await this.alertOperations.run(i,async()=>{let a=await this.state.get(i);if(a?.kind==="alert"){let l=a.includeInInbox===n.includeInInbox?a:{...a,includeInInbox:n.includeInInbox};if(l!==a)await this.state.set(i,l);if(l.status==="delivered"||l.status==="resolved")return;if(n.deliver)await this.deliverStoredAlert(i,l);return}let s={kind:"alert",checkId:e,dedupeKey:o.dedupeKey,status:n.deliver?"pending":"suppressed",alert:o,observedAt:this.currentTime().toISOString(),includeInInbox:n.includeInInbox};if(await this.state.set(i,s),n.deliver)await this.deliverStoredAlert(i,s)})}async deliverStoredAlert(e,t){if(await this.delivery.deliver(t.alert)===!1)return;await this.state.set(e,{...t,status:"delivered",deliveredAt:this.currentTime().toISOString()})}currentTime(){return this.clock?new Date(this.clock.unsafeCurrentTimeMillis()):this.nowFallback()}lastSuccessKey(e){return`run:${bn(e)}`}alertKeyPrefix(e){return`alert:${bn(e)}:`}alertKey(e,t){return`${this.alertKeyPrefix(e)}${bn(t)}`}}function Ad(e,t,n){let o=n==="daily"?Pd:vB,i=o/60000,a=bn(`${e}\x00${t}\x00${n}`),s=Number.parseInt(a.slice(0,12),16)%i,l=s%60,c=Math.floor(s/60),u=c%24;return{expression:n==="daily"?`${l} ${u} * * *`:`${l} ${u} * * ${Math.floor(c/24)}`,offsetMs:s*60000,periodMs:o,anchorMs:n==="daily"?0:bB}}function Ux(e,t){let n=e.getTime(),o=n-t.anchorMs,a=t.anchorMs+Math.floor(o/t.periodMs)*t.periodMs+t.offsetMs;if(a>n)a-=t.periodMs;return new Date(a)}function Dx(e,t){if(!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(e))throw Error(`Invalid recurring-check ${t}: ${e}. Use 1-64 alphanumeric, _, or - characters.`)}var qe=$x("runtime_state_records",{namespace:Is("namespace").notNull(),key:Is("key").notNull(),value:Is("value",{mode:"json"}).notNull(),createdAt:Md("created_at").notNull(),updatedAt:Md("updated_at").notNull()},(e)=>({pk:qx({columns:[e.namespace,e.key]}),namespaceUpdatedAtIdx:Lx("idx_runtime_state_namespace_updated_at").on(e.namespace,e.updatedAt)}));function Bx(e){return Fx({url:e.url,schema:{runtimeStateRecords:qe},authToken:e.authToken,authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN"})}var wB=/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,127}$/,Vx=512;class Od{db;namespace;schema;now;constructor(e,t,n,o=()=>new Date){xB(t),this.db=e,this.namespace=t,this.schema=n,this.now=o}async get(e){let t=Bn(e),o=(await this.db.select().from(qe).where(Do(ar(qe.namespace,this.namespace),ar(qe.key,t))).limit(1))[0];if(!o)return null;return this.schema.parse(o.value)}async has(e){let t=Bn(e);return(await this.db.select({key:qe.key}).from(qe).where(Do(ar(qe.namespace,this.namespace),ar(qe.key,t))).limit(1)).length>0}async set(e,t){let n=Bn(e),o=this.schema.parse(t),i=this.now().getTime();await this.db.insert(qe).values({namespace:this.namespace,key:n,value:o,createdAt:i,updatedAt:i}).onConflictDoUpdate({target:[qe.namespace,qe.key],set:{value:o,updatedAt:i}})}async setIfNotExists(e,t){let n=Bn(e),o=this.schema.parse(t),i=this.now().getTime(),a=await this.db.insert(qe).values({namespace:this.namespace,key:n,value:o,createdAt:i,updatedAt:i}).onConflictDoNothing({target:[qe.namespace,qe.key]});return Number(a.rowsAffected)>0}async compareAndSet(e,t,n){let o=Bn(e),i=this.schema.parse(t),a=this.schema.parse(n),s=await this.db.update(qe).set({value:a,updatedAt:this.now().getTime()}).where(Do(ar(qe.namespace,this.namespace),ar(qe.key,o),ar(qe.value,i)));return Number(s.rowsAffected)===1}async delete(e){let t=Bn(e),n=await this.db.delete(qe).where(Do(ar(qe.namespace,this.namespace),ar(qe.key,t)));return Number(n.rowsAffected)>0}async list(e={}){return(await this.listRows(e)).map((n)=>({key:n.key,value:this.schema.parse(n.value),createdAt:new Date(n.createdAt),updatedAt:new Date(n.updatedAt)}))}async clear(e={}){let t=e.keyPrefix;if(t===void 0){let o=await this.db.delete(qe).where(ar(qe.namespace,this.namespace));return Number(o.rowsAffected)}Gx(t);let n=await this.list({keyPrefix:t});return await Promise.all(n.map((o)=>this.delete(o.key))),n.length}async listRows(e){let{keyPrefix:t,afterKey:n,limit:o}=e;if(t!==void 0)Gx(t);if(n!==void 0)Bn(n);if(o!==void 0)r.number().int().min(1).max(1000).parse(o);let i=this.db.select({...Jx(qe),key:jd`CAST(${qe.key} AS BLOB)`.mapWith((a)=>new TextDecoder("utf-8",{fatal:!0}).decode(a))}).from(qe).where(Do(ar(qe.namespace,this.namespace),t!==void 0?jd`substr(CAST(${qe.key} AS BLOB), 1, length(CAST(${t} AS BLOB))) = CAST(${t} AS BLOB)`:void 0,n!==void 0?Hx(qe.key,n):void 0)).orderBy(Wx(qe.key)).$dynamic();return o===void 0?i:i.limit(o)}}function xB(e){if(!wB.test(e))throw Error(`Invalid runtime state namespace: ${e}. Use 1-128 alphanumeric, _, ., :, or - characters.`)}function Bn(e){if(e.length===0||e.length>Vx)throw Error("Runtime state keys must be 1-512 characters long");return e}function Gx(e){if(e.length>Vx)throw Error("Runtime state key prefixes must be 512 characters or shorter");return e}class Cs{db;client;logger;databaseUrl;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;static createFresh(e,t){return new Cs(e,t??vr.getInstance())}constructor(e,t){let{db:n,client:o,url:i}=Bx(e);this.db=n,this.client=o,this.databaseUrl=i,this.logger=t.child("RuntimeStateService")}initialize(){if(this.closeRequested)return Promise.resolve();return this.walInitialization??=this.initializeWALMode(),this.walInitialization}async initializeWALMode(){try{await Zx(this.client,this.databaseUrl)}catch(e){this.logger.warn("Failed to enable runtime state WAL mode (non-fatal)",e)}finally{if(this.walInitializationSettled=!0,this.closeRequested)this.closeClient()}}scoped(e){return new Od(this.db,e.namespace,e.schema)}close(){if(this.closeRequested=!0,!this.walInitialization||this.walInitializationSettled)this.closeClient()}closeClient(){if(this.clientClosed)return;this.clientClosed=!0,this.client.close()}}var Nd=rt.GenericTag("@brains/runtime-state/RuntimeStateService");function Kx(e){return vn(Nd,()=>{let t=e.service??Cs.createFresh(e.config,e.logger);return{service:t,close:()=>t.close()}})}async function Dd(e,t){if(e.status==="running"){t.warn(`Daemon already running: ${e.name}`);return}e.status="starting",delete e.error;try{await e.daemon.start(),e.status="running",e.startedAt=new Date,t.debug(`Daemon started successfully: ${e.name}`)}catch(n){throw e.status="error",e.error=ta(n),t.warn(`Daemon ${e.name} failed to start: ${ke(n)}`),n}}async function zd(e,t){if(e.status==="stopped"){t.warn(`Daemon already stopped: ${e.name}`);return}e.status="stopping";try{await e.daemon.stop(),e.status="stopped",e.stoppedAt=new Date,t.debug(`Daemon stopped successfully: ${e.name}`)}catch(n){throw e.status="error",e.error=ta(n),t.error(`Failed to stop daemon: ${e.name}`,n),n}}async function Yx(e){if(!e.daemon.healthCheck)return;try{let t=await e.daemon.healthCheck();return e.health=t,t}catch(t){let n={status:"error",message:ke(t),lastCheck:new Date};return e.health=n,n}}function Qx(e){return{name:e.name,pluginId:e.pluginId,status:e.status,health:e.health}}async function Mr(e){let t=await pe.runPromiseExit(e);if(tt.isSuccess(t))return t.value;throw ir.squash(t.cause)}async function Ud(e){let n=(await Mr(pe.all(e.map((o)=>pe.either(pe.tryPromise({try:o,catch:(i)=>i}))),{concurrency:"unbounded"}))).find(Xx.isLeft);if(n)throw n.left}class ks{daemons=new Map;daemonScopes=new Map;daemonTransitions=new Map;logger;static createFresh(e){return new ks(e)}constructor(e){this.logger=e.child("DaemonRegistry")}register(e,t,n){if(this.daemonScopes.has(e))throw Error(`Cannot overwrite running daemon: ${e}`);if((this.daemonTransitions.get(e)?.pending??0)>0)throw Error(`Cannot overwrite transitioning daemon: ${e}`);if(this.daemons.has(e))this.logger.warn(`Daemon already registered: ${e}, overwriting`);let o={name:e,daemon:t,pluginId:n,status:"stopped"};this.daemons.set(e,o),this.logger.debug(`Registered daemon: ${e} from plugin: ${n}`)}has(e){return this.daemons.has(e)}get(e){return this.daemons.get(e)}start(e){if(!this.daemons.has(e))return Promise.reject(Error(`Daemon not registered: ${e}`));return this.enqueueTransition(e,"start",()=>this.startDaemon(e))}async startDaemon(e){let t=this.requireDaemon(e);if(this.daemonScopes.has(e)){await Dd(t,this.logger);return}let n=pe.runSync(Xe.make()),o=pe.acquireRelease(pe.promise(()=>Dd(t,this.logger)),()=>pe.promise(()=>zd(t,this.logger)));try{await Mr(Xe.extend(o,n)),this.daemonScopes.set(e,n)}catch(i){throw await Mr(Xe.close(n,tt.fail(i))),i}}stop(e){if(!this.daemons.has(e))return Promise.reject(Error(`Daemon not registered: ${e}`));return this.enqueueTransition(e,"stop",()=>this.stopDaemon(e))}async stopDaemon(e){let t=this.requireDaemon(e),n=this.daemonScopes.get(e);if(!n){await zd(t,this.logger);return}this.daemonScopes.delete(e),await Mr(Xe.close(n,tt.void))}async checkHealth(e){let t=this.daemons.get(e);if(!t)throw Error(`Daemon not registered: ${e}`);return Yx(t)}getByPlugin(e){return Array.from(this.daemons.values()).filter((t)=>t.pluginId===e)}getAll(){return Array.from(this.daemons.keys())}getAllInfo(){return Array.from(this.daemons.values())}async getStatuses(){let e=this.getAllInfo();for(let t of e)if(t.daemon.healthCheck)await this.checkHealth(t.name);return e.map(Qx)}unregister(e){if(!this.daemons.has(e))return this.logger.warn(`Daemon not registered: ${e}`),Promise.resolve();return this.enqueueTransition(e,"unregister",async()=>{let t=this.requireDaemon(e);if(this.daemonScopes.has(e)||t.status!=="stopped")await this.stopDaemon(e);this.daemons.delete(e),this.logger.debug(`Unregistered daemon: ${e}`)},!0)}abandon(e){let t=this.daemons.get(e);if(!t)return;if(t.status!=="stopped"||this.daemonScopes.has(e)||(this.daemonTransitions.get(e)?.pending??0)>0)throw Error(`Cannot abandon active daemon: ${e}`);this.daemons.delete(e),this.logger.debug(`Abandoned daemon registration: ${e}`)}async startPlugin(e){let t=this.getByPlugin(e);this.logger.debug(`Starting ${t.length} daemons for plugin: ${e}`);let n,o=[];for(let i of t){let a=this.daemonScopes.has(i.name);try{if(await this.start(i.name),!a)o.push(i.name)}catch(s){if(n??=ta(s),!a)o.push(i.name)}}if(n){for(let i of o.reverse())try{await this.stop(i)}catch(a){this.logger.error(`Failed to roll back daemon: ${i}`,a)}throw n}}async stopPlugin(e){let t=this.getByPlugin(e);this.logger.debug(`Stopping ${t.length} daemons for plugin: ${e}`);for(let n of t)try{await this.stop(n.name)}catch(o){this.logger.error(`Failed to stop daemon: ${n.name}`,o)}}async clear(){this.logger.debug("Clearing all daemons");for(let e of[...this.daemons.keys()])try{await this.unregister(e)}catch(t){this.logger.error(`Failed to unregister daemon during clear: ${e}`,t)}this.logger.debug("All daemons cleared")}requireDaemon(e){let t=this.daemons.get(e);if(!t)throw Error(`Daemon not registered: ${e}`);return t}enqueueTransition(e,t,n,o=!1){let i=this.daemonTransitions.get(e);if(!i)i={tail:Promise.resolve(),lastKind:void 0,lastPromise:void 0,pending:0,terminal:!1},this.daemonTransitions.set(e,i);if(t==="start"&&i.terminal)return Promise.reject(Error(`Daemon is being unregistered: ${e}`));if(i.lastKind===t&&i.lastPromise)return i.lastPromise;if(o)i.terminal=!0;i.pending++;let a=i.tail.then(n),s=()=>{if(i.pending--,i.pending===0)this.daemonTransitions.delete(e)},l=a.then(s,s);return i.tail=l,i.lastKind=t,i.lastPromise=a,a}}var TB=r.object({projectionId:r.string().min(1),reason:r.string().min(1),openedAt:r.number().int().nonnegative(),expiresAt:r.number().int().nonnegative()}),IB=8,CB=32,kB=128,RB=5,EB=600000,AB=600000,PB=1000,MB="shell.projection-circuits";class Rs{operationContext;options;circuitStore;roots=new Map;reservedJobs=new Map;circuits=new Map;projections;static createFresh(e,t={}){return new Rs(e,t)}constructor(e,t){this.operationContext=e,this.options={maxDerivationDepth:t.maxDerivationDepth??IB,maxJobsPerRoot:t.maxJobsPerRoot??CB,maxMutationsPerRoot:t.maxMutationsPerRoot??kB,repeatedTargetLimit:t.repeatedTargetLimit??RB,retentionMs:t.retentionMs??EB,circuitOpenMs:t.circuitOpenMs??AB,maxTrackedRoots:t.maxTrackedRoots??PB,now:t.now??Date.now};for(let[n,o]of Object.entries(this.options)){if(n==="now")continue;if(typeof o!=="number"||!Number.isInteger(o)||o<=0)throw Error(`${n} must be a positive integer`)}this.circuitStore=t.runtimeState?.scoped({namespace:MB,schema:TB})}async initialize(e){if(this.projections)throw Error("Projection runtime supervisor is already initialized");if(this.projections=new Map(e.projections.map((n)=>[n.id,n])),!this.circuitStore)return;let t=this.options.now();for(let n of await this.circuitStore.list()){let o=n.value;if(o.expiresAt<=t||!this.projections.has(o.projectionId)){await this.circuitStore.delete(n.key);continue}this.circuits.set(o.projectionId,o)}}async reserveJobAdmission(e){let t=e.projectionId;if(!t)return this.createNoopJobReservation();let n=this.options.now();if(await this.prune(n),await this.requireProjection(t,n),await this.assertCircuitClosed(t,n),await this.assertDepth(e,n),e.projectionLineage.filter((u)=>u===t).length>1)await this.rejectAndOpen(t,`Projection ${t} repeats in one causal lineage`,n);let i=e.rootJobId,a=this.roots.get(i)?.jobs??0,s=this.reservedJobs.get(i)??0;if(a+s+1>this.options.maxJobsPerRoot)await this.rejectAndOpen(t,`Root ${i} exceeded projection job budget ${this.options.maxJobsPerRoot}`,n);this.reservedJobs.set(i,s+1);let l=!1,c=(u)=>{if(l)return;if(l=!0,this.releaseJobReservation(i),!u)return;let d=this.options.now(),m=this.getRootCounters(i,d);m.jobs++,m.updatedAt=d};return{commit:()=>c(!0),rollback:()=>c(!1)}}async assertMutationAdmission(e){let t=this.operationContext.current()?.provenance,n=t?.projectionId;if(!t||!n)return;let o=this.options.now();await this.prune(o),await this.requireProjection(n,o),await this.assertCircuitClosed(n,o);let i=this.getRootCounters(t.rootJobId,o);if(i.mutations++,i.updatedAt=o,i.mutations>this.options.maxMutationsPerRoot)await this.rejectAndOpen(n,`Root ${t.rootJobId} exceeded projection mutation budget ${this.options.maxMutationsPerRoot}`,o);let a=`${n}\x00${e.entityType}\x00${e.entityId}`,s=(i.targetMutations.get(a)??0)+1;if(i.targetMutations.set(a,s),s>this.options.repeatedTargetLimit)await this.rejectAndOpen(n,`Projection ${n} repeatedly mutated ${e.entityType}:${e.entityId}`,o)}async getDiagnostics(){let e=this.options.now();await this.prune(e);let t=Array.from(this.circuits.values()).sort((n,o)=>n.projectionId.localeCompare(o.projectionId)).map((n)=>({...n}));return{status:t.length>0?"unhealthy":"healthy",initialized:this.projections!==void 0,trackedRoots:this.roots.size,openCircuits:t}}async requireProjection(e,t){if(!this.projections)throw Error("Projection runtime supervisor is not initialized");let n=this.projections.get(e);if(!n)throw await this.rejectAndOpen(e,`Projection ${e} is not declared in the validated graph`,t),Error(`Projection ${e} is not declared`);return n}async assertDepth(e,t){let n=e.projectionId;if(!n)return;if(e.derivationDepth>this.options.maxDerivationDepth)await this.rejectAndOpen(n,`Projection ${n} depth ${e.derivationDepth} exceeds global maximum ${this.options.maxDerivationDepth}`,t)}async assertCircuitClosed(e,t){let n=this.circuits.get(e);if(!n)return;if(n.expiresAt<=t){this.circuits.delete(e),await this.circuitStore?.delete(e);return}throw Error(`Projection circuit ${e} is open: ${n.reason}`)}async rejectAndOpen(e,t,n){let o={projectionId:e,reason:t,openedAt:n,expiresAt:n+this.options.circuitOpenMs};this.circuits.set(e,o);try{await this.circuitStore?.set(e,o)}catch(i){throw Error(`Projection ${e} was rejected but its circuit could not be persisted`,{cause:i})}throw Error(t)}createNoopJobReservation(){return{commit:()=>{},rollback:()=>{}}}releaseJobReservation(e){let t=this.reservedJobs.get(e);if(t===void 0||t<=1){this.reservedJobs.delete(e);return}this.reservedJobs.set(e,t-1)}getRootCounters(e,t){let n=this.roots.get(e);if(n)return n;if(this.roots.size>=this.options.maxTrackedRoots){let i=Array.from(this.roots.entries()).sort(([a,s],[l,c])=>s.updatedAt-c.updatedAt||a.localeCompare(l))[0];if(i)this.roots.delete(i[0])}let o={jobs:0,mutations:0,targetMutations:new Map,updatedAt:t};return this.roots.set(e,o),o}async prune(e){for(let[t,n]of this.roots)if(e-n.updatedAt>=this.options.retentionMs)this.roots.delete(t);for(let[t,n]of this.circuits)if(n.expiresAt<=e)this.circuits.delete(t),await this.circuitStore?.delete(t)}}var jB={web:{serves:!0,executes:!1,handlerRegistrationMode:"validation-only",progressMonitorMode:"durable-reader",projectionActivation:"scheduler"},worker:{serves:!1,executes:!0,handlerRegistrationMode:"execution-only",progressMonitorMode:"durable-writer",projectionActivation:"executor"},combined:{serves:!0,executes:!0,handlerRegistrationMode:"combined",progressMonitorMode:"combined",projectionActivation:"scheduler"}};function Es(e){return jB[e??"combined"]}var OB=20,NB=0.5,DB=0.06,zB=5;function $d(e,t){let n=e[t];return typeof n==="string"&&n.trim().length>0?n.trim():void 0}function UB({entity:e},t){let n=$d(e.metadata,"title")??$d(e.metadata,"name"),o=$d(e.metadata,"slug")??e.id,i=t.siteBaseUrl?.replace(/^https?:\/\//,"").replace(/\/+$/,""),a=i?new URL(t.urlFor(e.entityType,o),`https://${i}`).href:void 0;return{id:`${e.entityType}:${e.id}`,...n?{title:n}:{},source:e.entityType,entityType:e.entityType,entityId:e.id,...a?{url:a}:{}}}function eT(e){return async({answer:t})=>{let o=(await e.entityService.search({query:t,options:{limit:OB,minScore:NB,visibilityScope:Wt("public"),publishedOnly:!0}})).filter((a)=>e.isCitable(a.entity.entityType)),i=Math.max(...o.map((a)=>a.score));return o.filter((a)=>a.score>=i-DB).slice(0,zB).map((a)=>UB(a,e))}}function Ld(e,t,n,o,i){return[As.created,As.updated,As.deleted].map((s)=>e.subscribe(s,async(l)=>{if(l.payload.entityType===t&&(n===null||l.payload.entityId===n)){await o();let c=s.replace("entity:","");i.debug(`${t} entity ${c}, cache refreshed`)}return{success:!0}}))}async function $B(e,t,n){let o=LB(e.kind);if(!o)return null;try{let i=t.scoped({namespace:o,refKind:e.kind,routePath:""});return qB(await i.read(e.id),e)}catch(i){return n.debug("Skipped unavailable prior runtime upload",{uploadKind:e.kind,uploadId:e.id,error:ke(i)}),null}}function LB(e){return e==="upload"?"upload":null}function qB(e,t){let{record:n,content:o}=e;if(FB(n.mediaType))return{kind:"text",filename:n.filename,mediaType:n.mediaType,content:new TextDecoder("utf-8").decode(o).replace(/^\uFEFF/,""),sizeBytes:n.sizeBytes,source:t};return{kind:"file",filename:n.filename,mediaType:n.mediaType,data:new Uint8Array(o),sizeBytes:n.sizeBytes,source:t}}function FB(e){let t=e.toLowerCase();return t.startsWith("text/")||t==="application/json"}function aT(e){let{config:t,entityService:n,logger:o,messageBus:i,aiService:a,mcpService:s,conversationService:l,runtimeUploadRegistry:c,disposables:u,executionOnly:d=!1}=e,m=nT.createFresh(n,o,t.identity);if(!d)u.push(...Ld(i,Rt.BRAIN_CHARACTER,Rt.BRAIN_CHARACTER,()=>m.refreshCache(),o));let p=oT.createFresh(n,o,t.profile),f=iT.createFresh(o,async(x)=>{let S=await ws(i,"shell:canonical-identity-service",x).catch(()=>null);if(!S?.canonicalId)return null;return{userId:S.userId,canonicalId:S.canonicalId,displayName:S.displayName}}),g=Cd({guestPricing:a.getConfig().model==="gpt-5.6-luna"?rd:void 0,model:a.getModel(),modelId:a.getConfig().model,webSearch:a.getConfig().webSearch,temperature:a.getConfig().temperature,maxTokens:a.getConfig().maxTokens,reasoningEffort:a.getConfig().reasoningEffort,messageBus:i}),h=fd(t.name),v=Xi.createFresh(s,l,m,p,o,{agentFactory:g,canonicalIdentityResolver:f,...e.embeddingUsage?{embeddingUsage:e.embeddingUsage}:{},...t.embedding.enabled?{indexReadiness:n,guestAnswerSources:eT({entityService:n,isCitable:(x)=>Qo.getInstance().isCitable(x),urlFor:(x,S)=>Qo.getInstance().generateUrl(x,S),siteBaseUrl:t.siteBaseUrl})}:{},uploadAttachmentResolver:(x)=>$B(x,c,o),agentContextProvider:async(x)=>(await i.collect({type:tT,sender:"shell:agent-service",payload:x})).flatMap((y)=>{if("noop"in y||!y.success)return[];return rT(y.data)}),...h?{assistantAgentId:h}:{},...t.agentInstructions&&{agentInstructions:t.agentInstructions}});if(!d){u.push(...Ld(i,Rt.ANCHOR_PROFILE,Rt.ANCHOR_PROFILE,()=>p.refreshCache(),o));for(let x of[Rt.BRAIN_CHARACTER,Rt.ANCHOR_PROFILE])u.push(...Ld(i,x,x,async()=>v.invalidateAgent(),o))}return{identityService:m,profileService:p,canonicalIdentityService:f,agentService:v}}var ra=rt.GenericTag("@brains/job-queue/JobQueueService"),Ps=rt.GenericTag("@brains/job-queue/BatchJobManager"),Ms=rt.GenericTag("@brains/job-queue/JobProgressMonitor"),js=rt.GenericTag("@brains/job-queue/JobQueueWorker");function dT(e){return vn(ra,()=>{let t=e.service??sT.createFresh(e.config,e.logger,{...e.operationContext&&{operationContext:e.operationContext},...e.projectionAdmission&&{projectionAdmission:e.projectionAdmission},...e.handlerRegistrationMode&&{handlerRegistrationMode:e.handlerRegistrationMode}});return{service:t,close:()=>t.close()}})}function pT(e){let t=!1,n=pe.gen(function*(){let o=yield*ra,i=e.batchJobManager??cT.createFresh(o,e.logger),a=e.jobProgressMonitor??uT.createFresh(o,e.messageBus,i,e.logger,e.progressMonitorMode),s=e.jobQueueWorker??lT.createFresh(o,a,e.logger,{pollInterval:100,concurrency:e.workerConcurrency,autoStart:!1,...e.onWorkerUnhealthy&&{onUnhealthy:e.onWorkerUnhealthy}},{...e.operationContext&&{operationContext:e.operationContext},...e.projectionBatchScope&&{projectionBatchScope:e.projectionBatchScope}});return rt.make(Ps,i).pipe(rt.add(Ms,a),rt.add(js,s))});return{layer:Xr.scopedContext(pe.acquireRelease(n,(o)=>t?pe.void:BB(o))),abandon:()=>{t=!0}}}function BB(e){let t=rt.get(e,js),n=rt.get(e,Ms),o=rt.get(e,Ps);return pe.gen(function*(){let i=yield*pe.exit(pe.tryPromise({try:()=>t.stop(),catch:(c)=>c})),a=yield*pe.exit(pe.try({try:()=>n.stop(),catch:(c)=>c})),s=yield*pe.exit(pe.tryPromise({try:async()=>{await o.stop()},catch:(c)=>c})),l=[i,a,s].find(tt.isFailure);if(l)yield*pe.die(ir.squash(l.cause))})}function GB(e,t=(n)=>process.exit(n)){return(n)=>{e.error("Job queue worker requires process restart",{reason:n,exitCode:1}),t(1)}}function Os(e){let t=pe.runSyncExit(Xe.close(e,tt.void));if(tt.isFailure(t))throw ir.squash(t.cause)}function mT(e){let t=e.operationContext??Ns.createFresh(),n=pe.runSync(Xe.make()),o,i;try{let a=pe.runSync(Xr.buildWithScope(dT({config:e.jobQueueConfig,logger:e.logger,operationContext:t,...e.projectionAdmission&&{projectionAdmission:e.projectionAdmission},...e.handlerRegistrationMode&&{handlerRegistrationMode:e.handlerRegistrationMode},...e.dependencies?.jobQueueService&&{service:e.dependencies.jobQueueService}}),n)),s=rt.get(a,ra),l=pe.runSync(Xe.make());o=l;let c=pT({messageBus:e.messageBus,logger:e.logger,operationContext:t,...e.projectionBatchScope&&{projectionBatchScope:e.projectionBatchScope},onWorkerUnhealthy:GB(e.logger),workerConcurrency:e.workerConcurrency,...e.progressMonitorMode&&{progressMonitorMode:e.progressMonitorMode},...e.dependencies?.batchJobManager&&{batchJobManager:e.dependencies.batchJobManager},...e.dependencies?.jobProgressMonitor&&{jobProgressMonitor:e.dependencies.jobProgressMonitor},...e.dependencies?.jobQueueWorker&&{jobQueueWorker:e.dependencies.jobQueueWorker}});i=c;let u=pe.runSync(Xr.buildWithScope(c.layer.pipe(Xr.provide(Xr.succeed(ra,s))),l)),d=rt.get(u,Ps),m=rt.get(u,Ms),p=rt.get(u,js),f,g=!1,h=!1;return{batchJobManager:d,jobProgressMonitor:m,jobQueueService:s,jobQueueWorker:p,closeRuntime:()=>(g=!0,f??=Mr(Xe.close(l,tt.void)),f),rollbackRuntime:()=>{if(g)return;g=!0,c.abandon(),Os(l)},closeDatabase:()=>{if(h)return;h=!0,Os(n)}}}catch(a){if(o)try{i?.abandon(),Os(o)}catch(s){e.logger.warn("Failed to release partial job runtime acquisition",s)}try{Os(n)}catch(s){e.logger.warn("Failed to release partial job database acquisition",s)}throw a}}function fT(e){return{deliver:async(t)=>{if(!e.hasHandlers(qd))return!1;let n=await e.send({type:qd,payload:{title:t.title,body:t.body,...t.html?{html:t.html}:{}},sender:"shell.recurring-checks"});if(!("success"in n)||!n.success||!n.data)throw Error("Recurring alert delivery failed");let o=gT.safeParse(n.data);if(!o.success||o.data.status!=="sent")throw Error("Recurring alert delivery failed");return!0}}}function yT(e){return{sourceId:"recurring-checks",displayName:"Recurring checks",list:async()=>(await e.listOpenAlerts()).map((t)=>({id:t.id,title:hT(t.title,160),summary:hT(t.body,1000),receivedAt:t.observedAt,urgency:"high",actions:[{id:"resolve",label:"Dismiss",confirm:!0}]})),act:async(t,n,o)=>{if(o.permissionLevel!=="admin")throw Error("Admin permission required");if(n!=="resolve")throw Error("Invalid recurring-check inbox action");await e.resolveOpenAlert(t)}}}function hT(e,t){return e.length<=t?e:e.slice(0,t)}function vT(e,t){if(t)return t;let n={debug:Ut.DEBUG,info:Ut.INFO,warn:Ut.WARN,error:Ut.ERROR}[e.logging.level];return vr.createFresh({level:n,context:e.logging.context,format:e.logging.format==="json"?"json":"text",...e.logging.file?{logFile:e.logging.file}:{}})}function bT(e){return{apiKey:e.ai.apiKey,model:e.ai.model,temperature:e.ai.temperature,maxTokens:e.ai.maxTokens,webSearch:e.ai.webSearch,...e.ai.reasoningEffort&&{reasoningEffort:e.ai.reasoningEffort},...e.ai.imageApiKey?{imageApiKey:e.ai.imageApiKey}:{}}}function zo(e){return{url:e.url,...e.authToken?{authToken:e.authToken}:{}}}function $T(e){let{config:t,dependencies:n,initializerLogger:o,lifecycle:i,processRole:a}=e;o.debug("Initializing Shell services");let s=Es(a),l=vT(t,n?.logger),c=n?.operationContext??Ns.createFresh(),u=[],d=Fi.createFresh(),m=n?.embeddingService??qi.createFresh({apiKey:t.ai.apiKey,logger:l,usage:d}),p=n?.aiService??Li.createFresh(bT(t),l),f=n?.entityRegistry??ST.createFresh(l),g=n?.messageBus??DT.createFresh(l,c),h=n?.templateRegistry??xT.createFresh(l),v=n?.dataSourceRegistry??wT.createFresh(l),x=n?.renderService??TT.createFresh(h),S=n?.daemonRegistry??ks.createFresh(l),y=n?.pluginManager??UT.createFresh(l,S),w=n?.permissionService??new vs(t.permissions,{spaces:t.spaces,entityActionFloor:(me)=>f.getEntityTypeConfig(me).actionPolicy}),_=n?.profileKindRegistry??new zT(t.profileKind),C=n?.channelRegistry??new kT,I=n?.inboxRegistry??new RT,b=n?.inboxFollowUpRegistry??new ET(l),E=n?.operationalHealthRegistry??new NT,B=n?.accountSettingsRegistry??new CT,R=n?.attachmentRegistry??AT.createFresh(),U=n?.runtimeUploadRegistry??PT.createFresh({dataDir:t.dataDir,logger:l}),z=i.buildLayer(Kx({config:zo(t.runtimeStateDatabase),logger:l,...n?.runtimeStateService&&{service:n.runtimeStateService}})),N=rt.get(z,Nd),re=n?.projectionRuntimeSupervisor??Rs.createFresh(c,{runtimeState:N}),Y=n?.mcpService??OT.createFresh(g,l),V={},q={runFreshBatchScope:(me)=>V.current?V.current.runFreshBatchScope(me):me()},ue=mT({dependencies:n,jobQueueConfig:zo(t.jobQueueDatabase),workerConcurrency:t.jobQueue.workerConcurrency,messageBus:g,operationContext:c,projectionBatchScope:q,projectionAdmission:re,handlerRegistrationMode:s.handlerRegistrationMode,progressMonitorMode:s.progressMonitorMode,logger:l}),{batchJobManager:ee,jobProgressMonitor:k,jobQueueService:X,jobQueueWorker:H}=ue;i.addSyncFinalizer(()=>ue.closeDatabase()),i.addSyncFinalizer(()=>ue.rollbackRuntime());let J=n?.recurringCheckService??new Ts({brainId:t.siteBaseUrl??t.dataDir,scheduler:new MT,runtimeState:N,clock:_T.make(),jobQueue:X,logger:l,delivery:fT(g)});i.addSyncFinalizer(()=>J.abandon()),I.registerSource("shell.recurring-checks",yT(J)),i.addSyncFinalizer(()=>I.unregisterPlugin("shell.recurring-checks"));let K=(me,Q)=>{if(!s.serves)return;S.register(me,Q,"shell"),i.addSyncFinalizer(()=>S.abandon(me))};K("shell:recurring-checks",{start:()=>J.start(),stop:()=>J.stop()});let D=i.buildLayer(Nx({embeddingService:m,embeddingsEnabled:t.embedding.enabled,entityRegistry:f,logger:l,jobQueueService:X,messageBus:g,mutationAdmission:re,...n?.projectionRuntime?.now&&{projectionNow:n.projectionRuntime.now},dbConfig:zo(t.database),embeddingDbConfig:zo(t.embeddingDatabase),...n?.entityService&&{service:n.entityService}})),F=rt.get(D,Rd);V.current=F.getProjectionStore();let G=i.buildLayer(jx({dbConfig:zo(t.conversationDatabase),logger:l,messageBus:g,...n?.conversationService&&{service:n.conversationService}})),Z=rt.get(G,kd);K("shell:guest-retention",jT({intervalMs:60000,logger:l,run:async()=>{await Z.deleteExpiredGuestConversations(100)}})),i.addSyncFinalizer(()=>{for(let me of u.splice(0))try{me()}catch(Q){l.warn("Failed to dispose shell subscription",Q)}});let A=n?.contentService??new IT({logger:l,entityService:F,aiService:p,templateRegistry:h,dataSourceRegistry:v,generationAuthorizer:Px(w,g)}),{identityService:O,profileService:W,canonicalIdentityService:P,agentService:L}=aT({config:t,entityService:F,embeddingService:m,embeddingUsage:d,entityRegistry:f,logger:l,messageBus:g,aiService:p,mcpService:Y,conversationService:Z,runtimeUploadRegistry:U,disposables:u,executionOnly:!s.serves});return{logger:l,operationContext:c,projectionRuntimeSupervisor:re,disposables:u,entityRegistry:f,messageBus:g,renderService:x,daemonRegistry:S,pluginManager:y,templateRegistry:h,dataSourceRegistry:v,mcpService:Y,embeddingService:m,entityService:F,aiService:p,conversationService:Z,contentService:A,jobQueueService:X,jobQueueWorker:H,batchJobManager:ee,jobProgressMonitor:k,jobServicesLifecycle:ue,permissionService:w,identityService:O,profileService:W,canonicalIdentityService:P,profileKindRegistry:_,channelRegistry:C,inboxRegistry:I,inboxFollowUpRegistry:b,operationalHealthRegistry:E,accountSettingsRegistry:B,agentService:L,attachmentRegistry:R,runtimeUploadRegistry:U,runtimeStateService:N,recurringCheckService:J}}function GT(e,t){e.register(Fd.name,Fd),t.debug("Shell system templates registered")}function JT(e,t){e.register(Yo.BASE_ENTITY_DISPLAY,{name:"base-entity-display",description:"Display template for base entities",schema:Bd,formatter:new LT,requiredPermission:"public"}),t.debug("Base entity display template registered")}function HT(e,t){e.registerEntityType(Rt.NOTE,Bd,new qT,{projectionSourceRole:"primary"}),t.debug("Fallback base entity adapter registered")}function WT(e,t){let n=new FT;e.registerEntityType(Rt.BRAIN_CHARACTER,n.schema,n,{classification:"system",projectionSource:!1,projectionSourceRole:"excluded"}),t.debug("Brain character entity support registered")}function VT(e,t){let n=new BT;e.registerEntityType(Rt.ANCHOR_PROFILE,n.schema,n,{classification:"system",projectionSourceRole:"canonical"}),t.debug("Anchor profile entity support registered")}async function ZT(e){let{plugins:t,pluginManager:n,logger:o,initOptions:i}=e,a=i?.registrationContext?.executionOnly?t.filter((s)=>s.type!=="interface"):t;o.debug(`Found ${a.length} plugins to register`);for(let s of a)o.debug(`Registering plugin: ${s.id}`),n.registerPlugin(s);if(await n.initializePlugins(i?.registrationContext),!i?.registerOnly){for(let{id:s,error:l}of n.getFailedPlugins())if(n.getPlugin(s)?.requiresDaemonStartup?.())throw l}o.debug("Plugin initialization complete")}class Ds{logger;config;processRole;static createFresh(e,t,n){return new Ds(e,t,n)}constructor(e,t,n){this.logger=e.child("ShellInitializer"),this.config=t,this.processRole=n}registerShellTemplates(e){GT(e,this.logger)}registerBaseEntityDisplayTemplate(e){JT(e,this.logger)}registerFallbackBaseEntity(e){HT(e,this.logger)}registerBrainCharacterSupport(e){WT(e,this.logger)}registerAnchorProfileSupport(e){VT(e,this.logger)}async initializePlugins(e,t){await ZT({plugins:this.config.plugins,pluginManager:e,logger:this.logger,initOptions:t})}initializeServices(e,t){return $T({config:this.config,dependencies:t,initializerLogger:this.logger,lifecycle:e,...this.processRole&&{processRole:this.processRole}})}registerJobHandlers(e,t,n){let o=YT.createFresh(t,n);e.registerHandler(KT.contentGeneration,o,"shell")}wireShell(e,t){e.pluginManager.setShell(t)}async initializeAll(e,t,n,o){this.logger.debug("Starting Shell initialization");try{if(this.registerShellTemplates(e),this.registerBaseEntityDisplayTemplate(e),this.registerBrainCharacterSupport(t),this.registerAnchorProfileSupport(t),await this.initializePlugins(n,o),!t.hasEntityType(Rt.NOTE))this.registerFallbackBaseEntity(t);this.logger.debug("Shell registration phase complete")}catch(i){throw this.logger.error("Shell initialization failed",i),i}}}var Gd=r.strictObject({waveId:r.string().trim().min(1),ruleId:r.string().trim().min(1)});class Jd{ruleById;store;coordinator;getJobStatus;onDiagnostic;inputContext;executionContext;reconcileTargets;now;constructor(e){let t=new Map;for(let n of e.rules){if(t.has(n.id))throw Error(`Duplicate executable projection rule "${n.id}"`);t.set(n.id,n)}this.ruleById=t,this.store=e.store,this.coordinator=e.coordinator,this.getJobStatus=e.getJobStatus??(async()=>null),this.onDiagnostic=e.onDiagnostic,this.inputContext=e.inputContext,this.executionContext=e.executionContext,this.reconcileTargets=e.reconcileTargets,this.now=e.now}validateAndParse(e){let t=Gd.safeParse(e);return t.success?t.data:null}async onTerminalError(e,t,n){let o=Gd.parse(t);await this.coordinator.failActiveWaveWithIncident({waveId:o.waveId,ruleId:o.ruleId,jobId:n,failureReason:"Projection rule job exhausted retries"})}async process(e,t,n,o){let i=Gd.parse(e),a=this.ruleById.get(i.ruleId);if(!a)throw Error(`Projection rule "${i.ruleId}" is not executable`);let[s,l,c,u]=await Promise.all([this.store.listWaveInputs(i.waveId),this.store.listWaveRules(i.waveId),this.store.getWave(i.waveId),this.getJobStatus(t)]);if(!c)throw Error(`Projection wave "${i.waveId}" does not exist`);if(c.status!=="running"&&c.status!=="superseded")throw Error(`Projection wave "${i.waveId}" is not active`);let d=l.find((_)=>_.ruleId===i.ruleId);if(!d)throw Error(`Projection rule "${i.ruleId}" is not scheduled for wave "${i.waveId}"`);let m={waveId:i.waveId,ruleId:a.id,ruleVersion:a.version,jobId:t,attemptNumber:(u?.retryCount??0)+1,cutoffGeneration:c.cutoffGeneration};if(await this.recordDiagnostic({...m,event:"attempt-started"}),c.status==="superseded"){let _=await this.store.listPendingInputs();return await this.recordDiagnostic({...m,event:"apply-completed",applyOutcome:"superseded",highestPendingGeneration:zs(_)}),{waveId:i.waveId,ruleId:a.id,outcome:"superseded",inputFingerprint:null,changedTargets:[]}}if(await this.store.supersedeWaveIfStale(i.waveId,this.now())){let _=await this.store.listPendingInputs();return await this.recordDiagnostic({...m,event:"apply-completed",applyOutcome:"superseded",highestPendingGeneration:zs(_)}),await this.coordinator.continueAfterSupersession(i.waveId),{waveId:i.waveId,ruleId:a.id,outcome:"superseded",inputFingerprint:null,changedTargets:[]}}let p=WB(s,l,d.level),f=await a.selectInput({waveId:i.waveId,inputs:p},this.inputContext,o),g=a.fingerprint(f),h={...m,inputFingerprint:g,selectedSourceCount:HB(f,p)};await this.recordDiagnostic({...h,event:"input-selected"});let v={ruleId:a.id,ruleVersion:a.version,inputFingerprint:g},x=await this.store.getRuleMemo(v);await this.recordDiagnostic({...h,event:"memo-resolved",memoHit:x!==null});let S;if(x)S=x.writeIntents;else{await this.recordDiagnostic({...h,event:"derive-started",memoHit:!1});try{S=await a.derive(f,this.executionContext,o),await this.recordDiagnostic({...h,event:"derive-completed",memoHit:!1})}catch(_){throw await this.recordDiagnostic({...h,event:o.aborted?"derive-cancelled":"derive-failed",memoHit:!1}),_}}let y=await this.store.applyRuleResult({waveId:i.waveId,ruleId:a.id,ruleVersion:a.version,inputFingerprint:g,writeIntents:S,completedAt:this.now()}),w=await this.store.listPendingInputs();if(!y)return await this.recordDiagnostic({...h,event:"apply-completed",memoHit:x!==null,applyOutcome:"superseded",highestPendingGeneration:zs(w)}),await this.coordinator.continueAfterSupersession(i.waveId),{waveId:i.waveId,ruleId:a.id,outcome:"superseded",inputFingerprint:g,changedTargets:[]};return await this.recordDiagnostic({...h,event:"apply-completed",memoHit:x!==null,applyOutcome:"applied",highestPendingGeneration:zs(w)}),await this.reconcileTargets(y.changedTargets),await this.coordinator.advanceActiveWave(i.waveId),{waveId:i.waveId,ruleId:a.id,outcome:"applied",inputFingerprint:g,changedTargets:y.changedTargets}}async recordDiagnostic(e){if(!this.onDiagnostic)return;try{await this.onDiagnostic(e)}catch(t){this.executionContext.logger.warn("Projection diagnostics callback failed",t)}}}function HB(e,t){if(typeof e==="object"&&e!==null&&"sources"in e&&Array.isArray(e.sources))return e.sources.length;return t.length}function zs(e){if(e.length===0)return null;return e.reduce((t,n)=>Math.max(t,n.generation),e[0]?.generation??0)}function WB(e,t,n){let o=e.map((a)=>({sourceType:a.sourceType,sourceId:a.sourceId,revision:a.revision,operation:a.operation,generation:a.generation})),i=t.filter((a)=>a.status==="completed"&&a.level<n).flatMap((a)=>a.changedTargets.map((s)=>({sourceType:s.entityType,sourceId:s.entityId,revision:s.contentHash??`deleted:${s.entityType}:${s.entityId}`,operation:s.operation})));return[...o,...i]}function VB(e){switch(e.jobStatus){case"failed":return"Projection rule job exhausted retries";case"completed":return"Projection rule job completed without applying its result";case"missing":return e.rule.jobId?"Projection rule job is missing":"Projection rule has no durable job id";default:return"Projection rule job is in an unexpected terminal state"}}var Uo="shell:projection-rule";class Hd{store;queue;graph;ruleById;graphFingerprint;createWaveId;beforeWaveCompletion;scheduleWakeup;onScheduledWakeupError;now;operationQueue=new QT;scheduledWakeup;constructor(e){this.store=e.store,this.queue=e.queue,this.graph=e.graph,this.ruleById=YB(e.graph,e.rules),this.graphFingerprint=QB(e.graph,e.rules),this.createWaveId=e.createWaveId,this.beforeWaveCompletion=e.beforeWaveCompletion??(async()=>{}),this.scheduleWakeup=e.scheduleWakeup??ZB,this.onScheduledWakeupError=e.onScheduledWakeupError??(()=>{}),this.now=e.now}dispose(){this.cancelScheduledWakeup()}advanceActiveWave(e){return this.runExclusive(async()=>{let t=await this.store.getActiveWave();if(t?.id!==e){let o=await this.store.getWave(e);if(o?.status==="completed")return o;throw Error(`Projection wave "${e}" is not active`)}let n=await this.advanceWave(t);if(n.status==="completed")await this.startNextWaveInternal();return n})}startNextWave(){return this.runExclusive(()=>this.startNextWaveInternal())}continueAfterSupersession(e){return this.runExclusive(async()=>{let t=await this.store.getActiveWave();if(t?.id===e)throw Error(`Projection wave "${e}" was not superseded`);if(t)return this.advanceWave(t);return this.startNextWaveInternal()})}failActiveWave(e){return this.runExclusive(async()=>{if((await this.store.getActiveWave())?.id!==e)throw Error(`Projection wave "${e}" is not active`);return this.store.failWave(e,this.now())})}failActiveWaveWithIncident(e){return this.runExclusive(async()=>{let t=await this.store.getActiveWave();if(t&&t.id!==e.waveId)throw Error(`Projection wave "${e.waveId}" is not active; "${t.id}" is running`);if(!t){let n=await this.store.getWave(e.waveId);if(n?.status==="superseded")return n}return this.store.failWaveWithIncident({...e,failedAt:this.now()})})}async startNextWaveInternal(){let e=await this.store.getActiveWave();if(e){let s=await this.advanceWave(e);if(s.status==="completed")await this.startNextWaveInternal();return s}let t=await this.store.listPendingInputs();if(t.length===0)return this.cancelScheduledWakeup(),null;let n=KB(this.graph,this.ruleById,t),o=this.now();if(n>o)return this.schedulePendingWakeup(n),null;this.cancelScheduledWakeup();let i=await this.store.claimPendingWave({waveId:this.createWaveId(),graphFingerprint:this.graphFingerprint,startedAt:o});if(!i)return null;let a=await this.advanceWave(i);if(a.status==="completed")await this.startNextWaveInternal();return a}async runExclusive(e){return this.operationQueue.run(e)}schedulePendingWakeup(e){if(this.scheduledWakeup?.readyAt===e)return;this.cancelScheduledWakeup();let t={readyAt:e,cancel:()=>{}};t.cancel=this.scheduleWakeup(Math.max(0,e-this.now()),async()=>{if(this.scheduledWakeup!==t)return;this.scheduledWakeup=void 0;try{await this.startNextWave()}catch(n){this.onScheduledWakeupError(n)}}),this.scheduledWakeup=t}cancelScheduledWakeup(){this.scheduledWakeup?.cancel(),this.scheduledWakeup=void 0}async advanceWave(e){if(e.graphFingerprint!==this.graphFingerprint)throw Error(`Projection wave "${e.id}" graph fingerprint does not match the finalized graph`);let t=await this.store.listWaveRules(e.id);if(t.length===0){let s=await this.store.listWaveInputs(e.id),l=eI(this.graph,this.ruleById,s);if(l.length===0)return this.completeWave(e);await this.store.putWaveRules(e.id,l),t=await this.store.listWaveRules(e.id)}if(t.every((s)=>s.status==="completed"))return this.completeWave(e,t);let n=t.find((s)=>s.status==="failed");if(n)return this.store.failWaveWithIncident({waveId:e.id,ruleId:n.ruleId,jobId:n.jobId,failureReason:"Projection rule is in a terminal failed state",failedAt:this.now()});let o=await this.findStrandedQueuedRule(t);if(o)return this.store.failWaveWithIncident({waveId:e.id,ruleId:o.rule.ruleId,jobId:o.rule.jobId,failureReason:VB(o),failedAt:this.now()});let i=Math.min(...t.filter((s)=>s.status!=="completed").map((s)=>s.level)),a=t.filter((s)=>s.level===i&&s.status==="pending");return await Promise.all(a.map((s)=>this.enqueueRule(e.id,s))),e}async findStrandedQueuedRule(e){for(let t of e){if(t.status!=="queued")continue;if(!t.jobId)return{rule:t,jobStatus:"missing"};let n=await this.queue.getStatus(t.jobId);if(!n||n.status==="completed"||n.status==="failed")return{rule:t,jobStatus:n?.status??"missing"}}return null}async completeWave(e,t){let[n,o]=await Promise.all([this.store.listWaveInputs(e.id),t?Promise.resolve(t):this.store.listWaveRules(e.id)]);return await this.beforeWaveCompletion({waveId:e.id,sourceTypes:[...new Set(n.map((i)=>i.sourceType))].sort(),changedTargetTypes:[...new Set(o.flatMap((i)=>i.changedTargets.map((a)=>a.entityType)))].sort()}),this.store.completeWave(e.id,this.now())}async enqueueRule(e,t){let n=await this.queue.enqueue({type:Uo,data:{waveId:e,ruleId:t.ruleId},options:{source:"projection-scheduler",rootJobId:`projection-wave:${e}`,metadata:{operationType:"data_processing",operationTarget:t.ruleId,silent:!0},deduplication:"coalesce",deduplicationKey:`projection-wave:${e}:${t.ruleId}`,projection:{id:t.ruleId}}});await this.store.queueWaveRule(e,t.ruleId,n)}}function ZB(e,t){let n=setTimeout(()=>{t()},e);return()=>clearTimeout(n)}function KB(e,t,n){let i=eI(e,t,n).reduce((s,l)=>Math.max(s,t.get(l.ruleId)?.sourceChangeBatchDelayMs??0),0);if(i===0)return 0;return n.reduce((s,l)=>Math.max(s,l.markedAt),0)+i}function YB(e,t){let n=new Map;for(let i of t){if(n.has(i.id))throw Error(`Duplicate executable projection rule "${i.id}"`);n.set(i.id,i)}let o=new Set(e.projections.map((i)=>i.id));for(let i of o)if(!n.has(i))throw Error(`Projection "${i}" has no executable rule`);for(let i of n.keys())if(!o.has(i))throw Error(`Executable projection rule "${i}" is not in the graph`);return n}function QB(e,t){return XT({projections:e.projections,edges:e.edges,rules:[...t].sort((n,o)=>n.id.localeCompare(o.id)).map((n)=>({id:n.id,version:n.version}))})}function eI(e,t,n){let o=new Map(e.projections.map((c)=>[c.id,c])),i=tI(e,(c)=>[c.from,c.to]),a=new Set(e.projections.filter((c)=>XB(c,n)).map((c)=>c.id)),s=[...a];while(s.length>0){let c=s.flatMap((u)=>i.get(u)??[]).filter((u)=>o.has(u)&&!a.has(u));for(let u of c)a.add(u);s=[...new Set(c)].sort()}let l=eG(e,a);return[...a].map((c)=>{let u=o.get(c),d=t.get(c),m=l.get(c);if(!u||!d||m===void 0)throw Error(`Cannot plan projection rule "${c}"`);return{ruleId:c,targetType:u.targetType,level:m}}).sort((c,u)=>c.level-u.level||c.ruleId.localeCompare(u.ruleId))}function XB(e,t){return e.sources.some((n)=>{let o=new Set(n.excludeTypes??[]);return t.some((i)=>!o.has(i.sourceType)&&(n.types.includes("*")||n.types.includes(i.sourceType)))})}function eG(e,t){let n=tI(e,(a)=>t.has(a.from)?[a.to,a.from]:void 0),o=new Map,i=new Set(t);while(i.size>0){let a=[...i].filter((s)=>(n.get(s)??[]).every((l)=>o.has(l))).sort();if(a.length===0)throw Error("Reachable projection graph is not acyclic");for(let s of a){let l=(n.get(s)??[]).map((u)=>o.get(u)).filter((u)=>u!==void 0),c=l.length===0?0:Math.max(...l)+1;o.set(s,c),i.delete(s)}}return o}function tI(e,t){let n=new Map;for(let o of e.edges){let i=t(o);if(!i)continue;let[a,s]=i,l=n.get(a);if(l)l.push(s);else n.set(a,[s])}return n}async function rI(e){let t=new Hd({store:e.store,queue:e.queue,graph:e.graph,rules:e.rules,createWaveId:e.createWaveId,beforeWaveCompletion:e.beforeWaveCompletion,onScheduledWakeupError:(s)=>e.logger.error("Scheduled projection wakeup failed",s),...e.scheduleWakeup&&{scheduleWakeup:e.scheduleWakeup},now:e.now}),n=new Jd({rules:e.rules,store:e.store,coordinator:t,getJobStatus:(s)=>e.queue.getStatus(s),...e.onDiagnostic&&{onDiagnostic:e.onDiagnostic},inputContext:e.inputContext,executionContext:e.executionContext,reconcileTargets:e.reconcileTargets,now:e.now});e.queue.registerHandler(Uo,n,"shell");let o=()=>{},i=()=>{};try{if(e.activationMode!=="executor"){let s=async(d)=>{if(d)await e.reconcileBatches?.();await t.startNextWave()},l,c=(d)=>{if(l)return l;let m=Promise.resolve().then(()=>s(d));l=m;let p=()=>{if(l===m)l=void 0};return m.then(p,p),m},u=async()=>{if(l)return;if(await e.store.hasActiveProjectionBatch())return;await c(!1)};o=e.setWakeup(u),await c(!0),i=(e.scheduleSweep??tG)(e.sweepIntervalMs??1000,async()=>{try{await c(!0)}catch(d){e.logger.error("Projection coordination sweep failed",d)}})}}catch(s){throw i(),o(),e.queue.unregisterHandler(Uo),s}e.logger.debug("Projection runtime activated",{rules:e.rules.length,mode:e.activationMode??"scheduler"});let a=!0;return{scheduler:t,dispose:()=>{if(!a)return;a=!1,i(),o(),t.dispose(),e.queue.unregisterHandler(Uo)}}}function tG(e,t){let n=setInterval(()=>{t()},e);return n.unref(),()=>clearInterval(n)}var rG=250,nG=r.object({projectionBatch:r.object({operationId:r.string().min(1),childKey:r.string().min(1)})});class Vd{config;services;lifecycle;initializer;role;hooks;constructor(e,t,n,o,i,a){this.config=e,this.services=t,this.lifecycle=n,this.initializer=o,this.role=Es(i),this.hooks=a}async boot(e){this.services.logger.debug("Starting Shell boot");let t=this.initializer;await Ud([()=>this.services.entityService.initialize(),()=>this.services.jobQueueService.initialize?.()??Promise.resolve(),()=>this.services.runtimeStateService.initialize(),()=>this.services.conversationService.initialize?.()??Promise.resolve()]);let n={...this.config.entityDisplay!==void 0&&{entityDisplay:this.config.entityDisplay},...!this.role.serves&&{executionOnly:!0}};if(await t.initializeAll(this.services.templateRegistry,this.services.entityRegistry,this.services.pluginManager,{...e?.mode==="register-only"&&{registerOnly:!0},...Object.keys(n).length>0&&{registrationContext:n}}),this.services.profileKindRegistry.finalize(),this.services.channelRegistry.finalize(),this.services.inboxRegistry.finalize(),this.services.inboxFollowUpRegistry.finalize(),await this.services.pluginManager.finalizePluginRegistrations(),this.hooks.finalizeHttpRoutes(),await this.services.projectionRuntimeSupervisor.initialize(this.services.pluginManager.getProjectionGraphSnapshot()),t.registerJobHandlers(this.services.jobQueueService,this.services.contentService,this.services.entityService),e?.mode===void 0){let o=await rI({store:this.services.entityService.getProjectionStore(),queue:this.services.jobQueueService,setWakeup:(i)=>this.services.entityService.setProjectionWakeup(i),graph:this.services.pluginManager.getProjectionGraphSnapshot(),rules:this.services.pluginManager.getProjectionRulesSnapshot(),inputContext:this.hooks.createProjectionInputContext(),executionContext:this.hooks.createProjectionExecutionContext(),reconcileTargets:(i)=>this.services.entityService.reconcileProjectionTargets(i),beforeWaveCompletion:async(i)=>{if(!this.services.messageBus.hasHandlers(Wd.waveReady))return;let a=await this.services.messageBus.collect({type:Wd.waveReady,payload:i,sender:"shell"});if(a.length===0||a.some((s)=>("noop"in s)||!s.success))throw Error(`Projection wave ${i.waveId} completion was not acknowledged`)},logger:this.services.logger,createWaveId:nI,now:this.hooks.projectionRuntime?.now??Date.now,...this.hooks.projectionRuntime?.scheduleWakeup&&{scheduleWakeup:this.hooks.projectionRuntime.scheduleWakeup},...this.hooks.projectionRuntime?.onDiagnostic&&{onDiagnostic:this.hooks.projectionRuntime.onDiagnostic},...this.hooks.projectionRuntime?.scheduleSweep&&{scheduleSweep:this.hooks.projectionRuntime.scheduleSweep},...this.hooks.projectionRuntime?.sweepIntervalMs!==void 0&&{sweepIntervalMs:this.hooks.projectionRuntime.sweepIntervalMs},reconcileBatches:()=>this.services.entityService.recoverProjectionBatches(async(i,a)=>(await this.services.jobQueueService.getJobsByRootJobId(i)).flatMap((l)=>{let c=nG.safeParse(JSON.parse(l.data));if(!c.success||c.data.projectionBatch.operationId!==a)return[];return[{jobId:l.id,childKey:c.data.projectionBatch.childKey,status:l.status,terminalAt:l.completedAt}]})),activationMode:this.role.projectionActivation});this.services.disposables.push(()=>o.dispose())}if(this.services.jobQueueService.finalizeHandlerRegistrations(),this.hooks.registerCoreDataSources(),this.role.serves)this.hooks.registerSystemCapabilities();if(e?.mode==="register-only"){this.services.logger.debug("Shell boot complete (register-only mode)");return}if(!this.role.serves){await this.initializeIdentityServices(),this.services.jobProgressMonitor.start(),await this.services.jobQueueWorker.start(),this.services.logger.debug("Shell boot complete (worker process)");return}if(e?.mode!=="startup-check"){await this.startEarlyWebserver(),await this.emitPluginsRegistered();let o=await this.services.entityService.backfillMissingEmbeddings();this.services.logger.debug("Queued missing embedding backfill jobs",{queued:o.queued,skipped:o.skipped}),await this.services.entityService.reprojectRegisteredGroupings()}if(await this.prepareReadyState(),await this.services.pluginManager.readyPlugins(),e?.mode==="startup-check"){this.services.logger.debug("Shell boot complete (startup-check mode)");return}await this.startRuntimeServices(),await this.startIndexReadinessMonitor(),this.services.logger.debug("Shell boot complete")}async startEarlyWebserver(){if(!this.services.daemonRegistry.has("webserver:webserver"))return;await this.services.daemonRegistry.start("webserver:webserver"),this.services.logger.debug("Started webserver before initial sync")}async emitPluginsRegistered(){await this.services.messageBus.send({type:Us.pluginsRegistered,payload:{timestamp:new Date().toISOString(),pluginCount:this.services.pluginManager.getAllPluginIds().length},sender:"shell",broadcast:!0}),this.services.logger.debug("Emitted plugins registered event")}async initializeIdentityServices(){await Ud([()=>this.services.identityService.initialize(),()=>this.services.profileService.initialize(),()=>this.services.canonicalIdentityService.refreshCache()]),this.services.logger.debug("Identity services initialized")}async prepareReadyState(){await this.initializeIdentityServices();let e=await oI(this.services.templateRegistry,this.services.entityService);if(e>0)this.services.logger.debug(`Materialized ${e} prompt entities`)}async startRuntimeServices(){for(let e of["shell:recurring-checks","shell:guest-retention"])if(this.services.daemonRegistry.has(e))await this.services.daemonRegistry.start(e);if(await this.services.pluginManager.startPluginDaemons(),this.role.executes)await this.services.jobQueueWorker.start();this.services.jobProgressMonitor.start(),await this.services.batchJobManager.start()}async startIndexReadinessMonitor(){await this.lifecycle.fork(this.runIndexReadinessMonitor())}runIndexReadinessMonitor(){let{entityService:e,logger:t}=this.services;return pe.tryPromise({try:(n)=>e.awaitIndexReady({intervalMs:rG,signal:n}),catch:(n)=>n}).pipe(pe.tap((n)=>pe.sync(()=>{if(n.degraded)t.warn("Semantic index ready with degraded embeddings",n);else t.debug("Semantic index ready",n)})),pe.catchAll((n)=>pe.sync(()=>{t.warn("Semantic index readiness monitor stopped",n)})))}}class aI{handlers=new Map;register(e,t){this.handlers.set(e,t)}unregister(e){this.handlers.delete(e)}getTypes(){return Array.from(this.handlers.keys())}async get(e,t,n){let o=this.handlers.get(e);if(!o)throw Error(`Unknown insight type: ${e}. Available: ${this.getTypes().join(", ")}`);let i=n==="public"?iI(t,{publishedOnly:!0,visibilityScope:n}):t;return o(i,n)}}function sI(e){let t=new aI;return t.register("overview",oG),t.register("publishing-cadence",iG),t.register("content-health",(n,o)=>aG(n,o,e)),t}async function oG(e,t){let n=await e.getEntityCounts(t),o={},i=0;for(let{entityType:f,count:g}of n)o[f]=g,i+=g;let a=await Zd(e,t),s=Date.now(),l=s-604800000,c=s-2592000000,u=0,d=0;for(let f of a){let g=new Date(f.created).getTime();if(g>=l)u++;if(g>=c)d++}let m=lI(a),p=a.filter((f)=>f.metadata.status==="published");return{entityCounts:o,totalEntities:i,recentActivity:{last7days:u,last30days:d},contentHealth:{drafts:m.length,published:p.length}}}async function iG(e,t){let n=await Zd(e,t),o=new Map;for(let a of n){let s=new Date(a.created);if(isNaN(s.getTime()))continue;let l=`${s.getUTCFullYear()}-${String(s.getUTCMonth()+1).padStart(2,"0")}`,c=o.get(l);if(!c)c={},o.set(l,c);c[a.entityType]=(c[a.entityType]??0)+1}return{months:Array.from(o.entries()).sort((a,s)=>s[0].localeCompare(a[0])).map(([a,s])=>{let l=0;for(let c of Object.values(s))l+=c;return{month:a,counts:s,total:l}})}}async function aG(e,t,n){let o=await Zd(e,t),i=lI(o).map((c)=>({id:c.id,entityType:c.entityType,title:typeof c.metadata.title==="string"?c.metadata.title:c.id,created:c.created})),a=Date.now(),s=a-7776000000,l=o.filter((c)=>{if(n.getEntityTypeConfig(c.entityType).binaryStorage)return!1;let u=new Date(c.updated).getTime();return!isNaN(u)&&u<s}).map((c)=>({id:c.id,entityType:c.entityType,title:typeof c.metadata.title==="string"?c.metadata.title:c.id,updated:c.updated,daysSinceUpdate:Math.floor((a-new Date(c.updated).getTime())/86400000)}));return{drafts:i,stale:l}}function lI(e){return e.filter((t)=>t.metadata.status==="draft")}async function Zd(e,t){let n=e.getEntityTypes(),o=[];for(let i of n){let a=await e.listEntities({entityType:i,options:{limit:1000,filter:{visibilityScope:t}}});o.push(...a)}return o}class na{parse;idOf;items=new Map;constructor(e,t){this.parse=e,this.idOf=t}register(e){let t=this.parse(e);this.items.set(this.keyFor(t.pluginId,this.idOf(t)),t)}unregister(e,t){if(t!==void 0){this.items.delete(this.keyFor(e,t));return}let n=`${e}:`;for(let o of this.items.keys())if(o.startsWith(n))this.items.delete(o)}list(){return Array.from(this.items.values()).sort((e,t)=>e.priority-t.priority||e.label.localeCompare(t.label))}keyFor(e,t){return`${e}:${t}`}}class Kd extends na{constructor(){super((e)=>cI.parse(e),(e)=>e.url)}}class Yd extends na{constructor(){super((e)=>uI.parse(e),(e)=>e.id)}}function dI(e,t){return{enqueueBatch:e.enqueueBatch.bind(e),getActiveBatches:e.getActiveBatches.bind(e),getBatchStatus:e.getBatchStatus.bind(e),getActiveJobs:t.getActiveJobs.bind(t),getRecentJobs:t.getRecentJobs.bind(t),getStatus:t.getStatus.bind(t)}}var sG=["/health","/images"],lG=new Set([pI]),cG=new Set(mI),uG=new Set(["GET","POST","PUT","DELETE"]);function gI(e){let t=[];for(let[n,{plugin:o}]of e.getAllPlugins()){let i,a;try{i=o.getWebRoutes?.()??[],a=o.getApiRoutes?.()??[]}catch(s){throw Error(`Failed to collect HTTP route declarations from plugin "${n}"`,{cause:s})}t.push({pluginId:n,webRoutes:i,apiRoutes:a})}return t}function dG(e){return lG.has(e)||sG.some((t)=>e===t||e.startsWith(`${t}/`))}function Qd(e,t,n=!0){let o;try{o=new URL(e,"http://route.invalid").pathname}catch{o=void 0}if(!e.startsWith("/")||e.includes("//")||e.includes("?")||e.includes("#")||e.includes("%")||e.length>1&&e.endsWith("/")||e.trim()!==e||o!==e||n&&dG(e))throw Error(`Invalid HTTP route path "${e}" declared by plugin "${t}"`)}function fI(e,t,n){if(!e.has(t))throw Error(`Invalid HTTP route method "${t}" declared by plugin "${n}"`)}function pG(e,t){if(e!=="exact"&&e!=="prefix")throw Error(`Invalid HTTP route match "${e}" declared by plugin "${t}"`)}function mG(e,t){Qd(t.path,e.pluginId);let n=t.method??"GET";fI(cG,n,e.pluginId);let o=t.match??"exact";if(pG(o,e.pluginId),typeof t.handler!=="function")throw Error(`Invalid HTTP route handler for "${t.path}" declared by plugin "${e.pluginId}"`);return Object.freeze({kind:"handler",ownerPluginId:e.pluginId,fullPath:t.path,method:n,match:o,sharedHostAdmission:t.public===!0?"admit":"deny",...t.preview===!0?{preview:!0}:{},handler:t.handler})}function gG(e,t){Qd(t.path,e.pluginId,!1);let n=`/api/${e.pluginId}${t.path}`;if(Qd(n,e.pluginId),fI(uG,t.method,e.pluginId),typeof t.tool!=="string"||t.tool.trim()==="")throw Error(`Invalid HTTP route tool for "${n}" declared by plugin "${e.pluginId}"`);return Object.freeze({kind:"tool",ownerPluginId:e.pluginId,fullPath:n,method:t.method,match:"exact",sharedHostAdmission:t.public?"admit":"deny",definition:Object.freeze({...t})})}function fG(e){let t=new Map;for(let n of e){let o=`${n.method} ${n.fullPath}`,i=t.get(o);if(i!==void 0)throw Error(`HTTP route conflict for ${o} between plugins "${i}" and "${n.ownerPluginId}"; give one declaration a different method or path`);t.set(o,n.ownerPluginId)}}function hG(e){return Object.freeze(e.map((t)=>Object.freeze({ownerPluginId:t.ownerPluginId,kind:t.kind,method:t.method,fullPath:t.fullPath,match:t.match,sharedHostAdmission:t.sharedHostAdmission})))}class $s{routes;manifest;apiRoutes;webRoutes;static createFresh(){return new $s}constructor(){}finalize(e){if(this.routes!==void 0)throw Error("HTTP route registry has already been finalized");let t=[],n=[],o=[];for(let i of e){for(let a of i.webRoutes)t.push(mG(i,a)),n.push(Object.freeze({pluginId:i.pluginId,fullPath:a.path,definition:Object.freeze({...a})}));for(let a of i.apiRoutes){let s=gG(i,a);t.push(s),o.push(Object.freeze({pluginId:i.pluginId,fullPath:s.fullPath,definition:s.definition}))}}return fG(t),this.routes=Object.freeze(t),this.manifest=hG(this.routes),this.webRoutes=Object.freeze(n),this.apiRoutes=Object.freeze(o),this.routes}getSnapshot(){if(this.routes===void 0)throw Error("HTTP route registry has not been finalized");return this.routes}getManifest(){if(this.manifest===void 0)throw Error("HTTP route registry has not been finalized");return this.manifest}getApiRoutes(){if(this.apiRoutes===void 0)throw Error("HTTP route registry has not been finalized");return[...this.apiRoutes]}getWebRoutes(){if(this.webRoutes===void 0)throw Error("HTTP route registry has not been finalized");return[...this.webRoutes]}}function hI(e,t){e.addFinalizer(()=>t.pluginManager.shutdownPlugins()),e.addFinalizer(()=>t.jobServicesLifecycle.closeRuntime()),e.addFinalizer(()=>t.agentService.shutdown?.()),e.addFinalizer(()=>t.daemonRegistry.unregister("shell:guest-retention")),e.addFinalizer(()=>t.daemonRegistry.unregister("shell:recurring-checks"))}var yG=r.discriminatedUnion("kind",[r.object({kind:r.literal("all")}).strict().describe("Search across all entity types"),r.object({kind:r.literal("type"),entityType:r.string().min(1).describe("Entity type to search")}).strict().describe("Search within one entity type")]),vI=r.object({query:r.string().describe("Search term"),scope:yG.describe("Structured search scope. Use { kind: 'all' } for broad search across all entity types. Use { kind: 'type', entityType } only when the user asks for a specific entity type."),limit:r.number().optional().describe("Maximum number of results"),minScore:r.number().min(0).optional().describe("Minimum relevance score. Default is 0.5; lower it only for exploratory or loose recall when weak candidates are acceptable."),includeUngenerated:r.boolean().optional().describe("Include queued/failed generation stubs in results")}),bI=r.object({entityType:r.string().describe("Entity type"),id:r.string().describe("Entity ID, slug, or title")}),_I=r.object({entityType:r.string().describe("Entity type to list"),status:r.string().optional().describe("Filter by status. Omit unless the user asks for a known status; do not invent generic statuses. For wish statuses: new, planned, in-progress, done, declined."),limit:r.number().optional().describe("Maximum number of results (default: 20)")}),vG=r.object({kind:r.literal("upload").describe("Upload ref kind"),id:r.string().min(1).describe("Upload ID")}),bG=r.object({kind:r.literal("user-message").describe("Save verbatim text already supplied by the user. The server reads the stored message; do not copy its body into tool arguments."),messageId:r.string().min(1).optional().describe("Stored user message ID in this conversation; omit for the latest user message."),boundaryMode:r.enum(["literal","lines"]).optional().describe("Use lines for standalone delimiter lines: supply marker text without newline characters. The server excludes the opening line and its line ending, and stops at the start of the closing line, preserving every byte between them, including final newlines. Omit or use literal for inline text boundaries."),startAfter:r.string().min(1).optional().describe("Exact unique opening boundary, excluded from saved text. In lines mode, supply the whole marker line WITHOUT newline characters. In literal mode, supply the exact prefix to exclude. Omit to start at the beginning of the message."),endBefore:r.string().min(1).optional().describe("Exact unique closing boundary, excluded from saved text. In lines mode, supply the whole marker line WITHOUT newline characters; preceding content newlines are preserved. In literal mode, supply the exact suffix to exclude. Omit to end at the end of the message."),contentHash:r.string().min(1).optional().describe("Internal source hash returned with the confirmation; omit on the initial request.")}).strict(),_G=r.discriminatedUnion("kind",[r.object({kind:r.literal("text").describe("Store exact/direct user-provided content without generation"),content:r.string().min(1).describe("Literal content for a direct save request without a stored user-message source. For pasted text already in this conversation, prefer source.kind user-message with exact boundaries instead of reproducing the body here.")}).strict(),bG,r.object({kind:r.literal("url").describe("Create URL/domain-backed entities such as links"),url:r.string().min(1).describe("URL or domain to create from; preserve a bare domain as provided instead of adding a scheme.")}).strict(),r.object({kind:r.literal("upload").describe("Use extract-markdown to import upload text into a note, or preserve only when the user explicitly wants to save the uploaded file/document bytes themselves. Do not use for saving a previous assistant summary about an upload; use prior-response for that."),upload:vG.describe("Exact upload candidate object from the current conversation"),transform:r.enum(["extract-markdown","preserve"]).describe("extract-markdown imports upload text into a note-like entity; preserve saves raw uploaded bytes via the registered upload-save handler and derives the durable entity type from media type. Use preserve only for explicit file/document preservation, not for saving an assistant summary response.")}).strict(),r.object({kind:r.literal("prior-response").describe("Save a previous assistant response as durable content, especially an assistant summary or answer about an upload."),messageId:r.string().min(1).optional().describe("Stored assistant message ID; omit for latest savable")}).strict()]),SG=r.discriminatedUnion("kind",[r.object({kind:r.literal("prompt").describe("Generate a new non-image durable entity from a broad prompt with no durable source entity. Use this for general topical social/newsletter/blog/deck generation. This branch has no source field; use prompt-from-source only after resolving a specific existing content entity."),entityType:r.string().min(1).describe("Entity type to generate from the prompt. Do not use image here; use standalone-image or cover-image."),title:r.string().optional().describe("Title for the generated entity"),prompt:r.string().min(1).describe("Prompt for creating new generated content. Do not use for saving/importing existing uploads or prior responses.")}).strict(),r.object({kind:r.literal("prompt-from-source").describe("Generate a new non-image durable entity from a specific resolved existing content entity. Use when the user asks to generate from/based on a source, including requests like 'create a newsletter based on my latest blog post'. After resolving the source with a tool result, call this operation in the same turn; do not merely say you can generate it."),entityType:r.string().min(1).describe("Entity type to generate from the source and prompt. Do not use image here; use standalone-image or cover-image."),title:r.string().optional().describe("Title for the generated entity"),source:r.object({entityType:r.string().min(1).describe("Resolved content source entity type, such as post for a newsletter from a blog post. Do not use brain-character or anchor-profile."),entityId:r.string().min(1).describe("Resolved source entity ID copied from a prior tool result or typed entity ref; never an upload id, filename, guessed slug, or future placeholder.")}).strict().describe("Existing durable source entity to ground this generation. Use only resolved entity refs, not uploads, filenames, profile/brain-character context, conversation-only context, unknown sources, or guessed sources."),prompt:r.string().min(1).describe("Prompt for creating new generated content from the resolved source. Do not use for saving/importing existing uploads or prior responses.")}).strict(),r.object({kind:r.literal("standalone-image").describe("Generate a standalone image that is not attached to another entity. Do not use this as a cover image substitute; requested covers require cover-image after the target entity exists."),title:r.string().optional().describe("Title for the generated image"),prompt:r.string().min(1).describe("Prompt for creating an unattached image. Not for cover images requested for a generated post/entity.")}).strict(),r.object({kind:r.literal("cover-image").describe("Generate an image and attach it to an existing entity as coverImageId. Use only after the target entity already exists and its real entityId is known; do not use in the same initial turn as generating that target entity."),target:r.object({entityType:r.string().min(1).describe("Existing target entity type. Use the actual type of the entity being covered: social-post for LinkedIn/social posts, post for blog posts, etc."),entityId:r.string().min(1).describe("Existing target entity ID copied from a prior tool result or typed entity ref; never a placeholder or guessed future id")}).strict().describe("Existing entity that should receive the generated coverImageId"),title:r.string().optional().describe("Title for the generated image"),prompt:r.string().min(1).describe("Prompt for creating the cover image")}).strict(),r.object({kind:r.literal("attachment").describe("Generate a deterministic durable artifact from an existing entity attachment provider"),source:r.object({entityType:r.string().min(1).describe("Source entity type"),entityId:r.string().min(1).describe("Canonical source entity ID copied from a prior tool result or typed entity ref; never an upload id, filename, guessed slug, or future placeholder")}).strict().describe("Existing durable entity whose attachment provider should render the artifact. Use only resolved entity refs, not uploads or conversation-only context."),attachmentType:r.string().min(1).describe('Source artifact type such as "carousel", "printable", or "og-image"'),title:r.string().optional().describe("Title for the generated artifact"),replace:r.boolean().optional().describe("Set true for regenerate, replace, refresh, or update requests so a deterministic artifact is regenerated instead of reused")}).strict()]),SI=r.object({entityType:r.string().describe("Entity type to create. Use wish for explicitly saved or tracked unmet requested capabilities or outcomes."),title:r.string().optional().describe("Title for a new entity."),visibility:yI.optional().describe("Content visibility. Omit for public. Use shared for team/collaborator content readable by Trusted and Admin callers. Use restricted for private/admin-only content."),source:_G.describe("Concrete source selector. Use exactly one source branch. For AI generation or source-derived artifacts, use system_generate instead."),replace:r.boolean().optional().describe("Create a new copy intentionally"),confirmed:r.literal(!0).optional().describe("Confirm the creation"),confirmationToken:r.string().optional().describe("Internal confirmation token returned by the confirmation flow")}).strict(),wI=r.object({operation:SG.describe("Generation operation selector. Use prompt for broad non-image AI-generated entities with no source, prompt-from-source for generation from a resolved existing entity, standalone-image for unattached images, cover-image for generated covers on existing entities, and attachment for deterministic source-derived artifacts; for regenerate/replace/refresh artifact requests use attachment with replace:true."),confirmed:r.literal(!0).optional().describe("Confirm generation"),confirmationToken:r.string().optional().describe("Internal confirmation token returned by the confirmation flow")}).strict(),wG=r.object({oldText:r.string().min(1).describe("Exact text occurring once in the original stored Markdown. Include enough context to be unique."),newText:r.string().describe("Literal replacement text; empty string deletes oldText.")}).strict(),Xd=r.object({entityType:r.string().describe("Entity type"),id:r.string().describe("Entity ID, slug, or title"),fields:r.record(r.string(),r.unknown()).optional().describe("Partial frontmatter fields to update. Use this for status, title, coverImageId, ogImageId, and metadata changes such as approving an agent. To set an existing image as an entity cover, update fields.coverImageId to that image id. To remove or clear a cover image, set fields.coverImageId to null, not an empty string. Do not use fields for anchor-profile; anchor-profile updates require full markdown content replacement via content."),content:r.string().optional().describe("Full markdown content replacement only. For small changes, use edits instead of regenerating the whole document. Do not combine content with edits or fields."),edits:r.array(wG).min(1).max(50).optional().describe("Preferred for small content edits, especially long notes. Exact, unique, non-overlapping replacements matched against the original Markdown, applied atomically after confirmation. Fetch the entity first. Omit content and fields when using edits. Unchanged text is preserved without regeneration."),confirmed:r.literal(!0).optional().describe("Confirm the update"),confirmationToken:r.string().optional().describe("Internal confirmation token returned by the confirmation flow"),contentHash:r.string().optional().describe("Content hash for optimistic concurrency")}),xI=r.object({entityType:r.string().describe("Entity type"),id:r.string().describe("Entity ID"),confirmed:r.literal(!0).optional().describe("Confirm the deletion"),confirmationToken:r.string().optional().describe("Internal confirmation token returned by the confirmation flow")}),WX=r.object({entityType:r.string().describe("Entity type to extract"),source:r.string().optional().describe("Source entity ID \u2014 omit for batch"),mode:r.enum(["derive","rebuild"]).optional().describe("Batch mode: project incrementally or rebuild from scratch"),confirmed:r.literal(!0).optional().describe("Confirm destructive rebuild"),confirmationToken:r.string().optional().describe("Internal confirmation token returned by the confirmation flow")}),TI=r.object({batchId:r.string().optional().describe("Specific batch ID to check"),jobTypes:r.array(r.string()).optional().describe("Filter by job types")}),II=r.object({type:r.string().describe("Type of insight to retrieve. Built-in: overview, publishing-cadence, content-health. Plugins may register additional types.")}),xG=r.object({entityType:r.string().optional(),entityId:r.string().optional(),attachmentType:r.string().optional()}),TG=r.object({mediaType:r.string(),url:r.string(),downloadUrl:r.string().optional(),previewUrl:r.string().optional(),filename:r.string().optional(),sizeBytes:r.number().optional(),source:xG.optional()}),VX=r.object({entityId:r.string().optional(),status:r.enum(["created","generating"]),jobId:r.string().optional(),attachment:TG.optional()}),ZX=r.object({status:r.literal("extracting"),jobId:r.string(),entityType:r.string(),source:r.string().optional(),mode:r.enum(["derive","rebuild"]).optional()});function jr(e,t,n,o){try{e.permissionService.assertEntityActionAllowed(t,n,o.userPermissionLevel);return}catch(i){if(i instanceof CI||i instanceof Error)return{success:!1,error:i.message};throw i}}var IG="system",kI=r.record(r.string(),r.unknown()),CG=r.looseObject({fields:kI});function Or(e,t,n,o,i={}){let{visibility:a="admin",sideEffects:s}=i;return{name:`${IG}_${e}`,description:t,inputSchema:n.shape,handler:async(l,c)=>{let u=n.safeParse(l);if(!u.success)return{success:!1,error:`Invalid input: ${u.error.issues.map((d)=>`${d.path.join(".")}: ${d.message}`).join(", ")}`};try{return await o(u.data,c)}catch(d){return{success:!1,error:ke(d)}}},visibility:a,...s?{sideEffects:s}:{}}}async function qs(e,t,n,o){let i={interfaceType:o.interfaceType,actor:o.actor,...o.channelId&&{channelId:o.channelId},...o.channelName&&{channelName:o.channelName}},a=await t(n,i);if(a.kind==="handled")return{kind:"handled",result:a.result};let s=a.input;if(s.visibility!==n.visibility)return{kind:"error",result:{success:!1,error:"Create interceptor changed or dropped the requested entity visibility."}};let l=jr(e,s.entityType,"create",o);if(l)return{kind:"error",result:l};return{kind:"continue",createInput:s}}function Gn(e,t){if(e.entityRegistry.hasEntityType(t))return;let n=e.entityService.getEntityTypes();return{success:!1,error:`Entity type "${t}" is not available in this brain. Available types: ${n.join(", ")}.`}}function $o(e){let t={...e.conversationId?{conversationId:e.conversationId}:{},...e.channelId?{channelId:e.channelId}:{},...e.runId?{runId:e.runId}:{},...e.toolCallId?{toolCallId:e.toolCallId}:{}};return Object.keys(t).length>0?t:void 0}function ep(e,t){if(t.getEntityTypeConfig(e.entityType).binaryStorage)return{...e,content:`[binary ${e.entityType} data \u2014 use metadata for ${e.entityType} info]`};return e}function Jn(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}function RI(e){if(e.fields!==void 0)return{...e};if(!e.content)return{};try{let t=JSON.parse(e.content),n=CG.safeParse(t);if(n.success)return{fields:n.data.fields};let o=kI.safeParse(t);if(o.success)return{fields:o.data}}catch{}return{content:e.content}}var kG={base:"note"};function EI(e){return kG[e]??e.replaceAll("-"," ")}function Fs(e){return[e.metadata.title,e.metadata.name,e.metadata.subject,e.metadata.slug].find((o)=>typeof o==="string"&&o.trim().length>0)??e.id}function AI(e){return!!e&&Object.keys(e.shape).length>0}async function PI(e,t,n){if(!n)return!1;let o=await e.conversationService.getMessages(n,{limit:100});for(let i of o){let s=Ls(i.metadata)?.attachments;if(!Array.isArray(s))continue;for(let l of s){if(!yr(l))continue;let c=l.source;if(!yr(c))continue;if(c.kind===t.kind&&c.id===t.id)return!0}}return!1}var RG={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"};function EG(e){return{summary:`Save uploaded file${e.title?` as "${e.title}"`:""}?`,preview:[`Filename: ${e.filename}`,`Media type: ${e.mediaType}`,`Entity type: ${e.entityType}`,`Visibility: ${e.visibility??"public"}`,...e.title?[`Title: ${e.title}`]:[]].join(`
169
+ `)}}function AG(e){let{entityType:t,title:n,visibility:o,prompt:i,content:a,url:s,from:l}=e,c=n?` "${n}"`:` ${t}`,u=`${i?"Generate":"Create"}${c}?`,d=l?.kind==="entity-attachment"?l:void 0,m=[`Entity type: ${t}`,`Visibility: ${o??"public"}`,...n?[`Title: ${n}`]:[],...s?[`URL: ${s}`]:[],...l?.kind==="upload"?["Upload: uploaded file"]:[],...d?[`Source attachment: ${d.sourceEntityType}/${d.sourceEntityId} (${d.attachmentType})`]:[],...i?[`Prompt: ${i}`]:[],...a?[`Content preview: ${a.slice(0,500)}`]:[]];return{summary:u,preview:m.join(`
170
+ `)}}async function PG(e,t,n){let o=n.conversationId??n.channelId;if(!o)return{success:!1,error:"Conversation message is not accessible in this conversation or does not exist."};let i=await e.conversationService.getMessages(o,{limit:100}),a=t.kind==="user-message",s=a?i.filter((p)=>{if(p.role!=="user")return!1;let f=n.userPermissionLevel??"public";if(f==="admin")return!0;let g=Ls(p.metadata)?.userPermissionLevel;return(g==="public"||g==="trusted"||g==="admin")&&e.permissionService.hasPermission(f,g)}):i.filter(MI),l=t.messageId?s.find((p)=>p.id===t.messageId):s.at(-1);if(!l)return{success:!1,error:"Conversation message is not accessible in this conversation or does not exist."};if(!a)return{success:!0,messageId:l.id,content:l.content};let c=(p,f,g)=>{if(p===void 0)return f;if(t.boundaryMode==="lines"){if(/[\r\n]/.test(p))return-1;let v=0,x=-1;for(let S of l.content.split(/(?<=\n)/)){if(S.replace(/\r?\n$/,"")===p){if(x>=0)return-1;x=v+(g?S.length:0)}v+=S.length}return x}let h=l.content.indexOf(p);return h>=0&&h===l.content.lastIndexOf(p)?h+(g?p.length:0):-1},u=c(t.startAfter,0,!0),d=c(t.endBefore,l.content.length,!1);if(u<0||d<0||u>=d)return{success:!1,error:"User-message boundaries must each occur exactly once and select non-empty content in order. In lines mode, use complete marker lines without newline characters. Request clarification if the intended content cannot be selected uniquely."};let m=l.content.slice(u,d);if(t.contentHash&&t.contentHash!==bn(m))return{success:!1,error:"User-message source changed after the proposal. Request creation again and confirm the new approval."};return{success:!0,messageId:l.id,content:m}}function MG(e){switch(e.kind){case"text":return{content:e.content};case"url":return{url:e.url};case"upload":return{from:e.upload,uploadRef:e.upload,transform:e.transform};case"prior-response":case"user-message":return{conversationMessageRef:e}}}function jG(e){if(e.source.kind==="user-message"){if(!e.resolvedMessageId||e.content===void 0)throw Error("User-message source was not resolved before confirmation");return{...e.source,messageId:e.resolvedMessageId,contentHash:bn(e.content)}}if(e.source.kind==="prior-response"){let t=e.source.messageId??e.resolvedMessageId;return{kind:"prior-response",...t?{messageId:t}:{}}}return e.source}async function OG(e,t){let n={interfaceType:t.interfaceType,actor:t.actor,...t.channelId&&{channelId:t.channelId},...t.channelName&&{channelName:t.channelName}};return e.handler({upload:e.upload,...e.title&&{title:e.title},...e.visibility!==void 0?{visibility:e.visibility}:{}},n)}async function NG(e,t,n){let{entityService:o,entityRegistry:i}=e,a=Qr(t.title??`${t.entityType}-${Date.now()}`),s=i.getEffectiveFrontmatterSchema(t.entityType);try{let l={deduplicateId:!0,...n?{eventContext:n}:{}};return{success:!0,data:{entityId:(t.content&&AI(s)?await o.createEntityFromMarkdown({input:{entityType:t.entityType,id:a,markdown:t.content,...t.visibility!==void 0?{visibility:t.visibility}:{}},options:l}):await o.createEntity({entity:{id:a,entityType:t.entityType,content:t.content??"",metadata:{title:t.title??a},...t.visibility!==void 0?{visibility:t.visibility}:{},created:new Date().toISOString(),updated:new Date().toISOString()},options:l})).entityId,status:"created"}}}catch(l){return{success:!1,error:ke(l,"Failed to create entity")}}}function _n(e){return{kind:"error",result:{success:!1,error:e}}}async function DG(e,t,n){let{content:o,url:i,from:a,uploadRef:s,conversationMessageRef:l,transform:c}=MG(t.source),u=l?await PG(e,l,n):void 0;if(u&&!u.success)return{kind:"error",result:u};let d=u?.success===!0?u.content:o;if(c==="extract-markdown"&&(!s||!e.entityRegistry.getEntityTypeConfig(t.entityType).markdownImport)){let m=e.entityRegistry.getAllEntityTypes().filter((p)=>e.entityRegistry.getEntityTypeConfig(p).markdownImport);return _n(`Transform "extract-markdown" requires an upload ref and a type declaring markdownImport. Available: ${m.join(", ")||"none"}. Omit transform for raw file promotion.`)}if(!d&&!i&&!a)return _n('Provide `source` with kind "user-message", "text", "url", "prior-response", or "upload". Use system_generate for generated content or artifacts.');return{kind:"ok",value:{content:d,url:i,from:a,uploadRef:s,transform:c,resolvedMessageId:u?.success===!0?u.messageId:void 0}}}async function zG(e,t,n){if(!await PI(e,t.uploadRef,n.conversationId??n.channelId))return _n("Upload ref is not accessible in this conversation or no longer exists.");if(t.transform!=="preserve")return{kind:"ok",value:{entityType:t.entityType,uploadPreserve:void 0}};let i;try{i=await e.runtimeUploads.scoped(RG).readRecord(t.uploadRef.id)}catch{return _n("Upload ref not found")}let a=e.entityRegistry.getUploadSaveHandler(i.mediaType);if(!a)return _n(`No installed plugin can save uploads with media type "${i.mediaType}".`);return{kind:"ok",value:{entityType:a.entityType,uploadPreserve:{upload:t.uploadRef,filename:i.filename,mediaType:i.mediaType,handler:a.handler}}}}function UG(e,t,n){let o=t?Gs(t):void 0;if(e!==void 0&&o!==void 0&&e!==o)return _n(`Conflicting entity visibility: system_create requested "${e}" but the source frontmatter declares "${o}".`);let i=e??o,a=i??"public";if(!Bs(n.userPermissionLevel,a))return _n(`Cannot create entity with visibility "${a}" \u2014 caller permission "${n.userPermissionLevel??"public"}" is not allowed to write at that level.`);return{kind:"ok",value:i}}async function $G(e,t,n){if(n||t.replace)return;let o=t.title?Qr(t.title):void 0;if(!o)return;if(!await e.entityService.getEntity({entityType:t.entityType,id:o}))return;return{success:!1,error:`A ${t.entityType} already exists for "${o}". To change its fields or status, use system_update; pass replace:true to create a new copy intentionally.`}}async function LG(e,t,n){if(!(t.source.kind==="upload"&&t.source.transform==="preserve")){let C=Gn(e,t.entityType);if(C)return{kind:"error",result:C}}let i=await DG(e,t,n);if(i.kind==="error")return i;let{content:a,url:s,from:l,uploadRef:c,transform:u,resolvedMessageId:d}=i.value,m=c?await zG(e,{entityType:t.entityType,uploadRef:c,transform:u},n):void 0;if(m?.kind==="error")return m;let p=m?.value.entityType??t.entityType,f=m?.value.uploadPreserve,g=Gn(e,p);if(g)return{kind:"error",result:g};let h=UG(t.visibility,a,n);if(h.kind==="error")return h;let v=Jn(t.title),x=t.replace===!0,S={entityType:p,...v&&{title:v},...h.value!==void 0?{visibility:h.value}:{},...a&&{content:a},...s&&{url:s},...l&&{from:l},...u&&{transform:u},...x&&{replace:x}},y=jr(e,S.entityType,"create",n);if(y)return{kind:"error",result:y};let w=e.entityRegistry.getCreateInterceptor(S.entityType);if(!S.content&&!w&&!f)return _n('URL or upload source creation is supported only for entity types that explicitly handle it. Provide source kind "text" for this entity type, or use system_generate for generated content/artifacts.');let _=await $G(e,S,w);if(_)return{kind:"error",result:_};return{kind:"ok",prepared:{createInput:S,resolvedMessageId:d,interceptor:w,eventContext:$o(n),...f&&{uploadPreserve:f}}}}function jI(e){let t=en({label:"create",requestNoun:"creation"});return Or("create","Create a new entity from existing material. Never create a duplicate to save edits: use system_update for entities already created or imported in this conversation, even while an upload import is generating. Requires confirmation; call this tool without confirmed to request that confirmation instead of asking for plain-text approval. Use visibility shared for team/collaborator content, restricted for private/admin-only content, and omit it for public content; keep visibility separate from exact source text. Use source to choose exactly one concrete source: user-message for verbatim content already pasted in this conversation (the server extracts the stored text without model copying), text for literal content without a stored message source, url for URL-first flows, prior-response for saving a previous assistant response, or upload with transform extract-markdown to import text into a note or transform preserve to save raw uploaded bytes as their durable file entity. Entity-specific instructions may direct proactive capture of the user's request itself; in that case the request is concrete text and no separate save verb is required. Use system_generate for AI generation, generated images, cover images, and source-derived artifacts such as carousel/printable PDFs or OG images. If the user includes content in the same direct save request, use source.kind user-message, omitting messageId for the latest user message. For standalone delimiter lines, use boundaryMode lines with startAfter/endBefore set to the exact marker line text WITHOUT newline characters; the server preserves all intervening bytes, including final newlines. For inline content, use literal startAfter/endBefore boundaries to exclude the save instruction. Omit boundaries only when saving the whole message. Never retype, shorten, correct, or include delimiter text in pasted source material, and never ask for a smaller copy just because it is long. For 'Save this as a note: ...', startAfter can be the exact 'Save this as a note: ' prefix. If boundaries are ambiguous, ask for clarification. If the user says save it/that/this after your immediately preceding upload summary/answer, use entityType note with source.kind prior-response unless they explicitly ask to save the uploaded file/document itself; do this even when the prior answer says there was limited readable content, and do not ask whether they meant the summary or the file after you just summarized/answered about the upload. A bare upload receipt like 'I got filename. What would you like me to do?' is not a summary/answer: for a following 'save it', preserve the latest uploaded file itself with upload transform preserve (image uploads as entityType image). Only use source.kind upload when the runtime supplies an actual upload reference/attachment; if the user message merely contains a pasted uploaded-file transcript with readable content, use source.kind user-message with boundaries selecting that visible content. On the initial create request, do not pass confirmed; the tool will return confirmation args after the user confirms.",SI,async(n,o)=>{let i=await LG(e,n,o);if(i.kind==="error")return i.result;let{createInput:a}=i.prepared,{resolvedMessageId:s,interceptor:l,eventContext:c,uploadPreserve:u}=i.prepared;if(n.confirmed){let d=t.validateConfirmed(n.confirmationToken,n);if(d)return d}else{let d=u?EG({...a.title&&{title:a.title},filename:u.filename,mediaType:u.mediaType,entityType:a.entityType,visibility:a.visibility}):AG(a),m=jG({source:n.source,...s&&{resolvedMessageId:s},...a.content!==void 0?{content:a.content}:{}}),p=t.buildArgs((f)=>({entityType:a.entityType,...a.title&&{title:a.title},...a.visibility!==void 0?{visibility:a.visibility}:{},source:m,...a.replace&&{replace:a.replace},confirmed:!0,confirmationToken:f}));return{needsConfirmation:!0,toolName:"system_create",summary:d.summary,preview:d.preview,args:p}}if(u)return OG({upload:u.upload,...a.title&&{title:a.title},...a.visibility!==void 0?{visibility:a.visibility}:{},handler:u.handler},o);if(l){let d=await qs(e,l,a,o);if(d.kind==="handled"||d.kind==="error")return d.result;a=d.createInput}if(!a.content)return{success:!1,error:'URL or upload source creation is supported only for entity types that explicitly handle it. Provide source kind "text" for this entity type, or use system_generate for generated content/artifacts.'};return NG(e,a,c)},{visibility:"trusted",sideEffects:"writes"})}function qG(e){let t=e.title?` "${e.title}"`:` ${e.entityType}`,n=e.from?.kind==="entity-attachment"?e.from:void 0,o=[`Entity type: ${e.entityType}`,...e.title?[`Title: ${e.title}`]:[],...e.prompt?[`Prompt: ${e.prompt}`]:[],...n?[`Source attachment: ${n.sourceEntityType}/${n.sourceEntityId} (${n.attachmentType})`]:[],...e.targetEntityType&&e.targetEntityId?[`Target: ${e.targetEntityType}/${e.targetEntityId}`]:[]];return{summary:`Generate${t}?`,preview:o.join(`
171
+ `)}}async function FG(e,t,n){if(!t)return{kind:"ok",sourceAttachment:void 0};let o=await Nr(e.entityService,t.sourceEntityType,t.sourceEntityId,e.logger,void 0,n);if(!o.ok)return{kind:"error",result:{success:!1,error:o.error,code:"source-not-found"}};let i={...t,sourceEntityId:o.entity.id};if(!e.attachments.hasProvider(i.sourceEntityType,i.attachmentType))return{kind:"error",result:{success:!1,error:`No attachment provider found for ${i.sourceEntityType}/${i.attachmentType}.`,code:"no-provider"}};let a=e.attachments.getProviderMetadata(i.sourceEntityType,i.attachmentType);if(!a)return{kind:"error",result:{success:!1,error:`Attachment provider for ${i.sourceEntityType}/${i.attachmentType} is missing output metadata.`,code:"provider-missing-metadata"}};return{kind:"ok",sourceAttachment:i,metadata:a}}async function BG(e,t,n){if(!t)return{kind:"ok",source:void 0};let o=await Nr(e.entityService,t.entityType,t.entityId,e.logger,void 0,n);if(!o.ok)return{kind:"error",result:{success:!1,error:o.error,code:"source-not-found"}};return{kind:"ok",source:{...t,entityId:o.entity.id}}}async function GG(e,t,n){if(!t)return{kind:"ok",target:void 0};let o=await Nr(e.entityService,t.entityType,t.entityId,e.logger,void 0,n);if(!o.ok)return{kind:"error",result:{success:!1,error:o.error}};return{kind:"ok",target:{...t,entityId:o.entity.id}}}async function JG(e,t,n,o,i){let{entityService:a,jobs:s}=e,l=Qr(t.title??n).slice(0,100);if(!l)return{success:!1,error:"Could not derive a slug from the provided title/prompt. Provide a 'title' with at least one URL-safe character."};let c=t.title??l,u=OI(e.entityRegistry,{entityType:t.entityType,id:l,title:c});if(!u)return{success:!1,error:`Entity type '${t.entityType}' does not support queued generation. Provide an exact source to system_create instead.`};let d;try{d=(await a.createEntity({entity:u,options:{deduplicateId:!0,...o?{eventContext:o}:{}}})).entityId}catch(m){return{success:!1,error:ke(m,"Failed to persist generation stub")}}try{let m=await s.enqueue({type:`${t.entityType}:generation`,data:{entityId:d,prompt:n,...t.title&&{title:t.title},...t.sourceEntityType&&{sourceEntityType:t.sourceEntityType},...t.sourceEntityId&&{sourceEntityId:t.sourceEntityId},...t.sourceEntityIds&&{sourceEntityIds:t.sourceEntityIds},...t.targetEntityType&&{targetEntityType:t.targetEntityType},...t.targetEntityId&&{targetEntityId:t.targetEntityId}},toolContext:i});return{success:!0,data:{entityId:d,status:"generating",jobId:m}}}catch(m){return{success:!1,error:ke(m,"Failed to queue generation job")}}}async function HG(e,t,n){let o,i,a=t.kind==="attachment"&&t.replace===!0;if(t.kind==="prompt"||t.kind==="prompt-from-source"){if(e.entityRegistry.getEntityTypeConfig(t.entityType).binaryStorage)return{kind:"error",result:{success:!1,error:`Prompt generation does not support binary entity type '${t.entityType}'. Use operation.kind 'attachment' for source-derived artifacts, or 'standalone-image' or 'cover-image' for generated images.`,code:"unsupported-generation"}};let s=t.kind==="prompt-from-source"?await BG(e,t.source,n):{kind:"ok",source:void 0};if(s.kind==="error")return s;let l=Jn(t.title);o={entityType:t.entityType,...l?{title:l}:{},prompt:t.prompt,...s.source?.entityType&&{sourceEntityType:s.source.entityType},...s.source?.entityId&&{sourceEntityId:s.source.entityId,sourceEntityIds:[s.source.entityId]}}}else if(t.kind==="standalone-image"){let s=Jn(t.title);o={entityType:"image",...s?{title:s}:{},prompt:t.prompt}}else if(t.kind==="cover-image"){let s=await GG(e,t.target,n);if(s.kind==="error"){let c=s.result;return{kind:"error",result:"success"in c&&c.success===!1?{...c,code:"target-not-found"}:c}}let l=Jn(t.title);o={entityType:"image",...l?{title:l}:{},prompt:t.prompt,...s.target?.entityType&&{targetEntityType:s.target.entityType},...s.target?.entityId&&{targetEntityId:s.target.entityId}}}else{let s=await FG(e,{sourceEntityType:t.source.entityType,sourceEntityId:t.source.entityId,attachmentType:t.attachmentType},n);if(s.kind==="error")return s;i=s.sourceAttachment;let l=s.metadata;if(!l||!i)return{kind:"error",result:{success:!1,error:"Attachment generation requires provider metadata.",code:"provider-missing-metadata"}};let c=Jn(t.title);o={entityType:l.outputEntityType,...c?{title:c}:{},from:{kind:"entity-attachment",...i},...a&&{replace:a},...l.targetField&&{targetEntityType:i.sourceEntityType,targetEntityId:i.sourceEntityId}}}return{kind:"ok",createInput:o,sourceAttachment:i}}async function WG(e,t,n){let o=t.operation,i=Wt(n.userPermissionLevel),a=await HG(e,o,i);if(a.kind==="error")return a;let{createInput:s,sourceAttachment:l}=a,c=o.kind==="attachment"&&o.replace===!0,u=Gn(e,s.entityType);if(u)return{kind:"error",result:u};let d=jr(e,s.entityType,"create",n);if(d)return{kind:"error",result:d};let m=e.entityRegistry.getCreateInterceptor(s.entityType);if(!s.prompt&&!s.from)return{kind:"error",result:{success:!1,error:"Provide a generation source."}};if(s.from&&!m)return{kind:"error",result:{success:!1,error:`Entity type '${s.entityType}' does not support attachment-based generation. Use operation.kind prompt-from-source for AI-generated content based on referenced source material, or choose an entity type with an attachment provider.`,code:"unsupported-generation"}};if(!m&&!c){let p=s.prompt?Qr(s.title??s.prompt).slice(0,100):s.title?Qr(s.title):void 0;if(p){if(await e.entityService.getEntity({entityType:s.entityType,id:p}))return{kind:"error",result:{success:!1,error:`A ${s.entityType} already exists for "${p}". To change its fields or status, use system_update; pass replace:true to generate a new copy intentionally.`}}}}return{kind:"ok",prepared:{createInput:s,operation:VG(o,s,l),sourceAttachment:l,interceptor:m,eventContext:$o(n)}}}function VG(e,t,n){if(e.kind==="attachment"){let o=n??{sourceEntityType:e.source.entityType,sourceEntityId:e.source.entityId,attachmentType:e.attachmentType};return{kind:"attachment",source:{entityType:o.sourceEntityType,entityId:o.sourceEntityId},attachmentType:o.attachmentType,...t.title&&{title:t.title},...t.replace&&{replace:t.replace}}}if(e.kind==="cover-image")return{kind:"cover-image",target:{entityType:t.targetEntityType??e.target.entityType,entityId:t.targetEntityId??e.target.entityId},...t.title&&{title:t.title},prompt:e.prompt};if(e.kind==="standalone-image")return{kind:"standalone-image",...t.title&&{title:t.title},prompt:e.prompt};if(e.kind==="prompt-from-source")return{kind:"prompt-from-source",entityType:t.entityType,...t.title&&{title:t.title},source:{entityType:t.sourceEntityType??e.source.entityType,entityId:t.sourceEntityId??e.source.entityId},prompt:e.prompt};return{kind:"prompt",entityType:t.entityType,...t.title&&{title:t.title},prompt:e.prompt}}function NI(e){let t=en({label:"generate",requestNoun:"generation"});return Or("generate","Generate durable content or artifacts. Critical: for a request to generate a post/social-post/newsletter/etc. with a cover image, call only the prompt generation first; do not call standalone-image or cover-image until the target entity exists after confirmation. Critical: broad or underspecified topical generation uses operation.kind prompt and has no source field; preserve the user's wording as the prompt and do not stop to ask what details to highlight. Never invent source IDs, use brain-character/profile, uploads, filenames, guessed ids, or placeholders as source refs. Critical: when the user asks to generate from a source such as 'my latest blog post', resolve the source, then call operation.kind prompt-from-source in the same turn; for latest blog/published source requests, use system_list metadata to compare publishedAt and do not rely on semantic search order. If dated candidates such as publishedAt are visible, choose the newest candidate by publishedAt (not updated/created order) and do not stop with prose like 'I found it and can generate it' or 'if that is the one you mean.' Requires confirmation. Calling this tool without confirmed is how you request that confirmation; do not respond with separate prose such as 'I can generate it if you want' or 'I need to queue it first.' Use operation.kind prompt for broad non-image AI-generated entities with no source, including in the same turn after an optional search finds no source. Use operation.kind prompt-from-source only when generating from a resolved existing durable source entity, for example a newsletter from a resolved post: { kind: 'prompt-from-source', entityType: 'newsletter', source: { entityType: 'post', entityId: '...' }, prompt: '...' }. Use standalone-image only for unattached generated images, cover-image with operation.target only for generated covers on existing entities, and attachment with operation.source for source-derived artifacts such as carousel/printable PDFs or OG/social preview images. When a cover-image request for an existing entity resolves a clear target via search/get, call this tool in the same turn; do not stop after saying you found the entity. For regenerate/replace/refresh source-derived artifact requests, call attachment with replace:true immediately; do not say you can queue it later. When the user asks to create/write/draft/generate new durable content, call this tool without confirmed to request confirmation instead of asking for separate prose approval. If you first resolve a clear source entity for the requested generation, still call this tool in the same turn using prompt-from-source. Use system_create instead for saving/importing existing text, URLs, uploads, prior assistant responses, or raw uploaded file preservation with upload transform preserve. On the initial generation request, do not pass confirmed; the tool returns confirmation args.",wI,async(n,o)=>{let i=await WG(e,n,o);if(i.kind==="error")return i.result;let{createInput:a}=i.prepared,{operation:s,interceptor:l,eventContext:c}=i.prepared;if(n.confirmed){let u=t.validateConfirmed(n.confirmationToken,n);if(u)return u}else{let u=qG(a),d=t.buildArgs((m)=>({operation:s,confirmed:!0,confirmationToken:m}));return{needsConfirmation:!0,toolName:"system_generate",summary:u.summary,preview:u.preview,args:d}}if(l){let u=await qs(e,l,a,o);if(u.kind==="handled"||u.kind==="error")return u.result;a=u.createInput}if(!a.prompt)return{success:!1,error:"Attachment generation is supported only for entity types that explicitly handle source-derived artifacts."};return JG(e,a,a.prompt,c,o)},{visibility:"trusted",sideEffects:"writes"})}function DI(e){let{entityService:t,entityRegistry:n,logger:o}=e,i=en({label:"delete",requestNoun:"deletion"});return Or("delete","Request entity deletion by id. Unauthorized callers get a permission error; authorized callers get confirmation first. Do not pass confirmed on the initial request.",xI,async(a,s)=>{if((s.userPermissionLevel??"public")==="public")return{success:!1,error:"Changing content requires higher permission; current permission is Public."};let l=jr(e,a.entityType,"delete",s);if(l)return l;let c=Gn(e,a.entityType);if(c)return c;if(n.getAdapter(a.entityType).isSingleton===!0)return{success:!1,error:`${a.entityType} is a singleton entity and cannot be deleted through system tools. Update it instead.`};let u=Wt(s.userPermissionLevel),d=await Nr(t,a.entityType,a.id,o,void 0,u);if(!d.ok)return{success:!1,error:d.error};let{entity:m}=d;if(a.confirmed){let g=i.validateConfirmed(a.confirmationToken,a);if(g)return g;try{await t.deleteEntity({entityType:a.entityType,id:m.id})}catch(h){return{success:!1,error:ke(h,"Failed to delete entity")}}return{success:!0,data:{deleted:m.id}}}let p=Fs(m),f=i.buildArgs((g)=>({...a,id:m.id,confirmed:!0,confirmationToken:g}));return{needsConfirmation:!0,toolName:"system_delete",summary:`Delete "${p}"?`,preview:m.content.slice(0,200),args:f}},{visibility:"admin",sideEffects:"writes"})}function zI(e,t){let n=t.map(({oldText:a,newText:s},l)=>{let c=e.indexOf(a);if(!a||c<0)throw Error(`Edit ${l+1}: oldText was not found. Fetch the entity again and provide exact text.`);if(e.indexOf(a,c+1)!==-1)throw Error(`Edit ${l+1}: oldText is ambiguous. Include more surrounding text to match exactly once.`);return{start:c,end:c+a.length,newText:s}}).sort((a,s)=>a.start-s.start),o=0,i=[];for(let a of n){if(a.start<o)throw Error("Edits overlap in the original content. Provide non-overlapping replacements.");i.push(e.slice(o,a.start),a.newText),o=a.end}return i.push(e.slice(o)),i.join("")}import{isDeepStrictEqual as iC}from"util";class Js{diff(e,t,n={}){let o;if(typeof n==="function")o=n,n={};else if("callback"in n)o=n.callback;let i=this.castInput(e,n),a=this.castInput(t,n),s=this.removeEmpty(this.tokenize(i,n)),l=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(s,l,n,o)}diffWithOptionsObj(e,t,n,o){var i;let a=(x)=>{if(x=this.postProcess(x,n),o){setTimeout(function(){o(x)},0);return}else return x},s=t.length,l=e.length,c=1,u=s+l;if(n.maxEditLength!=null)u=Math.min(u,n.maxEditLength);let d=(i=n.timeout)!==null&&i!==void 0?i:1/0,m=Date.now()+d,p=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(p[0],t,e,0,n);if(p[0].oldPos+1>=l&&f+1>=s)return a(this.buildValues(p[0].lastComponent,t,e));let g=-1/0,h=1/0,v=()=>{for(let x=Math.max(g,-c);x<=Math.min(h,c);x+=2){let S,y=p[x-1],w=p[x+1];if(y)p[x-1]=void 0;let _=!1;if(w){let I=w.oldPos-x;_=w&&0<=I&&I<s}let C=y&&y.oldPos+1<l;if(!_&&!C){p[x]=void 0;continue}if(!C||_&&y.oldPos<w.oldPos)S=this.addToPath(w,!0,!1,0,n);else S=this.addToPath(y,!1,!0,1,n);if(f=this.extractCommon(S,t,e,x,n),S.oldPos+1>=l&&f+1>=s)return a(this.buildValues(S.lastComponent,t,e))||!0;else{if(p[x]=S,S.oldPos+1>=l)h=Math.min(h,x-1);if(f+1>=s)g=Math.max(g,x+1)}}c++};if(o)(function x(){setTimeout(function(){if(c>u||Date.now()>m)return o(void 0);if(!v())x()},0)})();else while(c<=u&&Date.now()<=m){let x=v();if(x)return x}}addToPath(e,t,n,o,i){let a=e.lastComponent;if(a&&!i.oneChangePerToken&&a.added===t&&a.removed===n)return{oldPos:e.oldPos+o,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}};else return{oldPos:e.oldPos+o,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,o,i){let a=t.length,s=n.length,l=e.oldPos,c=l-o,u=0;while(c+1<a&&l+1<s&&this.equals(n[l+1],t[c+1],i))if(c++,l++,u++,i.oneChangePerToken)e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1};if(u&&!i.oneChangePerToken)e.lastComponent={count:u,previousComponent:e.lastComponent,added:!1,removed:!1};return e.oldPos=l,c}equals(e,t,n){if(n.comparator)return n.comparator(e,t);else return e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)if(e[n])t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join("")}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let o=[],i;while(e)o.push(e),i=e.previousComponent,delete e.previousComponent,e=i;o.reverse();let a=o.length,s=0,l=0,c=0;for(;s<a;s++){let u=o[s];if(!u.removed){if(!u.added&&this.useLongestToken){let d=t.slice(l,l+u.count);d=d.map(function(m,p){let f=n[c+p];return f.length>m.length?f:m}),u.value=this.join(d)}else u.value=this.join(t.slice(l,l+u.count));if(l+=u.count,!u.added)c+=u.count}else u.value=this.join(n.slice(c,c+u.count)),c+=u.count}return o}}class UI extends Js{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}}var $I=new UI;function tp(e,t,n){return $I.diff(e,t,n)}var Hs=r.enum(["png","jpg","jpeg","webp","gif","svg"]),qI=r.enum(["pending","draft","failed"]),FI=r.object({title:r.string().optional(),alt:r.string().optional(),format:Hs,width:r.number(),height:r.number(),status:qI.optional(),processingJobId:r.string().optional(),processingError:r.string().optional(),sourceUrl:r.url().optional(),sourceEntityType:r.string().optional(),sourceEntityId:r.string().optional(),sourceUploadId:r.string().optional(),sourceFilename:r.string().optional(),sourceMediaType:r.string().optional(),attachmentType:r.string().optional(),dedupKey:r.string().optional()}),oa=LI.extend({entityType:r.literal("image"),metadata:FI}),ZG=r.object({url:r.string(),alt:r.string(),title:r.string(),width:r.number(),height:r.number()});function BI(e){return/^https?:\/\//i.test(e)}async function GI(e,t){let n=await fetch(e);if(!n.ok)throw Error(`Failed to fetch: ${n.status} ${n.statusText}`);let o=n.headers.get("content-type");if(t&&!o?.startsWith(t))throw Error(`URL does not point to expected content type: ${o}`);let i=await n.arrayBuffer(),a=Buffer.from(i).toString("base64");return`data:${o?.split(";")[0]??"application/octet-stream"};base64,${a}`}function HI(e){let t=e.trim().match(/^data:image\/([a-z+]+);base64,(.+)$/i);if(!t?.[1]||!t[2])return null;return{format:t[1].toLowerCase(),base64:t[2]}}function Ws(e){let t=HI(e);if(!t)throw Error("Invalid image data URL");return t}function KG(e,t){return`data:image/${t==="jpg"?"jpeg":t};base64,${e}`}var YG={png:"iVBORw",jpg:"/9j/",gif:"R0lGOD",webp:"UklGR"};function rp(e){for(let[t,n]of JI(YG))if(e.startsWith(n))return t;return null}function WI(e){let t=e.toLowerCase(),n=t==="svg+xml"?"svg":t,o=Hs.safeParse(n);return o.success?o.data:null}async function QG(e){return GI(e,"image/")}function Vs(e){let t=Buffer.from(e,"base64");if(t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71){let n=t.readUInt32BE(16),o=t.readUInt32BE(20);return{width:n,height:o}}if(t[0]===255&&t[1]===216){let n=2;while(n<t.length-8){if(t[n]!==255){n++;continue}let o=t[n+1];if(o===192||o===194){let a=t.readUInt16BE(n+5);return{width:t.readUInt16BE(n+7),height:a}}let i=t.readUInt16BE(n+2);n+=2+i}}if(t[0]===71&&t[1]===73&&t[2]===70){let n=t.readUInt16LE(6),o=t.readUInt16LE(8);return{width:n,height:o}}if(t.length>=30&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70){if(t[12]===86&&t[13]===80&&t[14]===56){if(t[15]===32){let n=t[26]??0,o=t[27]??0,i=t[28]??0,a=t[29]??0,s=(n|o<<8)&16383,l=(i|a<<8)&16383;return{width:s,height:l}}if(t[15]===76&&t.length>=25){let n=t.readUInt32LE(21),o=(n&16383)+1,i=(n>>14&16383)+1;return{width:o,height:i}}}}return null}function VI(e){let t=WI(e);if(!t)throw Error(`Unsupported image format: ${e}`);return t}class np{entityType="image";purpose="Image assets such as generated covers, social previews, and uploaded images.";schema=oa;toMarkdown(e){return e.content}fromMarkdown(e){let{format:t,base64:n}=Ws(e),o=Vs(n);return{entityType:"image",content:e,metadata:{format:VI(t),width:o?.width??0,height:o?.height??0}}}extractMetadata(e){return e.metadata}parseFrontMatter(e,t){return t.parse({})}generateFrontMatter(e){return""}getBodyTemplate(){return""}createImageEntity(e){let{dataUrl:t,title:n,alt:o}=e,{format:i,base64:a}=Ws(t),s=Vs(a),c=rp(a)??VI(i);return{entityType:"image",content:t,metadata:{title:n,alt:o??n,format:c,width:s?.width??0,height:s?.height??0,...e.status&&{status:e.status},...e.sourceUrl&&{sourceUrl:e.sourceUrl},...e.sourceEntityType&&{sourceEntityType:e.sourceEntityType},...e.sourceEntityId&&{sourceEntityId:e.sourceEntityId},...e.sourceUploadId&&{sourceUploadId:e.sourceUploadId},...e.sourceFilename&&{sourceFilename:e.sourceFilename},...e.sourceMediaType&&{sourceMediaType:e.sourceMediaType},...e.attachmentType&&{attachmentType:e.attachmentType},...e.dedupKey&&{dedupKey:e.dedupKey}}}}}var XG=new np;function Dte(e){return KI(e,{skipInvalid:!0,noRefs:!0,sortKeys:!0})}function YI(e){return ZI(e)}var eJ=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,tJ=r.record(r.string(),r.unknown());async function QI(e,t){let n=await t.getEntity({entityType:"image",id:e},oa);if(!n)return;return{url:n.content,alt:n.metadata.alt??"",title:n.metadata.title??"",width:n.metadata.width,height:n.metadata.height}}function XI(e,t){let n=eJ.exec(e.content);if(!n?.[1])return;try{let o=tJ.safeParse(YI(n[1]));if(o.success){let i=o.data[t];return typeof i==="string"?i:void 0}}catch{return}return}function eC(e){return XI(e,"coverImageId")}function rJ(e){return XI(e,"ogImageId")}function op(e,t){return{...e,content:ia(e.content,"coverImageId",t)}}function ip(e,t){return{...e,content:ia(e.content,"ogImageId",t)}}async function nJ(e,t){let n=eC(e);if(!n)return;return QI(n,t)}var oJ=rC();function iJ(e){let t=[],n=oJ.parse(e);return tC(n,"image",(o)=>{t.push({url:o.url,alt:o.alt??"",title:o.title??void 0})}),t}function Zs(e,t,n){if(n===null)return!Object.hasOwn(e,t);return Object.hasOwn(e,t)&&iC(e[t],n)}function sp(e,t){return new Set([...t.getFrontmatterExtensions(e).flatMap((n)=>Object.keys(n.shape)),...t.getGroupings().filter((n)=>n.types.includes(e)).map((n)=>n.field)])}function aJ(e,t,n){if(n.has(t))return ap(e.content).frontmatter[t];return t==="visibility"?e.visibility:e.metadata[t]}function aC(e,t,n){let{visibility:o,coverImageId:i,ogImageId:a,...s}=t,l=o===void 0?e.visibility:nC.parse(o),c=Object.hasOwn(t,"coverImageId")?op(e,typeof i==="string"?i:null):e,u=Object.hasOwn(t,"ogImageId")?ip(c,typeof a==="string"?a:null):c,d={...e.metadata};for(let[g,h]of Object.entries(s))if(h===null)delete d[g];else d[g]=h;let m={...u,visibility:l,metadata:d};for(let[g,h]of Object.entries(s))if(h===null)delete m[g];else m[g]=h;let p=sp(e.entityType,n),f=!1;for(let[g,h]of Object.entries(t)){if(!p.has(g))continue;m.content=ia(m.content,g,h),f=!0}if(f)m.metadata=n.projectMetadata(e.entityType,m.content,d);return m}function sJ(e,t,n){let o=n.getAdapter(e.entityType),i=o.fromMarkdown(e.content),a=o.fromMarkdown(t),s={...e.metadata};for(let l of new Set([...Object.keys(i.metadata??{}),...Object.keys(a.metadata??{})])){let c=a.metadata?.[l];if(iC(i.metadata?.[l],c))continue;if(c===void 0)delete s[l];else s[l]=c}return{...e,...a,id:e.id,entityType:e.entityType,created:e.created,updated:e.updated,contentHash:e.contentHash,content:t,metadata:s,visibility:Gs(t)??e.visibility}}var lJ=new Set(["visibility","coverImageId","ogImageId"]),cJ=r.record(r.string(),r.unknown());function uJ(e,t,n,o){let i=t.fields;if(!i)return;let a=n.getEffectiveFrontmatterSchema(e.entityType);if(!a)return;let s=sp(e.entityType,n),l=Object.keys(i).filter((g)=>s.has(g)),c;try{if(c=aC(e,i,n),l.length>0){let g=n.validateEntity(e.entityType,c),h=o.serializeEntity(g),v=ap(h).frontmatter,x=o.deserializeEntity(h,e.entityType).metadata??{};for(let S of l){let y=i[S];if(!Zs(v,S,y)||!Zs(x,S,y))return{success:!1,error:`The requested ${S} value would not survive frontmatter persistence.`}}}}catch(g){return{success:!1,error:ke(g,"Invalid field update")}}let u=Object.keys(i).filter((g)=>!s.has(g)&&!lJ.has(g)&&(g in a.shape));if(u.length===0)return;let d=n.getAdapter(e.entityType),m;try{c=n.validateEntity(e.entityType,c),m=d.extractMetadata(c)}catch{return}let p=[],f=[];for(let g of u){let h=i[g];if(Object.hasOwn(m,g)){if(!Zs(m,g,h))p.push(g)}else if(h!==null||!Object.hasOwn(e.metadata,g))f.push(g)}if(f.length>0){let g;try{g=d.parseFrontMatter(d.toMarkdown(c),cJ)}catch{if(p.length===0)return}if(g){for(let h of f)if(!Zs(g,h,i[h]))p.push(h)}}if(p.length===0)return;return{success:!1,error:`${e.entityType} does not persist ${p.join(", ")} through 'fields'. The update would report success without changing anything. Provide full markdown with frontmatter via 'content' instead.`}}function dJ(e,t,n){if(t.content===void 0)return;let o=t.content.trim(),i=n.getEffectiveFrontmatterSchema(e);if(!i)return;if(!o)return{success:!1,error:"Full content replacement cannot be empty for this entity type. Use 'fields' for partial updates."};try{n.getAdapter(e).parseFrontMatter(t.content,i)}catch{return{success:!1,error:"Invalid content replacement for this entity type. Provide full markdown with valid frontmatter, or use 'fields' for partial updates."}}return}function pJ(e,t,n){if(!t.fields||!("coverImageId"in t.fields))return;let o=t.fields.coverImageId;if(o!==null&&o!==void 0&&typeof o!=="string")return{success:!1,error:"coverImageId must be a string or null"};if(o==="__PENDING__"||typeof o==="string"&&o.startsWith("upload-"))return{success:!1,error:"coverImageId must reference an existing image id or be null"};if(n.getAdapter(e).supportsCoverImage)return;return{success:!1,error:`Entity type '${e}' doesn't support cover images`}}function mJ(e,t,n){if(t.fields&&"status"in t.fields)return t.fields.status;if(t.content!==void 0){let o=n.getEffectiveFrontmatterSchema(e.entityType);if(!o)return e.metadata.status;try{return n.getAdapter(e.entityType).parseFrontMatter(t.content,o).status}catch{return e.metadata.status}}return e.metadata.status}function sC(e,t,n){let o=sp(e.entityType,n);if(t.fields)return Object.entries(t.fields).map(([l,c])=>{let u=aJ(e,l,o);if(!o.has(l))return`${l}: ${String(u??"(empty)")} \u2192 ${String(c)}`;let d=n.getEffectiveFrontmatterSchema(e.entityType)?.shape[l],m=d!==void 0&&r.safeParse(d,u).success,p=u===void 0?"(absent)":`${JSON.stringify(u)}${m?"":" (invalid existing value)"}`,f=c===null?"(removed)":JSON.stringify(c);return`${l}: ${p} \u2192 ${f}`}).join(`
172
+ `);let i=e.content.split(`
173
+ `),a=(t.content??"").split(`
174
+ `),s=tp(i,a,{timeout:100});if(!s)return"Full content replacement (line diff omitted: comparison exceeded its time limit).";return s.filter((l)=>l.added||l.removed).flatMap((l)=>l.value.map((c)=>`${l.added?"+":"-"} ${c}`)).join(`
175
+ `)}function lC(e,t,n,o){return uJ(e,t,n,o)??dJ(e.entityType,t,n)??pJ(e.entityType,t,n)}function cC(e,t,n){return oC(e.entityType,e.metadata.status,mJ(e,t,n),n)==="non-publish"?"update":"publish"}function uC(e,t,n){return t.content!==void 0?sJ(e,t.content,n):aC(e,t.fields??{},n)}function tn(e){return{success:!1,error:e}}function gJ(e,t){if(e.edits!==void 0&&(e.content!==void 0||e.fields!==void 0))return tn("Provide only one of 'edits', 'content', or 'fields'.");if(e.confirmed&&e.contentHash&&t.contentHash!==e.contentHash)return tn("Entity was modified since you reviewed the changes. Please try again.");let n=e.edits!==void 0?{content:zI(t.content,e.edits)}:RI({...e.fields!==void 0?{fields:e.fields}:{},...e.content!==void 0?{content:e.content}:{}});if(n.content!==void 0&&n.fields!==void 0)return tn("Provide either 'content' or 'fields', not both");if(!n.content&&!n.fields)return tn("Provide 'content' (full replacement) or 'fields' (partial update)");return n}function dC(e){let{entityService:t,logger:n,entityRegistry:o}=e,i=en({label:"update",requestNoun:"the update"}),a=(c,u)=>{if(!c.confirmed||!c.confirmationToken||c.edits!==void 0||c.fields!==void 0||c.content?.trim())return{input:c,replayed:!1};let d=Xd.safeParse(i.takePending(c.confirmationToken));if(!d.success||d.data.entityType!==u.entityType||d.data.id!==u.id)return tn("No pending update confirmation found for this entity. Please request the update again.");return{input:d.data,replayed:!0}},s=async(c,u,d,m,p)=>{if(!m){let g=i.validateConfirmed(c.confirmationToken,c);if(g)return g}let f=uC(u,d,o);if(f.visibility!==u.visibility&&!Bs(p.userPermissionLevel,f.visibility))return tn(`Cannot set entity visibility to "${f.visibility}" \u2014 caller permission "${p.userPermissionLevel??"public"}" is not allowed to write at that level.`);try{let g=$o(p);if((await t.updateEntity({entity:f,options:{expectedContentHash:u.contentHash,...g?{eventContext:g}:{}}})).skipReason==="content-conflict")return tn("Entity was modified before the update could be saved. Please request and confirm the update again.")}catch(g){return tn(ke(g,"Failed to update entity"))}return{success:!0,data:{updated:u.id}}},l=(c,u,d)=>{let{fields:m,content:p,...f}=c;return{needsConfirmation:!0,toolName:"system_update",summary:`Update "${Fs(u)}"?`,completionSummary:`Updated ${EI(u.entityType)}.`,preview:sC(u,d,o),args:i.buildArgs((g)=>({...f,...c.edits!==void 0?{edits:c.edits}:d,id:u.id,confirmed:!0,confirmationToken:g,contentHash:u.contentHash}))}};return Or("update","Update an entity's fields or content. For small content changes, fetch the entity and use edits with exact oldText/newText pairs instead of regenerating the whole document. Use only one of fields, content, or edits. Requires confirmation; call this tool without confirmed to request that confirmation instead of asking for plain-text approval. For direct requests that provide exact IDs to set an existing image as an entity cover, call this tool on the target entity with fields.coverImageId set to the image ID; do not stop after lookup.",Xd,async(c,u)=>{let d=await Nr(t,c.entityType,c.id,n,void 0,Wt(u.userPermissionLevel));if(!d.ok)return tn(d.error);let{entity:m}=d,p=a(c,m);if("success"in p)return p;let{input:f,replayed:g}=p,h=gJ(f,m);if("success"in h)return h;let v=lC(m,h,o,t);if(v)return v;let x=jr(e,f.entityType,cC(m,h,o),u);if(x)return x;return f.confirmed?s(f,m,h,g,u):l(f,m,h)},{visibility:"trusted",sideEffects:"writes"})}function pC(e){return[jI(e),NI(e),DI(e),dC(e)]}function Ks(e){if(e.interfaceType!==mt)return;if(e.userPermissionLevel!=="public"||e.isAnchor)throw Error("Guest execution denied")}var fJ=0.5,lp=(e)=>e==="public"?{publishedOnly:!0}:{};function mC(e){let{entityService:t,logger:n}=e;return[Sn("system","search","Search entities using semantic search. For broad search, make one system_search call with scope.kind all. Use scope.kind type only when the user asks for a specific entity type. Applies a default minScore of 0.5 to reduce weak matches; lower minScore only for exploratory or loose recall. Search results include each matched entity's content. When relevant results already contain the complete evidence needed, answer from those results instead of redundantly listing or getting the same entities. Search results are candidates; do not present weak or unrelated candidates as exact matches.",vI,async(o,i)=>{Ks(i);let a=Wt(i.userPermissionLevel);return{success:!0,data:{results:(await t.search({query:o.query,options:{limit:o.limit??e.searchLimit,...o.scope.kind==="type"&&{types:[o.scope.entityType]},minScore:o.minScore??fJ,...o.includeUngenerated!==void 0&&{includeUngenerated:o.includeUngenerated},visibilityScope:a,...lp(a)}})).map((s)=>{let l=ep(s.entity,e.entityRegistry);return{...s,entity:l,...l!==s.entity?{excerpt:l.content}:{}}})}}},{visibility:"public",sideEffects:"none",cli:{name:"search"}}),Sn("system","get","Retrieve a specific entity by type and identifier (ID, slug, or title). If retrieval fails, report the entity as not found rather than describing related generation work as pending.",bI,async(o,i)=>{if(Ks(i),!t.getEntityTypes().includes(o.entityType))return{success:!1,error:`Unknown entity type: ${o.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let a=Wt(i.userPermissionLevel),s=await Nr(t,o.entityType,o.id,n,void 0,a,lp(a));if(!s.ok)return{success:!1,error:s.error};return{success:!0,data:{entity:ep(s.entity,e.entityRegistry)}}},{visibility:"public",sideEffects:"none",cli:{name:"get"}}),Sn("system","list","List entities by a known entity type. Returns metadata only \u2014 use system_get for full content. Use system_search, not system_list, for broad or vague lookup requests. Use system_list to inspect metadata dates such as publishedAt when the user asks for the latest item of a known type, such as latest blog post.",_I,async(o,i)=>{if(Ks(i),!t.getEntityTypes().includes(o.entityType))return{success:!1,error:`Unknown entity type: ${o.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let a=Wt(i.userPermissionLevel),s={visibilityScope:a};if(o.status&&o.status!=="any")s.metadata={status:o.status};let{defaultSort:l}=e.entityRegistry.getEntityTypeConfig(o.entityType),u=(await t.listEntities({entityType:o.entityType,options:{limit:o.limit??20,filter:s,...lp(a),...l?{sortFields:l}:{}}})).map(({content:d,contentHash:m,...p})=>p);return{success:!0,data:{entities:u,count:u.length}}},{visibility:"public",sideEffects:"none",cli:{name:"list"}})]}function gC(e){let{entityService:t}=e;return[Sn("system","insights",`Get aggregate content insights and analytics only. For a general overview of actual content, use system_list instead. Available types: ${e.insights.getTypes().join(", ")}.`,II,async(n,o)=>{let i=Wt(o.userPermissionLevel);return{success:!0,data:await e.insights.get(n.type,t,i)}},{visibility:"public",sideEffects:"none"})]}function fC(e){let{jobs:t}=e;return[Or("job_status","Inspect runtime job status for ready checks only when the prior operation created a job, or for status disputes. With a known batch ID, pass batchId. Without an ID, call this tool with no arguments to list active jobs and batches; do not ask the user for an ID first. Do not argue from the transcript alone.",TI,async(n)=>{if(n.batchId){let a=await t.getBatchStatus(n.batchId);if(!a)return{success:!1,error:`No batch found with ID: ${n.batchId}`};let s=a.totalOperations>0?Math.round(a.completedOperations/a.totalOperations*100):0;return{success:!0,data:{batchId:n.batchId,status:a.status,progress:{total:a.totalOperations,completed:a.completedOperations,failed:a.failedOperations,percentComplete:s},currentOperation:a.currentOperation,errors:a.errors}}}let o=await t.getActiveJobs(n.jobTypes),i=await t.getActiveBatches();return{success:!0,data:{summary:{activeJobs:o.length,activeBatches:i.length},jobs:o.map((a)=>({id:a.id,type:a.type,status:a.status,priority:a.priority,retryCount:a.retryCount,createdAt:new Date(a.createdAt).toISOString(),startedAt:a.startedAt?new Date(a.startedAt).toISOString():null})),batches:i.map((a)=>({batchId:a.batchId,status:a.status.status,totalOperations:a.status.totalOperations,completedOperations:a.status.completedOperations,failedOperations:a.status.failedOperations,currentOperation:a.status.currentOperation,pluginId:a.metadata.metadata.pluginId,errors:a.status.errors}))}}},{visibility:"public",sideEffects:"none"})]}function hJ(e){let{entityCounts:t,daemons:n,endpoints:o,interactions:i,...a}=e;return a}function hC(e){return[Sn("system","status","Get system status including model, version, interfaces, and tools",r.object({}),async()=>({success:!0,data:hJ(await e.getAppInfo())}),{visibility:"public",sideEffects:"none",cli:{name:"status"}})]}function yC(e){return[...mC(e),...fC(e),...hC(e),...pC(e),...gC(e)]}function vC(e){return[{uri:"entity://types",name:"Entity Types",description:"List of registered entity types",mimeType:"text/plain",handler:async()=>({contents:[{uri:"entity://types",mimeType:"text/plain",text:e.entityService.getEntityTypes().join(`
176
+ `)}]})},{uri:"brain://identity",name:"Brain Identity",description:"Brain character \u2014 name, role, purpose, values",mimeType:"application/json",handler:async()=>({contents:[{uri:"brain://identity",mimeType:"application/json",text:JSON.stringify(e.getIdentity(),null,2)}]})},{uri:"brain://profile",name:"Anchor Profile",description:"Brain owner profile \u2014 name, bio, expertise",mimeType:"application/json",handler:async()=>({contents:[{uri:"brain://profile",mimeType:"application/json",text:JSON.stringify(e.getProfile(),null,2)}]})},{uri:"brain://status",name:"Brain Status",description:"System status \u2014 version, model, interfaces, tools",mimeType:"application/json",handler:async()=>({contents:[{uri:"brain://status",mimeType:"application/json",text:JSON.stringify(await e.getAppInfo(),null,2)}]})}]}function bC(e){let{entityService:t}=e;return[{name:"entity-list",uriTemplate:"entity://{type}",description:"List entities of a given type",mimeType:"application/json",list:async()=>t.getEntityTypes().map((o)=>({uri:`entity://${o}`,name:`${o} entities`})),complete:{type:async()=>t.getEntityTypes()},handler:async({type:n})=>{let o=t.getEntityTypes();if(!o.includes(n))throw Error(`Unknown entity type: ${n}. Available: ${o.join(", ")}`);let a=(await t.listEntities({entityType:n})).map((s)=>({id:s.id,entityType:s.entityType,...s.metadata,updated:s.updated}));return{contents:[{uri:`entity://${n}`,mimeType:"application/json",text:JSON.stringify(a,null,2)}]}}},{name:"entity-detail",uriTemplate:"entity://{type}/{id}",description:"Read a single entity by type and ID",mimeType:"text/markdown",complete:{type:async(n)=>{let o=t.getEntityTypes();return n?o.filter((i)=>i.startsWith(n)):o},id:async()=>[]},handler:async({type:n,id:o})=>{let i=await t.getEntity({entityType:n,id:o});if(!i)throw Error(`Entity not found: ${n}/${o}`);return{contents:[{uri:`entity://${n}/${o}`,mimeType:"text/markdown",text:i.content}]}}}]}function _C(e){return[{name:"create",description:"Create new content of any type",args:{type:{description:"Entity type (e.g. post, deck, note)",required:!0},topic:{description:"Topic or title for the content"}},handler:async({topic:n,type:o})=>({messages:[{role:"user",content:{type:"text",text:n?`Create a new ${o} about: ${n}`:`Create a new ${o}. Ask me what it should be about.`}}]})},{name:"generate",description:"AI-generate content with a prompt",args:{type:{description:`Entity type (${(()=>e.entityService.getEntityTypes().join(", "))()})`,required:!0},topic:{description:"What to generate",required:!0}},handler:async({type:n,topic:o})=>({messages:[{role:"user",content:{type:"text",text:`Generate a ${n} about: ${o}`}}]})},{name:"review",description:"Review and improve existing content",args:{type:{description:"Entity type",required:!0},id:{description:"Entity ID or slug",required:!0}},handler:async({type:n,id:o})=>({messages:[{role:"user",content:{type:"text",text:`Review my ${n} "${o}". Read it first, then give me specific feedback on structure, clarity, and impact. Suggest concrete improvements.`}}]})},{name:"publish",description:"Publish content \u2014 preview, confirm, and publish",args:{type:{description:"Entity type",required:!0},id:{description:"Entity ID or slug",required:!0}},handler:async({type:n,id:o})=>({messages:[{role:"user",content:{type:"text",text:`I want to publish my ${n} "${o}". Show me a preview first, then publish it.`}}]})},{name:"brainstorm",description:"Brainstorm ideas using brain context and expertise",args:{topic:{description:"Topic to brainstorm about",required:!0}},handler:async({topic:n})=>({messages:[{role:"user",content:{type:"text",text:`Let's brainstorm about: ${n}. Use my existing content and expertise as context. Give me fresh angles and concrete ideas.`}}]})}]}function SC(e){let t=e.entityService.getEntityTypes(),n=t.map((o)=>`- ${o}: ${e.entityRegistry.getAdapter(o).purpose}`);return["## Entity CRUD","","Use these system tools for ALL entity operations:","","Treat explicit verbs such as save, create, capture, remember, import, add/connect an agent, approve/archive an agent, update, delete, generate, publish, or sync as mutation requests. Entity-specific instructions may require proactively recording the user's request itself for demand or workflow tracking; follow those instructions even when the user did not use a separate save/create verb. Ordinary status questions like 'what is the status', 'is it ready', 'did that finish', or 'what happened' are not capture requests; answer them by using the relevant status/read tool for the prior operation. Never call system_create for a status follow-up.","",`- **system_create**: Create an entity from existing/concrete material. Requires confirmation before persisting; call system_create without \`confirmed\` to request that confirmation, and never pass \`confirmed: true\` on the initial user request. Use the typed \`visibility\` field instead of rewriting exact source text: omit it for public content, use \`shared\` for team/collaborator content, and use \`restricted\` for private/admin-only content. Public callers may write only public content, Trusted callers public or shared, and Admin callers all three levels. If the user only says 'not public' without clarifying team/shared versus private/admin-only, ask which scope they mean. Required \`source\` union: \`{ kind: "text", content }\` stores exact/direct content; \`{ kind: "url", url }\` creates URL/domain-backed records such as links (preserve bare domains as bare domains); \`{ kind: "upload", upload, transform: "extract-markdown" }\` imports extractable upload bytes as a markdown note; \`{ kind: "upload", upload, transform: "preserve" }\` preserves raw uploaded bytes as their durable file entity; \`{ kind: "prior-response", messageId? }\` saves a previous assistant answer/summary by reference without copying or paraphrasing it. If a direct save request includes the content in the same message, that content is sufficient, even if it is a short sentence or fragment after a colon or embedded in the request phrase (for example, "Save this memo about the launch timeline"); call system_create instead of asking the user to paste it again. If the immediate context is an assistant summary/answer about an upload and the user asks to save it/that/this/summary, create a note with \`source.kind: "prior-response"\`; do this even when the prior answer says there was limited readable content. Do not ask whether they meant the summary or the file after you just summarized/answered about the upload: save the visible prior response as a note. Do not treat a bare upload receipt like "I got filename. What would you like me to do?" as a summary/answer; if the user then says "save it", preserve the latest uploaded file itself with upload \`preserve\` (image uploads as entityType image, PDFs/documents as their file entity type). Only use \`source.kind: "upload"\` when the runtime supplies an actual upload reference/attachment; if the message contains a pasted uploaded-file transcript with readable content (for example, \`User uploaded a file "name.md": ...\`), save the visible transcript content as \`source.kind: "text"\`. Only use upload \`preserve\` otherwise when they explicitly want to save the uploaded file/document itself. Use system_generate, not system_create, for AI generation, generated images, cover images, and source-derived artifacts. Available entity types: ${t.join(", ")}.`,'- **system_generate**: Generate a new durable entity or deterministic artifact. Requires confirmation before queueing generation; call system_generate without `confirmed` to request that confirmation, and never pass `confirmed: true` on the initial user request. When the user asks you to create, write, draft, or generate new durable content and has not supplied final exact content to store, call system_generate instead of drafting the content in chat or asking for separate prose approval first. An underspecified generation request still supplies a usable prompt: preserve the user\'s wording and call system_generate rather than stopping to ask what details to highlight. If generation depends on an existing source entity (for example, a newsletter from a blog post), resolve the source with read/search/list tools first unless the user gives an exact entity id in quotes, then call system_generate with `operation.kind: "prompt-from-source"` in the same turn when a clear source is found. If you identify the latest source entity, do not stop after saying you found it or can generate from it; call system_generate immediately. If no existing durable source entity is resolved, use `operation.kind: "prompt"` in the same turn, including after an optional search returns no source; never invent source IDs, use upload IDs/filenames as entity refs, use profile/brain-character as a generic source, or create placeholder source refs. For broad topical prompts like \'about AI\' or \'about continuous learning\', use `operation.kind: "prompt"`. If the user asks for the latest published/blog source, use system_list for that entity type (for blog posts, entityType post) to inspect publishedAt dates; do not rely on semantic search result order. Choose the newest matching candidate by publishedAt (not updated/created order) and proceed with system_generate rather than asking for separate prose approval; do not say \'if that is the one you mean\' when a newest dated candidate is visible. Do not say \'I can generate it if you want\' or \'I need to queue it first\'; calling system_generate without `confirmed` is the confirmation request. Required `operation` union: `{ kind: "prompt", entityType, prompt }` generates a new non-image durable entity from a broad prompt with no source; `{ kind: "prompt-from-source", entityType, source: { entityType, entityId }, prompt }` generates from an existing resolved entity, such as a newsletter from a blog post. `{ kind: "standalone-image", prompt }` generates an unattached image; `{ kind: "cover-image", target: { entityType, entityId }, prompt }` generates an image and attaches it to an existing canonical entity as `coverImageId`; `{ kind: "attachment", source: { entityType, entityId }, attachmentType }` renders a deterministic artifact from an existing entity attachment provider. For save/render/regenerate/replace requests for source-derived artifacts, call `system_generate` with `operation.kind: "attachment"` immediately; do not say you can queue it later. Use `replace: true` when the user says regenerate, replace, refresh, or update an existing artifact. For OG/social preview renders, use `attachmentType: "og-image"`; the provider derives the output image and updates `ogImageId`. For deck carousel PDFs use `attachmentType: "carousel"`; for printable post/project PDFs use `attachmentType: "printable"`. If the user asks to attach a generated artifact to another entity, generate the artifact first in the same turn; do not ask whether they mean an existing artifact when the source entity is explicit or given as a quoted id such as deck `distributed-systems-primer`. Update the target only after the real artifact ID exists. To create an entity and a cover image, first create/generate only the entity, then after confirmation and after the real canonical entity ID is known call system_generate with operation.kind cover-image. When the user asks to create/regenerate a cover for an existing entity and search/get resolves a clear target, call system_generate with operation.kind cover-image in the same turn; do not stop after saying you found it. In a single initial request for \'a post with a cover image\', do not also call standalone-image; never guess a future target ID, and do not generate a standalone image as a substitute for a requested cover image.',"- **system_update**: Modify an entity's fields or content. Use `edits` for small content changes: fetch the entity, then send exact oldText/newText pairs, with each oldText matching once in the original Markdown. Put multiple non-overlapping edits in one call. Do not regenerate the whole note for a small change; omit `content` and `fields` when using `edits`. Never replace unchanged content with placeholders or ellipses. Use full `content` only for intentional whole-document replacements. Use `fields` for title, status, coverImageId, ogImageId, and other frontmatter/metadata changes. To remove or clear a cover image, set `fields.coverImageId` to null, not an empty string. Use system_update for coverImageId when an existing image entity id is known; if the user says to set an existing image as a cover, update `coverImageId` even when `ogImageId` already points at that image. To generate a new cover image for an existing entity, use system_generate with operation.kind cover-image. Cover images use `coverImageId`; OG/social previews use `ogImageId`; do not treat them as interchangeable. Requires confirmation before applying changes; call system_update without `confirmed` to request that confirmation, rather than asking for prose approval. For explicit publish requests, use the publishing tool if available instead of changing status with system_update; follow-up pronouns like 'publish it' should target the entity just read or updated in the conversation.","- **system_delete**: Admin-only entity removal. Requires confirmation before deleting. Never pass `confirmed: true` on the initial user request; call without `confirmed` so the confirmation flow can ask an administrator first. If system_delete is not available in the current tool surface, say deletion requires Admin access; do not imply a confirmation flow is available. Protected identity/profile records such as brain-character and anchor-profile cannot be deleted; update them instead.","- **system_get**: Retrieve a specific entity by type and ID/slug/title.","- **system_list**: List entities by type with optional filters. For simple list/show-all/summary requests that name or browse a known type or synonym (for example essays/articles/blog posts => post), use system_list with that entity type instead of semantic search. For 'summarize my blog posts' or similar whole-type summaries, first call system_list for entityType post, then summarize those returned entities. For 'latest' requests, use system_list metadata dates such as publishedAt to choose the newest candidate.","- **system_search**: Semantic search across all entities. Search results include matched entity content; when relevant results already provide the complete evidence needed, answer from them instead of redundantly calling system_list or system_get for those same entities. For each new user question about what they have written, mentioned, discussed, or saved, run a fresh search for that turn instead of answering from prior-turn search results or memory; this includes analysis phrasing such as 'How do I discuss X in my writing?' even if prior turns searched related topics.","","Do not ask for prose confirmation instead of calling the applicable mutating tool; for create, update, delete, generate, publish, sync, and similar state-changing requests, the initial tool call without `confirmed` is how you create the pending confirmation. Never claim a durable create/update/delete change was saved, created, done, or completed unless the relevant tool call succeeded or returned a pending confirmation. If a create/update/delete tool is unavailable, unauthorized, or intentionally not called, say you can't make that durable change from the current context; never say saved/created/done. For an explicit write request from an unauthorized/currently unwritable context, refuse directly; do not call system_status or system_search to check permission or look up related content. Entity type descriptions may mark projection-owned or system-maintained types read-only; refuse mutation requests for those types directly without calling read or write tools, searching for a target, or asking which record to mutate.","","Entity types \u2014 select `entityType` by what the type is for:",...n].join(`
177
+ `)}var Lo="system",yJ=r.object({toolName:r.string(),args:r.unknown(),...xC.partial().shape});function Ys(e,t,n,o,i){for(let a of e)try{t(a)}catch{i.debug(`System ${o} ${n(a)} already registered, skipping`)}}function TC(e,t,n,o){let i=yC(e);Ys(i,(d)=>t.registerTool(Lo,d),(d)=>d.name,"tool",o);let a=n.subscribe(wC.toolExecute(Lo),async(d)=>{let m=yJ.safeParse(d.payload);if(!m.success)return{success:!1,error:"Invalid system tool execute payload"};let{toolName:p,args:f,interfaceType:g,actor:h,conversationId:v,channelId:x,userPermissionLevel:S}=m.data,y=i.find((C)=>C.name===p);if(!y)return{success:!1,error:`System tool not found: ${p}`};let w={interfaceType:g??"system",actor:h??{kind:"service",serviceId:"system"}};if(v)w.conversationId=v;if(x)w.channelId=x;if(S)w.userPermissionLevel=S;return{success:!0,data:await y.handler(f,w)}});o.debug(`Registered ${i.length} system tools`);let s=vC(e);Ys(s,(d)=>t.registerResource(Lo,d),(d)=>d.uri,"resource",o),o.debug(`Registered ${s.length} system resources`);let l=bC(e);Ys(l,(d)=>t.registerResourceTemplate(Lo,d),(d)=>d.uriTemplate,"resource template",o),o.debug(`Registered ${l.length} system resource templates`);let c=_C(e);Ys(c,(d)=>t.registerPrompt(Lo,d),(d)=>d.name,"prompt",o),o.debug(`Registered ${c.length} system prompts`);let u=SC(e);try{t.registerInstructions(Lo,u)}catch{o.debug("System instructions already registered, skipping")}return o.debug("Registered system instructions"),a}function RC(e){let{services:t,jobs:n,insights:o,query:i,getAppInfo:a}=e,s=t.jobQueueService,l=t.logger.child("system"),c=TC({entityService:t.entityService,entityRegistry:t.entityRegistry,jobs:{...n,enqueue:IC(s,"system",!1),enqueueBatch:CC(n,"system"),registerHandler:kC(s,"system")},conversationService:t.conversationService,runtimeUploads:t.runtimeUploadRegistry,attachments:Qs(t.attachmentRegistry),logger:l,query:i,getIdentity:()=>t.identityService.getCharacter(),getProfile:()=>t.profileService.getProfile(),getAppInfo:a,searchLimit:10,insights:o,permissionService:t.permissionService},t.mcpService,t.messageBus,l);t.disposables.push(c)}class cp{scope;closePromise=null;closed=!1;constructor(){this.scope=pe.runSync(Xe.make())}buildLayer(e){this.assertOpen();let t=pe.runSyncExit(Xr.buildWithScope(e,this.scope));if(tt.isFailure(t))throw ir.squash(t.cause);return t.value}addFinalizer(e){this.assertOpen(),pe.runSync(Xe.addFinalizer(this.scope,pe.promise(async()=>{await e()})))}addSyncFinalizer(e){this.assertOpen(),pe.runSync(Xe.addFinalizer(this.scope,pe.sync(()=>{e()})))}async fork(e){if(this.closed)throw Error("Cannot start background work after shell shutdown");await Mr(pe.forkIn(e,this.scope))}close(e=tt.void){if(this.closePromise)return this.closePromise;if(this.closed)return Promise.resolve();return this.closed=!0,this.closePromise=Mr(Xe.close(this.scope,e)),this.closePromise}closeSync(e){if(this.closed)return;this.closed=!0,pe.runSync(Xe.close(this.scope,e))}assertOpen(){if(this.closed)throw Error("Cannot register cleanup after shell shutdown")}}class aa{config;services;lifecycle;bootloader;initialized=!1;lifecycleState="constructed";bootMode;bootPromise=null;shutdownPromise=null;insightsRegistry;bootTime=Date.now();endpointRegistry=new Kd;interactionRegistry=new Yd;httpRouteRegistry=$s.createFresh();jobs;static createFresh(e,t,n){return new aa(ma(e),t,n)}constructor(e,t,n){this.config=e,this.lifecycle=new cp,MC(this,()=>this.httpRouteRegistry.getSnapshot());let o=t?.logger??vr.getInstance(),i=Ds.createFresh(o,this.config,n?.processRole);try{this.services=i.initializeServices(this.lifecycle,t),this.jobs=dI(this.services.batchJobManager,this.services.jobQueueService),this.insightsRegistry=sI(this.services.entityRegistry),this.bootloader=new Vd(this.config,this.services,this.lifecycle,i,n?.processRole,{registerCoreDataSources:()=>Ip(this.services,this.config),finalizeHttpRoutes:()=>{this.httpRouteRegistry.finalize(gI(this.services.pluginManager))},registerSystemCapabilities:()=>RC({services:this.services,jobs:this.jobs,insights:this.insightsRegistry,query:(a,s)=>this.query(a,s),getAppInfo:()=>this.getAppInfo()}),createProjectionInputContext:()=>({entities:this.services.entityService,resolvePrompt:(a,s)=>ga(this.services.entityService,a,s),appInfo:()=>this.getAppInfo(),identityInput:()=>{let a=this.getIdentity(),s=this.getProfile();return AC.parse({brainName:a.name,role:a.role,purpose:a.purpose,values:a.values,profileName:s.name,...s.description!==void 0?{profileDescription:s.description}:{},...s.organization!==void 0?{profileOrganization:s.organization}:{}})}}),createProjectionExecutionContext:()=>({ai:PC(this),logger:this.services.logger.child("ProjectionRuntime")}),...t?.projectionRuntime&&{projectionRuntime:t.projectionRuntime}}),i.wireShell(this.services,this),hI(this.lifecycle,this.services)}catch(a){try{this.lifecycle.closeSync(tt.fail(a))}catch(s){o.error("Failed to roll back Shell service construction",s)}throw a}}getInsightsRegistry(){return this.insightsRegistry}async initialize(e){this.services.logger.debug("Shell.initialize() called");let t=e?.mode;if(this.lifecycleState==="running")return this.services.logger.warn("Shell already initialized"),Promise.resolve();if(this.lifecycleState==="booting"){if(this.bootMode!==t)return Promise.reject(Error(`Shell is already initializing in ${this.bootMode??"normal"} mode; cannot join ${t??"normal"} mode`));return this.bootPromise??Promise.resolve()}if(this.lifecycleState==="closing"||this.lifecycleState==="closed")return Promise.reject(Error("Cannot initialize a closing shell"));if(this.lifecycleState==="failed")return Promise.reject(Error("Cannot initialize a shell after boot failure"));return this.lifecycleState="booting",this.bootMode=t,this.bootPromise=this.boot(e),this.bootPromise}async boot(e){try{if(await this.bootloader.boot(e),this.lifecycleState==="booting"){if(this.lifecycleState="running",this.initialized=!0,e?.mode===void 0)await this.services.messageBus.send({type:Us.shellReady,payload:{timestamp:new Date().toISOString()},sender:"shell",broadcast:!0}),this.services.logger.debug("Emitted shell ready event")}}catch(t){if(this.initialized=!1,this.services.logger.error("Failed to initialize Shell",t),this.lifecycleState!=="closing")this.lifecycleState="failed";try{await this.lifecycle.close(tt.fail(t))}catch(n){this.services.logger.error("Failed to clean up Shell after initialization failure",n)}throw t}}registerTemplates(e,t){this.services.logger.debug("Registering templates",{pluginId:t,count:Object.keys(e).length});for(let[n,o]of Object.entries(e))this.registerTemplate(n,o,t)}shutdown(){return this.shutdownPromise??=this.shutdownShell(),this.shutdownPromise}async shutdownShell(){if(this.services.logger.debug("Shutting down Shell"),this.lifecycleState==="closed")return;let e=this.bootPromise;if(this.lifecycleState="closing",this.initialized=!1,e)try{await e}catch{}await this.lifecycle.close(),this.lifecycleState="closed",this.services.logger.debug("Shell shutdown complete")}async generateContent(e){return this.requireInitialized("Shell content generation"),Cp(this.services,e)}async query(e,t){this.requireInitialized("Shell query");let n=await this.getAppInfo(),o={...t,appInfo:n,timestamp:new Date().toISOString()},{conversationHistory:i,...a}=o;return EC.parse(await this.generateContent({prompt:e,templateName:Yo.KNOWLEDGE_QUERY,...i&&{conversationHistory:i},data:a,interfacePermissionGrant:"public"}))}registerPlugin(e){this.requireInitialized("Plugin registration"),this.services.pluginManager.registerPlugin(e)}isInitialized(){return this.initialized}requireInitialized(e){if(!this.initialized)throw Error(`${e} attempted before initialization`)}getEntityService(){return this.services.entityService}getConversationService(){return this.services.conversationService}getEntityRegistry(){return this.services.entityRegistry}async generateObject(e,t,n){this.requireInitialized("Shell generateObject");let{object:o}=await this.services.aiService.generateObject("You are a helpful assistant. Respond with the requested structured data.",e,t,n);return{object:o}}async judge(e){return this.requireInitialized("Shell judge"),this.services.aiService.judge(e)}getAIService(){return this.services.aiService}generateImage(e,t){return this.services.aiService.generateImage(e,t)}canGenerateImages(){return this.services.aiService.canGenerateImages()}getPluginManager(){return this.services.pluginManager}getContentService(){return this.services.contentService}getRenderService(){return this.services.renderService}getAttachmentRegistry(){return Qs(this.services.attachmentRegistry)}getRuntimeUploadRegistry(){return jC(this.services.runtimeUploadRegistry)}getRuntimeState(){return this.services.runtimeStateService}getRecurringChecks(e){return this.services.recurringCheckService.namespace(e)}isJobQueueWorkerRunning(){return this.services.jobQueueWorker.isWorkerRunning()}getMessageBus(){return this.services.messageBus}getLogger(){return this.services.logger}getJobQueueService(){return this.services.jobQueueService}getMCPService(){return this.services.mcpService}listToolsForPermissionLevel(e){return this.services.mcpService.listToolsForPermissionLevel(e).map(({pluginId:t,tool:n})=>({name:n.name,description:n.description,pluginId:t}))}getPermissionService(){return this.services.permissionService}getAgentService(){return this.services.agentService}registerTools(e,t){for(let n of t)try{this.services.mcpService.registerTool(e,n)}catch(o){this.services.logger.error(`Failed to register tool ${n.name} from ${e}:`,o)}}registerResources(e,t){for(let n of t)try{this.services.mcpService.registerResource(e,n)}catch(o){this.services.logger.error(`Failed to register resource ${n.name} from ${e}:`,o)}}registerResourceTemplate(e,t){this.services.mcpService.registerResourceTemplate(e,t)}registerPrompt(e,t){this.services.mcpService.registerPrompt(e,t)}registerInstructions(e,t){if(this.services.mcpService.registerInstructions(e,t),this.initialized)this.services.agentService.invalidateAgent()}async unregisterPluginCapabilities(e){this.services.mcpService.unregisterPlugin?.(e),this.services.jobQueueService.unregisterPluginHandlers(e),this.endpointRegistry.unregister(e),this.interactionRegistry.unregister(e);for(let n of this.services.templateRegistry.getNames())if(n.startsWith(`${e}:`))this.services.templateRegistry.unregister(n);let t=this.config.evalHandlerRegistry;if(t){for(let n of t.list())if(n.pluginId===e)t.unregister(e,n.handlerId)}this.services.agentService.invalidateAgent(),await this.services.recurringCheckService.unregisterPlugin(e)}getPluginPackageName(e){return this.services.pluginManager.getPluginPackageName(e)}hasPlugin(e){return this.services.pluginManager.hasPlugin(e)}getPluginHttpRouteManifest(){return this.httpRouteRegistry.getManifest()}getPluginApiRoutes(){return this.httpRouteRegistry.getApiRoutes()}getPluginWebRoutes(){return this.httpRouteRegistry.getWebRoutes()}registerDaemon(e,t,n){this.services.daemonRegistry.register(e,t,n)}registerEndpoint(e){this.endpointRegistry.register(e)}listEndpoints(){return this.endpointRegistry.list()}registerInteraction(e){this.interactionRegistry.register(e)}listInteractions(){return this.interactionRegistry.list()}registerTemplate(e,t,n){let o=n?`${n}:${e}`:`shell:${e}`;this.services.templateRegistry.register(o,t),this.services.logger.debug(`Registered template: ${o}`)}getTemplate(e){return this.services.templateRegistry.get(e)}getDataSourceRegistry(){return this.services.dataSourceRegistry}getIdentity(){return this.services.identityService.getCharacter()}getProfile(){return this.services.profileService.getProfile()}getProfileKindRegistry(){return this.services.profileKindRegistry}getChannelRegistry(){return this.services.channelRegistry}getInboxRegistry(){return this.services.inboxRegistry}getInboxFollowUpRegistry(){return this.services.inboxFollowUpRegistry}getOperationalHealthRegistry(){return this.services.operationalHealthRegistry}getAccountSettingsRegistry(){return this.services.accountSettingsRegistry}getDomain(){return this.config.siteBaseUrl}getLocalSiteUrl(){return this.config.localSiteUrl}shouldPreferLocalUrls(){return this.config.preferLocalUrls}getThemeCSS(){return this.config.themeCSS}getSpaces(){return this.config.spaces}getDataDir(){return this.config.dataDir}getGitBrokerSocket(){return this.config.gitBrokerSocket}getGitBrokerCheckout(){return this.config.gitBrokerCheckout}registerEvalHandler(e,t,n){this.config.evalHandlerRegistry?.register(e,t,n)}async getAppInfo(){return bp({config:this.config,services:this.services,bootTime:this.bootTime,endpoints:()=>this.listEndpoints(),interactions:()=>this.listInteractions()})}getRuntimeReadiness(){return wp(this.services)}}var OC={kind:"service",serviceId:"brain-cli"},up=`${OC.kind}:${OC.serviceId}`;var vJ=r.object({provider:r.enum(["hetzner","docker"]).default("hetzner"),serverSize:r.string().default("cx33"),location:r.string().default("fsn1"),domain:r.string().optional(),docker:r.object({enabled:r.boolean().default(!0),image:r.string().optional()}).prefault({}),ports:r.object({default:r.number().default(3333),preview:r.number().default(4321),production:r.number().default(8080)}).prefault({}),cdn:r.object({enabled:r.boolean().default(!1),provider:r.enum(["bunny","none"]).default("none")}).prefault({}),dns:r.object({enabled:r.boolean().default(!1),provider:r.enum(["bunny","none"]).default("none")}).prefault({}),paths:r.object({install:r.string().optional(),data:r.string().optional()}).prefault({})}),DC=r.object({name:r.string().default("brain-app"),version:r.string().default("1.0.0"),database:r.string().optional(),aiApiKey:r.string().optional(),aiImageKey:r.string().optional(),aiModel:r.string().optional(),aiReasoningEffort:Xn.optional(),logLevel:Qn.optional(),logFile:r.string().optional(),profileKind:r.string().trim().min(1).optional(),plugins:r.array(pa).default([]),spaces:r.array(r.string()).default([]),identity:NC.optional(),agentInstructions:r.array(r.string()).optional(),deployment:vJ.prefault({})});async function HC(e,t){await wn({label:"entity",config:e,schema:{assets:UC,entities:zC,projectionDirtyInputs:$C,projectionWaves:LC,projectionIncidents:qC,projectionWaveInputs:FC,projectionWaveRules:BC,projectionRuleMemos:GC},migrationsFolder:xn(import.meta.url,"entity-service"),authTokenEnv:"DATABASE_AUTH_TOKEN",logger:t,afterMigrate:JC})}async function ZC(e,t){await wn({label:"job-queue",config:e,schema:{jobQueue:WC,jobWorkerSessions:VC},migrationsFolder:xn(import.meta.url,"job-queue"),authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",logger:t})}async function XC(e,t){await wn({label:"conversation",config:e,schema:{conversations:KC,messages:YC,summaryTracking:QC},migrationsFolder:xn(import.meta.url,"conversation-service"),authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN",logger:t})}async function e0(e,t){await wn({label:"runtime-state",config:e,schema:{runtimeStateRecords:qe},migrationsFolder:xn(import.meta.url,"runtime-state"),authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN",logger:t})}import{mkdir as dp}from"fs/promises";import{isAbsolute as bJ}from"path";function t0(e=process.env){return{dataDir:e.XDG_DATA_HOME??"./data",cacheDir:e.XDG_CACHE_HOME??"./cache",distDir:"./dist"}}function r0(e=process.env){let t=e.BRAIN_GIT_BROKER_CHECKOUT;if(!t)return;if(!bJ(t))throw Error(`Git broker checkout path must be absolute: ${t}`);return t}function n0(e=process.env){let t=e.BRAIN_GIT_BROKER_SOCKET;if(!t)return;let n=107;if(Buffer.byteLength(t)>n)throw Error(`Git broker socket path is too long for a unix socket (${Buffer.byteLength(t)} > ${n} bytes): ${t}`);return t}function o0(e=process.env){return Cn(t0(e))}async function i0(e=process.env){let t=t0(e);try{await dp(t.dataDir,{recursive:!0}),await dp(t.cacheDir,{recursive:!0}),await dp(t.distDir,{recursive:!0})}catch(n){let o=n instanceof Error&&n.message.includes("EACCES")?`Cannot create data directories \u2014 permission denied. Run from a writable directory or check permissions on ${t.dataDir}`:`Cannot create data directories: ${ke(n)}`;throw Error(o,{cause:n})}return Cn(t)}class pp{logger;migrations;constructor(e,t){this.logger=e,this.migrations=t??{getStandardConfigWithDirectories:()=>i0(),migrateEntities:HC,migrateJobQueue:ZC,migrateConversations:XC,migrateRuntimeState:e0}}async runAllMigrations(e){this.logger.debug("Running database migrations...");let t=await this.migrations.getStandardConfigWithDirectories();if(e?.database)t.database.url=e.database;if(e?.jobQueueDatabase)t.jobQueueDatabase.url=e.jobQueueDatabase;if(e?.conversationDatabase)t.conversationDatabase.url=e.conversationDatabase;if(e?.runtimeStateDatabase)t.runtimeStateDatabase.url=e.runtimeStateDatabase;await this.migrateEntityDatabase(t),await this.migrateJobQueueDatabase(t),await this.migrateConversationDatabase(t),await this.migrateRuntimeStateDatabase(t),this.logger.debug("All database migrations completed successfully")}async migrateEntityDatabase(e){this.logger.debug("Running entity database migrations..."),await this.migrations.migrateEntities({url:e.database.url,...e.database.authToken&&{authToken:e.database.authToken}},this.logger)}async migrateJobQueueDatabase(e){this.logger.debug("Running job queue database migrations..."),await this.migrations.migrateJobQueue({url:e.jobQueueDatabase.url,...e.jobQueueDatabase.authToken&&{authToken:e.jobQueueDatabase.authToken}},this.logger)}async migrateConversationDatabase(e){this.logger.debug("Running conversation database migrations..."),await this.migrations.migrateConversations({url:e.conversationDatabase.url,...e.conversationDatabase.authToken&&{authToken:e.conversationDatabase.authToken}},this.logger)}async migrateRuntimeStateDatabase(e){this.logger.debug("Running runtime state database migrations..."),await this.migrations.migrateRuntimeState({url:e.runtimeStateDatabase.url,...e.runtimeStateDatabase.authToken&&{authToken:e.runtimeStateDatabase.authToken}},this.logger)}}var _J="NODE_ENV";function SJ(){return process.env[_J]}function a0(){return SJ()!=="production"}var wJ="startup-check";function xJ(e){let n={...DC.parse(e??{}),plugins:e?.plugins??[]};if(e?.permissions)n.permissions=e.permissions;if(e?.spaces)n.spaces=e.spaces;if(e?.cliConfig)n.cliConfig=e.cliConfig;if(e?.shellConfig)n.shellConfig=e.shellConfig;return n}function TJ(e,t){let n={plugins:e.plugins??[],...e.shellConfig};return IJ(n),CJ(e,n),kJ(e,n,t),RJ(e,n),EJ(e,n),AJ(e,n),PJ(e,n),MJ(e,n),jJ(e,n),n}function IJ(e){let t=o0();e.database??=t.database,e.jobQueueDatabase??=t.jobQueueDatabase,e.conversationDatabase??=t.conversationDatabase,e.runtimeStateDatabase??=t.runtimeStateDatabase,e.embeddingDatabase??=t.embeddingDatabase,e.embedding??=t.embedding,e.gitBrokerSocket??=n0(),e.gitBrokerCheckout??=r0()}function CJ(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function kJ(e,t,n){let o=n?.mode==="startup-check";if(!e.aiApiKey&&!e.aiImageKey&&!e.aiModel&&!e.aiReasoningEffort&&!o)return;t.ai={...t.ai,...o&&!t.ai?.apiKey&&{apiKey:wJ},...e.aiApiKey&&{apiKey:e.aiApiKey},...e.aiImageKey&&{imageApiKey:e.aiImageKey},...e.aiModel&&{model:e.aiModel},...e.aiReasoningEffort&&{reasoningEffort:e.aiReasoningEffort}}}function RJ(e,t){if(!e.logLevel&&!e.logFile)return;t.logging={level:e.logLevel??"info",format:"text",context:e.name,...e.logFile&&{file:e.logFile}}}function EJ(e,t){let n=e.permissions?.rules??[];t.permissions={...e.permissions,rules:n.some((o)=>o.pattern===up)?n:[{pattern:up,level:"admin"},...n]}}function AJ(e,t){if(e.spaces)t.spaces=e.spaces}function PJ(e,t){if(e.identity)t.identity=e.identity}function MJ(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function jJ(e,t){if(t.name=e.name,t.version=e.version,e.deployment.domain)t.siteBaseUrl=e.deployment.domain;t.localSiteUrl=`http://localhost:${e.deployment.ports.production}`,t.preferLocalUrls=a0()}class gp{shell=null;config;signalScope=null;signalShutdownFiber=null;stopPromise=null;hasCLI=!1;static create(e,t){return new gp(xJ(e),t)}constructor(e,t){if(this.config=e,this.hasCLI=process.argv.slice(2).includes("--cli"),t)this.shell=t}async migrate(){let e=vr.getInstance();await new pp(e).runAllMigrations({database:this.config.shellConfig?.database?.url??this.config.database,jobQueueDatabase:this.config.shellConfig?.jobQueueDatabase?.url,conversationDatabase:this.config.shellConfig?.conversationDatabase?.url,runtimeStateDatabase:this.config.shellConfig?.runtimeStateDatabase?.url})}createShell(e,t){this.shell=aa.createFresh(TJ(this.config,e),void 0,{...t&&{processRole:t}})}async registerCLIInterface(){if(!this.hasCLI)return;let e=this.getShell().getPluginManager(),{CLIInterface:t}=await import("./index-z5pd079j.js"),n=new t(this.config.cliConfig);e.registerPlugin(n)}async initialize(e,t){if(!this.shell){if(!t?.migrationsCompleted)await this.migrate();this.createShell(e,t?.processRole)}await this.registerCLIInterface(),await this.getShell().initialize(e)}async start(){if(this.stopPromise)return;this.setupSignalHandlers()}stop(){return this.stopPromise??=this.stopApp(),this.stopPromise}async stopApp(){await this.closeSignalScope(),await this.shell?.shutdown()}async run(e){let n={debug:Ut.DEBUG,info:Ut.INFO,warn:Ut.WARN,error:Ut.ERROR}[this.config.logLevel??"info"]??Ut.INFO,o=vr.createFresh({level:n,context:this.config.name,useStderr:this.hasCLI});if(this.hasCLI)vr.getInstance().setUseStderr(!0);try{await this.initialize(void 0,e),await this.start(),e?.onRuntimeReady?.(),o.info(`\u2705 ${this.config.name} v${this.config.version} ready`),process.stdin.resume()}catch(i){o.error(`\u274C Failed to start ${this.config.name}:`,i),process.exit(1)}}static async run(e,t,n){await gp.create(e,t).run(n)}setupSignalHandlers(){if(this.signalScope)return;let e=pe.runSync(Xe.make()),t=()=>{this.requestGracefulShutdown("SIGINT")},n=()=>{this.requestGracefulShutdown("SIGTERM")},o=mp(["SIGINT"],t),i=mp(["SIGTERM"],n);pe.runSync(Xe.addFinalizer(e,pe.sync(()=>{i(),o()}))),this.signalScope=e}requestGracefulShutdown(e){if(this.signalShutdownFiber)return;let t=vr.getInstance();t.info(`
178
+ Received ${e}, shutting down gracefully...`);let n=pe.tryPromise({try:()=>this.stop(),catch:(o)=>o}).pipe(pe.match({onFailure:(o)=>{t.error("Error during shutdown:",o),process.exit(1)},onSuccess:()=>{process.exit(0)}}));this.signalShutdownFiber=pe.runFork(n)}async closeSignalScope(){let e=this.signalScope;if(this.signalScope=null,e)await pe.runPromise(Xe.close(e,tt.void))}getShell(){if(!this.shell)throw Error("Shell not initialized. Call initialize() first.");return this.shell}}
179
+ export{Qn as S,Xn as T,nO as U,S6 as V,ce as W,oa as X,BI as Y,HI as Z,Ws as _,KG as $,rp as aa,QG as ba,Vs as ca,XG as da,Dte as ea,eC as fa,rJ as ga,op as ha,ip as ia,nJ as ja,iJ as ka,wJ as la,xJ as ma,TJ as na,gp as oa};
180
+
181
+ //# debugId=8DE25BEDFD29147A64756E2164756E21
182
+ //# sourceMappingURL=index-dc478rm4.js.map