@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.
- package/dist/brain.js +887 -887
- package/dist/chunks/{app-pbkbfz5n.js → app-mh6pm8fq.js} +2 -2
- package/dist/chunks/{index-tjyx7nav.js → index-0gp0br16.js} +2 -2
- package/dist/chunks/index-dc478rm4.js +182 -0
- package/dist/chunks/{index-rgmc3f14.js.map → index-dc478rm4.js.map} +11 -10
- package/dist/chunks/{index-99rxqmha.js → index-z5pd079j.js} +3 -3
- package/dist/chunks/{index-99rxqmha.js.map → index-z5pd079j.js.map} +1 -1
- package/dist/index.js +1 -1
- package/dist/model.js +38 -38
- package/dist/model.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunks/index-rgmc3f14.js +0 -182
- /package/dist/chunks/{app-pbkbfz5n.js.map → app-mh6pm8fq.js.map} +0 -0
- /package/dist/chunks/{index-tjyx7nav.js.map → index-0gp0br16.js.map} +0 -0
|
@@ -1,182 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{pa as CR,qa as DR,ra as zR}from"./index-16rgrexr.js";import{sa as pp}from"./index-48ksf4j5.js";import{$a as xn,$b as vd,$e as Ld,Aa as Do,Ae as KC,Ah as NT,Bf as kT,Bh as nT,Ca as Gx,Cd as WI,Cf as zs,Dd as VI,De as $s,Ee as AI,Fe as Ax,Ff as Ys,Fg as jT,Gf as RT,Hd as Qo,Hg as OT,If as PC,Ih as DT,Jb as tI,Je as jC,Jf as ET,Ka as Jx,Kd as JC,Kf as AT,Kg as vx,Lc as XI,Ld as HC,Lf as PT,Mb as RC,Md as Os,Nb as KT,Nd as iT,Oa as Pd,Ob as Nx,Od as aT,Pa as Ts,Pc as eC,Pd as sT,Qa as zx,Qd as lT,Ra as Ux,Rb as Yx,Rc as UT,Sb as qw,Sd as xC,Ta as $x,Tb as rt,Tc as $T,Td as TC,Te as xp,Ua as NC,Ub as ir,Uc as MI,Ud as IC,Ue as ma,Va as yr,Vb as vT,Vc as nI,Ve as rI,Wb as tt,Wd as mt,We as EC,Xa as qx,Xb as Xe,Xc as rC,Xe as Rx,Ya as Wx,Yb as Ki,Yc as _T,Ye as xT,Zb as de,_a as wn,_b as hs,_c as Qr,_e as ZT,ab as DC,ac as Xr,ae as hx,bb as zC,bg as dI,cb as UC,cc as vn,db as $C,dc as Mx,df as YT,eb as qC,fb as LC,gb as FC,hb as BC,ib as ua,jb as fI,jf as AC,kb as tC,ld as Nr,lf as TT,mb as Wt,mc as bT,mf as IT,nb as Fs,ob as Fd,pb as UI,qb as BI,ub as Bs,ug as sI,uh as qT,va as Md,vg as lI,vh as tT,wg as da,xa as Bx,ya as ar,ye as VC,yh as LT,ze as ZC,zf as CT,zh as rT}from"./index-a0b2j769.js";import{Kh as _s,Mh as SC,Nh as vs,Oh as Kw,Ph as bs,Qh as Yw,Rh as MT,Vh as Sn,Zh as en}from"./index-wymd3tew.js";import{$h as vr,_h as Ut}from"./index-y2qm5f33.js";import{Aj as Hd,Bj as VT,Cj as _C,Di as gt,Fi as os,Li as Zw,Pi as Xx,Qj as uI,Ri as eT,Si as Sx,Tj as kC,Uj as qd,Vi as fs,Xi as Cx,Zi as kx,Zj as pT,bi as Bm,ci as Gm,di as r,ek as ST,fj as bn,hi as ip,ij as Yn,ji as oa,jk as TI,kj as ke,kk as ys,lj as ea,lk as wT,nj as Ix,uj as Es}from"./index-vwrhjcsj.js";import{qk as On,rk as ye,tk as Al}from"./index-6nbmekgz.js";var El=ye(function(ZH,mg){var{defineProperty:Rl,getOwnPropertyDescriptor:bR,getOwnPropertyNames:_R}=Object,SR=Object.prototype.hasOwnProperty,wR=(e,t)=>{for(var n in t)Rl(e,n,{get:t[n],enumerable:!0})},xR=(e,t,n,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of _R(t))if(!SR.call(e,i)&&i!==n)Rl(e,i,{get:()=>t[i],enumerable:!(o=bR(t,i))||o.enumerable})}return e},TR=(e)=>xR(Rl({},"__esModule",{value:!0}),e),dg={};wR(dg,{SYMBOL_FOR_REQ_CONTEXT:()=>pg,getContext:()=>IR});mg.exports=TR(dg);var pg=Symbol.for("@vercel/request-context");function IR(){return globalThis[pg]?.get?.()??{}}});var hg=ye(function(KH,fg){var{defineProperty:Ml,getOwnPropertyDescriptor:kR,getOwnPropertyNames:RR}=Object,ER=Object.prototype.hasOwnProperty,AR=(e,t)=>{for(var n in t)Ml(e,n,{get:t[n],enumerable:!0})},PR=(e,t,n,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of RR(t))if(!ER.call(e,i)&&i!==n)Ml(e,i,{get:()=>t[i],enumerable:!(o=kR(t,i))||o.enumerable})}return e},MR=(e)=>PR(Ml({},"__esModule",{value:!0}),e),gg={};AR(gg,{getVercelOidcToken:()=>NR,getVercelOidcTokenSync:()=>Pl});fg.exports=MR(gg);var jR=El(),OR=CR();async function NR(e){let t="",n;try{t=Pl()}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=Pl()}catch(o){let i=n instanceof Error?n.message:"";if(o instanceof Error)i=`${i}
|
|
3
|
-
${o.message}`;if(i)throw new OR.VercelOidcTokenError(i);throw o}return t}function Pl(){let e=(0,jR.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 Ol=ye(function(YH,_g){var{defineProperty:jl,getOwnPropertyDescriptor:UR,getOwnPropertyNames:$R}=Object,qR=Object.prototype.hasOwnProperty,LR=(e,t)=>{for(var n in t)jl(e,n,{get:t[n],enumerable:!0})},FR=(e,t,n,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of $R(t))if(!qR.call(e,i)&&i!==n)jl(e,i,{get:()=>t[i],enumerable:!(o=UR(t,i))||o.enumerable})}return e},BR=(e)=>FR(jl({},"__esModule",{value:!0}),e),bg={};LR(bg,{AccessTokenMissingError:()=>vg.AccessTokenMissingError,RefreshAccessTokenFailedError:()=>vg.RefreshAccessTokenFailedError,getContext:()=>GR.getContext,getVercelOidcToken:()=>yg.getVercelOidcToken,getVercelOidcTokenSync:()=>yg.getVercelOidcTokenSync,getVercelToken:()=>JR.getVercelToken});_g.exports=BR(bg);var yg=hg(),GR=El(),vg=DR(),JR=zR()});var zl=ye(function(hf){Object.defineProperty(hf,"__esModule",{value:!0});hf.VERSION=void 0;hf.VERSION="1.9.1"});var wf=ye(function(_f){Object.defineProperty(_f,"__esModule",{value:!0});_f.isCompatible=_f._makeCompatibilityCheck=void 0;var lA=zl(),vf=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function bf(e){let t=new Set([e]),n=new Set,o=e.match(vf);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(vf);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)}}_f._makeCompatibilityCheck=bf;_f.isCompatible=bf(lA.VERSION)});var Nn=ye(function(xf){Object.defineProperty(xf,"__esModule",{value:!0});xf.unregisterGlobal=xf.getGlobal=xf.registerGlobal=void 0;var uo=zl(),uA=wf(),dA=uo.VERSION.split(".")[0],bi=Symbol.for(`opentelemetry.js.api.${dA}`),_i=typeof globalThis==="object"?globalThis:typeof self==="object"?self:typeof window==="object"?window:typeof global==="object"?global:{};function pA(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}xf.registerGlobal=pA;function mA(e){var t,n;let o=(t=_i[bi])===null||t===void 0?void 0:t.version;if(!o||!(0,uA.isCompatible)(o))return;return(n=_i[bi])===null||n===void 0?void 0:n[e]}xf.getGlobal=mA;function gA(e,t){t.debug(`@opentelemetry/api: Unregistering a global for ${e} v${uo.VERSION}.`);let n=_i[bi];if(n)delete n[e]}xf.unregisterGlobal=gA});var Rf=ye(function(Cf){Object.defineProperty(Cf,"__esModule",{value:!0});Cf.DiagComponentLogger=void 0;var yA=Nn();class If{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)}}Cf.DiagComponentLogger=If;function Si(e,t,n){let o=(0,yA.getGlobal)("diag");if(!o)return;return o[e](t,...n)}});var Da=ye(function(Ef){Object.defineProperty(Ef,"__esModule",{value:!0});Ef.DiagLogLevel=void 0;var vA;(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"})(vA=Ef.DiagLogLevel||(Ef.DiagLogLevel={}))});var Mf=ye(function(Af){Object.defineProperty(Af,"__esModule",{value:!0});Af.createLogLevelDiagLogger=void 0;var Hr=Da();function bA(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)}}Af.createLogLevelDiagLogger=bA});var Dn=ye(function(Of){Object.defineProperty(Of,"__esModule",{value:!0});Of.DiagAPI=void 0;var _A=Rf(),SA=Mf(),jf=Da(),za=Nn(),wA="diag";class $l{static instance(){if(!this._instance)this._instance=new $l;return this._instance}constructor(){function e(o){return function(...i){let a=(0,za.getGlobal)("diag");if(!a)return;return a[o](...i)}}let t=this,n=(o,i={logLevel:jf.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,za.getGlobal)("diag"),u=(0,SA.createLogLevelDiagLogger)((s=i.logLevel)!==null&&s!==void 0?s:jf.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,za.registerGlobal)("diag",u,t,!0)};t.setLogger=n,t.disable=()=>{(0,za.unregisterGlobal)(wA,t)},t.createComponentLogger=(o)=>new _A.DiagComponentLogger(o),t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}}Of.DiagAPI=$l});var Uf=ye(function(Df){Object.defineProperty(Df,"__esModule",{value:!0});Df.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}}Df.BaggageImpl=po});var Lf=ye(function($f){Object.defineProperty($f,"__esModule",{value:!0});$f.baggageEntryMetadataSymbol=void 0;$f.baggageEntryMetadataSymbol=Symbol("BaggageEntryMetadata")});var ql=ye(function(Ff){Object.defineProperty(Ff,"__esModule",{value:!0});Ff.baggageEntryMetadataFromString=Ff.createBaggage=void 0;var xA=Dn(),TA=Uf(),IA=Lf(),CA=xA.DiagAPI.instance();function kA(e={}){return new TA.BaggageImpl(new Map(Object.entries(e)))}Ff.createBaggage=kA;function RA(e){if(typeof e!=="string")CA.error(`Cannot create baggage metadata from unknown type: ${typeof e}`),e="";return{__TYPE__:IA.baggageEntryMetadataSymbol,toString(){return e}}}Ff.baggageEntryMetadataFromString=RA});var wi=ye(function(Gf){Object.defineProperty(Gf,"__esModule",{value:!0});Gf.ROOT_CONTEXT=Gf.createContextKey=void 0;function AA(e){return Symbol.for(e)}Gf.createContextKey=AA;class Ua{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 Ua(t._currentContext);return i._currentContext.set(n,o),i},t.deleteValue=(n)=>{let o=new Ua(t._currentContext);return o._currentContext.delete(n),o}}}Gf.ROOT_CONTEXT=new Ua});var Zf=ye(function(Wf){Object.defineProperty(Wf,"__esModule",{value:!0});Wf.DiagConsoleLogger=Wf._originalConsoleMethods=void 0;var Ll=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}];Wf._originalConsoleMethods={};if(typeof console<"u"){let e=["error","warn","info","debug","trace","log"];for(let t of e)if(typeof console[t]==="function")Wf._originalConsoleMethods[t]=console[t]}class Hf{constructor(){function e(t){return function(...n){let o=Wf._originalConsoleMethods[t];if(typeof o!=="function")o=Wf._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<Ll.length;t++)this[Ll[t].n]=e(Ll[t].c)}}Wf.DiagConsoleLogger=Hf});var Kl=ye(function(Kf){Object.defineProperty(Kf,"__esModule",{value:!0});Kf.createNoopMeter=Kf.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=Kf.NOOP_OBSERVABLE_GAUGE_METRIC=Kf.NOOP_OBSERVABLE_COUNTER_METRIC=Kf.NOOP_UP_DOWN_COUNTER_METRIC=Kf.NOOP_HISTOGRAM_METRIC=Kf.NOOP_GAUGE_METRIC=Kf.NOOP_COUNTER_METRIC=Kf.NOOP_METER=Kf.NoopObservableUpDownCounterMetric=Kf.NoopObservableGaugeMetric=Kf.NoopObservableCounterMetric=Kf.NoopObservableMetric=Kf.NoopHistogramMetric=Kf.NoopGaugeMetric=Kf.NoopUpDownCounterMetric=Kf.NoopCounterMetric=Kf.NoopMetric=Kf.NoopMeter=void 0;class Fl{constructor(){}createGauge(e,t){return Kf.NOOP_GAUGE_METRIC}createHistogram(e,t){return Kf.NOOP_HISTOGRAM_METRIC}createCounter(e,t){return Kf.NOOP_COUNTER_METRIC}createUpDownCounter(e,t){return Kf.NOOP_UP_DOWN_COUNTER_METRIC}createObservableGauge(e,t){return Kf.NOOP_OBSERVABLE_GAUGE_METRIC}createObservableCounter(e,t){return Kf.NOOP_OBSERVABLE_COUNTER_METRIC}createObservableUpDownCounter(e,t){return Kf.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC}addBatchObservableCallback(e,t){}removeBatchObservableCallback(e){}}Kf.NoopMeter=Fl;class mo{}Kf.NoopMetric=mo;class Bl extends mo{add(e,t){}}Kf.NoopCounterMetric=Bl;class Gl extends mo{add(e,t){}}Kf.NoopUpDownCounterMetric=Gl;class Jl extends mo{record(e,t){}}Kf.NoopGaugeMetric=Jl;class Hl extends mo{record(e,t){}}Kf.NoopHistogramMetric=Hl;class xi{addCallback(e){}removeCallback(e){}}Kf.NoopObservableMetric=xi;class Wl extends xi{}Kf.NoopObservableCounterMetric=Wl;class Vl extends xi{}Kf.NoopObservableGaugeMetric=Vl;class Zl extends xi{}Kf.NoopObservableUpDownCounterMetric=Zl;Kf.NOOP_METER=new Fl;Kf.NOOP_COUNTER_METRIC=new Bl;Kf.NOOP_GAUGE_METRIC=new Jl;Kf.NOOP_HISTOGRAM_METRIC=new Hl;Kf.NOOP_UP_DOWN_COUNTER_METRIC=new Gl;Kf.NOOP_OBSERVABLE_COUNTER_METRIC=new Wl;Kf.NOOP_OBSERVABLE_GAUGE_METRIC=new Vl;Kf.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=new Zl;function MA(){return Kf.NOOP_METER}Kf.createNoopMeter=MA});var sh=ye(function(ah){Object.defineProperty(ah,"__esModule",{value:!0});ah.ValueType=void 0;var BA;(function(e){e[e.INT=0]="INT",e[e.DOUBLE=1]="DOUBLE"})(BA=ah.ValueType||(ah.ValueType={}))});var Ql=ye(function(lh){Object.defineProperty(lh,"__esModule",{value:!0});lh.defaultTextMapSetter=lh.defaultTextMapGetter=void 0;lh.defaultTextMapGetter={get(e,t){if(e==null)return;return e[t]},keys(e){if(e==null)return[];return Object.keys(e)}};lh.defaultTextMapSetter={set(e,t,n){if(e==null)return;e[t]=n}}});var mh=ye(function(dh){Object.defineProperty(dh,"__esModule",{value:!0});dh.NoopContextManager=void 0;var JA=wi();class uh{active(){return JA.ROOT_CONTEXT}with(e,t,n,...o){return t.call(n,...o)}bind(e,t){return t}enable(){return this}disable(){return this}}dh.NoopContextManager=uh});var Ti=ye(function(fh){Object.defineProperty(fh,"__esModule",{value:!0});fh.ContextAPI=void 0;var HA=mh(),Xl=Nn(),gh=Dn(),ec="context",WA=new HA.NoopContextManager;class tc{constructor(){}static getInstance(){if(!this._instance)this._instance=new tc;return this._instance}setGlobalContextManager(e){return(0,Xl.registerGlobal)(ec,e,gh.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,Xl.getGlobal)(ec)||WA}disable(){this._getContextManager().disable(),(0,Xl.unregisterGlobal)(ec,gh.DiagAPI.instance())}}fh.ContextAPI=tc});var nc=ye(function(yh){Object.defineProperty(yh,"__esModule",{value:!0});yh.TraceFlags=void 0;var VA;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(VA=yh.TraceFlags||(yh.TraceFlags={}))});var qa=ye(function(vh){Object.defineProperty(vh,"__esModule",{value:!0});vh.INVALID_SPAN_CONTEXT=vh.INVALID_TRACEID=vh.INVALID_SPANID=void 0;var ZA=nc();vh.INVALID_SPANID="0000000000000000";vh.INVALID_TRACEID="00000000000000000000000000000000";vh.INVALID_SPAN_CONTEXT={traceId:vh.INVALID_TRACEID,spanId:vh.INVALID_SPANID,traceFlags:ZA.TraceFlags.NONE}});var La=ye(function(xh){Object.defineProperty(xh,"__esModule",{value:!0});xh.NonRecordingSpan=void 0;var KA=qa();class wh{constructor(e=KA.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){}}xh.NonRecordingSpan=wh});var ac=ye(function(Ch){Object.defineProperty(Ch,"__esModule",{value:!0});Ch.getSpanContext=Ch.setSpanContext=Ch.deleteSpan=Ch.setSpan=Ch.getActiveSpan=Ch.getSpan=void 0;var YA=wi(),QA=La(),XA=Ti(),oc=(0,YA.createContextKey)("OpenTelemetry Context Key SPAN");function ic(e){return e.getValue(oc)||void 0}Ch.getSpan=ic;function eP(){return ic(XA.ContextAPI.getInstance().active())}Ch.getActiveSpan=eP;function Ih(e,t){return e.setValue(oc,t)}Ch.setSpan=Ih;function tP(e){return e.deleteValue(oc)}Ch.deleteSpan=tP;function rP(e,t){return Ih(e,new QA.NonRecordingSpan(t))}Ch.setSpanContext=rP;function nP(e){var t;return(t=ic(e))===null||t===void 0?void 0:t.spanContext()}Ch.getSpanContext=nP});var Ba=ye(function(Mh){Object.defineProperty(Mh,"__esModule",{value:!0});Mh.wrapSpanContext=Mh.isSpanContextValid=Mh.isValidSpanId=Mh.isValidTraceId=void 0;var Rh=qa(),cP=La(),Fa=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 Eh(e,t){if(typeof e!=="string"||e.length!==t)return!1;let n=0;for(let o=0;o<e.length;o+=4)n+=(Fa[e.charCodeAt(o)]|0)+(Fa[e.charCodeAt(o+1)]|0)+(Fa[e.charCodeAt(o+2)]|0)+(Fa[e.charCodeAt(o+3)]|0);return n===t}function Ah(e){return Eh(e,32)&&e!==Rh.INVALID_TRACEID}Mh.isValidTraceId=Ah;function Ph(e){return Eh(e,16)&&e!==Rh.INVALID_SPANID}Mh.isValidSpanId=Ph;function uP(e){return Ah(e.traceId)&&Ph(e.spanId)}Mh.isSpanContextValid=uP;function dP(e){return new cP.NonRecordingSpan(e)}Mh.wrapSpanContext=dP});var cc=ye(function(Dh){Object.defineProperty(Dh,"__esModule",{value:!0});Dh.NoopTracer=void 0;var fP=Ti(),Oh=ac(),sc=La(),hP=Ba(),lc=fP.ContextAPI.getInstance();class Nh{startSpan(e,t,n=lc.active()){if(Boolean(t===null||t===void 0?void 0:t.root))return new sc.NonRecordingSpan;let i=n&&(0,Oh.getSpanContext)(n);if(yP(i)&&(0,hP.isSpanContextValid)(i))return new sc.NonRecordingSpan(i);else return new sc.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:lc.active(),c=this.startSpan(e,i,l),u=(0,Oh.setSpan)(l,c);return lc.with(u,s,void 0,c)}}Dh.NoopTracer=Nh;function yP(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 uc=ye(function($h){Object.defineProperty($h,"__esModule",{value:!0});$h.ProxyTracer=void 0;var vP=cc(),bP=new vP.NoopTracer;class Uh{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 bP;return this._delegate=e,this._delegate}}$h.ProxyTracer=Uh});var Gh=ye(function(Fh){Object.defineProperty(Fh,"__esModule",{value:!0});Fh.NoopTracerProvider=void 0;var _P=cc();class Lh{getTracer(e,t,n){return new _P.NoopTracer}}Fh.NoopTracerProvider=Lh});var dc=ye(function(Hh){Object.defineProperty(Hh,"__esModule",{value:!0});Hh.ProxyTracerProvider=void 0;var SP=uc(),wP=Gh(),xP=new wP.NoopTracerProvider;class Jh{getTracer(e,t,n){var o;return(o=this.getDelegateTracer(e,t,n))!==null&&o!==void 0?o:new SP.ProxyTracer(this,e,t,n)}getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:xP}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)}}Hh.ProxyTracerProvider=Jh});var Zh=ye(function(Vh){Object.defineProperty(Vh,"__esModule",{value:!0});Vh.SamplingDecision=void 0;var TP;(function(e){e[e.NOT_RECORD=0]="NOT_RECORD",e[e.RECORD=1]="RECORD",e[e.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(TP=Vh.SamplingDecision||(Vh.SamplingDecision={}))});var Yh=ye(function(Kh){Object.defineProperty(Kh,"__esModule",{value:!0});Kh.SpanKind=void 0;var IP;(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"})(IP=Kh.SpanKind||(Kh.SpanKind={}))});var Xh=ye(function(Qh){Object.defineProperty(Qh,"__esModule",{value:!0});Qh.SpanStatusCode=void 0;var CP;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(CP=Qh.SpanStatusCode||(Qh.SpanStatusCode={}))});var ry=ye(function(ey){Object.defineProperty(ey,"__esModule",{value:!0});ey.validateValue=ey.validateKey=void 0;var fc="[_0-9a-z-*/]",kP=`[a-z]${fc}{0,255}`,RP=`[a-z0-9]${fc}{0,240}@[a-z]${fc}{0,13}`,EP=new RegExp(`^(?:${kP}|${RP})$`),AP=/^[ -~]{0,255}[!-~]$/,PP=/,|=/;function MP(e){return EP.test(e)}ey.validateKey=MP;function jP(e){return AP.test(e)&&!PP.test(e)}ey.validateValue=jP});var cy=ye(function(sy){Object.defineProperty(sy,"__esModule",{value:!0});sy.TraceStateImpl=void 0;var ny=ry(),oy=32,NP=512,iy=",",ay="=";class hc{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+ay+this.get(t)),e),[]).join(iy)}_parse(e){if(e.length>NP)return;if(this._internalState=e.split(iy).reduceRight((t,n)=>{let o=n.trim(),i=o.indexOf(ay);if(i!==-1){let a=o.slice(0,i),s=o.slice(i+1,n.length);if((0,ny.validateKey)(a)&&(0,ny.validateValue)(s))t.set(a,s)}return t},new Map),this._internalState.size>oy)this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,oy))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new hc;return e._internalState=new Map(this._internalState),e}}sy.TraceStateImpl=hc});var py=ye(function(uy){Object.defineProperty(uy,"__esModule",{value:!0});uy.createTraceState=void 0;var DP=cy();function zP(e){return new DP.TraceStateImpl(e)}uy.createTraceState=zP});var fy=ye(function(my){Object.defineProperty(my,"__esModule",{value:!0});my.context=void 0;var UP=Ti();my.context=UP.ContextAPI.getInstance()});var vy=ye(function(hy){Object.defineProperty(hy,"__esModule",{value:!0});hy.diag=void 0;var $P=Dn();hy.diag=$P.DiagAPI.instance()});var Sy=ye(function(by){Object.defineProperty(by,"__esModule",{value:!0});by.NOOP_METER_PROVIDER=by.NoopMeterProvider=void 0;var qP=Kl();class yc{getMeter(e,t,n){return qP.NOOP_METER}}by.NoopMeterProvider=yc;by.NOOP_METER_PROVIDER=new yc});var Iy=ye(function(xy){Object.defineProperty(xy,"__esModule",{value:!0});xy.MetricsAPI=void 0;var FP=Sy(),vc=Nn(),wy=Dn(),bc="metrics";class _c{constructor(){}static getInstance(){if(!this._instance)this._instance=new _c;return this._instance}setGlobalMeterProvider(e){return(0,vc.registerGlobal)(bc,e,wy.DiagAPI.instance())}getMeterProvider(){return(0,vc.getGlobal)(bc)||FP.NOOP_METER_PROVIDER}getMeter(e,t,n){return this.getMeterProvider().getMeter(e,t,n)}disable(){(0,vc.unregisterGlobal)(bc,wy.DiagAPI.instance())}}xy.MetricsAPI=_c});var Ry=ye(function(Cy){Object.defineProperty(Cy,"__esModule",{value:!0});Cy.metrics=void 0;var BP=Iy();Cy.metrics=BP.MetricsAPI.getInstance()});var My=ye(function(Ay){Object.defineProperty(Ay,"__esModule",{value:!0});Ay.NoopTextMapPropagator=void 0;class Ey{inject(e,t){}extract(e,t){return e}fields(){return[]}}Ay.NoopTextMapPropagator=Ey});var Dy=ye(function(Oy){Object.defineProperty(Oy,"__esModule",{value:!0});Oy.deleteBaggage=Oy.setBaggage=Oy.getActiveBaggage=Oy.getBaggage=void 0;var GP=Ti(),JP=wi(),Sc=(0,JP.createContextKey)("OpenTelemetry Baggage Key");function jy(e){return e.getValue(Sc)||void 0}Oy.getBaggage=jy;function HP(){return jy(GP.ContextAPI.getInstance().active())}Oy.getActiveBaggage=HP;function WP(e,t){return e.setValue(Sc,t)}Oy.setBaggage=WP;function VP(e){return e.deleteValue(Sc)}Oy.deleteBaggage=VP});var Ly=ye(function($y){Object.defineProperty($y,"__esModule",{value:!0});$y.PropagationAPI=void 0;var wc=Nn(),QP=My(),zy=Ql(),Ga=Dy(),XP=ql(),Uy=Dn(),xc="propagation",eM=new QP.NoopTextMapPropagator;class Tc{constructor(){this.createBaggage=XP.createBaggage,this.getBaggage=Ga.getBaggage,this.getActiveBaggage=Ga.getActiveBaggage,this.setBaggage=Ga.setBaggage,this.deleteBaggage=Ga.deleteBaggage}static getInstance(){if(!this._instance)this._instance=new Tc;return this._instance}setGlobalPropagator(e){return(0,wc.registerGlobal)(xc,e,Uy.DiagAPI.instance())}inject(e,t,n=zy.defaultTextMapSetter){return this._getGlobalPropagator().inject(e,t,n)}extract(e,t,n=zy.defaultTextMapGetter){return this._getGlobalPropagator().extract(e,t,n)}fields(){return this._getGlobalPropagator().fields()}disable(){(0,wc.unregisterGlobal)(xc,Uy.DiagAPI.instance())}_getGlobalPropagator(){return(0,wc.getGlobal)(xc)||eM}}$y.PropagationAPI=Tc});var Gy=ye(function(Fy){Object.defineProperty(Fy,"__esModule",{value:!0});Fy.propagation=void 0;var tM=Ly();Fy.propagation=tM.PropagationAPI.getInstance()});var Ky=ye(function(Vy){Object.defineProperty(Vy,"__esModule",{value:!0});Vy.TraceAPI=void 0;var Ic=Nn(),Jy=dc(),Hy=Ba(),go=ac(),Wy=Dn(),Cc="trace";class kc{constructor(){this._proxyTracerProvider=new Jy.ProxyTracerProvider,this.wrapSpanContext=Hy.wrapSpanContext,this.isSpanContextValid=Hy.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 kc;return this._instance}setGlobalTracerProvider(e){let t=(0,Ic.registerGlobal)(Cc,this._proxyTracerProvider,Wy.DiagAPI.instance());if(t)this._proxyTracerProvider.setDelegate(e);return t}getTracerProvider(){return(0,Ic.getGlobal)(Cc)||this._proxyTracerProvider}getTracer(e,t){return this.getTracerProvider().getTracer(e,t)}disable(){(0,Ic.unregisterGlobal)(Cc,Wy.DiagAPI.instance()),this._proxyTracerProvider=new Jy.ProxyTracerProvider}}Vy.TraceAPI=kc});var Xy=ye(function(Yy){Object.defineProperty(Yy,"__esModule",{value:!0});Yy.trace=void 0;var rM=Ky();Yy.trace=rM.TraceAPI.getInstance()});var Ac=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 nM=ql();Object.defineProperty(Ze,"baggageEntryMetadataFromString",{enumerable:!0,get:function(){return nM.baggageEntryMetadataFromString}});var ev=wi();Object.defineProperty(Ze,"createContextKey",{enumerable:!0,get:function(){return ev.createContextKey}});Object.defineProperty(Ze,"ROOT_CONTEXT",{enumerable:!0,get:function(){return ev.ROOT_CONTEXT}});var oM=Zf();Object.defineProperty(Ze,"DiagConsoleLogger",{enumerable:!0,get:function(){return oM.DiagConsoleLogger}});var iM=Da();Object.defineProperty(Ze,"DiagLogLevel",{enumerable:!0,get:function(){return iM.DiagLogLevel}});var aM=Kl();Object.defineProperty(Ze,"createNoopMeter",{enumerable:!0,get:function(){return aM.createNoopMeter}});var sM=sh();Object.defineProperty(Ze,"ValueType",{enumerable:!0,get:function(){return sM.ValueType}});var tv=Ql();Object.defineProperty(Ze,"defaultTextMapGetter",{enumerable:!0,get:function(){return tv.defaultTextMapGetter}});Object.defineProperty(Ze,"defaultTextMapSetter",{enumerable:!0,get:function(){return tv.defaultTextMapSetter}});var lM=uc();Object.defineProperty(Ze,"ProxyTracer",{enumerable:!0,get:function(){return lM.ProxyTracer}});var cM=dc();Object.defineProperty(Ze,"ProxyTracerProvider",{enumerable:!0,get:function(){return cM.ProxyTracerProvider}});var uM=Zh();Object.defineProperty(Ze,"SamplingDecision",{enumerable:!0,get:function(){return uM.SamplingDecision}});var dM=Yh();Object.defineProperty(Ze,"SpanKind",{enumerable:!0,get:function(){return dM.SpanKind}});var pM=Xh();Object.defineProperty(Ze,"SpanStatusCode",{enumerable:!0,get:function(){return pM.SpanStatusCode}});var mM=nc();Object.defineProperty(Ze,"TraceFlags",{enumerable:!0,get:function(){return mM.TraceFlags}});var gM=py();Object.defineProperty(Ze,"createTraceState",{enumerable:!0,get:function(){return gM.createTraceState}});var Rc=Ba();Object.defineProperty(Ze,"isSpanContextValid",{enumerable:!0,get:function(){return Rc.isSpanContextValid}});Object.defineProperty(Ze,"isValidTraceId",{enumerable:!0,get:function(){return Rc.isValidTraceId}});Object.defineProperty(Ze,"isValidSpanId",{enumerable:!0,get:function(){return Rc.isValidSpanId}});var Ec=qa();Object.defineProperty(Ze,"INVALID_SPANID",{enumerable:!0,get:function(){return Ec.INVALID_SPANID}});Object.defineProperty(Ze,"INVALID_TRACEID",{enumerable:!0,get:function(){return Ec.INVALID_TRACEID}});Object.defineProperty(Ze,"INVALID_SPAN_CONTEXT",{enumerable:!0,get:function(){return Ec.INVALID_SPAN_CONTEXT}});var rv=fy();Object.defineProperty(Ze,"context",{enumerable:!0,get:function(){return rv.context}});var nv=vy();Object.defineProperty(Ze,"diag",{enumerable:!0,get:function(){return nv.diag}});var ov=Ry();Object.defineProperty(Ze,"metrics",{enumerable:!0,get:function(){return ov.metrics}});var iv=Gy();Object.defineProperty(Ze,"propagation",{enumerable:!0,get:function(){return iv.propagation}});var av=Xy();Object.defineProperty(Ze,"trace",{enumerable:!0,get:function(){return av.trace}});Ze.default={context:rv.context,diag:nv.diag,metrics:ov.metrics,propagation:iv.propagation,trace:av.trace}});var is=ye(function($S){Object.defineProperty($S,"__esModule",{value:!0});function zS(){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 US(){let e=zS();if(e.__xstate__)return e.__xstate__;return}function Mz(e){if(typeof window>"u")return;let t=US();if(t)t.register(e)}var jz=(e)=>{if(typeof window>"u")return;let t=US();if(t)t.register(e)};$S.devToolsAdapter=jz;$S.getGlobal=zS;$S.registerService=Mz});var Ao=ye(function(FU){var zz=is();class Pu{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 JS=".",Uz="",HS="",$z="#",Mu="*",WS="xstate.init",qz="xstate.error",as="xstate.stop";function Lz(e,t){return{type:`xstate.after.${e}.${t}`}}function ju(e,t){return{type:`xstate.done.state.${e}`,output:t}}function Fz(e,t){return{type:`xstate.done.actor.${e}`,output:t,actorId:e}}function VS(e,t){return{type:`xstate.error.actor.${e}`,error:t,actorId:e}}function ZS(e){return{type:WS,input:e}}function Pr(e){setTimeout(()=>{throw e})}var Bz=(()=>typeof Symbol==="function"&&Symbol.observable||"@@observable")();function zu(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 zu(n[i],o[i])})}function Uu(e){if(QS(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(hw(e))return e.value;if(typeof e!=="string")return e;let t=Uu(e);return KS(t)}function KS(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 Gz(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 YS(e){if(QS(e))return e;return[e]}function Gi(e){if(e===void 0)return[];return YS(e)}function Ou(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 QS(e){return Array.isArray(e)}function Jz(e){return e.type.startsWith("xstate.error.actor")}function xo(e){return YS(e).map((t)=>{if(typeof t>"u"||typeof t==="string")return{target:t};return t})}function XS(e){if(e===void 0||e===Uz)return;return Gi(e)}function Fi(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 Hz(e,t){return`${t}.${e}`}function ew(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 Wz(e){return[...new Set([...e._nodes.flatMap((t)=>t.ownEvents)])]}function tw(e,t){if(t===e)return!0;if(t===Mu)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 LS(e,t){return`${e.sessionId}.${t}`}var Vz=0;function rw(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 w={source:p,target:f,event:g,delay:h,id:v,startedAt:Date.now()},S=LS(p,v);m._snapshot._scheduledEvents[S]=w;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=LS(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:${Vz++}`,_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=Fi(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:w,id:S}=p[f];u.schedule(g,h,v,w,S)}},_clock:l,_logger:c};return m}FU.executingCustomAction=!1;var $u=1,Ht=function(e){return e[e.NotStarted=0]="NotStarted",e[e.Running=1]="Running",e[e.Stopped=2]="Stopped",e}({}),Zz={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 Pu(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={...Zz,...t},{clock:o,logger:i,parent:a,syncSnapshot:s,id:l,systemId:c,inspect:u}=n;if(this.system=a?a.system:rw(this,{clock:o,logger:i}),u&&!a)this.system.inspect(Fi(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=FU.executingCustomAction;try{FU.executingCustomAction=!0,d.exec(d.info,d.params)}finally{FU.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=Fz(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=Fi(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=Fi(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=ZS(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===as)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:as}),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,VS(this.id,e))}_stopProcedure(){if(this._processingStatus!==Ht.Running)return this;return this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new Pu(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:zz.devToolsAdapter)(this)}toJSON(){return{xstate$$type:$u,id:this.id}}getPersistedSnapshot(e){return this.logic.getPersistedSnapshot(this._snapshot,e)}[Bz](){return this}getSnapshot(){if(!this._snapshot)throw Error("Snapshot can't be read while the actor initializes itself");return this._snapshot}}function Lu(e,...[t]){return new qu(e,t)}var Kz=Lu;function Yz(e,t,n,o,{sendId:i}){let a=typeof i==="function"?i(n,o):i;return[t,{sendId:a},void 0]}function Qz(e,t){e.defer(()=>{e.system.scheduler.cancel(e.self,t.sendId)})}function nw(e){function t(n,o){throw Error("This isn't supposed to be called")}return t.type="xstate.cancel",t.sendId=e,t.resolve=Yz,t.execute=Qz,t}function Xz(e,t,n,o,{id:i,systemId:a,src:s,input:l,syncSnapshot:c}){let u=typeof s==="string"?ew(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=Lu(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[Ln(t,{children:{...t.children,[d]:m}}),{id:i,systemId:a,actorRef:m,src:s,input:p},void 0]}function eU(e,{actorRef:t}){if(!t)return;e.defer(()=>{if(t._processingStatus===Ht.Stopped)return;t.start()})}function ow(...[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=Xz,a.execute=eU,a}function tU(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[Ln(t,{children:l}),s,void 0]}function iw(e,t){let n=t.getSnapshot();if(n&&"children"in n)for(let o of Object.values(n.children))iw(e,o);e.system._unregister(t)}function rU(e,t){if(!t)return;if(iw(e,t),t._processingStatus!==Ht.Running){e.stopChild(t);return}e.defer(()=>{e.stopChild(t)})}function ls(e){function t(n,o){throw Error("This isn't supposed to be called")}return t.type="xstate.stopChild",t.actorRef=e,t.resolve=tU,t.execute=rU,t}var nU=ls;function oU(e,t,{stateValue:n}){if(typeof n==="string"&&Ji(n)){let o=e.machine.getStateNodeById(n);return e._nodes.some((i)=>i===o)}return e.matches(n)}function iU(e){function t(){throw Error("This isn't supposed to be called")}return t.check=oU,t.stateValue=e,t}function aU(e,{context:t,event:n},{guards:o}){return!Ro(o[0],t,n,e)}function sU(e){function t(n,o){throw Error("This isn't supposed to be called")}return t.check=aU,t.guards=[e],t}function lU(e,{context:t,event:n},{guards:o}){return o.every((i)=>Ro(i,t,n,e))}function aw(e){function t(n,o){throw Error("This isn't supposed to be called")}return t.check=lU,t.guards=e,t}function cU(e,{context:t,event:n},{guards:o}){return o.some((i)=>Ro(i,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 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 cs(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 Fu(e){let t=new Set(e),n=lw(t);for(let o of t)if(o.type==="compound"&&(!n.get(o)||!n.get(o).length))FS(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=FS(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 sw(e,t){let n=t.get(e);if(!n)return{};if(e.type==="compound"){let i=n[0];if(i){if(cs(i))return i.key}else return{}}let o={};for(let i of n)o[i.key]=sw(i,t);return o}function lw(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 cw(e,t){let n=Fu(t);return sw(e,lw(n))}function Bu(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)=>Bu(e,n));return t.type==="final"}var Ji=(e)=>e[0]===$z;function dU(e,t){let n=e.transitions.get(t),o=[...e.transitions.keys()].filter((i)=>i!==t&&tw(t,i)).sort((i,a)=>a.length-i.length).flatMap((i)=>e.transitions.get(i));return n?[...n,...o]:o}function pU(e){let t=e.config.after;if(!t)return[];let n=(i)=>{let a=Lz(i,e.id),s=a.type;return e.entry.push(bw(a,{id:s,delay:i})),e.exit.push(nw(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 Gi(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=XS(n.target),i=n.reenter??!1,a=hU(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:Gi(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 mU(e){let t=new Map;if(e.config.on)for(let n of Object.keys(e.config.on)){if(n===HS)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 gU(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?aw([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 fU(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"?[]:Gi(t.actions),eventType:null,reenter:!1,target:n?[n]:[],toJSON:()=>({...o,source:`#${e.id}`,target:n?[`#${n.id}`]:[]})};return o}function hU(e,t){if(t===void 0)return;return t.map((n)=>{if(typeof n!=="string")return n;if(Ji(n))return e.machine.getStateNodeById(n);let o=n[0]===JS;if(o&&!e.parent)return ss(e,n.slice(1));let i=o?e.key+n:n;if(e.parent)try{return ss(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 uw(e){let t=XS(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"?ss(e.parent,n):n)}}function qn(e){return e.type==="history"}function FS(e){let t=dw(e);for(let n of t)for(let o of Eo(n,e))t.add(o);return t}function dw(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(Ji(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 ss(e,t){if(typeof t==="string"&&Ji(t))try{return e.machine.getStateNodeById(t)}catch{}let n=Uu(t).slice(),o=e;while(n.length){let i=n.shift();if(!i.length)break;o=Co(o,i)}return o}function Gu(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=Gu(s,t[a]);return i.concat(l)},[]))}function yU(e,t,n,o){let a=Co(e,t).next(n,o);if(!a||!a.length)return e.next(n,o);return a}function vU(e,t,n,o){let i=Object.keys(t),a=Co(e,i[0]),s=Ju(a,t[i[0]],n,o);if(!s||!s.length)return e.next(n,o);return s}function bU(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=Ju(l,s,n,o);if(c)i.push(...c)}if(!i.length)return e.next(n,o);return i}function Ju(e,t,n,o){if(typeof t==="string")return yU(e,t,n,o);if(Object.keys(t).length===1)return vU(e,t,n,o);return bU(e,t,n,o)}function _U(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 SU(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 pw(e,t,n){let o=new Set;for(let i of e){let a=!1,s=new Set;for(let l of o)if(SU(Nu([i],t,n),Nu([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 wU(e){let[t,...n]=e;for(let o of Eo(t,void 0))if(n.every((i)=>yn(i,o)))return o}function Hu(e,t){if(!e.target)return[];let n=new Set;for(let o of e.target)if(qn(o))if(t[o.id])for(let i of t[o.id])n.add(i);else for(let i of Hu(uw(o),t))n.add(i);else n.add(o);return[...n]}function mw(e,t){let n=Hu(e,t);if(!n)return;if(!e.reenter&&n.every((i)=>i===e.source||yn(i,e.source)))return e.source;let o=wU(n.concat(e.source));if(o)return o;if(e.reenter)return;return e.source.machine.root}function Nu(e,t,n){let o=new Set;for(let i of e)if(i.target?.length){let a=mw(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 xU(e,t){if(e.length!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function TU(e,t,n,o,i){return Du([{target:[...dw(e)],source:e,reenter:!0,actions:[],eventType:null,toJSON:null}],t,n,o,!0,i)}function Du(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=pw(e,c,u),m=t;if(!i)[m,u]=RU(m,o,n,d,c,u,a,n.actionExecutor);m=ko(m,o,n,d.flatMap((f)=>f.actions),a,void 0),m=CU(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&&xU(t._nodes,c))return[m,s];return[Ln(m,{_nodes:p,historyValue:u}),s]}catch(f){throw f}}finally{n.actionExecutor=l}}function IU(e,t,n,o,i){if(o.output===void 0)return;let a=ju(i.id,i.output!==void 0&&i.parent?Ou(i.output,e.context,t,n.self):void 0);return Ou(o.output,e.context,a,n.self)}function CU(e,t,n,o,i,a,s,l){let c=e,u=new Set,d=new Set;if(kU(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(ow(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(ju(g.id,p.output!==void 0?Ou(p.output,c.context,t,n.self):void 0));while(h?.type==="parallel"&&!m.has(h)&&Bu(i,h))m.add(h),a.push(ju(h.id)),v=h,h=h.parent;if(h)continue;c=Ln(c,{status:"done",output:IU(c,t,n,c.machine.root,v)})}}return c}function kU(e,t,n,o){for(let i of e){let a=mw(i,t);for(let l of i.target||[]){if(!qn(l)&&(i.source!==l||i.source!==a||i.reenter))o.add(l),n.add(l);To(l,t,n,o)}let s=Hu(i,t);for(let l of s){let c=Eo(l,a);if(a?.type==="parallel")c.push(a);gw(o,t,n,c,!i.source.parent&&i.reenter?void 0:a)}}}function To(e,t,n,o){if(qn(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)Au(a,e.parent,o,t,n)}else{let i=uw(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)Au(a,e.parent,o,t,n)}else if(e.type==="compound"){let[i]=e.initial.target;if(!qn(i))o.add(i),n.add(i);To(i,t,n,o),Au(i,e,o,t,n)}else if(e.type==="parallel"){for(let i of Io(e).filter((a)=>!qn(a)))if(![...o].some((a)=>yn(a,i))){if(!qn(i))o.add(i),n.add(i);To(i,t,n,o)}}}function gw(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)=>!qn(l)))if(![...e].some((l)=>yn(l,s)))e.add(s),To(s,t,n,e)}}}function Au(e,t,n,o,i){gw(n,o,i,Eo(e,t))}function RU(e,t,n,o,i,a,s,l){let c=e,u=Nu(o,i,a);u.sort((m,p)=>p.order-m.order);let d;for(let m of u)for(let p of _U(m)){let f;if(p.history==="deep")f=(g)=>cs(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)=>ls(p.id))],s,void 0),i.delete(m);return[c,d||a]}function EU(e,t){return e.implementations.actions[t]}function fw(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:EU(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=fw(l,t,n,v,i,a)}return l}function ko(e,t,n,o,i,a){let s=a?[]:void 0,l=fw(e,t,n,o,{internalQueue:i,deferredActorIds:a},s);return s?.forEach(([c,u])=>{c.retryResolve(n,l,u)}),l}function AU(e,t,n,o){if(t.type===Mu)throw Error(`An event cannot have the wildcard type ('${Mu}')`);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===as)return i=Ln(BS(i,t,n),{status:"stopped"}),s([i,[]],t,[]),{snapshot:i,microsteps:a};let l=t;if(l.type!==WS){let m=l,p=Jz(m),f=GS(m,i);if(p&&!f.length)return i=Ln(e,{status:"error",error:m.error}),s([i,[]],m,[]),{snapshot:i,microsteps:a};let g=Du(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?PU(i,l):[],p=m.length?i:void 0;if(!m.length){if(!o.length)break;l=o.shift(),m=GS(l,i)}let f=Du(m,i,n,l,!1,o);i=f[0],c=i!==p,s(f,l,m)}if(i.status!=="active")BS(i,l,n);return{snapshot:i,microsteps:a}}function BS(e,t,n){return ko(e,t,n,Object.values(e.children).map((o)=>ls(o)),[],void 0)}function GS(e,t){return t.machine.getTransitionData(t,e)}function PU(e,t){let n=new Set,o=e._nodes.filter(cs);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 pw(Array.from(n),new Set(e._nodes),e.historyValue)}function MU(e,t){let n=Fu(Gu(e,t));return cw(e,[...n])}function hw(e){return!!e&&typeof e==="object"&&"machine"in e&&"value"in e}var jU=function(t){return zu(t,this.value)},OU=function(t){return this.tags.has(t)},NU=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)},DU=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)}},zU=function(){return this._nodes.reduce((t,n)=>{if(n.meta!==void 0)t[n.id]=n.meta;return t},{})};function yw(e,t){return{status:e.status,output:e.output,error:e.error,machine:t,context:e.context,_nodes:e._nodes,value:cw(t.root,e._nodes),tags:new Set(e._nodes.flatMap((n)=>n.tags)),children:e.children,historyValue:e.historyValue||{},matches:jU,hasTag:OU,can:NU,getMeta:zU,toJSON:DU}}function Ln(e,t={}){return yw({...e,...t},e.machine)}function UU(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 $U(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:vw(s),children:f,historyValue:UU(p.historyValue)}}function vw(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:$u,id:o.id};else{let i=vw(o);if(i!==o)t??=Array.isArray(e)?e.slice():{...e},t[n]=i}}return t??e}function qU(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 LU(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 bw(e,t){if(FU.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=qU,n.execute=LU,n}FU.$$ACTOR_TYPE=$u;FU.Actor=qu;FU.NULL_EVENT=HS;FU.ProcessingStatus=Ht;FU.STATE_DELIMITER=JS;FU.XSTATE_ERROR=qz;FU.XSTATE_STOP=as;FU.and=aw;FU.cancel=nw;FU.cloneMachineSnapshot=Ln;FU.createActor=Lu;FU.createErrorActorEvent=VS;FU.createInitEvent=ZS;FU.createInvokeId=Hz;FU.createMachineSnapshot=yw;FU.createSystem=rw;FU.evaluateGuard=Ro;FU.formatInitialTransition=fU;FU.formatRouteTransitions=gU;FU.formatTransition=hn;FU.formatTransitions=mU;FU.getAllOwnEventDescriptors=Wz;FU.getAllStateNodes=Fu;FU.getCandidates=dU;FU.getDelayedTransitions=pU;FU.getPersistedSnapshot=$U;FU.getProperAncestors=Eo;FU.getStateNodeByPath=ss;FU.getStateNodes=Gu;FU.initialMicrostep=TU;FU.interpret=Kz;FU.isAtomicStateNode=cs;FU.isInFinalState=Bu;FU.isMachineSnapshot=hw;FU.isStateId=Ji;FU.macrostep=AU;FU.mapValues=Gz;FU.matchesEventDescriptor=tw;FU.matchesState=zu;FU.not=sU;FU.or=uU;FU.pathToStateValue=KS;FU.raise=bw;FU.resolveActionsAndContext=ko;FU.resolveReferencedActor=ew;FU.resolveStateValue=MU;FU.spawnChild=ow;FU.stateIn=iU;FU.stop=nU;FU.stopChild=ls;FU.toArray=Gi;FU.toObserver=Fi;FU.toStatePath=Uu;FU.toTransitionConfigArray=xo;FU.transitionNode=Ju});var Iw=ye(function(Tw){Object.defineProperty(Tw,"__esModule",{value:!0});var Wi=Ao();is();function xw(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 Wu=new WeakMap;function G$(e){return{config:e,start:(n,o)=>{let{self:i,system:a,emit:s}=o,l={receivers:void 0,dispose:void 0};Wu.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=Wu.get(i.self);if(o.type===Wi.XSTATE_STOP)return n={...n,status:"stopped",error:void 0},Wu.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 _w="xstate.observable.next",us="xstate.observable.error",ds="xstate.observable.complete";function J$(e){return{config:e,transition:(n,o)=>{if(n.status!=="active")return n;switch(o.type){case _w:return{...n,context:o.data};case us:return{...n,status:"error",error:o.data,input:void 0,_subscription:void 0};case ds:return{...n,status:"done",input:void 0,_subscription:void 0};case Wi.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:_w,data:s})},error:(s)=>{i._relay(o,o,{type:us,data:s})},complete:()=>{i._relay(o,o,{type:ds})}})},getPersistedSnapshot:({_subscription:n,...o})=>o,restoreSnapshot:(n)=>({...n,_subscription:void 0})}}function H$(e){return{config:e,transition:(n,o)=>{if(n.status!=="active")return n;switch(o.type){case us:return{...n,status:"error",error:o.data,input:void 0,_subscription:void 0};case ds:return{...n,status:"done",input:void 0,_subscription:void 0};case Wi.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:us,data:s})},complete:()=>{i._relay(o,o,{type:ds})}})},getPersistedSnapshot:({_subscription:n,...o})=>o,restoreSnapshot:(n)=>({...n,_subscription:void 0})}}var Sw="xstate.promise.resolve",ww="xstate.promise.reject",Hi=new WeakMap;function W$(e){return{config:e,transition:(n,o,i)=>{if(n.status!=="active")return n;switch(o.type){case Sw:{let a=o.data;return{...n,status:"done",output:a,input:void 0}}case ww:return{...n,status:"error",error:o.data,input:void 0};case Wi.XSTATE_STOP:return Hi.get(i.self)?.abort(),Hi.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;Hi.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;Hi.delete(o),i._relay(o,o,{type:Sw,data:c})},(c)=>{if(o.getSnapshot().status!=="active")return;Hi.delete(o),i._relay(o,o,{type:ww,data:c})})},getInitialSnapshot:(n,o)=>({status:"active",output:void 0,error:void 0,input:o}),getPersistedSnapshot:(n)=>n,restoreSnapshot:(n)=>n}}var V$=xw((e)=>{return},void 0);function Z$(){return Wi.createActor(V$)}Tw.createEmptyActor=Z$;Tw.fromCallback=G$;Tw.fromEventObservable=H$;Tw.fromObservable=J$;Tw.fromPromise=W$;Tw.fromTransition=xw});var ps=ye(function(iq){var Po=Ao();function rq(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 nq(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:rq(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 oq(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=nq,t}iq.assign=oq});var kw=ye(function(uq){var je=Ao(),sq=ps(),Cw=new WeakMap;function Mo(e,t,n){let o=Cw.get(e);if(!o)o={[t]:n()},Cw.set(e,o);else if(!(t in o))o[t]=n();return o[t]}var lq={},Vi=(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 Zi{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 Zi(n,{_parent:this,_key:o,_machine:this.machine})):lq,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(Vi),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map((e)=>`#${e.id}`),source:`#${this.id}`,actions:this.initial.actions.map(Vi),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(Vi)})),entry:this.entry.map(Vi),exit:this.exit.map(Vi),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 cq="#";class Vu{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 Zi(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 Vu(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,[sq.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(cq.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 Zi)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}}uq.StateMachine=Vu;uq.StateNode=Zi});var Aw=ye(function(Iq){var Yr=Ao(),mq=ps();function gq(e,t,n,o,{event:i}){let a=typeof i==="function"?i(n,o):i;return[t,{event:a},void 0]}function fq(e,{event:t}){e.defer(()=>e.emit(t))}function Rw(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=gq,t.execute=fq,t}var ms=function(e){return e.Parent="#_parent",e.Internal="#_internal",e}({});function hq(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===ms.Parent)f=e.self._parent;else if(p===ms.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 yq(e,t,n){if(typeof n.to==="string")n.to=t.children[n.to]}function vq(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 gs(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=hq,o.retryResolve=yq,o.execute=vq,o}function Ew(e,t){return gs(ms.Parent,e,t)}function bq(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 gs(e,({event:n})=>n,t)}function _q(e,t,n,o,{collect:i}){let a=[],s=function(c){a.push(c)};return s.assign=(...l)=>{a.push(mq.assign(...l))},s.cancel=(...l)=>{a.push(Yr.cancel(...l))},s.raise=(...l)=>{a.push(Yr.raise(...l))},s.sendTo=(...l)=>{a.push(gs(...l))},s.sendParent=(...l)=>{a.push(Ew(...l))},s.spawnChild=(...l)=>{a.push(Yr.spawnChild(...l))},s.stopChild=(...l)=>{a.push(Yr.stopChild(...l))},s.emit=(...l)=>{a.push(Rw(...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 Sq(e){function t(n,o){throw Error("This isn't supposed to be called")}return t.type="xstate.enqueueActions",t.collect=e,t.resolve=_q,t}function wq(e,t,n,o,{value:i,label:a}){return[t,{value:typeof i==="function"?i(n,o):i,label:a},void 0]}function xq({logger:e},{value:t,label:n}){if(n)e(n,t);else e(t)}function Tq(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=wq,n.execute=xq,n}Iq.SpecialTargets=ms;Iq.emit=Rw;Iq.enqueueActions=Sq;Iq.forwardTo=bq;Iq.log=Tq;Iq.sendParent=Ew;Iq.sendTo=gs});var Dw=ye(function(Nw){Object.defineProperty(Nw,"__esModule",{value:!0});var jo=Iw(),He=Ao(),Zu=kw(),Pw=ps(),hr=Aw();is();function jq(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 Mw(e,t){return new Zu.StateMachine(e,t)}function Oq(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 Nq(e,...[t]){let n=Oo(e);return e.getInitialSnapshot(n,t)}function Dq(e,t,n){let o=Oo(e);return o.self._snapshot=t,e.transition(t,n,o)}function jw({schemas:e,actors:t,actions:n,guards:o,delays:i}){return{assign:Pw.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)=>Mw({...a,schemas:e},{actors:t,actions:n,guards:o,delays:i}),extend:(a)=>jw({schemas:e,actors:t,actions:{...n,...a.actions},guards:{...o,...a.guards},delays:{...i,...a.delays}})}}class Ow{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 zq(e){return new Promise((t,n)=>{e.subscribe({complete:()=>{t(e.getSnapshot().output)},error:n})})}function Uq(e,t,n){let o=[],i=Oo(e);return i.actionExecutor=(s)=>{o.push(s)},[e.transition(t,n,i),o]}function $q(e,...[t]){let n=[],o=Oo(e);return o.actionExecutor=(a)=>{n.push(a)},[e.getInitialSnapshot(o,t),n]}function qq(e,t,n){let o=Oo(e),{microsteps:i}=He.macrostep(t,n,o,[]);return i}function Lq(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 Fq(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 Bq={timeout:1/0};function Gq(e,t,n){let o={...Bq,...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()})}Nw.createEmptyActor=jo.createEmptyActor;Nw.fromCallback=jo.fromCallback;Nw.fromEventObservable=jo.fromEventObservable;Nw.fromObservable=jo.fromObservable;Nw.fromPromise=jo.fromPromise;Nw.fromTransition=jo.fromTransition;Nw.Actor=He.Actor;Nw.__unsafe_getAllOwnEventDescriptors=He.getAllOwnEventDescriptors;Nw.and=He.and;Nw.cancel=He.cancel;Nw.createActor=He.createActor;Nw.getStateNodes=He.getStateNodes;Nw.interpret=He.interpret;Nw.isMachineSnapshot=He.isMachineSnapshot;Nw.matchesState=He.matchesState;Nw.not=He.not;Nw.or=He.or;Nw.pathToStateValue=He.pathToStateValue;Nw.raise=He.raise;Nw.spawnChild=He.spawnChild;Nw.stateIn=He.stateIn;Nw.stop=He.stop;Nw.stopChild=He.stopChild;Nw.toObserver=He.toObserver;Nw.StateMachine=Zu.StateMachine;Nw.StateNode=Zu.StateNode;Nw.assign=Pw.assign;Nw.SpecialTargets=hr.SpecialTargets;Nw.emit=hr.emit;Nw.enqueueActions=hr.enqueueActions;Nw.forwardTo=hr.forwardTo;Nw.log=hr.log;Nw.sendParent=hr.sendParent;Nw.sendTo=hr.sendTo;Nw.SimulatedClock=Ow;Nw.assertEvent=jq;Nw.createMachine=Mw;Nw.getInitialMicrosteps=Lq;Nw.getInitialSnapshot=Nq;Nw.getMicrosteps=qq;Nw.getNextSnapshot=Dq;Nw.getNextTransitions=Fq;Nw.initialTransition=$q;Nw.mapState=Oq;Nw.setup=jw;Nw.toPromise=zq;Nw.transition=Uq;Nw.waitFor=Gq});function nl(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=nl(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 vp(e){let{config:t,services:n,bootTime:o,endpoints:i,interactions:a}=e,[s,l,c,u]=await Promise.all([n.entityService.getEntityCounts(ua("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 bp,readFile as s0}from"fs/promises";var l0=10;async function c0(e="/proc"){let t=null;try{t=(await bp(`${e}/self/fd`)).length}catch{}try{let o=(await bp(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 s0(`${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 _p(e,t,n){return t.status==="fulfilled"?{name:e,status:"healthy",message:n}:{name:e,status:"unhealthy",message:ke(t.reason)}}function u0(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 d0(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 p0(e,t){if(!e||!t)return{name:"job-execution-inventory",status:"degraded",message:"Job execution inventory is unavailable"};let n=nl(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 m0(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 g0(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 f0(e){let t=e.entityService.getProjectionStore(),[n,o,i]=await Promise.all([t.getActiveWave(),t.getUnresolvedProjectionIncidentDiagnostics(l0),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 h0(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 y0(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 Sp(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(ua("runtime readiness database probe")),e.jobQueueService.getDiagnostics(t),Promise.resolve().then(()=>e.jobQueueService.getExecutionRegistrations()),e.daemonRegistry.getStatuses(),(e.readProcessSignals??c0)(),e.projectionRuntimeSupervisor.getDiagnostics(),f0(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=[_p("entity-database",o,"Entity database is accessible"),_p("job-queue-database",i,"Job queue database is accessible"),u0(m),d0(m),p0(m,p),m0(m),c.status==="fulfilled"?g0(h):{name:"projection-circuits",status:"degraded",message:ke(c.reason)},u.status==="fulfilled"?h0(u.value):{name:"projection-waves",status:"degraded",message:ke(u.reason)},s.status==="fulfilled"?y0(f):{name:"daemons",status:"degraded",message:ke(s.reason)}],w=d.status==="fulfilled"?d.value:[{name:"plugin-operational-health",status:"degraded",message:"Plugin operational health is unavailable"}],S=[...v,...w];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 wp(){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 ol=wp(),v0=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 il(){return Cn(ol)}var Qn=r.enum(["debug","info","warn","error"]),Xn=r.enum(["none","low","medium","high","xhigh","max"]),al=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(da).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(),v0).optional(),profileKind:r.string().trim().min(1).optional()});function pa(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}=al.parse({...il(),...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"},sl={ENTITIES:"shell:entities"};var b0=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()}),_0=r.object({slug:r.string()});function S0(e){return e instanceof r.ZodType}function w0(e){if(!e)return;return e.replace(/^https?:\/\//,"").replace(/\/$/,"")}class ga{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=w0(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=b0.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 xp((v,w)=>o.getEntity(v,w),i.templateName,a.basePrompt):await ma(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(!S0(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=_0.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 x0=r.object({entityType:r.string(),query:r.object({id:r.string()})});class fa{entityService;id=sl.ENTITIES;name="Entity DataSource";description="Fetches entity content from the entity service";constructor(e){this.entityService=e}async fetch(e,t,n){let o=x0.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 Tp(e,t){e.dataSourceRegistry.register(new ga(e.aiService,e.entityService,e.templateRegistry,()=>e.identityService.getCharacterContent(),()=>e.profileService.getProfileContent(),t.siteBaseUrl)),e.dataSourceRegistry.register(new fa(e.entityService)),e.logger.debug("Core DataSources registered")}async function Ip(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 em="vercel.ai.error",T0=Symbol.for(em),Cp,kp,ie=class e extends(kp=Error,Cp=T0,kp){constructor({name:t,message:n,cause:o}){super(n);this[Cp]=!0,this.name=t,this.cause=o}static isInstance(t){return e.hasMarker(t,em)}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}},tm="AI_APICallError",rm=`vercel.ai.error.${tm}`,I0=Symbol.for(rm),Rp,Ep,De=class extends(Ep=ie,Rp=I0,Ep){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:tm,message:e,cause:s});this[Rp]=!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,rm)}},nm="AI_EmptyResponseBodyError",om=`vercel.ai.error.${nm}`,C0=Symbol.for(om),Ap,Pp,im=class extends(Pp=ie,Ap=C0,Pp){constructor({message:e="Empty response body"}={}){super({name:nm,message:e});this[Ap]=!0}static isInstance(e){return ie.hasMarker(e,om)}};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 am="AI_InvalidArgumentError",sm=`vercel.ai.error.${am}`,k0=Symbol.for(sm),Mp,jp,eo=class extends(jp=ie,Mp=k0,jp){constructor({message:e,cause:t,argument:n}){super({name:am,message:e,cause:t});this[Mp]=!0,this.argument=n}static isInstance(e){return ie.hasMarker(e,sm)}},lm="AI_InvalidPromptError",cm=`vercel.ai.error.${lm}`,R0=Symbol.for(cm),Op,Np,Ir=class extends(Np=ie,Op=R0,Np){constructor({prompt:e,message:t,cause:n}){super({name:lm,message:`Invalid prompt: ${t}`,cause:n});this[Op]=!0,this.prompt=e}static isInstance(e){return ie.hasMarker(e,cm)}},um="AI_InvalidResponseDataError",dm=`vercel.ai.error.${um}`,E0=Symbol.for(dm),Dp,zp,ya=class extends(zp=ie,Dp=E0,zp){constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:um,message:t});this[Dp]=!0,this.data=e}static isInstance(e){return ie.hasMarker(e,dm)}},pm="AI_JSONParseError",mm=`vercel.ai.error.${pm}`,A0=Symbol.for(mm),Up,$p,kn=class extends($p=ie,Up=A0,$p){constructor({text:e,cause:t}){super({name:pm,message:`JSON parsing failed: Text: ${e}.
|
|
23
|
-
Error message: ${Tr(t)}`,cause:t});this[Up]=!0,this.text=e}static isInstance(e){return ie.hasMarker(e,mm)}},gm="AI_LoadAPIKeyError",fm=`vercel.ai.error.${gm}`,P0=Symbol.for(fm),qp,Lp,Xo=class extends(Lp=ie,qp=P0,Lp){constructor({message:e}){super({name:gm,message:e});this[qp]=!0}static isInstance(e){return ie.hasMarker(e,fm)}},hm="AI_LoadSettingError",ym=`vercel.ai.error.${hm}`,M0=Symbol.for(ym),Fp,Bp,u4=class extends(Bp=ie,Fp=M0,Bp){constructor({message:e}){super({name:hm,message:e});this[Fp]=!0}static isInstance(e){return ie.hasMarker(e,ym)}},vm="AI_NoContentGeneratedError",bm=`vercel.ai.error.${vm}`,j0=Symbol.for(bm),Gp,Jp,d4=class extends(Jp=ie,Gp=j0,Jp){constructor({message:e="No content generated."}={}){super({name:vm,message:e});this[Gp]=!0}static isInstance(e){return ie.hasMarker(e,bm)}},_m="AI_NoSuchModelError",Sm=`vercel.ai.error.${_m}`,O0=Symbol.for(Sm),Hp,Wp,ll=class extends(Wp=ie,Hp=O0,Wp){constructor({errorName:e=_m,modelId:t,modelType:n,message:o=`No such ${n}: ${t}`}){super({name:e,message:o});this[Hp]=!0,this.modelId=t,this.modelType=n}static isInstance(e){return ie.hasMarker(e,Sm)}},wm="AI_TooManyEmbeddingValuesForCallError",xm=`vercel.ai.error.${wm}`,N0=Symbol.for(xm),Vp,Zp,va=class extends(Zp=ie,Vp=N0,Zp){constructor(e){super({name:wm,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[Vp]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return ie.hasMarker(e,xm)}},Tm="AI_TypeValidationError",Im=`vercel.ai.error.${Tm}`,D0=Symbol.for(Im),Kp,Yp,vt=class e extends(Yp=ie,Kp=D0,Yp){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:Tm,message:`${i}: Value: ${JSON.stringify(t)}.
|
|
24
|
-
Error message: ${Tr(n)}`,cause:n});this[Kp]=!0,this.value=t,this.context=o}static isInstance(t){return ie.hasMarker(t,Im)}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})}},Cm="AI_UnsupportedFunctionalityError",km=`vercel.ai.error.${Cm}`,z0=Symbol.for(km),Qp,Xp,We=class extends(Xp=ie,Qp=z0,Xp){constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:Cm,message:t});this[Qp]=!0,this.functionality=e}static isInstance(e){return ie.hasMarker(e,km)}};function ha(e){if(e===null||typeof e==="string"||typeof e==="number"||typeof e==="boolean")return!0;if(Array.isArray(e))return e.every(ha);if(typeof e==="object")return Object.entries(e).every(([t,n])=>typeof t==="string"&&(n===void 0||ha(n)));return!1}function cl(e){return Array.isArray(e)&&e.every(ha)}function ei(e){return e!=null&&typeof e==="object"&&Object.entries(e).every(([t,n])=>typeof t==="string"&&(n===void 0||ha(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 Rm;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Rm||(Rm={}));var ae=$e.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),qr=(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 U0=(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=U0;var $0=dn;function ti(){return $0}var ba=(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=ba({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}),ul=(e)=>e.status==="aborted",dl=(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 Em=(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 qr(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:qr(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:qr(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:qr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Em(n,o)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:qr(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:qr(e)},o=this._parse({data:e,path:n.path,parent:n}),i=await(ri(o)?o:Promise.resolve(o));return Em(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 fl({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 ka.create(this,e)}readonly(){return gi.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var q0=/^c[^\s-]{8,}$/i,L0=/^[0-9a-z]+$/,F0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,B0=/^[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,G0=/^[a-z0-9_-]{21}$/i,J0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,H0=/^[-+]?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)?)??$/,W0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,V0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",pl,Z0=/^(?:(?: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])$/,K0=/^(?:(?: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])$/,Y0=/^(([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]))$/,Q0=/^(([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])$/,X0=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ek=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Am="((\\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])))",tk=new RegExp(`^${Am}$`);function Pm(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 rk(e){return new RegExp(`^${Pm(e)}$`)}function nk(e){let t=`${Am}T${Pm(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 ok(e,t){if((t==="v4"||!t)&&Z0.test(e))return!0;if((t==="v6"||!t)&&Y0.test(e))return!0;return!1}function ik(e,t){if(!J0.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 ak(e,t){if((t==="v4"||!t)&&K0.test(e))return!0;if((t==="v6"||!t)&&Q0.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(!W0.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(!pl)pl=new RegExp(V0,"u");if(!pl.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(!B0.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(!G0.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(!q0.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(!L0.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(!F0.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(!nk(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(!tk.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(!rk(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(!H0.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(!ok(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(!ik(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(!ak(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(!X0.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(!ek.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 sk(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(sk(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 _a 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)}}_a.create=(e)=>new _a({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 Sa 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)}}Sa.create=(e)=>new Sa({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 wa extends ze{constructor(){super(...arguments);this._any=!0}_parse(e){return $t(e.data)}}wa.create=(e)=>new wa({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 xa 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)}}xa.create=(e)=>new xa({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 Mm($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 Lr=(e)=>{if(e instanceof ci)return Lr(e.schema);else if(e instanceof Rr)return Lr(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 Lr(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,...Lr(e.unwrap())];else if(e instanceof pn)return[null,...Lr(e.unwrap())];else if(e instanceof fl)return Lr(e.unwrap());else if(e instanceof gi)return Lr(e.unwrap());else if(e instanceof mi)return Lr(e._def.innerType);else return[]};class gl 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=Lr(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 gl({typeName:oe.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:o,...Pe(n)})}}function ml(e,t){let n=qr(e),o=qr(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=ml(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=ml(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(ul(i)||ul(a))return we;let s=ml(i.value,a.value);if(!s.valid)return le(n,{code:ne.invalid_intersection_types}),we;if(dl(i)||dl(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 Ta 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 Ta({keyType:e,valueType:t,typeName:oe.ZodRecord,...Pe(n)});return new Ta({keyType:Fr.create(),valueType:e,typeName:oe.ZodRecord,...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.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}}}}Ia.create=(e,t,n)=>new Ia({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 ba({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 ba({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 Mm(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=Mm;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 Ca 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}}}Ca.create=(e)=>new Ca({typeName:oe.ZodNaN,...Pe(e)});var F4=Symbol("zod_brand");class fl 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 ka 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 ka({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 B4={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 G4=Fr.create,J4=no.create,H4=Ca.create,W4=oo.create,V4=_a.create,Z4=oi.create,K4=Sa.create,Y4=ii.create,Q4=ai.create,X4=wa.create,eH=En.create,tH=Br.create,rH=xa.create,nH=Cr.create,oH=dt.create,iH=dt.strictCreate,aH=si.create,sH=gl.create,lH=li.create,cH=Gr.create,uH=Ta.create,dH=Ia.create,pH=io.create,mH=ni.create,gH=ci.create,fH=ui.create,hH=An.create,yH=di.create,vH=ao.create,bH=Rr.create,_H=kr.create,SH=pn.create,wH=Rr.createWithPreprocess,xH=ka.create;class Ra 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 jm=10,lk=13,Pn=32;function hl(e){}function Dm(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=hl,onError:n=hl,onRetry:o=hl,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 Ra(`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(Om(_,C,b)){let E=_.charCodeAt(C+5)===Pn?C+6:C+5,F=_.slice(E,I);if(m===0&&_.charCodeAt(I+1)===jm){t({id:u,event:p,data:F}),u=void 0,d="",p=void 0,C=I+2,I=_.indexOf(`
|
|
28
|
-
`,C);continue}d=m===0?F:`${d}
|
|
29
|
-
${F}`,m++}else Nm(_,C,b)?p=_.slice(_.charCodeAt(C+6)===Pn?C+7:C+6,I)||void 0:w(_,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;w(_,C,E),C=E+1,_.charCodeAt(C-1)===lk&&_.charCodeAt(C)===jm&&C++}return _.slice(C)}function w(_,C,I){if(C===I){y();return}let b=_.charCodeAt(C);if(Om(_,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(Nm(_,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),F=E.indexOf(":");if(F===-1){S(E,"",E);return}let R=E.slice(0,F),q=E.charCodeAt(F+1)===Pn?2:1,z=E.slice(F+q);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 Ra(`Invalid \`retry\` value: "${C}"`,{type:"invalid-retry",value:C,line:I}));break;default:n(new Ra(`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 x(_={}){if(_.consume&&s.length>0){let C=s.join("");w(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:x}}function Om(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 Nm(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 yl extends TransformStream{constructor({onError:e,onRetry:t,onComment:n,maxBufferSize:o}={}){let i;super({start(a){i=Dm({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 Ea({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(zm());return}let a=setTimeout(()=>{s(),o()},e),s=()=>{clearTimeout(a),n==null||n.removeEventListener("abort",l)},l=()=>{s(),i(zm())};n==null||n.addEventListener("abort",l)})}function zm(){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:ck,atob:uk}=globalThis;function wt(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=uk(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 ck(t)}function bt(e){return e instanceof Uint8Array?Nt(e):e}function Jm(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 Hm="AI_DownloadError",Wm=`vercel.ai.error.${Hm}`,dk=Symbol.for(Wm),Um,$m,Et=class extends($m=ie,Um=dk,$m){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:Hm,message:i,cause:o});this[Um]=!0,this.url=e,this.statusCode=t,this.statusText=n}static isInstance(e){return ie.hasMarker(e,Wm)}};function pk(e=globalThis){return e.window!=null}function mk(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(fk(o))throw new Et({url:e,message:`URL with IPv6 address ${n} is not allowed`});return}if(Vm(n)){if(Zm(n))throw new Et({url:e,message:`URL with IP address ${n} is not allowed`});return}}function Vm(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 Zm(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 gk(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||!Vm(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 fk(e){let t=gk(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 Zm(`${i}.${a}.${s}.${l}`)}return!1}var hk=10;async function wl({url:e,headers:t,abortSignal:n,maxRedirects:o=hk}){let i={signal:n};if(t!==void 0)i.headers=t;let a=e;for(let s=0;s<=o;s++){mk(a);let l=await fetch(a,{...i,redirect:"manual"});if(l.type==="opaqueredirect"){if(!pk())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 Aa=2147483648;async function Pa({response:e,url:t,maxBytes:n=Aa}){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 xl(e,t){var n,o;try{let i=await wl({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 Pa({response:i,url:e,maxBytes:(n=t==null?void 0:t.maxBytes)!=null?n:Aa}),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()}`},qe=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 yk=["fetch failed","failed to fetch"],vk=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function bk(e){if(!(e instanceof Error))return!1;let t=e.code;if(typeof t==="string"&&vk.includes(t))return!0;return!1}function Km({error:e,url:t,requestBodyValues:n}){if(Yt(e))return e;if(e instanceof TypeError&&yk.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(bk(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 _k(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(_k(e)),o=n.get("user-agent")||"";return n.set("user-agent",[o,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}var Ym="4.0.37",Sk=()=>globalThis.fetch,Xt=async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:o,abortSignal:i,fetch:a=Sk()})=>{try{let s=await a(e,{method:"GET",headers:it(t,`ai-sdk/provider-utils/${Ym}`,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 Km({error:s,url:e,requestBodyValues:{}})}};function yi(e){return e!=null}function Qm(e,t){try{return new URL(e).origin===new URL(t).origin}catch(n){return!1}}function Xm({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 eg(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 wk=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,xk=/"(?: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(wk.test(e)===!1&&xk.test(e)===!1)return t;return Tk(t)}function Tk(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 Tl(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 Tl(e)}var Ik=Symbol("Let zodToJsonSchema decide on which parser to use"),Lm={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"},Ck=(e)=>typeof e==="string"?{...Lm,name:e}:{...Lm,...e};function Qt(){return{}}function kk(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 Rk(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 Ek(){return{type:"boolean"}}function tg(e,t){return Ve(e.type._def,t)}var Ak=(e,t)=>Ve(e.innerType._def,t);function rg(e,t,n){let o=n!=null?n:t.dateStrategy;if(Array.isArray(o))return{anyOf:o.map((i,a)=>rg(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 Pk(e)}}var Pk=(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 Mk(e,t){return{...Ve(e.innerType._def,t),default:e.defaultValue()}}function jk(e,t){return t.effectStrategy==="input"?Ve(e.schema._def,t):Qt()}function Ok(e){return{type:"string",enum:Array.from(e.values)}}var Nk=(e)=>{if("type"in e&&e.type==="string")return!1;return"allOf"in e};function Dk(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(Nk(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 zk(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 vl=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(vl===void 0)vl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return vl},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 ng(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":qt(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":qt(n,o.regex,o.message,t);break;case"cuid":qt(n,dr.cuid,o.message,t);break;case"cuid2":qt(n,dr.cuid2,o.message,t);break;case"startsWith":qt(n,RegExp(`^${bl(o.value,t)}`),o.message,t);break;case"endsWith":qt(n,RegExp(`${bl(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":{qt(n,RegExp(bl(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":qt(n,dr.base64url,o.message,t);break;case"jwt":qt(n,dr.jwt,o.message,t);break;case"cidr":{if(o.version!=="v6")qt(n,dr.ipv4Cidr,o.message,t);if(o.version!=="v4")qt(n,dr.ipv6Cidr,o.message,t);break}case"emoji":qt(n,dr.emoji(),o.message,t);break;case"ulid":{qt(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":{qt(n,dr.base64,o.message,t);break}}break}case"nanoid":qt(n,dr.nanoid,o.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function bl(e,t){return t.patternStrategy==="escape"?$k(e):e}var Uk=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function $k(e){let t="";for(let n=0;n<e.length;n++){if(!Uk.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 qt(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:Fm(t,o),...n&&o.errorMessages&&{errorMessage:{pattern:n}}})}else e.pattern=Fm(t,o)}function Fm(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 og(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}=ng(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}=tg(e.keyType._def,t);return{...c,propertyNames:d}}return c}function qk(e,t){if(t.mapStrategy==="record")return og(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 Lk(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 Fk(){return{not:Qt()}}function Bk(){return{type:"null"}}var _l={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Gk(e,t){let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every((o)=>(o._def.typeName in _l)&&(!o._def.checks||!o._def.checks.length))){let o=n.reduce((i,a)=>{let s=_l[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 Jk(e,t)}var Jk=(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 Hk(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[_l[e.innerType._def.typeName],"null"]};let n=Ve(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function Wk(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 Vk(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=Kk(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=Zk(e,t);if(a!==void 0)n.additionalProperties=a;return n}function Zk(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 Kk(e){try{return e.isOptional()}catch(t){return!0}}var Yk=(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()},Qk=(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 Xk(e,t){return Ve(e.type._def,t)}function eR(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 tR(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 rR(){return{not:Qt()}}function nR(){return Qt()}var oR=(e,t)=>Ve(e.innerType._def,t),iR=(e,t,n)=>{switch(t){case oe.ZodString:return ng(e,n);case oe.ZodNumber:return Wk(e);case oe.ZodObject:return Vk(e,n);case oe.ZodBigInt:return Rk(e);case oe.ZodBoolean:return Ek();case oe.ZodDate:return rg(e,n);case oe.ZodUndefined:return rR();case oe.ZodNull:return Bk();case oe.ZodArray:return kk(e,n);case oe.ZodUnion:case oe.ZodDiscriminatedUnion:return Gk(e,n);case oe.ZodIntersection:return Dk(e,n);case oe.ZodTuple:return tR(e,n);case oe.ZodRecord:return og(e,n);case oe.ZodLiteral:return zk(e);case oe.ZodEnum:return Ok(e);case oe.ZodNativeEnum:return Lk(e);case oe.ZodNullable:return Hk(e,n);case oe.ZodOptional:return Yk(e,n);case oe.ZodMap:return qk(e,n);case oe.ZodSet:return eR(e,n);case oe.ZodLazy:return()=>e.getter()._def;case oe.ZodPromise:return Xk(e,n);case oe.ZodNaN:case oe.ZodNever:return Fk();case oe.ZodEffects:return jk(e,n);case oe.ZodAny:return Qt();case oe.ZodUnknown:return nR();case oe.ZodDefault:return Mk(e,n);case oe.ZodBranded:return tg(e,n);case oe.ZodReadonly:return oR(e,n);case oe.ZodCatch:return Ak(e,n);case oe.ZodPipeline:return Qk(e,n);case oe.ZodFunction:case oe.ZodVoid:case oe.ZodSymbol:return;default:return((o)=>{return})(t)}},aR=(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!==Ik)return c}if(i&&!n){let c=sR(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=iR(e,e.typeName,t),l=typeof s==="function"?Ve(s(),t):s;if(l)lR(e,t,l);if(t.postProcess){let c=t.postProcess(l,e,t);return a.jsonSchema=l,c}return a.jsonSchema=l,l}var sR=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:aR(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}}},lR=(e,t,n)=>{if(e.description)n.description=e.description;return n},cR=(e)=>{let t=Ck(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}]))}},uR=(e,t)=>{var n;let o=cR(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},Sl=Symbol.for("vercel.ai.schema");function j(e){let t;return()=>{if(t==null)t=e();return t}}function vi(e,{validate:t}={}){return{[Sl]:!0,_type:void 0,get jsonSchema(){if(typeof e==="function")e=e();return e},validate:t}}function dR(e){return typeof e==="object"&&e!==null&&Sl in e&&e[Sl]===!0&&"jsonSchema"in e&&"validate"in e}function Lt(e){return e==null?vi({type:"object",properties:{},additionalProperties:!1}):dR(e)?e:("~standard"in e)?e["~standard"].vendor==="zod"?M(e):pR(e):e()}function pR(e){return vi(()=>Tl(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 mR(e,t){var n;let o=(n=t==null?void 0:t.useReferences)!=null?n:!1;return vi(()=>uR(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 gR(e,t){var n;let o=(n=t==null?void 0:t.useReferences)!=null?n:!1;return vi(()=>Tl(Bm(e,{target:"draft-7",io:"input",reused:o?"ref":"inline"})),{validate:async(i)=>{let a=await Gm(e,i);return a.success?{success:!0,value:a.data}:{success:!1,error:a.error}}})}function fR(e){return"_zod"in e}function M(e,t){if(fR(e))return gR(e,t);else return mR(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=Lt(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 Il({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 Ma({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new yl).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 hR=()=>globalThis.fetch,Ie=async({url:e,headers:t,body:n,failedResponseHandler:o,successfulResponseHandler:i,abortSignal:a,fetch:s})=>ig({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:o,successfulResponseHandler:i,abortSignal:a,fetch:s}),ja=async({url:e,headers:t,formData:n,failedResponseHandler:o,successfulResponseHandler:i,abortSignal:a,fetch:s})=>ig({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:o,successfulResponseHandler:i,abortSignal:a,fetch:s}),ig=async({url:e,headers:t={},body:n,successfulResponseHandler:o,failedResponseHandler:i,abortSignal:a,fetch:s=hR()})=>{try{let l=await s(e,{method:"POST",headers:it(t,`ai-sdk/provider-utils/${Ym}`,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 Km({error:l,url:e,requestBodyValues:n.values})}};function Cl(e){return e}function kl(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})=>Cl({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})=>Cl({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 ag=({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)=>sg(l,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:o,shouldRetry:i,getDelayInMs:a,createRetryError:s});async function sg(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}),sg(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 yR=new TextDecoder;async function lg({response:e,url:t}){return yR.decode(await Pa({response:e,url:t}))}var Qe=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:o,url:i,requestBodyValues:a})=>{let s=await lg({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 Il({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 im({});return{responseHeaders:n,value:Ma({stream:t.body,schema:e})}},xe=(e)=>async({response:t,url:n,requestBodyValues:o})=>{let i=await lg({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}},cg=()=>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 vR(e){return e!=null&&typeof e[Symbol.asyncIterator]==="function"}async function*ug({execute:e,input:t,options:n}){let o=e(t,n);if(vR(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 mf=On(Ol(),1),gf=On(Ol(),1),HR="vercel.ai.gateway.error",Nl=Symbol.for(HR),Sg,wg,ft=class e extends(wg=Error,Sg=Nl,wg){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[Sg]=!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&&Nl in t&&t[Nl]===!0}},rf="GatewayAuthenticationError",WR=`vercel.ai.gateway.error.${rf}`,xg=Symbol.for(WR),Tg,Ig,Oa=class e extends(Ig=ft,Tg=xg,Ig){constructor({message:t="Authentication failed",statusCode:n=401,cause:o,generationId:i}={}){super({message:t,statusCode:n,cause:o,generationId:i});this[Tg]=!0,this.name=rf,this.type="authentication_error"}static isInstance(t){return ft.hasMarker(t)&&xg 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})}},nf="GatewayInvalidRequestError",VR=`vercel.ai.gateway.error.${nf}`,Cg=Symbol.for(VR),kg,Rg,ZR=class extends(Rg=ft,kg=Cg,Rg){constructor({message:e="Invalid request",statusCode:t=400,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o});this[kg]=!0,this.name=nf,this.type="invalid_request_error"}static isInstance(e){return ft.hasMarker(e)&&Cg in e}},of="GatewayRateLimitError",KR=`vercel.ai.gateway.error.${of}`,Eg=Symbol.for(KR),Ag,Pg,YR=class extends(Pg=ft,Ag=Eg,Pg){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o});this[Ag]=!0,this.name=of,this.type="rate_limit_exceeded"}static isInstance(e){return ft.hasMarker(e)&&Eg in e}},af="GatewayModelNotFoundError",QR=`vercel.ai.gateway.error.${af}`,Mg=Symbol.for(QR),XR=j(()=>M(r.object({modelId:r.string()}))),jg,Og,eE=class extends(Og=ft,jg=Mg,Og){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[jg]=!0,this.name=af,this.type="model_not_found",this.modelId=n}static isInstance(e){return ft.hasMarker(e)&&Mg in e}},sf="GatewayInternalServerError",tE=`vercel.ai.gateway.error.${sf}`,Ng=Symbol.for(tE),Dg,zg,Ug=class extends(zg=ft,Dg=Ng,zg){constructor({message:e="Internal server error",statusCode:t=500,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o});this[Dg]=!0,this.name=sf,this.type="internal_server_error"}static isInstance(e){return ft.hasMarker(e)&&Ng in e}},lf="GatewayFailedDependencyError",rE=`vercel.ai.gateway.error.${lf}`,$g=Symbol.for(rE),qg,Lg,nE=class extends(Lg=ft,qg=$g,Lg){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=lf,this.type="failed_dependency"}static isInstance(e){return ft.hasMarker(e)&&$g in e}},cf="GatewayForbiddenError",oE=`vercel.ai.gateway.error.${cf}`,Fg=Symbol.for(oE),Bg,Gg,iE=class extends(Gg=ft,Bg=Fg,Gg){constructor({message:e="Forbidden",statusCode:t=403,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o});this[Bg]=!0,this.name=cf,this.type="forbidden"}static isInstance(e){return ft.hasMarker(e)&&Fg in e}},uf="GatewayResponseError",aE=`vercel.ai.gateway.error.${uf}`,Jg=Symbol.for(aE),Hg,Wg,sE=class extends(Wg=ft,Hg=Jg,Wg){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[Hg]=!0,this.name=uf,this.type="response_error",this.response=n,this.validationError=o}static isInstance(e){return ft.hasMarker(e)&&Jg in e}};async function Vg({response:e,statusCode:t,defaultMessage:n="Gateway request failed",cause:o,authMethod:i}){var a;let s=await pt({value:e,schema:lE});if(!s.success){let m=typeof e==="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new sE({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 Oa.createContextualError({apiKeyProvided:i==="api-key",oidcTokenProvided:i==="oidc",statusCode:t,cause:o,generationId:d});case"invalid_request_error":return new ZR({message:u,statusCode:t,cause:o,generationId:d});case"rate_limit_exceeded":return new YR({message:u,statusCode:t,cause:o,generationId:d});case"model_not_found":{let m=await pt({value:l.error.param,schema:XR});return new eE({message:u,statusCode:t,modelId:m.success?m.value.modelId:void 0,cause:o,generationId:d})}case"internal_server_error":return new Ug({message:u,statusCode:t,cause:o,generationId:d});case"failed_dependency":return new nE({message:u,statusCode:t,cause:o,generationId:d});case"forbidden":return new iE({message:u,statusCode:t,cause:o,generationId:d});default:return new Ug({message:u,statusCode:t,cause:o,generationId:d})}}var lE=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 cE(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 df="GatewayTimeoutError",uE=`vercel.ai.gateway.error.${df}`,Zg=Symbol.for(uE),Kg,Yg,Qg=class e extends(Yg=ft,Kg=Zg,Yg){constructor({message:t="Request timed out",statusCode:n=408,cause:o,generationId:i}={}){super({message:t,statusCode:n,cause:o,generationId:i});this[Kg]=!0,this.name=df,this.type="timeout_error"}static isInstance(t){return ft.hasMarker(t)&&Zg 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 Xg(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(Xg(e))return Qg.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e});if(De.isInstance(e)){if(e.cause&&Xg(e.cause))return Qg.createTimeoutError({originalMessage:e.message,cause:e});return await Vg({response:cE(e),statusCode:(n=e.statusCode)!=null?n:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t})}return await Vg({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}var pf="ai-gateway-auth-method";async function tr(e){let t=await pt({value:e[pf],schema:dE});return t.success?t.value:void 0}var dE=j(()=>M(r.union([r.literal("api-key"),r.literal("oidc")]))),pE=["embedding","image","language","reranking","speech","transcription","video"],ef=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(mE),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(gE),failedResponseHandler:Qe({errorSchema:r.any(),errorToMessage:(n)=>n}),fetch:this.config.fetch});return t}catch(e){throw await zt(e)}}},mE=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||pE.includes(t.modelType)))}))),gE=j(()=>M(r.object({balance:r.string(),total_used:r.string()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),fE=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(hE),failedResponseHandler:Qe({errorSchema:r.any(),errorToMessage:(i)=>i}),fetch:this.config.fetch});return o}catch(t){throw await zt(t)}}},hE=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}:{}})))}))),yE=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(vE),failedResponseHandler:Qe({errorSchema:r.any(),errorToMessage:(o)=>o}),fetch:this.config.fetch});return n}catch(t){throw await zt(t)}}},vE=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))),bE=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)}}},_E=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(wE),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}}},SE=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()})]),wE=j(()=>M(r.object({embeddings:r.array(r.array(r.number())),usage:r.object({tokens:r.number()}).nullish(),warnings:r.array(SE).optional(),providerMetadata:r.record(r.string(),r.record(r.string(),r.unknown())).optional()})));function Na(e){return(e!=null?e:[]).map((t)=>t.type==="deprecated"?{type:"other",message:t.message}:t)}var xE=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((w)=>tf(w))},...s&&{mask:tf(s)}},successfulResponseHandler:xe(kE),failedResponseHandler:Qe({errorSchema:r.any(),errorToMessage:(w)=>w}),...u&&{abortSignal:u},fetch:this.config.fetch});return{images:h.images,warnings:Na(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 tf(e){if(e.type==="file"&&e.data instanceof Uint8Array)return{...e,data:Nt(e.data)};return e}var TE=r.object({images:r.array(r.unknown()).optional()}).catchall(r.unknown()),IE=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()})]),CE=r.object({inputTokens:r.number().nullish(),outputTokens:r.number().nullish(),totalTokens:r.number().nullish()}),kE=r.object({images:r.array(r.string()),warnings:r.array(IE).optional(),providerMetadata:r.record(r.string(),TE).optional(),usage:CE.optional()}),RE=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:Dl(c)},...u&&{frameImages:u.map((w)=>({...w,image:Dl(w.image)}))},...d&&{inputReferences:d.map((w)=>Dl(w))}},successfulResponseHandler:async({response:w,url:S,requestBodyValues:y})=>{if(w.body==null)throw new De({message:"SSE response body is empty",url:S,requestBodyValues:y,statusCode:w.status});let _=Ma({stream:w.body,schema:ME}).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:w.status});if(!I.success)throw new De({message:"Failed to parse video SSE event",cause:I.error,url:S,requestBodyValues:y,statusCode:w.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([...w.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([...w.headers])}},failedResponseHandler:Qe({errorSchema:r.any(),errorToMessage:(w)=>w}),...f&&{abortSignal:f},fetch:this.config.fetch});return{videos:v.videos,warnings:Na(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 Dl(e){if(e.type==="file"&&e.data instanceof Uint8Array)return{...e,data:Nt(e.data)};return e}var EE=r.object({videos:r.array(r.unknown()).optional()}).catchall(r.unknown()),AE=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()})]),PE=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()})]),ME=r.discriminatedUnion("type",[r.object({type:r.literal("result"),videos:r.array(AE),warnings:r.array(PE).optional(),providerMetadata:r.record(r.string(),EE).optional()}),r.object({type:r.literal("error"),message:r.string(),errorType:r.string(),statusCode:r.number(),param:r.unknown().nullable()})]),jE=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(NE),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}}},OE=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()})]),NE=j(()=>M(r.object({ranking:r.array(r.object({index:r.number(),relevanceScore:r.number()})),warnings:r.array(OE).optional(),providerMetadata:r.record(r.string(),r.record(r.string(),r.unknown())).optional()}))),DE=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($E),failedResponseHandler:Qe({errorSchema:r.any(),errorToMessage:(f)=>f}),...c&&{abortSignal:c},fetch:this.config.fetch});return{audio:m.audio,warnings:Na(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}}},zE=r.object({}).catchall(r.unknown()),UE=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()})]),$E=r.object({audio:r.string(),warnings:r.array(UE).optional(),providerMetadata:r.record(r.string(),zE).optional()}),qE=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(BE),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:Na(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}}},LE=r.object({}).catchall(r.unknown()),FE=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()})]),BE=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(FE).optional(),providerMetadata:r.record(r.string(),LE).optional()}),GE=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.")}))),JE=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()})]))),HE=Te({id:"gateway.exa_search",inputSchema:GE,outputSchema:JE}),WE=(e={})=>HE(e),VE=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.")}))),ZE=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()})]))),KE=Te({id:"gateway.parallel_search",inputSchema:VE,outputSchema:ZE}),YE=(e={})=>KE(e),QE=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.")}))),XE=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()})]))),eA=Te({id:"gateway.perplexity_search",inputSchema:QE,outputSchema:XE}),tA=(e={})=>eA(e),rA={exaSearch:WE,parallelSearch:YE,perplexitySearch:tA};async function nA(){var e;return(e=mf.getContext().headers)==null?void 0:e["x-vercel-id"]}var oA="3.0.145",iA="0.0.1";function aA(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 x=await sA(e);return it({Authorization:`Bearer ${x.token}`,"ai-gateway-protocol-version":iA,[pf]:x.authMethod,...e.headers},`ai-sdk/gateway/${oA}`)}catch(x){throw Oa.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:x})}},u=()=>{let x=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 nA();return{...x&&{"ai-o11y-deployment-id":x},..._&&{"ai-o11y-environment":_},...C&&{"ai-o11y-region":C},...b&&{"ai-o11y-request-id":b},...I&&{"ai-o11y-project-id":I}}}},d=(x)=>new bE(x,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:u()}),m=async()=>{var x,_,C;let I=(C=(_=(x=e._internal)==null?void 0:x.currentDate)==null?void 0:_.call(x).getTime())!=null?C:Date.now();if(!o||I-s>a)s=I,o=new ef({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 ef({baseURL:l,headers:c,fetch:e.fetch}).getCredits().catch(async(x)=>{throw await zt(x,await tr(await c()))}),f=async(x)=>new fE({baseURL:l,headers:c,fetch:e.fetch}).getSpendReport(x).catch(async(_)=>{throw await zt(_,await tr(await c()))}),g=async(x)=>new yE({baseURL:l,headers:c,fetch:e.fetch}).getGenerationInfo(x).catch(async(_)=>{throw await zt(_,await tr(await c()))}),h=function(x){if(new.target)throw Error("The Gateway Provider model function cannot be called with the new keyword.");return d(x)};h.specificationVersion="v3",h.getAvailableModels=m,h.getCredits=p,h.getSpendReport=f,h.getGenerationInfo=g,h.imageModel=(x)=>new xE(x,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:u()}),h.languageModel=d;let v=(x)=>new _E(x,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:u()});h.embeddingModel=v,h.textEmbeddingModel=v,h.videoModel=(x)=>new RE(x,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:u()});let w=(x)=>new jE(x,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:u()});h.rerankingModel=w,h.reranking=w;let S=(x)=>new DE(x,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:u()});h.speechModel=S,h.speech=S;let y=(x)=>new qE(x,{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=rA,h}var ff=aA();async function sA(e){let t=Ar({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(t)return{token:t,authMethod:"api-key"};return{token:await gf.getVercelOidcToken(),authMethod:"oidc"}}var Ib=On(Ac(),1),yo=On(Ac(),1);var yM=Object.defineProperty,vM=(e,t)=>{for(var n in t)yM(e,n,{get:t[n],enumerable:!0})},xv="AI_InvalidArgumentError",Tv=`vercel.ai.error.${xv}`,bM=Symbol.for(Tv),Iv,at=class extends ie{constructor({parameter:e,value:t,message:n}){super({name:xv,message:`Invalid argument for parameter ${e}: ${n}`});this[Iv]=!0,this.parameter=e,this.value=t}static isInstance(e){return ie.hasMarker(e,Tv)}};Iv=bM;var _M="AI_InvalidStreamPartError",SM=`vercel.ai.error.${_M}`,wM=Symbol.for(SM),xM;xM=wM;var Cv="AI_InvalidToolApprovalError",kv=`vercel.ai.error.${Cv}`,TM=Symbol.for(kv),Rv,IM=class extends ie{constructor({approvalId:e}){super({name:Cv,message:`Tool approval response references unknown approvalId: "${e}". No matching tool-approval-request found in message history.`});this[Rv]=!0,this.approvalId=e}static isInstance(e){return ie.hasMarker(e,kv)}};Rv=TM;var Ev="AI_InvalidToolApprovalSignatureError",Av=`vercel.ai.error.${Ev}`,CM=Symbol.for(Av),Pv,sv=class extends ie{constructor({approvalId:e,toolCallId:t,reason:n}){super({name:Ev,message:`Tool approval signature verification failed for approval "${e}" (tool call "${t}"): ${n}`});this[Pv]=!0,this.approvalId=e,this.toolCallId=t}static isInstance(e){return ie.hasMarker(e,Av)}};Pv=CM;var Mv="AI_InvalidToolInputError",jv=`vercel.ai.error.${Mv}`,kM=Symbol.for(jv),Ov,Ya=class extends ie{constructor({toolInput:e,toolName:t,cause:n,message:o=`Invalid input for tool ${t}: ${Tr(n)}`}){super({name:Mv,message:o,cause:n});this[Ov]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return ie.hasMarker(e,jv)}};Ov=kM;var Nv="AI_ToolCallNotFoundForApprovalError",Dv=`vercel.ai.error.${Nv}`,RM=Symbol.for(Dv),zv,Lc=class extends ie{constructor({toolCallId:e,approvalId:t}){super({name:Nv,message:`Tool call "${e}" not found for approval request "${t}".`});this[zv]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return ie.hasMarker(e,Dv)}};zv=RM;var Uv="AI_MissingToolResultsError",$v=`vercel.ai.error.${Uv}`,EM=Symbol.for($v),qv,lv=class extends ie{constructor({toolCallIds:e}){super({name:Uv,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,$v)}};qv=EM;var Lv="AI_NoImageGeneratedError",Fv=`vercel.ai.error.${Lv}`,AM=Symbol.for(Fv),Bv,PM=class extends ie{constructor({message:e="No image generated.",cause:t,responses:n}){super({name:Lv,message:e,cause:t});this[Bv]=!0,this.responses=n}static isInstance(e){return ie.hasMarker(e,Fv)}};Bv=AM;var Gv="AI_NoObjectGeneratedError",Jv=`vercel.ai.error.${Gv}`,MM=Symbol.for(Jv),Hv,Ft=class extends ie{constructor({message:e="No object generated.",cause:t,text:n,response:o,usage:i,finishReason:a}){super({name:Gv,message:e,cause:t});this[Hv]=!0,this.text=n,this.response=o,this.usage=i,this.finishReason=a}static isInstance(e){return ie.hasMarker(e,Jv)}};Hv=MM;var Wv="AI_NoOutputGeneratedError",Vv=`vercel.ai.error.${Wv}`,jM=Symbol.for(Vv),Zv,Ha=class extends ie{constructor({message:e="No output generated.",cause:t}={}){super({name:Wv,message:e,cause:t});this[Zv]=!0}static isInstance(e){return ie.hasMarker(e,Vv)}};Zv=jM;var OM="AI_NoSpeechGeneratedError",NM=`vercel.ai.error.${OM}`,DM=Symbol.for(NM),zM;zM=DM;var UM="AI_NoTranscriptGeneratedError",$M=`vercel.ai.error.${UM}`,qM=Symbol.for($M),LM;LM=qM;var FM="AI_NoVideoGeneratedError",BM=`vercel.ai.error.${FM}`,GM=Symbol.for(BM),JM;JM=GM;var Kv="AI_NoSuchToolError",Yv=`vercel.ai.error.${Kv}`,HM=Symbol.for(Yv),Qv,jc=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:Kv,message:n});this[Qv]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return ie.hasMarker(e,Yv)}};Qv=HM;var Xv="AI_ToolCallRepairError",eb=`vercel.ai.error.${Xv}`,WM=Symbol.for(eb),tb,VM=class extends ie{constructor({cause:e,originalError:t,message:n=`Error repairing tool call: ${Tr(e)}`}){super({name:Xv,message:n,cause:e});this[tb]=!0,this.originalError=t}static isInstance(e){return ie.hasMarker(e,eb)}};tb=WM;var Fc=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}},rb="AI_UIMessageStreamError",nb=`vercel.ai.error.${rb}`,ZM=Symbol.for(nb),ob,fo=class extends ie{constructor({chunkType:e,chunkId:t,message:n}){super({name:rb,message:n});this[ob]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return ie.hasMarker(e,nb)}};ob=ZM;var ib="AI_InvalidDataContentError",ab=`vercel.ai.error.${ib}`,KM=Symbol.for(ab),sb,cv=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:ib,message:n,cause:t});this[sb]=!0,this.content=e}static isInstance(e){return ie.hasMarker(e,ab)}};sb=KM;var lb="AI_InvalidMessageRoleError",cb=`vercel.ai.error.${lb}`,YM=Symbol.for(cb),ub,QM=class extends ie{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:lb,message:t});this[ub]=!0,this.role=e}static isInstance(e){return ie.hasMarker(e,cb)}};ub=YM;var XM="AI_MessageConversionError",ej=`vercel.ai.error.${XM}`,tj=Symbol.for(ej),rj;rj=tj;var db="AI_RetryError",pb=`vercel.ai.error.${db}`,nj=Symbol.for(pb),mb,oj=class extends ie{constructor({message:e,reason:t,errors:n}){super({name:db,message:e});this[mb]=!0,this.reason=t,this.errors=n,this.lastError=n[n.length-1]}static isInstance(e){return ie.hasMarker(e,pb)}};mb=nj;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 ij({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 aj="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",uv=!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(!uv)uv=!0,console.info(aj);for(let n of e.warnings)console.warn(ij({warning:n,provider:e.provider,model:e.model}))};function Bc({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 sj(e){if(e.specificationVersion==="v3")return e;return Bc({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,n){if(n==="specificationVersion")return"v3";return t[n]}})}function lj(e){if(e.specificationVersion==="v3")return e;return Bc({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,n){if(n==="specificationVersion")return"v3";return t[n]}})}function cj(e){if(e.specificationVersion==="v3")return e;return Bc({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:gb(i.finishReason),usage:fb(i.usage)}};case"doStream":return async(...o)=>{let i=await t.doStream(...o);return{...i,stream:uj(i.stream)}};default:return t[n]}}})}function uj(e){return e.pipeThrough(new TransformStream({transform(t,n){switch(t.type){case"finish":n.enqueue({...t,finishReason:gb(t.finishReason),usage:fb(t.usage)});break;default:n.enqueue(t);break}}}))}function gb(e){return{unified:e==="unknown"?"other":e,raw:void 0}}function fb(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 Fc({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return cj(e)}return Gc().languageModel(e)}function hb(e){if(typeof e!=="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){let t=e;throw new Fc({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return sj(e)}return Gc().embeddingModel(e)}function dj(e){if(typeof e!=="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){let t=e;throw new Fc({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return lj(e)}return Gc().imageModel(e)}function Gc(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:ff}function Jc(e){if(e==null)return;if(typeof e==="number")return e;return e.totalMs}function yb(e){if(e==null||typeof e==="number")return;return e.stepMs}function pj(e){if(e==null||typeof e==="number")return;return e.chunkMs}var Va=[{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 mj=(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 gj(e){return typeof e==="string"&&e.startsWith("SUQz")||typeof e!=="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?mj(e):e}function Za({data:e,signatures:t}){let n=gj(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",vb=async({url:e,maxBytes:t,abortSignal:n})=>{var o;let i=e.toString();try{let a=it({},`ai-sdk/${vo}`,lo()),s=await wl({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 Pa({response:s,url:i,maxBytes:t!=null?t:Aa}),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})}},fj=(e=vb)=>(t)=>Promise.all(t.map(async(n)=>n.isUrlSupportedByModel?null:e(n)));function bb(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 _b=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 Hc(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}=bb(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 Oc(e){if(typeof e==="string")return e;if(e instanceof ArrayBuffer)return Nt(new Uint8Array(e));return Nt(e)}function hj(e){if(e instanceof Uint8Array)return e;if(typeof e==="string")try{return wt(e)}catch(t){throw new cv({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 cv({content:e})}async function Wc({prompt:e,supportedUrls:t,download:n=fj()}){let o=await vj(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)=>yj({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 lv({toolCallIds:Array.from(c)});break}for(let u of a)c.delete(u);if(c.size>0)throw new lv({toolCallIds:Array.from(c)});return l.filter((u)=>u.role!=="tool"||u.content.length>0)}function yj({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)=>bj(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}=Hc(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:dv({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:dv({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 QM({role:n})}}async function vj(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}=Hc(l.data);return{mediaType:c,data:u}}).filter((l)=>l.data instanceof URL).map((l)=>({url:l.data,isUrlSupportedByModel:l.mediaType!=null&&Xm({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 bj(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}=Hc(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=Za({data:c,signatures:Va}))!=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 dv({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:Oc(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:Oc(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:pv(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:pv(n)}}function pv(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 _j(e){return e!=null&&Object.keys(e).length>0}async function Sb({tools:e,toolChoice:t,activeTools:n}){if(!_j(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 Lt(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())),wb=r.object({type:r.literal("text"),text:r.string(),providerOptions:fe.optional()}),Sj=r.object({type:r.literal("image"),image:r.union([_b,r.instanceof(URL)]),mediaType:r.string().optional(),providerOptions:fe.optional()}),xb=r.object({type:r.literal("file"),data:r.union([_b,r.instanceof(URL)]),filename:r.string().optional(),mediaType:r.string(),providerOptions:fe.optional()}),wj=r.object({type:r.literal("reasoning"),text:r.string(),providerOptions:fe.optional()}),xj=r.object({type:r.literal("tool-call"),toolCallId:r.string(),toolName:r.string(),input:r.unknown(),providerOptions:fe.optional(),providerExecuted:r.boolean().optional()}),Tj=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()})]))})]),Tb=r.object({type:r.literal("tool-result"),toolCallId:r.string(),toolName:r.string(),output:Tj,providerOptions:fe.optional()}),Ij=r.object({type:r.literal("tool-approval-request"),approvalId:r.string(),toolCallId:r.string()}),Cj=r.object({type:r.literal("tool-approval-response"),approvalId:r.string(),approved:r.boolean(),reason:r.string().optional()}),kj=r.object({role:r.literal("system"),content:r.string(),providerOptions:fe.optional()}),Rj=r.object({role:r.literal("user"),content:r.union([r.string(),r.array(r.union([wb,Sj,xb]))]),providerOptions:fe.optional()}),Ej=r.object({role:r.literal("assistant"),content:r.union([r.string(),r.array(r.union([wb,xb,wj,xj,Tb,Ij]))]),providerOptions:fe.optional()}),Aj=r.object({role:r.literal("tool"),content:r.array(r.union([Tb,Cj])),providerOptions:fe.optional()}),Pj=r.union([kj,Rj,Ej,Aj]);async function Vc({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(Pj)});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 Zc(e){if(!Oa.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=Jc(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 Mj={startSpan(){return Ja},startActiveSpan(e,t,n,o){if(typeof t==="function")return t(Ja);if(typeof n==="function")return n(Ja);if(typeof o==="function")return o(Ja)}},Ja={spanContext(){return jj},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}},jj={traceId:"",spanId:"",traceFlags:0};function Pi({isEnabled:e=!1,tracer:t}={}){if(!e)return Mj;if(t)return t;return Ib.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{Cb(a,l)}finally{a.end()}throw l}})}function Cb(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 Oj(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"}function Pc(e){if(!Array.isArray(e))return e;let t=new Set(e.filter(Oj).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=Pc(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=Pc(s);if(l!=null)n[o]=l}continue}let a=Pc(i);if(a!=null)n[o]=a}return n}function Kc(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?Oc(n.data):n.data}:n)})))}function Nj(){var e;return(e=globalThis.AI_SDK_TELEMETRY_INTEGRATIONS)!=null?e:[]}function kb(){let e=Nj();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 Mc(){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 Rb(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 Dj(e,t){return{inputTokens:Jt(e.inputTokens,t.inputTokens),outputTokens:Jt(e.outputTokens,t.outputTokens),totalTokens:Jt(e.totalTokens,t.totalTokens)}}function Qa(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]=Qa(a,i);else n[o]=i}}return n}function zj({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 Uj=({maxRetries:e=2,initialDelayInMs:t=2000,backoffFactor:n=2,abortSignal:o}={})=>ag({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})=>zj({error:i,exponentialBackoffDelay:a}),createRetryError:({message:i,reason:a,errors:s})=>new oj({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:Uj({maxRetries:n,abortSignal:t})}}function Nc({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 Eb({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 IM({approvalId:c.approvalId});if(i[u.toolCallId]!=null)continue;let d=n[u.toolCallId];if(d==null)throw new Lc({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 Wa(){var e,t;return(t=(e=globalThis==null?void 0:globalThis.performance)==null?void 0:e.now())!=null?t:Date.now()}async function Yc({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(w)=>{let S;await mr({event:v,callbacks:d});let y=Wa();try{let _=ug({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=Wa()-y;return await mr({event:{...v,success:!1,error:_,durationMs:C},callbacks:m}),Cb(w,_),{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 x=Wa()-y;await mr({event:{...v,success:!0,output:S,durationMs:x},callbacks:m});try{w.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 Dc(e){let t=e.filter((n)=>n.type==="reasoning");return t.length===0?void 0:t.map((n)=>n.text).join(`
|
|
63
|
-
`)}function zc(e){let t=e.filter((n)=>n.type==="text");if(t.length===0)return;return t.map((n)=>n.text).join("")}var Qc=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}},$j=class extends Qc{constructor(e){super(e);this.type="file"}};async function Xc({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 eu=new TextEncoder;function Uc(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(Uc).join(",")}]`;return`{${Object.keys(e).sort().map((o)=>`${JSON.stringify(o)}:${Uc(e[o])}`).join(",")}}`}function Ab(e){return Nt(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function qj(e){return wt(e)}async function Pb(e){let t=typeof e==="string"?eu.encode(e):e;return crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}async function Mb(e){let t=Uc(e),n=await crypto.subtle.digest("SHA-256",eu.encode(t));return Ab(new Uint8Array(n))}function jb(e,t,n,o){return eu.encode(`${e}
|
|
64
|
-
${t}
|
|
65
|
-
${n}
|
|
66
|
-
${o}`)}async function Lj({secret:e,approvalId:t,toolCallId:n,toolName:o,input:i}){let a=await Pb(e),s=await Mb(i),l=jb(t,n,o,s),c=await crypto.subtle.sign("HMAC",a,l);return Ab(new Uint8Array(c))}async function Fj({secret:e,signature:t,approvalId:n,toolCallId:o,toolName:i,input:a}){let s=await Pb(e),l=await Mb(a),c=jb(n,o,i,l),u=qj(t);return crypto.subtle.verify("HMAC",s,u,c)}async function Ob({secret:e,approvalId:t,toolCallId:n,toolName:o,input:i}){if(e==null)return;return Lj({secret:e,approvalId:t,toolCallId:n,toolName:o,input:i})}async function Nb({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 sv({approvalId:d.approvalId,toolCallId:u.toolCallId,reason:"missing signature"});if(!await Fj({secret:i,signature:d.signature,approvalId:d.approvalId,toolCallId:u.toolCallId,toolName:u.toolName,input:u.input}))throw new sv({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:Lt(m.inputSchema)});if(!f.success)throw new Ya({toolName:u.toolName,toolInput:JSON.stringify(u.input),cause:f.error})}if(m!=null&&await Xc({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 Bj={};vM(Bj,{array:()=>Hj,choice:()=>Wj,json:()=>Vj,object:()=>Jj,text:()=>Ka});function Gj(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:Gj(e)}),t.success)return{value:t.value,state:"repaired-parse"};return{value:void 0,state:"failed-parse"}}var Ka=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){return}}),Jj=({schema:e,name:t,description:n})=>{let o=Lt(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}}},Hj=({element:e,name:t,description:n})=>{let o=Lt(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])}})}}},Wj=({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}}),Vj=({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 Db({toolCall:e,tools:t,repairToolCall:n,system:o,messages:i}){try{if(t==null){if(e.providerExecuted&&e.dynamic)return await zb(e);throw new jc({toolName:e.toolName})}try{return await mv({toolCall:e,tools:t})}catch(a){if(n==null||!(jc.isInstance(a)||Ya.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 Lt(c).jsonSchema},system:o,messages:i,error:a})}catch(l){throw new VM({cause:l,originalError:a})}if(s==null)throw a;return await mv({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 zb(e){let t=e.input.trim()===""?{success:!0,value:{}}:await xt({text:e.input});if(t.success===!1)throw new Ya({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 mv({toolCall:e,tools:t}){let n=e.toolName,o=t[n];if(o==null){if(e.providerExecuted&&e.dynamic)return await zb(e);throw new jc({toolName:e.toolName,availableTools:Object.keys(t)})}let i=Lt(o.inputSchema),a=e.input.trim()===""?await pt({value:{},schema:i}):await xt({text:e.input,schema:i});if(a.success===!1)throw new Ya({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 Ub=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 $b({stopConditions:e,steps:t}){return(await Promise.all(e.map((n)=>n({steps:t})))).some((n)=>n)}async function $c({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:Zj({toolResultContent:a,toolCallOrder:o})});return n}function Zj({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 Kj=Er({prefix:"aitxt",size:24});async function tu({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:w=v,experimental_prepareStep:S,prepareStep:y=S,experimental_repairToolCall:x,experimental_download:_,experimental_context:C,experimental_toolApprovalSecret:I,experimental_include:b,_internal:{generateId:E=Kj}={},experimental_onStart:F,experimental_onStepStart:R,experimental_onToolCallStart:q,experimental_onToolCallFinish:z,onStepFinish:N,onFinish:re,...Y}){let V=ki(e),L=kb(),pe=zn(m),Q=Jc(u),k=yb(u),X=k!=null?new AbortController:void 0,J=qb(c,Q!=null?AbortSignal.timeout(Q):void 0,X==null?void 0:X.signal),{maxRetries:H,retry:K}=bo({maxRetries:l,abortSignal:J}),D=Ri(Y),B=it(d!=null?d:{},`ai/${vo}`),G=Ai({model:V,telemetry:g,headers:B,settings:{...D,maxRetries:H}}),Z={provider:V.provider,modelId:V.modelId},A=await Vc({system:o,prompt:i,messages:a,allowSystemInMessages:s}),O=L(g==null?void 0:g.integrations);await mr({event:{model:Z,system:o,prompt:i,messages:a,tools:t,toolChoice:n,activeTools:w,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:H,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:[F,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 U,me,ee,ue,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}=Eb({messages:ve}),{approvedToolApprovals:sr,deniedToolApprovals:lr}=await Nb({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 gv({toolCalls:sr.map((Ne)=>Ne.toolCall),tools:t,tracer:W,telemetry:g,messages:ve,abortSignal:J,experimental_context:C,stepNumber:0,model:Z,onToolCallStart:[q,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=Nc({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((U=Ne==null?void 0:Ne.model)!=null?U:V),an={provider:Bt.provider,modelId:Bt.modelId},Ur=await Wc({prompt:{system:(me=Ne==null?void 0:Ne.system)!=null?me:A.system,messages:(ee=Ne==null?void 0:Ne.messages)!=null?ee:Pt},supportedUrls:await Bt.supportedUrls,download:_});C=(ue=Ne==null?void 0:Ne.experimental_context)!=null?ue:C;let aa=(Ae=Ne==null?void 0:Ne.activeTools)!=null?Ae:w,{toolChoice:$r,tools:sn}=await Sb({tools:t,toolChoice:(Ke=Ne==null?void 0:Ne.toolChoice)!=null?Ke:n,activeTools:aa}),Sr=(nt=Ne==null?void 0:Ne.messages)!=null?nt:Pt,yt=(At=Ne==null?void 0:Ne.system)!=null?At:A.system,cr=Qa(h,Ne==null?void 0:Ne.providerOptions);await mr({event:{stepNumber:Be.length,model:an,system:yt,messages:Sr,tools:t,toolChoice:$r,activeTools:aa,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:()=>Kc(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,la,ca,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:J,headers:B}),Zt={id:(Ct=(wr=Ye.response)==null?void 0:wr.id)!=null?Ct:E(),timestamp:(la=(Bo=Ye.response)==null?void 0:Bo.timestamp)!=null?la:new Date,modelId:(cn=(ca=Ye.response)==null?void 0:ca.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:()=>zc(Ye.content)},"ai.response.reasoning":{output:()=>Dc(Ye.content)},"ai.response.toolCalls":{output:()=>{let Vn=fv(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)=>Db({toolCall:Me,tools:t,repairToolCall:x,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:J,experimental_context:C});if(await Xc({tool:Mt,toolCall:Me,messages:Pt,experimental_context:C})){let wr=E(),Ct=await Ob({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 sa=ln.filter((Me)=>Me.invalid&&Me.dynamic);Oe=[];for(let Me of sa)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 gv({toolCalls:lt.filter((Me)=>!Me.invalid&&Hn[Me.toolCallId]==null),tools:t,tracer:W,telemetry:g,messages:Pt,abortSignal:J,experimental_context:C,stepNumber:Be.length,model:an,onToolCallStart:[q,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=Qj({content:Fe.content,toolCalls:ln,toolOutputs:Oe,toolApprovalRequests:Object.values(Hn),tools:t});Re.push(...await $c({content:In,tools:t}));let Lo=((Dr=b==null?void 0:b.requestBody)!=null?Dr:!0)?(he=Fe.request)!=null?he:{}:{...Fe.request,body:void 0},Qs={...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},Xs=Be.length,Fo=new Ub({stepNumber:Xs,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:Lo,response:Qs});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 $b({stopConditions:pe,steps:Be}));P.setAttributes(await et({telemetry:g,attributes:{"ai.response.finishReason":Fe.finishReason.unified,"ai.response.text":{output:()=>zc(Fe.content)},"ai.response.reasoning":{output:()=>Dc(Fe.content)},"ai.response.toolCalls":{output:()=>{let It=fv(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)=>Rb(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:Ka()).parseCompleteOutput({text:Ce.text},{response:Ce.response,usage:Ce.usage,finishReason:Ce.finishReason});return new Yj({steps:Be,totalUsage:ot,output:ct})}})}catch(P){throw Zc(P)}}async function gv({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)=>Yc({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 Yj=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 Ha;return this._output}};function fv(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 Qj({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 Qc(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 Lc({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 Xj({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 Lb({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 eO({response:e,status:t,statusText:n,headers:o,textStream:i}){Lb({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 Fb=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
|
|
67
|
-
|
|
68
|
-
`)},flush(e){e.enqueue(`data: [DONE]
|
|
69
|
-
|
|
70
|
-
`)}})}},Bb={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function tO({status:e,statusText:t,headers:n,stream:o,consumeSseStream:i}){let a=o.pipeThrough(new Fb);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,Bb)})}function rO({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()),m6=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 nO(e){return e.type.startsWith("data-")}function Wr(){return Object.create(null)}function qc(e){return e.type.startsWith("tool-")}function oO(e){return e.type==="dynamic-tool"}function hv(e){return qc(e)||oO(e)}function yv(e){return e.type.split("-").slice(1).join("-")}function iO({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 aO({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(hv).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 x;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=(x=C.providerExecuted)!=null?x:_.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 w(y){var x,_;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=(x=I.rawInput)!=null?x: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 F=C;F.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 x=u.message.metadata!=null?Qa(u.message.metadata,y):y;if(t!=null)await Ee({value:x,schema:t,context:{field:"message.metadata",entityId:u.message.id}});u.message.metadata=x}}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)w({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:x}=await Mi(y.text);if(y.dynamic)w({toolCallId:l.toolCallId,toolName:y.toolName,state:"input-streaming",input:x,title:y.title,toolMetadata:y.toolMetadata});else v({toolCallId:l.toolCallId,toolName:y.toolName,state:"input-streaming",input:x,title:y.title,toolMetadata:y.toolMetadata});d();break}case"tool-input-available":{if(l.dynamic)w({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(hv).find((_)=>_.toolCallId===l.toolCallId);if(y!=null?y.type==="dynamic-tool":!!l.dynamic)w({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")w({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:yv(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")w({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:yv(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(nO(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 x=y.id!=null?u.message.parts.find((_)=>y.type===_.type&&y.id===_.id):void 0;if(x!=null)x.data=y.data;else u.message.parts.push(y);s==null||s(y),d()}}c.enqueue(l)})}}))}function Gb({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=iO({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 aO({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 sO({response:e,status:t,statusText:n,headers:o,stream:i,consumeSseStream:a}){let s=i.pipeThrough(new Fb);if(a){let[l,c]=s.tee();s=l,a({stream:c})}Lb({response:e,status:t,statusText:n,headers:Object.fromEntries(Oi(o,Bb).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 lO({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 vv(){let e,t;return{promise:new Promise((o,i)=>{e=o,t=i}),resolve:e,reject:t}}function cO(){let e=[],t=null,n=!1,o=vv(),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=vv(),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 uO({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}}),w=new Set,S=new Map,y=!1,x=void 0;function _(){if(y&&w.size===0){if(x!=null)h.enqueue(x);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 $j({data:I.data,mediaType:I.mediaType}),...I.providerMetadata!=null?{providerMetadata:I.providerMetadata}:{}});break}case"finish":{x={type:"finish",finishReason:I.finishReason.unified,rawFinishReason:I.finishReason.raw,usage:Ei(I.usage),providerMetadata:I.providerMetadata};break}case"tool-approval-request":{let F=S.get(I.toolCallId);if(F==null){h.enqueue({type:"error",error:new Lc({toolCallId:I.toolCallId,approvalId:I.approvalId})});break}b.enqueue({type:"tool-approval-request",approvalId:I.approvalId,toolCall:F});break}case"tool-call":{try{let F=await Db({toolCall:I,tools:e,repairToolCall:l,system:i,messages:a});if(S.set(F.toolCallId,F),b.enqueue(F),F.invalid){h.enqueue({type:"tool-error",toolCallId:F.toolCallId,toolName:F.toolName,input:F.input,error:hi(F.error),dynamic:!0,title:F.title,...F.toolMetadata!=null?{toolMetadata:F.toolMetadata}:{}});break}let R=e==null?void 0:e[F.toolName];if(R==null)break;if(R.onInputAvailable!=null)await R.onInputAvailable({input:F.input,toolCallId:F.toolCallId,messages:a,abortSignal:s,experimental_context:c});if(await Xc({tool:R,toolCall:F,messages:a,experimental_context:c})){let q=d(),z=await Ob({secret:u,approvalId:q,toolCallId:F.toolCallId,toolName:F.toolName,input:F.input});h.enqueue({type:"tool-approval-request",approvalId:q,toolCall:F,...z!=null?{signature:z}:{}});break}if(R.execute!=null&&F.providerExecuted!==!0){let q=d();w.add(q),Yc({toolCall:F,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(()=>{w.delete(q),_()})}}catch(F){h.enqueue({type:"error",error:F})}break}case"tool-result":{let F=I.toolName,R=S.get(I.toolCallId);if(I.isError)h.enqueue({type:"tool-error",toolCallId:I.toolCallId,toolName:F,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:F,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 dO=Er({prefix:"aitxt",size:24}),pO={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 mO({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:w,activeTools:S=w,experimental_repairToolCall:y,experimental_transform:x,experimental_download:_,includeRawChunks:C=!1,onChunk:I,onError:b=({error:X})=>{console.error(X)},onFinish:E,onAbort:F,onStepFinish:R,experimental_onStart:q,experimental_onStepStart:z,experimental_onToolCallStart:N,experimental_onToolCallFinish:re,experimental_context:Y,experimental_toolApprovalSecret:V,experimental_include:L,_internal:{now:pe=Wa,generateId:Q=dO}={},...k}){let X=Jc(u),J=yb(u),H=pj(u),K=J!=null?new AbortController:void 0,D=H!=null?new AbortController:void 0;return new fO({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:J,stepAbortController:K,chunkTimeoutMs:H,chunkAbortController:D,system:o,prompt:i,messages:a,allowSystemInMessages:s,tools:t,toolChoice:n,transforms:zn(x),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:F,onStepFinish:R,onStart:q,onStepStart:z,onToolCallStart:N,onToolCallFinish:re,now:pe,generateId:Q,experimental_context:Y,experimental_toolApprovalSecret:V,download:_,include:L})}function gO(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 fO=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:w,repairToolCall:S,stopConditions:y,output:x,providerOptions:_,prepareStep:C,includeRawChunks:I,now:b,generateId:E,timeout:F,stopWhen:R,originalAbortSignal:q,onChunk:z,onError:N,onFinish:re,onAbort:Y,onStepFinish:V,onStart:L,onStepStart:pe,onToolCallStart:Q,onToolCallFinish:k,experimental_context:X,experimental_toolApprovalSecret:J,download:H,include:K}){this._totalUsage=new jn,this._finishReason=new jn,this._rawFinishReason=new jn,this._steps=new jn,this.outputSpecification=x,this.includeRawChunks=I,this.tools=g;let B=kb()(t==null?void 0:t.integrations),G,Z=[],A=[],O=void 0,W=void 0,P=void 0,U={},me=[],ee=[],ue,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=Zc(se.error);if(Ha.isInstance(Je))ue=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(),U=se.request,me=se.warnings;if(se.type==="finish-step"){let Je=await $c({content:Z,tools:g}),Fe=new Ub({stepNumber:ee.length,model:T,...te,experimental_context:X,content:Z,finishReason:se.finishReason,rawFinishReason:se.rawFinishReason,usage:se.usage,warnings:me,request:U,response:{...se.response,messages:[...A,...Je]},providerMetadata:se.providerMetadata});await mr({event:Fe,callbacks:[V,B.onStepFinish]}),gn({warnings:me,provider:T.provider,model:T.modelId}),ee.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(ee.length===0||ue!=null){let Be=(a==null?void 0:a.aborted)?a.reason:ue!=null?ue:new Ha({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:Mc();ut._finishReason.resolve(Fe),ut._rawFinishReason.resolve(W),ut._totalUsage.resolve(lt),ut._steps.resolve(ee);let Oe=ee[ee.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:ee},callbacks:[re,B.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=cO();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:ee}),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(gO(x!=null?x:Ka())).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 Vc({system:d,prompt:m,messages:p,allowSystemInMessages:f});await mr({event:{model:T,system:d,prompt:m,messages:p,tools:g,toolChoice:h,activeTools:w,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:F,headers:n,providerOptions:_,stopWhen:R,output:x,abortSignal:q,include:K,...te,experimental_context:X},callbacks:[L,B.onStart]});let ht=Re.messages,Vt=[],{approvedToolApprovals:sr,deniedToolApprovals:lr}=Eb({messages:ht});if(lr.length>0||sr.length>0){let{approvedToolApprovals:Je,deniedToolApprovals:Fe}=await Nb({approvedToolApprovals:sr.filter((Ce)=>!Ce.toolCall.providerExecuted),tools:g,messages:ht,experimental_context:X,toolApprovalSecret:J}),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 Yc({toolCall:ot.toolCall,tools:g,tracer:_r,telemetry:t,messages:ht,abortSignal:a,experimental_context:X,stepNumber:ee.length,model:T,onToolCallStart:[Q,B.onToolCallStart],onToolCallFinish:[k,B.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=Nc({abortController:l,label:"Step",timeoutMs:s}),Ur=void 0;function aa(){if(Ur!=null)clearTimeout(Ur);Ur=Nc({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:ee,stepNumber:ee.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 Wc({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:H}),sa=(Ce=yt==null?void 0:yt.activeTools)!=null?Ce:w,{toolChoice:In,tools:Lo}=await Sb({tools:g,toolChoice:(ot=yt==null?void 0:yt.toolChoice)!=null?ot:h,activeTools:sa});X=(ct=yt==null?void 0:yt.experimental_context)!=null?ct:X;let Qs=(It=yt==null?void 0:yt.messages)!=null?It:Sr,Xs=(Pt=yt==null?void 0:yt.system)!=null?Pt:Re.system,Fo=Qa(_,yt==null?void 0:yt.providerOptions);await mr({event:{stepNumber:ee.length,model:ln,system:Xs,messages:Qs,tools:g,toolChoice:In,activeTools:sa,steps:[...ee],providerOptions:Fo,timeout:F,headers:n,stopWhen:R,output:x,abortSignal:q,include:K,...te,experimental_context:X},callbacks:[pe,B.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:()=>Kc(Hn)},"ai.prompt.tools":{input:()=>Lo==null?void 0:Lo.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:Lo,toolChoice:In,responseFormat:await(x==null?void 0:x.responseFormat),prompt:Hn,providerOptions:Fo,abortSignal:a,headers:n,includeRawChunks:Bt})})})),la=uO({tools:g,generatorStream:Me,tracer:_r,telemetry:t,system:d,messages:Sr,repairToolCall:S,abortSignal:a,experimental_context:X,toolApprovalSecret:J,generateId:E,stepNumber:ee.length,model:ln,onToolCallStart:[Q,B.onToolCallStart],onToolCallFinish:[k,B.onToolCallFinish]}),ca=((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,gp=!1,jt=Mc(),fp,hp=!0,xr={id:E(),timestamp:new Date,modelId:T.modelId},i0="";ut.addStream(la.pipeThrough(new TransformStream({async transform(be,_t){var Jo,Ho,Wo,Vo,Zo;if(aa(),be.type==="stream-start"){Wn=be.warnings;return}if(hp){let St=b()-Bo;hp=!1,Ct.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":St}),Ct.setAttributes({"ai.response.msToFirstChunk":St}),_t.enqueue({type:"start-step",request:ca,warnings:Wn!=null?Wn:[]})}let Zn=be.type;if(pO[Zn])gp=!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}),i0+=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,fp=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&&!gp){be.enqueue({type:"error",error:new Ha({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:fp,response:{...xr,headers:Mt==null?void 0:Mt.headers}});let Kn=Rb(lt,jt);await G.promise;let el=ee[ee.length-1];try{Ct.setAttributes(await et({telemetry:t,attributes:{"ai.response.text":{output:()=>el.text},"ai.response.reasoning":{output:()=>el.reasoningText},"ai.response.providerMetadata":JSON.stringify(el.providerMetadata)}}))}catch(kt){}finally{Ct.end()}let yp=cn.filter((kt)=>kt.providerExecuted!==!0),a0=un.filter((kt)=>kt.providerExecuted!==!0);for(let kt of cn){if(kt.providerExecuted!==!0)continue;let tl=g==null?void 0:g[kt.toolName];if((tl==null?void 0:tl.type)==="provider"&&tl.supportsDeferredResults){if(!un.some((rl)=>(rl.type==="tool-result"||rl.type==="tool-error")&&rl.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(),(yp.length>0&&a0.length===yp.length||Ae.size>0)&&!await $b({stopConditions:y,steps:ee})){Fe.push(...await $c({content:ee[ee.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:Mc()})}}).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 lO({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:Ka()).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?rO({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(Gb({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}={}){sO({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){eO({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 tO({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 Xj({textStream:this.textStream,...e})}},Jb=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 tu({...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 mO({...await this.prepareCall(i),abortSignal:e,timeout:t,experimental_transform:n,onStepFinish:this.mergeOnStepFinishCallbacks(o)})}};function h6({execute:e,onError:t=()=>"An error occurred.",originalMessages:n,onStepFinish:o,onFinish:i,generateId:a=qe}){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){}}),Gb({stream:c,messageId:a(),originalMessages:n,onStepFinish:o,onFinish:i,onError:t})}var Gt=r.record(r.string(),Un.optional()),b6=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 Hb({model:e,value:t,providerOptions:n,maxRetries:o,abortSignal:i,headers:a,experimental_telemetry:s}){let l=hb(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:w,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 x,_;let C=await l.doEmbed({values:[t],abortSignal:i,headers:d,providerOptions:n}),I=C.embeddings[0],b=(x=C.usage)!=null?x:{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 hO({value:t,embedding:g,usage:h,warnings:v,providerMetadata:S,response:w})}})}var hO=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 bv(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 Wb({model:e,values:t,maxParallelCalls:n=1/0,maxRetries:o,abortSignal:i,headers:a,providerOptions:s,experimental_telemetry:l}){let c=hb(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,w]=await Promise.all([c.maxEmbeddingsPerCall,c.supportsParallelCalls]);if(v==null||v===1/0){let{embeddings:E,usage:F,warnings:R,response:q,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}),L=V.embeddings,pe=(re=V.usage)!=null?re:{tokens:NaN};return N.setAttributes(await et({telemetry:l,attributes:{"ai.embeddings":{output:()=>L.map((Q)=>JSON.stringify(Q))},"ai.usage.tokens":pe.tokens}})),{embeddings:L,usage:pe,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":F.tokens}})),gn({warnings:R,provider:c.provider,model:c.modelId}),new _v({values:t,embeddings:E,usage:F,warnings:R,providerMetadata:z,responses:[q]})}let S=bv(t,v),y=[],x=[],_=[],C=0,I,b=bv(S,w?n:1);for(let E of b){let F=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((q)=>JSON.stringify(q))}}}),tracer:f,fn:async(q)=>{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 q.setAttributes(await et({telemetry:l,attributes:{"ai.embeddings":{output:()=>Y.map((L)=>JSON.stringify(L))},"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 F)if(y.push(...R.embeddings),x.push(...R.warnings),_.push(R.response),C+=R.usage.tokens,R.providerMetadata)if(!I)I={...R.providerMetadata};else for(let[q,z]of Object.entries(R.providerMetadata))I[q]={...(h=I[q])!=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:x,provider:c.provider,model:c.modelId}),new _v({values:t,embeddings:y,usage:{tokens:C},warnings:x,providerMetadata:I,responses:_})}})}var _v=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 ru({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=dj(e),g=it(d!=null?d:{},`ai/${vo}`),{retry:h}=bo({maxRetries:c,abortSignal:u}),v=(m=o!=null?o:await vO(f))!=null?m:1,w=Math.ceil(n/v),S=Array.from({length:w},(E,F)=>{if(F<w-1)return v;let R=n%v;return R===0?v:R}),y=await Promise.all(S.map(async(E)=>h(()=>{let{prompt:F,files:R,mask:q}=bO(t);return f.doGenerate({prompt:F,files:R,mask:q,n:E,abortSignal:u,headers:g,size:i,aspectRatio:a,seed:s,providerOptions:l!=null?l:{}})}))),x=[],_=[],C=[],I={},b={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};for(let E of y){if(x.push(...E.images.map((F)=>{var R;return new Qc({data:F,mediaType:(R=Za({data:F,signatures:Va}))!=null?R:"image/png"})})),_.push(...E.warnings),E.usage!=null)b=Dj(b,E.usage);if(E.providerMetadata)for(let[F,R]of Object.entries(E.providerMetadata))if(F==="gateway"){let q=I[F];if(q!=null&&typeof q==="object")I[F]={...q,...R};else I[F]=R;let z=I[F].images;if(Array.isArray(z)&&z.length===0)delete I[F].images}else(p=I[F])!=null||(I[F]={images:[]}),I[F].images.push(...E.providerMetadata[F].images);C.push(E.response)}if(gn({warnings:_,provider:f.provider,model:f.modelId}),!x.length)throw new PM({responses:C});return new yO({images:x,warnings:_,responses:C,providerMetadata:I,usage:b})}var yO=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 vO(e){if(!(e.maxImagesPerCall instanceof Function))return e.maxImagesPerCall;return e.maxImagesPerCall({modelId:e.modelId})}function bO(e){if(typeof e==="string")return{prompt:e,files:void 0,mask:void 0};return{prompt:e.text,files:e.images.map(Sv),mask:e.mask?Sv(e.mask):void 0}}function Sv(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}=bb(e);if(o!=null){let i=wt(o);return{type:"file",data:i,mediaType:n||Za({data:i,signatures:Va})||"image/png"}}}let t=hj(e);return{type:"file",data:t,mediaType:Za({data:t,signatures:Va})||"image/png"}}var _O={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"})}},SO=(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"})}}),wO=(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)||!cl(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)||!cl(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}`)}}})))}}),xO=(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 TO({output:e,schema:t,enumValues:n}){switch(e){case"object":return SO(Lt(t));case"array":return wO(Lt(t));case"enum":return xO(n);case"no-schema":return _O;default:throw Error(`Unsupported output: ${e}`)}}async function wv(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 IO(e,t,n,o){try{return await wv(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 wv(a,t,o)}throw i}}function CO({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 kO=Er({prefix:"aiobj",size:24});async function Vb(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=kO,currentDate:h=()=>new Date}={},...v}=e,w=ki(t),S="enum"in e?e.enum:void 0,{schema:y,schemaDescription:x,schemaName:_}="schema"in e?e:{};CO({output:n,schema:y,schemaName:_,schemaDescription:x,enumValues:S});let{maxRetries:C,retry:I}=bo({maxRetries:l,abortSignal:c}),b=TO({output:n,schema:y,enumValues:S}),E=Ri(v),F=it(u!=null?u:{},`ai/${vo}`),R=Ai({model:w,telemetry:m,headers:F,settings:{...E,maxRetries:C}}),q=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":x,"ai.settings.output":b.type}}),tracer:q,fn:async(N)=>{var re;let Y,V,L,pe,Q,k,X,J,H=await Vc({system:o,prompt:i,messages:a,allowSystemInMessages:s}),K=await Wc({prompt:H,supportedUrls:await w.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:()=>Kc(K)},"gen_ai.system":w.provider,"gen_ai.request.model":w.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:q,fn:async(G)=>{var Z,A,O,W,P,U,me,ee;let ue=await w.doGenerate({responseFormat:{type:"json",schema:z,name:_,description:x},...Ri(v),prompt:K,providerOptions:f,abortSignal:c,headers:F}),Ae={id:(A=(Z=ue.response)==null?void 0:Z.id)!=null?A:g(),timestamp:(W=(O=ue.response)==null?void 0:O.timestamp)!=null?W:h(),modelId:(U=(P=ue.response)==null?void 0:P.modelId)!=null?U:w.modelId,headers:(me=ue.response)==null?void 0:me.headers,body:(ee=ue.response)==null?void 0:ee.body},Ke=zc(ue.content),nt=Dc(ue.content);if(Ke===void 0)throw new Ft({message:"No object generated: the model did not return a response.",response:Ae,usage:Ei(ue.usage),finishReason:ue.finishReason.unified});return G.setAttributes(await et({telemetry:m,attributes:{"ai.response.finishReason":ue.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(ue.providerMetadata),"ai.usage.promptTokens":ue.usage.inputTokens.total,"ai.usage.completionTokens":ue.usage.outputTokens.total,"gen_ai.response.finish_reasons":[ue.finishReason.unified],"gen_ai.response.id":Ae.id,"gen_ai.response.model":Ae.modelId,"gen_ai.usage.input_tokens":ue.usage.inputTokens.total,"gen_ai.usage.output_tokens":ue.usage.outputTokens.total}})),{...ue,objectText:Ke,reasoning:nt,responseData:Ae}}}));Y=D.objectText,V=D.finishReason.unified,L=Ei(D.usage),pe=D.warnings,X=D.providerMetadata,k=(re=D.request)!=null?re:{},Q=D.responseData,J=D.reasoning,gn({warnings:pe,provider:w.provider,model:w.modelId});let B=await IO(Y,b,d,{response:Q,usage:L,finishReason:V});return N.setAttributes(await et({telemetry:m,attributes:{"ai.response.finishReason":V,"ai.response.object":{output:()=>JSON.stringify(B)},"ai.response.providerMetadata":JSON.stringify(X),"ai.usage.promptTokens":L.inputTokens,"ai.usage.completionTokens":L.outputTokens}})),new RO({object:B,reasoning:J,finishReason:V,usage:L,warnings:pe,request:k,response:Q,providerMetadata:X})}})}catch(N){throw Zc(N)}}var RO=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 Zb(e){return({url:t,abortSignal:n})=>vb({url:t,maxBytes:e==null?void 0:e.maxBytes,abortSignal:n})}var E6=Er({prefix:"aiobj",size:24});var A6=Zb();var EO="AI_NoSuchProviderError",AO=`vercel.ai.error.${EO}`,PO=Symbol.for(AO),MO;MO=PO;var P6=Zb();class Xa extends Error{constructor(e){super("AI object generation failed: invalid structured output",{cause:e});this.name="AIOutputValidationError"}}var jO=[[/^claude/,"anthropic"],[/^gpt-/,"openai"],[/^o[13]-/,"openai"],[/^gemini/,"google"],[/^llama/,"ollama"],[/^mistral/,"ollama"],[/^phi-/,"ollama"],[/^qwen/,"ollama"]];function Kb(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=Kb(e);if(t)return t;for(let[n,o]of jO)if(n.test(e))return{provider:o,modelId:e};return{provider:"anthropic",modelId:e}}function nu(e){if(!e)return"anthropic";return Ni(e).provider}var OO=[[/^gpt-image/,"openai"],[/^dall-e/,"openai"],[/^gemini/,"google"]],NO="gpt-image-1.5";function ou(e){if(!e)return{provider:"openai",modelId:NO};let t=Kb(e);if(t)return t;for(let[n,o]of OO)if(n.test(e))return{provider:o,modelId:e};return{provider:"openai",modelId:e}}var DO=/^(gpt-5|o[1-9])(?:[.-]|$)/;function zO(e){if(e.provider!=="openai")return!0;return!DO.test(e.modelId)}function Di(e){if(!e)return{provider:"anthropic",supportsTemperature:!0};let t=Ni(e);return{provider:t.provider,supportsTemperature:zO(t)}}var UO="3.0.95",$O=j(()=>M(r.object({type:r.literal("error"),error:r.object({type:r.string(),message:r.string()})}))),Yb=Qe({errorSchema:$O,errorToMessage:(e)=>e.error.message}),s_=r.object({type:r.string(),category:r.string().nullish(),explanation:r.string().nullish(),recommended_model:r.string().nullish()}),qO=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:s_.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()}))),LO=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:s_.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")})]))),FO=j(()=>M(r.object({signature:r.string().optional(),redactedData:r.string().optional()}))),Qb=r.object({citations:r.object({enabled:r.boolean()}).optional(),title:r.string().optional(),context:r.string().optional()}),Xb=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()}),e_=4;function BO(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 lu=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(e,t){let n=BO(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>e_){this.warnings.push({type:"unsupported",feature:"cacheControl breakpoint limit",details:`Maximum ${e_} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return n}getWarnings(){return this.warnings}},GO=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()}))),l_=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()})]))),JO=j(()=>M(r.object({}).strict())),HO=Te({id:"anthropic.advisor_20260301",inputSchema:JO,outputSchema:l_,supportsDeferredResults:!0}),WO=(e)=>HO(e),VO=j(()=>M(r.object({maxCharacters:r.number().optional()}))),ZO=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()}))),KO=Ge({id:"anthropic.text_editor_20250728",inputSchema:ZO}),YO=(e={})=>KO(e),QO=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()}))),XO=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")})))),eN=j(()=>M(r.object({query:r.string()}))),tN=Te({id:"anthropic.web_search_20260209",inputSchema:eN,outputSchema:XO,supportsDeferredResults:!0}),rN=(e={})=>tN(e),nN=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()}))),c_=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")})))),oN=j(()=>M(r.object({query:r.string()}))),iN=Te({id:"anthropic.web_search_20250305",inputSchema:oN,outputSchema:c_,supportsDeferredResults:!0}),aN=(e={})=>iN(e),sN=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()}))),lN=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()}))),cN=j(()=>M(r.object({url:r.string()}))),uN=Te({id:"anthropic.web_fetch_20260209",inputSchema:cN,outputSchema:lN,supportsDeferredResults:!0}),dN=(e={})=>uN(e),pN=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()}))),u_=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()}))),mN=j(()=>M(r.object({url:r.string()}))),gN=Te({id:"anthropic.web_fetch_20250910",inputSchema:mN,outputSchema:u_,supportsDeferredResults:!0}),fN=(e={})=>gN(e);async function hN({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 lu;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,w=(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,...w?{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((x)=>x.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:VO});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:pN});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:sN});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:nN});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:QO});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:GO});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 t_({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 d_=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([])}))),yN=j(()=>M(r.object({code:r.string()}))),vN=Te({id:"anthropic.code_execution_20250522",inputSchema:yN,outputSchema:d_}),bN=(e={})=>vN(e),p_=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()})]))),_N=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()})])]))),SN=Te({id:"anthropic.code_execution_20250825",inputSchema:_N,outputSchema:p_,supportsDeferredResults:!0}),wN=(e={})=>SN(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("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()})]))),xN=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()})])]))),TN=Te({id:"anthropic.code_execution_20260120",inputSchema:xN,outputSchema:m_,supportsDeferredResults:!0}),IN=(e={})=>TN(e),g_=j(()=>M(r.array(r.object({type:r.literal("tool_reference"),toolName:r.string()})))),CN=j(()=>M(r.object({pattern:r.string(),limit:r.number().optional()}))),kN=Te({id:"anthropic.tool_search_regex_20251119",inputSchema:CN,outputSchema:g_,supportsDeferredResults:!0}),RN=(e={})=>kN(e);function EN(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 iu(e){return e instanceof URL||AN(e)}function AN(e){return typeof e==="string"&&/^https?:\/\//i.test(e)}function au(e){return e instanceof URL?e.toString():e}async function r_(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 PN({prompt:e,sendReasoning:t,warnings:n,cacheControlValidator:o,toolNameMapping:i}){var a,s,l,c,u,d,m,p,f,g,h,v,w,S,y,x,_,C,I,b,E;let F=new Set,R=MN(e),q=o||new lu,z=void 0,N=[];async function re(V){var L,pe;let Q=await Ue({provider:"anthropic",providerOptions:V,schema:Qb});return(pe=(L=Q==null?void 0:Q.citations)==null?void 0:L.enabled)!=null?pe:!1}async function Y(V){let L=await Ue({provider:"anthropic",providerOptions:V,schema:Qb});return{title:L==null?void 0:L.title,context:L==null?void 0:L.context}}for(let V=0;V<R.length;V++){let L=R[V],pe=V===R.length-1,Q=L.type;switch(Q){case"system":{let k=L.messages.map(({content:X,providerOptions:J})=>({type:"text",text:X,cache_control:q.getCacheControl(J,{type:"system message",canCache:!0})}));if(z==null)z=k;else N.push({role:"system",content:k}),F.add("mid-conversation-system-2026-04-07");break}case"user":{let k=[];for(let X of L.messages){let{role:J,content:H}=X;switch(J){case"user":{for(let K=0;K<H.length;K++){let D=H[K],B=K===H.length-1,G=(a=q.getCacheControl(D.providerOptions,{type:"user message part",canCache:!0}))!=null?a:B?q.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:iu(D.data)?{type:"url",url:au(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"){F.add("pdfs-2024-09-25");let Z=await re(D.providerOptions),A=await Y(D.providerOptions);k.push({type:"document",source:iu(D.data)?{type:"url",url:au(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:iu(D.data)?{type:"url",url:au(D.data)}:{type:"text",media_type:"text/plain",data:EN(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<H.length;K++){let D=H[K];if(D.type==="tool-approval-response")continue;let B=D.output,G="providerOptions"in B?B.providerOptions:B.type==="content"?(c=B.value.find((W)=>W.providerOptions!=null))==null?void 0:c.providerOptions:void 0,Z=K===H.length-1,A=(d=(u=q.getCacheControl(D.providerOptions,{type:"tool result part",canCache:!0}))!=null?u:q.getCacheControl(G,{type:"tool result output",canCache:!0}))!=null?d:Z?q.getCacheControl(X.providerOptions,{type:"tool result message",canCache:!0}):void 0,O;switch(B.type){case"content":O=B.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 F.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 U=(P=W.providerOptions)==null?void 0:P.anthropic;if((U==null?void 0:U.type)==="tool-reference")return{type:"tool_reference",tool_name:U.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=B.value;break;case"execution-denied":O=(m=B.reason)!=null?m:"Tool call execution denied.";break;case"json":case"error-json":default:O=JSON.stringify(B.value);break}k.push({type:"tool_result",tool_use_id:D.toolCallId,content:O,is_error:B.type==="error-text"||B.type==="error-json"?!0:void 0,cache_control:A})}break}default:throw Error(`Unsupported role: ${J}`)}}N.push({role:"user",content:k});break}case"assistant":{let k=[],X=new Set;for(let J=0;J<L.messages.length;J++){let H=L.messages[J],K=J===L.messages.length-1,{content:D}=H;for(let B=0;B<D.length;B++){let G=D[B],Z=B===D.length-1,A=(p=q.getCacheControl(G.providerOptions,{type:"assistant message part",canCache:!0}))!=null?p:Z?q.getCacheControl(H.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:pe&&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:FO});if(O!=null)if(O.signature!=null)q.getCacheControl(G.providerOptions,{type:"thinking block",canCache:!1}),k.push({type:"thinking",thinking:G.text,signature:O.signature});else if(O.redactedData!=null)q.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=(w=(v=G.providerOptions)==null?void 0:v.anthropic)==null?void 0:w.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,...ee}=G.input;k.push({type:"server_tool_use",id:G.toolCallId,name:"code_execution",input:ee,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(U){}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:(x=P.errorCode)!=null?x:"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:d_});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:m_});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:p_});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 r_(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:u_});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 r_(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:c_});k.push({type:"web_search_tool_result",tool_use_id:G.toolCallId,content:P.map((U)=>({url:U.url,title:U.title,page_age:U.pageAge,encrypted_content:U.encryptedContent,type:U.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 U=(await Ee({value:W.value,schema:g_})).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:U},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:l_});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:jN(k)});break}default:throw Error(`content type: ${Q}`)}}return{prompt:{system:z,messages:N},betas:F}}function MN(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 jN(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 su({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 f_=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),ON=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","minItems","maxItems","uniqueItems","minProperties","maxProperties","not"];function NN(e){return h_(e)}function fn(e){if(typeof e==="boolean"||!$N(e))return e;return h_(e)}function h_(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"&&f_.has(e.format))t.format=e.format;let o=DN(e);if(o!=null)t.description=t.description==null?o:`${t.description}
|
|
71
|
-
${o}`;return t}function DN(e){let t=ON.flatMap((n)=>{let o=e[n];if(o==null||o===!1)return[];return`${zN(n)}: ${UN(o)}`});if(typeof e.format==="string"&&!f_.has(e.format))t.push(`format: ${e.format}`);return t.length===0?void 0:`${t.join("; ")}.`}function zN(e){return e.replace(/[A-Z]/g,(t)=>` ${t.toLowerCase()}`)}function UN(e){if(typeof e==="string")return e;return JSON.stringify(e)}function $N(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function n_(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 qN=class{constructor(e,t){this.specificationVersion="v3";var n;this.modelId=e,this.config=t,this.generateId=(n=t.generateId)!=null?n:qe}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,w,S,y,x,_,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 F=this.providerOptionsName,R=await Ue({provider:"anthropic",providerOptions:f,schema:Xb}),q=F!=="anthropic"?await Ue({provider:F,providerOptions:f,schema:Xb}):null,z=q!=null,N=Object.assign({},R!=null?R:{},q!=null?q:{}),{maxOutputTokens:re,supportsStructuredOutput:Y,rejectsSamplingParameters:V,isKnownModel:L}=LN(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 pe=L||this.modelId.startsWith("claude-"),Q=((h=this.config.supportsNativeStructuredOutput)!=null?h:!0)&&Y,k=((v=this.config.supportsStrictTools)!=null?v:!0)&&Y,X=(w=N==null?void 0:N.structuredOutputMode)!=null?w:"auto",J=X==="outputFormat"||X==="auto"&&Q,H=(u==null?void 0:u.type)==="json"&&u.schema!=null&&!J?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:u.schema}:void 0,K=N==null?void 0:N.contextManagement,D=new lu,B=Ea({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 PN({prompt:t,sendReasoning:(S=N==null?void 0:N.sendReasoning)!=null?S:!0,warnings:E,cacheControlValidator:D,toolNameMapping:B}),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"?(x=N==null?void 0:N.thinking)==null?void 0:x.budgetTokens:void 0,U=A==="adaptive"?(_=N==null?void 0:N.thinking)==null?void 0:_.display:void 0,me=n!=null?n:re,ee={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},...U!=null&&{display:U}}},...((N==null?void 0:N.effort)||(N==null?void 0:N.taskBudget)||J&&(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}}},...J&&(u==null?void 0:u.type)==="json"&&u.schema!=null&&{format:{type:"json_schema",schema:NN(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."}),ee.thinking={type:"enabled",budget_tokens:1024},P=1024;if(ee.temperature!=null)ee.temperature=void 0,E.push({type:"unsupported",feature:"temperature",details:"temperature is not supported when thinking is enabled"});if(a!=null)ee.top_k=void 0,E.push({type:"unsupported",feature:"topK",details:"topK is not supported when thinking is enabled"});if(i!=null)ee.top_p=void 0,E.push({type:"unsupported",feature:"topP",details:"topP is not supported when thinking is enabled"});ee.max_tokens=me+(P!=null?P:0)}else if(pe&&i!=null&&o!=null)E.push({type:"unsupported",feature:"topP",details:"topP is not supported when temperature is set. topP is ignored."}),ee.top_p=void 0;if(L&&ee.max_tokens>re){if(n!=null)E.push({type:"unsupported",feature:"maxOutputTokens",details:`${ee.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${re} max output tokens. The max output tokens have been limited to ${re}.`});ee.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 ue=g&&((I=N==null?void 0:N.toolStreaming)!=null?I:!0),{tools:Ae,toolChoice:Ke,toolWarnings:nt,betas:At}=await hN(H!=null?{tools:[...m!=null?m:[],H],toolChoice:{type:"required"},disableParallelToolUse:!0,cacheControlValidator:D,supportsStructuredOutput:!1,supportsStrictTools:k,defaultEagerInputStreaming:ue}:{tools:m!=null?m:[],toolChoice:p,disableParallelToolUse:N==null?void 0:N.disableParallelToolUse,cacheControlValidator:D,supportsStructuredOutput:Q,supportsStrictTools:k,defaultEagerInputStreaming:ue}),Dr=D.getWarnings();return{args:{...ee,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:H!=null,toolNameMapping:B,providerOptionsName:F,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=o_(c.tools),{responseHeaders:w,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:Yb,successfulResponseHandler:xe(qO),abortSignal:e.abortSignal,fetch:this.config.fetch}),x=[],_={},C={},I=!1;for(let b of S.content)switch(b.type){case"text":{if(!m){if(x.push({type:"text",text:b.text}),b.citations)for(let E of b.citations){let F=n_(E,h,this.generateId);if(F)x.push(F)}}break}case"thinking":{x.push({type:"reasoning",text:b.thinking,providerMetadata:{anthropic:{signature:b.signature}}});break}case"redacted_thinking":{x.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:b.data}}});break}case"compaction":{x.push({type:"text",text:b.content,providerMetadata:{anthropic:{type:"compaction"}}});break}case"tool_use":{if(m&&b.name==="json")I=!0,x.push({type:"text",text:JSON.stringify(b.input)});else{let F=b.caller,R=F?{type:F.type,toolId:"tool_id"in F?F.tool_id:void 0}:void 0;x.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")x.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;x.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,x.push({type:"tool-call",toolCallId:b.id,toolName:p.toCustomToolName(b.name),input:JSON.stringify(b.input),providerExecuted:!0});else if(b.name==="advisor")x.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}}},x.push(_[b.id]);break}case"mcp_tool_result":{x.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}),x.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")x.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)){x.push({type:"tool-result",toolCallId:b.tool_use_id,toolName:p.toCustomToolName("web_search"),result:b.content.map((E)=>{var F;return{url:E.url,title:E.title,pageAge:(F=E.page_age)!=null?F:null,encryptedContent:E.encrypted_content,type:E.type}})});for(let E of b.content)x.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 x.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")x.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")x.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")x.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":{x.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 F=p.toCustomToolName("tool_search_tool_bm25"),R=p.toCustomToolName("tool_search_tool_regex");if(F!=="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")x.push({type:"tool-result",toolCallId:b.tool_use_id,toolName:p.toCustomToolName(E),result:b.content.tool_references.map((F)=>({type:F.type,toolName:F.tool_name}))});else x.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")x.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")x.push({type:"tool-result",toolCallId:b.tool_use_id,toolName:E,result:{type:"advisor_redacted_result",encryptedContent:b.content.encrypted_content}});else x.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:x,finishReason:{unified:su({finishReason:S.stop_reason,isJsonResponseFromTool:I}),raw:(a=S.stop_reason)!=null?a:void 0},usage:t_({usage:S.usage}),request:{body:c},response:{id:(s=S.id)!=null?s:void 0,modelId:(l=S.model)!=null?l:void 0,headers:w,body:y},warnings:u,providerMetadata:(()=>{var b,E,F,R,q;let z=a_(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=(F=S.container.skills)==null?void 0:F.map((Y)=>({type:Y.type,skillId:Y.skill_id,version:Y.version})))!=null?R:null}:null,contextManagement:(q=i_(S.context_management))!=null?q: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=o_(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:Yb,successfulResponseHandler:Dt(LO),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},w={},S={},y={},x=null,_=void 0,C=null,I=null,b=void 0,E=null,F=!1,R=void 0,q=this.generateId,z=g.pipeThrough(new TransformStream({start(V){V.enqueue({type:"stream-start",warnings:i})},transform(V,L){var pe,Q,k,X,J,H,K,D,B,G,Z,A,O,W;if(e.includeRawChunks)L.enqueue({type:"raw",rawValue:V.rawValue});if(!V.success){L.enqueue({type:"error",error:V.error});return}let P=V.value;switch(P.type){case"ping":return;case"content_block_start":{let U=P.content_block,me=U.type;if(me==="fallback")return;switch(R=me,me){case"text":{if(s)return;w[P.index]={type:"text"},L.enqueue({type:"text-start",id:String(P.index)});return}case"thinking":{w[P.index]={type:"reasoning"},L.enqueue({type:"reasoning-start",id:String(P.index)});return}case"redacted_thinking":{w[P.index]={type:"reasoning"},L.enqueue({type:"reasoning-start",id:String(P.index),providerMetadata:{anthropic:{redactedData:U.data}}});return}case"compaction":{w[P.index]={type:"text"},L.enqueue({type:"text-start",id:String(P.index),providerMetadata:{anthropic:{type:"compaction"}}});return}case"tool_use":{if(s&&U.name==="json")F=!0,w[P.index]={type:"text"},L.enqueue({type:"text-start",id:String(P.index)});else{let ue=U.caller,Ae=ue?{type:ue.type,toolId:"tool_id"in ue?ue.tool_id:void 0}:void 0,nt=U.input&&Object.keys(U.input).length>0?JSON.stringify(U.input):"";w[P.index]={type:"tool-call",toolCallId:U.id,toolName:U.name,input:nt,firstDelta:nt.length===0,...Ae&&{caller:Ae}},L.enqueue({type:"tool-input-start",id:U.id,toolName:U.name})}return}case"server_tool_use":{if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(U.name)){let ee=U.name==="text_editor_code_execution"||U.name==="bash_code_execution"?"code_execution":U.name,ue=U.name==="text_editor_code_execution"||U.name==="bash_code_execution"?U.name:U.name==="code_execution"?"programmatic-tool-call":void 0,Ae=l.toCustomToolName(ee),Ke=U.input!=null&&typeof U.input==="object"&&Object.keys(U.input).length>0?JSON.stringify(U.input):"";w[P.index]={type:"tool-call",toolCallId:U.id,toolName:Ae,input:Ke,providerExecuted:!0,...m&&ee==="code_execution"?{dynamic:!0}:{},firstDelta:Ke.length===0,providerToolName:ee,providerToolInputType:ue},L.enqueue({type:"tool-input-start",id:U.id,toolName:Ae,providerExecuted:!0,...m&&ee==="code_execution"?{dynamic:!0}:{}})}else if(U.name==="tool_search_tool_regex"||U.name==="tool_search_tool_bm25"){y[U.id]=U.name;let ee=l.toCustomToolName(U.name);w[P.index]={type:"tool-call",toolCallId:U.id,toolName:ee,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:U.name},L.enqueue({type:"tool-input-start",id:U.id,toolName:ee,providerExecuted:!0})}else if(U.name==="advisor"){let ee=l.toCustomToolName("advisor");w[P.index]={type:"tool-call",toolCallId:U.id,toolName:ee,input:"{}",providerExecuted:!0,firstDelta:!0,providerToolName:U.name},L.enqueue({type:"tool-input-start",id:U.id,toolName:ee,providerExecuted:!0})}return}case"web_fetch_tool_result":{if(U.content.type==="web_fetch_result")d.push({title:(pe=U.content.content.title)!=null?pe:U.content.url,mediaType:U.content.content.source.media_type}),L.enqueue({type:"tool-result",toolCallId:U.tool_use_id,toolName:l.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:U.content.url,retrievedAt:U.content.retrieved_at,content:{type:U.content.content.type,title:U.content.content.title,citations:U.content.content.citations,source:{type:U.content.content.source.type,mediaType:U.content.content.source.media_type,data:U.content.content.source.data}}}});else if(U.content.type==="web_fetch_tool_result_error")L.enqueue({type:"tool-result",toolCallId:U.tool_use_id,toolName:l.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:U.content.error_code}});return}case"web_search_tool_result":{if(Array.isArray(U.content)){L.enqueue({type:"tool-result",toolCallId:U.tool_use_id,toolName:l.toCustomToolName("web_search"),result:U.content.map((ee)=>{var ue;return{url:ee.url,title:ee.title,pageAge:(ue=ee.page_age)!=null?ue:null,encryptedContent:ee.encrypted_content,type:ee.type}})});for(let ee of U.content)L.enqueue({type:"source",sourceType:"url",id:q(),url:ee.url,title:ee.title,providerMetadata:{anthropic:{pageAge:(Q=ee.page_age)!=null?Q:null}}})}else L.enqueue({type:"tool-result",toolCallId:U.tool_use_id,toolName:l.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:U.content.error_code}});return}case"code_execution_tool_result":{if(U.content.type==="code_execution_result")L.enqueue({type:"tool-result",toolCallId:U.tool_use_id,toolName:l.toCustomToolName("code_execution"),result:{type:U.content.type,stdout:U.content.stdout,stderr:U.content.stderr,return_code:U.content.return_code,content:(k=U.content.content)!=null?k:[]}});else if(U.content.type==="encrypted_code_execution_result")L.enqueue({type:"tool-result",toolCallId:U.tool_use_id,toolName:l.toCustomToolName("code_execution"),result:{type:U.content.type,encrypted_stdout:U.content.encrypted_stdout,stderr:U.content.stderr,return_code:U.content.return_code,content:(X=U.content.content)!=null?X:[]}});else if(U.content.type==="code_execution_tool_result_error")L.enqueue({type:"tool-result",toolCallId:U.tool_use_id,toolName:l.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:U.content.error_code}});return}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{L.enqueue({type:"tool-result",toolCallId:U.tool_use_id,toolName:l.toCustomToolName("code_execution"),result:U.content});return}case"tool_search_tool_result":{let ee=y[U.tool_use_id];if(ee==null){let ue=l.toCustomToolName("tool_search_tool_bm25"),Ae=l.toCustomToolName("tool_search_tool_regex");if(ue!=="tool_search_tool_bm25")ee="tool_search_tool_bm25";else if(Ae!=="tool_search_tool_regex")ee="tool_search_tool_regex";else ee="tool_search_tool_regex"}if(U.content.type==="tool_search_tool_search_result")L.enqueue({type:"tool-result",toolCallId:U.tool_use_id,toolName:l.toCustomToolName(ee),result:U.content.tool_references.map((ue)=>({type:ue.type,toolName:ue.tool_name}))});else L.enqueue({type:"tool-result",toolCallId:U.tool_use_id,toolName:l.toCustomToolName(ee),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:U.content.error_code}});return}case"advisor_tool_result":{let ee=l.toCustomToolName("advisor");if(U.content.type==="advisor_result")L.enqueue({type:"tool-result",toolCallId:U.tool_use_id,toolName:ee,result:{type:"advisor_result",text:U.content.text}});else if(U.content.type==="advisor_redacted_result")L.enqueue({type:"tool-result",toolCallId:U.tool_use_id,toolName:ee,result:{type:"advisor_redacted_result",encryptedContent:U.content.encrypted_content}});else L.enqueue({type:"tool-result",toolCallId:U.tool_use_id,toolName:ee,isError:!0,result:{type:"advisor_tool_result_error",errorCode:U.content.error_code}});return}case"mcp_tool_use":{S[U.id]={type:"tool-call",toolCallId:U.id,toolName:U.name,input:JSON.stringify(U.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:U.server_name}}},L.enqueue(S[U.id]);return}case"mcp_tool_result":{L.enqueue({type:"tool-result",toolCallId:U.tool_use_id,toolName:S[U.tool_use_id].toolName,isError:U.is_error,result:U.content,dynamic:!0,providerMetadata:S[U.tool_use_id].providerMetadata});return}default:throw Error(`Unsupported content block type: ${me}`)}}case"content_block_stop":{if(w[P.index]!=null){let U=w[P.index];switch(U.type){case"text":{L.enqueue({type:"text-end",id:String(P.index)});break}case"reasoning":{L.enqueue({type:"reasoning-end",id:String(P.index)});break}case"tool-call":if(!(s&&U.toolName==="json")){L.enqueue({type:"tool-input-end",id:U.toolCallId});let ee=U.input===""?"{}":U.input;if(U.providerToolName==="code_execution")try{let ue=er(ee);if(ue!=null&&typeof ue==="object"&&"code"in ue&&!("type"in ue))ee=JSON.stringify({type:"programmatic-tool-call",...ue})}catch(ue){}L.enqueue({type:"tool-call",toolCallId:U.toolCallId,toolName:U.toolName,input:ee,providerExecuted:U.providerExecuted,...m&&U.providerToolName==="code_execution"?{dynamic:!0}:{},...U.caller&&{providerMetadata:{anthropic:{caller:U.caller}}}})}break}delete w[P.index]}R=void 0;return}case"content_block_delta":{let U=P.delta.type;switch(U){case"text_delta":{if(s)return;L.enqueue({type:"text-delta",id:String(P.index),delta:P.delta.text});return}case"thinking_delta":{L.enqueue({type:"reasoning-delta",id:String(P.index),delta:P.delta.thinking});return}case"signature_delta":{if(R==="thinking")L.enqueue({type:"reasoning-delta",id:String(P.index),delta:"",providerMetadata:{anthropic:{signature:P.delta.signature}}});return}case"compaction_delta":{if(P.delta.content!=null)L.enqueue({type:"text-delta",id:String(P.index),delta:P.delta.content});return}case"input_json_delta":{let me=w[P.index],ee=P.delta.partial_json;if(ee.length===0)return;if(F){if((me==null?void 0:me.type)!=="text")return;L.enqueue({type:"text-delta",id:String(P.index),delta:ee})}else{if((me==null?void 0:me.type)!=="tool-call")return;if(me.firstDelta&&me.providerToolInputType!=null)ee=`{"type": "${me.providerToolInputType}",${ee.substring(1)}`;L.enqueue({type:"tool-input-delta",id:me.toolCallId,delta:ee}),me.input+=ee,me.firstDelta=!1}return}case"citations_delta":{let me=P.delta.citation,ee=n_(me,d,q);if(ee)L.enqueue(ee);return}default:throw Error(`Unsupported delta type: ${U}`)}}case"message_start":{if(v.input_tokens=P.message.usage.input_tokens,v.cache_read_input_tokens=(J=P.message.usage.cache_read_input_tokens)!=null?J:0,v.cache_creation_input_tokens=(H=P.message.usage.cache_creation_input_tokens)!=null?H: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:su({finishReason:P.message.stop_reason,isJsonResponseFromTool:F}),raw:P.message.stop_reason};if(L.enqueue({type:"response-metadata",id:(D=P.message.id)!=null?D:void 0,modelId:(B=P.message.model)!=null?B:void 0}),P.message.content!=null)for(let U=0;U<P.message.content.length;U++){let me=P.message.content[U];if(me.type==="tool_use"){let ee=me.caller,ue=ee?{type:ee.type,toolId:"tool_id"in ee?ee.tool_id:void 0}:void 0;L.enqueue({type:"tool-input-start",id:me.id,toolName:me.name});let Ae=JSON.stringify((G=me.input)!=null?G:{});L.enqueue({type:"tool-input-delta",id:me.id,delta:Ae}),L.enqueue({type:"tool-input-end",id:me.id}),L.enqueue({type:"tool-call",toolCallId:me.id,toolName:me.name,input:Ae,...ue&&{providerMetadata:{anthropic:{caller:ue}}}})}}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:su({finishReason:P.delta.stop_reason,isJsonResponseFromTool:F}),raw:(Z=P.delta.stop_reason)!=null?Z:void 0},I=(A=P.delta.stop_sequence)!=null?A:null,b=a_(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((U)=>({type:U.type,skillId:U.skill_id,version:U.version})))!=null?W:null}:null,P.context_management)x=i_(P.context_management);_={..._,...P.usage};return}case"message_stop":{let U={usage:_!=null?_:null,cacheCreationInputTokens:C,stopSequence:I,...b!=null?{stopDetails:b}:{},iterations:v.iterations?v.iterations.map((ee)=>({type:ee.type,...ee.model!=null?{model:ee.model}:{},inputTokens:ee.input_tokens,outputTokens:ee.output_tokens,...ee.cache_creation_input_tokens?{cacheCreationInputTokens:ee.cache_creation_input_tokens}:{},...ee.cache_read_input_tokens?{cacheReadInputTokens:ee.cache_read_input_tokens}:{}})):null,container:E,contextManagement:x},me={anthropic:U};if(u&&c!=="anthropic")me[c]=U;L.enqueue({type:"finish",finishReason:h,usage:t_({usage:v,rawUsage:_}),providerMetadata:me});return}case"error":{L.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 L=V.value.error;throw new De({message:L.message,url:p,requestBodyValues:o,statusCode:L.type==="overloaded_error"?529:500,responseHeaders:f,responseBody:JSON.stringify(L),isRetryable:L.type==="overloaded_error"})}}finally{Y.cancel().catch(()=>{}),Y.releaseLock()}return{stream:re,request:{body:o},response:{headers:f}}}};function LN(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 o_(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 i_(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 a_(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 FN=j(()=>M(r.object({command:r.string(),restart:r.boolean().optional()}))),BN=Ge({id:"anthropic.bash_20241022",inputSchema:FN}),GN=j(()=>M(r.object({command:r.string(),restart:r.boolean().optional()}))),JN=Ge({id:"anthropic.bash_20250124",inputSchema:GN}),HN=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()}))),WN=Ge({id:"anthropic.computer_20241022",inputSchema:HN}),VN=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()}))),ZN=Ge({id:"anthropic.computer_20250124",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","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()}))),YN=Ge({id:"anthropic.computer_20251124",inputSchema:KN}),QN=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()})]))),XN=Ge({id:"anthropic.memory_20250818",inputSchema:QN}),eD=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()}))),tD=Ge({id:"anthropic.text_editor_20241022",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_20250124",inputSchema:rD}),oD=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()}))),iD=Ge({id:"anthropic.text_editor_20250429",inputSchema:oD}),aD=j(()=>M(r.array(r.object({type:r.literal("tool_reference"),toolName:r.string()})))),sD=j(()=>M(r.object({query:r.string(),limit:r.number().optional()}))),lD=Te({id:"anthropic.tool_search_bm25_20251119",inputSchema:sD,outputSchema:aD,supportsDeferredResults:!0}),cD=(e={})=>lD(e),uD={advisor_20260301:WO,bash_20241022:BN,bash_20250124:JN,codeExecution_20250522:bN,codeExecution_20250825:wN,codeExecution_20260120:IN,computer_20241022:WN,computer_20250124:ZN,computer_20251124:YN,memory_20250818:XN,textEditor_20241022:tD,textEditor_20250124:nD,textEditor_20250429:iD,textEditor_20250728:YO,webFetch_20250910:fN,webFetch_20260209:dN,webSearch_20250305:aN,webSearch_20260209:rN,toolSearchRegex_20251119:RN,toolSearchBm25_20251119:cD},y_="https://api.anthropic.com",v_=`${y_}/v1`;function dD(e){let t=mn(e);return t===y_?v_:t}function cu(e={}){var t,n;let o=(t=dD(Ar({settingValue:e.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"})))!=null?t:v_,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/${UO}`)},s=(c)=>{var u;return new qN(c,{provider:i,baseURL:o,headers:a,fetch:e.fetch,generateId:(u=e.generateId)!=null?u:qe,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 ll({modelId:c,modelType:"embeddingModel"})},l.textEmbeddingModel=l.embeddingModel,l.imageModel=(c)=>{throw new ll({modelId:c,modelType:"imageModel"})},l.tools=uD,l}var b_=cu();var hu=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:hu,errorToMessage:(e)=>e.error.message});function $_(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 yu({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(()=>{}),pD({frame:m,url:o,requestBodyValues:i,responseHeaders:a});if(n(d.value))return l}}finally{c.cancel().catch(()=>{}),c.releaseLock()}}function pD({frame:e,url:t,requestBodyValues:n,responseHeaders:o}){var i;let a=mD(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:gD(a),responseHeaders:o,responseBody:JSON.stringify(e),data:e})}function mD(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:__(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:__(o.code),type:typeof o.type==="string"?o.type:void 0,frame:e}:void 0}function gD(e){if(typeof e.code==="number"&&S_(e.code))return e.code;if(typeof e.code==="string"&&/^\d{3}$/.test(e.code)){let n=Number(e.code);if(S_(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 __(e){return typeof e==="string"||typeof e==="number"?e:void 0}function S_(e){return Number.isInteger(e)&&e>=400&&e<=599}function w_(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 fD(e){return JSON.stringify(e===void 0?{}:e)}function hD({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:fD(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 uu({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 x_(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 yD=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()}))),vD=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()}),hu]))),bD=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 _D({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 SD=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,w;let S=[],y=(f=await Ue({provider:"openai",providerOptions:p,schema:bD}))!=null?f:{},x=$_(this.modelId),_=(g=y.forceReasoning)!=null?g:x.isReasoningModel;if(i!=null)S.push({type:"unsupported",feature:"topK"});let{messages:C,warnings:I}=hD({prompt:e,systemMessageMode:(h=y.systemMessageMode)!=null?h:_?"developer":x.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:(w=c.name)!=null?w:"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"||!x.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"&&!x.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"&&!x.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:F,toolChoice:R,toolWarnings:q}=_D({tools:d,toolChoice:m});return{args:{...E,tools:F,tool_choice:R},warnings:[...S,...q]}}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(yD),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:qe(),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:qe(),url:y.url_citation.url,title:y.url_citation.title});let v=(i=m.usage)==null?void 0:i.completion_tokens_details,w=(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:x_(f.finish_reason),raw:(l=f.finish_reason)!=null?l:void 0},usage:w_(m.usage),request:{body:c},response:{...uu(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(vD),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=await yu({stream:s,getError:(h)=>("error"in h)?h.error:void 0,isOutputChunk:wD,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 w,S,y,x,_,C,I,b,E,F,R,q,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=uu(N);if(Object.values(V).some(Boolean))m=!0,v.enqueue({type:"response-metadata",...uu(N)})}if(N.usage!=null){if(d=N.usage,((w=N.usage.completion_tokens_details)==null?void 0:w.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=(x=N.usage.completion_tokens_details)==null?void 0:x.rejected_prediction_tokens}let re=N.choices[0];if((re==null?void 0:re.finish_reason)!=null)u={unified:x_(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 L=V.index;if(c[L]==null){if(V.type!=null&&V.type!=="function")throw new ya({data:V,message:"Expected 'function' type."});if(V.id==null)throw new ya({data:V,message:"Expected 'id' to be a string."});if(((C=V.function)==null?void 0:C.name)==null)throw new ya({data:V,message:"Expected 'function.name' to be a string."});v.enqueue({type:"tool-input-start",id:V.id,toolName:V.function.name}),c[L]={id:V.id,type:"function",function:{name:V.function.name,arguments:(I=V.function.arguments)!=null?I:""},hasFinished:!1};let Q=c[L];if(((b=Q.function)==null?void 0:b.name)!=null&&((E=Q.function)==null?void 0:E.arguments)!=null){if(Q.function.arguments.length>0)v.enqueue({type:"tool-input-delta",id:Q.id,delta:Q.function.arguments})}continue}let pe=c[L];if(pe.hasFinished)continue;if(((F=V.function)==null?void 0:F.arguments)!=null)pe.function.arguments+=(q=(R=V.function)==null?void 0:R.arguments)!=null?q:"";v.enqueue({type:"tool-input-delta",id:pe.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:qe(),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 w of c)if(!w.hasFinished)h.enqueue({type:"tool-input-end",id:w.id}),h.enqueue({type:"tool-call",toolCallId:(v=w.id)!=null?v:qe(),toolName:w.function.name,input:w.function.arguments}),w.hasFinished=!0;h.enqueue({type:"finish",finishReason:u,usage:w_(d),...f!=null?{providerMetadata:f}:{}})}})),request:{body:o},response:{headers:a}}}};function wD(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 T_(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 xD({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 I_({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 C_(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 TD=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()}))),ID=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()}),hu]))),k_=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()}))),CD=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:k_}),...await Ue({provider:this.providerOptionsName,providerOptions:p,schema:k_})};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}=xD({prompt:e}),w=[...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:w.length>0?w: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(TD),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:T_(a.usage),finishReason:{unified:C_(l.finish_reason),raw:(t=l.finish_reason)!=null?t:void 0},request:{body:n},response:{...I_(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(ID),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=await yu({stream:s,getError:(f)=>("error"in f)?f.error:void 0,isOutputChunk:kD,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",...I_(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:C_(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:T_(d)})}})),request:{body:o},response:{headers:a}}}};function kD(e){return!("error"in e)&&e.choices.some((t)=>t.text.length>0)}var RD=j(()=>M(r.object({dimensions:r.number().optional(),user:r.string().optional()}))),ED=j(()=>M(r.object({data:r.array(r.object({embedding:r.array(r.number())})),usage:r.object({prompt_tokens:r.number()}).nullish()}))),AD=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 va({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=(i=await Ue({provider:"openai",providerOptions:o,schema:RD}))!=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(ED),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}}}},R_=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()}))),PD={"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},MD=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1","gpt-image-2"];function jD(e){return MD.some((t)=>e.startsWith(t))}var vu=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()}),q3=j(()=>M(vu)),OD=j(()=>M(vu.extend({style:r.enum(["vivid","natural"]).optional(),moderation:r.enum(["auto","low"]).optional()}))),ND=j(()=>M(vu.extend({inputFidelity:r.enum(["high","low"]).optional()}))),DD=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get maxImagesPerCall(){var e;return(e=PD[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,w,S,y,x;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 F=(f=await Ue({provider:"openai",providerOptions:l,schema:ND}))!=null?f:{},{value:R,responseHeaders:q}=await ja({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:_e(this.config.headers(),c),formData:Jm({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}):xl(z.url))),mask:n!=null?await zD(n):void 0,n:o,size:i,quality:F.quality,background:F.background,output_format:F.outputFormat,output_compression:F.outputCompression,input_fidelity:F.inputFidelity,user:F.user}),failedResponseHandler:gr,successfulResponseHandler:xe(R_),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:q},providerMetadata:{openai:{images:R.data.map((z,N)=>{var re,Y,V,L,pe,Q;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:(L=R.background)!=null?L:void 0,outputFormat:(pe=R.output_format)!=null?pe:void 0,...E_((Q=R.usage)==null?void 0:Q.input_tokens_details,N,R.data.length)}})}}}}let I=(w=await Ue({provider:"openai",providerOptions:l,schema:OD}))!=null?w:{},{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,...!jD(this.modelId)?{response_format:"b64_json"}:{}},failedResponseHandler:gr,successfulResponseHandler:xe(R_),abortSignal:u,fetch:this.config.fetch});return{images:b.data.map((F)=>F.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:(x=b.usage.total_tokens)!=null?x:void 0}:void 0,response:{timestamp:C,modelId:this.modelId,headers:E},providerMetadata:{openai:{images:b.data.map((F,R)=>{var q,z,N,re,Y,V;return{...F.revised_prompt?{revisedPrompt:F.revised_prompt}:{},created:(q=b.created)!=null?q: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,...E_((V=b.usage)==null?void 0:V.input_tokens_details,R,b.data.length)}})}}}}};function E_(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 zD(e){if(!e)return;if(e.type==="url")return xl(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()})])}))),L_=j(()=>M(r.object({status:r.enum(["completed","failed"]),output:r.string().optional()}))),B3=j(()=>M(r.object({}))),UD=Te({id:"openai.apply_patch",inputSchema:q_,outputSchema:L_}),$D=UD,qD=j(()=>M(r.object({code:r.string().nullish(),containerId:r.string()}))),LD=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()}))),FD=j(()=>M(r.object({container:r.union([r.string(),r.object({fileIds:r.array(r.string()).optional()})]).optional()}))),BD=Te({id:"openai.code_interpreter",inputSchema:qD,outputSchema:LD}),GD=(e={})=>BD(e),JD=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()}))),HD=j(()=>M(r.string())),WD=Ge({id:"openai.custom",inputSchema:HD}),VD=(e)=>WD(e),F_=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())])}),B_=r.object({type:r.enum(["and","or"]),filters:r.array(r.union([F_,r.lazy(()=>B_)]))}),ZD=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([F_,B_]).optional()}))),KD=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()}))),YD=Te({id:"openai.file_search",inputSchema:r.object({}),outputSchema:KD}),QD=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())),XD=j(()=>M(r.object({}))),e1=j(()=>M(r.object({result:r.string()}))),t1=Te({id:"openai.image_generation",inputSchema:XD,outputSchema:e1}),r1=(e={})=>t1(e),G_=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()})}))),J_=j(()=>M(r.object({output:r.string()}))),n1=Te({id:"openai.local_shell",inputSchema:G_,outputSchema:J_}),H_=j(()=>M(r.object({action:r.object({commands:r.array(r.string()),timeoutMs:r.number().optional(),maxOutputLength:r.number().optional()})}))),pu=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()})])}))}))),o1=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(),i1=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:o1}),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()}))),a1=Te({id:"openai.shell",inputSchema:H_,outputSchema:pu}),s1=j(()=>M(r.object({execution:r.enum(["server","client"]).optional(),description:r.string().optional(),parameters:r.record(r.string(),r.unknown()).optional()}))),mu=j(()=>M(r.object({arguments:r.unknown().optional(),call_id:r.string().nullish()}))),gu=j(()=>M(r.object({tools:r.array(r.record(r.string(),r.unknown()))}))),l1=Te({id:"openai.tool_search",inputSchema:mu,outputSchema:gu}),c1=(e={})=>l1(e),u1=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()}))),d1=j(()=>M(r.object({}))),p1=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()}))),m1=Te({id:"openai.web_search",inputSchema:d1,outputSchema:p1}),g1=(e={})=>m1(e),f1=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()}))),h1=j(()=>M(r.object({}))),y1=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()}))),v1=Te({id:"openai.web_search_preview",inputSchema:h1,outputSchema:y1}),fu=r.lazy(()=>r.union([r.string(),r.number(),r.boolean(),r.null(),r.array(fu),r.record(r.string(),fu)])),b1=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."))),_1=j(()=>M(r.object({}))),S1=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(),fu]).optional()}))),w1=Te({id:"openai.mcp",inputSchema:_1,outputSchema:S1}),x1=(e)=>w1(e),T1={applyPatch:$D,customTool:VD,codeInterpreter:GD,fileSearch:YD,imageGeneration:r1,localShell:n1,shell:a1,webSearchPreview:v1,webSearch:g1,mcp:x1,toolSearch:c1};function A_(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 I1(e){return JSON.stringify(e===void 0?{}:e)}function P_(e,t){if(!t)return!1;return t.some((n)=>e.startsWith(n))}async function C1({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,w,S,y,x,_,C,I,b,E,F,R,q,z,N,re,Y,V,L,pe;let Q=[],k=[],X=new Set;for(let{role:J,content:H}of e)switch(J){case"system":{switch(n){case"system":{Q.push({role:"system",content:H});break}case"developer":{Q.push({role:"developer",content:H});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":{Q.push({role:"user",content:H.map((K,D)=>{var B,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"&&P_(K.data,i)?{file_id:K.data}:{image_url:`data:${A};base64,${bt(K.data)}`},detail:(G=(B=K.providerOptions)==null?void 0:B[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"&&P_(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 H)switch(D.type){case"text":{let B=(f=D.providerOptions)==null?void 0:f[o],G=B==null?void 0:B.itemId,Z=B==null?void 0:B.phase;if(l&&G!=null)break;if(s&&G!=null){Q.push({type:"item_reference",id:G});break}Q.push({role:"assistant",content:[{type:"output_text",text:D.text}],id:G,...Z!=null&&{phase:Z}});break}case"tool-call":{let B=(S=(h=(g=D.providerOptions)==null?void 0:g[o])==null?void 0:h.itemId)!=null?S:(w=(v=D.providerMetadata)==null?void 0:v[o])==null?void 0:w.itemId,G=(I=(x=(y=D.providerOptions)==null?void 0:y[o])==null?void 0:x.namespace)!=null?I:(C=(_=D.providerMetadata)==null?void 0:_[o])==null?void 0:C.namespace;if(l&&B!=null)break;let Z=t.toProviderToolName(D.toolName);if(Z==="tool_search"){if(s&&B!=null){Q.push({type:"item_reference",id:B});break}let O=typeof D.input==="string"?await Il({text:D.input,schema:mu}):await Ee({value:D.input,schema:mu}),W=O.call_id!=null?"client":"server";Q.push({type:"tool_search_call",id:B!=null?B:D.toolCallId,execution:W,call_id:(b=O.call_id)!=null?b:null,status:"completed",arguments:O.arguments});break}if(D.providerExecuted){if(s&&B!=null)Q.push({type:"item_reference",id:B});break}if(c&&s&&B!=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&&B!=null&&A){Q.push({type:"item_reference",id:B});break}if(u&&Z==="local_shell"){let O=await Ee({value:D.input,schema:G_});Q.push({type:"local_shell_call",call_id:D.toolCallId,id:B,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:H_});Q.push({type:"shell_call",call_id:D.toolCallId,id:B,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_});Q.push({type:"apply_patch_call",call_id:O.callId,id:B,status:"completed",operation:O.operation});break}if(p==null?void 0:p.has(Z)){Q.push({type:"custom_tool_call",call_id:D.toolCallId,name:Z,input:typeof D.input==="string"?D.input:JSON.stringify(D.input),id:B});break}Q.push({type:"function_call",call_id:D.toolCallId,name:Z,arguments:I1(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 B=t.toProviderToolName(D.toolName);if(B==="tool_search"){let G=(q=(R=(F=D.providerOptions)==null?void 0:F[o])==null?void 0:R.itemId)!=null?q:D.toolCallId;if(s)Q.push({type:"item_reference",id:G});else if(D.output.type==="json"){let Z=await Ee({value:D.output.value,schema:gu});Q.push({type:"tool_search_output",id:G,execution:"server",call_id:null,status:"completed",tools:Z.tools})}break}if(d&&B==="shell"){if(D.output.type==="json"){let G=await Ee({value:D.output.value,schema:pu});Q.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;Q.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 B=await Ue({provider:o,providerOptions:D.providerOptions,schema:k1}),G=B==null?void 0:B.itemId;if((l||c)&&G!=null)break;if(G!=null){let Z=K[G];if(s){if(Z===void 0)Q.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:B==null?void 0:B.reasoningEncryptedContent,summary:A},Q.push(K[G]);else if(Z.summary.push(...A),(B==null?void 0:B.reasoningEncryptedContent)!=null)Z.encrypted_content=B.reasoningEncryptedContent}}else{let Z=B==null?void 0:B.reasoningEncryptedContent;if(Z!=null){let A=[];if(D.text.length>0)A.push({type:"summary_text",text:D.text});Q.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 H){if(K.type==="tool-approval-response"){let Z=K;if(X.has(Z.approvalId))continue;if(X.add(Z.approvalId),s)Q.push({type:"item_reference",id:Z.approvalId});Q.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 B=t.toProviderToolName(K.toolName);if(B==="tool_search"&&D.type==="json"){let Z=await Ee({value:D.value,schema:gu});Q.push({type:"tool_search_output",execution:"client",call_id:K.toolCallId,status:"completed",tools:Z.tools});continue}if(u&&B==="local_shell"&&D.type==="json"){let Z=await Ee({value:D.value,schema:J_});Q.push({type:"local_shell_call_output",call_id:K.toolCallId,output:Z.output});continue}if(d&&B==="shell"&&D.type==="json"){let Z=await Ee({value:D.value,schema:pu});Q.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:L_});Q.push({type:"apply_patch_call_output",call_id:K.toolCallId,status:Z.status,output:Z.output});continue}if(p==null?void 0:p.has(B)){let Z;switch(D.type){case"text":case"error-text":Z=D.value;break;case"execution-denied":Z=(L=D.reason)!=null?L:"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,U,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:(U=(P=A.providerOptions)==null?void 0:P[o])==null?void 0:U.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=""}Q.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=(pe=D.reason)!=null?pe:"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,U;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:(U=Z.filename)!=null?U:"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}Q.push({type:"function_call_output",call_id:K.toolCallId,output:G})}break}default:throw Error(`Unsupported role: ${J}`)}if(!s&&Q.some((J)=>("type"in J)&&J.type==="reasoning"&&J.encrypted_content==null))k.push({type:"other",message:"Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts."}),Q=Q.filter((J)=>!("type"in J)||J.type!=="reasoning"||J.encrypted_content!=null);return{input:Q,warnings:k}}var k1=r.object({itemId:r.string().nullish(),reasoningEncryptedContent:r.string().nullish()});function du({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())])),R1=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()})}),E1=r.object({type:r.literal("error"),sequence_number:r.number(),code:r.string().nullish(),message:r.string(),param:r.string().nullish()}),A1=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()}),R1,E1,r.object({type:r.string()}).loose().transform((e)=>({type:"unknown_chunk",message:e.type}))]))),P1=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()}))),W_=20,M1=["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"],b9=["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",...M1],M_=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(W_)]).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 j1({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=O1({tool:f,options:g}),v=g==null?void 0:g.namespace;if(v==null)u.push(h);else{let w=d.get(v.name);if(w==null)w={type:"namespace",name:v.name,description:v.description,tools:[]},d.set(v.name,w),u.push(w);else if(w.description!==v.description)throw new We({functionality:`conflicting descriptions for OpenAI tool namespace "${v.name}"`});w.tools.push(h)}break}case"provider":{switch(f.id){case"openai.file_search":{let g=await Ee({value:f.args,schema:ZD});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:i1});u.push({type:"shell",...g.environment&&{environment:N1(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:f1});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:u1});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:FD});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:QD});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:b1}),h=(S)=>({tool_names:S.toolNames}),v=g.requireApproval,w=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:w!=null?w:"never",server_description:g.serverDescription,server_url:g.serverUrl});break}case"openai.custom":{let g=await Ee({value:f.args,schema:JD});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:s1});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 O1({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 N1(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:D1(n.skills)}}return{type:"local",skills:e.skills}}function D1(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 j_(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 z1=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,w,S,y,x,_,C,I;let b=[],E=$_(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 F=this.config.provider.includes("azure")?"azure":"openai",R=await Ue({provider:F,providerOptions:u,schema:M_});if(R==null&&F!=="openai")R=await Ue({provider:"openai",providerOptions:u,schema:M_});let q=(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=Ea({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 j1({tools:d,toolChoice:m,allowedTools:(g=R==null?void 0:R.allowedTools)!=null?g:void 0,toolNameMapping:z,customProviderToolNames:N}),{input:L,warnings:pe}=await C1({prompt:c,toolNameMapping:z,systemMessageMode:(h=R==null?void 0:R.systemMessageMode)!=null?h:q?"developer":E.systemMessageMode,providerOptionsName:F,fileIdPrefixes:this.config.fileIdPrefixes,passThroughUnsupportedFiles:(v=R==null?void 0:R.passThroughUnsupportedFiles)!=null?v:!1,store:(w=R==null?void 0:R.store)!=null?w:!0,hasConversation:(R==null?void 0:R.conversation)!=null,hasPreviousResponseId:(R==null?void 0:R.previousResponseId)!=null,hasLocalShellTool:J("openai.local_shell"),hasShellTool:J("openai.shell"),hasApplyPatchTool:J("openai.apply_patch"),customProviderToolNames:N.size>0?N:void 0});b.push(...pe);let Q=(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 J(A){return(d==null?void 0:d.find((O)=>O.type==="provider"&&O.id===A))!=null}let H=typeof(R==null?void 0:R.logprobs)==="number"?R==null?void 0:R.logprobs:(R==null?void 0:R.logprobs)===!0?W_:void 0;if(H)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(J("openai.code_interpreter"))X("code_interpreter_call.outputs");let D=R==null?void 0:R.store;if(D===!1&&q)X("reasoning.encrypted_content");let B={model:this.modelId,input:L,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:Q,name:(x=p.name)!=null?x:"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:H,truncation:R==null?void 0:R.truncation,...q&&((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(q){if(!((R==null?void 0:R.reasoningEffort)==="none"&&E.supportsNonReasoningParameters)){if(B.temperature!=null)B.temperature=void 0,b.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"});if(B.top_p!=null)B.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 B.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 B.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:{...B,tools:re,tool_choice:Y},warnings:[...b,...V],store:D,toolNameMapping:z,providerOptionsName:F,isShellProviderExecuted:Z}}async doGenerate(e){var t,n,o,i,a,s,l,c,u,d,m,p,f,g,h,v,w,S,y,x,_,C,I,b,E,F,R,q;let{args:z,warnings:N,webSearchToolName:re,toolNameMapping:Y,providerOptionsName:V,isShellProviderExecuted:L}=await this.getArgs(e),pe=this.config.url({path:"/responses",modelId:this.modelId}),Q=j_(e.prompt),{responseHeaders:k,value:X,rawValue:J}=await Ie({url:pe,headers:_e(this.config.headers(),e.headers),body:z,failedResponseHandler:gr,successfulResponseHandler:xe(P1),abortSignal:e.abortSignal,fetch:this.config.fetch});if(X.error)throw new De({message:X.error.message,url:pe,requestBodyValues:z,statusCode:400,responseHeaders:k,responseBody:J,isRetryable:!1});let H=[],K=[],D=!1,B=[];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)H.push({type:"reasoning",text:O.text,providerMetadata:{[V]:{itemId:A.id,reasoningEncryptedContent:(t=A.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{H.push({type:"tool-call",toolCallId:A.id,toolName:Y.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),H.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)B.push(O);H.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:B.shift())!=null?i:A.id;H.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":{H.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":{H.push({type:"tool-call",toolCallId:A.call_id,toolName:Y.toCustomToolName("shell"),input:JSON.stringify({action:{commands:A.action.commands}}),...L&&{providerExecuted:!0},providerMetadata:{[V]:{itemId:A.id}}});break}case"shell_call_output":{H.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}};H.push({type:"text",text:O.text,providerMetadata:{[V]:W}});for(let P of O.annotations)if(P.type==="url_citation")H.push({type:"source",sourceType:"url",id:(u=(c=(l=this.config).generateId)==null?void 0:c.call(l))!=null?u:qe(),url:P.url,title:P.title});else if(P.type==="file_citation")H.push({type:"source",sourceType:"document",id:(p=(m=(d=this.config).generateId)==null?void 0:m.call(d))!=null?p:qe(),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")H.push({type:"source",sourceType:"document",id:(h=(g=(f=this.config).generateId)==null?void 0:g.call(f))!=null?h:qe(),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")H.push({type:"source",sourceType:"document",id:(S=(w=(v=this.config).generateId)==null?void 0:w.call(v))!=null?S:qe(),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,H.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);H.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":{H.push({type:"tool-call",toolCallId:A.id,toolName:Y.toCustomToolName(re!=null?re:"web_search"),input:JSON.stringify({}),providerExecuted:!0}),H.push({type:"tool-result",toolCallId:A.id,toolName:Y.toCustomToolName(re!=null?re:"web_search"),result:z_(A.action)});break}case"mcp_call":{let O=A.approval_request_id!=null?(y=Q[A.approval_request_id])!=null?y:A.id:A.id,W=`mcp.${A.name}`;H.push({type:"tool-call",toolCallId:O,toolName:W,input:A.arguments,providerExecuted:!0,dynamic:!0}),H.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=(x=A.approval_request_id)!=null?x:A.id,W=(I=(C=(_=this.config).generateId)==null?void 0:C.call(_))!=null?I:qe(),P=`mcp.${A.name}`;H.push({type:"tool-call",toolCallId:W,toolName:P,input:A.arguments,providerExecuted:!0,dynamic:!0}),H.push({type:"tool-approval-request",approvalId:O,toolCallId:W});break}case"computer_call":{H.push({type:"tool-call",toolCallId:A.id,toolName:Y.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),H.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":{H.push({type:"tool-call",toolCallId:A.id,toolName:Y.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),H.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":{H.push({type:"tool-call",toolCallId:A.id,toolName:Y.toCustomToolName("code_interpreter"),input:JSON.stringify({code:A.code,containerId:A.container_id}),providerExecuted:!0}),H.push({type:"tool-result",toolCallId:A.id,toolName:Y.toCustomToolName("code_interpreter"),result:{outputs:A.outputs}});break}case"apply_patch_call":{H.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:H,finishReason:{unified:du({finishReason:(F=X.incomplete_details)==null?void 0:F.reason,hasFunctionCall:D}),raw:(q=(R=X.incomplete_details)==null?void 0:R.reason)!=null?q:void 0},usage:A_(Z),request:{body:z},response:{id:X.id,timestamp:new Date(X.created_at*1000),modelId:X.model,headers:k,body:J},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(A1),abortSignal:e.abortSignal,fetch:this.config.fetch}),m=await yu({stream:d,getError:(q)=>D_(q)||O_(q)&&q.response.error!=null?q:void 0,isOutputChunk:X1,url:c,requestBodyValues:t,responseHeaders:u}),p=this,f=j_(e.prompt),g=new Map,h={unified:"other",raw:void 0},v=void 0,w=[],S=null,y={},x=[],_,C=!1,I={},b,E=[],F=!1;return{stream:m.pipeThrough(new TransformStream({start(q){q.enqueue({type:"stream-start",warnings:n})},transform(q,z){var N,re,Y,V,L,pe,Q,k,X,J,H,K,D,B,G,Z,A,O,W,P,U,me,ee,ue,Ae,Ke,nt,At,Dr,he,br,zr,rn,Tn,_r,st,nn,ut;if(e.includeRawChunks)z.enqueue({type:"raw",rawValue:q.rawValue});if(!q.success){let te=$1(q.rawValue)?q1({value:q.rawValue,cause:q.error,url:c,requestBodyValues:t,responseHeaders:u}):q.error;h={unified:"error",raw:void 0},z.enqueue({type:"error",error:te});return}let T=q.value;if(N_(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")x.splice(0,x.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(N_(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(F1(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},...x.length>0&&{annotations:x}}}})}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:z_(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:(pe=(L=T.item.results)==null?void 0:L.map((te)=>({attributes:te.attributes,fileId:te.file_id,filename:te.filename,score:te.score,text:te.text})))!=null?pe: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:(Q=T.item.call_id)!=null?Q: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=(J=T.item.approval_request_id)!=null?J:void 0,ve=te!=null?(K=(H=g.get(te))!=null?H: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=(B=(D=p.config).generateId)==null?void 0:B.call(D))!=null?G:qe(),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(J1(T)){let te=y[T.output_index];if(te!=null)z.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:T.delta})}else if(H1(T)){let te=y[T.output_index];if(te!=null)z.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:T.delta})}else if(K1(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(Y1(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(W1(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(V1(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(Z1(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(G1(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(U1(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)w.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:(U=(P=I[T.item_id])==null?void 0:P.encryptedContent)!=null?U: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(B1(T)){if(h={unified:du({finishReason:(me=T.response.incomplete_details)==null?void 0:me.reason,hasFunctionCall:C}),raw:(ue=(ee=T.response.incomplete_details)==null?void 0:ee.reason)!=null?ue:void 0},v=T.response.usage,typeof T.response.service_tier==="string")b=T.response.service_tier}else if(O_(T)){let te=(Ae=T.response.incomplete_details)==null?void 0:Ae.reason;if(h={unified:te?du({finishReason:te,hasFunctionCall:C}):"error",raw:te!=null?te:"error"},v=(Ke=T.response.usage)!=null?Ke:void 0,!F&&T.response.error!=null)F=!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(Q1(T)){if(x.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:qe(),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:qe(),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:qe(),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:qe(),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(D_(T))F=!0,h={unified:"error",raw:"error"},z.enqueue({type:"error",error:T})},flush(q){let z={[s]:{responseId:S,...w.length>0?{logprobs:w}:{},...b!==void 0?{serviceTier:b}:{}}};q.enqueue({type:"finish",finishReason:h,usage:A_(v),providerMetadata:z})}})),request:{body:t},response:{headers:u}}}};function U1(e){return e.type==="response.output_text.delta"}function $1(e){let t=L1(e);return t!=null&&Array.isArray(t.choices)&&typeof t.type!=="string"}function q1({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 L1(e){return typeof e==="object"&&e!=null?e:void 0}function F1(e){return e.type==="response.output_item.done"}function B1(e){return e.type==="response.completed"||e.type==="response.incomplete"}function O_(e){return e.type==="response.failed"}function G1(e){return e.type==="response.created"}function J1(e){return e.type==="response.function_call_arguments.delta"}function H1(e){return e.type==="response.custom_tool_call_input.delta"}function W1(e){return e.type==="response.image_generation_call.partial_image"}function V1(e){return e.type==="response.code_interpreter_call_code.delta"}function Z1(e){return e.type==="response.code_interpreter_call_code.done"}function K1(e){return e.type==="response.apply_patch_call_operation_diff.delta"}function Y1(e){return e.type==="response.apply_patch_call_operation_diff.done"}function N_(e){return e.type==="response.output_item.added"}function Q1(e){return e.type==="response.output_text.annotation.added"}function D_(e){return e.type==="error"}function X1(e){return!(e.type==="response.created"||e.type==="response.failed"||e.type==="error"||e.type==="unknown_chunk")}function z_(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 e2=j(()=>M(r.object({instructions:r.string().nullish(),speed:r.number().min(0.25).max(4).default(1).nullish()}))),t2=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:e2}),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:cg(),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}}}},r2=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()}))),n2=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()}))),U_={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"},o2=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:n2}),a=new FormData,s=e instanceof Uint8Array?new Blob([e]):new Blob([wt(e)]);a.append("model",this.modelId);let l=eg(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 ja({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:_e(this.config.headers(),e.headers),formData:d,failedResponseHandler:gr,successfulResponseHandler:xe(r2),abortSignal:e.abortSignal,fetch:this.config.fetch}),h=p.language!=null&&p.language in U_?U_[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}}}},i2="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/${i2}`),s=(h)=>new SD(h,{provider:`${i}.chat`,url:({path:v})=>`${o}${v}`,headers:a,fetch:e.fetch}),l=(h)=>new CD(h,{provider:`${i}.completion`,url:({path:v})=>`${o}${v}`,headers:a,fetch:e.fetch}),c=(h)=>new AD(h,{provider:`${i}.embedding`,url:({path:v})=>`${o}${v}`,headers:a,fetch:e.fetch}),u=(h)=>new DD(h,{provider:`${i}.image`,url:({path:v})=>`${o}${v}`,headers:a,fetch:e.fetch}),d=(h)=>new o2(h,{provider:`${i}.transcription`,url:({path:v})=>`${o}${v}`,headers:a,fetch:e.fetch}),m=(h)=>new t2(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 z1(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=T1,g}var A9=_o();var a2="3.0.90",s2=j(()=>M(r.object({error:r.object({code:r.number().nullable(),message:r.string(),status:r.string()})}))),or=Qe({errorSchema:s2,errorToMessage:(e)=>e.error.message}),l2=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()})})]),c2=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(l2).min(1).nullable()).optional()}))),u2=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:c2});if(e.length>this.maxEmbeddingsPerCall)throw new va({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(p2),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(d2),abortSignal:n,fetch:this.config.fetch});return{warnings:[],embeddings:c.embeddings.map((d)=>d.values),usage:void 0,response:{headers:l,body:u}}}},d2=j(()=>M(r.object({embeddings:r.array(r.object({values:r.array(r.number())}))}))),p2=j(()=>M(r.object({embedding:r.object({values:r.array(r.number())})})));function V_(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(m2(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((w)=>w!=="null");if(v.length===0)g.type="null";else if(g.anyOf=v.map((w)=>({type:w})),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,w])=>(h[v]=fr(w,!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 m2(e){return e!=null&&typeof e==="object"&&e.type==="object"&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}var g2="skip_thought_signature_validator";function Z_(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 f2=/^data:([^;,]+);base64,(.+)$/s;function h2(e){let t=f2.exec(e);if(t==null)return;return{mediaType:t[1],data:t[2]}}function y2(e){let t=h2(e);if(t==null)return;return{inlineData:{mimeType:t.mediaType,data:t.data}}}function v2(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=y2(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 b2(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 _2(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=[],w=(S)=>(v.push(S),h=!0,g2);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 x=[];for(let _ of y)switch(_.type){case"text":{x.push({text:_.text});break}case"file":{let C=_.mediaType==="image/*"?"image/jpeg":_.mediaType;x.push(_.data instanceof URL?{fileData:{mimeType:C,fileUri:_.data.toString()}}:{inlineData:{mimeType:C,data:bt(_.data)}});break}}c.push({role:"user",parts:x});break}case"assistant":{u=!1,c.push({role:"model",parts:y.map((x)=>{let _=Z_(x.providerOptions,p),C=(_==null?void 0:_.thoughtSignature)!=null?String(_.thoughtSignature):void 0;switch(x.type){case"text":return x.text.length===0?void 0:{text:x.text,thoughtSignature:C};case"reasoning":return x.text.length===0?void 0:{text:x.text,thought:!0,thoughtSignature:C};case"file":{if(x.data instanceof URL)throw new We({functionality:"File data URLs in assistant messages are not supported"});return{inlineData:{mimeType:x.mediaType,data:bt(x.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?w(x.toolName):void 0;if(I&&b)return{toolCall:{toolType:b,args:typeof x.input==="string"?er(x.input):x.input,id:I},thoughtSignature:E};return{functionCall:{...x.toolCallId!=null?{id:x.toolCallId}:{},name:x.toolName,args:x.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:x.output.type==="json"?x.output.value:{},id:I},thoughtSignature:C};return}}}).filter((x)=>x!==void 0)});break}case"tool":{u=!1;let x=[];for(let _ of y){if(_.type==="tool-approval-response")continue;let C=Z_(_.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 F=(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:F});continue}}}let E=_.output;if(E.type==="content")if(f)v2(x,_.toolName,E.value,_.toolCallId);else b2(x,_.toolName,E.value,_.toolCallId);else x.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:x});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 K_(e){return e.includes("/")?e:`models/${e}`}var Y_=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 S2({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 x of e)if(x.type==="function")S.push({name:x.name,description:(i=x.description)!=null?i:"",parameters:fr(x.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 w2=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=x2(o),a=I2(this.accumulatedArgs,i);if(n.stringValue!=null&&a!==void 0){let c=JSON.stringify(n.stringValue).slice(1,-1);X_(this.accumulatedArgs,i,a+n.stringValue),t+=c;continue}let l=C2(n);if(l==null)continue;X_(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 x2(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 T2=Object.prototype.hasOwnProperty;function uS(e,t){return T2.call(e,t)}function Q_(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})}function I2(e,t){let n=e;for(let o of t){if(n==null||typeof n!=="object")return;let i=n;if(!uS(i,o))return;n=i[o]}return n}function X_(e,t,n){let o=e;for(let i=0;i<t.length-1;i++){let a=t[i],s=t[i+1];if(!uS(o,a)||o[a]==null)Q_(o,a,typeof s==="number"?[]:{});o=o[a]}Q_(o,t[t.length-1],n)}function C2(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 eS({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 dS=class{constructor(e,t){this.specificationVersion="v3";var n;this.modelId=e,this.config=t,this.generateId=(n=t.generateId)!=null?n:qe}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=[],w=this.config.provider.includes("vertex")?"vertex":"google",S=await Ue({provider:w,providerOptions:p,schema:Y_});if(S==null&&w!=="google")S=await Ue({provider:"google",providerOptions:p,schema:Y_});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 x=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:F}=_2(e,{isGemmaModel:C,isGemini3Model:I,providerOptionsName:w,supportsFunctionResponseParts:b,onWarning:(Y)=>v.push(Y)}),{tools:R,toolConfig:q,toolWarnings:z}=S2({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=q||N||(S==null?void 0:S.retrievalConfig)?{...q,...N&&{functionCallingConfig:{...q==null?void 0:q.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:F,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:w,extraHeaders:x}}async doGenerate(e){var t,n,o,i,a,s,l,c,u,d,m,p,f,g,h,v,w,S;let{args:y,warnings:x,providerOptionsName:_,extraHeaders:C}=await this.getArgs(e),I=_e(await Se(this.config.headers),e.headers,C),{responseHeaders:b,value:E,rawValue:F}=await Ie({url:`${this.config.baseURL}/${K_(this.modelId)}:generateContent`,headers:I,body:y,failedResponseHandler:or,successfulResponseHandler:xe(R2),abortSignal:e.abortSignal,fetch:this.config.fetch}),R=E.candidates[0],q=[],z=(n=(t=R.content)==null?void 0:t.parts)!=null?n:[],N=E.usageMetadata,re,Y;for(let L of z)if("executableCode"in L&&((o=L.executableCode)==null?void 0:o.code)){let pe=this.config.generateId();re=pe,q.push({type:"tool-call",toolCallId:pe,toolName:"code_execution",input:JSON.stringify(L.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in L&&L.codeExecutionResult)q.push({type:"tool-result",toolCallId:re,toolName:"code_execution",result:{outcome:L.codeExecutionResult.outcome,output:(i=L.codeExecutionResult.output)!=null?i:""}}),re=void 0;else if("text"in L&&L.text!=null){let pe=L.thoughtSignature?{[_]:{thoughtSignature:L.thoughtSignature}}:void 0;if(L.text.length===0){if(pe!=null&&q.length>0){let Q=q[q.length-1];Q.providerMetadata=pe}}else q.push({type:L.thought===!0?"reasoning":"text",text:L.text,providerMetadata:pe})}else if("functionCall"in L&&L.functionCall.name!=null)q.push({type:"tool-call",toolCallId:(a=L.functionCall.id)!=null?a:this.config.generateId(),toolName:L.functionCall.name,input:JSON.stringify((s=L.functionCall.args)!=null?s:{}),providerMetadata:L.thoughtSignature?{[_]:{thoughtSignature:L.thoughtSignature}}:void 0});else if("inlineData"in L){let pe=L.thought===!0,Q=!!L.thoughtSignature;q.push({type:"file",data:L.inlineData.data,mediaType:L.inlineData.mimeType,providerMetadata:pe||Q?{[_]:{...pe?{thought:!0}:{},...Q?{thoughtSignature:L.thoughtSignature}:{}}}:void 0})}else if("toolCall"in L&&L.toolCall){let pe=(l=L.toolCall.id)!=null?l:this.config.generateId();Y=pe,q.push({type:"tool-call",toolCallId:pe,toolName:`server:${L.toolCall.toolType}`,input:JSON.stringify((c=L.toolCall.args)!=null?c:{}),providerExecuted:!0,dynamic:!0,providerMetadata:L.thoughtSignature?{[_]:{thoughtSignature:L.thoughtSignature,serverToolCallId:pe,serverToolType:L.toolCall.toolType}}:{[_]:{serverToolCallId:pe,serverToolType:L.toolCall.toolType}}})}else if("toolResponse"in L&&L.toolResponse){let pe=(u=Y!=null?Y:L.toolResponse.id)!=null?u:this.config.generateId();q.push({type:"tool-result",toolCallId:pe,toolName:`server:${L.toolResponse.toolType}`,result:(d=L.toolResponse.response)!=null?d:{},providerMetadata:L.thoughtSignature?{[_]:{thoughtSignature:L.thoughtSignature,serverToolCallId:pe,serverToolType:L.toolResponse.toolType}}:{[_]:{serverToolCallId:pe,serverToolType:L.toolResponse.toolType}}}),Y=void 0}let V=(m=tS({groundingMetadata:R.groundingMetadata,generateId:this.config.generateId}))!=null?m:[];for(let L of V)q.push(L);return{content:q,finishReason:{unified:eS({finishReason:R.finishReason,hasToolCalls:q.some((L)=>L.type==="tool-call"&&!L.providerExecuted)}),raw:(p=R.finishReason)!=null?p:void 0},usage:V_(N),warnings:x,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:(w=R.finishMessage)!=null?w:null,serviceTier:(S=N==null?void 0:N.serviceTier)!=null?S:null}},request:{body:y},response:{headers:b,body:F}}}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}/${K_(this.modelId)}:streamGenerateContent?alt=sse`,headers:a,body:t,failedResponseHandler:or,successfulResponseHandler:Dt(E2),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,w=0,S=new Set,y,x,_=[],C=(I)=>{let b=_.pop();if(b==null)return;let{finalJSON:E,closingDelta:F}=b.accumulator.finalize();if(F.length>0)I.enqueue({type:"tool-input-delta",id:b.toolCallId,delta:F,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,F,R,q,z,N,re,Y,V,L,pe,Q,k,X,J,H;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 B=(E=K.candidates)==null?void 0:E[0];if(B==null)return;let G=B.content;if(B.groundingMetadata!=null)m=B.groundingMetadata;if(B.urlContextMetadata!=null)p=B.urlContextMetadata;let Z=tS({groundingMetadata:B.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=(F=G.parts)!=null?F:[];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:(q=O.codeExecutionResult.output)!=null?q:""}}),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(w++),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(w++),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,U=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:U})}else if("toolCall"in O&&O.toolCall){let W=(z=O.toolCall.id)!=null?z:f();x=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=x!=null?x: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}),x=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,U=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,ee=O.functionCall.name!=null&&O.functionCall.args==null&&O.functionCall.partialArgs==null&&O.functionCall.willContinue!==!0;if(P){if(O.functionCall.name!=null){let ue=(V=O.functionCall.id)!=null?V:f(),Ae=new w2;if(_.push({toolCallId:ue,toolName:O.functionCall.name,accumulator:Ae,providerMetadata:W}),b.enqueue({type:"tool-input-start",id:ue,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:ue,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 ue=_[_.length-1],Ae=O.functionCall.partialArgs,{textDelta:Ke}=ue.accumulator.processPartialArgs(Ae);if(Ke.length>0)b.enqueue({type:"tool-input-delta",id:ue.toolCallId,delta:Ke,providerMetadata:W});if(O.functionCall.willContinue!==!0&&Ae.every((nt)=>nt.willContinue!==!0))C(b)}}else if(U&&_.length>0)C(b);else if(me){let ue=(L=O.functionCall.id)!=null?L:f(),Ae=O.functionCall.name,Ke=typeof O.functionCall.args==="string"?O.functionCall.args:JSON.stringify((pe=O.functionCall.args)!=null?pe:{});b.enqueue({type:"tool-input-start",id:ue,toolName:Ae,providerMetadata:W}),b.enqueue({type:"tool-input-delta",id:ue,delta:Ke,providerMetadata:W}),b.enqueue({type:"tool-input-end",id:ue,providerMetadata:W}),b.enqueue({type:"tool-call",toolCallId:ue,toolName:Ae,input:Ke,providerMetadata:W}),g=!0}else if(ee){let ue=(Q=O.functionCall.id)!=null?Q:f(),Ae=O.functionCall.name;b.enqueue({type:"tool-input-start",id:ue,toolName:Ae,providerMetadata:W}),b.enqueue({type:"tool-input-end",id:ue,providerMetadata:W}),b.enqueue({type:"tool-call",toolCallId:ue,toolName:Ae,input:"{}",providerMetadata:W}),g=!0}}}if(B.finishReason!=null)c={unified:eS({finishReason:B.finishReason,hasToolCalls:g}),raw:B.finishReason},d={[o]:{promptFeedback:(k=K.promptFeedback)!=null?k:null,groundingMetadata:m,urlContextMetadata:p,safetyRatings:(X=B.safetyRatings)!=null?X:null,usageMetadata:D!=null?D:null,finishMessage:(J=B.finishMessage)!=null?J:null,serviceTier:(H=u==null?void 0:u.serviceTier)!=null?H: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:V_(u),providerMetadata:d})}})),response:{headers:s},request:{body:t}}}};function tS({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 pS=()=>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()}),k2=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()}),mS=()=>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(k2).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()}),ts=()=>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()}),rS=r.array(r.object({modality:r.string(),tokenCount:r.number()})).nullish(),gS=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:rS,candidatesTokensDetails:rS}),fS=()=>r.object({urlMetadata:r.array(r.object({retrievedUrl:r.string(),urlRetrievalStatus:r.string()})).nullish()}),R2=j(()=>M(r.object({candidates:r.array(r.object({content:mS().nullish().or(r.object({}).strict()),finishReason:r.string().nullish(),finishMessage:r.string().nullish(),safetyRatings:r.array(ts()).nullish(),groundingMetadata:pS().nullish(),urlContextMetadata:fS().nullish()})),usageMetadata:gS.nullish(),promptFeedback:r.object({blockReason:r.string().nullish(),safetyRatings:r.array(ts()).nullish()}).nullish()}))),E2=j(()=>M(r.object({candidates:r.array(r.object({content:mS().nullish(),finishReason:r.string().nullish(),finishMessage:r.string().nullish(),safetyRatings:r.array(ts()).nullish(),groundingMetadata:pS().nullish(),urlContextMetadata:fS().nullish()})).nullish(),usageMetadata:gS.nullish(),promptFeedback:r.object({blockReason:r.string().nullish(),safetyRatings:r.array(ts()).nullish()}).nullish()}))),A2=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.")})}),P2=Ge({id:"google.enterprise_web_search",inputSchema:j(()=>M(r.object({})))}),M2=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(),j2=j(()=>M(M2)),O2=Ge({id:"google.file_search",inputSchema:j2}),N2=Ge({id:"google.google_maps",inputSchema:j(()=>M(r.object({})))}),hS=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(),D2=j(()=>M(hS)),z2=Ge({id:"google.google_search",inputSchema:D2}),U2=Ge({id:"google.url_context",inputSchema:j(()=>M(r.object({})))}),$2=Ge({id:"google.vertex_rag_store",inputSchema:r.object({ragCorpus:r.string(),topK:r.number().optional()})}),q2={googleSearch:z2,enterpriseWebSearch:P2,googleMaps:N2,urlContext:U2,fileSearch:O2,codeExecution:A2,vertexRagStore:$2},L2=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(nS(this.modelId))return 10;return 4}get provider(){return this.config.provider}async doGenerate(e){if(nS(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:oS}),v=(o=(n=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:n.call(t))!=null?o:new Date,w={sampleCount:a};if(l!=null)w.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(w,C)}let S={instances:[{prompt:i}],parameters:w},{responseHeaders:y,value:x}=await Ie({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:_e(await Se(this.config.headers),d),body:S,failedResponseHandler:or,successfulResponseHandler:xe(F2),abortSignal:m,fetch:this.config.fetch});return{images:x.predictions.map((_)=>_.bytesBase64Encoded),warnings:g,providerMetadata:{google:{images:x.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:w,headers:S,abortSignal:y,files:x,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(x!=null&&x.length>0)for(let V of x)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:w,schema:oS}),{googleSearch:F,...R}=(t=w==null?void 0:w.google)!=null?t:{},z=await new dS(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:qe}).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 nS(e){return e.startsWith("gemini-")}var F2=j(()=>M(r.object({predictions:r.array(r.object({bytesBase64Encoded:r.string()})).default([])}))),oS=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:hS.optional()})));function B2(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 G2(e){var t;return(t=B2(e))!=null?t:e.image}function J2(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 H2(e){if(e.frameImages!=null&&e.frameImages.length>0)return;return e.inputReferences!=null&&e.inputReferences.length>0?e.inputReferences:void 0}function _u(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 W2(e){if(e.bytesBase64Encoded)return{inlineData:{mimeType:"image/png",data:e.bytesBase64Encoded}};if(e.gcsUri)return{gcsUri:e.gcsUri};return e}function V2(e,t){let n=_u(e,t);return n!=null?{image:n,referenceType:"asset"}:void 0}var Z2=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:K2}),p=[{}],f=p[0];if(e.prompt!=null)f.prompt=e.prompt;let g=G2(e);if(g!=null){let N=_u(g,d);if(N!=null)f.image=N}let h=J2(e);if(h!=null){let N=_u(h,d);if(N!=null)f.lastFrame=N}let v=H2(e);if(v!=null)f.referenceImages=v.flatMap((N)=>{let re=V2(N,d);return re!=null?[re]:[]});else if((m==null?void 0:m.referenceImages)!=null)f.referenceImages=m.referenceImages.map((N)=>W2(N));let w={sampleCount:e.n};if(e.aspectRatio)w.aspectRatio=e.aspectRatio;if(e.resolution){let N={"1280x720":"720p","1920x1080":"1080p","3840x2160":"4k"};w.resolution=N[e.resolution]||e.resolution}if(e.duration)w.durationSeconds=e.duration;if(e.seed)w.seed=e.seed;if(m!=null){let N=m;if(N.personGeneration!==void 0&&N.personGeneration!==null)w.personGeneration=N.personGeneration;if(N.negativePrompt!==void 0&&N.negativePrompt!==null)w.negativePrompt=N.negativePrompt;for(let[re,Y]of Object.entries(N))if(!["pollIntervalMs","pollTimeoutMs","personGeneration","negativePrompt","referenceImages"].includes(re))w[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:w},successfulResponseHandler:xe(iS),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 x=(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(x),(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(iS),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 F=[],R=[],q=await Se(this.config.headers),z=q==null?void 0:q["x-goog-api-key"];for(let N of E.generateVideoResponse.generatedSamples)if((c=N.video)==null?void 0:c.uri){let re=z&&Qm(N.video.uri,this.config.baseURL)?`${N.video.uri}${N.video.uri.includes("?")?"&":"?"}key=${z}`:N.video.uri;F.push({type:"url",url:re,mediaType:"video/mp4"}),R.push({uri:N.video.uri})}if(F.length===0)throw new ie({name:"GOOGLE_VIDEO_GENERATION_ERROR",message:"No valid videos in response"});return{videos:F,warnings:d,response:{timestamp:u,modelId:this.modelId,headers:b},providerMetadata:{google:{videos:R}}}}},iS=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()}),K2=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 Tu(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 yS(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 Y2={pdf:"application/pdf",txt:"text/plain",md:"text/markdown",markdown:"text/markdown",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function vS(e){let t=e.toLowerCase();for(let[n,o]of Object.entries(Y2))if(t.endsWith(`.${n}`))return o;return"application/octet-stream"}function bS(e){let t=e.split("/"),n=t[t.length-1];return n&&n.length>0?n:void 0}function Q2({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:bS(c),d=vS(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 _S({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,w=(c=(l=v.url)!=null?l:v.document_uri)!=null?c:v.file_name;if(w==null||w.length===0)continue;if(w.startsWith("http://")||w.startsWith("https://")){f.push({type:"source",sourceType:"url",id:t(),url:w,...v.title!=null?{title:v.title}:{}});continue}let S=(u=v.file_name)!=null?u:bS(w),y=vS(w);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:w,...S!=null?{filename:S}:{}})}break}default:break}return f}function Su({annotations:e,generateId:t}){var n;if(e==null)return[];let o=new Set,i=[];for(let a of e){let s=Q2({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 Iu({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 X2=new Set(["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"]),ez=new Set(["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"]);function tz(e){return e.replace(/_call$/,"")}function rz(e){return e.replace(/_result$/,"")}function aS({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,w,S,y,x,_,C,I,b,E,F,R,q,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 L=p.value,pe=L.event_type;switch(pe){case"interaction.created":{let k=L.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,J;if(typeof X==="string"){let H=new Date(X);if(!Number.isNaN(H.getTime()))J=H}f.enqueue({type:"response-metadata",...i!=null?{id:i}:{},modelId:k==null?void 0:k.model,...J?{timestamp:J}:{}});break}case"step.start":{let Q=L,k=Q.step,X=Q.index,J=`${i!=null?i:"interaction"}:${X}`,H=k==null?void 0:k.type;if(H==="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:J,emittedSourceKeys:new Set}),f.enqueue({type:"text-start",id:J});let D=Su({annotations:K.annotations,generateId:t});for(let B of D){let G=m(B);if(d.has(G))continue;d.add(G),f.enqueue(B)}}else if((K==null?void 0:K.type)==="image")u.set(X,{kind:"image",id:J,...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:J})}else if(H==="thought"){let K=k==null?void 0:k.signature;if(u.set(X,{kind:"reasoning",id:J,...K!=null?{signature:K}:{}}),f.enqueue({type:"reasoning-start",id:J}),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:J,delta:D.text})}}else if(H==="function_call"){let K=(h=k==null?void 0:k.id)!=null?h:J,D=(v=k==null?void 0:k.name)!=null?v:"unknown";c=!0;let B={kind:"function_call",id:J,toolCallId:K,toolName:D,argumentsAccum:"",...(k==null?void 0:k.signature)!=null?{signature:k.signature}:{}};u.set(X,B),f.enqueue({type:"tool-input-start",id:K,toolName:D})}else if(H!=null&&X2.has(H)){let K=H==="mcp_server_tool_call"?(w=k==null?void 0:k.name)!=null?w:"mcp_server_tool":tz(H),D=(S=k==null?void 0:k.id)!=null?S:J,B={kind:"builtin_tool_call",id:J,blockType:H,toolCallId:D,toolName:K,arguments:(y=k==null?void 0:k.arguments)!=null?y:{},callEmitted:!1};u.set(X,B)}else if(H!=null&&ez.has(H)){let K=H==="mcp_server_tool_result"?(x=k==null?void 0:k.name)!=null?x:"mcp_server_tool":rz(H),D=(_=k==null?void 0:k.call_id)!=null?_:J,B={kind:"builtin_tool_result",id:J,blockType:H,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,B)}else u.set(X,{kind:"unknown",id:J});break}case"step.delta":{let Q=L,k=u.get(Q.index);if(k==null)break;let X=(I=Q.delta)==null?void 0:I.type;if(k.kind==="pending_model_output"){if(X==="text"||X==="text_annotation"||X==="text_annotation_delta"){let H={kind:"text",id:k.id,emittedSourceKeys:new Set};u.set(Q.index,H),k=H,f.enqueue({type:"text-start",id:H.id})}}if(X==="image"&&(k.kind==="pending_model_output"||k.kind==="text"||k.kind==="image")){let H=Q.delta,K={};if(i!=null)K.interactionId=i;let D=Object.keys(K).length>0?{google:K}:void 0;if((H==null?void 0:H.data)!=null&&H.data.length>0)f.enqueue({type:"file",mediaType:(b=H.mime_type)!=null?b:"image/png",data:H.data,...D?{providerMetadata:D}:{}});else if((H==null?void 0:H.uri)!=null&&H.uri.length>0){let B={google:{...i!=null?{interactionId:i}:{},imageUri:H.uri}};f.enqueue({type:"file",mediaType:(E=H.mime_type)!=null?E:"image/png",data:"",providerMetadata:B})}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 H=Q.delta,K={};if(i!=null)K.interactionId=i;let D=Object.keys(K).length>0?{google:K}:void 0;if((H==null?void 0:H.data)!=null&&H.data.length>0)f.enqueue({type:"file",mediaType:(F=H.mime_type)!=null?F:"video/mp4",data:H.data,...D?{providerMetadata:D}:{}});else if((H==null?void 0:H.uri)!=null&&H.uri.length>0){let B={google:{...i!=null?{interactionId:i}:{},videoUri:H.uri}};f.enqueue({type:"file",mediaType:(R=H.mime_type)!=null?R:"video/mp4",data:"",providerMetadata:B})}break}let J=Q.delta;if(k.kind==="text"&&(J==null?void 0:J.type)==="text"){let H=(q=J.text)!=null?q:"";if(H.length>0)f.enqueue({type:"text-delta",id:k.id,delta:H})}else if(k.kind==="text"&&((J==null?void 0:J.type)==="text_annotation"||(J==null?void 0:J.type)==="text_annotation_delta")){let H=Su({annotations:J.annotations,generateId:t});for(let K of H){let D=m(K);if(d.has(D))continue;d.add(D),k.emittedSourceKeys.add(D),f.enqueue(K)}}else if(k.kind==="image"&&(J==null?void 0:J.type)==="image"){if(J.data!=null)k.data=J.data;if(J.mime_type!=null)k.mimeType=J.mime_type;if(J.uri!=null)k.uri=J.uri}else if(k.kind==="reasoning"){if((J==null?void 0:J.type)==="thought_summary"){let H=J.content;if((H==null?void 0:H.type)==="text"&&typeof H.text==="string")f.enqueue({type:"reasoning-delta",id:k.id,delta:H.text})}else if((J==null?void 0:J.type)==="thought_signature"){let H=J.signature;if(H!=null)k.signature=H}}else if(k.kind==="function_call"&&(J==null?void 0:J.type)==="arguments_delta"){let H=typeof J.arguments==="string"?J.arguments:"";if(H.length>0)k.argumentsAccum+=H,f.enqueue({type:"tool-input-delta",id:k.toolCallId,delta:H});if(J.id!=null)k.toolCallId=J.id;if(J.signature!=null)k.signature=J.signature;c=!0}else if(k.kind==="builtin_tool_call"&&(J==null?void 0:J.type)===k.blockType){if(J.id!=null)k.toolCallId=J.id;if(J.arguments!=null&&typeof J.arguments==="object")k.arguments=J.arguments;if(J.name!=null&&k.blockType==="mcp_server_tool_call")k.toolName=J.name}else if(k.kind==="builtin_tool_result"&&(J==null?void 0:J.type)===k.blockType){if(J.call_id!=null)k.callId=J.call_id;if(J.result!==void 0)k.result=J.result;if(J.is_error!=null)k.isError=J.is_error;if(J.name!=null&&k.blockType==="mcp_server_tool_result")k.toolName=J.name}break}case"step.stop":{let Q=L,k=u.get(Q.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 J=Object.keys(X).length>0?{google:X}:void 0;f.enqueue({type:"reasoning-end",id:k.id,...J?{providerMetadata:J}:{}})}else if(k.kind==="image"){let X={};if(i!=null)X.interactionId=i;let J=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,...J?{providerMetadata:J}:{}});else if(k.uri!=null&&k.uri.length>0){let H={google:{...i!=null?{interactionId:i}:{},imageUri:k.uri}};f.enqueue({type:"file",mediaType:(N=k.mimeType)!=null?N:"image/png",data:"",providerMetadata:H})}}else if(k.kind==="function_call"){let X=k.argumentsAccum.length>0?k.argumentsAccum:"{}";f.enqueue({type:"tool-input-end",id:k.toolCallId});let J={};if(k.signature!=null)J.signature=k.signature;if(i!=null)J.interactionId=i;let H=Object.keys(J).length>0?{google:J}:void 0;f.enqueue({type:"tool-call",toolCallId:k.toolCallId,toolName:k.toolName,input:X,...H?{providerMetadata:H}:{}})}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=_S({block:{type:k.blockType,call_id:k.callId,result:k.result},generateId:t});for(let J of X){let H=m(J);if(d.has(H))continue;d.add(H),f.enqueue(J)}}u.delete(Q.index);break}case"interaction.status_update":case"interaction.in_progress":case"interaction.requires_action":{let Q=L;if(Q.status!=null)l=Q.status;else if(pe==="interaction.requires_action")l="requires_action";else l="in_progress";break}case"interaction.completed":{let k=L.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 Q=L;l="failed";let k=(V=Q.error)!=null?V:{message:"Unknown interaction error"};f.enqueue({type:"error",error:k});break}default:break}},flush(p){let f={unified:Iu({status:l,hasFunctionCall:c}),raw:l},g=yS(a),h={google:{...i!=null?{interactionId:i}:{},...s!=null?{serviceTier:s}:{},...g!=null?{outputTokensByModality:g}:{}}};p.enqueue({type:"finish",finishReason:f,usage:Tu(a),providerMetadata:h})}})}function SS(e){let t=e.indexOf("/");return t===-1?e:e.substring(0,t)}function rs(e){let t=e.indexOf("/");if(t===-1)return!1;let n=e.substring(t+1);return n.length>0&&n!=="*"}function nz({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?oz({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=sS({part:_,warnings:m,mediaResolution:o});if(C!=null)y.push(C)}let x=sz(y);if(x.length>0)v.push({type:"user_input",content:x});break}case"assistant":{let y=[],x=()=>{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"){x();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=sS({part:_,warnings:m,mediaResolution:o});if(C!=null)y.push(C)}else if(_.type==="tool-call"){x();let C=(l=(s=_.providerOptions)==null?void 0:s.google)==null?void 0:l.signature,I=typeof _.input==="string"?iz(_.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.`});x();break}case"tool":{let y=[];for(let x of S.content){if(x.type!=="tool-result"){m.push({type:"other",message:`google.interactions: unsupported tool message part type "${x.type}"; part dropped.`});continue}let _=az({toolCallId:x.toolCallId,toolName:x.toolName,output:x.output,signature:(d=(u=x.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 w=h.length>0?h.join(`
|
|
87
|
-
|
|
88
|
-
`):void 0;return{input:v,systemInstruction:w,warnings:m}}function sS({part:e,warnings:t,mediaResolution:n}){let o=SS(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(),...rs(e.mediaType)?{mime_type:e.mediaType}:{},...a};if(!rs(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 oz({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 iz(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 az({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=bu({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=bu({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(SS(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=bu({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 bu({part:e,warnings:t}){if(e.data instanceof URL)return{type:"image",uri:e.data.toString(),...rs(e.mediaType)?{mime_type:e.mediaType}:{}};if(!rs(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 sz(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 es=()=>r.object({modality:r.string().nullish(),tokens:r.number().nullish()}).loose(),wS=()=>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(es()).nullish(),output_tokens_by_modality:r.array(es()).nullish(),cached_tokens_by_modality:r.array(es()).nullish(),tool_use_tokens_by_modality:r.array(es()).nullish(),grounding_tool_count:r.array(r.object({type:r.string().nullish(),count:r.number().nullish()}).loose()).nullish()}).loose(),xS=()=>r.enum(["in_progress","requires_action","completed","failed","cancelled","incomplete"]),TS=()=>{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()])},IS=()=>r.object({type:r.string(),text:r.string().nullish(),data:r.string().nullish(),mime_type:r.string().nullish()}).loose(),lS=()=>{let e=r.object({type:r.literal("text"),text:r.string(),annotations:r.array(TS()).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()])},CS=["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"],kS=["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"],RS=()=>{let e=r.object({type:r.literal("user_input"),content:r.array(lS()).nullish()}).loose(),t=r.object({type:r.literal("model_output"),content:r.array(lS()).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(IS()).nullish()}).loose(),i=r.object({type:r.enum(CS),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(kS),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()])},wu=j(()=>M(r.object({id:r.string().nullish(),created:r.string().nullish(),updated:r.string().nullish(),status:xS(),model:r.string().nullish(),agent:r.string().nullish(),steps:r.array(RS()).nullish(),usage:wS().nullish(),service_tier:r.string().nullish(),previous_interaction_id:r.string().nullish(),response_modalities:r.array(r.string()).nullish()}).loose())),ES=j(()=>M((()=>{let e=xS(),t=TS(),n=IS(),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:RS()}).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(CS),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(kS),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(),w=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(),x=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:wS().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,w,S,y,x,_,C,I])})())),lz=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 cz=new Set(["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"]),uz=new Set(["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"]);function dz(e){return e.replace(/_call$/,"")}function pz(e){return e.replace(/_result$/,"")}function AS({steps:e,generateId:t,interactionId:n}){var o,i,a,s,l,c,u,d,m,p,f,g,h;let v=[],w=!1;if(e==null)return{content:v,hasFunctionCall:w};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 x=(o=S.content)!=null?o:[];for(let _ of x){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=Su({annotations:b,generateId:t});for(let F of E)v.push(F)}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 x=S,C=(Array.isArray(x.summary)?x.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:x.signature,interactionId:n})});break}case"function_call":{w=!0;let x=S;v.push({type:"tool-call",toolCallId:x.id,toolName:x.name,input:JSON.stringify((u=x.arguments)!=null?u:{}),...$i({signature:x.signature,interactionId:n})});break}default:{if(cz.has(y)){let x=S,_=y==="mcp_server_tool_call"?(d=x.name)!=null?d:"mcp_server_tool":dz(y),C=JSON.stringify((m=x.arguments)!=null?m:{});v.push({type:"tool-call",toolCallId:(p=x.id)!=null?p:t(),toolName:_,input:C,providerExecuted:!0})}else if(uz.has(y)){let x=S,_=y==="mcp_server_tool_result"?(f=x.name)!=null?f:"mcp_server_tool":pz(y);v.push({type:"tool-result",toolCallId:(g=x.call_id)!=null?g:t(),toolName:_,result:(h=x.result)!=null?h:null});let C=_S({block:S,generateId:t});for(let I of C)v.push(I)}break}}}return{content:v,hasFunctionCall:w}}var mz=()=>globalThis.fetch;async function PS({baseURL:e,interactionId:t,headers:n,fetch:o=mz()}){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 gz=new Set(["completed","failed","cancelled","incomplete"]);function xu(e){return e!=null&&gz.has(e)}var fz=1000,hz=1e4,yz=1800000;async function vz({baseURL:e,interactionId:t,headers:n,fetch:o,abortSignal:i,initialDelayMs:a=fz,maxDelayMs:s=hz,timeoutMs:l=yz}){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=()=>PS({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(wu),abortSignal:i,fetch:o});if(xu(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 bz({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 _z=3,Sz=500;function wz({baseURL:e,interactionId:t,headers:n,fetch:o,abortSignal:i,maxRetries:a=_z,retryDelayMs:s=Sz}){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 w(){let{value:S}=await Xt({url:v(),headers:l,failedResponseHandler:or,successfulResponseHandler:Dt(ES),abortSignal:h,fetch:o});return S.getReader()}return new ReadableStream({async start(S){try{while(!u&&!h.aborted){if(p==null)try{p=await w(),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:x}=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,x.success){let _=x.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(x)}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 PS({baseURL:e,interactionId:t,headers:n,fetch:o})}},cancel(){f.abort(),p==null||p.cancel().catch(()=>{}),p=void 0}})}function xz({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}=AS({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 x=h(),_=y.providerMetadata;if(a.enqueue({type:"text-start",id:x}),y.text.length>0)a.enqueue({type:"text-delta",id:x,delta:y.text});a.enqueue({type:"text-end",id:x,..._?{providerMetadata:_}:{}});break}case"reasoning":{let x=h(),_=y.providerMetadata;if(a.enqueue({type:"reasoning-start",id:x}),y.text.length>0)a.enqueue({type:"reasoning-delta",id:x,delta:y.text});a.enqueue({type:"reasoning-end",id:x,..._?{providerMetadata:_}:{}});break}case"tool-call":{let x=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}:{},...x?{providerMetadata:x}:{}});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,w={unified:Iu({status:e.status,hasFunctionCall:f}),raw:e.status},S={google:{...u!=null?{interactionId:u}:{},...v!=null?{serviceTier:v}:{}}};a.enqueue({type:"finish",finishReason:w,usage:Tu(e.usage),providerMetadata:S}),a.close()}})}var Tz=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,w,S,y,x,_,C,I,b,E,F;let R=[],q=await Ue({provider:"google",providerOptions:e.providerOptions,schema:lz}),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 B=bz({tools:e.tools,toolChoice:e.toolChoice});re=B.tools,Y=B.toolChoice,R.push(...B.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 B={type:"text",mime_type:"application/json",...e.responseFormat.schema!=null?{schema:e.responseFormat.schema}:{}};V.push(B)}if((q==null?void 0:q.responseFormat)!=null){for(let B of q.responseFormat)if(B.type==="text")V.push(Vr({type:"text",mime_type:(n=B.mimeType)!=null?n:void 0,schema:(o=B.schema)!=null?o:void 0}));else if(B.type==="image")V.push(Vr({type:"image",mime_type:(i=B.mimeType)!=null?i:void 0,aspect_ratio:(a=B.aspectRatio)!=null?a:void 0,image_size:(s=B.imageSize)!=null?s:void 0}));else if(B.type==="audio")V.push(Vr({type:"audio",mime_type:(l=B.mimeType)!=null?l:void 0}))}let{input:L,systemInstruction:pe,warnings:Q}=nz({prompt:e.prompt,previousInteractionId:(c=q==null?void 0:q.previousInteractionId)!=null?c:void 0,store:(u=q==null?void 0:q.store)!=null?u:void 0,mediaResolution:(d=q==null?void 0:q.mediaResolution)!=null?d:void 0});R.push(...Q);let k=pe,X=(m=q==null?void 0:q.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 J;if(z){let B=[];if(e.temperature!=null)B.push("temperature");if(e.topP!=null)B.push("topP");if(e.seed!=null)B.push("seed");if(e.stopSequences!=null&&e.stopSequences.length>0)B.push("stopSequences");if(e.maxOutputTokens!=null)B.push("maxOutputTokens");if((q==null?void 0:q.thinkingLevel)!=null)B.push("thinkingLevel");if((q==null?void 0:q.thinkingSummaries)!=null)B.push("thinkingSummaries");if((q==null?void 0:q.imageConfig)!=null)B.push("imageConfig");if(B.length>0)R.push({type:"other",message:`google.interactions: ${B.join(", ")} ${B.length===1?"is":"are"} not supported when an agent is set; use providerOptions.google.agentConfig instead. Dropped from the request body.`});J=void 0}else if(J=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=q==null?void 0:q.thinkingLevel)!=null?v:void 0,thinking_summaries:(w=q==null?void 0:q.thinkingSummaries)!=null?w:void 0,tool_choice:Y}),(q==null?void 0:q.imageConfig)!=null){let B=V.some((G)=>G.type==="image");if(R.push({type:"other",message:B?"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.'}),!B)V.push({type:"image",mime_type:"image/png",...q.imageConfig.aspectRatio!=null?{aspect_ratio:q.imageConfig.aspectRatio}:{},...q.imageConfig.imageSize!=null?{image_size:q.imageConfig.imageSize}:{}})}let H;if(z&&(q==null?void 0:q.agentConfig)!=null){let B=q.agentConfig;if(B.type==="deep-research")H=Vr({type:"deep-research",thinking_summaries:(S=B.thinkingSummaries)!=null?S:void 0,visualization:(y=B.visualization)!=null?y:void 0,collaborative_planning:(x=B.collaborativePlanning)!=null?x:void 0});else if(B.type==="dynamic")H={type:"dynamic"}}let K;if((q==null?void 0:q.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 q.environment==="string")K=q.environment;else{let B=q.environment,G=(_=B.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(B.network==="disabled")Z="disabled";else if(B.network!=null)Z={allowlist:B.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:L,system_instruction:k,tools:re,response_format:V.length>0?V:void 0,response_modalities:(q==null?void 0:q.responseModalities)!=null?q.responseModalities:void 0,previous_interaction_id:(C=q==null?void 0:q.previousInteractionId)!=null?C:void 0,service_tier:(I=q==null?void 0:q.serviceTier)!=null?I:void 0,store:(b=q==null?void 0:q.store)!=null?b:void 0,generation_config:J!=null&&Object.keys(J).length>0?J:void 0,agent_config:H,environment:K,background:(E=q==null?void 0:q.background)!=null?E:void 0}),warnings:R,isAgent:z,isBackground:(q==null?void 0:q.background)===!0,pollingTimeoutMs:(F=q==null?void 0:q.pollingTimeoutMs)!=null?F: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(cS,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(wu),abortSignal:e.abortSignal,fetch:this.config.fetch}),{responseHeaders:g,value:h,rawValue:v}=f;if(u&&!xu(h.status)){let E=await vz({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 w=typeof h.id==="string"&&h.id.length>0?h.id:void 0,{content:S,hasFunctionCall:y}=AS({steps:(n=h.steps)!=null?n:null,generateId:(o=this.config.generateId)!=null?o:qe,interactionId:w}),x={unified:Iu({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=yS(h.usage),I={google:{...w!=null?{interactionId:w}:{},..._!=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:x,usage:Tu(h.usage),warnings:c,providerMetadata:I,request:{body:l},response:{headers:g,body:v,...w!=null?{id:w}:{},...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(cS,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(ES),abortSignal:e.abortSignal,fetch:this.config.fetch}),m=u==null?void 0:u["x-gemini-service-tier"],p=aS({warnings:o,generateId:(t=this.config.generateId)!=null?t:qe,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(wu),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(xu(d.status))return{stream:xz({response:d,warnings:t,generateId:(s=this.config.generateId)!=null?s:qe,includeRawChunks:i.includeRawChunks,headerServiceTier:p}),request:{body:e},response:{headers:u}};let f=wz({baseURL:this.config.baseURL,interactionId:m,headers:o,fetch:this.config.fetch,abortSignal:i.abortSignal}),g=aS({warnings:t,generateId:(l=this.config.generateId)!=null?l:qe,includeRawChunks:i.includeRawChunks,serviceTier:p});return{stream:f.pipeThrough(g),request:{body:e},response:{headers:u}}}},cS={"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 Iz=["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"],Cz=/^https:\/\/.*$/;function kz(e){return/(^|\/)gemini-/.test(e)&&!/(^|\/)gemini-2\.0/.test(e)}function ns(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/${a2}`),s=(p)=>{var f;return new dS(p,{provider:i,baseURL:o,headers:a,generateId:(f=e.generateId)!=null?f:qe,supportedUrls:()=>({"*":[new RegExp(`^${o}/files/.*$`),new RegExp("^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$"),new RegExp("^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$")],...kz(p)?Object.fromEntries(Iz.map((g)=>[g,[Cz]])):{}}),fetch:e.fetch})},l=(p)=>new u2(p,{provider:i,baseURL:o,headers:a,fetch:e.fetch}),c=(p,f={})=>new L2(p,f,{provider:i,baseURL:o,headers:a,fetch:e.fetch}),u=(p)=>{var f;return new Z2(p,{provider:i,baseURL:o,headers:a,fetch:e.fetch,generateId:(f=e.generateId)!=null?f:qe})},d=(p)=>{var f;return new Tz(p,{provider:`${i}.interactions`,baseURL:o,headers:a,generateId:(f=e.generateId)!=null?f:qe,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=q2,m}var RK=ns();function Cu(e){let t=e.model?nu(e.model):void 0,n=e.apiKey,o=e.imageApiKey??e.apiKey;return{anthropicProvider:n?cu({apiKey:n}):b_,openaiProvider:t==="openai"&&n?_o({apiKey:n}):o?_o({apiKey:o}):null,googleProvider:t==="google"&&n?ns({apiKey:n}):o?ns({apiKey:o}):null}}function MS(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 jS(e){return e.openaiProvider!==null||e.googleProvider!==null}function OS(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 NS(e,t,n,o,i){let a=n?.signal;a?.throwIfAborted();let{provider:s,modelId:l}=ou(t),c=OS(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 ru({model:c,prompt:e,aspectRatio:u,...a?{abortSignal:a}:{}}):await ru({model:c,prompt:e,size:Rz[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 Rz={"1:1":"1024x1024","16:9":"1536x1024","9:16":"1024x1536","4:3":"1536x1024","3:4":"1024x1536"};function ku(e){return{...e,temperature:e.temperature??0.7,maxTokens:e.maxTokens??1000,webSearch:e.webSearch??!0}}function Ru(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 qi{config;logger;providers;capabilities;cachedModel=null;static createFresh(e,t){return new qi(e,t)}constructor(e,t){this.config=ku(e),this.logger=t.child("AIService"),this.providers=Cu(this.config),this.capabilities=Di(this.config.model)}getModel(){return this.cachedModel??=MS(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 tu({model:this.getModel(),system:e,prompt:t,...n?{abortSignal:n}:{},...Ru(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=Ru(this.config,this.capabilities.provider,this.capabilities.supportsTemperature),a=await Vb({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 Xa(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=ku({...this.config,...e});let n=this.config.model!==t;if(e.apiKey!==void 0||e.imageApiKey!==void 0||n)this.providers=Cu(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 jS(this.providers)}async generateImage(e,t){return NS(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 Ez="text-embedding-3-small",Az=1536;class Li{model;dimensions;openai;logger;static createFresh(e){return new Li(e)}constructor(e){if(!e.apiKey)throw Error("API key is required for online embedding provider");this.model=e.model??Ez,this.dimensions=e.dimensions??Az,this.logger=e.logger.child("OnlineEmbeddingProvider"),this.openai=_o({apiKey:e.apiKey})}async generateEmbedding(e,t){t?.throwIfAborted(),this.logger.debug(`Generating embedding for text (${e.length} chars)`);let{embedding:n,usage:o}=await Hb({model:this.openai.embedding(this.model),value:e,...t?{abortSignal:t}:{},providerOptions:{openai:{dimensions:this.dimensions}}});return{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 Wb({model:this.openai.embedding(this.model),values:e,...t?{abortSignal:t}:{},providerOptions:{openai:{dimensions:this.dimensions}}});return{embeddings:n.map((i)=>new Float32Array(i)),usage:{tokens:o.tokens}}}}var Pz=new Set(["system_search","system_get","system_list"]);function Zr(e){return Pz.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=os.safeParse(e.guestExecution);if(!t.success)throw Error("Guest execution limits required");return t.data}function Eu(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 DS=`## 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(Dw(),1);var Tt={promptTokens:0,completionTokens:0,totalTokens:0},$L=r.record(r.string(),r.unknown());function qL(e){let t=$L.safeParse(e);return t.success?t.data:void 0}function LL(e){return e?fs(e.identity):void 0}function zw(e,t){let n=LL(t.actor);return e.map((o)=>({...o,requester:{...n?{actorKey:n}:{},userPermissionLevel:t.userPermissionLevel}}))}function Ku(e,t){return e.pendingConfirmations.find((n)=>n.id===t)??null}function Yu(e,t){return e.pendingConfirmations.filter((n)=>n.id!==t)}function FL({context:e,event:t}){if(t.type!=="CONFIRM"&&t.type!=="CANCEL")return!1;return Yu(e,t.approvalId).length>0}function Uw(e){let t=e?.summary??"unknown action",n=qL(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 $w=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:zw(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:Ku(e,t.approvalId),pendingConfirmations:Yu(e,t.approvalId)}))},CANCEL:[{guard:FL,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:Uw(Ku(e,t.approvalId)),pendingConfirmations:Yu(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:Uw(Ku(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,...zw(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 BL=10;function GL(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 Qu{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??BL,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)}),GL(l,o)}scheduleEviction(e){if(this.closed)return;let t=this.cancelEviction(e);if(this.idleTtlMs<=0)return;let n=this.evictionGeneration,o=de.sleep(this.idleTtlMs).pipe(de.andThen(de.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?de.withClock(o,this.clock):o,a=de.runFork(i);hs.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([de.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=hs.unsafeGet(this.evictionSupervisor.fibers,e);if(qw.isSome(n))de.runSync(Ki.interruptFork(n.value));return t}assertOpen(){if(this.closed)throw this.closeReason}createEvictionSupervisor(){let e=de.runSync(Xe.make()),t=de.runSync(Xe.extend(hs.make(),e));return{scope:e,fibers:t}}}function JL(e){return e?fs(e.identity):void 0}function Xu(e,t){if(t.userPermissionLevel==="admin")return!0;let n=e.requester.actorKey;if(n){if(JL(t.actor)!==n)return!1}return ys.hasPermission(t.userPermissionLevel,e.requester.userPermissionLevel)}function HL(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 ed{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=HL(o,s.context);if(!c)return{text:"Confirmation requires caller context.",usage:Tt};if(!Xu(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 WL=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 Lw(e){if(!WL.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 Fw(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 VL(e){return e.mediaType.startsWith("image/")}function ZL(e){return e.mediaType==="application/pdf"}function KL(e){return e.kind==="text"||e.mediaType.startsWith("text/")}function Bw(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(VL(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(ZL(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(KL(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 Gw(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 Jw(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 YL=r.record(r.string(),r.unknown()),Qw=r.looseObject({jobId:r.string()}),od=r.looseObject({id:r.string().min(1),entityType:r.string().min(1),content:r.string().optional(),metadata:r.record(r.string(),r.unknown()).default({})}),QL=r.looseObject({entity:od,score:r.number().finite().optional(),excerpt:r.string().optional()}),XL=r.object({results:r.array(QL)}),eF=r.object({entity:od}),tF=r.custom((e)=>Zw.safeParse(e).success,"expected structured chat card"),rF=r.object({cards:r.array(tF)}),nF=r.object({currentState:r.object({prompt:r.string().min(1).optional()})}),oF=r.object({entities:r.array(od)}),iF=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 aF(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 sF(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 Xw(e){for(let t of e){let n=nF.safeParse(t.data);if(n.success&&n.data.currentState.prompt)return n.data.currentState.prompt}return}function id(e){let t=Qw.safeParse(e),n=iF.safeParse(e);if(!n.success)return;let{attachmentId:o,attachment:i}=n.data,a=i.source,s=aF(i.mediaType),l=sF(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&>(a)})}}}var Hw=500,lF=3;function nd(e){let t=e.trim();if(t.length<=Hw)return t;return`${t.slice(0,Hw-1).trimEnd()}\u2026`}function td(e,t){let n=e?.[t];return typeof n==="string"&&n.length>0?n:void 0}function ex(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:nd(t.content),...gt({title:t.title,url:td(t.provenance,"url"),entityType:td(t.provenance,"entityType"),entityId:td(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 tx(e){return Fn(e.metadata,"title")??Fn(e.metadata,"name")??Fn(e.metadata,"slug")??e.id}function cF(e){return Fn(e.metadata,"url")??Fn(e.metadata,"permalink")??Fn(e.metadata,"canonicalUrl")}function Ww(e){let{entity:t,toolName:n,score:o}=e,i=e.excerpt!==void 0?nd(e.excerpt):t.content!==void 0?nd(t.content):void 0,a=cF(t);return{id:`${t.entityType}:${t.id}`,title:tx(t),source:t.entityType,entityType:t.entityType,entityId:t.id,...gt({url:a,excerpt:i}),provenance:{toolName:n,...gt({score:o})}}}function uF(e){if(e.toolName==="system_search"){let t=XL.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:Ww({toolName:e.toolName,entity:n.entity,excerpt:n.excerpt,score:n.score})}))}if(e.toolName==="system_get"){let t=eF.safeParse(e.data);if(!t.success)return[];return[{citation:Ww({toolName:e.toolName,entity:t.data.entity})}]}return[]}function Vw(e){return` ${e.toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").trim()} `}function dF(e,t){let n=t===void 0?"":Vw(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=Vw(l);return c.trim().length>=4&&n.includes(c)});return[...i.length>0?i:o.filter((s)=>(s.rank??0)<lF),...e.filter((s)=>s.rank===void 0)].map((s)=>s.citation)}function rx(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 nx(e,t){let n=rx(t);if(!n)return e;return[...e.filter((o)=>o.kind!=="sources"||o.id!==n.id),n]}function ad(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=YL.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=bs.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}`,x=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:x,completionSummary:f.data.completionSummary,preview:f.data.preview})});continue}let g=Yw.safeParse(p.output);if(!g.success){n.push({toolName:p.toolName});continue}let h=vs.safeParse(g.data);if(h.success&&h.data.cached===!0)continue;let v=p.toolCallId?u.get(p.toolCallId):void 0,w={toolName:p.toolName};if(v!==void 0)w.args=v;let S=Kw.safeParse(g.data);if(S.success)w.error={message:S.data.error,...gt({code:S.data.code})};if(h.success&&h.data.data!=null){w.data=h.data.data;let y=Qw.safeParse(h.data.data);if(y.success)w.jobId=y.data.jobId;let x=rF.safeParse(h.data.data);if(x.success)o.push(...x.data.cards);let _=id(h.data.data);if(_)o.push(_);i.push(...uF({toolName:p.toolName,data:h.data.data}))}n.push(w)}if(d)break}let l=rx(dF(i,t));if(l)o.push(l);return{toolResults:n,pendingConfirmations:a,cards:o,totalToolCalls:s}}var pF=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 rd(e){return e===void 0||e===""?void 0:e}var mF=r.object({entityType:r.string().optional(),id:r.string().optional(),title:r.string().optional()}),ox=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()}),sd=r.object({source:r.object({kind:r.literal("url"),url:r.string().min(1)})}),gF=r.object({agent:r.string().min(1)}),fF=r.object({agentContactCandidate:sd});function ix(e){let t=new Set,n=[];for(let o of e){if(o.toolName!=="agent_call")continue;let i=fF.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=gF.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 ax(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 Yi(e){let t=new Set,n=[];for(let o of e){let i=pF.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=mF.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:rd(u),title:rd(d),status:rd(l)})});continue}if(o.toolName!=="system_list")continue;let s=oF.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=tx(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 sx(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 hF(e){return e.map((t)=>t.role==="user"?{role:"user",content:t.content}:{role:"assistant",content:[{type:"text",text:t.content+yF(t.metadata)+vF(t.metadata)}]})}function yF(e){let t=No(e),n=_F(t?.entityMemoryRefs);return sx(n)}function vF(e){let t=No(e),n=bF(t?.agentContactCandidates);return ax(n)}function bF(e){if(!Array.isArray(e))return[];return e.flatMap((t)=>{let n=sd.safeParse(t);return n.success?[n.data]:[]})}function _F(e){if(!Array.isArray(e))return[];return e.flatMap((t)=>{let n=ox.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 lx={public:0,trusted:1,admin:2};function ld(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 lx[i]<=lx[t]})}function cd(e,t){return[...hF(e),{role:"user",content:t}]}function SF(e){return`${e.source.kind}:${e.source.id}`}function cx(e){if(e.source===void 0)return null;return{filename:e.filename,mediaType:e.mediaType,source:e.source}}function wF(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 ud(e){return e!==null}function xF(e){let t=e.flatMap((n)=>{let i=No(n.metadata)?.attachments;if(!Array.isArray(i))return[];return i.map(wF).filter(ud)});return dd(t)}var TF=6;function ux(e){let t=IF({message:e.message,currentAttachments:e.currentAttachments,historyMessages:e.historyMessages}),n=t.length>0?RF(e.historyMessages):void 0;return{kind:"selected",message:e.message,refs:t,attachments:e.currentAttachments,...n?{priorResponseRef:n}:{}}}function IF(e){let t=e.currentAttachments.map(cx).filter(ud),n=xF(e.historyMessages).slice(-TF).reverse(),o=dd([...t,...n]),i=CF(e.message);if(i===void 0)return o;return o.filter((a)=>kF(a,i)).slice(0,1)}function CF(e){let t=e.toLowerCase();if(t.includes("uploaded image"))return"image";if(t.includes("uploaded pdf"))return"pdf";return}function kF(e,t){if(t==="image")return e.mediaType.startsWith("image/");return e.mediaType==="application/pdf"}function dd(e){let t=new Set,n=[];for(let o of e){let i=SF(o);if(t.has(i))continue;t.add(i),n.push(o)}return n}function RF(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(EF(n))continue;if(AF(n))continue;return{messageId:n.id}}return}function EF(e){let t=No(e.metadata);return Array.isArray(t?.entityMemoryRefs)}function AF(e){let n=No(e.metadata)?.cards;if(!Array.isArray(n))return!1;return n.some((o)=>yr(o)&&o.kind==="actions")}function dx(e,t,n={}){let o=t??[],i=o.filter((l)=>l.kind==="text").map(PF),a=[e,...i,MF(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 PF(e){return`User uploaded a file "${e.filename}":
|
|
108
|
-
|
|
109
|
-
${e.content}`}function MF(e,t,n){let o=e.map(cx).filter(ud),i=dd([...t,...o]).map(jF),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 jF(e){return[`- ${e.filename}`,`upload: { kind: "${e.source.kind}", id: "${e.source.id}" }`,`mediaType: ${e.mediaType}`].join("; ")}function pd(e){if(e===void 0)return;return e.length===0?OF():NF(e)}function OF(){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 NF(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)=>DF(n,o)).join(`
|
|
111
|
-
|
|
112
|
-
`)].join(`
|
|
113
|
-
`)}function DF(e,t){let n=e.title??e.id,o=zF(e.provenance);return[`${t+1}. ${n} [${e.source}]`,e.content.trim(),...o?[`Provenance: ${o}`]:[]].join(`
|
|
114
|
-
`)}function zF(e){if(!e)return;let t=Object.entries(e).filter(([,n])=>n!==void 0&&n!==null&&n!=="").map(([n,o])=>`${n}=${UF(o)}`);return t.length>0?t.join(", "):void 0}function UF(e){if(typeof e==="string")return e;if(typeof e==="number"||typeof e==="boolean")return String(e);return JSON.stringify(e)}var $F="brain:assistant",qF="Assistant";function md(e){if(!e)return;let t=Qr(e);return t?`brain:${t}`:void 0}function gd(e){let t=e.character.name.trim()||qF;return{identity:{kind:"agent",agentId:e.agentId??$F},interfaceType:"agent",role:"assistant",displayName:t,isBot:!0}}function px(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 LF=r.record(r.string(),r.unknown()),FF=r.looseObject({success:r.literal(!1)});function hd(e){let t=LF.safeParse(e);return t.success?t.data:void 0}function fd(e,t){let o=hd(e)?.[t];return typeof o==="string"?o:void 0}function BF(e){return FF.safeParse(e).success}function GF(e){return e.trim().replace(/[?\uFF1F]+$/u,"")}var JF=new Set(["confirmed","confirmationToken","contentHash"]);function HF(e){let t=hd(e);if(!t)return;return Object.fromEntries(Object.entries(t).filter(([n])=>!JF.has(n)))}function mx(e,t){let n=BF(t),o=n?"Failed":"Completed",i=n?fd(t,"error")??fd(t,"message"):void 0,a=GF(n?e.summary:e.completionSummary??e.summary),s=i?`${o}: ${a}
|
|
115
|
-
|
|
116
|
-
${i}`:`${o}: ${a}`,l=hd(e.args),c={toolName:e.toolName,data:t,...l?{args:l}:{}},u=HF(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:fd(t,"error")??"Action failed"}:{}},m=vs.safeParse(t),p=m.success?id(m.data.data):void 0,f=[d,...p?[p]:[]],g=m.success?Yi([{...c,data:m.data.data}]):[];return{resultText:s,toolResult:c,cards:f,entityMemoryRefs:g}}function WF(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 gx(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)=>WF(d))}:{},...a.length>0?{cards:a}:{},...s.length>0?{entityMemoryRefs:s}:{},...l.length>0?{agentContactCandidates:l}:{}}}function fx(e){return Object.keys(e).length>0?{metadata:e}:{}}class yd{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=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,i)}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=Fw(l),u=Bw(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=ld(u,l).map((w)=>e.guest?{...w,metadata:null}:w),m=ux({message:o,currentAttachments:c,historyMessages:d}),p=await Gw({refs:m.refs,resolver:this.deps.uploadAttachmentResolver,logger:this.deps.logger}),f=m.message,g=await Jw({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=dx(f,g,{uploadRefs:p,...m.priorResponseRef?{priorResponseRef:m.priorResponseRef}:{}});return{effectiveMessage:f,effectiveAttachments:g,uploadRefs:p,hasPriorResponseCandidate:m.priorResponseRef!==void 0,contextItems:h,messages:cd(d,v),agentContextInstructions:pd(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 px({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 nx(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=ad(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=ex(t.contextItems),g=f?[...p,f]:p,h=d.length>0?"Confirmation required.":n.text.trim().length>0?n.text:Xw(u)??n.text,v=l||d.length>0?[]:Yi(u),w=l||d.length>0?[]:ix(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:w,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=mx(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}),w=Lw(g.toolResult.data),S=v?.text.trim()?`${g.resultText}
|
|
117
|
-
|
|
118
|
-
${v.text}`:w?`${g.resultText}
|
|
119
|
-
|
|
120
|
-
${w}`:g.resultText,y=[...g.cards,...v?.cards??[]],x=[g.toolResult,...v?.toolResults??[]],_=v?Yi(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:x,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=ld(o,e.userPermissionLevel),a=cd(i,t),s=pd(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}=ad(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=hx(e.cards);return{metadata:{userPermissionLevel:"public",...i.length?{cards:i}:{}}}}let{actorAlreadyEnriched:t=!1,guest:n,...o}=e;return fx(await gx({...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 gd({character:this.deps.identityService.getCharacter(),...this.deps.assistantAgentId?{agentId:this.deps.assistantAgentId}:{}})}buildAssistantSource(e,t){return{...e?{channelId:e}:{},channelName:t}}}class bd{runtime;closePromise=null;closed=!1;constructor(){let e=de.runSync(Xe.make()),t=de.runSync(Xe.extend(vd.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=de.runFork(de.tryPromise({try:e,catch:(i)=>i}));vd.unsafeAdd(this.runtime.fibers,n);let o=()=>{de.runSync(Ki.interruptFork(n))};if(t?.addEventListener("abort",o,{once:!0}),t?.aborted)o();try{let i=await de.runPromise(Ki.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??=de.runPromise(Xe.close(this.runtime.scope,tt.void)),this.closePromise}}var VF=10,ZF=1800000;function yx(e,t){return t?AbortSignal.any([e,t]):e}function KF(e){let{email:t,...n}=e;return n}class Qi{get guestReady(){return!this.indexReadiness||this.indexReadiness.isIndexReady()}mcpService;identityService;profileService;logger;stepLimit;agentFactory;agentInstructions;indexReadiness;conversationService;activeTurns=new bd;shutdownPromise=null;providedMachine=$w.provide({actors:{processMessage:ce.fromPromise(async({input:e,signal:t})=>this.activeTurns.run((n)=>this.turns.processMessage(e,n),yx(t,e.signal))),executeConfirmedAction:ce.fromPromise(async({input:e,signal:t})=>this.activeTurns.run((n)=>this.turns.executeConfirmedAction(e,n),yx(t,e.signal)))}});conversationActors;confirmations;turns;agent=null;guestAgent=null;static createFresh(e,t,n,o,i,a){return new Qi(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??VF,this.agentFactory=a.agentFactory,this.agentInstructions=a.agentInstructions,this.indexReadiness=a.indexReadiness,this.turns=new yd({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}),this.conversationActors=new Qu({createActor:()=>{let s=ce.createActor(this.providedMachine);return s.start(),s},isEvictable:(s)=>s.getSnapshot().matches("idle"),idleTtlMs:a.conversationActorIdleTtlMs??ZF}),this.confirmations=new ed(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?KF(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,w=vx(e),S=v.filter((y)=>Xu(y,h));if(w){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,w.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 bx={standard:{input:20,cacheRead:2,cacheWrite:25,output:120},long:{input:40,cacheRead:void 0,cacheWrite:50,output:180}};function YF(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?bx.long:bx.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 _d(e){let t=e.calls.map(YF),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 _x(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 wx=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:Sx.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:os.optional()});function xx(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 Sd(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 wd(e,t="brain-agent"){return{emit:async(n,o)=>{await e.send({type:n,payload:o,sender:t,broadcast:!0}).catch(()=>{return})}}}var xd={success:!1,error:"Public retrieval unavailable"},QF=500;function XF(e){if(!_s(e))return xd;if(e.success===!0)return e;let t=e.error;return{success:!1,error:typeof t==="string"&&t.trim()?t.slice(0,QF):"Nothing public matches that request."}}var eB=new Set(["confirmed","confirmationToken","contentHash"]),tB=new Set(["content","prompt","url","from","upload","transform","sourceAttachment"]),rB=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 nB(e){return typeof e==="object"&&e!==null&&"safeParse"in e&&typeof e.safeParse==="function"}function oB(e,t={}){let n={};for(let[o,i]of Object.entries(e)){if(eB.has(o))continue;if(t.toolName==="system_create"&&tB.has(o))continue;if(nB(i))n[o]=i}return n}function iB(e){let t=rB.safeParse(e);if(!t.success)return{type:"json",value:Tx(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:Tx({...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 aB(e){if(!_s(e))return e;if(e.success!==!0)return e;return{...e,cached:!0}}function Tx(e){if(e===void 0)return null;return Ix.parse(JSON.parse(JSON.stringify(e)))}function Td(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=Sd(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 aB(a.get(p));let f;try{f=o?XF(await s.handler(c,m)):await s.handler(c,m)}catch(g){if(!o)throw g;f=xd}if(o&&!_s(f))f=xd;if(!o)a.set(p,f);return f},t,o?void 0:n);i[s.name]=kl({description:s.description,inputSchema:r.object(oB(s.inputSchema,{toolName:s.name,...t.enableCreateUpload!==void 0&&{enableCreateUpload:t.enableCreateUpload},...t.enableCreateTransform!==void 0&&{enableCreateTransform:t.enableCreateTransform}})),execute:l,toModelOutput:({output:c})=>iB(c)})}return i}function sB(e,t){return t.interfaceType===mt?e.filter(Zr):e}function lB(e){return typeof e==="object"&&e!==null&&"action"in e&&e.action==="start"}function cB(e){let t=e.steps.at(-1),n=t?.toolResults?.some((i)=>bs.safeParse(i.output).success)??!1,o=t?.toolCalls?.some((i)=>i.toolName==="playbook_manage"&&lB(i.input))??!1;return n||o}function Id(e){let{model:t,modelId:n,webSearch:o,temperature:i,maxTokens:a,reasoningEffort:s,messageBus:l}=e,c=Di(n),u=wd(l);return function(p){let f=Td(p.tools,{conversationId:"",interfaceType:"agent"},u),g=new Jb({model:t,callOptionsSchema:wx,prepareCall:({options:h,...v})=>{Kr(h);let w=h.interfaceType===mt;if(w&&(h.actor||h.agentContextInstructions||h.enableCreateUpload||h.enableCreateTransform))throw Error("Guest execution denied");let S=h.disableTools?[]:sB(p.getToolsForPermission(h.userPermissionLevel),h),y=S.map((_)=>_.name),x=Td(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,...w&&{messages:Eu(v.messages),allowSystemInMessages:!1,providerOptions:{}},instructions:xx(p.identity,h.userPermissionLevel,p.pluginInstructions,p.profile,p.agentInstructions,h.agentContextInstructions,h.isAnchor)+(w?`
|
|
167
|
-
|
|
168
|
-
${DS}`:""),tools:x,activeTools:y,...i!==void 0&&c.supportsTemperature&&{temperature:i},...a!==void 0&&{maxTokens:a},...(c.provider==="openai"&&s!==void 0?!0:o&&!w)&&{providerOptions:{...c.provider==="openai"&&s&&{openai:{reasoningEffort:s}},...o&&!w&&{anthropic:{webSearch:!0}}}}}},tools:f,stopWhen:[cB,ji(p.stepLimit??10)]});return{generate:async(h)=>{Kr(h.options);let v=wo(h.options);if(!v)return g.generate(h);let w=Eu(h.messages).at(-1);if(w?.role!=="user"||typeof w.content!=="string"||!w.content.trim()||w.content.length>v.limits.messageCharacters)throw Error("Guest input limit exceeded");let S=await g.generate(h);return Object.assign(S,{guestSettlement:_x(S.steps,e.guestPricing)})}}}}async function Ss(e,t,n){let o=await e.send({type:Cx,sender:t,payload:{actor:n}});if("noop"in o)return null;if(!o.success)throw Error("Principal resolution unavailable");return kx.parse(o.data).principal}function Ex(e,t){return new Rx(e,(n)=>Ss(t,"shell:content-service",n))}var Cd=rt.GenericTag("@brains/conversation-service/ConversationService");function dB(e){if(e.service){let n=e.service;return{service:n,close:()=>n.close()}}let t=Ax.createFreshFromConfig(e.logger,e.messageBus,e.dbConfig,e.config);try{return{service:t,close:()=>t.close()}}catch(n){throw t.close(),n}}function Px(e){return vn(Cd,()=>dB(e))}var kd=rt.GenericTag("@brains/entity-service/EntityService");function pB(e){return"close"in e&&typeof e.close==="function"}function jx(e){return vn(kd,()=>{let t=e.service??Mx.createFresh(e);return{service:t,close:()=>{if(pB(t))t.close()}}})}var Xi=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()}),Rd=r.strictObject({alerts:r.array(Xi).optional()});var ws="shell:recurring-check",Ad=86400000,mB=7*Ad,gB=3*Ad,fB=r.strictObject({checkId:r.string().min(1)}),hB=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:Xi,observedAt:r.string().datetime(),includeInInbox:r.boolean().optional(),deliveredAt:r.string().datetime().optional(),resolvedAt:r.string().datetime().optional()})]);class xs{brainId;scheduler;state;jobQueue;delivery;logger;clock;nowFallback;checks=new Map;pluginChecks=new Map;alertOperations=new Nx;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:hB});let t={validateAndParse:(n)=>{let o=fB.safeParse(n);return o.success?o.data:null},process:async(n)=>{await this.runNow(n.checkId)}};this.jobQueue.registerHandler(ws,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(ws),this.handlerRegistered=!1}namespace(e){return{register:(t)=>this.register(e,t)}}register(e,t){Ox(e,"plugin ID"),Ox(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=de.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=Rd.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 de.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=Ed(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=Ed(this.brainId,e.id,e.cadence),o=Dx(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:ws,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=Xi.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 Ed(e,t,n){let o=n==="daily"?Ad:mB,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:gB}}function Dx(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 Ox(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 Le=zx("runtime_state_records",{namespace:Ts("namespace").notNull(),key:Ts("key").notNull(),value:Ts("value",{mode:"json"}).notNull(),createdAt:Pd("created_at").notNull(),updatedAt:Pd("updated_at").notNull()},(e)=>({pk:$x({columns:[e.namespace,e.key]}),namespaceUpdatedAtIdx:Ux("idx_runtime_state_namespace_updated_at").on(e.namespace,e.updatedAt)}));function Lx(e){return qx({url:e.url,schema:{runtimeStateRecords:Le},authToken:e.authToken,authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN"})}var yB=/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,127}$/,Hx=512;class jd{db;namespace;schema;now;constructor(e,t,n,o=()=>new Date){vB(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(Le).where(Do(ar(Le.namespace,this.namespace),ar(Le.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:Le.key}).from(Le).where(Do(ar(Le.namespace,this.namespace),ar(Le.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(Le).values({namespace:this.namespace,key:n,value:o,createdAt:i,updatedAt:i}).onConflictDoUpdate({target:[Le.namespace,Le.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(Le).values({namespace:this.namespace,key:n,value:o,createdAt:i,updatedAt:i}).onConflictDoNothing({target:[Le.namespace,Le.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(Le).set({value:a,updatedAt:this.now().getTime()}).where(Do(ar(Le.namespace,this.namespace),ar(Le.key,o),ar(Le.value,i)));return Number(s.rowsAffected)===1}async delete(e){let t=Bn(e),n=await this.db.delete(Le).where(Do(ar(Le.namespace,this.namespace),ar(Le.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(Le).where(ar(Le.namespace,this.namespace));return Number(o.rowsAffected)}Fx(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)Fx(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({...Bx(Le),key:Md`CAST(${Le.key} AS BLOB)`.mapWith((a)=>new TextDecoder("utf-8",{fatal:!0}).decode(a))}).from(Le).where(Do(ar(Le.namespace,this.namespace),t!==void 0?Md`substr(CAST(${Le.key} AS BLOB), 1, length(CAST(${t} AS BLOB))) = CAST(${t} AS BLOB)`:void 0,n!==void 0?Gx(Le.key,n):void 0)).orderBy(Jx(Le.key)).$dynamic();return o===void 0?i:i.limit(o)}}function vB(e){if(!yB.test(e))throw Error(`Invalid runtime state namespace: ${e}. Use 1-128 alphanumeric, _, ., :, or - characters.`)}function Bn(e){if(e.length===0||e.length>Hx)throw Error("Runtime state keys must be 1-512 characters long");return e}function Fx(e){if(e.length>Hx)throw Error("Runtime state key prefixes must be 512 characters or shorter");return e}class Is{db;client;logger;databaseUrl;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;static createFresh(e,t){return new Is(e,t??vr.getInstance())}constructor(e,t){let{db:n,client:o,url:i}=Lx(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 Wx(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 jd(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 Od=rt.GenericTag("@brains/runtime-state/RuntimeStateService");function Vx(e){return vn(Od,()=>{let t=e.service??Is.createFresh(e.config,e.logger);return{service:t,close:()=>t.close()}})}async function Nd(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=ea(n),t.warn(`Daemon ${e.name} failed to start: ${ke(n)}`),n}}async function Dd(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=ea(n),t.error(`Failed to stop daemon: ${e.name}`,n),n}}async function Zx(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 Kx(e){return{name:e.name,pluginId:e.pluginId,status:e.status,health:e.health}}async function Mr(e){let t=await de.runPromiseExit(e);if(tt.isSuccess(t))return t.value;throw ir.squash(t.cause)}async function zd(e){let n=(await Mr(de.all(e.map((o)=>de.either(de.tryPromise({try:o,catch:(i)=>i}))),{concurrency:"unbounded"}))).find(Yx.isLeft);if(n)throw n.left}class Cs{daemons=new Map;daemonScopes=new Map;daemonTransitions=new Map;logger;static createFresh(e){return new Cs(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 Nd(t,this.logger);return}let n=de.runSync(Xe.make()),o=de.acquireRelease(de.promise(()=>Nd(t,this.logger)),()=>de.promise(()=>Dd(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 Dd(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 Zx(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(Kx)}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??=ea(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 bB=r.object({projectionId:r.string().min(1),reason:r.string().min(1),openedAt:r.number().int().nonnegative(),expiresAt:r.number().int().nonnegative()}),_B=8,SB=32,wB=128,xB=5,TB=600000,IB=600000,CB=1000,kB="shell.projection-circuits";class ks{operationContext;options;circuitStore;roots=new Map;reservedJobs=new Map;circuits=new Map;projections;static createFresh(e,t={}){return new ks(e,t)}constructor(e,t){this.operationContext=e,this.options={maxDerivationDepth:t.maxDerivationDepth??_B,maxJobsPerRoot:t.maxJobsPerRoot??SB,maxMutationsPerRoot:t.maxMutationsPerRoot??wB,repeatedTargetLimit:t.repeatedTargetLimit??xB,retentionMs:t.retentionMs??TB,circuitOpenMs:t.circuitOpenMs??IB,maxTrackedRoots:t.maxTrackedRoots??CB,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:kB,schema:bB})}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 RB={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 Rs(e){return RB[e??"combined"]}var EB=20,AB=0.5,PB=0.06,MB=5;function Ud(e,t){let n=e[t];return typeof n==="string"&&n.trim().length>0?n.trim():void 0}function jB({entity:e},t){let n=Ud(e.metadata,"title")??Ud(e.metadata,"name"),o=Ud(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 Qx(e){return async({answer:t})=>{let o=(await e.entityService.search({query:t,options:{limit:EB,minScore:AB,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-PB).slice(0,MB).map((a)=>jB(a,e))}}function $d(e,t,n,o,i){return[Es.created,Es.updated,Es.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 OB(e,t,n){let o=NB(e.kind);if(!o)return null;try{let i=t.scoped({namespace:o,refKind:e.kind,routePath:""});return DB(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 NB(e){return e==="upload"?"upload":null}function DB(e,t){let{record:n,content:o}=e;if(zB(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 zB(e){let t=e.toLowerCase();return t.startsWith("text/")||t==="application/json"}function oT(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=tT.createFresh(n,o,t.identity);if(!d)u.push(...$d(i,Rt.BRAIN_CHARACTER,Rt.BRAIN_CHARACTER,()=>m.refreshCache(),o));let p=rT.createFresh(n,o,t.profile),f=nT.createFresh(o,async(w)=>{let S=await Ss(i,"shell:canonical-identity-service",w).catch(()=>null);if(!S?.canonicalId)return null;return{userId:S.userId,canonicalId:S.canonicalId,displayName:S.displayName}}),g=Id({guestPricing:a.getConfig().model==="gpt-5.6-luna"?_d: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=md(t.name),v=Qi.createFresh(s,l,m,p,o,{agentFactory:g,canonicalIdentityResolver:f,...t.embedding.enabled?{indexReadiness:n,guestAnswerSources:Qx({entityService:n,isCitable:(w)=>Qo.getInstance().isCitable(w),urlFor:(w,S)=>Qo.getInstance().generateUrl(w,S),siteBaseUrl:t.siteBaseUrl})}:{},uploadAttachmentResolver:(w)=>OB(w,c,o),agentContextProvider:async(w)=>(await i.collect({type:Xx,sender:"shell:agent-service",payload:w})).flatMap((y)=>{if("noop"in y||!y.success)return[];return eT(y.data)}),...h?{assistantAgentId:h}:{},...t.agentInstructions&&{agentInstructions:t.agentInstructions}});if(!d){u.push(...$d(i,Rt.ANCHOR_PROFILE,Rt.ANCHOR_PROFILE,()=>p.refreshCache(),o));for(let w of[Rt.BRAIN_CHARACTER,Rt.ANCHOR_PROFILE])u.push(...$d(i,w,w,async()=>v.invalidateAgent(),o))}return{identityService:m,profileService:p,canonicalIdentityService:f,agentService:v}}var ta=rt.GenericTag("@brains/job-queue/JobQueueService"),As=rt.GenericTag("@brains/job-queue/BatchJobManager"),Ps=rt.GenericTag("@brains/job-queue/JobProgressMonitor"),Ms=rt.GenericTag("@brains/job-queue/JobQueueWorker");function cT(e){return vn(ta,()=>{let t=e.service??iT.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 uT(e){let t=!1,n=de.gen(function*(){let o=yield*ta,i=e.batchJobManager??sT.createFresh(o,e.logger),a=e.jobProgressMonitor??lT.createFresh(o,e.messageBus,i,e.logger,e.progressMonitorMode),s=e.jobQueueWorker??aT.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(As,i).pipe(rt.add(Ps,a),rt.add(Ms,s))});return{layer:Xr.scopedContext(de.acquireRelease(n,(o)=>t?de.void:UB(o))),abandon:()=>{t=!0}}}function UB(e){let t=rt.get(e,Ms),n=rt.get(e,Ps),o=rt.get(e,As);return de.gen(function*(){let i=yield*de.exit(de.tryPromise({try:()=>t.stop(),catch:(c)=>c})),a=yield*de.exit(de.try({try:()=>n.stop(),catch:(c)=>c})),s=yield*de.exit(de.tryPromise({try:async()=>{await o.stop()},catch:(c)=>c})),l=[i,a,s].find(tt.isFailure);if(l)yield*de.die(ir.squash(l.cause))})}function $B(e,t=(n)=>process.exit(n)){return(n)=>{e.error("Job queue worker requires process restart",{reason:n,exitCode:1}),t(1)}}function js(e){let t=de.runSyncExit(Xe.close(e,tt.void));if(tt.isFailure(t))throw ir.squash(t.cause)}function dT(e){let t=e.operationContext??Os.createFresh(),n=de.runSync(Xe.make()),o,i;try{let a=de.runSync(Xr.buildWithScope(cT({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,ta),l=de.runSync(Xe.make());o=l;let c=uT({messageBus:e.messageBus,logger:e.logger,operationContext:t,...e.projectionBatchScope&&{projectionBatchScope:e.projectionBatchScope},onWorkerUnhealthy:$B(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=de.runSync(Xr.buildWithScope(c.layer.pipe(Xr.provide(Xr.succeed(ta,s))),l)),d=rt.get(u,As),m=rt.get(u,Ps),p=rt.get(u,Ms),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(),js(l)},closeDatabase:()=>{if(h)return;h=!0,js(n)}}}catch(a){if(o)try{i?.abandon(),js(o)}catch(s){e.logger.warn("Failed to release partial job runtime acquisition",s)}try{js(n)}catch(s){e.logger.warn("Failed to release partial job database acquisition",s)}throw a}}function mT(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=pT.safeParse(n.data);if(!o.success||o.data.status!=="sent")throw Error("Recurring alert delivery failed");return!0}}}function fT(e){return{sourceId:"recurring-checks",displayName:"Recurring checks",list:async()=>(await e.listOpenAlerts()).map((t)=>({id:t.id,title:gT(t.title,160),summary:gT(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 gT(e,t){return e.length<=t?e:e.slice(0,t)}function hT(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 yT(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 zT(e){let{config:t,dependencies:n,initializerLogger:o,lifecycle:i,processRole:a}=e;o.debug("Initializing Shell services");let s=Rs(a),l=hT(t,n?.logger),c=n?.operationContext??Os.createFresh(),u=[],d=n?.embeddingService??Li.createFresh({apiKey:t.ai.apiKey,logger:l}),m=n?.aiService??qi.createFresh(yT(t),l),p=n?.entityRegistry??bT.createFresh(l),f=n?.messageBus??OT.createFresh(l,c),g=n?.templateRegistry??ST.createFresh(l),h=n?.dataSourceRegistry??_T.createFresh(l),v=n?.renderService??wT.createFresh(g),w=n?.daemonRegistry??Cs.createFresh(l),S=n?.pluginManager??DT.createFresh(l,w),y=n?.permissionService??new ys(t.permissions,{spaces:t.spaces,entityActionFloor:(U)=>p.getEntityTypeConfig(U).actionPolicy}),x=n?.profileKindRegistry??new NT(t.profileKind),_=n?.channelRegistry??new IT,C=n?.inboxRegistry??new CT,I=n?.inboxFollowUpRegistry??new kT(l),b=n?.operationalHealthRegistry??new jT,E=n?.accountSettingsRegistry??new TT,F=n?.attachmentRegistry??RT.createFresh(),R=n?.runtimeUploadRegistry??ET.createFresh({dataDir:t.dataDir,logger:l}),q=i.buildLayer(Vx({config:zo(t.runtimeStateDatabase),logger:l,...n?.runtimeStateService&&{service:n.runtimeStateService}})),z=rt.get(q,Od),N=n?.projectionRuntimeSupervisor??ks.createFresh(c,{runtimeState:z}),re=n?.mcpService??MT.createFresh(f,l),Y={},V={runFreshBatchScope:(U)=>Y.current?Y.current.runFreshBatchScope(U):U()},L=dT({dependencies:n,jobQueueConfig:zo(t.jobQueueDatabase),workerConcurrency:t.jobQueue.workerConcurrency,messageBus:f,operationContext:c,projectionBatchScope:V,projectionAdmission:N,handlerRegistrationMode:s.handlerRegistrationMode,progressMonitorMode:s.progressMonitorMode,logger:l}),{batchJobManager:pe,jobProgressMonitor:Q,jobQueueService:k,jobQueueWorker:X}=L;i.addSyncFinalizer(()=>L.closeDatabase()),i.addSyncFinalizer(()=>L.rollbackRuntime());let J=n?.recurringCheckService??new xs({brainId:t.siteBaseUrl??t.dataDir,scheduler:new AT,runtimeState:z,clock:vT.make(),jobQueue:k,logger:l,delivery:mT(f)});i.addSyncFinalizer(()=>J.abandon()),C.registerSource("shell.recurring-checks",fT(J)),i.addSyncFinalizer(()=>C.unregisterPlugin("shell.recurring-checks"));let H=(U,me)=>{if(!s.serves)return;w.register(U,me,"shell"),i.addSyncFinalizer(()=>w.abandon(U))};H("shell:recurring-checks",{start:()=>J.start(),stop:()=>J.stop()});let K=i.buildLayer(jx({embeddingService:d,embeddingsEnabled:t.embedding.enabled,entityRegistry:p,logger:l,jobQueueService:k,messageBus:f,mutationAdmission:N,...n?.projectionRuntime?.now&&{projectionNow:n.projectionRuntime.now},dbConfig:zo(t.database),embeddingDbConfig:zo(t.embeddingDatabase),...n?.entityService&&{service:n.entityService}})),D=rt.get(K,kd);Y.current=D.getProjectionStore();let B=i.buildLayer(Px({dbConfig:zo(t.conversationDatabase),logger:l,messageBus:f,...n?.conversationService&&{service:n.conversationService}})),G=rt.get(B,Cd);H("shell:guest-retention",PT({intervalMs:60000,logger:l,run:async()=>{await G.deleteExpiredGuestConversations(100)}})),i.addSyncFinalizer(()=>{for(let U of u.splice(0))try{U()}catch(me){l.warn("Failed to dispose shell subscription",me)}});let Z=n?.contentService??new xT({logger:l,entityService:D,aiService:m,templateRegistry:g,dataSourceRegistry:h,generationAuthorizer:Ex(y,f)}),{identityService:A,profileService:O,canonicalIdentityService:W,agentService:P}=oT({config:t,entityService:D,embeddingService:d,entityRegistry:p,logger:l,messageBus:f,aiService:m,mcpService:re,conversationService:G,runtimeUploadRegistry:R,disposables:u,executionOnly:!s.serves});return{logger:l,operationContext:c,projectionRuntimeSupervisor:N,disposables:u,entityRegistry:p,messageBus:f,renderService:v,daemonRegistry:w,pluginManager:S,templateRegistry:g,dataSourceRegistry:h,mcpService:re,embeddingService:d,entityService:D,aiService:m,conversationService:G,contentService:Z,jobQueueService:k,jobQueueWorker:X,batchJobManager:pe,jobProgressMonitor:Q,jobServicesLifecycle:L,permissionService:y,identityService:A,profileService:O,canonicalIdentityService:W,profileKindRegistry:x,channelRegistry:_,inboxRegistry:C,inboxFollowUpRegistry:I,operationalHealthRegistry:b,accountSettingsRegistry:E,agentService:P,attachmentRegistry:F,runtimeUploadRegistry:R,runtimeStateService:z,recurringCheckService:J}}function FT(e,t){e.register(Ld.name,Ld),t.debug("Shell system templates registered")}function BT(e,t){e.register(Yo.BASE_ENTITY_DISPLAY,{name:"base-entity-display",description:"Display template for base entities",schema:Fd,formatter:new UT,requiredPermission:"public"}),t.debug("Base entity display template registered")}function GT(e,t){e.registerEntityType(Rt.NOTE,Fd,new $T,{projectionSourceRole:"primary"}),t.debug("Fallback base entity adapter registered")}function JT(e,t){let n=new qT;e.registerEntityType(Rt.BRAIN_CHARACTER,n.schema,n,{classification:"system",projectionSource:!1,projectionSourceRole:"excluded"}),t.debug("Brain character entity support registered")}function HT(e,t){let n=new LT;e.registerEntityType(Rt.ANCHOR_PROFILE,n.schema,n,{classification:"system",projectionSourceRole:"canonical"}),t.debug("Anchor profile entity support registered")}async function WT(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 Ns{logger;config;processRole;static createFresh(e,t,n){return new Ns(e,t,n)}constructor(e,t,n){this.logger=e.child("ShellInitializer"),this.config=t,this.processRole=n}registerShellTemplates(e){FT(e,this.logger)}registerBaseEntityDisplayTemplate(e){BT(e,this.logger)}registerFallbackBaseEntity(e){GT(e,this.logger)}registerBrainCharacterSupport(e){JT(e,this.logger)}registerAnchorProfileSupport(e){HT(e,this.logger)}async initializePlugins(e,t){await WT({plugins:this.config.plugins,pluginManager:e,logger:this.logger,initOptions:t})}initializeServices(e,t){return zT({config:this.config,dependencies:t,initializerLogger:this.logger,lifecycle:e,...this.processRole&&{processRole:this.processRole}})}registerJobHandlers(e,t,n){let o=ZT.createFresh(t,n);e.registerHandler(VT.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 Bd=r.strictObject({waveId:r.string().trim().min(1),ruleId:r.string().trim().min(1)});class Gd{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=Bd.safeParse(e);return t.success?t.data:null}async onTerminalError(e,t,n){let o=Bd.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=Bd.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:Ds(_)}),{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:Ds(_)}),await this.coordinator.continueAfterSupersession(i.waveId),{waveId:i.waveId,ruleId:a.id,outcome:"superseded",inputFingerprint:null,changedTargets:[]}}let p=FB(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:LB(f,p)};await this.recordDiagnostic({...h,event:"input-selected"});let v={ruleId:a.id,ruleVersion:a.version,inputFingerprint:g},w=await this.store.getRuleMemo(v);await this.recordDiagnostic({...h,event:"memo-resolved",memoHit:w!==null});let S;if(w)S=w.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()}),x=await this.store.listPendingInputs();if(!y)return await this.recordDiagnostic({...h,event:"apply-completed",memoHit:w!==null,applyOutcome:"superseded",highestPendingGeneration:Ds(x)}),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:w!==null,applyOutcome:"applied",highestPendingGeneration:Ds(x)}),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 LB(e,t){if(typeof e==="object"&&e!==null&&"sources"in e&&Array.isArray(e.sources))return e.sources.length;return t.length}function Ds(e){if(e.length===0)return null;return e.reduce((t,n)=>Math.max(t,n.generation),e[0]?.generation??0)}function FB(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 BB(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 Jd{store;queue;graph;ruleById;graphFingerprint;createWaveId;beforeWaveCompletion;scheduleWakeup;onScheduledWakeupError;now;operationQueue=new KT;scheduledWakeup;constructor(e){this.store=e.store,this.queue=e.queue,this.graph=e.graph,this.ruleById=HB(e.graph,e.rules),this.graphFingerprint=WB(e.graph,e.rules),this.createWaveId=e.createWaveId,this.beforeWaveCompletion=e.beforeWaveCompletion??(async()=>{}),this.scheduleWakeup=e.scheduleWakeup??GB,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=JB(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=QT(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:BB(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 GB(e,t){let n=setTimeout(()=>{t()},e);return()=>clearTimeout(n)}function JB(e,t,n){let i=QT(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 HB(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 WB(e,t){return YT({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 QT(e,t,n){let o=new Map(e.projections.map((c)=>[c.id,c])),i=XT(e,(c)=>[c.from,c.to]),a=new Set(e.projections.filter((c)=>VB(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=ZB(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 VB(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 ZB(e,t){let n=XT(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 XT(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 eI(e){let t=new Jd({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 Gd({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??KB)(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 KB(e,t){let n=setInterval(()=>{t()},e);return n.unref(),()=>clearInterval(n)}var YB=250,QB=r.object({projectionBatch:r.object({operationId:r.string().min(1),childKey:r.string().min(1)})});class Wd{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=Rs(i),this.hooks=a}async boot(e){this.services.logger.debug("Starting Shell boot");let t=this.initializer;await zd([()=>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 eI({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(Hd.waveReady))return;let a=await this.services.messageBus.collect({type:Hd.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:tI,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=QB.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:zs.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 zd([()=>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 rI(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 de.tryPromise({try:(n)=>e.awaitIndexReady({intervalMs:YB,signal:n}),catch:(n)=>n}).pipe(de.tap((n)=>de.sync(()=>{if(n.degraded)t.warn("Semantic index ready with degraded embeddings",n);else t.debug("Semantic index ready",n)})),de.catchAll((n)=>de.sync(()=>{t.warn("Semantic index readiness monitor stopped",n)})))}}class oI{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"?nI(t,{publishedOnly:!0,visibilityScope:n}):t;return o(i,n)}}function iI(e){let t=new oI;return t.register("overview",XB),t.register("publishing-cadence",eG),t.register("content-health",(n,o)=>tG(n,o,e)),t}async function XB(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 Vd(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=aI(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 eG(e,t){let n=await Vd(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 tG(e,t,n){let o=await Vd(e,t),i=aI(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 aI(e){return e.filter((t)=>t.metadata.status==="draft")}async function Vd(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 ra{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 Zd extends ra{constructor(){super((e)=>sI.parse(e),(e)=>e.url)}}class Kd extends ra{constructor(){super((e)=>lI.parse(e),(e)=>e.id)}}function cI(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 rG=["/health","/images"],nG=new Set([uI]),oG=new Set(dI),iG=new Set(["GET","POST","PUT","DELETE"]);function pI(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 aG(e){return nG.has(e)||rG.some((t)=>e===t||e.startsWith(`${t}/`))}function Yd(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&&aG(e))throw Error(`Invalid HTTP route path "${e}" declared by plugin "${t}"`)}function mI(e,t,n){if(!e.has(t))throw Error(`Invalid HTTP route method "${t}" declared by plugin "${n}"`)}function sG(e,t){if(e!=="exact"&&e!=="prefix")throw Error(`Invalid HTTP route match "${e}" declared by plugin "${t}"`)}function lG(e,t){Yd(t.path,e.pluginId);let n=t.method??"GET";mI(oG,n,e.pluginId);let o=t.match??"exact";if(sG(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 cG(e,t){Yd(t.path,e.pluginId,!1);let n=`/api/${e.pluginId}${t.path}`;if(Yd(n,e.pluginId),mI(iG,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 uG(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 dG(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 Us{routes;manifest;apiRoutes;webRoutes;static createFresh(){return new Us}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(lG(i,a)),n.push(Object.freeze({pluginId:i.pluginId,fullPath:a.path,definition:Object.freeze({...a})}));for(let a of i.apiRoutes){let s=cG(i,a);t.push(s),o.push(Object.freeze({pluginId:i.pluginId,fullPath:s.fullPath,definition:s.definition}))}}return uG(t),this.routes=Object.freeze(t),this.manifest=dG(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 gI(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 pG=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")]),hI=r.object({query:r.string().describe("Search term"),scope:pG.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")}),yI=r.object({entityType:r.string().describe("Entity type"),id:r.string().describe("Entity ID, slug, or title")}),vI=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)")}),mG=r.object({kind:r.literal("upload").describe("Upload ref kind"),id:r.string().min(1).describe("Upload ID")}),gG=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(),fG=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(),gG,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:mG.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()]),hG=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()]),bI=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:fI.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:fG.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(),_I=r.object({operation:hG.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(),yG=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(),Qd=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(yG).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")}),SI=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")}),UX=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")}),wI=r.object({batchId:r.string().optional().describe("Specific batch ID to check"),jobTypes:r.array(r.string()).optional().describe("Filter by job types")}),xI=r.object({type:r.string().describe("Type of insight to retrieve. Built-in: overview, publishing-cadence, content-health. Plugins may register additional types.")}),vG=r.object({entityType:r.string().optional(),entityId:r.string().optional(),attachmentType:r.string().optional()}),bG=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:vG.optional()}),$X=r.object({entityId:r.string().optional(),status:r.enum(["created","generating"]),jobId:r.string().optional(),attachment:bG.optional()}),qX=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 TI||i instanceof Error)return{success:!1,error:i.message};throw i}}var _G="system",II=r.record(r.string(),r.unknown()),SG=r.looseObject({fields:II});function Or(e,t,n,o,i={}){let{visibility:a="admin",sideEffects:s}=i;return{name:`${_G}_${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 Xd(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 CI(e){if(e.fields!==void 0)return{...e};if(!e.content)return{};try{let t=JSON.parse(e.content),n=SG.safeParse(t);if(n.success)return{fields:n.data.fields};let o=II.safeParse(t);if(o.success)return{fields:o.data}}catch{}return{content:e.content}}var wG={base:"note"};function kI(e){return wG[e]??e.replaceAll("-"," ")}function Ls(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 RI(e){return!!e&&Object.keys(e.shape).length>0}async function EI(e,t,n){if(!n)return!1;let o=await e.conversationService.getMessages(n,{limit:100});for(let i of o){let s=$s(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 xG={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"};function TG(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 IG(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 CG(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=$s(p.metadata)?.userPermissionLevel;return(g==="public"||g==="trusted"||g==="admin")&&e.permissionService.hasPermission(f,g)}):i.filter(AI),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,w=-1;for(let S of l.content.split(/(?<=\n)/)){if(S.replace(/\r?\n$/,"")===p){if(w>=0)return-1;w=v+(g?S.length:0)}v+=S.length}return w}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 kG(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 RG(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 EG(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 AG(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&&RI(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 PG(e,t,n){let{content:o,url:i,from:a,uploadRef:s,conversationMessageRef:l,transform:c}=kG(t.source),u=l?await CG(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 MG(e,t,n){if(!await EI(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(xG).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 jG(e,t,n){let o=t?Bs(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(!Fs(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 OG(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 NG(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 PG(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 MG(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=jG(t.visibility,a,n);if(h.kind==="error")return h;let v=Jn(t.title),w=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},...w&&{replace:w}},y=jr(e,S.entityType,"create",n);if(y)return{kind:"error",result:y};let x=e.entityRegistry.getCreateInterceptor(S.entityType);if(!S.content&&!x&&!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 OG(e,S,x);if(_)return{kind:"error",result:_};return{kind:"ok",prepared:{createInput:S,resolvedMessageId:d,interceptor:x,eventContext:$o(n),...f&&{uploadPreserve:f}}}}function PI(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.",bI,async(n,o)=>{let i=await NG(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?TG({...a.title&&{title:a.title},filename:u.filename,mediaType:u.mediaType,entityType:a.entityType,visibility:a.visibility}):IG(a),m=RG({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 EG({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 AG(e,a,c)},{visibility:"trusted",sideEffects:"writes"})}function DG(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 zG(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 UG(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 $G(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 qG(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=MI(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 LG(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 UG(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 $G(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 zG(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 FG(e,t,n){let o=t.operation,i=Wt(n.userPermissionLevel),a=await LG(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:BG(o,s,l),sourceAttachment:l,interceptor:m,eventContext:$o(n)}}}function BG(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 jI(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.",_I,async(n,o)=>{let i=await FG(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=DG(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 qG(e,a,a.prompt,c,o)},{visibility:"trusted",sideEffects:"writes"})}function OI(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.",SI,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=Ls(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 NI(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 nC}from"util";class Gs{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=(w)=>{if(w=this.postProcess(w,n),o){setTimeout(function(){o(w)},0);return}else return w},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 w=Math.max(g,-c);w<=Math.min(h,c);w+=2){let S,y=p[w-1],x=p[w+1];if(y)p[w-1]=void 0;let _=!1;if(x){let I=x.oldPos-w;_=x&&0<=I&&I<s}let C=y&&y.oldPos+1<l;if(!_&&!C){p[w]=void 0;continue}if(!C||_&&y.oldPos<x.oldPos)S=this.addToPath(x,!0,!1,0,n);else S=this.addToPath(y,!1,!0,1,n);if(f=this.extractCommon(S,t,e,w,n),S.oldPos+1>=l&&f+1>=s)return a(this.buildValues(S.lastComponent,t,e))||!0;else{if(p[w]=S,S.oldPos+1>=l)h=Math.min(h,w-1);if(f+1>=s)g=Math.max(g,w+1)}}c++};if(o)(function w(){setTimeout(function(){if(c>u||Date.now()>m)return o(void 0);if(!v())w()},0)})();else while(c<=u&&Date.now()<=m){let w=v();if(w)return w}}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 DI extends Gs{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}}var zI=new DI;function ep(e,t,n){return zI.diff(e,t,n)}var Js=r.enum(["png","jpg","jpeg","webp","gif","svg"]),$I=r.enum(["pending","draft","failed"]),qI=r.object({title:r.string().optional(),alt:r.string().optional(),format:Js,width:r.number(),height:r.number(),status:$I.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()}),na=UI.extend({entityType:r.literal("image"),metadata:qI}),GG=r.object({url:r.string(),alt:r.string(),title:r.string(),width:r.number(),height:r.number()});function LI(e){return/^https?:\/\//i.test(e)}async function FI(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 GI(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 Hs(e){let t=GI(e);if(!t)throw Error("Invalid image data URL");return t}function JG(e,t){return`data:image/${t==="jpg"?"jpeg":t};base64,${e}`}var HG={png:"iVBORw",jpg:"/9j/",gif:"R0lGOD",webp:"UklGR"};function tp(e){for(let[t,n]of BI(HG))if(e.startsWith(n))return t;return null}function JI(e){let t=e.toLowerCase(),n=t==="svg+xml"?"svg":t,o=Js.safeParse(n);return o.success?o.data:null}async function WG(e){return FI(e,"image/")}function Ws(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 HI(e){let t=JI(e);if(!t)throw Error(`Unsupported image format: ${e}`);return t}class rp{entityType="image";purpose="Image assets such as generated covers, social previews, and uploaded images.";schema=na;toMarkdown(e){return e.content}fromMarkdown(e){let{format:t,base64:n}=Hs(e),o=Ws(n);return{entityType:"image",content:e,metadata:{format:HI(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}=Hs(t),s=Ws(a),c=tp(a)??HI(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 VG=new rp;function kte(e){return VI(e,{skipInvalid:!0,noRefs:!0,sortKeys:!0})}function ZI(e){return WI(e)}var ZG=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,KG=r.record(r.string(),r.unknown());async function KI(e,t){let n=await t.getEntity({entityType:"image",id:e},na);if(!n)return;return{url:n.content,alt:n.metadata.alt??"",title:n.metadata.title??"",width:n.metadata.width,height:n.metadata.height}}function YI(e,t){let n=ZG.exec(e.content);if(!n?.[1])return;try{let o=KG.safeParse(ZI(n[1]));if(o.success){let i=o.data[t];return typeof i==="string"?i:void 0}}catch{return}return}function QI(e){return YI(e,"coverImageId")}function YG(e){return YI(e,"ogImageId")}function np(e,t){return{...e,content:oa(e.content,"coverImageId",t)}}function op(e,t){return{...e,content:oa(e.content,"ogImageId",t)}}async function QG(e,t){let n=QI(e);if(!n)return;return KI(n,t)}var XG=eC();function eJ(e){let t=[],n=XG.parse(e);return XI(n,"image",(o)=>{t.push({url:o.url,alt:o.alt??"",title:o.title??void 0})}),t}function Vs(e,t,n){if(n===null)return!Object.hasOwn(e,t);return Object.hasOwn(e,t)&&nC(e[t],n)}function ap(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 tJ(e,t,n){if(n.has(t))return ip(e.content).frontmatter[t];return t==="visibility"?e.visibility:e.metadata[t]}function oC(e,t,n){let{visibility:o,coverImageId:i,ogImageId:a,...s}=t,l=o===void 0?e.visibility:tC.parse(o),c=Object.hasOwn(t,"coverImageId")?np(e,typeof i==="string"?i:null):e,u=Object.hasOwn(t,"ogImageId")?op(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=ap(e.entityType,n),f=!1;for(let[g,h]of Object.entries(t)){if(!p.has(g))continue;m.content=oa(m.content,g,h),f=!0}if(f)m.metadata=n.projectMetadata(e.entityType,m.content,d);return m}function rJ(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(nC(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:Bs(t)??e.visibility}}var nJ=new Set(["visibility","coverImageId","ogImageId"]),oJ=r.record(r.string(),r.unknown());function iJ(e,t,n,o){let i=t.fields;if(!i)return;let a=n.getEffectiveFrontmatterSchema(e.entityType);if(!a)return;let s=ap(e.entityType,n),l=Object.keys(i).filter((g)=>s.has(g)),c;try{if(c=oC(e,i,n),l.length>0){let g=n.validateEntity(e.entityType,c),h=o.serializeEntity(g),v=ip(h).frontmatter,w=o.deserializeEntity(h,e.entityType).metadata??{};for(let S of l){let y=i[S];if(!Vs(v,S,y)||!Vs(w,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)&&!nJ.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(!Vs(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),oJ)}catch{if(p.length===0)return}if(g){for(let h of f)if(!Vs(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 aJ(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 sJ(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 lJ(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 iC(e,t,n){let o=ap(e.entityType,n);if(t.fields)return Object.entries(t.fields).map(([l,c])=>{let u=tJ(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=ep(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 aC(e,t,n,o){return iJ(e,t,n,o)??aJ(e.entityType,t,n)??sJ(e.entityType,t,n)}function sC(e,t,n){return rC(e.entityType,e.metadata.status,lJ(e,t,n),n)==="non-publish"?"update":"publish"}function lC(e,t,n){return t.content!==void 0?rJ(e,t.content,n):oC(e,t.fields??{},n)}function tn(e){return{success:!1,error:e}}function cJ(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:NI(t.content,e.edits)}:CI({...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 cC(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=Qd.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=lC(u,d,o);if(f.visibility!==u.visibility&&!Fs(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 "${Ls(u)}"?`,completionSummary:`Updated ${kI(u.entityType)}.`,preview:iC(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.",Qd,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=cJ(f,m);if("success"in h)return h;let v=aC(m,h,o,t);if(v)return v;let w=jr(e,f.entityType,sC(m,h,o),u);if(w)return w;return f.confirmed?s(f,m,h,g,u):l(f,m,h)},{visibility:"trusted",sideEffects:"writes"})}function uC(e){return[PI(e),jI(e),OI(e),cC(e)]}function Zs(e){if(e.interfaceType!==mt)return;if(e.userPermissionLevel!=="public"||e.isAnchor)throw Error("Guest execution denied")}var uJ=0.5,sp=(e)=>e==="public"?{publishedOnly:!0}:{};function dC(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.",hI,async(o,i)=>{Zs(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??uJ,...o.includeUngenerated!==void 0&&{includeUngenerated:o.includeUngenerated},visibilityScope:a,...sp(a)}})).map((s)=>{let l=Xd(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.",yI,async(o,i)=>{if(Zs(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,sp(a));if(!s.ok)return{success:!1,error:s.error};return{success:!0,data:{entity:Xd(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.",vI,async(o,i)=>{if(Zs(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,...sp(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 pC(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(", ")}.`,xI,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 mC(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.",wI,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 dJ(e){let{entityCounts:t,daemons:n,endpoints:o,interactions:i,...a}=e;return a}function gC(e){return[Sn("system","status","Get system status including model, version, interfaces, and tools",r.object({}),async()=>({success:!0,data:dJ(await e.getAppInfo())}),{visibility:"public",sideEffects:"none",cli:{name:"status"}})]}function fC(e){return[...dC(e),...mC(e),...gC(e),...uC(e),...pC(e)]}function hC(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 yC(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 vC(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 bC(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 qo="system",pJ=r.object({toolName:r.string(),args:r.unknown(),...SC.partial().shape});function Ks(e,t,n,o,i){for(let a of e)try{t(a)}catch{i.debug(`System ${o} ${n(a)} already registered, skipping`)}}function wC(e,t,n,o){let i=fC(e);Ks(i,(d)=>t.registerTool(qo,d),(d)=>d.name,"tool",o);let a=n.subscribe(_C.toolExecute(qo),async(d)=>{let m=pJ.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:w,userPermissionLevel:S}=m.data,y=i.find((C)=>C.name===p);if(!y)return{success:!1,error:`System tool not found: ${p}`};let x={interfaceType:g??"system",actor:h??{kind:"service",serviceId:"system"}};if(v)x.conversationId=v;if(w)x.channelId=w;if(S)x.userPermissionLevel=S;return{success:!0,data:await y.handler(f,x)}});o.debug(`Registered ${i.length} system tools`);let s=hC(e);Ks(s,(d)=>t.registerResource(qo,d),(d)=>d.uri,"resource",o),o.debug(`Registered ${s.length} system resources`);let l=yC(e);Ks(l,(d)=>t.registerResourceTemplate(qo,d),(d)=>d.uriTemplate,"resource template",o),o.debug(`Registered ${l.length} system resource templates`);let c=vC(e);Ks(c,(d)=>t.registerPrompt(qo,d),(d)=>d.name,"prompt",o),o.debug(`Registered ${c.length} system prompts`);let u=bC(e);try{t.registerInstructions(qo,u)}catch{o.debug("System instructions already registered, skipping")}return o.debug("Registered system instructions"),a}function CC(e){let{services:t,jobs:n,insights:o,query:i,getAppInfo:a}=e,s=t.jobQueueService,l=t.logger.child("system"),c=wC({entityService:t.entityService,entityRegistry:t.entityRegistry,jobs:{...n,enqueue:xC(s,"system",!1),enqueueBatch:TC(n,"system"),registerHandler:IC(s,"system")},conversationService:t.conversationService,runtimeUploads:t.runtimeUploadRegistry,attachments:Ys(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 lp{scope;closePromise=null;closed=!1;constructor(){this.scope=de.runSync(Xe.make())}buildLayer(e){this.assertOpen();let t=de.runSyncExit(Xr.buildWithScope(e,this.scope));if(tt.isFailure(t))throw ir.squash(t.cause);return t.value}addFinalizer(e){this.assertOpen(),de.runSync(Xe.addFinalizer(this.scope,de.promise(async()=>{await e()})))}addSyncFinalizer(e){this.assertOpen(),de.runSync(Xe.addFinalizer(this.scope,de.sync(()=>{e()})))}async fork(e){if(this.closed)throw Error("Cannot start background work after shell shutdown");await Mr(de.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,de.runSync(Xe.close(this.scope,e))}assertOpen(){if(this.closed)throw Error("Cannot register cleanup after shell shutdown")}}class ia{config;services;lifecycle;bootloader;initialized=!1;lifecycleState="constructed";bootMode;bootPromise=null;shutdownPromise=null;insightsRegistry;bootTime=Date.now();endpointRegistry=new Zd;interactionRegistry=new Kd;httpRouteRegistry=Us.createFresh();jobs;static createFresh(e,t,n){return new ia(pa(e),t,n)}constructor(e,t,n){this.config=e,this.lifecycle=new lp,AC(this,()=>this.httpRouteRegistry.getSnapshot());let o=t?.logger??vr.getInstance(),i=Ns.createFresh(o,this.config,n?.processRole);try{this.services=i.initializeServices(this.lifecycle,t),this.jobs=cI(this.services.batchJobManager,this.services.jobQueueService),this.insightsRegistry=iI(this.services.entityRegistry),this.bootloader=new Wd(this.config,this.services,this.lifecycle,i,n?.processRole,{registerCoreDataSources:()=>Tp(this.services,this.config),finalizeHttpRoutes:()=>{this.httpRouteRegistry.finalize(pI(this.services.pluginManager))},registerSystemCapabilities:()=>CC({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)=>ma(this.services.entityService,a,s),appInfo:()=>this.getAppInfo(),identityInput:()=>{let a=this.getIdentity(),s=this.getProfile();return RC.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:EC(this),logger:this.services.logger.child("ProjectionRuntime")}),...t?.projectionRuntime&&{projectionRuntime:t.projectionRuntime}}),i.wireShell(this.services,this),gI(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:zs.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"),Ip(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 kC.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 Ys(this.services.attachmentRegistry)}getRuntimeUploadRegistry(){return PC(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 vp({config:this.config,services:this.services,bootTime:this.bootTime,endpoints:()=>this.listEndpoints(),interactions:()=>this.listInteractions()})}getRuntimeReadiness(){return Sp(this.services)}}var MC={kind:"service",serviceId:"brain-cli"},cp=`${MC.kind}:${MC.serviceId}`;var mJ=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({})}),OC=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(da).default([]),spaces:r.array(r.string()).default([]),identity:jC.optional(),agentInstructions:r.array(r.string()).optional(),deployment:mJ.prefault({})});async function GC(e,t){await wn({label:"entity",config:e,schema:{assets:DC,entities:NC,projectionDirtyInputs:zC,projectionWaves:UC,projectionIncidents:$C,projectionWaveInputs:qC,projectionWaveRules:LC,projectionRuleMemos:FC},migrationsFolder:xn(import.meta.url,"entity-service"),authTokenEnv:"DATABASE_AUTH_TOKEN",logger:t,afterMigrate:BC})}async function WC(e,t){await wn({label:"job-queue",config:e,schema:{jobQueue:JC,jobWorkerSessions:HC},migrationsFolder:xn(import.meta.url,"job-queue"),authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",logger:t})}async function YC(e,t){await wn({label:"conversation",config:e,schema:{conversations:VC,messages:ZC,summaryTracking:KC},migrationsFolder:xn(import.meta.url,"conversation-service"),authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN",logger:t})}async function QC(e,t){await wn({label:"runtime-state",config:e,schema:{runtimeStateRecords:Le},migrationsFolder:xn(import.meta.url,"runtime-state"),authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN",logger:t})}import{mkdir as up}from"fs/promises";import{isAbsolute as gJ}from"path";function XC(e=process.env){return{dataDir:e.XDG_DATA_HOME??"./data",cacheDir:e.XDG_CACHE_HOME??"./cache",distDir:"./dist"}}function e0(e=process.env){let t=e.BRAIN_GIT_BROKER_CHECKOUT;if(!t)return;if(!gJ(t))throw Error(`Git broker checkout path must be absolute: ${t}`);return t}function t0(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 r0(e=process.env){return Cn(XC(e))}async function n0(e=process.env){let t=XC(e);try{await up(t.dataDir,{recursive:!0}),await up(t.cacheDir,{recursive:!0}),await up(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 dp{logger;migrations;constructor(e,t){this.logger=e,this.migrations=t??{getStandardConfigWithDirectories:()=>n0(),migrateEntities:GC,migrateJobQueue:WC,migrateConversations:YC,migrateRuntimeState:QC}}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 fJ="NODE_ENV";function hJ(){return process.env[fJ]}function o0(){return hJ()!=="production"}var yJ="startup-check";function vJ(e){let n={...OC.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 bJ(e,t){let n={plugins:e.plugins??[],...e.shellConfig};return _J(n),SJ(e,n),wJ(e,n,t),xJ(e,n),TJ(e,n),IJ(e,n),CJ(e,n),kJ(e,n),RJ(e,n),n}function _J(e){let t=r0();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??=t0(),e.gitBrokerCheckout??=e0()}function SJ(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function wJ(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:yJ},...e.aiApiKey&&{apiKey:e.aiApiKey},...e.aiImageKey&&{imageApiKey:e.aiImageKey},...e.aiModel&&{model:e.aiModel},...e.aiReasoningEffort&&{reasoningEffort:e.aiReasoningEffort}}}function xJ(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 TJ(e,t){let n=e.permissions?.rules??[];t.permissions={...e.permissions,rules:n.some((o)=>o.pattern===cp)?n:[{pattern:cp,level:"admin"},...n]}}function IJ(e,t){if(e.spaces)t.spaces=e.spaces}function CJ(e,t){if(e.identity)t.identity=e.identity}function kJ(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function RJ(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=o0()}class mp{shell=null;config;signalScope=null;signalShutdownFiber=null;stopPromise=null;hasCLI=!1;static create(e,t){return new mp(vJ(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 dp(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=ia.createFresh(bJ(this.config,e),void 0,{...t&&{processRole:t}})}async registerCLIInterface(){if(!this.hasCLI)return;let e=this.getShell().getPluginManager(),{CLIInterface:t}=await import("./index-99rxqmha.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 mp.create(e,t).run(n)}setupSignalHandlers(){if(this.signalScope)return;let e=de.runSync(Xe.make()),t=()=>{this.requestGracefulShutdown("SIGINT")},n=()=>{this.requestGracefulShutdown("SIGTERM")},o=pp(["SIGINT"],t),i=pp(["SIGTERM"],n);de.runSync(Xe.addFinalizer(e,de.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=de.tryPromise({try:()=>this.stop(),catch:(o)=>o}).pipe(de.match({onFailure:(o)=>{t.error("Error during shutdown:",o),process.exit(1)},onSuccess:()=>{process.exit(0)}}));this.signalShutdownFiber=de.runFork(n)}async closeSignalScope(){let e=this.signalScope;if(this.signalScope=null,e)await de.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,tO as U,h6 as V,ce as W,na as X,LI as Y,GI as Z,Hs as _,JG as $,tp as aa,WG as ba,Ws as ca,VG as da,kte as ea,QI as fa,YG as ga,np as ha,op as ia,QG as ja,eJ as ka,yJ as la,vJ as ma,bJ as na,mp as oa};
|
|
180
|
-
|
|
181
|
-
//# debugId=401CF23F857DAC5464756E2164756E21
|
|
182
|
-
//# sourceMappingURL=index-rgmc3f14.js.map
|