@rizom/brain 0.2.0-alpha.435 → 0.2.0-alpha.436
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 +40 -40
- package/dist/chunks/{app-jqh973n4.js → app-4x6q6j3m.js} +2 -2
- package/dist/chunks/{index-dbckeb36.js → index-67w0q4xz.js} +30 -30
- package/dist/chunks/{index-dbckeb36.js.map → index-67w0q4xz.js.map} +3 -3
- package/dist/chunks/{index-kggew50t.js → index-6ax31den.js} +3 -3
- package/dist/chunks/{index-kggew50t.js.map → index-6ax31den.js.map} +1 -1
- package/dist/chunks/{index-vpfmgg9f.js → index-jd5411fj.js} +2 -2
- package/dist/index.js +1 -1
- package/dist/model.js +39 -39
- package/dist/model.js.map +1 -1
- package/package.json +1 -1
- /package/dist/chunks/{app-jqh973n4.js.map → app-4x6q6j3m.js.map} +0 -0
- /package/dist/chunks/{index-vpfmgg9f.js.map → index-jd5411fj.js.map} +0 -0
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{pa as vR,qa as RR,ra as ER}from"./index-pnk0v35n.js";import{sa as cp}from"./index-48ksf4j5.js";import{$d as OI,Ab as Ko,Ac as de,Af as IT,Ag as PT,Bc as hs,Bd as IC,Cb as yr,Cc as hd,Ce as hT,Cf as xC,Dc as Xr,De as NT,Df as CT,Dg as fx,Eb as QT,Ef as kT,Fc as yn,Fe as DT,Ff as RT,Gc as nT,Ge as EI,Hb as Ad,Hc as oT,Ib as Lx,Ic as iT,Ie as XI,Jb as ar,Je as yT,Kc as fC,Lb as Oo,Lc as hC,Ld as kC,Mc as yC,Md as RC,Me as Nr,Nb as Ux,Nd as EC,Ne as _p,Oc as mt,Od as AC,Oe as ma,Pd as PC,Pe as XT,Qd as MC,Qe as SC,Rd as jC,Re as Ix,Sd as OC,Se as _T,Td as NC,Uc as mx,Ud as ua,Ue as WT,Vb as Fx,Vd as dI,Ve as
|
|
3
|
-
${o.message}`;if(i)throw new CR.VercelOidcTokenError(i);throw o}return t}function El(){let e=(0,IR.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 Ml=ye(function(GW,yg){var{defineProperty:Pl,getOwnPropertyDescriptor:AR,getOwnPropertyNames:PR}=Object,MR=Object.prototype.hasOwnProperty,jR=(e,t)=>{for(var n in t)Pl(e,n,{get:t[n],enumerable:!0})},OR=(e,t,n,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of PR(t))if(!MR.call(e,i)&&i!==n)Pl(e,i,{get:()=>t[i],enumerable:!(o=AR(t,i))||o.enumerable})}return e},NR=(e)=>OR(Pl({},"__esModule",{value:!0}),e),hg={};jR(hg,{AccessTokenMissingError:()=>fg.AccessTokenMissingError,RefreshAccessTokenFailedError:()=>fg.RefreshAccessTokenFailedError,getContext:()=>DR.getContext,getVercelOidcToken:()=>gg.getVercelOidcToken,getVercelOidcTokenSync:()=>gg.getVercelOidcTokenSync,getVercelToken:()=>zR.getVercelToken});yg.exports=NR(hg);var gg=mg(),DR=kl(),fg=RR(),zR=ER()});var Nl=ye(function(mf){Object.defineProperty(mf,"__esModule",{value:!0});mf.VERSION=void 0;mf.VERSION="1.9.1"});var bf=ye(function(yf){Object.defineProperty(yf,"__esModule",{value:!0});yf.isCompatible=yf._makeCompatibilityCheck=void 0;var eA=Nl(),ff=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function hf(e){let t=new Set([e]),n=new Set,o=e.match(ff);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(ff);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)}}yf._makeCompatibilityCheck=hf;yf.isCompatible=hf(eA.VERSION)});var jn=ye(function(_f){Object.defineProperty(_f,"__esModule",{value:!0});_f.unregisterGlobal=_f.getGlobal=_f.registerGlobal=void 0;var lo=Nl(),rA=bf(),nA=lo.VERSION.split(".")[0],yi=Symbol.for(`opentelemetry.js.api.${nA}`),vi=typeof globalThis==="object"?globalThis:typeof self==="object"?self:typeof window==="object"?window:typeof global==="object"?global:{};function oA(e,t,n,o=!1){var i;let a=vi[yi]=(i=vi[yi])!==null&&i!==void 0?i:{version:lo.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!==lo.VERSION){let s=Error(`@opentelemetry/api: Registration of version v${a.version} for ${e} does not match previously registered API v${lo.VERSION}`);return n.error(s.stack||s.message),!1}return a[e]=t,n.debug(`@opentelemetry/api: Registered a global for ${e} v${lo.VERSION}.`),!0}_f.registerGlobal=oA;function iA(e){var t,n;let o=(t=vi[yi])===null||t===void 0?void 0:t.version;if(!o||!(0,rA.isCompatible)(o))return;return(n=vi[yi])===null||n===void 0?void 0:n[e]}_f.getGlobal=iA;function aA(e,t){t.debug(`@opentelemetry/api: Unregistering a global for ${e} v${lo.VERSION}.`);let n=vi[yi];if(n)delete n[e]}_f.unregisterGlobal=aA});var If=ye(function(xf){Object.defineProperty(xf,"__esModule",{value:!0});xf.DiagComponentLogger=void 0;var cA=jn();class wf{constructor(e){this._namespace=e.namespace||"DiagComponentLogger"}debug(...e){return bi("debug",this._namespace,e)}error(...e){return bi("error",this._namespace,e)}info(...e){return bi("info",this._namespace,e)}warn(...e){return bi("warn",this._namespace,e)}verbose(...e){return bi("verbose",this._namespace,e)}}xf.DiagComponentLogger=wf;function bi(e,t,n){let o=(0,cA.getGlobal)("diag");if(!o)return;return o[e](t,...n)}});var Da=ye(function(Cf){Object.defineProperty(Cf,"__esModule",{value:!0});Cf.DiagLogLevel=void 0;var uA;(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"})(uA=Cf.DiagLogLevel||(Cf.DiagLogLevel={}))});var Ef=ye(function(kf){Object.defineProperty(kf,"__esModule",{value:!0});kf.createLogLevelDiagLogger=void 0;var Wr=Da();function dA(e,t){if(e<Wr.DiagLogLevel.NONE)e=Wr.DiagLogLevel.NONE;else if(e>Wr.DiagLogLevel.ALL)e=Wr.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",Wr.DiagLogLevel.ERROR),warn:n("warn",Wr.DiagLogLevel.WARN),info:n("info",Wr.DiagLogLevel.INFO),debug:n("debug",Wr.DiagLogLevel.DEBUG),verbose:n("verbose",Wr.DiagLogLevel.VERBOSE)}}kf.createLogLevelDiagLogger=dA});var On=ye(function(Pf){Object.defineProperty(Pf,"__esModule",{value:!0});Pf.DiagAPI=void 0;var pA=If(),mA=Ef(),Af=Da(),za=jn(),gA="diag";class zl{static instance(){if(!this._instance)this._instance=new zl;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:Af.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,mA.createLogLevelDiagLogger)((s=i.logLevel)!==null&&s!==void 0?s:Af.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)(gA,t)},t.createComponentLogger=(o)=>new pA.DiagComponentLogger(o),t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}}Pf.DiagAPI=zl});var Nf=ye(function(jf){Object.defineProperty(jf,"__esModule",{value:!0});jf.BaggageImpl=void 0;class co{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 co(this._entries);return n._entries.set(e,t),n}removeEntry(e){let t=new co(this._entries);return t._entries.delete(e),t}removeEntries(...e){let t=new co(this._entries);for(let n of e)t._entries.delete(n);return t}clear(){return new co}}jf.BaggageImpl=co});var qf=ye(function(Df){Object.defineProperty(Df,"__esModule",{value:!0});Df.baggageEntryMetadataSymbol=void 0;Df.baggageEntryMetadataSymbol=Symbol("BaggageEntryMetadata")});var ql=ye(function($f){Object.defineProperty($f,"__esModule",{value:!0});$f.baggageEntryMetadataFromString=$f.createBaggage=void 0;var fA=On(),hA=Nf(),yA=qf(),vA=fA.DiagAPI.instance();function bA(e={}){return new hA.BaggageImpl(new Map(Object.entries(e)))}$f.createBaggage=bA;function _A(e){if(typeof e!=="string")vA.error(`Cannot create baggage metadata from unknown type: ${typeof e}`),e="";return{__TYPE__:yA.baggageEntryMetadataSymbol,toString(){return e}}}$f.baggageEntryMetadataFromString=_A});var _i=ye(function(Uf){Object.defineProperty(Uf,"__esModule",{value:!0});Uf.ROOT_CONTEXT=Uf.createContextKey=void 0;function wA(e){return Symbol.for(e)}Uf.createContextKey=wA;class qa{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 qa(t._currentContext);return i._currentContext.set(n,o),i},t.deleteValue=(n)=>{let o=new qa(t._currentContext);return o._currentContext.delete(n),o}}}Uf.ROOT_CONTEXT=new qa});var Wf=ye(function(Gf){Object.defineProperty(Gf,"__esModule",{value:!0});Gf.DiagConsoleLogger=Gf._originalConsoleMethods=void 0;var $l=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}];Gf._originalConsoleMethods={};if(typeof console<"u"){let e=["error","warn","info","debug","trace","log"];for(let t of e)if(typeof console[t]==="function")Gf._originalConsoleMethods[t]=console[t]}class Bf{constructor(){function e(t){return function(...n){let o=Gf._originalConsoleMethods[t];if(typeof o!=="function")o=Gf._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<$l.length;t++)this[$l[t].n]=e($l[t].c)}}Gf.DiagConsoleLogger=Bf});var Vl=ye(function(Hf){Object.defineProperty(Hf,"__esModule",{value:!0});Hf.createNoopMeter=Hf.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=Hf.NOOP_OBSERVABLE_GAUGE_METRIC=Hf.NOOP_OBSERVABLE_COUNTER_METRIC=Hf.NOOP_UP_DOWN_COUNTER_METRIC=Hf.NOOP_HISTOGRAM_METRIC=Hf.NOOP_GAUGE_METRIC=Hf.NOOP_COUNTER_METRIC=Hf.NOOP_METER=Hf.NoopObservableUpDownCounterMetric=Hf.NoopObservableGaugeMetric=Hf.NoopObservableCounterMetric=Hf.NoopObservableMetric=Hf.NoopHistogramMetric=Hf.NoopGaugeMetric=Hf.NoopUpDownCounterMetric=Hf.NoopCounterMetric=Hf.NoopMetric=Hf.NoopMeter=void 0;class Ll{constructor(){}createGauge(e,t){return Hf.NOOP_GAUGE_METRIC}createHistogram(e,t){return Hf.NOOP_HISTOGRAM_METRIC}createCounter(e,t){return Hf.NOOP_COUNTER_METRIC}createUpDownCounter(e,t){return Hf.NOOP_UP_DOWN_COUNTER_METRIC}createObservableGauge(e,t){return Hf.NOOP_OBSERVABLE_GAUGE_METRIC}createObservableCounter(e,t){return Hf.NOOP_OBSERVABLE_COUNTER_METRIC}createObservableUpDownCounter(e,t){return Hf.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC}addBatchObservableCallback(e,t){}removeBatchObservableCallback(e){}}Hf.NoopMeter=Ll;class uo{}Hf.NoopMetric=uo;class Ul extends uo{add(e,t){}}Hf.NoopCounterMetric=Ul;class Fl extends uo{add(e,t){}}Hf.NoopUpDownCounterMetric=Fl;class Bl extends uo{record(e,t){}}Hf.NoopGaugeMetric=Bl;class Gl extends uo{record(e,t){}}Hf.NoopHistogramMetric=Gl;class Si{addCallback(e){}removeCallback(e){}}Hf.NoopObservableMetric=Si;class Jl extends Si{}Hf.NoopObservableCounterMetric=Jl;class Wl extends Si{}Hf.NoopObservableGaugeMetric=Wl;class Hl extends Si{}Hf.NoopObservableUpDownCounterMetric=Hl;Hf.NOOP_METER=new Ll;Hf.NOOP_COUNTER_METRIC=new Ul;Hf.NOOP_GAUGE_METRIC=new Bl;Hf.NOOP_HISTOGRAM_METRIC=new Gl;Hf.NOOP_UP_DOWN_COUNTER_METRIC=new Fl;Hf.NOOP_OBSERVABLE_COUNTER_METRIC=new Jl;Hf.NOOP_OBSERVABLE_GAUGE_METRIC=new Wl;Hf.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=new Hl;function TA(){return Hf.NOOP_METER}Hf.createNoopMeter=TA});var oh=ye(function(nh){Object.defineProperty(nh,"__esModule",{value:!0});nh.ValueType=void 0;var NA;(function(e){e[e.INT=0]="INT",e[e.DOUBLE=1]="DOUBLE"})(NA=nh.ValueType||(nh.ValueType={}))});var Kl=ye(function(ih){Object.defineProperty(ih,"__esModule",{value:!0});ih.defaultTextMapSetter=ih.defaultTextMapGetter=void 0;ih.defaultTextMapGetter={get(e,t){if(e==null)return;return e[t]},keys(e){if(e==null)return[];return Object.keys(e)}};ih.defaultTextMapSetter={set(e,t,n){if(e==null)return;e[t]=n}}});var uh=ye(function(lh){Object.defineProperty(lh,"__esModule",{value:!0});lh.NoopContextManager=void 0;var zA=_i();class sh{active(){return zA.ROOT_CONTEXT}with(e,t,n,...o){return t.call(n,...o)}bind(e,t){return t}enable(){return this}disable(){return this}}lh.NoopContextManager=sh});var wi=ye(function(ph){Object.defineProperty(ph,"__esModule",{value:!0});ph.ContextAPI=void 0;var qA=uh(),Yl=jn(),dh=On(),Ql="context",$A=new qA.NoopContextManager;class Xl{constructor(){}static getInstance(){if(!this._instance)this._instance=new Xl;return this._instance}setGlobalContextManager(e){return(0,Yl.registerGlobal)(Ql,e,dh.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,Yl.getGlobal)(Ql)||$A}disable(){this._getContextManager().disable(),(0,Yl.unregisterGlobal)(Ql,dh.DiagAPI.instance())}}ph.ContextAPI=Xl});var tc=ye(function(gh){Object.defineProperty(gh,"__esModule",{value:!0});gh.TraceFlags=void 0;var LA;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(LA=gh.TraceFlags||(gh.TraceFlags={}))});var La=ye(function(fh){Object.defineProperty(fh,"__esModule",{value:!0});fh.INVALID_SPAN_CONTEXT=fh.INVALID_TRACEID=fh.INVALID_SPANID=void 0;var UA=tc();fh.INVALID_SPANID="0000000000000000";fh.INVALID_TRACEID="00000000000000000000000000000000";fh.INVALID_SPAN_CONTEXT={traceId:fh.INVALID_TRACEID,spanId:fh.INVALID_SPANID,traceFlags:UA.TraceFlags.NONE}});var Ua=ye(function(_h){Object.defineProperty(_h,"__esModule",{value:!0});_h.NonRecordingSpan=void 0;var FA=La();class bh{constructor(e=FA.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){}}_h.NonRecordingSpan=bh});var oc=ye(function(xh){Object.defineProperty(xh,"__esModule",{value:!0});xh.getSpanContext=xh.setSpanContext=xh.deleteSpan=xh.setSpan=xh.getActiveSpan=xh.getSpan=void 0;var BA=_i(),GA=Ua(),JA=wi(),rc=(0,BA.createContextKey)("OpenTelemetry Context Key SPAN");function nc(e){return e.getValue(rc)||void 0}xh.getSpan=nc;function WA(){return nc(JA.ContextAPI.getInstance().active())}xh.getActiveSpan=WA;function wh(e,t){return e.setValue(rc,t)}xh.setSpan=wh;function HA(e){return e.deleteValue(rc)}xh.deleteSpan=HA;function VA(e,t){return wh(e,new GA.NonRecordingSpan(t))}xh.setSpanContext=VA;function ZA(e){var t;return(t=nc(e))===null||t===void 0?void 0:t.spanContext()}xh.getSpanContext=ZA});var Ba=ye(function(Eh){Object.defineProperty(Eh,"__esModule",{value:!0});Eh.wrapSpanContext=Eh.isSpanContextValid=Eh.isValidSpanId=Eh.isValidTraceId=void 0;var Ih=La(),tP=Ua(),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 Ch(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 kh(e){return Ch(e,32)&&e!==Ih.INVALID_TRACEID}Eh.isValidTraceId=kh;function Rh(e){return Ch(e,16)&&e!==Ih.INVALID_SPANID}Eh.isValidSpanId=Rh;function rP(e){return kh(e.traceId)&&Rh(e.spanId)}Eh.isSpanContextValid=rP;function nP(e){return new tP.NonRecordingSpan(e)}Eh.wrapSpanContext=nP});var sc=ye(function(jh){Object.defineProperty(jh,"__esModule",{value:!0});jh.NoopTracer=void 0;var sP=wi(),Ph=oc(),ic=Ua(),lP=Ba(),ac=sP.ContextAPI.getInstance();class Mh{startSpan(e,t,n=ac.active()){if(Boolean(t===null||t===void 0?void 0:t.root))return new ic.NonRecordingSpan;let i=n&&(0,Ph.getSpanContext)(n);if(cP(i)&&(0,lP.isSpanContextValid)(i))return new ic.NonRecordingSpan(i);else return new ic.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:ac.active(),c=this.startSpan(e,i,l),u=(0,Ph.setSpan)(l,c);return ac.with(u,s,void 0,c)}}jh.NoopTracer=Mh;function cP(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 lc=ye(function(Dh){Object.defineProperty(Dh,"__esModule",{value:!0});Dh.ProxyTracer=void 0;var uP=sc(),dP=new uP.NoopTracer;class Nh{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 dP;return this._delegate=e,this._delegate}}Dh.ProxyTracer=Nh});var Uh=ye(function($h){Object.defineProperty($h,"__esModule",{value:!0});$h.NoopTracerProvider=void 0;var pP=sc();class qh{getTracer(e,t,n){return new pP.NoopTracer}}$h.NoopTracerProvider=qh});var cc=ye(function(Bh){Object.defineProperty(Bh,"__esModule",{value:!0});Bh.ProxyTracerProvider=void 0;var mP=lc(),gP=Uh(),fP=new gP.NoopTracerProvider;class Fh{getTracer(e,t,n){var o;return(o=this.getDelegateTracer(e,t,n))!==null&&o!==void 0?o:new mP.ProxyTracer(this,e,t,n)}getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:fP}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)}}Bh.ProxyTracerProvider=Fh});var Wh=ye(function(Jh){Object.defineProperty(Jh,"__esModule",{value:!0});Jh.SamplingDecision=void 0;var hP;(function(e){e[e.NOT_RECORD=0]="NOT_RECORD",e[e.RECORD=1]="RECORD",e[e.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(hP=Jh.SamplingDecision||(Jh.SamplingDecision={}))});var Vh=ye(function(Hh){Object.defineProperty(Hh,"__esModule",{value:!0});Hh.SpanKind=void 0;var yP;(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"})(yP=Hh.SpanKind||(Hh.SpanKind={}))});var Kh=ye(function(Zh){Object.defineProperty(Zh,"__esModule",{value:!0});Zh.SpanStatusCode=void 0;var vP;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(vP=Zh.SpanStatusCode||(Zh.SpanStatusCode={}))});var Xh=ye(function(Yh){Object.defineProperty(Yh,"__esModule",{value:!0});Yh.validateValue=Yh.validateKey=void 0;var mc="[_0-9a-z-*/]",bP=`[a-z]${mc}{0,255}`,_P=`[a-z0-9]${mc}{0,240}@[a-z]${mc}{0,13}`,SP=new RegExp(`^(?:${bP}|${_P})$`),wP=/^[ -~]{0,255}[!-~]$/,xP=/,|=/;function TP(e){return SP.test(e)}Yh.validateKey=TP;function IP(e){return wP.test(e)&&!xP.test(e)}Yh.validateValue=IP});var ay=ye(function(oy){Object.defineProperty(oy,"__esModule",{value:!0});oy.TraceStateImpl=void 0;var ey=Xh(),ty=32,kP=512,ry=",",ny="=";class gc{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+ny+this.get(t)),e),[]).join(ry)}_parse(e){if(e.length>kP)return;if(this._internalState=e.split(ry).reduceRight((t,n)=>{let o=n.trim(),i=o.indexOf(ny);if(i!==-1){let a=o.slice(0,i),s=o.slice(i+1,n.length);if((0,ey.validateKey)(a)&&(0,ey.validateValue)(s))t.set(a,s)}return t},new Map),this._internalState.size>ty)this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,ty))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new gc;return e._internalState=new Map(this._internalState),e}}oy.TraceStateImpl=gc});var cy=ye(function(sy){Object.defineProperty(sy,"__esModule",{value:!0});sy.createTraceState=void 0;var RP=ay();function EP(e){return new RP.TraceStateImpl(e)}sy.createTraceState=EP});var py=ye(function(uy){Object.defineProperty(uy,"__esModule",{value:!0});uy.context=void 0;var AP=wi();uy.context=AP.ContextAPI.getInstance()});var fy=ye(function(my){Object.defineProperty(my,"__esModule",{value:!0});my.diag=void 0;var PP=On();my.diag=PP.DiagAPI.instance()});var vy=ye(function(hy){Object.defineProperty(hy,"__esModule",{value:!0});hy.NOOP_METER_PROVIDER=hy.NoopMeterProvider=void 0;var MP=Vl();class fc{getMeter(e,t,n){return MP.NOOP_METER}}hy.NoopMeterProvider=fc;hy.NOOP_METER_PROVIDER=new fc});var wy=ye(function(_y){Object.defineProperty(_y,"__esModule",{value:!0});_y.MetricsAPI=void 0;var OP=vy(),hc=jn(),by=On(),yc="metrics";class vc{constructor(){}static getInstance(){if(!this._instance)this._instance=new vc;return this._instance}setGlobalMeterProvider(e){return(0,hc.registerGlobal)(yc,e,by.DiagAPI.instance())}getMeterProvider(){return(0,hc.getGlobal)(yc)||OP.NOOP_METER_PROVIDER}getMeter(e,t,n){return this.getMeterProvider().getMeter(e,t,n)}disable(){(0,hc.unregisterGlobal)(yc,by.DiagAPI.instance())}}_y.MetricsAPI=vc});var Iy=ye(function(xy){Object.defineProperty(xy,"__esModule",{value:!0});xy.metrics=void 0;var NP=wy();xy.metrics=NP.MetricsAPI.getInstance()});var Ey=ye(function(ky){Object.defineProperty(ky,"__esModule",{value:!0});ky.NoopTextMapPropagator=void 0;class Cy{inject(e,t){}extract(e,t){return e}fields(){return[]}}ky.NoopTextMapPropagator=Cy});var jy=ye(function(Py){Object.defineProperty(Py,"__esModule",{value:!0});Py.deleteBaggage=Py.setBaggage=Py.getActiveBaggage=Py.getBaggage=void 0;var DP=wi(),zP=_i(),bc=(0,zP.createContextKey)("OpenTelemetry Baggage Key");function Ay(e){return e.getValue(bc)||void 0}Py.getBaggage=Ay;function qP(){return Ay(DP.ContextAPI.getInstance().active())}Py.getActiveBaggage=qP;function $P(e,t){return e.setValue(bc,t)}Py.setBaggage=$P;function LP(e){return e.deleteValue(bc)}Py.deleteBaggage=LP});var qy=ye(function(Dy){Object.defineProperty(Dy,"__esModule",{value:!0});Dy.PropagationAPI=void 0;var _c=jn(),GP=Ey(),Oy=Kl(),Ga=jy(),JP=ql(),Ny=On(),Sc="propagation",WP=new GP.NoopTextMapPropagator;class wc{constructor(){this.createBaggage=JP.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 wc;return this._instance}setGlobalPropagator(e){return(0,_c.registerGlobal)(Sc,e,Ny.DiagAPI.instance())}inject(e,t,n=Oy.defaultTextMapSetter){return this._getGlobalPropagator().inject(e,t,n)}extract(e,t,n=Oy.defaultTextMapGetter){return this._getGlobalPropagator().extract(e,t,n)}fields(){return this._getGlobalPropagator().fields()}disable(){(0,_c.unregisterGlobal)(Sc,Ny.DiagAPI.instance())}_getGlobalPropagator(){return(0,_c.getGlobal)(Sc)||WP}}Dy.PropagationAPI=wc});var Uy=ye(function($y){Object.defineProperty($y,"__esModule",{value:!0});$y.propagation=void 0;var HP=qy();$y.propagation=HP.PropagationAPI.getInstance()});var Hy=ye(function(Jy){Object.defineProperty(Jy,"__esModule",{value:!0});Jy.TraceAPI=void 0;var xc=jn(),Fy=cc(),By=Ba(),po=oc(),Gy=On(),Tc="trace";class Ic{constructor(){this._proxyTracerProvider=new Fy.ProxyTracerProvider,this.wrapSpanContext=By.wrapSpanContext,this.isSpanContextValid=By.isSpanContextValid,this.deleteSpan=po.deleteSpan,this.getSpan=po.getSpan,this.getActiveSpan=po.getActiveSpan,this.getSpanContext=po.getSpanContext,this.setSpan=po.setSpan,this.setSpanContext=po.setSpanContext}static getInstance(){if(!this._instance)this._instance=new Ic;return this._instance}setGlobalTracerProvider(e){let t=(0,xc.registerGlobal)(Tc,this._proxyTracerProvider,Gy.DiagAPI.instance());if(t)this._proxyTracerProvider.setDelegate(e);return t}getTracerProvider(){return(0,xc.getGlobal)(Tc)||this._proxyTracerProvider}getTracer(e,t){return this.getTracerProvider().getTracer(e,t)}disable(){(0,xc.unregisterGlobal)(Tc,Gy.DiagAPI.instance()),this._proxyTracerProvider=new Fy.ProxyTracerProvider}}Jy.TraceAPI=Ic});var Ky=ye(function(Vy){Object.defineProperty(Vy,"__esModule",{value:!0});Vy.trace=void 0;var VP=Hy();Vy.trace=VP.TraceAPI.getInstance()});var Rc=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 ZP=ql();Object.defineProperty(Ze,"baggageEntryMetadataFromString",{enumerable:!0,get:function(){return ZP.baggageEntryMetadataFromString}});var Yy=_i();Object.defineProperty(Ze,"createContextKey",{enumerable:!0,get:function(){return Yy.createContextKey}});Object.defineProperty(Ze,"ROOT_CONTEXT",{enumerable:!0,get:function(){return Yy.ROOT_CONTEXT}});var KP=Wf();Object.defineProperty(Ze,"DiagConsoleLogger",{enumerable:!0,get:function(){return KP.DiagConsoleLogger}});var YP=Da();Object.defineProperty(Ze,"DiagLogLevel",{enumerable:!0,get:function(){return YP.DiagLogLevel}});var QP=Vl();Object.defineProperty(Ze,"createNoopMeter",{enumerable:!0,get:function(){return QP.createNoopMeter}});var XP=oh();Object.defineProperty(Ze,"ValueType",{enumerable:!0,get:function(){return XP.ValueType}});var Qy=Kl();Object.defineProperty(Ze,"defaultTextMapGetter",{enumerable:!0,get:function(){return Qy.defaultTextMapGetter}});Object.defineProperty(Ze,"defaultTextMapSetter",{enumerable:!0,get:function(){return Qy.defaultTextMapSetter}});var eM=lc();Object.defineProperty(Ze,"ProxyTracer",{enumerable:!0,get:function(){return eM.ProxyTracer}});var tM=cc();Object.defineProperty(Ze,"ProxyTracerProvider",{enumerable:!0,get:function(){return tM.ProxyTracerProvider}});var rM=Wh();Object.defineProperty(Ze,"SamplingDecision",{enumerable:!0,get:function(){return rM.SamplingDecision}});var nM=Vh();Object.defineProperty(Ze,"SpanKind",{enumerable:!0,get:function(){return nM.SpanKind}});var oM=Kh();Object.defineProperty(Ze,"SpanStatusCode",{enumerable:!0,get:function(){return oM.SpanStatusCode}});var iM=tc();Object.defineProperty(Ze,"TraceFlags",{enumerable:!0,get:function(){return iM.TraceFlags}});var aM=cy();Object.defineProperty(Ze,"createTraceState",{enumerable:!0,get:function(){return aM.createTraceState}});var Cc=Ba();Object.defineProperty(Ze,"isSpanContextValid",{enumerable:!0,get:function(){return Cc.isSpanContextValid}});Object.defineProperty(Ze,"isValidTraceId",{enumerable:!0,get:function(){return Cc.isValidTraceId}});Object.defineProperty(Ze,"isValidSpanId",{enumerable:!0,get:function(){return Cc.isValidSpanId}});var kc=La();Object.defineProperty(Ze,"INVALID_SPANID",{enumerable:!0,get:function(){return kc.INVALID_SPANID}});Object.defineProperty(Ze,"INVALID_TRACEID",{enumerable:!0,get:function(){return kc.INVALID_TRACEID}});Object.defineProperty(Ze,"INVALID_SPAN_CONTEXT",{enumerable:!0,get:function(){return kc.INVALID_SPAN_CONTEXT}});var Xy=py();Object.defineProperty(Ze,"context",{enumerable:!0,get:function(){return Xy.context}});var ev=fy();Object.defineProperty(Ze,"diag",{enumerable:!0,get:function(){return ev.diag}});var tv=Iy();Object.defineProperty(Ze,"metrics",{enumerable:!0,get:function(){return tv.metrics}});var rv=Uy();Object.defineProperty(Ze,"propagation",{enumerable:!0,get:function(){return rv.propagation}});var nv=Ky();Object.defineProperty(Ze,"trace",{enumerable:!0,get:function(){return nv.trace}});Ze.default={context:Xy.context,diag:ev.diag,metrics:tv.metrics,propagation:rv.propagation,trace:nv.trace}});var is=ye(function(DS){Object.defineProperty(DS,"__esModule",{value:!0});function OS(){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 NS(){let e=OS();if(e.__xstate__)return e.__xstate__;return}function Tz(e){if(typeof window>"u")return;let t=NS();if(t)t.register(e)}var Iz=(e)=>{if(typeof window>"u")return;let t=NS();if(t)t.register(e)};DS.devToolsAdapter=Iz;DS.getGlobal=OS;DS.registerService=Tz});var Ro=ye(function(Oq){var Ez=is();class Eu{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 FS=".",Az="",BS="",Pz="#",Au="*",GS="xstate.init",Mz="xstate.error",as="xstate.stop";function jz(e,t){return{type:`xstate.after.${e}.${t}`}}function Pu(e,t){return{type:`xstate.done.state.${e}`,output:t}}function Oz(e,t){return{type:`xstate.done.actor.${e}`,output:t,actorId:e}}function JS(e,t){return{type:`xstate.error.actor.${e}`,error:t,actorId:e}}function WS(e){return{type:GS,input:e}}function Pr(e){setTimeout(()=>{throw e})}var Nz=(()=>typeof Symbol==="function"&&Symbol.observable||"@@observable")();function Nu(e,t){let n=zS(e),o=zS(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 Nu(n[i],o[i])})}function Du(e){if(ZS(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 zS(e){if(mw(e))return e.value;if(typeof e!=="string")return e;let t=Du(e);return HS(t)}function HS(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 Dz(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 VS(e){if(ZS(e))return e;return[e]}function Fi(e){if(e===void 0)return[];return VS(e)}function Mu(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.
|
|
2
|
+
import{pa as vR,qa as RR,ra as ER}from"./index-pnk0v35n.js";import{sa as cp}from"./index-48ksf4j5.js";import{$d as OI,Ab as Ko,Ac as de,Af as IT,Ag as PT,Bc as hs,Bd as IC,Cb as yr,Cc as hd,Ce as hT,Cf as xC,Dc as Xr,De as NT,Df as CT,Dg as fx,Eb as QT,Ef as kT,Fc as yn,Fe as DT,Ff as RT,Gc as nT,Ge as EI,Hb as Ad,Hc as oT,Ib as Lx,Ic as iT,Ie as XI,Jb as ar,Je as yT,Kc as fC,Lb as Oo,Lc as hC,Ld as kC,Mc as yC,Md as RC,Me as Nr,Nb as Ux,Nd as EC,Ne as _p,Oc as mt,Od as AC,Oe as ma,Pd as PC,Pe as XT,Qd as MC,Qe as SC,Rd as jC,Re as Ix,Sd as OC,Se as _T,Td as NC,Uc as mx,Ud as ua,Ue as WT,Vb as Fx,Vd as dI,Ve as qd,Wd as QI,Xf as sI,Yb as Ed,Yd as Ht,Zb as Ts,Zd as Us,Ze as VT,_b as Ox,_d as Ld,ac as Nx,ae as qI,cb as ZI,cc as Dx,df as wC,ee as Fs,fc as zx,ff as ST,gb as KI,gc as Gx,gf as wT,ib as BI,ic as _n,jb as GI,jc as Sn,kc as zC,lc as $C,mc as HT,nc as Mx,ng as nI,nh as zT,ob as Qr,og as oI,oh as Qx,pg as da,qc as Os,qd as LC,rc as rT,rd as UC,rh as $T,sc as Vx,sd as FC,se as _C,sh as Xx,tc as zw,te as Ex,tf as xT,th as MT,uc as rt,uh as eT,vc as ir,vd as wI,vf as TT,wc as fT,wd as Yd,wf as zs,xc as tt,xd as kx,yc as Xe,yg as AT,yh as jT,zc as Vi,zf as Zs}from"./index-2yv19jfg.js";import{Ah as _s,Ch as mC,Dh as vs,Eh as Hw,Fh as bs,Gh as Vw,Hh as ET,Lh as bn,Ph as en}from"./index-yjze2rv7.js";import{Qh as $t,Rh as vr}from"./index-tk259k9b.js";import{$h as na,$i as wx,Bi as Kx,Cj as aI,Di as Yx,Ei as vx,Fj as bC,Gj as $d,Hi as fs,Ji as xx,Li as Tx,Lj as cT,Sj as vT,Th as Lm,Ti as Qi,Uh as Um,Vh as r,Wi as Zn,Xj as SI,Yi as Re,Yj as ys,Zh as np,Zi as Xi,Zj as bT,gj as Es,mj as Gd,nj as JT,oj as pC,pi as gt,ri as os,xi as Ww}from"./index-cg08v65w.js";import{ck as Mn,dk as ye,fk as Rl}from"./index-wk8ajgjh.js";var kl=ye(function(FW,ug){var{defineProperty:Cl,getOwnPropertyDescriptor:dR,getOwnPropertyNames:pR}=Object,mR=Object.prototype.hasOwnProperty,gR=(e,t)=>{for(var n in t)Cl(e,n,{get:t[n],enumerable:!0})},fR=(e,t,n,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of pR(t))if(!mR.call(e,i)&&i!==n)Cl(e,i,{get:()=>t[i],enumerable:!(o=dR(t,i))||o.enumerable})}return e},hR=(e)=>fR(Cl({},"__esModule",{value:!0}),e),lg={};gR(lg,{SYMBOL_FOR_REQ_CONTEXT:()=>cg,getContext:()=>yR});ug.exports=hR(lg);var cg=Symbol.for("@vercel/request-context");function yR(){return globalThis[cg]?.get?.()??{}}});var mg=ye(function(BW,pg){var{defineProperty:Al,getOwnPropertyDescriptor:bR,getOwnPropertyNames:_R}=Object,SR=Object.prototype.hasOwnProperty,wR=(e,t)=>{for(var n in t)Al(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)Al(e,i,{get:()=>t[i],enumerable:!(o=bR(t,i))||o.enumerable})}return e},TR=(e)=>xR(Al({},"__esModule",{value:!0}),e),dg={};wR(dg,{getVercelOidcToken:()=>kR,getVercelOidcTokenSync:()=>El});pg.exports=TR(dg);var IR=kl(),CR=vR();async function kR(e){let t="",n;try{t=El()}catch(o){n=o}try{let[{getTokenPayload:o,isExpired:i},{refreshToken:a}]=await Promise.all([await import("./token-util-vteawk6a.js").then((m)=>Mn(m.default)),await import("./token-4y57emyd.js").then((m)=>Mn(m.default))]);if(!t||i(o(t),e?.expirationBufferMs))await a(e),t=El()}catch(o){let i=n instanceof Error?n.message:"";if(o instanceof Error)i=`${i}
|
|
3
|
+
${o.message}`;if(i)throw new CR.VercelOidcTokenError(i);throw o}return t}function El(){let e=(0,IR.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 Ml=ye(function(GW,yg){var{defineProperty:Pl,getOwnPropertyDescriptor:AR,getOwnPropertyNames:PR}=Object,MR=Object.prototype.hasOwnProperty,jR=(e,t)=>{for(var n in t)Pl(e,n,{get:t[n],enumerable:!0})},OR=(e,t,n,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of PR(t))if(!MR.call(e,i)&&i!==n)Pl(e,i,{get:()=>t[i],enumerable:!(o=AR(t,i))||o.enumerable})}return e},NR=(e)=>OR(Pl({},"__esModule",{value:!0}),e),hg={};jR(hg,{AccessTokenMissingError:()=>fg.AccessTokenMissingError,RefreshAccessTokenFailedError:()=>fg.RefreshAccessTokenFailedError,getContext:()=>DR.getContext,getVercelOidcToken:()=>gg.getVercelOidcToken,getVercelOidcTokenSync:()=>gg.getVercelOidcTokenSync,getVercelToken:()=>zR.getVercelToken});yg.exports=NR(hg);var gg=mg(),DR=kl(),fg=RR(),zR=ER()});var Nl=ye(function(mf){Object.defineProperty(mf,"__esModule",{value:!0});mf.VERSION=void 0;mf.VERSION="1.9.1"});var bf=ye(function(yf){Object.defineProperty(yf,"__esModule",{value:!0});yf.isCompatible=yf._makeCompatibilityCheck=void 0;var eA=Nl(),ff=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function hf(e){let t=new Set([e]),n=new Set,o=e.match(ff);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(ff);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)}}yf._makeCompatibilityCheck=hf;yf.isCompatible=hf(eA.VERSION)});var jn=ye(function(_f){Object.defineProperty(_f,"__esModule",{value:!0});_f.unregisterGlobal=_f.getGlobal=_f.registerGlobal=void 0;var lo=Nl(),rA=bf(),nA=lo.VERSION.split(".")[0],yi=Symbol.for(`opentelemetry.js.api.${nA}`),vi=typeof globalThis==="object"?globalThis:typeof self==="object"?self:typeof window==="object"?window:typeof global==="object"?global:{};function oA(e,t,n,o=!1){var i;let a=vi[yi]=(i=vi[yi])!==null&&i!==void 0?i:{version:lo.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!==lo.VERSION){let s=Error(`@opentelemetry/api: Registration of version v${a.version} for ${e} does not match previously registered API v${lo.VERSION}`);return n.error(s.stack||s.message),!1}return a[e]=t,n.debug(`@opentelemetry/api: Registered a global for ${e} v${lo.VERSION}.`),!0}_f.registerGlobal=oA;function iA(e){var t,n;let o=(t=vi[yi])===null||t===void 0?void 0:t.version;if(!o||!(0,rA.isCompatible)(o))return;return(n=vi[yi])===null||n===void 0?void 0:n[e]}_f.getGlobal=iA;function aA(e,t){t.debug(`@opentelemetry/api: Unregistering a global for ${e} v${lo.VERSION}.`);let n=vi[yi];if(n)delete n[e]}_f.unregisterGlobal=aA});var If=ye(function(xf){Object.defineProperty(xf,"__esModule",{value:!0});xf.DiagComponentLogger=void 0;var cA=jn();class wf{constructor(e){this._namespace=e.namespace||"DiagComponentLogger"}debug(...e){return bi("debug",this._namespace,e)}error(...e){return bi("error",this._namespace,e)}info(...e){return bi("info",this._namespace,e)}warn(...e){return bi("warn",this._namespace,e)}verbose(...e){return bi("verbose",this._namespace,e)}}xf.DiagComponentLogger=wf;function bi(e,t,n){let o=(0,cA.getGlobal)("diag");if(!o)return;return o[e](t,...n)}});var Da=ye(function(Cf){Object.defineProperty(Cf,"__esModule",{value:!0});Cf.DiagLogLevel=void 0;var uA;(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"})(uA=Cf.DiagLogLevel||(Cf.DiagLogLevel={}))});var Ef=ye(function(kf){Object.defineProperty(kf,"__esModule",{value:!0});kf.createLogLevelDiagLogger=void 0;var Wr=Da();function dA(e,t){if(e<Wr.DiagLogLevel.NONE)e=Wr.DiagLogLevel.NONE;else if(e>Wr.DiagLogLevel.ALL)e=Wr.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",Wr.DiagLogLevel.ERROR),warn:n("warn",Wr.DiagLogLevel.WARN),info:n("info",Wr.DiagLogLevel.INFO),debug:n("debug",Wr.DiagLogLevel.DEBUG),verbose:n("verbose",Wr.DiagLogLevel.VERBOSE)}}kf.createLogLevelDiagLogger=dA});var On=ye(function(Pf){Object.defineProperty(Pf,"__esModule",{value:!0});Pf.DiagAPI=void 0;var pA=If(),mA=Ef(),Af=Da(),za=jn(),gA="diag";class zl{static instance(){if(!this._instance)this._instance=new zl;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:Af.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,mA.createLogLevelDiagLogger)((s=i.logLevel)!==null&&s!==void 0?s:Af.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)(gA,t)},t.createComponentLogger=(o)=>new pA.DiagComponentLogger(o),t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}}Pf.DiagAPI=zl});var Nf=ye(function(jf){Object.defineProperty(jf,"__esModule",{value:!0});jf.BaggageImpl=void 0;class co{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 co(this._entries);return n._entries.set(e,t),n}removeEntry(e){let t=new co(this._entries);return t._entries.delete(e),t}removeEntries(...e){let t=new co(this._entries);for(let n of e)t._entries.delete(n);return t}clear(){return new co}}jf.BaggageImpl=co});var $f=ye(function(Df){Object.defineProperty(Df,"__esModule",{value:!0});Df.baggageEntryMetadataSymbol=void 0;Df.baggageEntryMetadataSymbol=Symbol("BaggageEntryMetadata")});var $l=ye(function(qf){Object.defineProperty(qf,"__esModule",{value:!0});qf.baggageEntryMetadataFromString=qf.createBaggage=void 0;var fA=On(),hA=Nf(),yA=$f(),vA=fA.DiagAPI.instance();function bA(e={}){return new hA.BaggageImpl(new Map(Object.entries(e)))}qf.createBaggage=bA;function _A(e){if(typeof e!=="string")vA.error(`Cannot create baggage metadata from unknown type: ${typeof e}`),e="";return{__TYPE__:yA.baggageEntryMetadataSymbol,toString(){return e}}}qf.baggageEntryMetadataFromString=_A});var _i=ye(function(Uf){Object.defineProperty(Uf,"__esModule",{value:!0});Uf.ROOT_CONTEXT=Uf.createContextKey=void 0;function wA(e){return Symbol.for(e)}Uf.createContextKey=wA;class $a{constructor(e){let t=this;t._currentContext=e?new Map(e):new Map,t.getValue=(n)=>t._currentContext.get(n),t.setValue=(n,o)=>{let i=new $a(t._currentContext);return i._currentContext.set(n,o),i},t.deleteValue=(n)=>{let o=new $a(t._currentContext);return o._currentContext.delete(n),o}}}Uf.ROOT_CONTEXT=new $a});var Wf=ye(function(Gf){Object.defineProperty(Gf,"__esModule",{value:!0});Gf.DiagConsoleLogger=Gf._originalConsoleMethods=void 0;var ql=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}];Gf._originalConsoleMethods={};if(typeof console<"u"){let e=["error","warn","info","debug","trace","log"];for(let t of e)if(typeof console[t]==="function")Gf._originalConsoleMethods[t]=console[t]}class Bf{constructor(){function e(t){return function(...n){let o=Gf._originalConsoleMethods[t];if(typeof o!=="function")o=Gf._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<ql.length;t++)this[ql[t].n]=e(ql[t].c)}}Gf.DiagConsoleLogger=Bf});var Vl=ye(function(Hf){Object.defineProperty(Hf,"__esModule",{value:!0});Hf.createNoopMeter=Hf.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=Hf.NOOP_OBSERVABLE_GAUGE_METRIC=Hf.NOOP_OBSERVABLE_COUNTER_METRIC=Hf.NOOP_UP_DOWN_COUNTER_METRIC=Hf.NOOP_HISTOGRAM_METRIC=Hf.NOOP_GAUGE_METRIC=Hf.NOOP_COUNTER_METRIC=Hf.NOOP_METER=Hf.NoopObservableUpDownCounterMetric=Hf.NoopObservableGaugeMetric=Hf.NoopObservableCounterMetric=Hf.NoopObservableMetric=Hf.NoopHistogramMetric=Hf.NoopGaugeMetric=Hf.NoopUpDownCounterMetric=Hf.NoopCounterMetric=Hf.NoopMetric=Hf.NoopMeter=void 0;class Ll{constructor(){}createGauge(e,t){return Hf.NOOP_GAUGE_METRIC}createHistogram(e,t){return Hf.NOOP_HISTOGRAM_METRIC}createCounter(e,t){return Hf.NOOP_COUNTER_METRIC}createUpDownCounter(e,t){return Hf.NOOP_UP_DOWN_COUNTER_METRIC}createObservableGauge(e,t){return Hf.NOOP_OBSERVABLE_GAUGE_METRIC}createObservableCounter(e,t){return Hf.NOOP_OBSERVABLE_COUNTER_METRIC}createObservableUpDownCounter(e,t){return Hf.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC}addBatchObservableCallback(e,t){}removeBatchObservableCallback(e){}}Hf.NoopMeter=Ll;class uo{}Hf.NoopMetric=uo;class Ul extends uo{add(e,t){}}Hf.NoopCounterMetric=Ul;class Fl extends uo{add(e,t){}}Hf.NoopUpDownCounterMetric=Fl;class Bl extends uo{record(e,t){}}Hf.NoopGaugeMetric=Bl;class Gl extends uo{record(e,t){}}Hf.NoopHistogramMetric=Gl;class Si{addCallback(e){}removeCallback(e){}}Hf.NoopObservableMetric=Si;class Jl extends Si{}Hf.NoopObservableCounterMetric=Jl;class Wl extends Si{}Hf.NoopObservableGaugeMetric=Wl;class Hl extends Si{}Hf.NoopObservableUpDownCounterMetric=Hl;Hf.NOOP_METER=new Ll;Hf.NOOP_COUNTER_METRIC=new Ul;Hf.NOOP_GAUGE_METRIC=new Bl;Hf.NOOP_HISTOGRAM_METRIC=new Gl;Hf.NOOP_UP_DOWN_COUNTER_METRIC=new Fl;Hf.NOOP_OBSERVABLE_COUNTER_METRIC=new Jl;Hf.NOOP_OBSERVABLE_GAUGE_METRIC=new Wl;Hf.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=new Hl;function TA(){return Hf.NOOP_METER}Hf.createNoopMeter=TA});var oh=ye(function(nh){Object.defineProperty(nh,"__esModule",{value:!0});nh.ValueType=void 0;var NA;(function(e){e[e.INT=0]="INT",e[e.DOUBLE=1]="DOUBLE"})(NA=nh.ValueType||(nh.ValueType={}))});var Kl=ye(function(ih){Object.defineProperty(ih,"__esModule",{value:!0});ih.defaultTextMapSetter=ih.defaultTextMapGetter=void 0;ih.defaultTextMapGetter={get(e,t){if(e==null)return;return e[t]},keys(e){if(e==null)return[];return Object.keys(e)}};ih.defaultTextMapSetter={set(e,t,n){if(e==null)return;e[t]=n}}});var uh=ye(function(lh){Object.defineProperty(lh,"__esModule",{value:!0});lh.NoopContextManager=void 0;var zA=_i();class sh{active(){return zA.ROOT_CONTEXT}with(e,t,n,...o){return t.call(n,...o)}bind(e,t){return t}enable(){return this}disable(){return this}}lh.NoopContextManager=sh});var wi=ye(function(ph){Object.defineProperty(ph,"__esModule",{value:!0});ph.ContextAPI=void 0;var $A=uh(),Yl=jn(),dh=On(),Ql="context",qA=new $A.NoopContextManager;class Xl{constructor(){}static getInstance(){if(!this._instance)this._instance=new Xl;return this._instance}setGlobalContextManager(e){return(0,Yl.registerGlobal)(Ql,e,dh.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,Yl.getGlobal)(Ql)||qA}disable(){this._getContextManager().disable(),(0,Yl.unregisterGlobal)(Ql,dh.DiagAPI.instance())}}ph.ContextAPI=Xl});var tc=ye(function(gh){Object.defineProperty(gh,"__esModule",{value:!0});gh.TraceFlags=void 0;var LA;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(LA=gh.TraceFlags||(gh.TraceFlags={}))});var La=ye(function(fh){Object.defineProperty(fh,"__esModule",{value:!0});fh.INVALID_SPAN_CONTEXT=fh.INVALID_TRACEID=fh.INVALID_SPANID=void 0;var UA=tc();fh.INVALID_SPANID="0000000000000000";fh.INVALID_TRACEID="00000000000000000000000000000000";fh.INVALID_SPAN_CONTEXT={traceId:fh.INVALID_TRACEID,spanId:fh.INVALID_SPANID,traceFlags:UA.TraceFlags.NONE}});var Ua=ye(function(_h){Object.defineProperty(_h,"__esModule",{value:!0});_h.NonRecordingSpan=void 0;var FA=La();class bh{constructor(e=FA.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){}}_h.NonRecordingSpan=bh});var oc=ye(function(xh){Object.defineProperty(xh,"__esModule",{value:!0});xh.getSpanContext=xh.setSpanContext=xh.deleteSpan=xh.setSpan=xh.getActiveSpan=xh.getSpan=void 0;var BA=_i(),GA=Ua(),JA=wi(),rc=(0,BA.createContextKey)("OpenTelemetry Context Key SPAN");function nc(e){return e.getValue(rc)||void 0}xh.getSpan=nc;function WA(){return nc(JA.ContextAPI.getInstance().active())}xh.getActiveSpan=WA;function wh(e,t){return e.setValue(rc,t)}xh.setSpan=wh;function HA(e){return e.deleteValue(rc)}xh.deleteSpan=HA;function VA(e,t){return wh(e,new GA.NonRecordingSpan(t))}xh.setSpanContext=VA;function ZA(e){var t;return(t=nc(e))===null||t===void 0?void 0:t.spanContext()}xh.getSpanContext=ZA});var Ba=ye(function(Eh){Object.defineProperty(Eh,"__esModule",{value:!0});Eh.wrapSpanContext=Eh.isSpanContextValid=Eh.isValidSpanId=Eh.isValidTraceId=void 0;var Ih=La(),tP=Ua(),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 Ch(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 kh(e){return Ch(e,32)&&e!==Ih.INVALID_TRACEID}Eh.isValidTraceId=kh;function Rh(e){return Ch(e,16)&&e!==Ih.INVALID_SPANID}Eh.isValidSpanId=Rh;function rP(e){return kh(e.traceId)&&Rh(e.spanId)}Eh.isSpanContextValid=rP;function nP(e){return new tP.NonRecordingSpan(e)}Eh.wrapSpanContext=nP});var sc=ye(function(jh){Object.defineProperty(jh,"__esModule",{value:!0});jh.NoopTracer=void 0;var sP=wi(),Ph=oc(),ic=Ua(),lP=Ba(),ac=sP.ContextAPI.getInstance();class Mh{startSpan(e,t,n=ac.active()){if(Boolean(t===null||t===void 0?void 0:t.root))return new ic.NonRecordingSpan;let i=n&&(0,Ph.getSpanContext)(n);if(cP(i)&&(0,lP.isSpanContextValid)(i))return new ic.NonRecordingSpan(i);else return new ic.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:ac.active(),c=this.startSpan(e,i,l),u=(0,Ph.setSpan)(l,c);return ac.with(u,s,void 0,c)}}jh.NoopTracer=Mh;function cP(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 lc=ye(function(Dh){Object.defineProperty(Dh,"__esModule",{value:!0});Dh.ProxyTracer=void 0;var uP=sc(),dP=new uP.NoopTracer;class Nh{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 dP;return this._delegate=e,this._delegate}}Dh.ProxyTracer=Nh});var Uh=ye(function(qh){Object.defineProperty(qh,"__esModule",{value:!0});qh.NoopTracerProvider=void 0;var pP=sc();class $h{getTracer(e,t,n){return new pP.NoopTracer}}qh.NoopTracerProvider=$h});var cc=ye(function(Bh){Object.defineProperty(Bh,"__esModule",{value:!0});Bh.ProxyTracerProvider=void 0;var mP=lc(),gP=Uh(),fP=new gP.NoopTracerProvider;class Fh{getTracer(e,t,n){var o;return(o=this.getDelegateTracer(e,t,n))!==null&&o!==void 0?o:new mP.ProxyTracer(this,e,t,n)}getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:fP}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)}}Bh.ProxyTracerProvider=Fh});var Wh=ye(function(Jh){Object.defineProperty(Jh,"__esModule",{value:!0});Jh.SamplingDecision=void 0;var hP;(function(e){e[e.NOT_RECORD=0]="NOT_RECORD",e[e.RECORD=1]="RECORD",e[e.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(hP=Jh.SamplingDecision||(Jh.SamplingDecision={}))});var Vh=ye(function(Hh){Object.defineProperty(Hh,"__esModule",{value:!0});Hh.SpanKind=void 0;var yP;(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"})(yP=Hh.SpanKind||(Hh.SpanKind={}))});var Kh=ye(function(Zh){Object.defineProperty(Zh,"__esModule",{value:!0});Zh.SpanStatusCode=void 0;var vP;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(vP=Zh.SpanStatusCode||(Zh.SpanStatusCode={}))});var Xh=ye(function(Yh){Object.defineProperty(Yh,"__esModule",{value:!0});Yh.validateValue=Yh.validateKey=void 0;var mc="[_0-9a-z-*/]",bP=`[a-z]${mc}{0,255}`,_P=`[a-z0-9]${mc}{0,240}@[a-z]${mc}{0,13}`,SP=new RegExp(`^(?:${bP}|${_P})$`),wP=/^[ -~]{0,255}[!-~]$/,xP=/,|=/;function TP(e){return SP.test(e)}Yh.validateKey=TP;function IP(e){return wP.test(e)&&!xP.test(e)}Yh.validateValue=IP});var ay=ye(function(oy){Object.defineProperty(oy,"__esModule",{value:!0});oy.TraceStateImpl=void 0;var ey=Xh(),ty=32,kP=512,ry=",",ny="=";class gc{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+ny+this.get(t)),e),[]).join(ry)}_parse(e){if(e.length>kP)return;if(this._internalState=e.split(ry).reduceRight((t,n)=>{let o=n.trim(),i=o.indexOf(ny);if(i!==-1){let a=o.slice(0,i),s=o.slice(i+1,n.length);if((0,ey.validateKey)(a)&&(0,ey.validateValue)(s))t.set(a,s)}return t},new Map),this._internalState.size>ty)this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,ty))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new gc;return e._internalState=new Map(this._internalState),e}}oy.TraceStateImpl=gc});var cy=ye(function(sy){Object.defineProperty(sy,"__esModule",{value:!0});sy.createTraceState=void 0;var RP=ay();function EP(e){return new RP.TraceStateImpl(e)}sy.createTraceState=EP});var py=ye(function(uy){Object.defineProperty(uy,"__esModule",{value:!0});uy.context=void 0;var AP=wi();uy.context=AP.ContextAPI.getInstance()});var fy=ye(function(my){Object.defineProperty(my,"__esModule",{value:!0});my.diag=void 0;var PP=On();my.diag=PP.DiagAPI.instance()});var vy=ye(function(hy){Object.defineProperty(hy,"__esModule",{value:!0});hy.NOOP_METER_PROVIDER=hy.NoopMeterProvider=void 0;var MP=Vl();class fc{getMeter(e,t,n){return MP.NOOP_METER}}hy.NoopMeterProvider=fc;hy.NOOP_METER_PROVIDER=new fc});var wy=ye(function(_y){Object.defineProperty(_y,"__esModule",{value:!0});_y.MetricsAPI=void 0;var OP=vy(),hc=jn(),by=On(),yc="metrics";class vc{constructor(){}static getInstance(){if(!this._instance)this._instance=new vc;return this._instance}setGlobalMeterProvider(e){return(0,hc.registerGlobal)(yc,e,by.DiagAPI.instance())}getMeterProvider(){return(0,hc.getGlobal)(yc)||OP.NOOP_METER_PROVIDER}getMeter(e,t,n){return this.getMeterProvider().getMeter(e,t,n)}disable(){(0,hc.unregisterGlobal)(yc,by.DiagAPI.instance())}}_y.MetricsAPI=vc});var Iy=ye(function(xy){Object.defineProperty(xy,"__esModule",{value:!0});xy.metrics=void 0;var NP=wy();xy.metrics=NP.MetricsAPI.getInstance()});var Ey=ye(function(ky){Object.defineProperty(ky,"__esModule",{value:!0});ky.NoopTextMapPropagator=void 0;class Cy{inject(e,t){}extract(e,t){return e}fields(){return[]}}ky.NoopTextMapPropagator=Cy});var jy=ye(function(Py){Object.defineProperty(Py,"__esModule",{value:!0});Py.deleteBaggage=Py.setBaggage=Py.getActiveBaggage=Py.getBaggage=void 0;var DP=wi(),zP=_i(),bc=(0,zP.createContextKey)("OpenTelemetry Baggage Key");function Ay(e){return e.getValue(bc)||void 0}Py.getBaggage=Ay;function $P(){return Ay(DP.ContextAPI.getInstance().active())}Py.getActiveBaggage=$P;function qP(e,t){return e.setValue(bc,t)}Py.setBaggage=qP;function LP(e){return e.deleteValue(bc)}Py.deleteBaggage=LP});var $y=ye(function(Dy){Object.defineProperty(Dy,"__esModule",{value:!0});Dy.PropagationAPI=void 0;var _c=jn(),GP=Ey(),Oy=Kl(),Ga=jy(),JP=$l(),Ny=On(),Sc="propagation",WP=new GP.NoopTextMapPropagator;class wc{constructor(){this.createBaggage=JP.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 wc;return this._instance}setGlobalPropagator(e){return(0,_c.registerGlobal)(Sc,e,Ny.DiagAPI.instance())}inject(e,t,n=Oy.defaultTextMapSetter){return this._getGlobalPropagator().inject(e,t,n)}extract(e,t,n=Oy.defaultTextMapGetter){return this._getGlobalPropagator().extract(e,t,n)}fields(){return this._getGlobalPropagator().fields()}disable(){(0,_c.unregisterGlobal)(Sc,Ny.DiagAPI.instance())}_getGlobalPropagator(){return(0,_c.getGlobal)(Sc)||WP}}Dy.PropagationAPI=wc});var Uy=ye(function(qy){Object.defineProperty(qy,"__esModule",{value:!0});qy.propagation=void 0;var HP=$y();qy.propagation=HP.PropagationAPI.getInstance()});var Hy=ye(function(Jy){Object.defineProperty(Jy,"__esModule",{value:!0});Jy.TraceAPI=void 0;var xc=jn(),Fy=cc(),By=Ba(),po=oc(),Gy=On(),Tc="trace";class Ic{constructor(){this._proxyTracerProvider=new Fy.ProxyTracerProvider,this.wrapSpanContext=By.wrapSpanContext,this.isSpanContextValid=By.isSpanContextValid,this.deleteSpan=po.deleteSpan,this.getSpan=po.getSpan,this.getActiveSpan=po.getActiveSpan,this.getSpanContext=po.getSpanContext,this.setSpan=po.setSpan,this.setSpanContext=po.setSpanContext}static getInstance(){if(!this._instance)this._instance=new Ic;return this._instance}setGlobalTracerProvider(e){let t=(0,xc.registerGlobal)(Tc,this._proxyTracerProvider,Gy.DiagAPI.instance());if(t)this._proxyTracerProvider.setDelegate(e);return t}getTracerProvider(){return(0,xc.getGlobal)(Tc)||this._proxyTracerProvider}getTracer(e,t){return this.getTracerProvider().getTracer(e,t)}disable(){(0,xc.unregisterGlobal)(Tc,Gy.DiagAPI.instance()),this._proxyTracerProvider=new Fy.ProxyTracerProvider}}Jy.TraceAPI=Ic});var Ky=ye(function(Vy){Object.defineProperty(Vy,"__esModule",{value:!0});Vy.trace=void 0;var VP=Hy();Vy.trace=VP.TraceAPI.getInstance()});var Rc=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 ZP=$l();Object.defineProperty(Ze,"baggageEntryMetadataFromString",{enumerable:!0,get:function(){return ZP.baggageEntryMetadataFromString}});var Yy=_i();Object.defineProperty(Ze,"createContextKey",{enumerable:!0,get:function(){return Yy.createContextKey}});Object.defineProperty(Ze,"ROOT_CONTEXT",{enumerable:!0,get:function(){return Yy.ROOT_CONTEXT}});var KP=Wf();Object.defineProperty(Ze,"DiagConsoleLogger",{enumerable:!0,get:function(){return KP.DiagConsoleLogger}});var YP=Da();Object.defineProperty(Ze,"DiagLogLevel",{enumerable:!0,get:function(){return YP.DiagLogLevel}});var QP=Vl();Object.defineProperty(Ze,"createNoopMeter",{enumerable:!0,get:function(){return QP.createNoopMeter}});var XP=oh();Object.defineProperty(Ze,"ValueType",{enumerable:!0,get:function(){return XP.ValueType}});var Qy=Kl();Object.defineProperty(Ze,"defaultTextMapGetter",{enumerable:!0,get:function(){return Qy.defaultTextMapGetter}});Object.defineProperty(Ze,"defaultTextMapSetter",{enumerable:!0,get:function(){return Qy.defaultTextMapSetter}});var eM=lc();Object.defineProperty(Ze,"ProxyTracer",{enumerable:!0,get:function(){return eM.ProxyTracer}});var tM=cc();Object.defineProperty(Ze,"ProxyTracerProvider",{enumerable:!0,get:function(){return tM.ProxyTracerProvider}});var rM=Wh();Object.defineProperty(Ze,"SamplingDecision",{enumerable:!0,get:function(){return rM.SamplingDecision}});var nM=Vh();Object.defineProperty(Ze,"SpanKind",{enumerable:!0,get:function(){return nM.SpanKind}});var oM=Kh();Object.defineProperty(Ze,"SpanStatusCode",{enumerable:!0,get:function(){return oM.SpanStatusCode}});var iM=tc();Object.defineProperty(Ze,"TraceFlags",{enumerable:!0,get:function(){return iM.TraceFlags}});var aM=cy();Object.defineProperty(Ze,"createTraceState",{enumerable:!0,get:function(){return aM.createTraceState}});var Cc=Ba();Object.defineProperty(Ze,"isSpanContextValid",{enumerable:!0,get:function(){return Cc.isSpanContextValid}});Object.defineProperty(Ze,"isValidTraceId",{enumerable:!0,get:function(){return Cc.isValidTraceId}});Object.defineProperty(Ze,"isValidSpanId",{enumerable:!0,get:function(){return Cc.isValidSpanId}});var kc=La();Object.defineProperty(Ze,"INVALID_SPANID",{enumerable:!0,get:function(){return kc.INVALID_SPANID}});Object.defineProperty(Ze,"INVALID_TRACEID",{enumerable:!0,get:function(){return kc.INVALID_TRACEID}});Object.defineProperty(Ze,"INVALID_SPAN_CONTEXT",{enumerable:!0,get:function(){return kc.INVALID_SPAN_CONTEXT}});var Xy=py();Object.defineProperty(Ze,"context",{enumerable:!0,get:function(){return Xy.context}});var ev=fy();Object.defineProperty(Ze,"diag",{enumerable:!0,get:function(){return ev.diag}});var tv=Iy();Object.defineProperty(Ze,"metrics",{enumerable:!0,get:function(){return tv.metrics}});var rv=Uy();Object.defineProperty(Ze,"propagation",{enumerable:!0,get:function(){return rv.propagation}});var nv=Ky();Object.defineProperty(Ze,"trace",{enumerable:!0,get:function(){return nv.trace}});Ze.default={context:Xy.context,diag:ev.diag,metrics:tv.metrics,propagation:rv.propagation,trace:nv.trace}});var is=ye(function(DS){Object.defineProperty(DS,"__esModule",{value:!0});function OS(){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 NS(){let e=OS();if(e.__xstate__)return e.__xstate__;return}function Tz(e){if(typeof window>"u")return;let t=NS();if(t)t.register(e)}var Iz=(e)=>{if(typeof window>"u")return;let t=NS();if(t)t.register(e)};DS.devToolsAdapter=Iz;DS.getGlobal=OS;DS.registerService=Tz});var Ro=ye(function(O$){var Ez=is();class Eu{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 FS=".",Az="",BS="",Pz="#",Au="*",GS="xstate.init",Mz="xstate.error",as="xstate.stop";function jz(e,t){return{type:`xstate.after.${e}.${t}`}}function Pu(e,t){return{type:`xstate.done.state.${e}`,output:t}}function Oz(e,t){return{type:`xstate.done.actor.${e}`,output:t,actorId:e}}function JS(e,t){return{type:`xstate.error.actor.${e}`,error:t,actorId:e}}function WS(e){return{type:GS,input:e}}function Pr(e){setTimeout(()=>{throw e})}var Nz=(()=>typeof Symbol==="function"&&Symbol.observable||"@@observable")();function Nu(e,t){let n=zS(e),o=zS(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 Nu(n[i],o[i])})}function Du(e){if(ZS(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 zS(e){if(mw(e))return e.value;if(typeof e!=="string")return e;let t=Du(e);return HS(t)}function HS(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 Dz(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 VS(e){if(ZS(e))return e;return[e]}function Fi(e){if(e===void 0)return[];return VS(e)}function Mu(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
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 ZS(e){return Array.isArray(e)}function zz(e){return e.type.startsWith("xstate.error.actor")}function So(e){return VS(e).map((t)=>{if(typeof t>"u"||typeof t==="string")return{target:t};return t})}function KS(e){if(e===void 0||e===Az)return;return Fi(e)}function Li(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
|
|
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:Ez.devToolsAdapter)(this)}toJSON(){return{xstate$$type:zu,id:this.id}}getPersistedSnapshot(e){return this.logic.getPersistedSnapshot(this._snapshot,e)}[Nz](){return this}getSnapshot(){if(!this._snapshot)throw Error("Snapshot can't be read while the actor initializes itself");return this._snapshot}}function
|
|
7
|
-
${a.message}`)}else throw Error(`Invalid target: "${n}" is not a valid target from the root node. Did you mean ".${n}"?`)})}function sw(e){let t=KS(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 $S(e){let t=lw(e);for(let n of t)for(let o of ko(n,e))t.add(o);return t}function lw(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 xo(o))n(i)}return n(e),t}function To(e,t){if(Bi(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"&&Bi(t))try{return e.machine.getStateNodeById(t)}catch{}let n=Du(t).slice(),o=e;while(n.length){let i=n.shift();if(!i.length)break;o=To(o,i)}return o}function Fu(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)=>To(e,i)).filter(Boolean);return[e.machine.root,e].concat(o,n.reduce((i,a)=>{let s=To(e,a);if(!s)return i;let l=Fu(s,t[a]);return i.concat(l)},[]))}function cq(e,t,n,o){let a=To(e,t).next(n,o);if(!a||!a.length)return e.next(n,o);return a}function uq(e,t,n,o){let i=Object.keys(t),a=To(e,i[0]),s=Bu(a,t[i[0]],n,o);if(!s||!s.length)return e.next(n,o);return s}function dq(e,t,n,o){let i=[];for(let a of Object.keys(t)){let s=t[a];if(!s)continue;let l=To(e,a),c=Bu(l,s,n,o);if(c)i.push(...c)}if(!i.length)return e.next(n,o);return i}function Bu(e,t,n,o){if(typeof t==="string")return cq(e,t,n,o);if(Object.keys(t).length===1)return uq(e,t,n,o);return dq(e,t,n,o)}function pq(e){return Object.keys(e.states).map((t)=>e.states[t]).filter((t)=>t.type==="history")}function hn(e,t){let n=e;while(n.parent&&n.parent!==t)n=n.parent;return n.parent===t}function mq(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 cw(e,t,n){let o=new Set;for(let i of e){let a=!1,s=new Set;for(let l of o)if(mq(ju([i],t,n),ju([l],t,n)))if(hn(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 gq(e){let[t,...n]=e;for(let o of ko(t,void 0))if(n.every((i)=>hn(i,o)))return o}function Gu(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 Gu(sw(o),t))n.add(i);else n.add(o);return[...n]}function uw(e,t){let n=Gu(e,t);if(!n)return;if(!e.reenter&&n.every((i)=>i===e.source||hn(i,e.source)))return e.source;let o=gq(n.concat(e.source));if(o)return o;if(e.reenter)return;return e.source.machine.root}function ju(e,t,n){let o=new Set;for(let i of e)if(i.target?.length){let a=uw(i,n);if(i.reenter&&i.source===a)o.add(a);for(let s of t)if(hn(s,a))o.add(s)}return[...o]}function fq(e,t){if(e.length!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function hq(e,t,n,o,i){return Ou([{target:[...lw(e)],source:e,reenter:!0,actions:[],eventType:null,toJSON:null}],t,n,o,!0,i)}function Ou(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=cw(e,c,u),m=t;if(!i)[m,u]=_q(m,o,n,d,c,u,a,n.actionExecutor);m=Io(m,o,n,d.flatMap((f)=>f.actions),a,void 0),m=vq(m,o,n,d,c,a,u,i);let p=[...c];if(m.status==="done")m=Io(m,o,n,p.sort((f,g)=>g.order-f.order).flatMap((f)=>f.exit),a,void 0);try{if(u===t.historyValue&&fq(t._nodes,c))return[m,s];return[$n(m,{_nodes:p,historyValue:u}),s]}catch(f){throw f}}finally{n.actionExecutor=l}}function yq(e,t,n,o,i){if(o.output===void 0)return;let a=Pu(i.id,i.output!==void 0&&i.parent?Mu(i.output,e.context,t,n.self):void 0);return Mu(o.output,e.context,a,n.self)}function vq(e,t,n,o,i,a,s,l){let c=e,u=new Set,d=new Set;if(bq(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(tw(g.src,{...g,syncSnapshot:!!g.onSnapshot}));if(d.has(p)){let g=p.initial.actions;f.push(...g)}if(c=Io(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(Pu(g.id,p.output!==void 0?Mu(p.output,c.context,t,n.self):void 0));while(h?.type==="parallel"&&!m.has(h)&&Uu(i,h))m.add(h),a.push(Pu(h.id)),v=h,h=h.parent;if(h)continue;c=$n(c,{status:"done",output:yq(c,t,n,c.machine.root,v)})}}return c}function bq(e,t,n,o){for(let i of e){let a=uw(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);wo(l,t,n,o)}let s=Gu(i,t);for(let l of s){let c=ko(l,a);if(a?.type==="parallel")c.push(a);dw(o,t,n,c,!i.source.parent&&i.reenter?void 0:a)}}}function wo(e,t,n,o){if(qn(e))if(t[e.id]){let i=t[e.id];for(let a of i)o.add(a),wo(a,t,n,o);for(let a of i)Ru(a,e.parent,o,t,n)}else{let i=sw(e);for(let a of i.target){if(o.add(a),i===e.parent?.initial)n.add(e.parent);wo(a,t,n,o)}for(let a of i.target)Ru(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);wo(i,t,n,o),Ru(i,e,o,t,n)}else if(e.type==="parallel"){for(let i of xo(e).filter((a)=>!qn(a)))if(![...o].some((a)=>hn(a,i))){if(!qn(i))o.add(i),n.add(i);wo(i,t,n,o)}}}function dw(e,t,n,o,i){for(let a of o){if(!i||hn(a,i))e.add(a);if(a.type==="parallel"){for(let s of xo(a).filter((l)=>!qn(l)))if(![...e].some((l)=>hn(l,s)))e.add(s),wo(s,t,n,e)}}}function Ru(e,t,n,o,i){dw(n,o,i,ko(e,t))}function _q(e,t,n,o,i,a,s,l){let c=e,u=ju(o,i,a);u.sort((m,p)=>p.order-m.order);let d;for(let m of u)for(let p of pq(m)){let f;if(p.history==="deep")f=(g)=>cs(g)&&hn(g,m);else f=(g)=>g.parent===m;d??={...a},d[p.id]=Array.from(i).filter(f)}for(let m of u)c=Io(c,t,n,[...m.exit,...m.invoke.map((p)=>ls(p.id))],s,void 0),i.delete(m);return[c,d||a]}function Sq(e,t){return e.implementations.actions[t]}function pw(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:Sq(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=pw(l,t,n,v,i,a)}return l}function Io(e,t,n,o,i,a){let s=a?[]:void 0,l=pw(e,t,n,o,{internalQueue:i,deferredActorIds:a},s);return s?.forEach(([c,u])=>{c.retryResolve(n,l,u)}),l}function wq(e,t,n,o){if(t.type===Au)throw Error(`An event cannot have the wildcard type ('${Au}')`);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=$n(LS(i,t,n),{status:"stopped"}),s([i,[]],t,[]),{snapshot:i,microsteps:a};let l=t;if(l.type!==GS){let m=l,p=zz(m),f=US(m,i);if(p&&!f.length)return i=$n(e,{status:"error",error:m.error}),s([i,[]],m,[]),{snapshot:i,microsteps:a};let g=Ou(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?xq(i,l):[],p=m.length?i:void 0;if(!m.length){if(!o.length)break;l=o.shift(),m=US(l,i)}let f=Ou(m,i,n,l,!1,o);i=f[0],c=i!==p,s(f,l,m)}if(i.status!=="active")LS(i,l,n);return{snapshot:i,microsteps:a}}function LS(e,t,n){return Io(e,t,n,Object.values(e.children).map((o)=>ls(o)),[],void 0)}function US(e,t){return t.machine.getTransitionData(t,e)}function xq(e,t){let n=new Set,o=e._nodes.filter(cs);for(let i of o)e:for(let a of[i].concat(ko(i,void 0))){if(!a.always)continue;for(let s of a.always)if(s.guard===void 0||Co(s.guard,e.context,t,e)){n.add(s);break e}}return cw(Array.from(n),new Set(e._nodes),e.historyValue)}function Tq(e,t){let n=Lu(Fu(e,t));return aw(e,[...n])}function mw(e){return!!e&&typeof e==="object"&&"machine"in e&&"value"in e}var Iq=function(t){return Nu(t,this.value)},Cq=function(t){return this.tags.has(t)},kq=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)},Rq=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)}},Eq=function(){return this._nodes.reduce((t,n)=>{if(n.meta!==void 0)t[n.id]=n.meta;return t},{})};function gw(e,t){return{status:e.status,output:e.output,error:e.error,machine:t,context:e.context,_nodes:e._nodes,value:aw(t.root,e._nodes),tags:new Set(e._nodes.flatMap((n)=>n.tags)),children:e.children,historyValue:e.historyValue||{},matches:Iq,hasTag:Cq,can:kq,getMeta:Eq,toJSON:Rq}}function $n(e,t={}){return gw({...e,...t},e.machine)}function Aq(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 Pq(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:fw(s),children:f,historyValue:Aq(p.historyValue)}}function fw(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:zu,id:o.id};else{let i=fw(o);if(i!==o)t??=Array.isArray(e)?e.slice():{...e},t[n]=i}}return t??e}function Mq(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 jq(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 hw(e,t){if(Oq.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=Mq,n.execute=jq,n}Oq.$$ACTOR_TYPE=zu;Oq.Actor=qu;Oq.NULL_EVENT=BS;Oq.ProcessingStatus=Wt;Oq.STATE_DELIMITER=FS;Oq.XSTATE_ERROR=Mz;Oq.XSTATE_STOP=as;Oq.and=nw;Oq.cancel=ew;Oq.cloneMachineSnapshot=$n;Oq.createActor=$u;Oq.createErrorActorEvent=JS;Oq.createInitEvent=WS;Oq.createInvokeId=qz;Oq.createMachineSnapshot=gw;Oq.createSystem=XS;Oq.evaluateGuard=Co;Oq.formatInitialTransition=sq;Oq.formatRouteTransitions=aq;Oq.formatTransition=fn;Oq.formatTransitions=iq;Oq.getAllOwnEventDescriptors=$z;Oq.getAllStateNodes=Lu;Oq.getCandidates=nq;Oq.getDelayedTransitions=oq;Oq.getPersistedSnapshot=Pq;Oq.getProperAncestors=ko;Oq.getStateNodeByPath=ss;Oq.getStateNodes=Fu;Oq.initialMicrostep=hq;Oq.interpret=Fz;Oq.isAtomicStateNode=cs;Oq.isInFinalState=Uu;Oq.isMachineSnapshot=mw;Oq.isStateId=Bi;Oq.macrostep=wq;Oq.mapValues=Dz;Oq.matchesEventDescriptor=QS;Oq.matchesState=Nu;Oq.not=Xz;Oq.or=rq;Oq.pathToStateValue=HS;Oq.raise=hw;Oq.resolveActionsAndContext=Io;Oq.resolveReferencedActor=YS;Oq.resolveStateValue=Tq;Oq.spawnChild=tw;Oq.stateIn=Yz;Oq.stop=Zz;Oq.stopChild=ls;Oq.toArray=Fi;Oq.toObserver=Li;Oq.toStatePath=Du;Oq.toTransitionConfigArray=So;Oq.transitionNode=Bu});var ww=ye(function(Sw){Object.defineProperty(Sw,"__esModule",{value:!0});var Ji=Ro();is();function _w(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 Ju=new WeakMap;function D$(e){return{config:e,start:(n,o)=>{let{self:i,system:a,emit:s}=o,l={receivers:void 0,dispose:void 0};Ju.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=Ju.get(i.self);if(o.type===Ji.XSTATE_STOP)return n={...n,status:"stopped",error:void 0},Ju.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 yw="xstate.observable.next",us="xstate.observable.error",ds="xstate.observable.complete";function z$(e){return{config:e,transition:(n,o)=>{if(n.status!=="active")return n;switch(o.type){case yw: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 Ji.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:yw,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 q$(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 Ji.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 vw="xstate.promise.resolve",bw="xstate.promise.reject",Gi=new WeakMap;function $$(e){return{config:e,transition:(n,o,i)=>{if(n.status!=="active")return n;switch(o.type){case vw:{let a=o.data;return{...n,status:"done",output:a,input:void 0}}case bw:return{...n,status:"error",error:o.data,input:void 0};case Ji.XSTATE_STOP:return Gi.get(i.self)?.abort(),Gi.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;Gi.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;Gi.delete(o),i._relay(o,o,{type:vw,data:c})},(c)=>{if(o.getSnapshot().status!=="active")return;Gi.delete(o),i._relay(o,o,{type:bw,data:c})})},getInitialSnapshot:(n,o)=>({status:"active",output:void 0,error:void 0,input:o}),getPersistedSnapshot:(n)=>n,restoreSnapshot:(n)=>n}}var L$=_w((e)=>{return},void 0);function U$(){return Ji.createActor(L$)}Sw.createEmptyActor=U$;Sw.fromCallback=D$;Sw.fromEventObservable=q$;Sw.fromObservable=z$;Sw.fromPromise=$$;Sw.fromTransition=_w});var ps=ye(function(Y$){var Eo=Ro();function V$(e,{machine:t,context:n},o,i){let a=(s,l)=>{if(typeof s==="string"){let c=Eo.resolveReferencedActor(t,s);if(!c)throw Error(`Actor logic '${s}' not implemented in machine '${t.id}'`);let u=Eo.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 Eo.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===Eo.ProcessingStatus.Stopped)return;c.start()}),c}}function Z$(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:V$(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[Eo.cloneMachineSnapshot(t,{context:c,children:Object.keys(a).length?{...t.children,...a}:t.children}),void 0,void 0]}function K$(e){if(Eo.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=Z$,t}Y$.assign=K$});var Tw=ye(function(rL){var je=Ro(),X$=ps(),xw=new WeakMap;function Ao(e,t,n){let o=xw.get(e);if(!o)o={[t]:n()},xw.set(e,o);else if(!(t in o))o[t]=n();return o[t]}var eL={},Wi=(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 Hi{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 Hi(n,{_parent:this,_key:o,_machine:this.machine})):eL,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(Wi),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map((e)=>`#${e.id}`),source:`#${this.id}`,actions:this.initial.actions.map(Wi),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(Wi)})),entry:this.entry.map(Wi),exit:this.exit.map(Wi),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 Ao(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 Ao(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 Ao(this,"delayedTransitions",()=>je.getDelayedTransitions(this))}get initial(){return Ao(this,"initial",()=>je.formatInitialTransition(this,this.config.initial))}next(e,t){let n=t.type,o=[],i,a=Ao(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 Ao(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 tL="#";class Wu{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 Hi(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 Wu(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,[X$.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(tL.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 Hi)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}}rL.StateMachine=Wu;rL.StateNode=Hi});var kw=ye(function(yL){var Yr=Ro(),iL=ps();function aL(e,t,n,o,{event:i}){let a=typeof i==="function"?i(n,o):i;return[t,{event:a},void 0]}function sL(e,{event:t}){e.defer(()=>e.emit(t))}function Iw(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=aL,t.execute=sL,t}var ms=function(e){return e.Parent="#_parent",e.Internal="#_internal",e}({});function lL(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 cL(e,t,n){if(typeof n.to==="string")n.to=t.children[n.to]}function uL(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=lL,o.retryResolve=cL,o.execute=uL,o}function Cw(e,t){return gs(ms.Parent,e,t)}function dL(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 pL(e,t,n,o,{collect:i}){let a=[],s=function(c){a.push(c)};return s.assign=(...l)=>{a.push(iL.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(Cw(...l))},s.spawnChild=(...l)=>{a.push(Yr.spawnChild(...l))},s.stopChild=(...l)=>{a.push(Yr.stopChild(...l))},s.emit=(...l)=>{a.push(Iw(...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 mL(e){function t(n,o){throw Error("This isn't supposed to be called")}return t.type="xstate.enqueueActions",t.collect=e,t.resolve=pL,t}function gL(e,t,n,o,{value:i,label:a}){return[t,{value:typeof i==="function"?i(n,o):i,label:a},void 0]}function fL({logger:e},{value:t,label:n}){if(n)e(n,t);else e(t)}function hL(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=gL,n.execute=fL,n}yL.SpecialTargets=ms;yL.emit=Iw;yL.enqueueActions=mL;yL.forwardTo=dL;yL.log=hL;yL.sendParent=Cw;yL.sendTo=gs});var jw=ye(function(Mw){Object.defineProperty(Mw,"__esModule",{value:!0});var Po=ww(),We=Ro(),Hu=Tw(),Rw=ps(),hr=kw();is();function IL(e,t){let n=We.toArray(t);if(!n.some((i)=>We.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 Ew(e,t){return new Hu.StateMachine(e,t)}function CL(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(We.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 Mo(e){let t=We.createActor(e),n=We.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 kL(e,...[t]){let n=Mo(e);return e.getInitialSnapshot(n,t)}function RL(e,t,n){let o=Mo(e);return o.self._snapshot=t,e.transition(t,n,o)}function Aw({schemas:e,actors:t,actions:n,guards:o,delays:i}){return{assign:Rw.assign,sendTo:hr.sendTo,raise:We.raise,log:hr.log,cancel:We.cancel,stopChild:We.stopChild,enqueueActions:hr.enqueueActions,emit:hr.emit,spawnChild:We.spawnChild,createStateConfig:(a)=>a,createAction:(a)=>a,createMachine:(a)=>Ew({...a,schemas:e},{actors:t,actions:n,guards:o,delays:i}),extend:(a)=>Aw({schemas:e,actors:t,actions:{...n,...a.actions},guards:{...o,...a.guards},delays:{...i,...a.delays}})}}class Pw{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 EL(e){return new Promise((t,n)=>{e.subscribe({complete:()=>{t(e.getSnapshot().output)},error:n})})}function AL(e,t,n){let o=[],i=Mo(e);return i.actionExecutor=(s)=>{o.push(s)},[e.transition(t,n,i),o]}function PL(e,...[t]){let n=[],o=Mo(e);return o.actionExecutor=(a)=>{n.push(a)},[e.getInitialSnapshot(o,t),n]}function ML(e,t,n){let o=Mo(e),{microsteps:i}=We.macrostep(t,n,o,[]);return i}function jL(e,...[t]){let n=Mo(e),o=We.createInitEvent(t),i=[],a=e._getPreInitialState(n,o,i),s=We.initialMicrostep(e.root,a,n,o,i),{microsteps:l}=We.macrostep(s[0],o,n,i);return[s,...l]}function OL(e){let t=[],n=e._nodes.filter(We.isAtomicStateNode),o=new Set;for(let i of n)for(let a of[i].concat(We.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 NL={timeout:1/0};function DL(e,t,n){let o={...NL,...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()})}Mw.createEmptyActor=Po.createEmptyActor;Mw.fromCallback=Po.fromCallback;Mw.fromEventObservable=Po.fromEventObservable;Mw.fromObservable=Po.fromObservable;Mw.fromPromise=Po.fromPromise;Mw.fromTransition=Po.fromTransition;Mw.Actor=We.Actor;Mw.__unsafe_getAllOwnEventDescriptors=We.getAllOwnEventDescriptors;Mw.and=We.and;Mw.cancel=We.cancel;Mw.createActor=We.createActor;Mw.getStateNodes=We.getStateNodes;Mw.interpret=We.interpret;Mw.isMachineSnapshot=We.isMachineSnapshot;Mw.matchesState=We.matchesState;Mw.not=We.not;Mw.or=We.or;Mw.pathToStateValue=We.pathToStateValue;Mw.raise=We.raise;Mw.spawnChild=We.spawnChild;Mw.stateIn=We.stateIn;Mw.stop=We.stop;Mw.stopChild=We.stopChild;Mw.toObserver=We.toObserver;Mw.StateMachine=Hu.StateMachine;Mw.StateNode=Hu.StateNode;Mw.assign=Rw.assign;Mw.SpecialTargets=hr.SpecialTargets;Mw.emit=hr.emit;Mw.enqueueActions=hr.enqueueActions;Mw.forwardTo=hr.forwardTo;Mw.log=hr.log;Mw.sendParent=hr.sendParent;Mw.sendTo=hr.sendTo;Mw.SimulatedClock=Pw;Mw.assertEvent=IL;Mw.createMachine=Ew;Mw.getInitialMicrosteps=jL;Mw.getInitialSnapshot=kL;Mw.getMicrosteps=ML;Mw.getNextSnapshot=RL;Mw.getNextTransitions=OL;Mw.initialTransition=PL;Mw.mapState=CL;Mw.setup=Aw;Mw.toPromise=EL;Mw.transition=AL;Mw.waitFor=DL});function tl(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 Vo(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=tl(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 fp(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:Vo(u,n.jobQueueService.getExecutionRegistrations()),ai:{model:t.ai.model,embeddingModel:"text-embedding-3-small"},daemons:c,endpoints:i(),interactions:a()}}import{readdir as hp,readFile as XC}from"fs/promises";var e0=10;async function t0(e="/proc"){let t=null;try{t=(await hp(`${e}/self/fd`)).length}catch{}try{let o=(await hp(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 XC(`${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 yp(e,t,n){return t.status==="fulfilled"?{name:e,status:"healthy",message:n}:{name:e,status:"unhealthy",message:Re(t.reason)}}function r0(e){if(!e)return{name:"job-worker",status:"degraded",message:"Worker session state is unavailable"};let t=e.workerSessions,n=Vo(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 n0(e){if(!e)return{name:"job-queue-progress",status:"degraded",message:"Queue progress state is unavailable"};let t=Vo(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 o0(e,t){if(!e||!t)return{name:"job-execution-inventory",status:"degraded",message:"Job execution inventory is unavailable"};let n=tl(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 i0(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 a0(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 s0(e){let t=e.entityService.getProjectionStore(),[n,o,i]=await Promise.all([t.getActiveWave(),t.getUnresolvedProjectionIncidentDiagnostics(e0),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 l0(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 c0(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 vp(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??t0)(),e.projectionRuntimeSupervisor.getDiagnostics(),s0(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=[yp("entity-database",o,"Entity database is accessible"),yp("job-queue-database",i,"Job queue database is accessible"),r0(m),n0(m),o0(m,p),i0(m),c.status==="fulfilled"?a0(h):{name:"projection-circuits",status:"degraded",message:Re(c.reason)},u.status==="fulfilled"?l0(u.value):{name:"projection-waves",status:"degraded",message:Re(u.reason)},s.status==="fulfilled"?c0(f):{name:"daemons",status:"degraded",message:Re(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 bp(){return{dataDir:"./data",cacheDir:"./cache",distDir:"./dist"}}function Tn(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 rl=bp(),u0=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 nl(){return Tn(rl)}var Kn=r.enum(["debug","info","warn","error"]),Yn=r.enum(["none","low","medium","high","xhigh","max"]),ol=r.object({name:r.string().default("brain-app"),version:r.string().default("1.0.0"),database:Zn,jobQueueDatabase:Zn,jobQueue:r.object({workerConcurrency:r.number().int().min(1).max(32).default(4)}).prefault({}),conversationDatabase:Zn,runtimeStateDatabase:Zn,embeddingDatabase:Zn,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:Yn.optional()}),embedding:r.object({enabled:r.boolean().default(!0)}),logging:r.object({level:Kn.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(),u0).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}=ol.parse({...nl(),...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"},Zo={KNOWLEDGE_QUERY:"shell:knowledge-query",BASE_ENTITY_DISPLAY:"shell:base-entity-display",CONTENT_GENERATION:"shell:content-generation"},il={ENTITIES:"shell:entities"};var d0=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()}),p0=r.object({slug:r.string()});function m0(e){return e instanceof r.ZodType}function g0(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=g0(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=d0.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 _p((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(!m0(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(`
|
|
5
|
+
- ${i}: ${a.toString().replace(/\n\s*/g,"")}`).join("")}`);return e}function ZS(e){return Array.isArray(e)}function zz(e){return e.type.startsWith("xstate.error.actor")}function So(e){return VS(e).map((t)=>{if(typeof t>"u"||typeof t==="string")return{target:t};return t})}function KS(e){if(e===void 0||e===Az)return;return Fi(e)}function Li(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 $z(e,t){return`${t}.${e}`}function YS(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 qz(e){return[...new Set([...e._nodes.flatMap((t)=>t.ownEvents)])]}function QS(e,t){if(t===e)return!0;if(t===Au)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 $S(e,t){return`${e.sessionId}.${t}`}var Lz=0;function XS(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=$S(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=$S(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:${Lz++}`,_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=Li(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}O$.executingCustomAction=!1;var zu=1,Wt=function(e){return e[e.NotStarted=0]="NotStarted",e[e.Running=1]="Running",e[e.Stopped=2]="Stopped",e}({}),Uz={clock:{setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:(e)=>clearTimeout(e)},logger:console.log.bind(console),devTools:!1};class $u{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 Eu(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=Wt.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={...Uz,...t},{clock:o,logger:i,parent:a,syncSnapshot:s,id:l,systemId:c,inspect:u}=n;if(this.system=a?a.system:XS(this,{clock:o,logger:i}),u&&!a)this.system.inspect(Li(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=O$.executingCustomAction;try{O$.executingCustomAction=!0,d.exec(d.info,d.params)}finally{O$.executingCustomAction=p}};if(this._processingStatus===Wt.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=Oz(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=Li(e,t,n);if(this._processingStatus!==Wt.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=Li(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===Wt.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=Wt.Running;let e=WS(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===Wt.Stopped)return this;if(this.mailbox.clear(),this._processingStatus===Wt.NotStarted)return this._processingStatus=Wt.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,JS(this.id,e))}_stopProcedure(){if(this._processingStatus!==Wt.Running)return this;return this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new Eu(this._process.bind(this)),this._processingStatus=Wt.Stopped,this.system._unregister(this),this}_send(e){if(this._processingStatus===Wt.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:Ez.devToolsAdapter)(this)}toJSON(){return{xstate$$type:zu,id:this.id}}getPersistedSnapshot(e){return this.logic.getPersistedSnapshot(this._snapshot,e)}[Nz](){return this}getSnapshot(){if(!this._snapshot)throw Error("Snapshot can't be read while the actor initializes itself");return this._snapshot}}function qu(e,...[t]){return new $u(e,t)}var Fz=qu;function Bz(e,t,n,o,{sendId:i}){let a=typeof i==="function"?i(n,o):i;return[t,{sendId:a},void 0]}function Gz(e,t){e.defer(()=>{e.system.scheduler.cancel(e.self,t.sendId)})}function ew(e){function t(n,o){throw Error("This isn't supposed to be called")}return t.type="xstate.cancel",t.sendId=e,t.resolve=Bz,t.execute=Gz,t}function Jz(e,t,n,o,{id:i,systemId:a,src:s,input:l,syncSnapshot:c}){let u=typeof s==="string"?YS(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=qu(u,{id:d,src:s,parent:e.self,syncSnapshot:c,systemId:a,input:p});if(!m)console.warn(`Actor type '${s}' not found in machine '${e.id}'.`);return[qn(t,{children:{...t.children,[d]:m}}),{id:i,systemId:a,actorRef:m,src:s,input:p},void 0]}function Wz(e,{actorRef:t}){if(!t)return;e.defer(()=>{if(t._processingStatus===Wt.Stopped)return;t.start()})}function tw(...[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=Jz,a.execute=Wz,a}function Hz(e,t,n,o,{actorRef:i}){let a=typeof i==="function"?i(n,o):i,s=typeof a==="string"?t.children[a]:a,l=t.children;if(s)l={...l},delete l[s.id];return[qn(t,{children:l}),s,void 0]}function rw(e,t){let n=t.getSnapshot();if(n&&"children"in n)for(let o of Object.values(n.children))rw(e,o);e.system._unregister(t)}function Vz(e,t){if(!t)return;if(rw(e,t),t._processingStatus!==Wt.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=Hz,t.execute=Vz,t}var Zz=ls;function Kz(e,t,{stateValue:n}){if(typeof n==="string"&&Bi(n)){let o=e.machine.getStateNodeById(n);return e._nodes.some((i)=>i===o)}return e.matches(n)}function Yz(e){function t(){throw Error("This isn't supposed to be called")}return t.check=Kz,t.stateValue=e,t}function Qz(e,{context:t,event:n},{guards:o}){return!Co(o[0],t,n,e)}function Xz(e){function t(n,o){throw Error("This isn't supposed to be called")}return t.check=Qz,t.guards=[e],t}function e$(e,{context:t,event:n},{guards:o}){return o.every((i)=>Co(i,t,n,e))}function nw(e){function t(n,o){throw Error("This isn't supposed to be called")}return t.check=e$,t.guards=e,t}function t$(e,{context:t,event:n},{guards:o}){return o.some((i)=>Co(i,t,n,e))}function r$(e){function t(n,o){throw Error("This isn't supposed to be called")}return t.check=t$,t.guards=e,t}function Co(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 Co(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 xo(e){return Object.values(e.states).filter((t)=>t.type!=="history")}function ko(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 Lu(e){let t=new Set(e),n=iw(t);for(let o of t)if(o.type==="compound"&&(!n.get(o)||!n.get(o).length))qS(o).forEach((i)=>t.add(i));else if(o.type==="parallel")for(let i of xo(o)){if(i.type==="history")continue;if(!t.has(i)){let a=qS(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 ow(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]=ow(i,t);return o}function iw(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 aw(e,t){let n=Lu(t);return ow(e,iw(n))}function Uu(e,t){if(t.type==="compound")return xo(t).some((n)=>n.type==="final"&&e.has(n));if(t.type==="parallel")return xo(t).every((n)=>Uu(e,n));return t.type==="final"}var Bi=(e)=>e[0]===Pz;function n$(e,t){let n=e.transitions.get(t),o=[...e.transitions.keys()].filter((i)=>i!==t&&QS(t,i)).sort((i,a)=>a.length-i.length).flatMap((i)=>e.transitions.get(i));return n?[...n,...o]:o}function o$(e){let t=e.config.after;if(!t)return[];let n=(i)=>{let a=jz(i,e.id),s=a.type;return e.entry.push(hw(a,{id:s,delay:i})),e.exit.push(ew(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 Fi(s).map((u)=>({...u,event:c,delay:l}))}).map((i)=>{let{delay:a}=i;return{...fn(e,i.event,i),delay:a}})}function fn(e,t,n){let o=KS(n.target),i=n.reenter??!1,a=l$(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:Fi(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 i$(e){let t=new Map;if(e.config.on)for(let n of Object.keys(e.config.on)){if(n===BS)throw Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');let o=e.config.on[n];t.set(n,So(o).map((i)=>fn(e,n,i)))}if(e.config.onDone){let n=`xstate.done.state.${e.id}`;t.set(n,So(e.config.onDone).map((o)=>fn(e,n,o)))}for(let n of e.invoke){if(n.onDone){let o=`xstate.done.actor.${n.id}`;t.set(o,So(n.onDone).map((i)=>fn(e,o,i)))}if(n.onError){let o=`xstate.error.actor.${n.id}`;t.set(o,So(n.onError).map((i)=>fn(e,o,i)))}if(n.onSnapshot){let o=`xstate.snapshot.${n.id}`;t.set(o,So(n.onSnapshot).map((i)=>fn(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 a$(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?nw([l,s]):l,target:`#${a}`};t.push(fn(e,"xstate.route",c))}if(i.states)n(i.states)})};if(n(e.states),t.length>0)e.transitions.set("xstate.route",t)}function s$(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"?[]:Fi(t.actions),eventType:null,reenter:!1,target:n?[n]:[],toJSON:()=>({...o,source:`#${e.id}`,target:n?[`#${n.id}`]:[]})};return o}function l$(e,t){if(t===void 0)return;return t.map((n)=>{if(typeof n!=="string")return n;if(Bi(n))return e.machine.getStateNodeById(n);let o=n[0]===FS;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 sw(e){let t=KS(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 $n(e){return e.type==="history"}function qS(e){let t=lw(e);for(let n of t)for(let o of ko(n,e))t.add(o);return t}function lw(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 xo(o))n(i)}return n(e),t}function To(e,t){if(Bi(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"&&Bi(t))try{return e.machine.getStateNodeById(t)}catch{}let n=Du(t).slice(),o=e;while(n.length){let i=n.shift();if(!i.length)break;o=To(o,i)}return o}function Fu(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)=>To(e,i)).filter(Boolean);return[e.machine.root,e].concat(o,n.reduce((i,a)=>{let s=To(e,a);if(!s)return i;let l=Fu(s,t[a]);return i.concat(l)},[]))}function c$(e,t,n,o){let a=To(e,t).next(n,o);if(!a||!a.length)return e.next(n,o);return a}function u$(e,t,n,o){let i=Object.keys(t),a=To(e,i[0]),s=Bu(a,t[i[0]],n,o);if(!s||!s.length)return e.next(n,o);return s}function d$(e,t,n,o){let i=[];for(let a of Object.keys(t)){let s=t[a];if(!s)continue;let l=To(e,a),c=Bu(l,s,n,o);if(c)i.push(...c)}if(!i.length)return e.next(n,o);return i}function Bu(e,t,n,o){if(typeof t==="string")return c$(e,t,n,o);if(Object.keys(t).length===1)return u$(e,t,n,o);return d$(e,t,n,o)}function p$(e){return Object.keys(e.states).map((t)=>e.states[t]).filter((t)=>t.type==="history")}function hn(e,t){let n=e;while(n.parent&&n.parent!==t)n=n.parent;return n.parent===t}function m$(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 cw(e,t,n){let o=new Set;for(let i of e){let a=!1,s=new Set;for(let l of o)if(m$(ju([i],t,n),ju([l],t,n)))if(hn(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 g$(e){let[t,...n]=e;for(let o of ko(t,void 0))if(n.every((i)=>hn(i,o)))return o}function Gu(e,t){if(!e.target)return[];let n=new Set;for(let o of e.target)if($n(o))if(t[o.id])for(let i of t[o.id])n.add(i);else for(let i of Gu(sw(o),t))n.add(i);else n.add(o);return[...n]}function uw(e,t){let n=Gu(e,t);if(!n)return;if(!e.reenter&&n.every((i)=>i===e.source||hn(i,e.source)))return e.source;let o=g$(n.concat(e.source));if(o)return o;if(e.reenter)return;return e.source.machine.root}function ju(e,t,n){let o=new Set;for(let i of e)if(i.target?.length){let a=uw(i,n);if(i.reenter&&i.source===a)o.add(a);for(let s of t)if(hn(s,a))o.add(s)}return[...o]}function f$(e,t){if(e.length!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function h$(e,t,n,o,i){return Ou([{target:[...lw(e)],source:e,reenter:!0,actions:[],eventType:null,toJSON:null}],t,n,o,!0,i)}function Ou(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=cw(e,c,u),m=t;if(!i)[m,u]=_$(m,o,n,d,c,u,a,n.actionExecutor);m=Io(m,o,n,d.flatMap((f)=>f.actions),a,void 0),m=v$(m,o,n,d,c,a,u,i);let p=[...c];if(m.status==="done")m=Io(m,o,n,p.sort((f,g)=>g.order-f.order).flatMap((f)=>f.exit),a,void 0);try{if(u===t.historyValue&&f$(t._nodes,c))return[m,s];return[qn(m,{_nodes:p,historyValue:u}),s]}catch(f){throw f}}finally{n.actionExecutor=l}}function y$(e,t,n,o,i){if(o.output===void 0)return;let a=Pu(i.id,i.output!==void 0&&i.parent?Mu(i.output,e.context,t,n.self):void 0);return Mu(o.output,e.context,a,n.self)}function v$(e,t,n,o,i,a,s,l){let c=e,u=new Set,d=new Set;if(b$(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(tw(g.src,{...g,syncSnapshot:!!g.onSnapshot}));if(d.has(p)){let g=p.initial.actions;f.push(...g)}if(c=Io(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(Pu(g.id,p.output!==void 0?Mu(p.output,c.context,t,n.self):void 0));while(h?.type==="parallel"&&!m.has(h)&&Uu(i,h))m.add(h),a.push(Pu(h.id)),v=h,h=h.parent;if(h)continue;c=qn(c,{status:"done",output:y$(c,t,n,c.machine.root,v)})}}return c}function b$(e,t,n,o){for(let i of e){let a=uw(i,t);for(let l of i.target||[]){if(!$n(l)&&(i.source!==l||i.source!==a||i.reenter))o.add(l),n.add(l);wo(l,t,n,o)}let s=Gu(i,t);for(let l of s){let c=ko(l,a);if(a?.type==="parallel")c.push(a);dw(o,t,n,c,!i.source.parent&&i.reenter?void 0:a)}}}function wo(e,t,n,o){if($n(e))if(t[e.id]){let i=t[e.id];for(let a of i)o.add(a),wo(a,t,n,o);for(let a of i)Ru(a,e.parent,o,t,n)}else{let i=sw(e);for(let a of i.target){if(o.add(a),i===e.parent?.initial)n.add(e.parent);wo(a,t,n,o)}for(let a of i.target)Ru(a,e.parent,o,t,n)}else if(e.type==="compound"){let[i]=e.initial.target;if(!$n(i))o.add(i),n.add(i);wo(i,t,n,o),Ru(i,e,o,t,n)}else if(e.type==="parallel"){for(let i of xo(e).filter((a)=>!$n(a)))if(![...o].some((a)=>hn(a,i))){if(!$n(i))o.add(i),n.add(i);wo(i,t,n,o)}}}function dw(e,t,n,o,i){for(let a of o){if(!i||hn(a,i))e.add(a);if(a.type==="parallel"){for(let s of xo(a).filter((l)=>!$n(l)))if(![...e].some((l)=>hn(l,s)))e.add(s),wo(s,t,n,e)}}}function Ru(e,t,n,o,i){dw(n,o,i,ko(e,t))}function _$(e,t,n,o,i,a,s,l){let c=e,u=ju(o,i,a);u.sort((m,p)=>p.order-m.order);let d;for(let m of u)for(let p of p$(m)){let f;if(p.history==="deep")f=(g)=>cs(g)&&hn(g,m);else f=(g)=>g.parent===m;d??={...a},d[p.id]=Array.from(i).filter(f)}for(let m of u)c=Io(c,t,n,[...m.exit,...m.invoke.map((p)=>ls(p.id))],s,void 0),i.delete(m);return[c,d||a]}function S$(e,t){return e.implementations.actions[t]}function pw(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:S$(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=pw(l,t,n,v,i,a)}return l}function Io(e,t,n,o,i,a){let s=a?[]:void 0,l=pw(e,t,n,o,{internalQueue:i,deferredActorIds:a},s);return s?.forEach(([c,u])=>{c.retryResolve(n,l,u)}),l}function w$(e,t,n,o){if(t.type===Au)throw Error(`An event cannot have the wildcard type ('${Au}')`);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=qn(LS(i,t,n),{status:"stopped"}),s([i,[]],t,[]),{snapshot:i,microsteps:a};let l=t;if(l.type!==GS){let m=l,p=zz(m),f=US(m,i);if(p&&!f.length)return i=qn(e,{status:"error",error:m.error}),s([i,[]],m,[]),{snapshot:i,microsteps:a};let g=Ou(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?x$(i,l):[],p=m.length?i:void 0;if(!m.length){if(!o.length)break;l=o.shift(),m=US(l,i)}let f=Ou(m,i,n,l,!1,o);i=f[0],c=i!==p,s(f,l,m)}if(i.status!=="active")LS(i,l,n);return{snapshot:i,microsteps:a}}function LS(e,t,n){return Io(e,t,n,Object.values(e.children).map((o)=>ls(o)),[],void 0)}function US(e,t){return t.machine.getTransitionData(t,e)}function x$(e,t){let n=new Set,o=e._nodes.filter(cs);for(let i of o)e:for(let a of[i].concat(ko(i,void 0))){if(!a.always)continue;for(let s of a.always)if(s.guard===void 0||Co(s.guard,e.context,t,e)){n.add(s);break e}}return cw(Array.from(n),new Set(e._nodes),e.historyValue)}function T$(e,t){let n=Lu(Fu(e,t));return aw(e,[...n])}function mw(e){return!!e&&typeof e==="object"&&"machine"in e&&"value"in e}var I$=function(t){return Nu(t,this.value)},C$=function(t){return this.tags.has(t)},k$=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)},R$=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)}},E$=function(){return this._nodes.reduce((t,n)=>{if(n.meta!==void 0)t[n.id]=n.meta;return t},{})};function gw(e,t){return{status:e.status,output:e.output,error:e.error,machine:t,context:e.context,_nodes:e._nodes,value:aw(t.root,e._nodes),tags:new Set(e._nodes.flatMap((n)=>n.tags)),children:e.children,historyValue:e.historyValue||{},matches:I$,hasTag:C$,can:k$,getMeta:E$,toJSON:R$}}function qn(e,t={}){return gw({...e,...t},e.machine)}function A$(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 P$(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:fw(s),children:f,historyValue:A$(p.historyValue)}}function fw(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:zu,id:o.id};else{let i=fw(o);if(i!==o)t??=Array.isArray(e)?e.slice():{...e},t[n]=i}}return t??e}function M$(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 j$(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 hw(e,t){if(O$.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=M$,n.execute=j$,n}O$.$$ACTOR_TYPE=zu;O$.Actor=$u;O$.NULL_EVENT=BS;O$.ProcessingStatus=Wt;O$.STATE_DELIMITER=FS;O$.XSTATE_ERROR=Mz;O$.XSTATE_STOP=as;O$.and=nw;O$.cancel=ew;O$.cloneMachineSnapshot=qn;O$.createActor=qu;O$.createErrorActorEvent=JS;O$.createInitEvent=WS;O$.createInvokeId=$z;O$.createMachineSnapshot=gw;O$.createSystem=XS;O$.evaluateGuard=Co;O$.formatInitialTransition=s$;O$.formatRouteTransitions=a$;O$.formatTransition=fn;O$.formatTransitions=i$;O$.getAllOwnEventDescriptors=qz;O$.getAllStateNodes=Lu;O$.getCandidates=n$;O$.getDelayedTransitions=o$;O$.getPersistedSnapshot=P$;O$.getProperAncestors=ko;O$.getStateNodeByPath=ss;O$.getStateNodes=Fu;O$.initialMicrostep=h$;O$.interpret=Fz;O$.isAtomicStateNode=cs;O$.isInFinalState=Uu;O$.isMachineSnapshot=mw;O$.isStateId=Bi;O$.macrostep=w$;O$.mapValues=Dz;O$.matchesEventDescriptor=QS;O$.matchesState=Nu;O$.not=Xz;O$.or=r$;O$.pathToStateValue=HS;O$.raise=hw;O$.resolveActionsAndContext=Io;O$.resolveReferencedActor=YS;O$.resolveStateValue=T$;O$.spawnChild=tw;O$.stateIn=Yz;O$.stop=Zz;O$.stopChild=ls;O$.toArray=Fi;O$.toObserver=Li;O$.toStatePath=Du;O$.toTransitionConfigArray=So;O$.transitionNode=Bu});var ww=ye(function(Sw){Object.defineProperty(Sw,"__esModule",{value:!0});var Ji=Ro();is();function _w(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 Ju=new WeakMap;function Dq(e){return{config:e,start:(n,o)=>{let{self:i,system:a,emit:s}=o,l={receivers:void 0,dispose:void 0};Ju.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=Ju.get(i.self);if(o.type===Ji.XSTATE_STOP)return n={...n,status:"stopped",error:void 0},Ju.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 yw="xstate.observable.next",us="xstate.observable.error",ds="xstate.observable.complete";function zq(e){return{config:e,transition:(n,o)=>{if(n.status!=="active")return n;switch(o.type){case yw: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 Ji.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:yw,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 $q(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 Ji.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 vw="xstate.promise.resolve",bw="xstate.promise.reject",Gi=new WeakMap;function qq(e){return{config:e,transition:(n,o,i)=>{if(n.status!=="active")return n;switch(o.type){case vw:{let a=o.data;return{...n,status:"done",output:a,input:void 0}}case bw:return{...n,status:"error",error:o.data,input:void 0};case Ji.XSTATE_STOP:return Gi.get(i.self)?.abort(),Gi.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;Gi.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;Gi.delete(o),i._relay(o,o,{type:vw,data:c})},(c)=>{if(o.getSnapshot().status!=="active")return;Gi.delete(o),i._relay(o,o,{type:bw,data:c})})},getInitialSnapshot:(n,o)=>({status:"active",output:void 0,error:void 0,input:o}),getPersistedSnapshot:(n)=>n,restoreSnapshot:(n)=>n}}var Lq=_w((e)=>{return},void 0);function Uq(){return Ji.createActor(Lq)}Sw.createEmptyActor=Uq;Sw.fromCallback=Dq;Sw.fromEventObservable=$q;Sw.fromObservable=zq;Sw.fromPromise=qq;Sw.fromTransition=_w});var ps=ye(function(Yq){var Eo=Ro();function Vq(e,{machine:t,context:n},o,i){let a=(s,l)=>{if(typeof s==="string"){let c=Eo.resolveReferencedActor(t,s);if(!c)throw Error(`Actor logic '${s}' not implemented in machine '${t.id}'`);let u=Eo.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 Eo.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===Eo.ProcessingStatus.Stopped)return;c.start()}),c}}function Zq(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:Vq(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[Eo.cloneMachineSnapshot(t,{context:c,children:Object.keys(a).length?{...t.children,...a}:t.children}),void 0,void 0]}function Kq(e){if(Eo.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=Zq,t}Yq.assign=Kq});var Tw=ye(function(rL){var je=Ro(),Xq=ps(),xw=new WeakMap;function Ao(e,t,n){let o=xw.get(e);if(!o)o={[t]:n()},xw.set(e,o);else if(!(t in o))o[t]=n();return o[t]}var eL={},Wi=(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 Hi{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 Hi(n,{_parent:this,_key:o,_machine:this.machine})):eL,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(Wi),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map((e)=>`#${e.id}`),source:`#${this.id}`,actions:this.initial.actions.map(Wi),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(Wi)})),entry:this.entry.map(Wi),exit:this.exit.map(Wi),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 Ao(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 Ao(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 Ao(this,"delayedTransitions",()=>je.getDelayedTransitions(this))}get initial(){return Ao(this,"initial",()=>je.formatInitialTransition(this,this.config.initial))}next(e,t){let n=t.type,o=[],i,a=Ao(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 Ao(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 tL="#";class Wu{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 Hi(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 Wu(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,[Xq.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(tL.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 Hi)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}}rL.StateMachine=Wu;rL.StateNode=Hi});var kw=ye(function(yL){var Yr=Ro(),iL=ps();function aL(e,t,n,o,{event:i}){let a=typeof i==="function"?i(n,o):i;return[t,{event:a},void 0]}function sL(e,{event:t}){e.defer(()=>e.emit(t))}function Iw(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=aL,t.execute=sL,t}var ms=function(e){return e.Parent="#_parent",e.Internal="#_internal",e}({});function lL(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 cL(e,t,n){if(typeof n.to==="string")n.to=t.children[n.to]}function uL(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=lL,o.retryResolve=cL,o.execute=uL,o}function Cw(e,t){return gs(ms.Parent,e,t)}function dL(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 pL(e,t,n,o,{collect:i}){let a=[],s=function(c){a.push(c)};return s.assign=(...l)=>{a.push(iL.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(Cw(...l))},s.spawnChild=(...l)=>{a.push(Yr.spawnChild(...l))},s.stopChild=(...l)=>{a.push(Yr.stopChild(...l))},s.emit=(...l)=>{a.push(Iw(...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 mL(e){function t(n,o){throw Error("This isn't supposed to be called")}return t.type="xstate.enqueueActions",t.collect=e,t.resolve=pL,t}function gL(e,t,n,o,{value:i,label:a}){return[t,{value:typeof i==="function"?i(n,o):i,label:a},void 0]}function fL({logger:e},{value:t,label:n}){if(n)e(n,t);else e(t)}function hL(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=gL,n.execute=fL,n}yL.SpecialTargets=ms;yL.emit=Iw;yL.enqueueActions=mL;yL.forwardTo=dL;yL.log=hL;yL.sendParent=Cw;yL.sendTo=gs});var jw=ye(function(Mw){Object.defineProperty(Mw,"__esModule",{value:!0});var Po=ww(),We=Ro(),Hu=Tw(),Rw=ps(),hr=kw();is();function IL(e,t){let n=We.toArray(t);if(!n.some((i)=>We.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 Ew(e,t){return new Hu.StateMachine(e,t)}function CL(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(We.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 Mo(e){let t=We.createActor(e),n=We.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 kL(e,...[t]){let n=Mo(e);return e.getInitialSnapshot(n,t)}function RL(e,t,n){let o=Mo(e);return o.self._snapshot=t,e.transition(t,n,o)}function Aw({schemas:e,actors:t,actions:n,guards:o,delays:i}){return{assign:Rw.assign,sendTo:hr.sendTo,raise:We.raise,log:hr.log,cancel:We.cancel,stopChild:We.stopChild,enqueueActions:hr.enqueueActions,emit:hr.emit,spawnChild:We.spawnChild,createStateConfig:(a)=>a,createAction:(a)=>a,createMachine:(a)=>Ew({...a,schemas:e},{actors:t,actions:n,guards:o,delays:i}),extend:(a)=>Aw({schemas:e,actors:t,actions:{...n,...a.actions},guards:{...o,...a.guards},delays:{...i,...a.delays}})}}class Pw{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 EL(e){return new Promise((t,n)=>{e.subscribe({complete:()=>{t(e.getSnapshot().output)},error:n})})}function AL(e,t,n){let o=[],i=Mo(e);return i.actionExecutor=(s)=>{o.push(s)},[e.transition(t,n,i),o]}function PL(e,...[t]){let n=[],o=Mo(e);return o.actionExecutor=(a)=>{n.push(a)},[e.getInitialSnapshot(o,t),n]}function ML(e,t,n){let o=Mo(e),{microsteps:i}=We.macrostep(t,n,o,[]);return i}function jL(e,...[t]){let n=Mo(e),o=We.createInitEvent(t),i=[],a=e._getPreInitialState(n,o,i),s=We.initialMicrostep(e.root,a,n,o,i),{microsteps:l}=We.macrostep(s[0],o,n,i);return[s,...l]}function OL(e){let t=[],n=e._nodes.filter(We.isAtomicStateNode),o=new Set;for(let i of n)for(let a of[i].concat(We.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 NL={timeout:1/0};function DL(e,t,n){let o={...NL,...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()})}Mw.createEmptyActor=Po.createEmptyActor;Mw.fromCallback=Po.fromCallback;Mw.fromEventObservable=Po.fromEventObservable;Mw.fromObservable=Po.fromObservable;Mw.fromPromise=Po.fromPromise;Mw.fromTransition=Po.fromTransition;Mw.Actor=We.Actor;Mw.__unsafe_getAllOwnEventDescriptors=We.getAllOwnEventDescriptors;Mw.and=We.and;Mw.cancel=We.cancel;Mw.createActor=We.createActor;Mw.getStateNodes=We.getStateNodes;Mw.interpret=We.interpret;Mw.isMachineSnapshot=We.isMachineSnapshot;Mw.matchesState=We.matchesState;Mw.not=We.not;Mw.or=We.or;Mw.pathToStateValue=We.pathToStateValue;Mw.raise=We.raise;Mw.spawnChild=We.spawnChild;Mw.stateIn=We.stateIn;Mw.stop=We.stop;Mw.stopChild=We.stopChild;Mw.toObserver=We.toObserver;Mw.StateMachine=Hu.StateMachine;Mw.StateNode=Hu.StateNode;Mw.assign=Rw.assign;Mw.SpecialTargets=hr.SpecialTargets;Mw.emit=hr.emit;Mw.enqueueActions=hr.enqueueActions;Mw.forwardTo=hr.forwardTo;Mw.log=hr.log;Mw.sendParent=hr.sendParent;Mw.sendTo=hr.sendTo;Mw.SimulatedClock=Pw;Mw.assertEvent=IL;Mw.createMachine=Ew;Mw.getInitialMicrosteps=jL;Mw.getInitialSnapshot=kL;Mw.getMicrosteps=ML;Mw.getNextSnapshot=RL;Mw.getNextTransitions=OL;Mw.initialTransition=PL;Mw.mapState=CL;Mw.setup=Aw;Mw.toPromise=EL;Mw.transition=AL;Mw.waitFor=DL});function tl(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 Vo(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=tl(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 fp(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:Vo(u,n.jobQueueService.getExecutionRegistrations()),ai:{model:t.ai.model,embeddingModel:"text-embedding-3-small"},daemons:c,endpoints:i(),interactions:a()}}import{readdir as hp,readFile as XC}from"fs/promises";var e0=10;async function t0(e="/proc"){let t=null;try{t=(await hp(`${e}/self/fd`)).length}catch{}try{let o=(await hp(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 XC(`${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 yp(e,t,n){return t.status==="fulfilled"?{name:e,status:"healthy",message:n}:{name:e,status:"unhealthy",message:Re(t.reason)}}function r0(e){if(!e)return{name:"job-worker",status:"degraded",message:"Worker session state is unavailable"};let t=e.workerSessions,n=Vo(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 n0(e){if(!e)return{name:"job-queue-progress",status:"degraded",message:"Queue progress state is unavailable"};let t=Vo(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 o0(e,t){if(!e||!t)return{name:"job-execution-inventory",status:"degraded",message:"Job execution inventory is unavailable"};let n=tl(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 i0(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 a0(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 s0(e){let t=e.entityService.getProjectionStore(),[n,o,i]=await Promise.all([t.getActiveWave(),t.getUnresolvedProjectionIncidentDiagnostics(e0),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 l0(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 c0(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 vp(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??t0)(),e.projectionRuntimeSupervisor.getDiagnostics(),s0(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=[yp("entity-database",o,"Entity database is accessible"),yp("job-queue-database",i,"Job queue database is accessible"),r0(m),n0(m),o0(m,p),i0(m),c.status==="fulfilled"?a0(h):{name:"projection-circuits",status:"degraded",message:Re(c.reason)},u.status==="fulfilled"?l0(u.value):{name:"projection-waves",status:"degraded",message:Re(u.reason)},s.status==="fulfilled"?c0(f):{name:"daemons",status:"degraded",message:Re(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 bp(){return{dataDir:"./data",cacheDir:"./cache",distDir:"./dist"}}function Tn(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 rl=bp(),u0=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 nl(){return Tn(rl)}var Kn=r.enum(["debug","info","warn","error"]),Yn=r.enum(["none","low","medium","high","xhigh","max"]),ol=r.object({name:r.string().default("brain-app"),version:r.string().default("1.0.0"),database:Zn,jobQueueDatabase:Zn,jobQueue:r.object({workerConcurrency:r.number().int().min(1).max(32).default(4)}).prefault({}),conversationDatabase:Zn,runtimeStateDatabase:Zn,embeddingDatabase:Zn,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:Yn.optional()}),embedding:r.object({enabled:r.boolean().default(!0)}),logging:r.object({level:Kn.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(),u0).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}=ol.parse({...nl(),...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"},Zo={KNOWLEDGE_QUERY:"shell:knowledge-query",BASE_ENTITY_DISPLAY:"shell:base-entity-display",CONTENT_GENERATION:"shell:content-generation"},il={ENTITIES:"shell:entities"};var d0=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()}),p0=r.object({slug:r.string()});function m0(e){return e instanceof r.ZodType}function g0(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=g0(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=d0.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 _p((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(!m0(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
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
10
|
`)}async buildPrompt(e,t,n=[]){let o=e.basePrompt;if(t.conversationHistory)o+=`
|
|
11
11
|
|
|
@@ -20,8 +20,8 @@ Context data:
|
|
|
20
20
|
${JSON.stringify(t.data,null,2)}`;if(t.prompt)o+=`
|
|
21
21
|
|
|
22
22
|
Additional instructions: ${t.prompt}`;return o}formatRelevantEntity(e,t){let{entity:n,excerpt:o}=e,i=n.entityType,a=p0.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 f0=r.object({entityType:r.string(),query:r.object({id:r.string()})});class fa{entityService;id=il.ENTITIES;name="Entity DataSource";description="Fetches entity content from the entity service";constructor(e){this.entityService=e}async fetch(e,t,n){let o=f0.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 Sp(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 wp(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 Yp="vercel.ai.error",h0=Symbol.for(Yp),xp,Tp,ie=class e extends(Tp=Error,xp=h0,Tp){constructor({name:t,message:n,cause:o}){super(n);this[xp]=!0,this.name=t,this.cause=o}static isInstance(t){return e.hasMarker(t,Yp)}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}},Qp="AI_APICallError",Xp=`vercel.ai.error.${Qp}`,y0=Symbol.for(Xp),Ip,Cp,De=class extends(Cp=ie,Ip=y0,Cp){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:Qp,message:e,cause:s});this[Ip]=!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,Xp)}},em="AI_EmptyResponseBodyError",tm=`vercel.ai.error.${em}`,v0=Symbol.for(tm),kp,Rp,rm=class extends(Rp=ie,kp=v0,Rp){constructor({message:e="Empty response body"}={}){super({name:em,message:e});this[kp]=!0}static isInstance(e){return ie.hasMarker(e,tm)}};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 nm="AI_InvalidArgumentError",om=`vercel.ai.error.${nm}`,b0=Symbol.for(om),Ep,Ap,Qn=class extends(Ap=ie,Ep=b0,Ap){constructor({message:e,cause:t,argument:n}){super({name:nm,message:e,cause:t});this[Ep]=!0,this.argument=n}static isInstance(e){return ie.hasMarker(e,om)}},im="AI_InvalidPromptError",am=`vercel.ai.error.${im}`,_0=Symbol.for(am),Pp,Mp,Ir=class extends(Mp=ie,Pp=_0,Mp){constructor({prompt:e,message:t,cause:n}){super({name:im,message:`Invalid prompt: ${t}`,cause:n});this[Pp]=!0,this.prompt=e}static isInstance(e){return ie.hasMarker(e,am)}},sm="AI_InvalidResponseDataError",lm=`vercel.ai.error.${sm}`,S0=Symbol.for(lm),jp,Op,ya=class extends(Op=ie,jp=S0,Op){constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:sm,message:t});this[jp]=!0,this.data=e}static isInstance(e){return ie.hasMarker(e,lm)}},cm="AI_JSONParseError",um=`vercel.ai.error.${cm}`,w0=Symbol.for(um),Np,Dp,In=class extends(Dp=ie,Np=w0,Dp){constructor({text:e,cause:t}){super({name:cm,message:`JSON parsing failed: Text: ${e}.
|
|
23
|
-
Error message: ${Tr(t)}`,cause:t});this[Np]=!0,this.text=e}static isInstance(e){return ie.hasMarker(e,um)}},dm="AI_LoadAPIKeyError",pm=`vercel.ai.error.${dm}`,x0=Symbol.for(pm),zp,
|
|
24
|
-
Error message: ${Tr(n)}`,cause:n});this[Hp]=!0,this.value=t,this.context=o}static isInstance(t){return ie.hasMarker(t,wm)}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})}},xm="AI_UnsupportedFunctionalityError",Tm=`vercel.ai.error.${xm}`,E0=Symbol.for(Tm),Zp,Kp,He=class extends(Kp=ie,Zp=E0,Kp){constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:xm,message:t});this[Zp]=!0,this.functionality=e}static isInstance(e){return ie.hasMarker(e,Tm)}};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 sl(e){return Array.isArray(e)&&e.every(ha)}function Qo(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 Im;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Im||(Im={}));var ae=$e.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Lr=(e)=>{switch(typeof e){case"undefined":return ae.undefined;case"string":return ae.string;case"number":return Number.isNaN(e)?ae.nan:ae.number;case"boolean":return ae.boolean;case"function":return ae.function;case"bigint":return ae.bigint;case"symbol":return ae.symbol;case"object":if(Array.isArray(e))return ae.array;if(e===null)return ae.null;if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return ae.promise;if(typeof Map<"u"&&e instanceof Map)return ae.map;if(typeof Set<"u"&&e instanceof Set)return ae.set;if(typeof Date<"u"&&e instanceof Date)return ae.date;return ae.object;default:return ae.unknown}};var ne=$e.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Kt extends Error{get errors(){return this.issues}constructor(e){super();this.issues=[],this.addIssue=(n)=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,t);else this.__proto__=t;this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},n={_errors:[]},o=(i)=>{for(let a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)n._errors.push(t(a));else{let s=n,l=0;while(l<a.path.length){let c=a.path[l];if(l!==a.path.length-1)s[c]=s[c]||{_errors:[]};else s[c]=s[c]||{_errors:[]},s[c]._errors.push(t(a));s=s[c],l++}}};return o(this),n}static assert(e){if(!(e instanceof Kt))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,$e.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=(t)=>t.message){let t=Object.create(null),n=[];for(let o of this.issues)if(o.path.length>0){let i=o.path[0];t[i]=t[i]||[],t[i].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}Kt.create=(e)=>new Kt(e);var A0=(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}},un=A0;var P0=un;function Xo(){return P0}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=Xo(),o=ba({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===un?void 0:un].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"}),Xn=(e)=>({status:"dirty",value:e}),$t=(e)=>({status:"valid",value:e}),ll=(e)=>e.status==="aborted",cl=(e)=>e.status==="dirty",Cn=(e)=>e.status==="valid",ei=(e)=>typeof Promise<"u"&&e instanceof Promise;var me;(function(e){e.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},e.toString=(t)=>typeof t==="string"?t:t?.message})(me||(me={}));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 Cm=(e,t)=>{if(Cn(t))return{success:!0,data:t.value};else{if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new Kt(e.common.issues);return this._error=n,this._error}}}};function Pe(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:o,description:i}=e;if(t&&(n||o))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:i};return{errorMap:(s,l)=>{let{message:c}=e;if(s.code==="invalid_enum_value")return{message:c??l.defaultError};if(typeof l.data>"u")return{message:c??o??l.defaultError};if(s.code!=="invalid_type")return{message:l.defaultError};return{message:c??n??l.defaultError}},description:i}}class ze{get description(){return this._def.description}_getType(e){return Lr(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Lr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ot,ctx:{common:e.parent.common,data:e.data,parsedType:Lr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(ei(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Lr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Cm(n,o)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Lr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return Cn(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)=>Cn(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Lr(e)},o=this._parse({data:e,path:n.path,parent:n}),i=await(ei(o)?o:Promise.resolve(o));return Cm(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 dn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Cr.create(this)}promise(){return oo.create(this,this._def)}or(e){return ii.create([this,e],this._def)}and(e){return ai.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 ui({...Pe(this._def),innerType:this,defaultValue:t,typeName:oe.ZodDefault})}brand(){return new ml({typeName:oe.ZodBranded,type:this,...Pe(this._def)})}catch(e){let t=typeof e==="function"?e:()=>e;return new di({...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 pi.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var M0=/^c[^\s-]{8,}$/i,j0=/^[0-9a-z]+$/,O0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,N0=/^[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,D0=/^[a-z0-9_-]{21}$/i,z0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,q0=/^[-+]?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)?)??$/,$0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,L0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ul,U0=/^(?:(?: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])$/,F0=/^(?:(?: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])$/,B0=/^(([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]))$/,G0=/^(([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])$/,J0=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,W0=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,km="((\\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])))",H0=new RegExp(`^${km}$`);function Rm(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 V0(e){return new RegExp(`^${Rm(e)}$`)}function Z0(e){let t=`${km}T${Rm(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 K0(e,t){if((t==="v4"||!t)&&U0.test(e))return!0;if((t==="v6"||!t)&&B0.test(e))return!0;return!1}function Y0(e,t){if(!z0.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 Q0(e,t){if((t==="v4"||!t)&&F0.test(e))return!0;if((t==="v6"||!t)&&G0.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(!$0.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(!ul)ul=new RegExp(L0,"u");if(!ul.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(!N0.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(!D0.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(!M0.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(!j0.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(!O0.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(!Z0(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(!H0.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(!V0(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(!q0.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(!K0(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(!Y0(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(!Q0(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(!J0.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(!W0.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,...me.errToObj(n)})}_addCheck(e){return new Fr({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...me.errToObj(e)})}url(e){return this._addCheck({kind:"url",...me.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...me.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...me.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...me.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...me.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...me.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...me.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...me.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...me.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...me.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...me.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...me.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,...me.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,...me.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...me.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...me.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...me.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...me.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...me.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...me.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...me.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...me.errToObj(t)})}nonempty(e){return this.min(1,me.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 X0(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 to 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(X0(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,me.toString(t))}gt(e,t){return this.setLimit("min",e,!1,me.toString(t))}lte(e,t){return this.setLimit("max",e,!0,me.toString(t))}lt(e,t){return this.setLimit("max",e,!1,me.toString(t))}setLimit(e,t,n,o){return new to({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:me.toString(o)}]})}_addCheck(e){return new to({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:me.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:me.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:me.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:me.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:me.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:me.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:me.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:me.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:me.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)}}to.create=(e)=>new to({checks:[],typeName:oe.ZodNumber,coerce:e?.coerce||!1,...Pe(e)});class ro 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,me.toString(t))}gt(e,t){return this.setLimit("min",e,!1,me.toString(t))}lte(e,t){return this.setLimit("max",e,!0,me.toString(t))}lt(e,t){return this.setLimit("max",e,!1,me.toString(t))}setLimit(e,t,n,o){return new ro({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:me.toString(o)}]})}_addCheck(e){return new ro({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:me.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:me.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:me.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:me.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:me.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}}ro.create=(e)=>new ro({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 ri 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 ri({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:me.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:me.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}}ri.create=(e)=>new ri({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 ni 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)}}ni.create=(e)=>new ni({typeName:oe.ZodUndefined,...Pe(e)});class oi 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)}}oi.create=(e)=>new oi({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 kn extends ze{constructor(){super(...arguments);this._unknown=!0}_parse(e){return $t(e.data)}}kn.create=(e)=>new kn({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:me.toString(t)}})}max(e,t){return new Cr({...this._def,maxLength:{value:e,message:me.toString(t)}})}length(e,t){return new Cr({...this._def,exactLength:{value:e,message:me.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 eo(e){if(e instanceof dt){let t={};for(let n in e.shape){let o=e.shape[n];t[n]=kr.create(eo(o))}return new dt({...e._def,shape:()=>t})}else if(e instanceof Cr)return new Cr({...e._def,type:eo(e.element)});else if(e instanceof kr)return kr.create(eo(e.unwrap()));else if(e instanceof dn)return dn.create(eo(e.unwrap()));else if(e instanceof Gr)return Gr.create(e.items.map((t)=>eo(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 me.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:me.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 eo(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 Em($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 ii 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}}ii.create=(e,t)=>new ii({options:e,typeName:oe.ZodUnion,...Pe(t)});var Ur=(e)=>{if(e instanceof si)return Ur(e.schema);else if(e instanceof Rr)return Ur(e.innerType());else if(e instanceof li)return[e.value];else if(e instanceof Rn)return e.options;else if(e instanceof ci)return $e.objectValues(e.enum);else if(e instanceof ui)return Ur(e._def.innerType);else if(e instanceof ni)return[void 0];else if(e instanceof oi)return[null];else if(e instanceof kr)return[void 0,...Ur(e.unwrap())];else if(e instanceof dn)return[null,...Ur(e.unwrap())];else if(e instanceof ml)return Ur(e.unwrap());else if(e instanceof pi)return Ur(e.unwrap());else if(e instanceof di)return Ur(e._def.innerType);else return[]};class pl 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=Ur(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 pl({typeName:oe.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:o,...Pe(n)})}}function dl(e,t){let n=Lr(e),o=Lr(t);if(e===t)return{valid:!0,data:e};else if(n===ae.object&&o===ae.object){let i=$e.objectKeys(t),a=$e.objectKeys(e).filter((l)=>i.indexOf(l)!==-1),s={...e,...t};for(let l of a){let c=dl(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=dl(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 ai extends ze{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),o=(i,a)=>{if(ll(i)||ll(a))return we;let s=dl(i.value,a.value);if(!s.valid)return le(n,{code:ne.invalid_intersection_types}),we;if(cl(i)||cl(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}))}}ai.create=(e,t,n)=>new ai({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 no 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 no({...this._def,minSize:{value:e,message:me.toString(t)}})}max(e,t){return new no({...this._def,maxSize:{value:e,message:me.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}no.create=(e,t)=>new no({valueType:e,minSize:null,maxSize:null,typeName:oe.ZodSet,...Pe(t)});class ti 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,Xo(),un].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,Xo(),un].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 oo){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 ti({...this._def,args:Gr.create(e).rest(kn.create())})}returns(e){return new ti({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new ti({args:e?e:Gr.create([]).rest(kn.create()),returns:t||kn.create(),typeName:oe.ZodFunction,...Pe(n)})}}class si 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})}}si.create=(e,t)=>new si({getter:e,typeName:oe.ZodLazy,...Pe(t)});class li 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}}li.create=(e,t)=>new li({value:e,typeName:oe.ZodLiteral,...Pe(t)});function Em(e,t){return new Rn({values:e,typeName:oe.ZodEnum,...Pe(t)})}class Rn 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 Rn.create(e,{...this._def,...t})}exclude(e,t=this._def){return Rn.create(this.options.filter((n)=>!e.includes(n)),{...this._def,...t})}}Rn.create=Em;class ci 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}}ci.create=(e,t)=>new ci({values:e,typeName:oe.ZodNativeEnum,...Pe(t)});class oo 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})))}}oo.create=(e,t)=>new oo({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 Xn(l.value);if(t.value==="dirty")return Xn(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 Xn(s.value);if(t.value==="dirty")return Xn(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(!Cn(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(!Cn(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 dn extends ze{_parse(e){if(this._getType(e)===ae.null)return $t(null);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}dn.create=(e,t)=>new dn({innerType:e,typeName:oe.ZodNullable,...Pe(t)});class ui 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}}ui.create=(e,t)=>new ui({innerType:e,typeName:oe.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...Pe(t)});class di 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(ei(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}}di.create=(e,t)=>new di({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 N4=Symbol("zod_brand");class ml 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(),Xn(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 pi extends ze{_parse(e){let t=this._def.innerType._parse(e),n=(o)=>{if(Cn(o))o.value=Object.freeze(o.value);return o};return ei(t)?t.then((o)=>n(o)):n(t)}unwrap(){return this._def.innerType}}pi.create=(e,t)=>new pi({innerType:e,typeName:oe.ZodReadonly,...Pe(t)});var D4={object:dt.lazycreate},oe;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(oe||(oe={}));var z4=Fr.create,q4=to.create,$4=Ca.create,L4=ro.create,U4=_a.create,F4=ri.create,B4=Sa.create,G4=ni.create,J4=oi.create,W4=wa.create,H4=kn.create,V4=Br.create,Z4=xa.create,K4=Cr.create,Y4=dt.create,Q4=dt.strictCreate,X4=ii.create,eW=pl.create,tW=ai.create,rW=Gr.create,nW=Ta.create,oW=Ia.create,iW=no.create,aW=ti.create,sW=si.create,lW=li.create,cW=Rn.create,uW=ci.create,dW=oo.create,pW=Rr.create,mW=kr.create,gW=dn.create,fW=Rr.createWithPreprocess,hW=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 Am=10,ek=13,En=32;function gl(e){}function jm(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=gl,onError:n=gl,onRetry:o=gl,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(`
|
|
23
|
+
Error message: ${Tr(t)}`,cause:t});this[Np]=!0,this.text=e}static isInstance(e){return ie.hasMarker(e,um)}},dm="AI_LoadAPIKeyError",pm=`vercel.ai.error.${dm}`,x0=Symbol.for(pm),zp,$p,Yo=class extends($p=ie,zp=x0,$p){constructor({message:e}){super({name:dm,message:e});this[zp]=!0}static isInstance(e){return ie.hasMarker(e,pm)}},mm="AI_LoadSettingError",gm=`vercel.ai.error.${mm}`,T0=Symbol.for(gm),qp,Lp,n4=class extends(Lp=ie,qp=T0,Lp){constructor({message:e}){super({name:mm,message:e});this[qp]=!0}static isInstance(e){return ie.hasMarker(e,gm)}},fm="AI_NoContentGeneratedError",hm=`vercel.ai.error.${fm}`,I0=Symbol.for(hm),Up,Fp,o4=class extends(Fp=ie,Up=I0,Fp){constructor({message:e="No content generated."}={}){super({name:fm,message:e});this[Up]=!0}static isInstance(e){return ie.hasMarker(e,hm)}},ym="AI_NoSuchModelError",vm=`vercel.ai.error.${ym}`,C0=Symbol.for(vm),Bp,Gp,al=class extends(Gp=ie,Bp=C0,Gp){constructor({errorName:e=ym,modelId:t,modelType:n,message:o=`No such ${n}: ${t}`}){super({name:e,message:o});this[Bp]=!0,this.modelId=t,this.modelType=n}static isInstance(e){return ie.hasMarker(e,vm)}},bm="AI_TooManyEmbeddingValuesForCallError",_m=`vercel.ai.error.${bm}`,k0=Symbol.for(_m),Jp,Wp,va=class extends(Wp=ie,Jp=k0,Wp){constructor(e){super({name:bm,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[Jp]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return ie.hasMarker(e,_m)}},Sm="AI_TypeValidationError",wm=`vercel.ai.error.${Sm}`,R0=Symbol.for(wm),Hp,Vp,vt=class e extends(Vp=ie,Hp=R0,Vp){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:Sm,message:`${i}: Value: ${JSON.stringify(t)}.
|
|
24
|
+
Error message: ${Tr(n)}`,cause:n});this[Hp]=!0,this.value=t,this.context=o}static isInstance(t){return ie.hasMarker(t,wm)}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})}},xm="AI_UnsupportedFunctionalityError",Tm=`vercel.ai.error.${xm}`,E0=Symbol.for(Tm),Zp,Kp,He=class extends(Kp=ie,Zp=E0,Kp){constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:xm,message:t});this[Zp]=!0,this.functionality=e}static isInstance(e){return ie.hasMarker(e,Tm)}};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 sl(e){return Array.isArray(e)&&e.every(ha)}function Qo(e){return e!=null&&typeof e==="object"&&Object.entries(e).every(([t,n])=>typeof t==="string"&&(n===void 0||ha(n)))}var qe;(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}})(qe||(qe={}));var Im;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Im||(Im={}));var ae=qe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Lr=(e)=>{switch(typeof e){case"undefined":return ae.undefined;case"string":return ae.string;case"number":return Number.isNaN(e)?ae.nan:ae.number;case"boolean":return ae.boolean;case"function":return ae.function;case"bigint":return ae.bigint;case"symbol":return ae.symbol;case"object":if(Array.isArray(e))return ae.array;if(e===null)return ae.null;if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return ae.promise;if(typeof Map<"u"&&e instanceof Map)return ae.map;if(typeof Set<"u"&&e instanceof Set)return ae.set;if(typeof Date<"u"&&e instanceof Date)return ae.date;return ae.object;default:return ae.unknown}};var ne=qe.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,qe.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 A0=(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,qe.jsonStringifyReplacer)}`;break;case ne.unrecognized_keys:n=`Unrecognized key(s) in object: ${qe.joinValues(e.keys,", ")}`;break;case ne.invalid_union:n="Invalid input";break;case ne.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${qe.joinValues(e.options)}`;break;case ne.invalid_enum_value:n=`Invalid enum value. Expected ${qe.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 qe.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,qe.assertNever(e)}return{message:n}},un=A0;var P0=un;function Xo(){return P0}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=Xo(),o=ba({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===un?void 0:un].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"}),Xn=(e)=>({status:"dirty",value:e}),qt=(e)=>({status:"valid",value:e}),ll=(e)=>e.status==="aborted",cl=(e)=>e.status==="dirty",Cn=(e)=>e.status==="valid",ei=(e)=>typeof Promise<"u"&&e instanceof Promise;var me;(function(e){e.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},e.toString=(t)=>typeof t==="string"?t:t?.message})(me||(me={}));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 Cm=(e,t)=>{if(Cn(t))return{success:!0,data:t.value};else{if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new Kt(e.common.issues);return this._error=n,this._error}}}};function Pe(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:o,description:i}=e;if(t&&(n||o))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:i};return{errorMap:(s,l)=>{let{message:c}=e;if(s.code==="invalid_enum_value")return{message:c??l.defaultError};if(typeof l.data>"u")return{message:c??o??l.defaultError};if(s.code!=="invalid_type")return{message:l.defaultError};return{message:c??n??l.defaultError}},description:i}}class ze{get description(){return this._def.description}_getType(e){return Lr(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Lr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ot,ctx:{common:e.parent.common,data:e.data,parsedType:Lr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(ei(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Lr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Cm(n,o)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Lr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return Cn(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)=>Cn(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Lr(e)},o=this._parse({data:e,path:n.path,parent:n}),i=await(ei(o)?o:Promise.resolve(o));return Cm(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 dn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Cr.create(this)}promise(){return oo.create(this,this._def)}or(e){return ii.create([this,e],this._def)}and(e){return ai.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 ui({...Pe(this._def),innerType:this,defaultValue:t,typeName:oe.ZodDefault})}brand(){return new ml({typeName:oe.ZodBranded,type:this,...Pe(this._def)})}catch(e){let t=typeof e==="function"?e:()=>e;return new di({...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 pi.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var M0=/^c[^\s-]{8,}$/i,j0=/^[0-9a-z]+$/,O0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,N0=/^[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,D0=/^[a-z0-9_-]{21}$/i,z0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,$0=/^[-+]?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)?)??$/,q0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,L0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ul,U0=/^(?:(?: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])$/,F0=/^(?:(?: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])$/,B0=/^(([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]))$/,G0=/^(([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])$/,J0=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,W0=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,km="((\\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])))",H0=new RegExp(`^${km}$`);function Rm(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 V0(e){return new RegExp(`^${Rm(e)}$`)}function Z0(e){let t=`${km}T${Rm(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 K0(e,t){if((t==="v4"||!t)&&U0.test(e))return!0;if((t==="v6"||!t)&&B0.test(e))return!0;return!1}function Y0(e,t){if(!z0.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 Q0(e,t){if((t==="v4"||!t)&&F0.test(e))return!0;if((t==="v6"||!t)&&G0.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(!q0.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(!ul)ul=new RegExp(L0,"u");if(!ul.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(!N0.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(!D0.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(!M0.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(!j0.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(!O0.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(!Z0(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(!H0.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(!V0(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(!$0.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(!K0(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(!Y0(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(!Q0(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(!J0.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(!W0.test(e.data))o=this._getOrReturnCtx(e,o),le(o,{validation:"base64url",code:ne.invalid_string,message:i.message}),n.dirty()}else qe.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,...me.errToObj(n)})}_addCheck(e){return new Fr({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...me.errToObj(e)})}url(e){return this._addCheck({kind:"url",...me.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...me.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...me.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...me.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...me.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...me.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...me.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...me.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...me.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...me.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...me.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...me.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,...me.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,...me.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...me.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...me.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...me.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...me.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...me.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...me.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...me.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...me.errToObj(t)})}nonempty(e){return this.min(1,me.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 X0(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 to 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(!qe.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(X0(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 qe.assertNever(i);return{status:o.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,me.toString(t))}gt(e,t){return this.setLimit("min",e,!1,me.toString(t))}lte(e,t){return this.setLimit("max",e,!0,me.toString(t))}lt(e,t){return this.setLimit("max",e,!1,me.toString(t))}setLimit(e,t,n,o){return new to({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:me.toString(o)}]})}_addCheck(e){return new to({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:me.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:me.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:me.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:me.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:me.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:me.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:me.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:me.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:me.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"&&qe.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)}}to.create=(e)=>new to({checks:[],typeName:oe.ZodNumber,coerce:e?.coerce||!1,...Pe(e)});class ro 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 qe.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,me.toString(t))}gt(e,t){return this.setLimit("min",e,!1,me.toString(t))}lte(e,t){return this.setLimit("max",e,!0,me.toString(t))}lt(e,t){return this.setLimit("max",e,!1,me.toString(t))}setLimit(e,t,n,o){return new ro({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:me.toString(o)}]})}_addCheck(e){return new ro({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:me.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:me.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:me.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:me.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:me.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}}ro.create=(e)=>new ro({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 qt(e.data)}}_a.create=(e)=>new _a({typeName:oe.ZodBoolean,coerce:e?.coerce||!1,...Pe(e)});class ri 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 qe.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ri({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:me.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:me.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}}ri.create=(e)=>new ri({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 qt(e.data)}}Sa.create=(e)=>new Sa({typeName:oe.ZodSymbol,...Pe(e)});class ni 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 qt(e.data)}}ni.create=(e)=>new ni({typeName:oe.ZodUndefined,...Pe(e)});class oi 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 qt(e.data)}}oi.create=(e)=>new oi({typeName:oe.ZodNull,...Pe(e)});class wa extends ze{constructor(){super(...arguments);this._any=!0}_parse(e){return qt(e.data)}}wa.create=(e)=>new wa({typeName:oe.ZodAny,...Pe(e)});class kn extends ze{constructor(){super(...arguments);this._unknown=!0}_parse(e){return qt(e.data)}}kn.create=(e)=>new kn({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 qt(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:me.toString(t)}})}max(e,t){return new Cr({...this._def,maxLength:{value:e,message:me.toString(t)}})}length(e,t){return new Cr({...this._def,exactLength:{value:e,message:me.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 eo(e){if(e instanceof dt){let t={};for(let n in e.shape){let o=e.shape[n];t[n]=kr.create(eo(o))}return new dt({...e._def,shape:()=>t})}else if(e instanceof Cr)return new Cr({...e._def,type:eo(e.element)});else if(e instanceof kr)return kr.create(eo(e.unwrap()));else if(e instanceof dn)return dn.create(eo(e.unwrap()));else if(e instanceof Gr)return Gr.create(e.items.map((t)=>eo(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=qe.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 me.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:me.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 qe.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 qe.objectKeys(this.shape))if(!e[n])t[n]=this.shape[n];return new dt({...this._def,shape:()=>t})}deepPartial(){return eo(this)}partial(e){let t={};for(let n of qe.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 qe.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 Em(qe.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 ii 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}}ii.create=(e,t)=>new ii({options:e,typeName:oe.ZodUnion,...Pe(t)});var Ur=(e)=>{if(e instanceof si)return Ur(e.schema);else if(e instanceof Rr)return Ur(e.innerType());else if(e instanceof li)return[e.value];else if(e instanceof Rn)return e.options;else if(e instanceof ci)return qe.objectValues(e.enum);else if(e instanceof ui)return Ur(e._def.innerType);else if(e instanceof ni)return[void 0];else if(e instanceof oi)return[null];else if(e instanceof kr)return[void 0,...Ur(e.unwrap())];else if(e instanceof dn)return[null,...Ur(e.unwrap())];else if(e instanceof ml)return Ur(e.unwrap());else if(e instanceof pi)return Ur(e.unwrap());else if(e instanceof di)return Ur(e._def.innerType);else return[]};class pl 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=Ur(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 pl({typeName:oe.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:o,...Pe(n)})}}function dl(e,t){let n=Lr(e),o=Lr(t);if(e===t)return{valid:!0,data:e};else if(n===ae.object&&o===ae.object){let i=qe.objectKeys(t),a=qe.objectKeys(e).filter((l)=>i.indexOf(l)!==-1),s={...e,...t};for(let l of a){let c=dl(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=dl(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 ai extends ze{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),o=(i,a)=>{if(ll(i)||ll(a))return we;let s=dl(i.value,a.value);if(!s.valid)return le(n,{code:ne.invalid_intersection_types}),we;if(cl(i)||cl(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}))}}ai.create=(e,t,n)=>new ai({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 no 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 no({...this._def,minSize:{value:e,message:me.toString(t)}})}max(e,t){return new no({...this._def,maxSize:{value:e,message:me.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}no.create=(e,t)=>new no({valueType:e,minSize:null,maxSize:null,typeName:oe.ZodSet,...Pe(t)});class ti 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,Xo(),un].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,Xo(),un].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 oo){let s=this;return qt(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 qt(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 ti({...this._def,args:Gr.create(e).rest(kn.create())})}returns(e){return new ti({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new ti({args:e?e:Gr.create([]).rest(kn.create()),returns:t||kn.create(),typeName:oe.ZodFunction,...Pe(n)})}}class si 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})}}si.create=(e,t)=>new si({getter:e,typeName:oe.ZodLazy,...Pe(t)});class li 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}}li.create=(e,t)=>new li({value:e,typeName:oe.ZodLiteral,...Pe(t)});function Em(e,t){return new Rn({values:e,typeName:oe.ZodEnum,...Pe(t)})}class Rn extends ze{_parse(e){if(typeof e.data!=="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return le(t,{expected:qe.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 qt(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 Rn.create(e,{...this._def,...t})}exclude(e,t=this._def){return Rn.create(this.options.filter((n)=>!e.includes(n)),{...this._def,...t})}}Rn.create=Em;class ci extends ze{_parse(e){let t=qe.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==ae.string&&n.parsedType!==ae.number){let o=qe.objectValues(t);return le(n,{expected:qe.joinValues(o),received:n.parsedType,code:ne.invalid_type}),we}if(!this._cache)this._cache=new Set(qe.getValidEnumValues(this._def.values));if(!this._cache.has(e.data)){let o=qe.objectValues(t);return le(n,{received:n.data,code:ne.invalid_enum_value,options:o}),we}return qt(e.data)}get enum(){return this._def.values}}ci.create=(e,t)=>new ci({values:e,typeName:oe.ZodNativeEnum,...Pe(t)});class oo 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 qt(n.then((o)=>this._def.type.parseAsync(o,{path:t.path,errorMap:t.common.contextualErrorMap})))}}oo.create=(e,t)=>new oo({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 Xn(l.value);if(t.value==="dirty")return Xn(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 Xn(s.value);if(t.value==="dirty")return Xn(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(!Cn(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(!Cn(a))return we;return Promise.resolve(o.transform(a.value,i)).then((s)=>({status:t.value,value:s}))});qe.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 qt(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 dn extends ze{_parse(e){if(this._getType(e)===ae.null)return qt(null);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}dn.create=(e,t)=>new dn({innerType:e,typeName:oe.ZodNullable,...Pe(t)});class ui 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}}ui.create=(e,t)=>new ui({innerType:e,typeName:oe.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...Pe(t)});class di 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(ei(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}}di.create=(e,t)=>new di({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 N4=Symbol("zod_brand");class ml 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(),Xn(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 pi extends ze{_parse(e){let t=this._def.innerType._parse(e),n=(o)=>{if(Cn(o))o.value=Object.freeze(o.value);return o};return ei(t)?t.then((o)=>n(o)):n(t)}unwrap(){return this._def.innerType}}pi.create=(e,t)=>new pi({innerType:e,typeName:oe.ZodReadonly,...Pe(t)});var D4={object:dt.lazycreate},oe;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(oe||(oe={}));var z4=Fr.create,$4=to.create,q4=Ca.create,L4=ro.create,U4=_a.create,F4=ri.create,B4=Sa.create,G4=ni.create,J4=oi.create,W4=wa.create,H4=kn.create,V4=Br.create,Z4=xa.create,K4=Cr.create,Y4=dt.create,Q4=dt.strictCreate,X4=ii.create,eW=pl.create,tW=ai.create,rW=Gr.create,nW=Ta.create,oW=Ia.create,iW=no.create,aW=ti.create,sW=si.create,lW=li.create,cW=Rn.create,uW=ci.create,dW=oo.create,pW=Rr.create,mW=kr.create,gW=dn.create,fW=Rr.createWithPreprocess,hW=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 Am=10,ek=13,En=32;function gl(e){}function jm(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=gl,onError:n=gl,onRetry:o=gl,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
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
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
27
|
`,C);continue}let b=_.charCodeAt(C);if(Pm(_,C,b)){let E=_.charCodeAt(C+5)===En?C+6:C+5,F=_.slice(E,I);if(m===0&&_.charCodeAt(I+1)===Am){t({id:u,event:p,data:F}),u=void 0,d="",p=void 0,C=I+2,I=_.indexOf(`
|
|
@@ -30,11 +30,11 @@ ${F}`,m++}else Mm(_,C,b)?p=_.slice(_.charCodeAt(C+6)===En?C+7:C+6,I)||void 0:w(_
|
|
|
30
30
|
`,C)}return _.slice(C)}for(;C<_.length;){let I=_.indexOf("\r",C),b=_.indexOf(`
|
|
31
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)===ek&&_.charCodeAt(C)===Am&&C++}return _.slice(C)}function w(_,C,I){if(C===I){y();return}let b=_.charCodeAt(C);if(Pm(_,C,b)){let N=_.charCodeAt(C+5)===En?C+6:C+5,re=_.slice(N,I);d=m===0?re:`${d}
|
|
32
32
|
${re}`,m++;return}if(Mm(_,C,b)){p=_.slice(_.charCodeAt(C+6)===En?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)===En?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)===En?2:1))}return}let E=_.slice(C,I),F=E.indexOf(":");if(F===-1){S(E,"",E);return}let R=E.slice(0,F),z=E.charCodeAt(F+1)===En?2:1,D=E.slice(F+z);S(R,D,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 Pm(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 Mm(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 fl extends TransformStream{constructor({onError:e,onRetry:t,onComment:n,maxBufferSize:o}={}){let i;super({start(a){i=jm({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(Om());return}let a=setTimeout(()=>{s(),o()},e),s=()=>{clearTimeout(a),n==null||n.removeEventListener("abort",l)},l=()=>{s(),i(Om())};n==null||n.addEventListener("abort",l)})}function Om(){return new DOMException("Delay was aborted","AbortError")}var Pn=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 io(e){return Object.fromEntries([...e.headers])}var{btoa:tk,atob:rk}=globalThis;function wt(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=rk(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 tk(t)}function bt(e){return e instanceof Uint8Array?Nt(e):e}function Fm(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 mi(e){var t;try{await((t=e.body)==null?void 0:t.cancel())}catch(n){}}var Bm="AI_DownloadError",Gm=`vercel.ai.error.${Bm}`,nk=Symbol.for(Gm),Nm,Dm,Et=class extends(Dm=ie,Nm=nk,Dm){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:Bm,message:i,cause:o});this[Nm]=!0,this.url=e,this.statusCode=t,this.statusText=n}static isInstance(e){return ie.hasMarker(e,Gm)}};function ok(e=globalThis){return e.window!=null}function ik(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(sk(o))throw new Et({url:e,message:`URL with IPv6 address ${n} is not allowed`});return}if(Jm(n)){if(Wm(n))throw new Et({url:e,message:`URL with IP address ${n} is not allowed`});return}}function Jm(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 Wm(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 ak(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||!Jm(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 sk(e){let t=ak(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 Wm(`${i}.${a}.${s}.${l}`)}return!1}var lk=10;async function _l({url:e,headers:t,abortSignal:n,maxRedirects:o=lk}){let i={signal:n};if(t!==void 0)i.headers=t;let a=e;for(let s=0;s<=o;s++){ik(a);let l=await fetch(a,{...i,redirect:"manual"});if(l.type==="opaqueredirect"){if(!ok())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 mi(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 mi(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 Sl(e,t){var n,o;try{let i=await _l({url:e,abortSignal:t==null?void 0:t.abortSignal});if(!i.ok)throw await mi(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 Qn({argument:"separator",message:`The separator "${o}" must not be part of the alphabet "${n}".`});return()=>`${e}${o}${i()}`},Le=Er();function gi(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 ck=["fetch failed","failed to fetch"],uk=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function dk(e){if(!(e instanceof Error))return!1;let t=e.code;if(typeof t==="string"&&uk.includes(t))return!0;return!1}function Hm({error:e,url:t,requestBodyValues:n}){if(Yt(e))return e;if(e instanceof TypeError&&ck.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(dk(e))return new De({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:n,isRetryable:!0});return e}function ao(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 pk(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(pk(e)),o=n.get("user-agent")||"";return n.set("user-agent",[o,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}var Vm="4.0.37",mk=()=>globalThis.fetch,Xt=async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:o,abortSignal:i,fetch:a=mk()})=>{try{let s=await a(e,{method:"GET",headers:it(t,`ai-sdk/provider-utils/${Vm}`,ao()),signal:i}),l=io(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 Hm({error:s,url:e,requestBodyValues:{}})}};function fi(e){return e!=null}function Zm(e,t){try{return new URL(e).origin===new URL(t).origin}catch(n){return!1}}function Km({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 so({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:o}){if(typeof e==="string")return e;if(e!=null)throw new Yo({message:`${o} API key must be a string.`});if(typeof process>"u")throw new Yo({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 Yo({message:`${o} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=="string")throw new Yo({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 Ym(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 gk=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,fk=/"(?: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 zm(e){let t=JSON.parse(e);if(t===null||typeof t!=="object")return t;if(gk.test(e)===!1&&fk.test(e)===!1)return t;return hk(t)}function hk(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 zm(e)}try{return zm(e)}finally{Error.stackTraceLimit=t}}function wl(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]=An(n[o])}if(e.items!=null)e.items=Array.isArray(e.items)?e.items.map(An):An(e.items);if(e.anyOf!=null)e.anyOf=e.anyOf.map(An);if(e.allOf!=null)e.allOf=e.allOf.map(An);if(e.oneOf!=null)e.oneOf=e.oneOf.map(An);let{definitions:t}=e;if(t!=null)for(let n of Object.keys(t))t[n]=An(t[n]);return e}function An(e){if(typeof e==="boolean")return e;return wl(e)}var yk=Symbol("Let zodToJsonSchema decide on which parser to use"),qm={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"},vk=(e)=>typeof e==="string"?{...qm,name:e}:{...qm,...e};function Qt(){return{}}function bk(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 _k(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 Sk(){return{type:"boolean"}}function Qm(e,t){return Ve(e.type._def,t)}var wk=(e,t)=>Ve(e.innerType._def,t);function Xm(e,t,n){let o=n!=null?n:t.dateStrategy;if(Array.isArray(o))return{anyOf:o.map((i,a)=>Xm(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 xk(e)}}var xk=(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 Tk(e,t){return{...Ve(e.innerType._def,t),default:e.defaultValue()}}function Ik(e,t){return t.effectStrategy==="input"?Ve(e.schema._def,t):Qt()}function Ck(e){return{type:"string",enum:Array.from(e.values)}}var kk=(e)=>{if("type"in e&&e.type==="string")return!1;return"allOf"in e};function Rk(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(kk(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 Ek(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 hl=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(hl===void 0)hl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return hl},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 eg(e,t){let n={type:"string"};if(e.checks)for(let o of e.checks)switch(o.kind){case"min":n.minLength=typeof n.minLength==="number"?Math.max(n.minLength,o.value):o.value;break;case"max":n.maxLength=typeof n.maxLength==="number"?Math.min(n.maxLength,o.value):o.value;break;case"email":switch(t.emailStrategy){case"format:email":pr(n,"email",o.message,t);break;case"format:idn-email":pr(n,"idn-email",o.message,t);break;case"pattern:zod":Lt(n,dr.email,o.message,t);break}break;case"url":pr(n,"uri",o.message,t);break;case"uuid":pr(n,"uuid",o.message,t);break;case"regex":Lt(n,o.regex,o.message,t);break;case"cuid":Lt(n,dr.cuid,o.message,t);break;case"cuid2":Lt(n,dr.cuid2,o.message,t);break;case"startsWith":Lt(n,RegExp(`^${yl(o.value,t)}`),o.message,t);break;case"endsWith":Lt(n,RegExp(`${yl(o.value,t)}$`),o.message,t);break;case"datetime":pr(n,"date-time",o.message,t);break;case"date":pr(n,"date",o.message,t);break;case"time":pr(n,"time",o.message,t);break;case"duration":pr(n,"duration",o.message,t);break;case"length":n.minLength=typeof n.minLength==="number"?Math.max(n.minLength,o.value):o.value,n.maxLength=typeof n.maxLength==="number"?Math.min(n.maxLength,o.value):o.value;break;case"includes":{Lt(n,RegExp(yl(o.value,t)),o.message,t);break}case"ip":{if(o.version!=="v6")pr(n,"ipv4",o.message,t);if(o.version!=="v4")pr(n,"ipv6",o.message,t);break}case"base64url":Lt(n,dr.base64url,o.message,t);break;case"jwt":Lt(n,dr.jwt,o.message,t);break;case"cidr":{if(o.version!=="v6")Lt(n,dr.ipv4Cidr,o.message,t);if(o.version!=="v4")Lt(n,dr.ipv6Cidr,o.message,t);break}case"emoji":Lt(n,dr.emoji(),o.message,t);break;case"ulid":{Lt(n,dr.ulid,o.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{pr(n,"binary",o.message,t);break}case"contentEncoding:base64":{n.contentEncoding="base64";break}case"pattern:zod":{Lt(n,dr.base64,o.message,t);break}}break}case"nanoid":Lt(n,dr.nanoid,o.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function yl(e,t){return t.patternStrategy==="escape"?Pk(e):e}var Ak=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Pk(e){let t="";for(let n=0;n<e.length;n++){if(!Ak.has(e[n]))t+="\\";t+=e[n]}return t}function pr(e,t,n,o){var i;if(e.format||((i=e.anyOf)==null?void 0:i.some((a)=>a.format))){if(!e.anyOf)e.anyOf=[];if(e.format)e.anyOf.push({format:e.format}),delete e.format;e.anyOf.push({format:t,...n&&o.errorMessages&&{errorMessage:{format:n}}})}else e.format=t}function Lt(e,t,n,o){var i;if(e.pattern||((i=e.allOf)==null?void 0:i.some((a)=>a.pattern))){if(!e.allOf)e.allOf=[];if(e.pattern)e.allOf.push({pattern:e.pattern}),delete e.pattern;e.allOf.push({pattern:$m(t,o),...n&&o.errorMessages&&{errorMessage:{pattern:n}}})}else e.pattern=$m(t,o)}function $m(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
|
|
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 Pm(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 Mm(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 fl extends TransformStream{constructor({onError:e,onRetry:t,onComment:n,maxBufferSize:o}={}){let i;super({start(a){i=jm({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(Om());return}let a=setTimeout(()=>{s(),o()},e),s=()=>{clearTimeout(a),n==null||n.removeEventListener("abort",l)},l=()=>{s(),i(Om())};n==null||n.addEventListener("abort",l)})}function Om(){return new DOMException("Delay was aborted","AbortError")}var Pn=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 io(e){return Object.fromEntries([...e.headers])}var{btoa:tk,atob:rk}=globalThis;function wt(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=rk(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 tk(t)}function bt(e){return e instanceof Uint8Array?Nt(e):e}function Fm(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 mi(e){var t;try{await((t=e.body)==null?void 0:t.cancel())}catch(n){}}var Bm="AI_DownloadError",Gm=`vercel.ai.error.${Bm}`,nk=Symbol.for(Gm),Nm,Dm,Et=class extends(Dm=ie,Nm=nk,Dm){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:Bm,message:i,cause:o});this[Nm]=!0,this.url=e,this.statusCode=t,this.statusText=n}static isInstance(e){return ie.hasMarker(e,Gm)}};function ok(e=globalThis){return e.window!=null}function ik(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(sk(o))throw new Et({url:e,message:`URL with IPv6 address ${n} is not allowed`});return}if(Jm(n)){if(Wm(n))throw new Et({url:e,message:`URL with IP address ${n} is not allowed`});return}}function Jm(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 Wm(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 ak(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||!Jm(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 sk(e){let t=ak(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 Wm(`${i}.${a}.${s}.${l}`)}return!1}var lk=10;async function _l({url:e,headers:t,abortSignal:n,maxRedirects:o=lk}){let i={signal:n};if(t!==void 0)i.headers=t;let a=e;for(let s=0;s<=o;s++){ik(a);let l=await fetch(a,{...i,redirect:"manual"});if(l.type==="opaqueredirect"){if(!ok())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 mi(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 mi(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 Sl(e,t){var n,o;try{let i=await _l({url:e,abortSignal:t==null?void 0:t.abortSignal});if(!i.ok)throw await mi(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 Qn({argument:"separator",message:`The separator "${o}" must not be part of the alphabet "${n}".`});return()=>`${e}${o}${i()}`},Le=Er();function gi(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 ck=["fetch failed","failed to fetch"],uk=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function dk(e){if(!(e instanceof Error))return!1;let t=e.code;if(typeof t==="string"&&uk.includes(t))return!0;return!1}function Hm({error:e,url:t,requestBodyValues:n}){if(Yt(e))return e;if(e instanceof TypeError&&ck.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(dk(e))return new De({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:n,isRetryable:!0});return e}function ao(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 pk(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(pk(e)),o=n.get("user-agent")||"";return n.set("user-agent",[o,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}var Vm="4.0.37",mk=()=>globalThis.fetch,Xt=async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:o,abortSignal:i,fetch:a=mk()})=>{try{let s=await a(e,{method:"GET",headers:it(t,`ai-sdk/provider-utils/${Vm}`,ao()),signal:i}),l=io(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 Hm({error:s,url:e,requestBodyValues:{}})}};function fi(e){return e!=null}function Zm(e,t){try{return new URL(e).origin===new URL(t).origin}catch(n){return!1}}function Km({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 so({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:o}){if(typeof e==="string")return e;if(e!=null)throw new Yo({message:`${o} API key must be a string.`});if(typeof process>"u")throw new Yo({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 Yo({message:`${o} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=="string")throw new Yo({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 Ym(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 gk=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,fk=/"(?: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 zm(e){let t=JSON.parse(e);if(t===null||typeof t!=="object")return t;if(gk.test(e)===!1&&fk.test(e)===!1)return t;return hk(t)}function hk(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 zm(e)}try{return zm(e)}finally{Error.stackTraceLimit=t}}function wl(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]=An(n[o])}if(e.items!=null)e.items=Array.isArray(e.items)?e.items.map(An):An(e.items);if(e.anyOf!=null)e.anyOf=e.anyOf.map(An);if(e.allOf!=null)e.allOf=e.allOf.map(An);if(e.oneOf!=null)e.oneOf=e.oneOf.map(An);let{definitions:t}=e;if(t!=null)for(let n of Object.keys(t))t[n]=An(t[n]);return e}function An(e){if(typeof e==="boolean")return e;return wl(e)}var yk=Symbol("Let zodToJsonSchema decide on which parser to use"),$m={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"},vk=(e)=>typeof e==="string"?{...$m,name:e}:{...$m,...e};function Qt(){return{}}function bk(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 _k(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 Sk(){return{type:"boolean"}}function Qm(e,t){return Ve(e.type._def,t)}var wk=(e,t)=>Ve(e.innerType._def,t);function Xm(e,t,n){let o=n!=null?n:t.dateStrategy;if(Array.isArray(o))return{anyOf:o.map((i,a)=>Xm(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 xk(e)}}var xk=(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 Tk(e,t){return{...Ve(e.innerType._def,t),default:e.defaultValue()}}function Ik(e,t){return t.effectStrategy==="input"?Ve(e.schema._def,t):Qt()}function Ck(e){return{type:"string",enum:Array.from(e.values)}}var kk=(e)=>{if("type"in e&&e.type==="string")return!1;return"allOf"in e};function Rk(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(kk(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 Ek(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 hl=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(hl===void 0)hl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return hl},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 eg(e,t){let n={type:"string"};if(e.checks)for(let o of e.checks)switch(o.kind){case"min":n.minLength=typeof n.minLength==="number"?Math.max(n.minLength,o.value):o.value;break;case"max":n.maxLength=typeof n.maxLength==="number"?Math.min(n.maxLength,o.value):o.value;break;case"email":switch(t.emailStrategy){case"format:email":pr(n,"email",o.message,t);break;case"format:idn-email":pr(n,"idn-email",o.message,t);break;case"pattern:zod":Lt(n,dr.email,o.message,t);break}break;case"url":pr(n,"uri",o.message,t);break;case"uuid":pr(n,"uuid",o.message,t);break;case"regex":Lt(n,o.regex,o.message,t);break;case"cuid":Lt(n,dr.cuid,o.message,t);break;case"cuid2":Lt(n,dr.cuid2,o.message,t);break;case"startsWith":Lt(n,RegExp(`^${yl(o.value,t)}`),o.message,t);break;case"endsWith":Lt(n,RegExp(`${yl(o.value,t)}$`),o.message,t);break;case"datetime":pr(n,"date-time",o.message,t);break;case"date":pr(n,"date",o.message,t);break;case"time":pr(n,"time",o.message,t);break;case"duration":pr(n,"duration",o.message,t);break;case"length":n.minLength=typeof n.minLength==="number"?Math.max(n.minLength,o.value):o.value,n.maxLength=typeof n.maxLength==="number"?Math.min(n.maxLength,o.value):o.value;break;case"includes":{Lt(n,RegExp(yl(o.value,t)),o.message,t);break}case"ip":{if(o.version!=="v6")pr(n,"ipv4",o.message,t);if(o.version!=="v4")pr(n,"ipv6",o.message,t);break}case"base64url":Lt(n,dr.base64url,o.message,t);break;case"jwt":Lt(n,dr.jwt,o.message,t);break;case"cidr":{if(o.version!=="v6")Lt(n,dr.ipv4Cidr,o.message,t);if(o.version!=="v4")Lt(n,dr.ipv6Cidr,o.message,t);break}case"emoji":Lt(n,dr.emoji(),o.message,t);break;case"ulid":{Lt(n,dr.ulid,o.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{pr(n,"binary",o.message,t);break}case"contentEncoding:base64":{n.contentEncoding="base64";break}case"pattern:zod":{Lt(n,dr.base64,o.message,t);break}}break}case"nanoid":Lt(n,dr.nanoid,o.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function yl(e,t){return t.patternStrategy==="escape"?Pk(e):e}var Ak=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Pk(e){let t="";for(let n=0;n<e.length;n++){if(!Ak.has(e[n]))t+="\\";t+=e[n]}return t}function pr(e,t,n,o){var i;if(e.format||((i=e.anyOf)==null?void 0:i.some((a)=>a.format))){if(!e.anyOf)e.anyOf=[];if(e.format)e.anyOf.push({format:e.format}),delete e.format;e.anyOf.push({format:t,...n&&o.errorMessages&&{errorMessage:{format:n}}})}else e.format=t}function Lt(e,t,n,o){var i;if(e.pattern||((i=e.allOf)==null?void 0:i.some((a)=>a.pattern))){if(!e.allOf)e.allOf=[];if(e.pattern)e.allOf.push({pattern:e.pattern}),delete e.pattern;e.allOf.push({pattern:qm(t,o),...n&&o.errorMessages&&{errorMessage:{pattern:n}}})}else e.pattern=qm(t,o)}function qm(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
34
|
]))`;continue}else if(i[u]==="$"){a+=`($|(?=[\r
|
|
35
35
|
]))`;continue}}if(o.s&&i[u]==="."){a+=l?`${i[u]}\r
|
|
36
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 tg(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}=eg(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}=Qm(e.keyType._def,t);return{...c,propertyNames:d}}return c}function Mk(e,t){if(t.mapStrategy==="record")return tg(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 jk(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 Ok(){return{not:Qt()}}function Nk(){return{type:"null"}}var vl={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Dk(e,t){let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every((o)=>(o._def.typeName in vl)&&(!o._def.checks||!o._def.checks.length))){let o=n.reduce((i,a)=>{let s=vl[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 zk(e,t)}var zk=(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 qk(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[vl[e.innerType._def.typeName],"null"]};let n=Ve(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function $k(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 Lk(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=Fk(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=Uk(e,t);if(a!==void 0)n.additionalProperties=a;return n}function Uk(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 Fk(e){try{return e.isOptional()}catch(t){return!0}}var Bk=(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()},Gk=(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 Jk(e,t){return Ve(e.type._def,t)}function Wk(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 Hk(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 Vk(){return{not:Qt()}}function Zk(){return Qt()}var Kk=(e,t)=>Ve(e.innerType._def,t),Yk=(e,t,n)=>{switch(t){case oe.ZodString:return eg(e,n);case oe.ZodNumber:return $k(e);case oe.ZodObject:return Lk(e,n);case oe.ZodBigInt:return _k(e);case oe.ZodBoolean:return Sk();case oe.ZodDate:return Xm(e,n);case oe.ZodUndefined:return Vk();case oe.ZodNull:return Nk();case oe.ZodArray:return bk(e,n);case oe.ZodUnion:case oe.ZodDiscriminatedUnion:return Dk(e,n);case oe.ZodIntersection:return Rk(e,n);case oe.ZodTuple:return Hk(e,n);case oe.ZodRecord:return tg(e,n);case oe.ZodLiteral:return Ek(e);case oe.ZodEnum:return Ck(e);case oe.ZodNativeEnum:return jk(e);case oe.ZodNullable:return qk(e,n);case oe.ZodOptional:return Bk(e,n);case oe.ZodMap:return Mk(e,n);case oe.ZodSet:return Wk(e,n);case oe.ZodLazy:return()=>e.getter()._def;case oe.ZodPromise:return Jk(e,n);case oe.ZodNaN:case oe.ZodNever:return Ok();case oe.ZodEffects:return Ik(e,n);case oe.ZodAny:return Qt();case oe.ZodUnknown:return Zk();case oe.ZodDefault:return Tk(e,n);case oe.ZodBranded:return Qm(e,n);case oe.ZodReadonly:return Kk(e,n);case oe.ZodCatch:return wk(e,n);case oe.ZodPipeline:return Gk(e,n);case oe.ZodFunction:case oe.ZodVoid:case oe.ZodSymbol:return;default:return((o)=>{return})(t)}},Qk=(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!==yk)return c}if(i&&!n){let c=Xk(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=Yk(e,e.typeName,t),l=typeof s==="function"?Ve(s(),t):s;if(l)eR(e,t,l);if(t.postProcess){let c=t.postProcess(l,e,t);return a.jsonSchema=l,c}return a.jsonSchema=l,l}var Xk=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Qk(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}}},eR=(e,t,n)=>{if(e.description)n.description=e.description;return n},tR=(e)=>{let t=vk(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}]))}},rR=(e,t)=>{var n;let o=tR(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},bl=Symbol.for("vercel.ai.schema");function j(e){let t;return()=>{if(t==null)t=e();return t}}function hi(e,{validate:t}={}){return{[bl]:!0,_type:void 0,get jsonSchema(){if(typeof e==="function")e=e();return e},validate:t}}function nR(e){return typeof e==="object"&&e!==null&&bl in e&&e[bl]===!0&&"jsonSchema"in e&&"validate"in e}function Ut(e){return e==null?hi({type:"object",properties:{},additionalProperties:!1}):nR(e)?e:("~standard"in e)?e["~standard"].vendor==="zod"?M(e):oR(e):e()}function oR(e){return hi(()=>wl(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 iR(e,t){var n;let o=(n=t==null?void 0:t.useReferences)!=null?n:!1;return hi(()=>rR(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 aR(e,t){var n;let o=(n=t==null?void 0:t.useReferences)!=null?n:!1;return hi(()=>wl(Lm(e,{target:"draft-7",io:"input",reused:o?"ref":"inline"})),{validate:async(i)=>{let a=await Um(e,i);return a.success?{success:!0,value:a.data}:{success:!1,error:a.error}}})}function sR(e){return"_zod"in e}function M(e,t){if(sR(e))return aR(e,t);else return iR(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=Ut(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 xl({text:e,schema:t}){try{let n=er(e);if(t==null)return n;return Ee({value:n,schema:t})}catch(n){if(In.isInstance(n)||vt.isInstance(n))throw n;throw new In({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:In.isInstance(n)?n:new In({text:e,cause:n}),rawValue:void 0}}}function Ma({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new fl).pipeThrough(new TransformStream({async transform({data:n},o){if(n==="[DONE]")return;o.enqueue(await xt({text:n,schema:t}))}}))}async function qe({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 Qn({argument:"providerOptions",message:`invalid ${e} provider options`,cause:o.error});return o.value}var lR=()=>globalThis.fetch,Ie=async({url:e,headers:t,body:n,failedResponseHandler:o,successfulResponseHandler:i,abortSignal:a,fetch:s})=>rg({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})=>rg({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:o,successfulResponseHandler:i,abortSignal:a,fetch:s}),rg=async({url:e,headers:t={},body:n,successfulResponseHandler:o,failedResponseHandler:i,abortSignal:a,fetch:s=lR()})=>{try{let l=await s(e,{method:"POST",headers:it(t,`ai-sdk/provider-utils/${Vm}`,ao()),body:n.content,signal:a}),c=io(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 Hm({error:l,url:e,requestBodyValues:n.values})}};function Tl(e){return e}function Il(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})=>Tl({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})=>Tl({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 ng=({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)=>og(l,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:o,shouldRetry:i,getDelayInMs:a,createRetryError:s});async function og(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=gi(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}),og(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 cR=new TextDecoder;async function ig({response:e,url:t}){return cR.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 ig({response:o,url:i}),l=io(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 xl({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=io(t);if(t.body==null)throw new rm({});return{responseHeaders:n,value:Ma({stream:t.body,schema:e})}},xe=(e)=>async({response:t,url:n,requestBodyValues:o})=>{let i=await ig({response:t,url:n}),a=await xt({text:i,schema:e}),s=io(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}},ag=()=>async({response:e,url:t,requestBodyValues:n})=>{let o=io(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 pn(e){return e==null?void 0:e.replace(/\/$/,"")}function uR(e){return e!=null&&typeof e[Symbol.asyncIterator]==="function"}async function*sg({execute:e,input:t,options:n}){let o=e(t,n);if(uR(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 uf=Mn(Ml(),1),df=Mn(Ml(),1),qR="vercel.ai.gateway.error",jl=Symbol.for(qR),vg,bg,ft=class e extends(bg=Error,vg=jl,bg){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[vg]=!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&&jl in t&&t[jl]===!0}},Xg="GatewayAuthenticationError",$R=`vercel.ai.gateway.error.${Xg}`,_g=Symbol.for($R),Sg,wg,Oa=class e extends(wg=ft,Sg=_g,wg){constructor({message:t="Authentication failed",statusCode:n=401,cause:o,generationId:i}={}){super({message:t,statusCode:n,cause:o,generationId:i});this[Sg]=!0,this.name=Xg,this.type="authentication_error"}static isInstance(t){return ft.hasMarker(t)&&_g 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.
|
|
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 tg(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}=eg(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}=Qm(e.keyType._def,t);return{...c,propertyNames:d}}return c}function Mk(e,t){if(t.mapStrategy==="record")return tg(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 jk(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 Ok(){return{not:Qt()}}function Nk(){return{type:"null"}}var vl={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Dk(e,t){let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every((o)=>(o._def.typeName in vl)&&(!o._def.checks||!o._def.checks.length))){let o=n.reduce((i,a)=>{let s=vl[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 zk(e,t)}var zk=(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 $k(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[vl[e.innerType._def.typeName],"null"]};let n=Ve(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function qk(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 Lk(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=Fk(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=Uk(e,t);if(a!==void 0)n.additionalProperties=a;return n}function Uk(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 Fk(e){try{return e.isOptional()}catch(t){return!0}}var Bk=(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()},Gk=(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 Jk(e,t){return Ve(e.type._def,t)}function Wk(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 Hk(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 Vk(){return{not:Qt()}}function Zk(){return Qt()}var Kk=(e,t)=>Ve(e.innerType._def,t),Yk=(e,t,n)=>{switch(t){case oe.ZodString:return eg(e,n);case oe.ZodNumber:return qk(e);case oe.ZodObject:return Lk(e,n);case oe.ZodBigInt:return _k(e);case oe.ZodBoolean:return Sk();case oe.ZodDate:return Xm(e,n);case oe.ZodUndefined:return Vk();case oe.ZodNull:return Nk();case oe.ZodArray:return bk(e,n);case oe.ZodUnion:case oe.ZodDiscriminatedUnion:return Dk(e,n);case oe.ZodIntersection:return Rk(e,n);case oe.ZodTuple:return Hk(e,n);case oe.ZodRecord:return tg(e,n);case oe.ZodLiteral:return Ek(e);case oe.ZodEnum:return Ck(e);case oe.ZodNativeEnum:return jk(e);case oe.ZodNullable:return $k(e,n);case oe.ZodOptional:return Bk(e,n);case oe.ZodMap:return Mk(e,n);case oe.ZodSet:return Wk(e,n);case oe.ZodLazy:return()=>e.getter()._def;case oe.ZodPromise:return Jk(e,n);case oe.ZodNaN:case oe.ZodNever:return Ok();case oe.ZodEffects:return Ik(e,n);case oe.ZodAny:return Qt();case oe.ZodUnknown:return Zk();case oe.ZodDefault:return Tk(e,n);case oe.ZodBranded:return Qm(e,n);case oe.ZodReadonly:return Kk(e,n);case oe.ZodCatch:return wk(e,n);case oe.ZodPipeline:return Gk(e,n);case oe.ZodFunction:case oe.ZodVoid:case oe.ZodSymbol:return;default:return((o)=>{return})(t)}},Qk=(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!==yk)return c}if(i&&!n){let c=Xk(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=Yk(e,e.typeName,t),l=typeof s==="function"?Ve(s(),t):s;if(l)eR(e,t,l);if(t.postProcess){let c=t.postProcess(l,e,t);return a.jsonSchema=l,c}return a.jsonSchema=l,l}var Xk=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Qk(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}}},eR=(e,t,n)=>{if(e.description)n.description=e.description;return n},tR=(e)=>{let t=vk(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}]))}},rR=(e,t)=>{var n;let o=tR(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},bl=Symbol.for("vercel.ai.schema");function j(e){let t;return()=>{if(t==null)t=e();return t}}function hi(e,{validate:t}={}){return{[bl]:!0,_type:void 0,get jsonSchema(){if(typeof e==="function")e=e();return e},validate:t}}function nR(e){return typeof e==="object"&&e!==null&&bl in e&&e[bl]===!0&&"jsonSchema"in e&&"validate"in e}function Ut(e){return e==null?hi({type:"object",properties:{},additionalProperties:!1}):nR(e)?e:("~standard"in e)?e["~standard"].vendor==="zod"?M(e):oR(e):e()}function oR(e){return hi(()=>wl(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 iR(e,t){var n;let o=(n=t==null?void 0:t.useReferences)!=null?n:!1;return hi(()=>rR(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 aR(e,t){var n;let o=(n=t==null?void 0:t.useReferences)!=null?n:!1;return hi(()=>wl(Lm(e,{target:"draft-7",io:"input",reused:o?"ref":"inline"})),{validate:async(i)=>{let a=await Um(e,i);return a.success?{success:!0,value:a.data}:{success:!1,error:a.error}}})}function sR(e){return"_zod"in e}function M(e,t){if(sR(e))return aR(e,t);else return iR(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=Ut(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 xl({text:e,schema:t}){try{let n=er(e);if(t==null)return n;return Ee({value:n,schema:t})}catch(n){if(In.isInstance(n)||vt.isInstance(n))throw n;throw new In({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:In.isInstance(n)?n:new In({text:e,cause:n}),rawValue:void 0}}}function Ma({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new fl).pipeThrough(new TransformStream({async transform({data:n},o){if(n==="[DONE]")return;o.enqueue(await xt({text:n,schema:t}))}}))}async function $e({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 Qn({argument:"providerOptions",message:`invalid ${e} provider options`,cause:o.error});return o.value}var lR=()=>globalThis.fetch,Ie=async({url:e,headers:t,body:n,failedResponseHandler:o,successfulResponseHandler:i,abortSignal:a,fetch:s})=>rg({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})=>rg({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:o,successfulResponseHandler:i,abortSignal:a,fetch:s}),rg=async({url:e,headers:t={},body:n,successfulResponseHandler:o,failedResponseHandler:i,abortSignal:a,fetch:s=lR()})=>{try{let l=await s(e,{method:"POST",headers:it(t,`ai-sdk/provider-utils/${Vm}`,ao()),body:n.content,signal:a}),c=io(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 Hm({error:l,url:e,requestBodyValues:n.values})}};function Tl(e){return e}function Il(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})=>Tl({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})=>Tl({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 ng=({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)=>og(l,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:o,shouldRetry:i,getDelayInMs:a,createRetryError:s});async function og(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=gi(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}),og(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 cR=new TextDecoder;async function ig({response:e,url:t}){return cR.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 ig({response:o,url:i}),l=io(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 xl({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=io(t);if(t.body==null)throw new rm({});return{responseHeaders:n,value:Ma({stream:t.body,schema:e})}},xe=(e)=>async({response:t,url:n,requestBodyValues:o})=>{let i=await ig({response:t,url:n}),a=await xt({text:i,schema:e}),s=io(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}},ag=()=>async({response:e,url:t,requestBodyValues:n})=>{let o=io(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 pn(e){return e==null?void 0:e.replace(/\/$/,"")}function uR(e){return e!=null&&typeof e[Symbol.asyncIterator]==="function"}async function*sg({execute:e,input:t,options:n}){let o=e(t,n);if(uR(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 uf=Mn(Ml(),1),df=Mn(Ml(),1),$R="vercel.ai.gateway.error",jl=Symbol.for($R),vg,bg,ft=class e extends(bg=Error,vg=jl,bg){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[vg]=!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&&jl in t&&t[jl]===!0}},Xg="GatewayAuthenticationError",qR=`vercel.ai.gateway.error.${Xg}`,_g=Symbol.for(qR),Sg,wg,Oa=class e extends(wg=ft,Sg=_g,wg){constructor({message:t="Authentication failed",statusCode:n=401,cause:o,generationId:i}={}){super({message:t,statusCode:n,cause:o,generationId:i});this[Sg]=!0,this.name=Xg,this.type="authentication_error"}static isInstance(t){return ft.hasMarker(t)&&_g 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
38
|
|
|
39
39
|
Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
40
40
|
|
|
@@ -49,9 +49,9 @@ Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
|
49
49
|
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
|
|
50
50
|
|
|
51
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})}},ef="GatewayInvalidRequestError",LR=`vercel.ai.gateway.error.${ef}`,xg=Symbol.for(LR),Tg,Ig,UR=class extends(Ig=ft,Tg=xg,Ig){constructor({message:e="Invalid request",statusCode:t=400,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o});this[Tg]=!0,this.name=ef,this.type="invalid_request_error"}static isInstance(e){return ft.hasMarker(e)&&xg in e}},tf="GatewayRateLimitError",FR=`vercel.ai.gateway.error.${tf}`,Cg=Symbol.for(FR),kg,Rg,BR=class extends(Rg=ft,kg=Cg,Rg){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o});this[kg]=!0,this.name=tf,this.type="rate_limit_exceeded"}static isInstance(e){return ft.hasMarker(e)&&Cg in e}},rf="GatewayModelNotFoundError",GR=`vercel.ai.gateway.error.${rf}`,Eg=Symbol.for(GR),JR=j(()=>M(r.object({modelId:r.string()}))),Ag,Pg,WR=class extends(Pg=ft,Ag=Eg,Pg){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[Ag]=!0,this.name=rf,this.type="model_not_found",this.modelId=n}static isInstance(e){return ft.hasMarker(e)&&Eg in e}},nf="GatewayInternalServerError",HR=`vercel.ai.gateway.error.${nf}`,Mg=Symbol.for(HR),jg,Og,Ng=class extends(Og=ft,jg=Mg,Og){constructor({message:e="Internal server error",statusCode:t=500,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o});this[jg]=!0,this.name=nf,this.type="internal_server_error"}static isInstance(e){return ft.hasMarker(e)&&Mg in e}},of="GatewayFailedDependencyError",VR=`vercel.ai.gateway.error.${of}`,Dg=Symbol.for(VR),zg,
|
|
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})}},ef="GatewayInvalidRequestError",LR=`vercel.ai.gateway.error.${ef}`,xg=Symbol.for(LR),Tg,Ig,UR=class extends(Ig=ft,Tg=xg,Ig){constructor({message:e="Invalid request",statusCode:t=400,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o});this[Tg]=!0,this.name=ef,this.type="invalid_request_error"}static isInstance(e){return ft.hasMarker(e)&&xg in e}},tf="GatewayRateLimitError",FR=`vercel.ai.gateway.error.${tf}`,Cg=Symbol.for(FR),kg,Rg,BR=class extends(Rg=ft,kg=Cg,Rg){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o});this[kg]=!0,this.name=tf,this.type="rate_limit_exceeded"}static isInstance(e){return ft.hasMarker(e)&&Cg in e}},rf="GatewayModelNotFoundError",GR=`vercel.ai.gateway.error.${rf}`,Eg=Symbol.for(GR),JR=j(()=>M(r.object({modelId:r.string()}))),Ag,Pg,WR=class extends(Pg=ft,Ag=Eg,Pg){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[Ag]=!0,this.name=rf,this.type="model_not_found",this.modelId=n}static isInstance(e){return ft.hasMarker(e)&&Eg in e}},nf="GatewayInternalServerError",HR=`vercel.ai.gateway.error.${nf}`,Mg=Symbol.for(HR),jg,Og,Ng=class extends(Og=ft,jg=Mg,Og){constructor({message:e="Internal server error",statusCode:t=500,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o});this[jg]=!0,this.name=nf,this.type="internal_server_error"}static isInstance(e){return ft.hasMarker(e)&&Mg in e}},of="GatewayFailedDependencyError",VR=`vercel.ai.gateway.error.${of}`,Dg=Symbol.for(VR),zg,$g,ZR=class extends($g=ft,zg=Dg,$g){constructor({message:e="Failed dependency",statusCode:t=424,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o});this[zg]=!0,this.name=of,this.type="failed_dependency"}static isInstance(e){return ft.hasMarker(e)&&Dg in e}},af="GatewayForbiddenError",KR=`vercel.ai.gateway.error.${af}`,qg=Symbol.for(KR),Lg,Ug,YR=class extends(Ug=ft,Lg=qg,Ug){constructor({message:e="Forbidden",statusCode:t=403,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o});this[Lg]=!0,this.name=af,this.type="forbidden"}static isInstance(e){return ft.hasMarker(e)&&qg in e}},sf="GatewayResponseError",QR=`vercel.ai.gateway.error.${sf}`,Fg=Symbol.for(QR),Bg,Gg,XR=class extends(Gg=ft,Bg=Fg,Gg){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[Bg]=!0,this.name=sf,this.type="response_error",this.response=n,this.validationError=o}static isInstance(e){return ft.hasMarker(e)&&Fg in e}};async function Jg({response:e,statusCode:t,defaultMessage:n="Gateway request failed",cause:o,authMethod:i}){var a;let s=await pt({value:e,schema:eE});if(!s.success){let m=typeof e==="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new XR({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 UR({message:u,statusCode:t,cause:o,generationId:d});case"rate_limit_exceeded":return new BR({message:u,statusCode:t,cause:o,generationId:d});case"model_not_found":{let m=await pt({value:l.error.param,schema:JR});return new WR({message:u,statusCode:t,modelId:m.success?m.value.modelId:void 0,cause:o,generationId:d})}case"internal_server_error":return new Ng({message:u,statusCode:t,cause:o,generationId:d});case"failed_dependency":return new ZR({message:u,statusCode:t,cause:o,generationId:d});case"forbidden":return new YR({message:u,statusCode:t,cause:o,generationId:d});default:return new Ng({message:u,statusCode:t,cause:o,generationId:d})}}var eE=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 tE(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 lf="GatewayTimeoutError",rE=`vercel.ai.gateway.error.${lf}`,Wg=Symbol.for(rE),Hg,Vg,Zg=class e extends(Vg=ft,Hg=Wg,Vg){constructor({message:t="Request timed out",statusCode:n=408,cause:o,generationId:i}={}){super({message:t,statusCode:n,cause:o,generationId:i});this[Hg]=!0,this.name=lf,this.type="timeout_error"}static isInstance(t){return ft.hasMarker(t)&&Wg in t}static createTimeoutError({originalMessage:t,statusCode:n=408,cause:o,generationId:i}){let a=`Gateway request timed out: ${t}
|
|
53
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 Kg(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(Kg(e))return Zg.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e});if(De.isInstance(e)){if(e.cause&&Kg(e.cause))return Zg.createTimeoutError({originalMessage:e.message,cause:e});return await Jg({response:tE(e),statusCode:(n=e.statusCode)!=null?n:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t})}return await Jg({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}var cf="ai-gateway-auth-method";async function tr(e){let t=await pt({value:e[cf],schema:nE});return t.success?t.value:void 0}var nE=j(()=>M(r.union([r.literal("api-key"),r.literal("oidc")]))),oE=["embedding","image","language","reranking","speech","transcription","video"],Yg=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(iE),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(aE),failedResponseHandler:Qe({errorSchema:r.any(),errorToMessage:(n)=>n}),fetch:this.config.fetch});return t}catch(e){throw await zt(e)}}},iE=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||oE.includes(t.modelType)))}))),aE=j(()=>M(r.object({balance:r.string(),total_used:r.string()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),sE=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(lE),failedResponseHandler:Qe({errorSchema:r.any(),errorToMessage:(i)=>i}),fetch:this.config.fetch});return o}catch(t){throw await zt(t)}}},lE=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}:{}})))}))),cE=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(uE),failedResponseHandler:Qe({errorSchema:r.any(),errorToMessage:(o)=>o}),fetch:this.config.fetch});return n}catch(t){throw await zt(t)}}},uE=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))),dE=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)}}},pE=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(gE),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}}},mE=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()})]),gE=j(()=>M(r.object({embeddings:r.array(r.array(r.number())),usage:r.object({tokens:r.number()}).nullish(),warnings:r.array(mE).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 fE=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)=>Qg(w))},...s&&{mask:Qg(s)}},successfulResponseHandler:xe(bE),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 Qg(e){if(e.type==="file"&&e.data instanceof Uint8Array)return{...e,data:Nt(e.data)};return e}var hE=r.object({images:r.array(r.unknown()).optional()}).catchall(r.unknown()),yE=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()})]),vE=r.object({inputTokens:r.number().nullish(),outputTokens:r.number().nullish(),totalTokens:r.number().nullish()}),bE=r.object({images:r.array(r.string()),warnings:r.array(yE).optional(),providerMetadata:r.record(r.string(),hE).optional(),usage:vE.optional()}),_E=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:Ol(c)},...u&&{frameImages:u.map((w)=>({...w,image:Ol(w.image)}))},...d&&{inputReferences:d.map((w)=>Ol(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:TE}).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 Ol(e){if(e.type==="file"&&e.data instanceof Uint8Array)return{...e,data:Nt(e.data)};return e}var SE=r.object({videos:r.array(r.unknown()).optional()}).catchall(r.unknown()),wE=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()})]),xE=r.discriminatedUnion("type",[r.object({type:r.literal("unsupported"),feature:r.string(),details:r.string().optional()}),r.object({type:r.literal("compatibility"),feature:r.string(),details:r.string().optional()}),r.object({type:r.literal("deprecated"),setting:r.string(),message:r.string()}),r.object({type:r.literal("other"),message:r.string()})]),TE=r.discriminatedUnion("type",[r.object({type:r.literal("result"),videos:r.array(wE),warnings:r.array(xE).optional(),providerMetadata:r.record(r.string(),SE).optional()}),r.object({type:r.literal("error"),message:r.string(),errorType:r.string(),statusCode:r.number(),param:r.unknown().nullable()})]),IE=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(kE),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}}},CE=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()})]),kE=j(()=>M(r.object({ranking:r.array(r.object({index:r.number(),relevanceScore:r.number()})),warnings:r.array(CE).optional(),providerMetadata:r.record(r.string(),r.record(r.string(),r.unknown())).optional()}))),RE=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(PE),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}}},EE=r.object({}).catchall(r.unknown()),AE=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()})]),PE=r.object({audio:r.string(),warnings:r.array(AE).optional(),providerMetadata:r.record(r.string(),EE).optional()}),ME=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(NE),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}}},jE=r.object({}).catchall(r.unknown()),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("deprecated"),setting:r.string(),message:r.string()}),r.object({type:r.literal("other"),message:r.string()})]),NE=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(OE).optional(),providerMetadata:r.record(r.string(),jE).optional()}),DE=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.")}))),zE=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()})]))),qE=Te({id:"gateway.exa_search",inputSchema:DE,outputSchema:zE}),$E=(e={})=>qE(e),LE=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.")}))),UE=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()})]))),FE=Te({id:"gateway.parallel_search",inputSchema:LE,outputSchema:UE}),BE=(e={})=>FE(e),GE=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.")}))),JE=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()})]))),WE=Te({id:"gateway.perplexity_search",inputSchema:GE,outputSchema:JE}),HE=(e={})=>WE(e),VE={exaSearch:$E,parallelSearch:BE,perplexitySearch:HE};async function ZE(){var e;return(e=uf.getContext().headers)==null?void 0:e["x-vercel-id"]}var KE="3.0.145",YE="0.0.1";function QE(e={}){var t,n;let o=null,i=null,a=(t=e.metadataCacheRefreshMillis)!=null?t:300000,s=0,l=(n=pn(e.baseURL))!=null?n:"https://ai-gateway.vercel.sh/v3/ai",c=async()=>{try{let x=await XE(e);return it({Authorization:`Bearer ${x.token}`,"ai-gateway-protocol-version":YE,[cf]:x.authMethod,...e.headers},`ai-sdk/gateway/${KE}`)}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 ZE();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 dE(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 Yg({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 Yg({baseURL:l,headers:c,fetch:e.fetch}).getCredits().catch(async(x)=>{throw await zt(x,await tr(await c()))}),f=async(x)=>new sE({baseURL:l,headers:c,fetch:e.fetch}).getSpendReport(x).catch(async(_)=>{throw await zt(_,await tr(await c()))}),g=async(x)=>new cE({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 fE(x,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:u()}),h.languageModel=d;let v=(x)=>new pE(x,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:u()});h.embeddingModel=v,h.textEmbeddingModel=v,h.videoModel=(x)=>new _E(x,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:u()});let w=(x)=>new IE(x,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:u()});h.rerankingModel=w,h.reranking=w;let S=(x)=>new RE(x,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:u()});h.speechModel=S,h.speech=S;let y=(x)=>new ME(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=VE,h}var pf=QE();async function XE(e){let t=Ar({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(t)return{token:t,authMethod:"api-key"};return{token:await df.getVercelOidcToken(),authMethod:"oidc"}}var wb=Mn(Rc(),1),fo=Mn(Rc(),1);var cM=Object.defineProperty,uM=(e,t)=>{for(var n in t)cM(e,n,{get:t[n],enumerable:!0})},_v="AI_InvalidArgumentError",Sv=`vercel.ai.error.${_v}`,dM=Symbol.for(Sv),wv,at=class extends ie{constructor({parameter:e,value:t,message:n}){super({name:_v,message:`Invalid argument for parameter ${e}: ${n}`});this[wv]=!0,this.parameter=e,this.value=t}static isInstance(e){return ie.hasMarker(e,Sv)}};wv=dM;var pM="AI_InvalidStreamPartError",mM=`vercel.ai.error.${pM}`,gM=Symbol.for(mM),fM;fM=gM;var xv="AI_InvalidToolApprovalError",Tv=`vercel.ai.error.${xv}`,hM=Symbol.for(Tv),Iv,yM=class extends ie{constructor({approvalId:e}){super({name:xv,message:`Tool approval response references unknown approvalId: "${e}". No matching tool-approval-request found in message history.`});this[Iv]=!0,this.approvalId=e}static isInstance(e){return ie.hasMarker(e,Tv)}};Iv=hM;var Cv="AI_InvalidToolApprovalSignatureError",kv=`vercel.ai.error.${Cv}`,vM=Symbol.for(kv),Rv,ov=class extends ie{constructor({approvalId:e,toolCallId:t,reason:n}){super({name:Cv,message:`Tool approval signature verification failed for approval "${e}" (tool call "${t}"): ${n}`});this[Rv]=!0,this.approvalId=e,this.toolCallId=t}static isInstance(e){return ie.hasMarker(e,kv)}};Rv=vM;var Ev="AI_InvalidToolInputError",Av=`vercel.ai.error.${Ev}`,bM=Symbol.for(Av),Pv,Ya=class extends ie{constructor({toolInput:e,toolName:t,cause:n,message:o=`Invalid input for tool ${t}: ${Tr(n)}`}){super({name:Ev,message:o,cause:n});this[Pv]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return ie.hasMarker(e,Av)}};Pv=bM;var Mv="AI_ToolCallNotFoundForApprovalError",jv=`vercel.ai.error.${Mv}`,_M=Symbol.for(jv),Ov,$c=class extends ie{constructor({toolCallId:e,approvalId:t}){super({name:Mv,message:`Tool call "${e}" not found for approval request "${t}".`});this[Ov]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return ie.hasMarker(e,jv)}};Ov=_M;var Nv="AI_MissingToolResultsError",Dv=`vercel.ai.error.${Nv}`,SM=Symbol.for(Dv),zv,iv=class extends ie{constructor({toolCallIds:e}){super({name:Nv,message:`Tool result${e.length>1?"s are":" is"} missing for tool call${e.length>1?"s":""} ${e.join(", ")}.`});this[zv]=!0,this.toolCallIds=e}static isInstance(e){return ie.hasMarker(e,Dv)}};zv=SM;var qv="AI_NoImageGeneratedError",$v=`vercel.ai.error.${qv}`,wM=Symbol.for($v),Lv,xM=class extends ie{constructor({message:e="No image generated.",cause:t,responses:n}){super({name:qv,message:e,cause:t});this[Lv]=!0,this.responses=n}static isInstance(e){return ie.hasMarker(e,$v)}};Lv=wM;var Uv="AI_NoObjectGeneratedError",Fv=`vercel.ai.error.${Uv}`,TM=Symbol.for(Fv),Bv,Ft=class extends ie{constructor({message:e="No object generated.",cause:t,text:n,response:o,usage:i,finishReason:a}){super({name:Uv,message:e,cause:t});this[Bv]=!0,this.text=n,this.response=o,this.usage=i,this.finishReason=a}static isInstance(e){return ie.hasMarker(e,Fv)}};Bv=TM;var Gv="AI_NoOutputGeneratedError",Jv=`vercel.ai.error.${Gv}`,IM=Symbol.for(Jv),Wv,Wa=class extends ie{constructor({message:e="No output generated.",cause:t}={}){super({name:Gv,message:e,cause:t});this[Wv]=!0}static isInstance(e){return ie.hasMarker(e,Jv)}};Wv=IM;var CM="AI_NoSpeechGeneratedError",kM=`vercel.ai.error.${CM}`,RM=Symbol.for(kM),EM;EM=RM;var AM="AI_NoTranscriptGeneratedError",PM=`vercel.ai.error.${AM}`,MM=Symbol.for(PM),jM;jM=MM;var OM="AI_NoVideoGeneratedError",NM=`vercel.ai.error.${OM}`,DM=Symbol.for(NM),zM;zM=DM;var Hv="AI_NoSuchToolError",Vv=`vercel.ai.error.${Hv}`,qM=Symbol.for(Vv),Zv,Pc=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:Hv,message:n});this[Zv]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return ie.hasMarker(e,Vv)}};Zv=qM;var Kv="AI_ToolCallRepairError",Yv=`vercel.ai.error.${Kv}`,$M=Symbol.for(Yv),Qv,LM=class extends ie{constructor({cause:e,originalError:t,message:n=`Error repairing tool call: ${Tr(e)}`}){super({name:Kv,message:n,cause:e});this[Qv]=!0,this.originalError=t}static isInstance(e){return ie.hasMarker(e,Yv)}};Qv=$M;var Lc=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}},Xv="AI_UIMessageStreamError",eb=`vercel.ai.error.${Xv}`,UM=Symbol.for(eb),tb,mo=class extends ie{constructor({chunkType:e,chunkId:t,message:n}){super({name:Xv,message:n});this[tb]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return ie.hasMarker(e,eb)}};tb=UM;var rb="AI_InvalidDataContentError",nb=`vercel.ai.error.${rb}`,FM=Symbol.for(nb),ob,av=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:rb,message:n,cause:t});this[ob]=!0,this.content=e}static isInstance(e){return ie.hasMarker(e,nb)}};ob=FM;var ib="AI_InvalidMessageRoleError",ab=`vercel.ai.error.${ib}`,BM=Symbol.for(ab),sb,GM=class extends ie{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:ib,message:t});this[sb]=!0,this.role=e}static isInstance(e){return ie.hasMarker(e,ab)}};sb=BM;var JM="AI_MessageConversionError",WM=`vercel.ai.error.${JM}`,HM=Symbol.for(WM),VM;VM=HM;var lb="AI_RetryError",cb=`vercel.ai.error.${lb}`,ZM=Symbol.for(cb),ub,KM=class extends ie{constructor({message:e,reason:t,errors:n}){super({name:lb,message:e});this[ub]=!0,this.reason=t,this.errors=n,this.lastError=n[n.length-1]}static isInstance(e){return ie.hasMarker(e,cb)}};ub=ZM;function Nn(e){return e===void 0?[]:Array.isArray(e)?e:[e]}async function mr(e){for(let t of Nn(e.callbacks)){if(t==null)continue;try{await t(e.event)}catch(n){}}}function YM({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 QM="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",sv=!1,mn=(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(!sv)sv=!0,console.info(QM);for(let n of e.warnings)console.warn(YM({warning:n,provider:e.provider,model:e.model}))};function Uc({provider:e,modelId:t}){mn({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}function XM(e){if(e.specificationVersion==="v3")return e;return Uc({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,n){if(n==="specificationVersion")return"v3";return t[n]}})}function ej(e){if(e.specificationVersion==="v3")return e;return Uc({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,n){if(n==="specificationVersion")return"v3";return t[n]}})}function tj(e){if(e.specificationVersion==="v3")return e;return Uc({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:db(i.finishReason),usage:pb(i.usage)}};case"doStream":return async(...o)=>{let i=await t.doStream(...o);return{...i,stream:rj(i.stream)}};default:return t[n]}}})}function rj(e){return e.pipeThrough(new TransformStream({transform(t,n){switch(t.type){case"finish":n.enqueue({...t,finishReason:db(t.finishReason),usage:pb(t.usage)});break;default:n.enqueue(t);break}}}))}function db(e){return{unified:e==="unknown"?"other":e,raw:void 0}}function pb(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 Ii(e){if(typeof e!=="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){let t=e;throw new Lc({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return tj(e)}return Fc().languageModel(e)}function mb(e){if(typeof e!=="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){let t=e;throw new Lc({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return XM(e)}return Fc().embeddingModel(e)}function nj(e){if(typeof e!=="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){let t=e;throw new Lc({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return ej(e)}return Fc().imageModel(e)}function Fc(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:pf}function Bc(e){if(e==null)return;if(typeof e==="number")return e;return e.totalMs}function gb(e){if(e==null||typeof e==="number")return;return e.stepMs}function oj(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 ij=(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 aj(e){return typeof e==="string"&&e.startsWith("SUQz")||typeof e!=="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?ij(e):e}function Za({data:e,signatures:t}){let n=aj(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 ho="6.0.221",fb=async({url:e,maxBytes:t,abortSignal:n})=>{var o;let i=e.toString();try{let a=it({},`ai-sdk/${ho}`,ao()),s=await _l({url:i,headers:a,abortSignal:n});if(!s.ok)throw await mi(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})}},sj=(e=fb)=>(t)=>Promise.all(t.map(async(n)=>n.isUrlSupportedByModel?null:e(n)));function hb(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 yb=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 Gc(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}=hb(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 Mc(e){if(typeof e==="string")return e;if(e instanceof ArrayBuffer)return Nt(new Uint8Array(e));return Nt(e)}function lj(e){if(e instanceof Uint8Array)return e;if(typeof e==="string")try{return wt(e)}catch(t){throw new av({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 av({content:e})}async function Jc({prompt:e,supportedUrls:t,download:n=sj()}){let o=await uj(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}]:Nn(e.system).map((u)=>({role:"system",content:u.content,providerOptions:u.providerOptions})):[],...e.messages.map((u)=>cj({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 iv({toolCallIds:Array.from(c)});break}for(let u of a)c.delete(u);if(c.size>0)throw new iv({toolCallIds:Array.from(c)});return l.filter((u)=>u.role!=="tool"||u.content.length>0)}function cj({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)=>dj(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}=Gc(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:lv({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:lv({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 GM({role:n})}}async function uj(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}=Gc(l.data);return{mediaType:c,data:u}}).filter((l)=>l.data instanceof URL).map((l)=>({url:l.data,isUrlSupportedByModel:l.mediaType!=null&&Km({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 dj(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}=Gc(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 lv({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:Mc(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:Mc(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 Ti({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:cv(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:cv(n)}}function cv(e){return e===void 0?null:e}function Ci({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 pj(e){return e!=null&&Object.keys(e).length>0}async function vb({tools:e,toolChoice:t,activeTools:n}){if(!pj(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 Ut(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 Dn=r.lazy(()=>r.union([r.null(),r.string(),r.number(),r.boolean(),r.record(r.string(),Dn.optional()),r.array(Dn)])),fe=r.record(r.string(),r.record(r.string(),Dn.optional())),bb=r.object({type:r.literal("text"),text:r.string(),providerOptions:fe.optional()}),mj=r.object({type:r.literal("image"),image:r.union([yb,r.instanceof(URL)]),mediaType:r.string().optional(),providerOptions:fe.optional()}),_b=r.object({type:r.literal("file"),data:r.union([yb,r.instanceof(URL)]),filename:r.string().optional(),mediaType:r.string(),providerOptions:fe.optional()}),gj=r.object({type:r.literal("reasoning"),text:r.string(),providerOptions:fe.optional()}),fj=r.object({type:r.literal("tool-call"),toolCallId:r.string(),toolName:r.string(),input:r.unknown(),providerOptions:fe.optional(),providerExecuted:r.boolean().optional()}),hj=r.discriminatedUnion("type",[r.object({type:r.literal("text"),value:r.string(),providerOptions:fe.optional()}),r.object({type:r.literal("json"),value:Dn,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:Dn,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()})]))})]),Sb=r.object({type:r.literal("tool-result"),toolCallId:r.string(),toolName:r.string(),output:hj,providerOptions:fe.optional()}),yj=r.object({type:r.literal("tool-approval-request"),approvalId:r.string(),toolCallId:r.string()}),vj=r.object({type:r.literal("tool-approval-response"),approvalId:r.string(),approved:r.boolean(),reason:r.string().optional()}),bj=r.object({role:r.literal("system"),content:r.string(),providerOptions:fe.optional()}),_j=r.object({role:r.literal("user"),content:r.union([r.string(),r.array(r.union([bb,mj,_b]))]),providerOptions:fe.optional()}),Sj=r.object({role:r.literal("assistant"),content:r.union([r.string(),r.array(r.union([bb,_b,gj,fj,Sb,yj]))]),providerOptions:fe.optional()}),wj=r.object({role:r.literal("tool"),content:r.array(r.union([Sb,vj])),providerOptions:fe.optional()}),xj=r.union([bj,_j,Sj,wj]);async function Wc({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"&&!Nn(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(xj)});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 Hc(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
|
|
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 Kg(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(Kg(e))return Zg.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e});if(De.isInstance(e)){if(e.cause&&Kg(e.cause))return Zg.createTimeoutError({originalMessage:e.message,cause:e});return await Jg({response:tE(e),statusCode:(n=e.statusCode)!=null?n:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t})}return await Jg({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}var cf="ai-gateway-auth-method";async function tr(e){let t=await pt({value:e[cf],schema:nE});return t.success?t.value:void 0}var nE=j(()=>M(r.union([r.literal("api-key"),r.literal("oidc")]))),oE=["embedding","image","language","reranking","speech","transcription","video"],Yg=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(iE),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(aE),failedResponseHandler:Qe({errorSchema:r.any(),errorToMessage:(n)=>n}),fetch:this.config.fetch});return t}catch(e){throw await zt(e)}}},iE=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||oE.includes(t.modelType)))}))),aE=j(()=>M(r.object({balance:r.string(),total_used:r.string()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),sE=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(lE),failedResponseHandler:Qe({errorSchema:r.any(),errorToMessage:(i)=>i}),fetch:this.config.fetch});return o}catch(t){throw await zt(t)}}},lE=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}:{}})))}))),cE=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(uE),failedResponseHandler:Qe({errorSchema:r.any(),errorToMessage:(o)=>o}),fetch:this.config.fetch});return n}catch(t){throw await zt(t)}}},uE=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))),dE=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)}}},pE=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(gE),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}}},mE=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()})]),gE=j(()=>M(r.object({embeddings:r.array(r.array(r.number())),usage:r.object({tokens:r.number()}).nullish(),warnings:r.array(mE).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 fE=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)=>Qg(w))},...s&&{mask:Qg(s)}},successfulResponseHandler:xe(bE),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 Qg(e){if(e.type==="file"&&e.data instanceof Uint8Array)return{...e,data:Nt(e.data)};return e}var hE=r.object({images:r.array(r.unknown()).optional()}).catchall(r.unknown()),yE=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()})]),vE=r.object({inputTokens:r.number().nullish(),outputTokens:r.number().nullish(),totalTokens:r.number().nullish()}),bE=r.object({images:r.array(r.string()),warnings:r.array(yE).optional(),providerMetadata:r.record(r.string(),hE).optional(),usage:vE.optional()}),_E=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:Ol(c)},...u&&{frameImages:u.map((w)=>({...w,image:Ol(w.image)}))},...d&&{inputReferences:d.map((w)=>Ol(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:TE}).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 Ol(e){if(e.type==="file"&&e.data instanceof Uint8Array)return{...e,data:Nt(e.data)};return e}var SE=r.object({videos:r.array(r.unknown()).optional()}).catchall(r.unknown()),wE=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()})]),xE=r.discriminatedUnion("type",[r.object({type:r.literal("unsupported"),feature:r.string(),details:r.string().optional()}),r.object({type:r.literal("compatibility"),feature:r.string(),details:r.string().optional()}),r.object({type:r.literal("deprecated"),setting:r.string(),message:r.string()}),r.object({type:r.literal("other"),message:r.string()})]),TE=r.discriminatedUnion("type",[r.object({type:r.literal("result"),videos:r.array(wE),warnings:r.array(xE).optional(),providerMetadata:r.record(r.string(),SE).optional()}),r.object({type:r.literal("error"),message:r.string(),errorType:r.string(),statusCode:r.number(),param:r.unknown().nullable()})]),IE=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(kE),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}}},CE=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()})]),kE=j(()=>M(r.object({ranking:r.array(r.object({index:r.number(),relevanceScore:r.number()})),warnings:r.array(CE).optional(),providerMetadata:r.record(r.string(),r.record(r.string(),r.unknown())).optional()}))),RE=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(PE),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}}},EE=r.object({}).catchall(r.unknown()),AE=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()})]),PE=r.object({audio:r.string(),warnings:r.array(AE).optional(),providerMetadata:r.record(r.string(),EE).optional()}),ME=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(NE),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}}},jE=r.object({}).catchall(r.unknown()),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("deprecated"),setting:r.string(),message:r.string()}),r.object({type:r.literal("other"),message:r.string()})]),NE=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(OE).optional(),providerMetadata:r.record(r.string(),jE).optional()}),DE=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.")}))),zE=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()})]))),$E=Te({id:"gateway.exa_search",inputSchema:DE,outputSchema:zE}),qE=(e={})=>$E(e),LE=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.")}))),UE=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()})]))),FE=Te({id:"gateway.parallel_search",inputSchema:LE,outputSchema:UE}),BE=(e={})=>FE(e),GE=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.")}))),JE=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()})]))),WE=Te({id:"gateway.perplexity_search",inputSchema:GE,outputSchema:JE}),HE=(e={})=>WE(e),VE={exaSearch:qE,parallelSearch:BE,perplexitySearch:HE};async function ZE(){var e;return(e=uf.getContext().headers)==null?void 0:e["x-vercel-id"]}var KE="3.0.145",YE="0.0.1";function QE(e={}){var t,n;let o=null,i=null,a=(t=e.metadataCacheRefreshMillis)!=null?t:300000,s=0,l=(n=pn(e.baseURL))!=null?n:"https://ai-gateway.vercel.sh/v3/ai",c=async()=>{try{let x=await XE(e);return it({Authorization:`Bearer ${x.token}`,"ai-gateway-protocol-version":YE,[cf]:x.authMethod,...e.headers},`ai-sdk/gateway/${KE}`)}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 ZE();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 dE(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 Yg({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 Yg({baseURL:l,headers:c,fetch:e.fetch}).getCredits().catch(async(x)=>{throw await zt(x,await tr(await c()))}),f=async(x)=>new sE({baseURL:l,headers:c,fetch:e.fetch}).getSpendReport(x).catch(async(_)=>{throw await zt(_,await tr(await c()))}),g=async(x)=>new cE({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 fE(x,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:u()}),h.languageModel=d;let v=(x)=>new pE(x,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:u()});h.embeddingModel=v,h.textEmbeddingModel=v,h.videoModel=(x)=>new _E(x,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:u()});let w=(x)=>new IE(x,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:u()});h.rerankingModel=w,h.reranking=w;let S=(x)=>new RE(x,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:u()});h.speechModel=S,h.speech=S;let y=(x)=>new ME(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=VE,h}var pf=QE();async function XE(e){let t=Ar({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(t)return{token:t,authMethod:"api-key"};return{token:await df.getVercelOidcToken(),authMethod:"oidc"}}var wb=Mn(Rc(),1),fo=Mn(Rc(),1);var cM=Object.defineProperty,uM=(e,t)=>{for(var n in t)cM(e,n,{get:t[n],enumerable:!0})},_v="AI_InvalidArgumentError",Sv=`vercel.ai.error.${_v}`,dM=Symbol.for(Sv),wv,at=class extends ie{constructor({parameter:e,value:t,message:n}){super({name:_v,message:`Invalid argument for parameter ${e}: ${n}`});this[wv]=!0,this.parameter=e,this.value=t}static isInstance(e){return ie.hasMarker(e,Sv)}};wv=dM;var pM="AI_InvalidStreamPartError",mM=`vercel.ai.error.${pM}`,gM=Symbol.for(mM),fM;fM=gM;var xv="AI_InvalidToolApprovalError",Tv=`vercel.ai.error.${xv}`,hM=Symbol.for(Tv),Iv,yM=class extends ie{constructor({approvalId:e}){super({name:xv,message:`Tool approval response references unknown approvalId: "${e}". No matching tool-approval-request found in message history.`});this[Iv]=!0,this.approvalId=e}static isInstance(e){return ie.hasMarker(e,Tv)}};Iv=hM;var Cv="AI_InvalidToolApprovalSignatureError",kv=`vercel.ai.error.${Cv}`,vM=Symbol.for(kv),Rv,ov=class extends ie{constructor({approvalId:e,toolCallId:t,reason:n}){super({name:Cv,message:`Tool approval signature verification failed for approval "${e}" (tool call "${t}"): ${n}`});this[Rv]=!0,this.approvalId=e,this.toolCallId=t}static isInstance(e){return ie.hasMarker(e,kv)}};Rv=vM;var Ev="AI_InvalidToolInputError",Av=`vercel.ai.error.${Ev}`,bM=Symbol.for(Av),Pv,Ya=class extends ie{constructor({toolInput:e,toolName:t,cause:n,message:o=`Invalid input for tool ${t}: ${Tr(n)}`}){super({name:Ev,message:o,cause:n});this[Pv]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return ie.hasMarker(e,Av)}};Pv=bM;var Mv="AI_ToolCallNotFoundForApprovalError",jv=`vercel.ai.error.${Mv}`,_M=Symbol.for(jv),Ov,qc=class extends ie{constructor({toolCallId:e,approvalId:t}){super({name:Mv,message:`Tool call "${e}" not found for approval request "${t}".`});this[Ov]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return ie.hasMarker(e,jv)}};Ov=_M;var Nv="AI_MissingToolResultsError",Dv=`vercel.ai.error.${Nv}`,SM=Symbol.for(Dv),zv,iv=class extends ie{constructor({toolCallIds:e}){super({name:Nv,message:`Tool result${e.length>1?"s are":" is"} missing for tool call${e.length>1?"s":""} ${e.join(", ")}.`});this[zv]=!0,this.toolCallIds=e}static isInstance(e){return ie.hasMarker(e,Dv)}};zv=SM;var $v="AI_NoImageGeneratedError",qv=`vercel.ai.error.${$v}`,wM=Symbol.for(qv),Lv,xM=class extends ie{constructor({message:e="No image generated.",cause:t,responses:n}){super({name:$v,message:e,cause:t});this[Lv]=!0,this.responses=n}static isInstance(e){return ie.hasMarker(e,qv)}};Lv=wM;var Uv="AI_NoObjectGeneratedError",Fv=`vercel.ai.error.${Uv}`,TM=Symbol.for(Fv),Bv,Ft=class extends ie{constructor({message:e="No object generated.",cause:t,text:n,response:o,usage:i,finishReason:a}){super({name:Uv,message:e,cause:t});this[Bv]=!0,this.text=n,this.response=o,this.usage=i,this.finishReason=a}static isInstance(e){return ie.hasMarker(e,Fv)}};Bv=TM;var Gv="AI_NoOutputGeneratedError",Jv=`vercel.ai.error.${Gv}`,IM=Symbol.for(Jv),Wv,Wa=class extends ie{constructor({message:e="No output generated.",cause:t}={}){super({name:Gv,message:e,cause:t});this[Wv]=!0}static isInstance(e){return ie.hasMarker(e,Jv)}};Wv=IM;var CM="AI_NoSpeechGeneratedError",kM=`vercel.ai.error.${CM}`,RM=Symbol.for(kM),EM;EM=RM;var AM="AI_NoTranscriptGeneratedError",PM=`vercel.ai.error.${AM}`,MM=Symbol.for(PM),jM;jM=MM;var OM="AI_NoVideoGeneratedError",NM=`vercel.ai.error.${OM}`,DM=Symbol.for(NM),zM;zM=DM;var Hv="AI_NoSuchToolError",Vv=`vercel.ai.error.${Hv}`,$M=Symbol.for(Vv),Zv,Pc=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:Hv,message:n});this[Zv]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return ie.hasMarker(e,Vv)}};Zv=$M;var Kv="AI_ToolCallRepairError",Yv=`vercel.ai.error.${Kv}`,qM=Symbol.for(Yv),Qv,LM=class extends ie{constructor({cause:e,originalError:t,message:n=`Error repairing tool call: ${Tr(e)}`}){super({name:Kv,message:n,cause:e});this[Qv]=!0,this.originalError=t}static isInstance(e){return ie.hasMarker(e,Yv)}};Qv=qM;var Lc=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}},Xv="AI_UIMessageStreamError",eb=`vercel.ai.error.${Xv}`,UM=Symbol.for(eb),tb,mo=class extends ie{constructor({chunkType:e,chunkId:t,message:n}){super({name:Xv,message:n});this[tb]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return ie.hasMarker(e,eb)}};tb=UM;var rb="AI_InvalidDataContentError",nb=`vercel.ai.error.${rb}`,FM=Symbol.for(nb),ob,av=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:rb,message:n,cause:t});this[ob]=!0,this.content=e}static isInstance(e){return ie.hasMarker(e,nb)}};ob=FM;var ib="AI_InvalidMessageRoleError",ab=`vercel.ai.error.${ib}`,BM=Symbol.for(ab),sb,GM=class extends ie{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:ib,message:t});this[sb]=!0,this.role=e}static isInstance(e){return ie.hasMarker(e,ab)}};sb=BM;var JM="AI_MessageConversionError",WM=`vercel.ai.error.${JM}`,HM=Symbol.for(WM),VM;VM=HM;var lb="AI_RetryError",cb=`vercel.ai.error.${lb}`,ZM=Symbol.for(cb),ub,KM=class extends ie{constructor({message:e,reason:t,errors:n}){super({name:lb,message:e});this[ub]=!0,this.reason=t,this.errors=n,this.lastError=n[n.length-1]}static isInstance(e){return ie.hasMarker(e,cb)}};ub=ZM;function Nn(e){return e===void 0?[]:Array.isArray(e)?e:[e]}async function mr(e){for(let t of Nn(e.callbacks)){if(t==null)continue;try{await t(e.event)}catch(n){}}}function YM({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 QM="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",sv=!1,mn=(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(!sv)sv=!0,console.info(QM);for(let n of e.warnings)console.warn(YM({warning:n,provider:e.provider,model:e.model}))};function Uc({provider:e,modelId:t}){mn({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}function XM(e){if(e.specificationVersion==="v3")return e;return Uc({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,n){if(n==="specificationVersion")return"v3";return t[n]}})}function ej(e){if(e.specificationVersion==="v3")return e;return Uc({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,n){if(n==="specificationVersion")return"v3";return t[n]}})}function tj(e){if(e.specificationVersion==="v3")return e;return Uc({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:db(i.finishReason),usage:pb(i.usage)}};case"doStream":return async(...o)=>{let i=await t.doStream(...o);return{...i,stream:rj(i.stream)}};default:return t[n]}}})}function rj(e){return e.pipeThrough(new TransformStream({transform(t,n){switch(t.type){case"finish":n.enqueue({...t,finishReason:db(t.finishReason),usage:pb(t.usage)});break;default:n.enqueue(t);break}}}))}function db(e){return{unified:e==="unknown"?"other":e,raw:void 0}}function pb(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 Ii(e){if(typeof e!=="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){let t=e;throw new Lc({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return tj(e)}return Fc().languageModel(e)}function mb(e){if(typeof e!=="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){let t=e;throw new Lc({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return XM(e)}return Fc().embeddingModel(e)}function nj(e){if(typeof e!=="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){let t=e;throw new Lc({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return ej(e)}return Fc().imageModel(e)}function Fc(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:pf}function Bc(e){if(e==null)return;if(typeof e==="number")return e;return e.totalMs}function gb(e){if(e==null||typeof e==="number")return;return e.stepMs}function oj(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 ij=(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 aj(e){return typeof e==="string"&&e.startsWith("SUQz")||typeof e!=="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?ij(e):e}function Za({data:e,signatures:t}){let n=aj(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 ho="6.0.221",fb=async({url:e,maxBytes:t,abortSignal:n})=>{var o;let i=e.toString();try{let a=it({},`ai-sdk/${ho}`,ao()),s=await _l({url:i,headers:a,abortSignal:n});if(!s.ok)throw await mi(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})}},sj=(e=fb)=>(t)=>Promise.all(t.map(async(n)=>n.isUrlSupportedByModel?null:e(n)));function hb(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 yb=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 Gc(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}=hb(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 Mc(e){if(typeof e==="string")return e;if(e instanceof ArrayBuffer)return Nt(new Uint8Array(e));return Nt(e)}function lj(e){if(e instanceof Uint8Array)return e;if(typeof e==="string")try{return wt(e)}catch(t){throw new av({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 av({content:e})}async function Jc({prompt:e,supportedUrls:t,download:n=sj()}){let o=await uj(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}]:Nn(e.system).map((u)=>({role:"system",content:u.content,providerOptions:u.providerOptions})):[],...e.messages.map((u)=>cj({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 iv({toolCallIds:Array.from(c)});break}for(let u of a)c.delete(u);if(c.size>0)throw new iv({toolCallIds:Array.from(c)});return l.filter((u)=>u.role!=="tool"||u.content.length>0)}function cj({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)=>dj(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}=Gc(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:lv({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:lv({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 GM({role:n})}}async function uj(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}=Gc(l.data);return{mediaType:c,data:u}}).filter((l)=>l.data instanceof URL).map((l)=>({url:l.data,isUrlSupportedByModel:l.mediaType!=null&&Km({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 dj(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}=Gc(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 lv({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:Mc(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:Mc(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 Ti({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:cv(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:cv(n)}}function cv(e){return e===void 0?null:e}function Ci({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 pj(e){return e!=null&&Object.keys(e).length>0}async function vb({tools:e,toolChoice:t,activeTools:n}){if(!pj(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 Ut(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 Dn=r.lazy(()=>r.union([r.null(),r.string(),r.number(),r.boolean(),r.record(r.string(),Dn.optional()),r.array(Dn)])),fe=r.record(r.string(),r.record(r.string(),Dn.optional())),bb=r.object({type:r.literal("text"),text:r.string(),providerOptions:fe.optional()}),mj=r.object({type:r.literal("image"),image:r.union([yb,r.instanceof(URL)]),mediaType:r.string().optional(),providerOptions:fe.optional()}),_b=r.object({type:r.literal("file"),data:r.union([yb,r.instanceof(URL)]),filename:r.string().optional(),mediaType:r.string(),providerOptions:fe.optional()}),gj=r.object({type:r.literal("reasoning"),text:r.string(),providerOptions:fe.optional()}),fj=r.object({type:r.literal("tool-call"),toolCallId:r.string(),toolName:r.string(),input:r.unknown(),providerOptions:fe.optional(),providerExecuted:r.boolean().optional()}),hj=r.discriminatedUnion("type",[r.object({type:r.literal("text"),value:r.string(),providerOptions:fe.optional()}),r.object({type:r.literal("json"),value:Dn,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:Dn,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()})]))})]),Sb=r.object({type:r.literal("tool-result"),toolCallId:r.string(),toolName:r.string(),output:hj,providerOptions:fe.optional()}),yj=r.object({type:r.literal("tool-approval-request"),approvalId:r.string(),toolCallId:r.string()}),vj=r.object({type:r.literal("tool-approval-response"),approvalId:r.string(),approved:r.boolean(),reason:r.string().optional()}),bj=r.object({role:r.literal("system"),content:r.string(),providerOptions:fe.optional()}),_j=r.object({role:r.literal("user"),content:r.union([r.string(),r.array(r.union([bb,mj,_b]))]),providerOptions:fe.optional()}),Sj=r.object({role:r.literal("assistant"),content:r.union([r.string(),r.array(r.union([bb,_b,gj,fj,Sb,yj]))]),providerOptions:fe.optional()}),wj=r.object({role:r.literal("tool"),content:r.array(r.union([Sb,vj])),providerOptions:fe.optional()}),xj=r.union([bj,_j,Sj,wj]);async function Wc({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"&&!Nn(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(xj)});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 Hc(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
55
|
|
|
56
56
|
To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
|
|
57
57
|
|
|
@@ -59,16 +59,16 @@ Alternatively, you can use a provider module instead of the AI Gateway.
|
|
|
59
59
|
|
|
60
60
|
Learn more: \x1B[34m${n}\x1B[0m
|
|
61
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 Ri({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=Bc(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 Tj={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 Ij},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}},Ij={traceId:"",spanId:"",traceFlags:0};function Ei({isEnabled:e=!1,tracer:t}={}){if(!e)return Tj;if(t)return t;return wb.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=fo.context.active();try{let l=await fo.context.with(s,()=>o(a));if(i)a.end();return l}catch(l){try{xb(a,l)}finally{a.end()}throw l}})}function xb(e,t){if(t instanceof Error)e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:fo.SpanStatusCode.ERROR,message:t.message});else e.setStatus({code:fo.SpanStatusCode.ERROR})}function Cj(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"}function Ec(e){if(!Array.isArray(e))return e;let t=new Set(e.filter(Cj).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=Ec(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=Ec(s);if(l!=null)n[o]=l}continue}let a=Ec(i);if(a!=null)n[o]=a}return n}function Vc(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?Mc(n.data):n.data}:n)})))}function kj(){var e;return(e=globalThis.AI_SDK_TELEMETRY_INTEGRATIONS)!=null?e:[]}function Tb(){let e=kj();return(t)=>{let n=Nn(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 ki(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 Ac(){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 Ib(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 Rj(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 Ej({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 Aj=({maxRetries:e=2,initialDelayInMs:t=2000,backoffFactor:n=2,abortSignal:o}={})=>ng({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})=>Ej({error:i,exponentialBackoffDelay:a}),createRetryError:({message:i,reason:a,errors:s})=>new KM({message:i,reason:a,errors:s})});function yo({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:Aj({maxRetries:n,abortSignal:t})}}function jc({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 Cb({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 yM({approvalId:c.approvalId});if(i[u.toolCallId]!=null)continue;let d=n[u.toolCallId];if(d==null)throw new $c({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 Ha(){var e,t;return(t=(e=globalThis==null?void 0:globalThis.performance)==null?void 0:e.now())!=null?t:Date.now()}async function Zc({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=Ha();try{let _=sg({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=Ha()-y;return await mr({event:{...v,success:!1,error:_,durationMs:C},callbacks:m}),xb(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=Ha()-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 Oc(e){let t=e.filter((n)=>n.type==="reasoning");return t.length===0?void 0:t.map((n)=>n.text).join(`
|
|
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 Ri({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=Bc(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 Tj={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 Ij},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}},Ij={traceId:"",spanId:"",traceFlags:0};function Ei({isEnabled:e=!1,tracer:t}={}){if(!e)return Tj;if(t)return t;return wb.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=fo.context.active();try{let l=await fo.context.with(s,()=>o(a));if(i)a.end();return l}catch(l){try{xb(a,l)}finally{a.end()}throw l}})}function xb(e,t){if(t instanceof Error)e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:fo.SpanStatusCode.ERROR,message:t.message});else e.setStatus({code:fo.SpanStatusCode.ERROR})}function Cj(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"}function Ec(e){if(!Array.isArray(e))return e;let t=new Set(e.filter(Cj).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=Ec(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=Ec(s);if(l!=null)n[o]=l}continue}let a=Ec(i);if(a!=null)n[o]=a}return n}function Vc(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?Mc(n.data):n.data}:n)})))}function kj(){var e;return(e=globalThis.AI_SDK_TELEMETRY_INTEGRATIONS)!=null?e:[]}function Tb(){let e=kj();return(t)=>{let n=Nn(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 ki(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 Ac(){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 Ib(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 Rj(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 Ej({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 Aj=({maxRetries:e=2,initialDelayInMs:t=2000,backoffFactor:n=2,abortSignal:o}={})=>ng({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})=>Ej({error:i,exponentialBackoffDelay:a}),createRetryError:({message:i,reason:a,errors:s})=>new KM({message:i,reason:a,errors:s})});function yo({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:Aj({maxRetries:n,abortSignal:t})}}function jc({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 Cb({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 yM({approvalId:c.approvalId});if(i[u.toolCallId]!=null)continue;let d=n[u.toolCallId];if(d==null)throw new qc({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 Ha(){var e,t;return(t=(e=globalThis==null?void 0:globalThis.performance)==null?void 0:e.now())!=null?t:Date.now()}async function Zc({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=Ha();try{let _=sg({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=Ha()-y;return await mr({event:{...v,success:!1,error:_,durationMs:C},callbacks:m}),xb(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=Ha()-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 Oc(e){let t=e.filter((n)=>n.type==="reasoning");return t.length===0?void 0:t.map((n)=>n.text).join(`
|
|
63
63
|
`)}function Nc(e){let t=e.filter((n)=>n.type==="text");if(t.length===0)return;return t.map((n)=>n.text).join("")}var Kc=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}},Pj=class extends Kc{constructor(e){super(e);this.type="file"}};async function Yc({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 Qc=new TextEncoder;function Dc(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(Dc).join(",")}]`;return`{${Object.keys(e).sort().map((o)=>`${JSON.stringify(o)}:${Dc(e[o])}`).join(",")}}`}function kb(e){return Nt(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Mj(e){return wt(e)}async function Rb(e){let t=typeof e==="string"?Qc.encode(e):e;return crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}async function Eb(e){let t=Dc(e),n=await crypto.subtle.digest("SHA-256",Qc.encode(t));return kb(new Uint8Array(n))}function Ab(e,t,n,o){return Qc.encode(`${e}
|
|
64
64
|
${t}
|
|
65
65
|
${n}
|
|
66
|
-
${o}`)}async function jj({secret:e,approvalId:t,toolCallId:n,toolName:o,input:i}){let a=await Rb(e),s=await Eb(i),l=Ab(t,n,o,s),c=await crypto.subtle.sign("HMAC",a,l);return kb(new Uint8Array(c))}async function Oj({secret:e,signature:t,approvalId:n,toolCallId:o,toolName:i,input:a}){let s=await Rb(e),l=await Eb(a),c=Ab(n,o,i,l),u=Mj(t);return crypto.subtle.verify("HMAC",s,u,c)}async function Pb({secret:e,approvalId:t,toolCallId:n,toolName:o,input:i}){if(e==null)return;return jj({secret:e,approvalId:t,toolCallId:n,toolName:o,input:i})}async function Mb({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 ov({approvalId:d.approvalId,toolCallId:u.toolCallId,reason:"missing signature"});if(!await Oj({secret:i,signature:d.signature,approvalId:d.approvalId,toolCallId:u.toolCallId,toolName:u.toolName,input:u.input}))throw new ov({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:Ut(m.inputSchema)});if(!f.success)throw new Ya({toolName:u.toolName,toolInput:JSON.stringify(u.input),cause:f.error})}if(m!=null&&await Yc({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 Nj={};uM(Nj,{array:()=>qj,choice:()=>$j,json:()=>Lj,object:()=>zj,text:()=>Ka});function Dj(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 Ai(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:Dj(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}}),zj=({schema:e,name:t,description:n})=>{let o=Ut(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 Ai(i);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:a.value}}},createElementStreamTransform(){return}}},qj=({element:e,name:t,description:n})=>{let o=Ut(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 Ai(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])}})}}},$j=({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 Ai(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}}),Lj=({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 Ai(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 jb({toolCall:e,tools:t,repairToolCall:n,system:o,messages:i}){try{if(t==null){if(e.providerExecuted&&e.dynamic)return await Ob(e);throw new Pc({toolName:e.toolName})}try{return await uv({toolCall:e,tools:t})}catch(a){if(n==null||!(Pc.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 Ut(c).jsonSchema},system:o,messages:i,error:a})}catch(l){throw new LM({cause:l,originalError:a})}if(s==null)throw a;return await uv({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 Ob(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 uv({toolCall:e,tools:t}){let n=e.toolName,o=t[n];if(o==null){if(e.providerExecuted&&e.dynamic)return await Ob(e);throw new Pc({toolName:e.toolName,availableTools:Object.keys(t)})}let i=Ut(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 Nb=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 Pi(e){return({steps:t})=>t.length===e}async function Db({stopConditions:e,steps:t}){return(await Promise.all(e.map((n)=>n({steps:t})))).some((n)=>n)}async function zc({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 Ti({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 Ti({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 Ti({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:Uj({toolResultContent:a,toolCallOrder:o})});return n}function Uj({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 zb(...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 Fj=Er({prefix:"aitxt",size:24});async function Xc({model:e,tools:t,toolChoice:n,system:o,prompt:i,messages:a,allowSystemInMessages:s,maxRetries:l,abortSignal:c,timeout:u,headers:d,stopWhen:m=Pi(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=Fj}={},experimental_onStart:F,experimental_onStepStart:R,experimental_onToolCallStart:z,experimental_onToolCallFinish:D,onStepFinish:N,onFinish:re,...Y}){let V=Ii(e),L=Tb(),pe=Nn(m),X=Bc(u),k=gb(u),Q=k!=null?new AbortController:void 0,J=zb(c,X!=null?AbortSignal.timeout(X):void 0,Q==null?void 0:Q.signal),{maxRetries:W,retry:K}=yo({maxRetries:l,abortSignal:J}),q=Ci(Y),B=it(d!=null?d:{},`ai/${ho}`),G=Ri({model:V,telemetry:g,headers:B,settings:{...q,maxRetries:W}}),Z={provider:V.provider,modelId:V.modelId},A=await Wc({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:q.maxOutputTokens,temperature:q.temperature,topP:q.topP,topK:q.topK,presencePenalty:q.presencePenalty,frequencyPenalty:q.frequencyPenalty,stopSequences:q.stopSequences,seed:q.seed,maxRetries:W,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 H=Ei(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:H,fn:async(P)=>{var U,ge,ee,ue,Ae,Ke,nt,At,Dr,he,br,zr,tn,wn,_r,st,rn,ut,T,te;let ve=A.messages,ke=[],{approvedToolApprovals:ht,deniedToolApprovals:Vt}=Cb({messages:ve}),{approvedToolApprovals:sr,deniedToolApprovals:lr}=await Mb({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 dv({toolCalls:sr.map((Ne)=>Ne.toolCall),tools:t,tracer:H,telemetry:g,messages:ve,abortSignal:J,experimental_context:C,stepNumber:0,model:Z,onToolCallStart:[z,O.onToolCallStart],onToolCallFinish:[D,O.onToolCallFinish]}),Pt=[];for(let Ne of It){let Bt=await Ti({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}}}}});ke.push({role:"tool",content:Pt})}let Je=Ci(Y),Fe,lt=[],Oe=[],Be=[],nn=new Map;do{let It=jc({abortController:Q,label:"Step",timeoutMs:k});try{let Pt=[...ve,...ke],Ne=await(y==null?void 0:y({model:V,steps:Be,stepNumber:Be.length,messages:Pt,experimental_context:C})),Bt=Ii((U=Ne==null?void 0:Ne.model)!=null?U:V),on={provider:Bt.provider,modelId:Bt.modelId},qr=await Jc({prompt:{system:(ge=Ne==null?void 0:Ne.system)!=null?ge: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:an}=await vb({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:on,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:()=>Vc(qr)},"ai.prompt.tools":{input:()=>an==null?void 0:an.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:H,fn:async(Mt)=>{var wr,Ct,Uo,la,ca,ln,cn,Jn;let Ye=await Bt.doGenerate({...Je,tools:an,toolChoice:$r,responseFormat:await(f==null?void 0:f.responseFormat),prompt:qr,providerOptions:cr,abortSignal:J,headers:B}),Zt={id:(Ct=(wr=Ye.response)==null?void 0:wr.id)!=null?Ct:E(),timestamp:(la=(Uo=Ye.response)==null?void 0:Uo.timestamp)!=null?la:new Date,modelId:(ln=(ca=Ye.response)==null?void 0:ca.modelId)!=null?ln:Bt.modelId,headers:(cn=Ye.response)==null?void 0:cn.headers,body:(Jn=Ye.response)==null?void 0:Jn.body},Fo=ki(Ye.usage);return Mt.setAttributes(await et({telemetry:g,attributes:{"ai.response.finishReason":Ye.finishReason.unified,"ai.response.text":{output:()=>Nc(Ye.content)},"ai.response.reasoning":{output:()=>Oc(Ye.content)},"ai.response.toolCalls":{output:()=>{let Wn=pv(Ye.content);return Wn==null?void 0:JSON.stringify(Wn)}},"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":Fo.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 sn=await Promise.all(Fe.content.filter((Me)=>Me.type==="tool-call").map((Me)=>jb({toolCall:Me,tools:t,repairToolCall:x,system:o,messages:Pt}))),Gn={};for(let Me of sn){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 Yc({tool:Mt,toolCall:Me,messages:Pt,experimental_context:C})){let wr=E(),Ct=await Pb({secret:I,approvalId:wr,toolCallId:Me.toolCallId,toolName:Me.toolName,input:Me.input});Gn[Me.toolCallId]={type:"tool-approval-request",approvalId:wr,toolCall:Me,...Ct!=null?{signature:Ct}:{}}}}let sa=sn.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:gi(Me.error),dynamic:!0});if(lt=sn.filter((Me)=>!Me.providerExecuted),t!=null)Oe.push(...await dv({toolCalls:lt.filter((Me)=>!Me.invalid&&Gn[Me.toolCallId]==null),tools:t,tracer:H,telemetry:g,messages:Pt,abortSignal:J,experimental_context:C,stepNumber:Be.length,model:on,onToolCallStart:[z,O.onToolCallStart],onToolCallFinish:[D,O.onToolCallFinish]}));for(let Me of sn){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))nn.set(Me.toolCallId,{toolName:Me.toolName})}}for(let Me of Fe.content)if(Me.type==="tool-result")nn.delete(Me.toolCallId);let xn=Gj({content:Fe.content,toolCalls:sn,toolOutputs:Oe,toolApprovalRequests:Object.values(Gn),tools:t});ke.push(...await zc({content:xn,tools:t}));let $o=((Dr=b==null?void 0:b.requestBody)!=null?Dr:!0)?(he=Fe.request)!=null?he:{}:{...Fe.request,body:void 0},Ks={...Fe.response,messages:structuredClone(ke),body:((br=b==null?void 0:b.responseBody)!=null?br:!0)?(zr=Fe.response)==null?void 0:zr.body:void 0},Ys=Be.length,Lo=new Nb({stepNumber:Ys,model:on,functionId:g==null?void 0:g.functionId,metadata:g==null?void 0:g.metadata,experimental_context:C,content:xn,finishReason:Fe.finishReason.unified,rawFinishReason:Fe.finishReason.raw,usage:ki(Fe.usage),warnings:Fe.warnings,providerMetadata:Fe.providerMetadata,request:$o,response:Ks});mn({warnings:(tn=Fe.warnings)!=null?tn:[],provider:on.provider,model:on.modelId}),Be.push(Lo),await mr({event:Lo,callbacks:[N,O.onStepFinish]})}finally{if(It!=null)clearTimeout(It)}}while((lt.length>0&&Oe.length===lt.length||nn.size>0)&&!await Db({stopConditions:pe,steps:Be}));P.setAttributes(await et({telemetry:g,attributes:{"ai.response.finishReason":Fe.finishReason.unified,"ai.response.text":{output:()=>Nc(Fe.content)},"ai.response.reasoning":{output:()=>Oc(Fe.content)},"ai.response.toolCalls":{output:()=>{let It=pv(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)=>Ib(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":(wn=ot.inputTokenDetails)==null?void 0:wn.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":(rn=ot.outputTokenDetails)==null?void 0:rn.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 Bj({steps:Be,totalUsage:ot,output:ct})}})}catch(P){throw Hc(P)}}async function dv({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)=>Zc({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 Bj=class{constructor(e){this.steps=e.steps,this._output=e.output,this.totalUsage=e.totalUsage}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get rawFinishReason(){return this.finalStep.rawFinishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get experimental_output(){return this.output}get output(){if(this._output==null)throw new Wa;return this._output}};function pv(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 Gj({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 Kc(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 $c({toolCallId:s.toolCallId,approvalId:s.approvalId});a.push({type:"tool-approval-request",approvalId:s.approvalId,toolCall:l});break}}return[...a,...n,...o]}function Mi(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 Jj({status:e,statusText:t,headers:n,textStream:o}){return new Response(o.pipeThrough(new TextEncoderStream),{status:e!=null?e:200,statusText:t,headers:Mi(n,{"content-type":"text/plain; charset=utf-8"})})}function qb({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 Wj({response:e,status:t,statusText:n,headers:o,textStream:i}){qb({response:e,status:t,statusText:n,headers:Object.fromEntries(Mi(o,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:i.pipeThrough(new TextEncoderStream)})}var $b=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
|
|
66
|
+
${o}`)}async function jj({secret:e,approvalId:t,toolCallId:n,toolName:o,input:i}){let a=await Rb(e),s=await Eb(i),l=Ab(t,n,o,s),c=await crypto.subtle.sign("HMAC",a,l);return kb(new Uint8Array(c))}async function Oj({secret:e,signature:t,approvalId:n,toolCallId:o,toolName:i,input:a}){let s=await Rb(e),l=await Eb(a),c=Ab(n,o,i,l),u=Mj(t);return crypto.subtle.verify("HMAC",s,u,c)}async function Pb({secret:e,approvalId:t,toolCallId:n,toolName:o,input:i}){if(e==null)return;return jj({secret:e,approvalId:t,toolCallId:n,toolName:o,input:i})}async function Mb({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 ov({approvalId:d.approvalId,toolCallId:u.toolCallId,reason:"missing signature"});if(!await Oj({secret:i,signature:d.signature,approvalId:d.approvalId,toolCallId:u.toolCallId,toolName:u.toolName,input:u.input}))throw new ov({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:Ut(m.inputSchema)});if(!f.success)throw new Ya({toolName:u.toolName,toolInput:JSON.stringify(u.input),cause:f.error})}if(m!=null&&await Yc({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 Nj={};uM(Nj,{array:()=>$j,choice:()=>qj,json:()=>Lj,object:()=>zj,text:()=>Ka});function Dj(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 Ai(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:Dj(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}}),zj=({schema:e,name:t,description:n})=>{let o=Ut(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 Ai(i);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:a.value}}},createElementStreamTransform(){return}}},$j=({element:e,name:t,description:n})=>{let o=Ut(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 Ai(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])}})}}},qj=({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 Ai(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}}),Lj=({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 Ai(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 jb({toolCall:e,tools:t,repairToolCall:n,system:o,messages:i}){try{if(t==null){if(e.providerExecuted&&e.dynamic)return await Ob(e);throw new Pc({toolName:e.toolName})}try{return await uv({toolCall:e,tools:t})}catch(a){if(n==null||!(Pc.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 Ut(c).jsonSchema},system:o,messages:i,error:a})}catch(l){throw new LM({cause:l,originalError:a})}if(s==null)throw a;return await uv({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 Ob(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 uv({toolCall:e,tools:t}){let n=e.toolName,o=t[n];if(o==null){if(e.providerExecuted&&e.dynamic)return await Ob(e);throw new Pc({toolName:e.toolName,availableTools:Object.keys(t)})}let i=Ut(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 Nb=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 Pi(e){return({steps:t})=>t.length===e}async function Db({stopConditions:e,steps:t}){return(await Promise.all(e.map((n)=>n({steps:t})))).some((n)=>n)}async function zc({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 Ti({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 Ti({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 Ti({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:Uj({toolResultContent:a,toolCallOrder:o})});return n}function Uj({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 zb(...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 Fj=Er({prefix:"aitxt",size:24});async function Xc({model:e,tools:t,toolChoice:n,system:o,prompt:i,messages:a,allowSystemInMessages:s,maxRetries:l,abortSignal:c,timeout:u,headers:d,stopWhen:m=Pi(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=Fj}={},experimental_onStart:F,experimental_onStepStart:R,experimental_onToolCallStart:z,experimental_onToolCallFinish:D,onStepFinish:N,onFinish:re,...Y}){let V=Ii(e),L=Tb(),pe=Nn(m),X=Bc(u),k=gb(u),Q=k!=null?new AbortController:void 0,J=zb(c,X!=null?AbortSignal.timeout(X):void 0,Q==null?void 0:Q.signal),{maxRetries:W,retry:K}=yo({maxRetries:l,abortSignal:J}),q=Ci(Y),B=it(d!=null?d:{},`ai/${ho}`),G=Ri({model:V,telemetry:g,headers:B,settings:{...q,maxRetries:W}}),Z={provider:V.provider,modelId:V.modelId},A=await Wc({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:q.maxOutputTokens,temperature:q.temperature,topP:q.topP,topK:q.topK,presencePenalty:q.presencePenalty,frequencyPenalty:q.frequencyPenalty,stopSequences:q.stopSequences,seed:q.seed,maxRetries:W,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 H=Ei(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:H,fn:async(P)=>{var U,ge,ee,ue,Ae,Ke,nt,At,Dr,he,br,zr,tn,wn,_r,st,rn,ut,T,te;let ve=A.messages,ke=[],{approvedToolApprovals:ht,deniedToolApprovals:Vt}=Cb({messages:ve}),{approvedToolApprovals:sr,deniedToolApprovals:lr}=await Mb({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 dv({toolCalls:sr.map((Ne)=>Ne.toolCall),tools:t,tracer:H,telemetry:g,messages:ve,abortSignal:J,experimental_context:C,stepNumber:0,model:Z,onToolCallStart:[z,O.onToolCallStart],onToolCallFinish:[D,O.onToolCallFinish]}),Pt=[];for(let Ne of It){let Bt=await Ti({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}}}}});ke.push({role:"tool",content:Pt})}let Je=Ci(Y),Fe,lt=[],Oe=[],Be=[],nn=new Map;do{let It=jc({abortController:Q,label:"Step",timeoutMs:k});try{let Pt=[...ve,...ke],Ne=await(y==null?void 0:y({model:V,steps:Be,stepNumber:Be.length,messages:Pt,experimental_context:C})),Bt=Ii((U=Ne==null?void 0:Ne.model)!=null?U:V),on={provider:Bt.provider,modelId:Bt.modelId},$r=await Jc({prompt:{system:(ge=Ne==null?void 0:Ne.system)!=null?ge: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:qr,tools:an}=await vb({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:on,system:yt,messages:Sr,tools:t,toolChoice:qr,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:()=>Vc($r)},"ai.prompt.tools":{input:()=>an==null?void 0:an.map((Mt)=>JSON.stringify(Mt))},"ai.prompt.toolChoice":{input:()=>qr!=null?JSON.stringify(qr):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:H,fn:async(Mt)=>{var wr,Ct,Uo,la,ca,ln,cn,Jn;let Ye=await Bt.doGenerate({...Je,tools:an,toolChoice:qr,responseFormat:await(f==null?void 0:f.responseFormat),prompt:$r,providerOptions:cr,abortSignal:J,headers:B}),Zt={id:(Ct=(wr=Ye.response)==null?void 0:wr.id)!=null?Ct:E(),timestamp:(la=(Uo=Ye.response)==null?void 0:Uo.timestamp)!=null?la:new Date,modelId:(ln=(ca=Ye.response)==null?void 0:ca.modelId)!=null?ln:Bt.modelId,headers:(cn=Ye.response)==null?void 0:cn.headers,body:(Jn=Ye.response)==null?void 0:Jn.body},Fo=ki(Ye.usage);return Mt.setAttributes(await et({telemetry:g,attributes:{"ai.response.finishReason":Ye.finishReason.unified,"ai.response.text":{output:()=>Nc(Ye.content)},"ai.response.reasoning":{output:()=>Oc(Ye.content)},"ai.response.toolCalls":{output:()=>{let Wn=pv(Ye.content);return Wn==null?void 0:JSON.stringify(Wn)}},"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":Fo.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 sn=await Promise.all(Fe.content.filter((Me)=>Me.type==="tool-call").map((Me)=>jb({toolCall:Me,tools:t,repairToolCall:x,system:o,messages:Pt}))),Gn={};for(let Me of sn){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 Yc({tool:Mt,toolCall:Me,messages:Pt,experimental_context:C})){let wr=E(),Ct=await Pb({secret:I,approvalId:wr,toolCallId:Me.toolCallId,toolName:Me.toolName,input:Me.input});Gn[Me.toolCallId]={type:"tool-approval-request",approvalId:wr,toolCall:Me,...Ct!=null?{signature:Ct}:{}}}}let sa=sn.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:gi(Me.error),dynamic:!0});if(lt=sn.filter((Me)=>!Me.providerExecuted),t!=null)Oe.push(...await dv({toolCalls:lt.filter((Me)=>!Me.invalid&&Gn[Me.toolCallId]==null),tools:t,tracer:H,telemetry:g,messages:Pt,abortSignal:J,experimental_context:C,stepNumber:Be.length,model:on,onToolCallStart:[z,O.onToolCallStart],onToolCallFinish:[D,O.onToolCallFinish]}));for(let Me of sn){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))nn.set(Me.toolCallId,{toolName:Me.toolName})}}for(let Me of Fe.content)if(Me.type==="tool-result")nn.delete(Me.toolCallId);let xn=Gj({content:Fe.content,toolCalls:sn,toolOutputs:Oe,toolApprovalRequests:Object.values(Gn),tools:t});ke.push(...await zc({content:xn,tools:t}));let qo=((Dr=b==null?void 0:b.requestBody)!=null?Dr:!0)?(he=Fe.request)!=null?he:{}:{...Fe.request,body:void 0},Ks={...Fe.response,messages:structuredClone(ke),body:((br=b==null?void 0:b.responseBody)!=null?br:!0)?(zr=Fe.response)==null?void 0:zr.body:void 0},Ys=Be.length,Lo=new Nb({stepNumber:Ys,model:on,functionId:g==null?void 0:g.functionId,metadata:g==null?void 0:g.metadata,experimental_context:C,content:xn,finishReason:Fe.finishReason.unified,rawFinishReason:Fe.finishReason.raw,usage:ki(Fe.usage),warnings:Fe.warnings,providerMetadata:Fe.providerMetadata,request:qo,response:Ks});mn({warnings:(tn=Fe.warnings)!=null?tn:[],provider:on.provider,model:on.modelId}),Be.push(Lo),await mr({event:Lo,callbacks:[N,O.onStepFinish]})}finally{if(It!=null)clearTimeout(It)}}while((lt.length>0&&Oe.length===lt.length||nn.size>0)&&!await Db({stopConditions:pe,steps:Be}));P.setAttributes(await et({telemetry:g,attributes:{"ai.response.finishReason":Fe.finishReason.unified,"ai.response.text":{output:()=>Nc(Fe.content)},"ai.response.reasoning":{output:()=>Oc(Fe.content)},"ai.response.toolCalls":{output:()=>{let It=pv(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)=>Ib(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":(wn=ot.inputTokenDetails)==null?void 0:wn.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":(rn=ot.outputTokenDetails)==null?void 0:rn.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 Bj({steps:Be,totalUsage:ot,output:ct})}})}catch(P){throw Hc(P)}}async function dv({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)=>Zc({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 Bj=class{constructor(e){this.steps=e.steps,this._output=e.output,this.totalUsage=e.totalUsage}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get rawFinishReason(){return this.finalStep.rawFinishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get experimental_output(){return this.output}get output(){if(this._output==null)throw new Wa;return this._output}};function pv(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 Gj({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 Kc(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 qc({toolCallId:s.toolCallId,approvalId:s.approvalId});a.push({type:"tool-approval-request",approvalId:s.approvalId,toolCall:l});break}}return[...a,...n,...o]}function Mi(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 Jj({status:e,statusText:t,headers:n,textStream:o}){return new Response(o.pipeThrough(new TextEncoderStream),{status:e!=null?e:200,statusText:t,headers:Mi(n,{"content-type":"text/plain; charset=utf-8"})})}function $b({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 Wj({response:e,status:t,statusText:n,headers:o,textStream:i}){$b({response:e,status:t,statusText:n,headers:Object.fromEntries(Mi(o,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:i.pipeThrough(new TextEncoderStream)})}var qb=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
|
|
67
67
|
|
|
68
68
|
`)},flush(e){e.enqueue(`data: [DONE]
|
|
69
69
|
|
|
70
|
-
`)}})}},Lb={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function Hj({status:e,statusText:t,headers:n,stream:o,consumeSseStream:i}){let a=o.pipeThrough(new $b);if(i){let[s,l]=a.tee();a=s,i({stream:l})}return new Response(a.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:Mi(n,Lb)})}function Vj({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 xi=r.record(r.string(),Dn.optional()),a6=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:xi.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:xi.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:xi.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:xi.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:xi.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 Zj(e){return e.type.startsWith("data-")}function Hr(){return Object.create(null)}function qc(e){return e.type.startsWith("tool-")}function Kj(e){return e.type==="dynamic-tool"}function mv(e){return qc(e)||Kj(e)}function gv(e){return e.type.split("-").slice(1).join("-")}function Yj({lastMessage:e,messageId:t}){return{message:(e==null?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:Hr(),activeReasoningParts:Hr(),partialToolCalls:Hr()}}function Qj({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(mv).find((C)=>C.toolCallId===y);if(_==null)throw new mo({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 mo({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 mo({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 mo({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 mo({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 mo({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 Ai(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(mv).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:gv(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:gv(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=Hr(),u.activeReasoningParts=Hr();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(Zj(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 Ub({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=Yj({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 Qj({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 Xj({response:e,status:t,statusText:n,headers:o,stream:i,consumeSseStream:a}){let s=i.pipeThrough(new $b);if(a){let[l,c]=s.tee();s=l,a({stream:c})}qb({response:e,status:t,statusText:n,headers:Object.fromEntries(Mi(o,Lb).entries()),stream:s.pipeThrough(new TextEncoderStream)})}function go(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 eO({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 fv(){let e,t;return{promise:new Promise((o,i)=>{e=o,t=i}),resolve:e,reject:t}}function tO(){let e=[],t=null,n=!1,o=fv(),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=fv(),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 rO({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 Pj({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:ki(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 $c({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 jb({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:gi(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 Yc({tool:R,toolCall:F,messages:a,experimental_context:c})){let z=d(),D=await Pb({secret:u,approvalId:z,toolCallId:F.toolCallId,toolName:F.toolName,input:F.input});h.enqueue({type:"tool-approval-request",approvalId:z,toolCall:F,...D!=null?{signature:D}:{}});break}if(R.execute!=null&&F.providerExecuted!==!0){let z=d();w.add(z),Zc({toolCall:F,tools:e,tracer:n,telemetry:o,messages:a,abortSignal:s,experimental_context:c,stepNumber:m,model:p,onToolCallStart:f,onToolCallFinish:g,onPreliminaryToolResult:(D)=>{h.enqueue(D)}}).then((D)=>{h.enqueue(D)}).catch((D)=>{h.enqueue({type:"error",error:D})}).finally(()=>{w.delete(z),_()})}}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 nO=Er({prefix:"aitxt",size:24}),oO={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 iO({model:e,tools:t,toolChoice:n,system:o,prompt:i,messages:a,allowSystemInMessages:s,maxRetries:l,abortSignal:c,timeout:u,headers:d,stopWhen:m=Pi(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:Q})=>{console.error(Q)},onFinish:E,onAbort:F,onStepFinish:R,experimental_onStart:z,experimental_onStepStart:D,experimental_onToolCallStart:N,experimental_onToolCallFinish:re,experimental_context:Y,experimental_toolApprovalSecret:V,experimental_include:L,_internal:{now:pe=Ha,generateId:X=nO}={},...k}){let Q=Bc(u),J=gb(u),W=oj(u),K=J!=null?new AbortController:void 0,q=W!=null?new AbortController:void 0;return new sO({model:Ii(e),telemetry:g,headers:d,settings:k,maxRetries:l,abortSignal:zb(c,Q!=null?AbortSignal.timeout(Q):void 0,K==null?void 0:K.signal,q==null?void 0:q.signal),stepTimeoutMs:J,stepAbortController:K,chunkTimeoutMs:W,chunkAbortController:q,system:o,prompt:i,messages:a,allowSystemInMessages:s,tools:t,toolChoice:n,transforms:Nn(x),activeTools:S,repairToolCall:y,stopConditions:Nn(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:z,onStepStart:D,onToolCallStart:N,onToolCallFinish:re,now:pe,generateId:X,experimental_context:Y,experimental_toolApprovalSecret:V,download:_,include:L})}function aO(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 sO=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:z,onChunk:D,onError:N,onFinish:re,onAbort:Y,onStepFinish:V,onStart:L,onStepStart:pe,onToolCallStart:X,onToolCallFinish:k,experimental_context:Q,experimental_toolApprovalSecret:J,download:W,include:K}){this._totalUsage=new Pn,this._finishReason=new Pn,this._rawFinishReason=new Pn,this._steps=new Pn,this.outputSpecification=x,this.includeRawChunks=I,this.tools=g;let B=Tb()(t==null?void 0:t.integrations),G,Z=[],A=[],O=void 0,H=void 0,P=void 0,U={},ge=[],ee=[],ue,Ae=new Map,Ke,nt=Hr(),At=Hr(),Dr=new TransformStream({async transform(ve,ke){var ht,Vt,sr,lr;ke.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(D==null?void 0:D({chunk:se}));if(se.type==="error"){let Je=Hc(se.error);if(Wa.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){ke.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){ke.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){ke.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){ke.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=Hr(),nt=Hr(),U=se.request,ge=se.warnings;if(se.type==="finish-step"){let Je=await zc({content:Z,tools:g}),Fe=new Nb({stepNumber:ee.length,model:T,...te,experimental_context:Q,content:Z,finishReason:se.finishReason,rawFinishReason:se.rawFinishReason,usage:se.usage,warnings:ge,request:U,response:{...se.response,messages:[...A,...Je]},providerMetadata:se.providerMetadata});await mr({event:Fe,callbacks:[V,B.onStepFinish]}),mn({warnings:ge,provider:T.provider,model:T.modelId}),ee.push(Fe),A.push(...Je),G.resolve()}if(se.type==="finish")P=se.totalUsage,O=se.finishReason,H=se.rawFinishReason},async flush(ve){var ke,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 Wa({message:"No output generated. Check the stream for errors."});ut._finishReason.reject(Be),ut._rawFinishReason.reject(Be),ut._totalUsage.reject(Be),ut._steps.reject(Be);return}let Fe=O!=null?O:"other",lt=P!=null?P:Ac();ut._finishReason.resolve(Fe),ut._rawFinishReason.resolve(H),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":(ke=lt.inputTokenDetails)==null?void 0:ke.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=tO();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 ke(){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){ke();return}ve.enqueue(Vt)}catch(ht){if(Yt(ht)&&(a==null?void 0:a.aborted))ke();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(aO(x!=null?x:Ka())).pipeThrough(Dr);let{maxRetries:tn,retry:wn}=yo({maxRetries:i,abortSignal:a}),_r=Ei(t),st=Ci(o),rn=Ri({model:e,telemetry:t,headers:n,settings:{...st,maxRetries:tn}}),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}),...rn,"ai.prompt":{input:()=>JSON.stringify({system:d,prompt:m,messages:p})}}}),tracer:_r,endWhenDone:!1,fn:async(ve)=>{Ke=ve;let ke=await Wc({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:tn,timeout:F,headers:n,providerOptions:_,stopWhen:R,output:x,abortSignal:z,include:K,...te,experimental_context:Q},callbacks:[L,B.onStart]});let ht=ke.messages,Vt=[],{approvedToolApprovals:sr,deniedToolApprovals:lr}=Cb({messages:ht});if(lr.length>0||sr.length>0){let{approvedToolApprovals:Je,deniedToolApprovals:Fe}=await Mb({approvedToolApprovals:sr.filter((Ce)=>!Ce.toolCall.providerExecuted),tools:g,messages:ht,experimental_context:Q,toolApprovalSecret:J}),lt=[...lr.filter((Ce)=>!Ce.toolCall.providerExecuted),...Fe],Oe=lr.filter((Ce)=>Ce.toolCall.providerExecuted),Be,nn=new ReadableStream({start(Ce){Be=Ce}});ut.addStream(nn);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 Zc({toolCall:ot.toolCall,tools:g,tracer:_r,telemetry:t,messages:ht,abortSignal:a,experimental_context:Q,stepNumber:ee.length,model:T,onToolCallStart:[X,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 Ti({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,nn,Ce,ot,ct,It,Pt,Ne;let Bt=ut.includeRawChunks,on=jc({abortController:l,label:"Step",timeoutMs:s}),qr=void 0;function aa(){if(qr!=null)clearTimeout(qr);qr=jc({abortController:u,label:"Chunk",timeoutMs:c})}function $r(){if(qr!=null)clearTimeout(qr),qr=void 0}function an(){if(on!=null)clearTimeout(on)}a==null||a.addEventListener("abort",an),a==null||a.addEventListener("abort",$r);try{G=new Pn;let Sr=[...ht,...Fe],yt=await(C==null?void 0:C({model:e,steps:ee,stepNumber:ee.length,messages:Sr,experimental_context:Q})),cr=Ii((Oe=yt==null?void 0:yt.model)!=null?Oe:e),sn={provider:cr.provider,modelId:cr.modelId},Gn=await Jc({prompt:{system:(Be=yt==null?void 0:yt.system)!=null?Be:ke.system,messages:(nn=yt==null?void 0:yt.messages)!=null?nn:Sr},supportedUrls:await cr.supportedUrls,download:W}),sa=(Ce=yt==null?void 0:yt.activeTools)!=null?Ce:w,{toolChoice:xn,tools:$o}=await vb({tools:g,toolChoice:(ot=yt==null?void 0:yt.toolChoice)!=null?ot:h,activeTools:sa});Q=(ct=yt==null?void 0:yt.experimental_context)!=null?ct:Q;let Ks=(It=yt==null?void 0:yt.messages)!=null?It:Sr,Ys=(Pt=yt==null?void 0:yt.system)!=null?Pt:ke.system,Lo=Qa(_,yt==null?void 0:yt.providerOptions);await mr({event:{stepNumber:ee.length,model:sn,system:Ys,messages:Ks,tools:g,toolChoice:xn,activeTools:sa,steps:[...ee],providerOptions:Lo,timeout:F,headers:n,stopWhen:R,output:x,abortSignal:z,include:K,...te,experimental_context:Q},callbacks:[pe,B.onStepStart]});let{result:{stream:Me,response:Mt,request:wr},doStreamSpan:Ct,startTimestampMs:Uo}=await wn(()=>nr({name:"ai.streamText.doStream",attributes:et({telemetry:t,attributes:{...rr({operationId:"ai.streamText.doStream",telemetry:t}),...rn,"ai.model.provider":cr.provider,"ai.model.id":cr.modelId,"ai.prompt.messages":{input:()=>Vc(Gn)},"ai.prompt.tools":{input:()=>$o==null?void 0:$o.map((be)=>JSON.stringify(be))},"ai.prompt.toolChoice":{input:()=>xn!=null?JSON.stringify(xn):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:$o,toolChoice:xn,responseFormat:await(x==null?void 0:x.responseFormat),prompt:Gn,providerOptions:Lo,abortSignal:a,headers:n,includeRawChunks:Bt})})})),la=rO({tools:g,generatorStream:Me,tracer:_r,telemetry:t,system:d,messages:Sr,repairToolCall:S,abortSignal:a,experimental_context:Q,toolApprovalSecret:J,generateId:E,stepNumber:ee.length,model:sn,onToolCallStart:[X,B.onToolCallStart],onToolCallFinish:[k,B.onToolCallFinish]}),ca=((Ne=K==null?void 0:K.requestBody)!=null?Ne:!0)?wr!=null?wr:{}:{...wr,body:void 0},ln=[],cn=[],Jn,Ye={},Zt="other",Fo=void 0,Wn=!1,dp=!1,jt=Ac(),pp,mp=!0,xr={id:E(),timestamp:new Date,modelId:T.modelId},YC="";ut.addStream(la.pipeThrough(new TransformStream({async transform(be,_t){var Bo,Go,Jo,Wo,Ho;if(aa(),be.type==="stream-start"){Jn=be.warnings;return}if(mp){let St=b()-Uo;mp=!1,Ct.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":St}),Ct.setAttributes({"ai.response.msToFirstChunk":St}),_t.enqueue({type:"start-step",request:ca,warnings:Jn!=null?Jn:[]})}let Hn=be.type;if(oO[Hn])dp=!0;switch(Hn){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}),YC+=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),ln.push(be);break}case"tool-result":{if(_t.enqueue(be),!be.preliminary)cn.push(be);break}case"tool-error":{_t.enqueue(be),cn.push(be);break}case"response-metadata":{xr={id:(Bo=be.id)!=null?Bo:xr.id,timestamp:(Go=be.timestamp)!=null?Go:xr.timestamp,modelId:(Jo=be.modelId)!=null?Jo:xr.modelId};break}case"finish":{Wn=!0,jt=be.usage,Zt=be.finishReason,Fo=be.rawFinishReason,pp=be.providerMetadata;let St=b()-Uo;Ct.addEvent("ai.stream.finish"),Ct.setAttributes({"ai.response.msToFinish":St,"ai.response.avgOutputTokensPerSecond":1000*((Wo=jt.outputTokens)!=null?Wo: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:Q});_t.enqueue({...be,dynamic:(Ho=be.dynamic)!=null?Ho:(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],Vn=g==null?void 0:g[St];if((Vn==null?void 0:Vn.onInputDelta)!=null)await Vn.onInputDelta({inputTextDelta:be.delta,toolCallId:be.id,messages:Sr,abortSignal:a,experimental_context:Q});_t.enqueue(be);break}case"error":{Wn=!0,_t.enqueue(be),Zt="error";break}case"raw":{if(Bt)_t.enqueue(be);break}default:throw Error(`Unknown chunk type: ${Hn}`)}},async flush(be){var _t,Bo,Go,Jo,Wo,Ho,Hn;if(!Wn&&!dp){be.enqueue({type:"error",error:new Wa({message:"No output generated. The model stream ended without a finish chunk."})}),Ct.end(),an(),$r(),ut.closeStream();return}let St=ln.length>0?JSON.stringify(ln):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":(Bo=jt.inputTokenDetails)==null?void 0:Bo.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(Go=jt.inputTokenDetails)==null?void 0:Go.cacheWriteTokens,"ai.usage.outputTokens":jt.outputTokens,"ai.usage.outputTokenDetails.textTokens":(Jo=jt.outputTokenDetails)==null?void 0:Jo.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(Wo=jt.outputTokenDetails)==null?void 0:Wo.reasoningTokens,"ai.usage.totalTokens":jt.totalTokens,"ai.usage.reasoningTokens":(Ho=jt.outputTokenDetails)==null?void 0:Ho.reasoningTokens,"ai.usage.cachedInputTokens":(Hn=jt.inputTokenDetails)==null?void 0:Hn.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:Fo,usage:jt,providerMetadata:pp,response:{...xr,headers:Mt==null?void 0:Mt.headers}});let Vn=Ib(lt,jt);await G.promise;let Qs=ee[ee.length-1];try{Ct.setAttributes(await et({telemetry:t,attributes:{"ai.response.text":{output:()=>Qs.text},"ai.response.reasoning":{output:()=>Qs.reasoningText},"ai.response.providerMetadata":JSON.stringify(Qs.providerMetadata)}}))}catch(kt){}finally{Ct.end()}let gp=ln.filter((kt)=>kt.providerExecuted!==!0),QC=cn.filter((kt)=>kt.providerExecuted!==!0);for(let kt of ln){if(kt.providerExecuted!==!0)continue;let Xs=g==null?void 0:g[kt.toolName];if((Xs==null?void 0:Xs.type)==="provider"&&Xs.supportsDeferredResults){if(!cn.some((el)=>(el.type==="tool-result"||el.type==="tool-error")&&el.toolCallId===kt.toolCallId))Ae.set(kt.toolCallId,{toolName:kt.toolName})}}for(let kt of cn)if(kt.type==="tool-result"||kt.type==="tool-error")Ae.delete(kt.toolCallId);if(an(),$r(),(gp.length>0&&QC.length===gp.length||Ae.size>0)&&!await Db({stopConditions:y,steps:ee})){Fe.push(...await zc({content:ee[ee.length-1].content,tools:g}));try{await se({currentStep:Je+1,responseMessages:Fe,usage:Vn})}catch(kt){be.enqueue({type:"error",error:kt}),ut.closeStream()}}else be.enqueue({type:"finish",finishReason:Zt,rawFinishReason:Fo,totalUsage:Vn}),ut.closeStream()}})))}catch(Sr){throw an(),$r(),Sr}}await se({currentStep:0,responseMessages:Vt,usage:Ac()})}}).catch((ve)=>{ut.addStream(new ReadableStream({start(ke){ke.enqueue({type:"error",error:ve}),ke.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 go(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){if(e.type==="text-delta")t.enqueue(e.text)}})))}get fullStream(){return go(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 eO({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 go(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 He({functionality:`element streams in ${(n=(t=this.outputSpecification)==null?void 0:t.name)!=null?n:"text"} mode`});return go(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?Vj({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 go(Ub({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}={}){Xj({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){Wj({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 Hj({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 Jj({textStream:this.textStream,...e})}},Fb=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:Pi(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 Xc({...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 iO({...await this.prepareCall(i),abortSignal:e,timeout:t,experimental_transform:n,onStepFinish:this.mergeOnStepFinishCallbacks(o)})}};function c6({execute:e,onError:t=()=>"An error occurred.",originalMessages:n,onStepFinish:o,onFinish:i,generateId:a=Le}){let s,l=[],c=new ReadableStream({start(m){s=m}});function u(m){try{s.enqueue(m)}catch(p){}}try{let m=e({writer:{write(p){u(p)},merge(p){l.push((async()=>{let f=p.getReader();while(!0){let{done:g,value:h}=await f.read();if(g)break;u(h)}})().catch((f)=>{u({type:"error",errorText:t(f)})}))},onError:t}});if(m)l.push(m.catch((p)=>{u({type:"error",errorText:t(p)})}))}catch(m){u({type:"error",errorText:t(m)})}return new Promise(async(m)=>{while(l.length>0)await l.shift();m()}).finally(()=>{try{s.close()}catch(m){}}),Ub({stream:c,messageId:a(),originalMessages:n,onStepFinish:o,onFinish:i,onError:t})}var Gt=r.record(r.string(),Dn.optional()),p6=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 Bb({model:e,value:t,providerOptions:n,maxRetries:o,abortSignal:i,headers:a,experimental_telemetry:s}){let l=mb(e),{maxRetries:c,retry:u}=yo({maxRetries:o,abortSignal:i}),d=it(a!=null?a:{},`ai/${ho}`),m=Ri({model:l,telemetry:s,headers:d,settings:{maxRetries:c}}),p=Ei(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}})),mn({warnings:v,provider:l.provider,model:l.modelId}),new lO({value:t,embedding:g,usage:h,warnings:v,providerMetadata:S,response:w})}})}var lO=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 hv(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 Gb({model:e,values:t,maxParallelCalls:n=1/0,maxRetries:o,abortSignal:i,headers:a,providerOptions:s,experimental_telemetry:l}){let c=mb(e),{maxRetries:u,retry:d}=yo({maxRetries:o,abortSignal:i}),m=it(a!=null?a:{},`ai/${ho}`),p=Ri({model:c,telemetry:l,headers:m,settings:{maxRetries:u}}),f=Ei(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:z,providerMetadata:D}=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((X)=>JSON.stringify(X))},"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}})),mn({warnings:R,provider:c.provider,model:c.modelId}),new yv({values:t,embeddings:E,usage:F,warnings:R,providerMetadata:D,responses:[z]})}let S=hv(t,v),y=[],x=[],_=[],C=0,I,b=hv(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((z)=>JSON.stringify(z))}}}),tracer:f,fn:async(z)=>{var D,N;let re=await c.doEmbed({values:R,abortSignal:i,headers:m,providerOptions:s}),Y=re.embeddings,V=(D=re.usage)!=null?D:{tokens:NaN};return z.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[z,D]of Object.entries(R.providerMetadata))I[z]={...(h=I[z])!=null?h:{},...D}}return g.setAttributes(await et({telemetry:l,attributes:{"ai.embeddings":{output:()=>y.map((E)=>JSON.stringify(E))},"ai.usage.tokens":C}})),mn({warnings:x,provider:c.provider,model:c.modelId}),new yv({values:t,embeddings:y,usage:{tokens:C},warnings:x,providerMetadata:I,responses:_})}})}var yv=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 eu({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=nj(e),g=it(d!=null?d:{},`ai/${ho}`),{retry:h}=yo({maxRetries:c,abortSignal:u}),v=(m=o!=null?o:await uO(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:z}=dO(t);return f.doGenerate({prompt:F,files:R,mask:z,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 Kc({data:F,mediaType:(R=Za({data:F,signatures:Va}))!=null?R:"image/png"})})),_.push(...E.warnings),E.usage!=null)b=Rj(b,E.usage);if(E.providerMetadata)for(let[F,R]of Object.entries(E.providerMetadata))if(F==="gateway"){let z=I[F];if(z!=null&&typeof z==="object")I[F]={...z,...R};else I[F]=R;let D=I[F].images;if(Array.isArray(D)&&D.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(mn({warnings:_,provider:f.provider,model:f.modelId}),!x.length)throw new xM({responses:C});return new cO({images:x,warnings:_,responses:C,providerMetadata:I,usage:b})}var cO=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 uO(e){if(!(e.maxImagesPerCall instanceof Function))return e.maxImagesPerCall;return e.maxImagesPerCall({modelId:e.modelId})}function dO(e){if(typeof e==="string")return{prompt:e,files:void 0,mask:void 0};return{prompt:e.text,files:e.images.map(vv),mask:e.mask?vv(e.mask):void 0}}function vv(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}=hb(e);if(o!=null){let i=wt(o);return{type:"file",data:i,mediaType:n||Za({data:i,signatures:Va})||"image/png"}}}let t=lj(e);return{type:"file",data:t,mediaType:Za({data:t,signatures:Va})||"image/png"}}var pO={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 He({functionality:"element streams in no-schema mode"})}},mO=(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 He({functionality:"element streams in object mode"})}}),gO=(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(!Qo(t)||!sl(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(!Qo(t)||!sl(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 go(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}`)}}})))}}),fO=(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(!Qo(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(!Qo(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 He({functionality:"element streams in enum mode"})}});function hO({output:e,schema:t,enumValues:n}){switch(e){case"object":return mO(Ut(t));case"array":return gO(Ut(t));case"enum":return fO(n);case"no-schema":return pO;default:throw Error(`Unsupported output: ${e}`)}}async function bv(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 yO(e,t,n,o){try{return await bv(e,t,o)}catch(i){if(n!=null&&Ft.isInstance(i)&&(In.isInstance(i.cause)||vt.isInstance(i.cause))){let a=await n({text:e,error:i.cause});if(a===null)throw i;return await bv(a,t,o)}throw i}}function vO({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 bO=Er({prefix:"aiobj",size:24});async function Jb(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=bO,currentDate:h=()=>new Date}={},...v}=e,w=Ii(t),S="enum"in e?e.enum:void 0,{schema:y,schemaDescription:x,schemaName:_}="schema"in e?e:{};vO({output:n,schema:y,schemaName:_,schemaDescription:x,enumValues:S});let{maxRetries:C,retry:I}=yo({maxRetries:l,abortSignal:c}),b=hO({output:n,schema:y,enumValues:S}),E=Ci(v),F=it(u!=null?u:{},`ai/${ho}`),R=Ri({model:w,telemetry:m,headers:F,settings:{...E,maxRetries:C}}),z=Ei(m),D=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":D!=null?{input:()=>JSON.stringify(D)}:void 0,"ai.schema.name":_,"ai.schema.description":x,"ai.settings.output":b.type}}),tracer:z,fn:async(N)=>{var re;let Y,V,L,pe,X,k,Q,J,W=await Wc({system:o,prompt:i,messages:a,allowSystemInMessages:s}),K=await Jc({prompt:W,supportedUrls:await w.supportedUrls,download:p}),q=await I(()=>nr({name:"ai.generateObject.doGenerate",attributes:et({telemetry:m,attributes:{...rr({operationId:"ai.generateObject.doGenerate",telemetry:m}),...R,"ai.prompt.messages":{input:()=>Vc(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:z,fn:async(G)=>{var Z,A,O,H,P,U,ge,ee;let ue=await w.doGenerate({responseFormat:{type:"json",schema:D,name:_,description:x},...Ci(v),prompt:K,providerOptions:f,abortSignal:c,headers:F}),Ae={id:(A=(Z=ue.response)==null?void 0:Z.id)!=null?A:g(),timestamp:(H=(O=ue.response)==null?void 0:O.timestamp)!=null?H:h(),modelId:(U=(P=ue.response)==null?void 0:P.modelId)!=null?U:w.modelId,headers:(ge=ue.response)==null?void 0:ge.headers,body:(ee=ue.response)==null?void 0:ee.body},Ke=Nc(ue.content),nt=Oc(ue.content);if(Ke===void 0)throw new Ft({message:"No object generated: the model did not return a response.",response:Ae,usage:ki(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=q.objectText,V=q.finishReason.unified,L=ki(q.usage),pe=q.warnings,Q=q.providerMetadata,k=(re=q.request)!=null?re:{},X=q.responseData,J=q.reasoning,mn({warnings:pe,provider:w.provider,model:w.modelId});let B=await yO(Y,b,d,{response:X,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(Q),"ai.usage.promptTokens":L.inputTokens,"ai.usage.completionTokens":L.outputTokens}})),new _O({object:B,reasoning:J,finishReason:V,usage:L,warnings:pe,request:k,response:X,providerMetadata:Q})}})}catch(N){throw Hc(N)}}var _O=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:Mi(e==null?void 0:e.headers,{"content-type":"application/json; charset=utf-8"})})}};function Wb(e){return({url:t,abortSignal:n})=>fb({url:t,maxBytes:e==null?void 0:e.maxBytes,abortSignal:n})}var w6=Er({prefix:"aiobj",size:24});var x6=Wb();var SO="AI_NoSuchProviderError",wO=`vercel.ai.error.${SO}`,xO=Symbol.for(wO),TO;TO=xO;var T6=Wb();class Xa extends Error{constructor(e){super("AI object generation failed: invalid structured output",{cause:e});this.name="AIOutputValidationError"}}var IO=[[/^claude/,"anthropic"],[/^gpt-/,"openai"],[/^o[13]-/,"openai"],[/^gemini/,"google"],[/^llama/,"ollama"],[/^mistral/,"ollama"],[/^phi-/,"ollama"],[/^qwen/,"ollama"]];function Hb(e){let t=e.indexOf(":");if(t>0)return{provider:e.slice(0,t),modelId:e.slice(t+1)};return null}function ji(e){let t=Hb(e);if(t)return t;for(let[n,o]of IO)if(n.test(e))return{provider:o,modelId:e};return{provider:"anthropic",modelId:e}}function tu(e){if(!e)return"anthropic";return ji(e).provider}var CO=[[/^gpt-image/,"openai"],[/^dall-e/,"openai"],[/^gemini/,"google"]],kO="gpt-image-1.5";function ru(e){if(!e)return{provider:"openai",modelId:kO};let t=Hb(e);if(t)return t;for(let[n,o]of CO)if(n.test(e))return{provider:o,modelId:e};return{provider:"openai",modelId:e}}var RO=/^(gpt-5|o[1-9])(?:[.-]|$)/;function EO(e){if(e.provider!=="openai")return!0;return!RO.test(e.modelId)}function Oi(e){if(!e)return{provider:"anthropic",supportsTemperature:!0};let t=ji(e);return{provider:t.provider,supportsTemperature:EO(t)}}var AO="3.0.95",PO=j(()=>M(r.object({type:r.literal("error"),error:r.object({type:r.string(),message:r.string()})}))),Vb=Qe({errorSchema:PO,errorToMessage:(e)=>e.error.message}),o_=r.object({type:r.string(),category:r.string().nullish(),explanation:r.string().nullish(),recommended_model:r.string().nullish()}),MO=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:o_.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()}))),jO=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:o_.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")})]))),OO=j(()=>M(r.object({signature:r.string().optional(),redactedData:r.string().optional()}))),Zb=r.object({citations:r.object({enabled:r.boolean()}).optional(),title:r.string().optional(),context:r.string().optional()}),Kb=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()}),Yb=4;function NO(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 au=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(e,t){let n=NO(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>Yb){this.warnings.push({type:"unsupported",feature:"cacheControl breakpoint limit",details:`Maximum ${Yb} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return n}getWarnings(){return this.warnings}},DO=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()}))),i_=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()})]))),zO=j(()=>M(r.object({}).strict())),qO=Te({id:"anthropic.advisor_20260301",inputSchema:zO,outputSchema:i_,supportsDeferredResults:!0}),$O=(e)=>qO(e),LO=j(()=>M(r.object({maxCharacters:r.number().optional()}))),UO=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()}))),FO=Ge({id:"anthropic.text_editor_20250728",inputSchema:UO}),BO=(e={})=>FO(e),GO=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()}))),JO=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")})))),WO=j(()=>M(r.object({query:r.string()}))),HO=Te({id:"anthropic.web_search_20260209",inputSchema:WO,outputSchema:JO,supportsDeferredResults:!0}),VO=(e={})=>HO(e),ZO=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()}))),a_=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")})))),KO=j(()=>M(r.object({query:r.string()}))),YO=Te({id:"anthropic.web_search_20250305",inputSchema:KO,outputSchema:a_,supportsDeferredResults:!0}),QO=(e={})=>YO(e),XO=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()}))),eN=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()}))),tN=j(()=>M(r.object({url:r.string()}))),rN=Te({id:"anthropic.web_fetch_20260209",inputSchema:tN,outputSchema:eN,supportsDeferredResults:!0}),nN=(e={})=>rN(e),oN=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()}))),s_=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()}))),iN=j(()=>M(r.object({url:r.string()}))),aN=Te({id:"anthropic.web_fetch_20250910",inputSchema:iN,outputSchema:s_,supportsDeferredResults:!0}),sN=(e={})=>aN(e);async function lN({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 au;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:LO});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:oN});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:XO});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:ZO});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:GO});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:DO});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 He({functionality:`tool choice type: ${f}`})}}function Qb({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 l_=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([])}))),cN=j(()=>M(r.object({code:r.string()}))),uN=Te({id:"anthropic.code_execution_20250522",inputSchema:cN,outputSchema:l_}),dN=(e={})=>uN(e),c_=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()})]))),pN=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()})])]))),mN=Te({id:"anthropic.code_execution_20250825",inputSchema:pN,outputSchema:c_,supportsDeferredResults:!0}),gN=(e={})=>mN(e),u_=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()})]))),fN=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()})])]))),hN=Te({id:"anthropic.code_execution_20260120",inputSchema:fN,outputSchema:u_,supportsDeferredResults:!0}),yN=(e={})=>hN(e),d_=j(()=>M(r.array(r.object({type:r.literal("tool_reference"),toolName:r.string()})))),vN=j(()=>M(r.object({pattern:r.string(),limit:r.number().optional()}))),bN=Te({id:"anthropic.tool_search_regex_20251119",inputSchema:vN,outputSchema:d_,supportsDeferredResults:!0}),_N=(e={})=>bN(e);function SN(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 He({functionality:"URL-based text documents are not supported for citations"});throw new He({functionality:`unsupported data type for text documents: ${typeof e}`})}function nu(e){return e instanceof URL||wN(e)}function wN(e){return typeof e==="string"&&/^https?:\/\//i.test(e)}function ou(e){return e instanceof URL?e.toString():e}async function Xb(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 xN({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=TN(e),z=o||new au,D=void 0,N=[];async function re(V){var L,pe;let X=await qe({provider:"anthropic",providerOptions:V,schema:Zb});return(pe=(L=X==null?void 0:X.citations)==null?void 0:L.enabled)!=null?pe:!1}async function Y(V){let L=await qe({provider:"anthropic",providerOptions:V,schema:Zb});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,X=L.type;switch(X){case"system":{let k=L.messages.map(({content:Q,providerOptions:J})=>({type:"text",text:Q,cache_control:z.getCacheControl(J,{type:"system message",canCache:!0})}));if(D==null)D=k;else N.push({role:"system",content:k}),F.add("mid-conversation-system-2026-04-07");break}case"user":{let k=[];for(let Q of L.messages){let{role:J,content:W}=Q;switch(J){case"user":{for(let K=0;K<W.length;K++){let q=W[K],B=K===W.length-1,G=(a=z.getCacheControl(q.providerOptions,{type:"user message part",canCache:!0}))!=null?a:B?z.getCacheControl(Q.providerOptions,{type:"user message",canCache:!0}):void 0;switch(q.type){case"text":{k.push({type:"text",text:q.text,cache_control:G});break}case"file":{if(q.mediaType.startsWith("image/"))k.push({type:"image",source:nu(q.data)?{type:"url",url:ou(q.data)}:{type:"base64",media_type:q.mediaType==="image/*"?"image/jpeg":q.mediaType,data:bt(q.data)},cache_control:G});else if(q.mediaType==="application/pdf"){F.add("pdfs-2024-09-25");let Z=await re(q.providerOptions),A=await Y(q.providerOptions);k.push({type:"document",source:nu(q.data)?{type:"url",url:ou(q.data)}:{type:"base64",media_type:"application/pdf",data:bt(q.data)},title:(s=A.title)!=null?s:q.filename,...A.context&&{context:A.context},...Z&&{citations:{enabled:!0}},cache_control:G})}else if(q.mediaType==="text/plain"){let Z=await re(q.providerOptions),A=await Y(q.providerOptions);k.push({type:"document",source:nu(q.data)?{type:"url",url:ou(q.data)}:{type:"text",media_type:"text/plain",data:SN(q.data)},title:(l=A.title)!=null?l:q.filename,...A.context&&{context:A.context},...Z&&{citations:{enabled:!0}},cache_control:G})}else throw new He({functionality:`media type: ${q.mediaType}`});break}}}break}case"tool":{for(let K=0;K<W.length;K++){let q=W[K];if(q.type==="tool-approval-response")continue;let B=q.output,G="providerOptions"in B?B.providerOptions:B.type==="content"?(c=B.value.find((H)=>H.providerOptions!=null))==null?void 0:c.providerOptions:void 0,Z=K===W.length-1,A=(d=(u=z.getCacheControl(q.providerOptions,{type:"tool result part",canCache:!0}))!=null?u:z.getCacheControl(G,{type:"tool result output",canCache:!0}))!=null?d:Z?z.getCacheControl(Q.providerOptions,{type:"tool result message",canCache:!0}):void 0,O;switch(B.type){case"content":O=B.value.map((H)=>{var P;switch(H.type){case"text":return{type:"text",text:H.text};case"image-data":return{type:"image",source:{type:"base64",media_type:H.mediaType,data:H.data}};case"image-url":return{type:"image",source:{type:"url",url:H.url}};case"file-url":return{type:"document",source:{type:"url",url:H.url}};case"file-data":{if(H.mediaType==="application/pdf")return F.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:H.mediaType,data:H.data}};n.push({type:"other",message:`unsupported tool content part type: ${H.type} with media type: ${H.mediaType}`});return}case"custom":{let U=(P=H.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: ${H.type}`});return}}}).filter(fi);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:q.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=[],Q=new Set;for(let J=0;J<L.messages.length;J++){let W=L.messages[J],K=J===L.messages.length-1,{content:q}=W;for(let B=0;B<q.length;B++){let G=q[B],Z=B===q.length-1,A=(p=z.getCacheControl(G.providerOptions,{type:"assistant message part",canCache:!0}))!=null?p:Z?z.getCacheControl(W.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 qe({provider:"anthropic",providerOptions:G.providerOptions,schema:OO});if(O!=null)if(O.signature!=null)z.getCacheControl(G.providerOptions,{type:"thinking block",canCache:!1}),k.push({type:"thinking",thinking:G.text,signature:O.signature});else if(O.redactedData!=null)z.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"){Q.add(G.toolCallId);let ge=(w=(v=G.providerOptions)==null?void 0:v.anthropic)==null?void 0:w.serverName;if(ge==null||typeof ge!=="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:ge,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:ge,...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,H=(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,...H&&{caller:H},cache_control:A});break}case"tool-result":{let O=i.toProviderToolName(G.toolName);if(Q.has(G.toolCallId)){let H=G.output;if(H.type!=="json"&&H.type!=="error-json"){n.push({type:"other",message:`provider executed tool result output type ${H.type} for tool ${G.toolName} is not supported`});break}k.push({type:"mcp_tool_result",tool_use_id:G.toolCallId,is_error:H.type==="error-json",content:H.value,cache_control:A})}else if(O==="code_execution"){let H=G.output;if(H.type==="error-text"||H.type==="error-json"){let P={};try{if(typeof H.value==="string")P=er(H.value);else if(typeof H.value==="object"&&H.value!==null)P=H.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(H.type!=="json"){n.push({type:"other",message:`provider executed tool result output type ${H.type} for tool ${G.toolName} is not supported`});break}if(H.value==null||typeof H.value!=="object"||!("type"in H.value)||typeof H.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(H.value.type==="code_execution_result"){let P=await Ee({value:H.value,schema:l_});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(H.value.type==="encrypted_code_execution_result"){let P=await Ee({value:H.value,schema:u_});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:H.value,schema:c_});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 H=G.output;if(H.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 Xb(H.value)).errorCode)!=null?b:"unavailable"},cache_control:A});break}if(H.type!=="json"){n.push({type:"other",message:`provider executed tool result output type ${H.type} for tool ${G.toolName} is not supported`});break}let P=await Ee({value:H.value,schema:s_});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 H=G.output;if(H.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 Xb(H.value)).errorCode)!=null?E:"unavailable"},cache_control:A});break}if(H.type!=="json"){n.push({type:"other",message:`provider executed tool result output type ${H.type} for tool ${G.toolName} is not supported`});break}let P=await Ee({value:H.value,schema:a_});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 H=G.output;if(H.type!=="json"){n.push({type:"other",message:`provider executed tool result output type ${H.type} for tool ${G.toolName} is not supported`});break}let U=(await Ee({value:H.value,schema:d_})).map((ge)=>({type:"tool_reference",tool_name:ge.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 H=G.output;if(H.type!=="json"&&H.type!=="error-json"){n.push({type:"other",message:`provider executed tool result output type ${H.type} for tool ${G.toolName} is not supported`});break}let P=await Ee({value:H.value,schema:i_});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:IN(k)});break}default:throw Error(`content type: ${X}`)}}return{prompt:{system:D,messages:N},betas:F}}function TN(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 IN(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 iu({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 p_=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),CN=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","minItems","maxItems","uniqueItems","minProperties","maxProperties","not"];function kN(e){return m_(e)}function gn(e){if(typeof e==="boolean"||!PN(e))return e;return m_(e)}function m_(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(gn);else if(e.oneOf!=null)t.anyOf=e.oneOf.map(gn);if(e.allOf!=null)t.allOf=e.allOf.map(gn);if(e.definitions!=null)t.definitions=Object.fromEntries(Object.entries(e.definitions).map(([i,a])=>[i,gn(a)]));if(n.$defs!=null){let i=t;i.$defs=Object.fromEntries(Object.entries(n.$defs).map(([a,s])=>[a,gn(s)]))}if(e.type==="object"||e.properties!=null){if(e.properties!=null)t.properties=Object.fromEntries(Object.entries(e.properties).map(([i,a])=>[i,gn(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(gn):gn(e.items);if(typeof e.format==="string"&&p_.has(e.format))t.format=e.format;let o=RN(e);if(o!=null)t.description=t.description==null?o:`${t.description}
|
|
71
|
-
${o}`;return t}function RN(e){let t=CN.flatMap((n)=>{let o=e[n];if(o==null||o===!1)return[];return`${EN(n)}: ${AN(o)}`});if(typeof e.format==="string"&&!p_.has(e.format))t.push(`format: ${e.format}`);return t.length===0?void 0:`${t.join("; ")}.`}function EN(e){return e.replace(/[A-Z]/g,(t)=>` ${t.toLowerCase()}`)}function AN(e){if(typeof e==="string")return e;return JSON.stringify(e)}function PN(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function e_(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 MN=class{constructor(e,t){this.specificationVersion="v3";var n;this.modelId=e,this.config=t,this.generateId=(n=t.generateId)!=null?n:Le}supportsUrl(e){return e.protocol==="https:"}get provider(){return this.config.provider}get providerOptionsName(){let e=this.config.provider,t=e.indexOf(".");return t===-1?e:e.substring(0,t)}get supportedUrls(){var e,t,n;return(n=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?n:{}}async getArgs({userSuppliedBetas:e,prompt:t,maxOutputTokens:n,temperature:o,topP:i,topK:a,frequencyPenalty:s,presencePenalty:l,stopSequences:c,responseFormat:u,seed:d,tools:m,toolChoice:p,providerOptions:f,stream:g}){var h,v,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 qe({provider:"anthropic",providerOptions:f,schema:Kb}),z=F!=="anthropic"?await qe({provider:F,providerOptions:f,schema:Kb}):null,D=z!=null,N=Object.assign({},R!=null?R:{},z!=null?z:{}),{maxOutputTokens:re,supportsStructuredOutput:Y,rejectsSamplingParameters:V,isKnownModel:L}=jN(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-"),X=((h=this.config.supportsNativeStructuredOutput)!=null?h:!0)&&Y,k=((v=this.config.supportsStrictTools)!=null?v:!0)&&Y,Q=(w=N==null?void 0:N.structuredOutputMode)!=null?w:"auto",J=Q==="outputFormat"||Q==="auto"&&X,W=(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,q=new au,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 xN({prompt:t,sendReasoning:(S=N==null?void 0:N.sendReasoning)!=null?S:!0,warnings:E,cacheControlValidator:q,toolNameMapping:B}),A=(y=N==null?void 0:N.thinking)==null?void 0:y.type,O=A==="enabled"||A==="adaptive",H=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,ge=n!=null?n:re,ee={model:this.modelId,max_tokens:ge,temperature:o,top_k:a,top_p:i,stop_sequences:c,...H&&{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:kN(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=ge+(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 lN(W!=null?{tools:[...m!=null?m:[],W],toolChoice:{type:"required"},disableParallelToolUse:!0,cacheControlValidator:q,supportsStructuredOutput:!1,supportsStrictTools:k,defaultEagerInputStreaming:ue}:{tools:m!=null?m:[],toolChoice:p,disableParallelToolUse:N==null?void 0:N.disableParallelToolUse,cacheControlValidator:q,supportsStructuredOutput:X,supportsStrictTools:k,defaultEagerInputStreaming:ue}),Dr=q.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:W!=null,toolNameMapping:B,providerOptionsName:F,usedCustomProviderKey:D}}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=t_(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:Vb,successfulResponseHandler:xe(MO),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=e_(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:iu({finishReason:S.stop_reason,isJsonResponseFromTool:I}),raw:(a=S.stop_reason)!=null?a:void 0},usage:Qb({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,z;let D=n_(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,...D!=null?{stopDetails:D}:{},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:(z=r_(S.context_management))!=null?z: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=t_(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:Vb,successfulResponseHandler:Dt(jO),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,z=this.generateId,D=g.pipeThrough(new TransformStream({start(V){V.enqueue({type:"stream-start",warnings:i})},transform(V,L){var pe,X,k,Q,J,W,K,q,B,G,Z,A,O,H;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,ge=U.type;if(ge==="fallback")return;switch(R=ge,ge){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:z(),url:ee.url,title:ee.title,providerMetadata:{anthropic:{pageAge:(X=ee.page_age)!=null?X: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:(Q=U.content.content)!=null?Q:[]}});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: ${ge}`)}}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 ge=w[P.index],ee=P.delta.partial_json;if(ee.length===0)return;if(F){if((ge==null?void 0:ge.type)!=="text")return;L.enqueue({type:"text-delta",id:String(P.index),delta:ee})}else{if((ge==null?void 0:ge.type)!=="tool-call")return;if(ge.firstDelta&&ge.providerToolInputType!=null)ee=`{"type": "${ge.providerToolInputType}",${ee.substring(1)}`;L.enqueue({type:"tool-input-delta",id:ge.toolCallId,delta:ee}),ge.input+=ee,ge.firstDelta=!1}return}case"citations_delta":{let ge=P.delta.citation,ee=e_(ge,d,z);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=(W=P.message.usage.cache_creation_input_tokens)!=null?W: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:iu({finishReason:P.message.stop_reason,isJsonResponseFromTool:F}),raw:P.message.stop_reason};if(L.enqueue({type:"response-metadata",id:(q=P.message.id)!=null?q: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 ge=P.message.content[U];if(ge.type==="tool_use"){let ee=ge.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:ge.id,toolName:ge.name});let Ae=JSON.stringify((G=ge.input)!=null?G:{});L.enqueue({type:"tool-input-delta",id:ge.id,delta:Ae}),L.enqueue({type:"tool-input-end",id:ge.id}),L.enqueue({type:"tool-call",toolCallId:ge.id,toolName:ge.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:iu({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=n_(P.delta.stop_details),E=P.delta.container!=null?{expiresAt:P.delta.container.expires_at,id:P.delta.container.id,skills:(H=(O=P.delta.container.skills)==null?void 0:O.map((U)=>({type:U.type,skillId:U.skill_id,version:U.version})))!=null?H:null}:null,P.context_management)x=r_(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},ge={anthropic:U};if(u&&c!=="anthropic")ge[c]=U;L.enqueue({type:"finish",finishReason:h,usage:Qb({usage:v,rawUsage:_}),providerMetadata:ge});return}case"error":{L.enqueue({type:"error",error:P.error});return}default:throw Error(`Unsupported chunk type: ${P}`)}}})),[N,re]=D.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 jN(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 t_(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 r_(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 n_(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 ON=j(()=>M(r.object({command:r.string(),restart:r.boolean().optional()}))),NN=Ge({id:"anthropic.bash_20241022",inputSchema:ON}),DN=j(()=>M(r.object({command:r.string(),restart:r.boolean().optional()}))),zN=Ge({id:"anthropic.bash_20250124",inputSchema:DN}),qN=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()}))),$N=Ge({id:"anthropic.computer_20241022",inputSchema:qN}),LN=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()}))),UN=Ge({id:"anthropic.computer_20250124",inputSchema:LN}),FN=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()}))),BN=Ge({id:"anthropic.computer_20251124",inputSchema:FN}),GN=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()})]))),JN=Ge({id:"anthropic.memory_20250818",inputSchema:GN}),WN=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()}))),HN=Ge({id:"anthropic.text_editor_20241022",inputSchema:WN}),VN=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()}))),ZN=Ge({id:"anthropic.text_editor_20250124",inputSchema:VN}),KN=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()}))),YN=Ge({id:"anthropic.text_editor_20250429",inputSchema:KN}),QN=j(()=>M(r.array(r.object({type:r.literal("tool_reference"),toolName:r.string()})))),XN=j(()=>M(r.object({query:r.string(),limit:r.number().optional()}))),eD=Te({id:"anthropic.tool_search_bm25_20251119",inputSchema:XN,outputSchema:QN,supportsDeferredResults:!0}),tD=(e={})=>eD(e),rD={advisor_20260301:$O,bash_20241022:NN,bash_20250124:zN,codeExecution_20250522:dN,codeExecution_20250825:gN,codeExecution_20260120:yN,computer_20241022:$N,computer_20250124:UN,computer_20251124:BN,memory_20250818:JN,textEditor_20241022:HN,textEditor_20250124:ZN,textEditor_20250429:YN,textEditor_20250728:BO,webFetch_20250910:sN,webFetch_20260209:nN,webSearch_20250305:QO,webSearch_20260209:VO,toolSearchRegex_20251119:_N,toolSearchBm25_20251119:tD},g_="https://api.anthropic.com",f_=`${g_}/v1`;function nD(e){let t=pn(e);return t===g_?f_:t}function su(e={}){var t,n;let o=(t=nD(Ar({settingValue:e.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"})))!=null?t:f_,i=(n=e.name)!=null?n:"anthropic.messages";if(e.apiKey&&e.authToken)throw new Qn({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":so({apiKey:e.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"})};return it({"anthropic-version":"2023-06-01",...c,...e.headers},`ai-sdk/anthropic/${AO}`)},s=(c)=>{var u;return new MN(c,{provider:i,baseURL:o,headers:a,fetch:e.fetch,generateId:(u=e.generateId)!=null?u:Le,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]})})},l=function(c){if(new.target)throw Error("The Anthropic model function cannot be called with the new keyword.");return s(c)};return l.specificationVersion="v3",l.languageModel=s,l.chat=s,l.messages=s,l.embeddingModel=(c)=>{throw new al({modelId:c,modelType:"embeddingModel"})},l.textEmbeddingModel=l.embeddingModel,l.imageModel=(c)=>{throw new al({modelId:c,modelType:"imageModel"})},l.tools=rD,l}var h_=su();var gu=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:gu,errorToMessage:(e)=>e.error.message});function D_(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 fu({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(()=>{}),oD({frame:m,url:o,requestBodyValues:i,responseHeaders:a});if(n(d.value))return l}}finally{c.cancel().catch(()=>{}),c.releaseLock()}}function oD({frame:e,url:t,requestBodyValues:n,responseHeaders:o}){var i;let a=iD(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:aD(a),responseHeaders:o,responseBody:JSON.stringify(e),data:e})}function iD(e){var t;let n=Ni(e);if(n==null)return;if(n.type==="response.failed"){let i=Ni(n.response),a=Ni(i==null?void 0:i.error);return typeof(a==null?void 0:a.message)==="string"?{message:a.message,code:y_(a.code),type:"response.failed",frame:e}:void 0}let o=(t=Ni(n.error))!=null?t:n;return typeof o.message==="string"&&(Ni(n.error)!=null||typeof o.type==="string"||("code"in o)||("param"in o))?{message:o.message,code:y_(o.code),type:typeof o.type==="string"?o.type:void 0,frame:e}:void 0}function aD(e){if(typeof e.code==="number"&&v_(e.code))return e.code;if(typeof e.code==="string"&&/^\d{3}$/.test(e.code)){let n=Number(e.code);if(v_(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 Ni(e){return typeof e==="object"&&e!=null?e:void 0}function y_(e){return typeof e==="string"||typeof e==="number"?e:void 0}function v_(e){return Number.isInteger(e)&&e>=400&&e<=599}function b_(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 sD(e){return JSON.stringify(e===void 0?{}:e)}function lD({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 He({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 He({functionality:`audio content parts with media type ${l.mediaType}`})}}else if(l.mediaType==="application/pdf"){if(l.data instanceof URL)throw new He({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 He({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:sD(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 lu({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 __(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var cD=j(()=>M(r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({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()}))),uD=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()}),gu]))),dD=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 pD({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 He({functionality:`tool choice type: ${i}`})}}var mD=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 qe({provider:"openai",providerOptions:p,schema:dD}))!=null?f:{},x=D_(this.modelId),_=(g=y.forceReasoning)!=null?g:x.isReasoningModel;if(i!=null)S.push({type:"unsupported",feature:"topK"});let{messages:C,warnings:I}=lD({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:z}=pD({tools:d,toolChoice:m});return{args:{...E,tools:F,tool_choice:R},warnings:[...S,...z]}}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(cD),abortSignal:e.abortSignal,fetch:this.config.fetch}),f=m.choices[0],g=[],h=f.message.content;if(h!=null&&h.length>0)g.push({type:"text",text:h});for(let y of(t=f.message.tool_calls)!=null?t:[])g.push({type:"tool-call",toolCallId:(n=y.id)!=null?n:Le(),toolName:y.function.name,input:y.function.arguments});for(let y of(o=f.message.annotations)!=null?o:[])g.push({type:"source",sourceType:"url",id:Le(),url:y.url_citation.url,title:y.url_citation.title});let v=(i=m.usage)==null?void 0:i.completion_tokens_details,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:__(f.finish_reason),raw:(l=f.finish_reason)!=null?l:void 0},usage:b_(m.usage),request:{body:c},response:{...lu(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(uD),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=await fu({stream:s,getError:(h)=>("error"in h)?h.error:void 0,isOutputChunk:gD,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,z,D;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=lu(N);if(Object.values(V).some(Boolean))m=!0,v.enqueue({type:"response-metadata",...lu(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:__(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 X=c[L];if(((b=X.function)==null?void 0:b.name)!=null&&((E=X.function)==null?void 0:E.arguments)!=null){if(X.function.arguments.length>0)v.enqueue({type:"tool-input-delta",id:X.id,delta:X.function.arguments})}continue}let pe=c[L];if(pe.hasFinished)continue;if(((F=V.function)==null?void 0:F.arguments)!=null)pe.function.arguments+=(z=(R=V.function)==null?void 0:R.arguments)!=null?z:"";v.enqueue({type:"tool-input-delta",id:pe.id,delta:(D=V.function.arguments)!=null?D:""})}if(Y.annotations!=null)for(let V of Y.annotations)v.enqueue({type:"source",sourceType:"url",id:Le(),url:V.url_citation.url,title:V.url_citation.title})},flush(h){var v;if(p)h.enqueue({type:"text-end",id:"0"});for(let 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:Le(),toolName:w.function.name,input:w.function.arguments}),w.hasFinished=!0;h.enqueue({type:"finish",finishReason:u,usage:b_(d),...f!=null?{providerMetadata:f}:{}})}})),request:{body:o},response:{headers:a}}}};function gD(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 S_(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 fD({prompt:e,user:t="user",assistant:n="assistant"}){let o="";if(e[0].role==="system")o+=`${e[0].content}
|
|
70
|
+
`)}})}},Lb={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function Hj({status:e,statusText:t,headers:n,stream:o,consumeSseStream:i}){let a=o.pipeThrough(new qb);if(i){let[s,l]=a.tee();a=s,i({stream:l})}return new Response(a.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:Mi(n,Lb)})}function Vj({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 xi=r.record(r.string(),Dn.optional()),a6=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:xi.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:xi.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:xi.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:xi.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:xi.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 Zj(e){return e.type.startsWith("data-")}function Hr(){return Object.create(null)}function $c(e){return e.type.startsWith("tool-")}function Kj(e){return e.type==="dynamic-tool"}function mv(e){return $c(e)||Kj(e)}function gv(e){return e.type.split("-").slice(1).join("-")}function Yj({lastMessage:e,messageId:t}){return{message:(e==null?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:Hr(),activeReasoningParts:Hr(),partialToolCalls:Hr()}}function Qj({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(mv).find((C)=>C.toolCallId===y);if(_==null)throw new mo({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)=>$c(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 mo({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 mo({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 mo({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 mo({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($c);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 mo({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 Ai(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(mv).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:gv(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:gv(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=Hr(),u.activeReasoningParts=Hr();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(Zj(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 Ub({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=Yj({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 Qj({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 Xj({response:e,status:t,statusText:n,headers:o,stream:i,consumeSseStream:a}){let s=i.pipeThrough(new qb);if(a){let[l,c]=s.tee();s=l,a({stream:c})}$b({response:e,status:t,statusText:n,headers:Object.fromEntries(Mi(o,Lb).entries()),stream:s.pipeThrough(new TextEncoderStream)})}function go(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 eO({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 fv(){let e,t;return{promise:new Promise((o,i)=>{e=o,t=i}),resolve:e,reject:t}}function tO(){let e=[],t=null,n=!1,o=fv(),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=fv(),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 rO({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 Pj({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:ki(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 qc({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 jb({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:gi(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 Yc({tool:R,toolCall:F,messages:a,experimental_context:c})){let z=d(),D=await Pb({secret:u,approvalId:z,toolCallId:F.toolCallId,toolName:F.toolName,input:F.input});h.enqueue({type:"tool-approval-request",approvalId:z,toolCall:F,...D!=null?{signature:D}:{}});break}if(R.execute!=null&&F.providerExecuted!==!0){let z=d();w.add(z),Zc({toolCall:F,tools:e,tracer:n,telemetry:o,messages:a,abortSignal:s,experimental_context:c,stepNumber:m,model:p,onToolCallStart:f,onToolCallFinish:g,onPreliminaryToolResult:(D)=>{h.enqueue(D)}}).then((D)=>{h.enqueue(D)}).catch((D)=>{h.enqueue({type:"error",error:D})}).finally(()=>{w.delete(z),_()})}}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 nO=Er({prefix:"aitxt",size:24}),oO={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 iO({model:e,tools:t,toolChoice:n,system:o,prompt:i,messages:a,allowSystemInMessages:s,maxRetries:l,abortSignal:c,timeout:u,headers:d,stopWhen:m=Pi(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:Q})=>{console.error(Q)},onFinish:E,onAbort:F,onStepFinish:R,experimental_onStart:z,experimental_onStepStart:D,experimental_onToolCallStart:N,experimental_onToolCallFinish:re,experimental_context:Y,experimental_toolApprovalSecret:V,experimental_include:L,_internal:{now:pe=Ha,generateId:X=nO}={},...k}){let Q=Bc(u),J=gb(u),W=oj(u),K=J!=null?new AbortController:void 0,q=W!=null?new AbortController:void 0;return new sO({model:Ii(e),telemetry:g,headers:d,settings:k,maxRetries:l,abortSignal:zb(c,Q!=null?AbortSignal.timeout(Q):void 0,K==null?void 0:K.signal,q==null?void 0:q.signal),stepTimeoutMs:J,stepAbortController:K,chunkTimeoutMs:W,chunkAbortController:q,system:o,prompt:i,messages:a,allowSystemInMessages:s,tools:t,toolChoice:n,transforms:Nn(x),activeTools:S,repairToolCall:y,stopConditions:Nn(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:z,onStepStart:D,onToolCallStart:N,onToolCallFinish:re,now:pe,generateId:X,experimental_context:Y,experimental_toolApprovalSecret:V,download:_,include:L})}function aO(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 sO=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:z,onChunk:D,onError:N,onFinish:re,onAbort:Y,onStepFinish:V,onStart:L,onStepStart:pe,onToolCallStart:X,onToolCallFinish:k,experimental_context:Q,experimental_toolApprovalSecret:J,download:W,include:K}){this._totalUsage=new Pn,this._finishReason=new Pn,this._rawFinishReason=new Pn,this._steps=new Pn,this.outputSpecification=x,this.includeRawChunks=I,this.tools=g;let B=Tb()(t==null?void 0:t.integrations),G,Z=[],A=[],O=void 0,H=void 0,P=void 0,U={},ge=[],ee=[],ue,Ae=new Map,Ke,nt=Hr(),At=Hr(),Dr=new TransformStream({async transform(ve,ke){var ht,Vt,sr,lr;ke.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(D==null?void 0:D({chunk:se}));if(se.type==="error"){let Je=Hc(se.error);if(Wa.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){ke.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){ke.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){ke.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){ke.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=Hr(),nt=Hr(),U=se.request,ge=se.warnings;if(se.type==="finish-step"){let Je=await zc({content:Z,tools:g}),Fe=new Nb({stepNumber:ee.length,model:T,...te,experimental_context:Q,content:Z,finishReason:se.finishReason,rawFinishReason:se.rawFinishReason,usage:se.usage,warnings:ge,request:U,response:{...se.response,messages:[...A,...Je]},providerMetadata:se.providerMetadata});await mr({event:Fe,callbacks:[V,B.onStepFinish]}),mn({warnings:ge,provider:T.provider,model:T.modelId}),ee.push(Fe),A.push(...Je),G.resolve()}if(se.type==="finish")P=se.totalUsage,O=se.finishReason,H=se.rawFinishReason},async flush(ve){var ke,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 Wa({message:"No output generated. Check the stream for errors."});ut._finishReason.reject(Be),ut._rawFinishReason.reject(Be),ut._totalUsage.reject(Be),ut._steps.reject(Be);return}let Fe=O!=null?O:"other",lt=P!=null?P:Ac();ut._finishReason.resolve(Fe),ut._rawFinishReason.resolve(H),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":(ke=lt.inputTokenDetails)==null?void 0:ke.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=tO();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 ke(){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){ke();return}ve.enqueue(Vt)}catch(ht){if(Yt(ht)&&(a==null?void 0:a.aborted))ke();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(aO(x!=null?x:Ka())).pipeThrough(Dr);let{maxRetries:tn,retry:wn}=yo({maxRetries:i,abortSignal:a}),_r=Ei(t),st=Ci(o),rn=Ri({model:e,telemetry:t,headers:n,settings:{...st,maxRetries:tn}}),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}),...rn,"ai.prompt":{input:()=>JSON.stringify({system:d,prompt:m,messages:p})}}}),tracer:_r,endWhenDone:!1,fn:async(ve)=>{Ke=ve;let ke=await Wc({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:tn,timeout:F,headers:n,providerOptions:_,stopWhen:R,output:x,abortSignal:z,include:K,...te,experimental_context:Q},callbacks:[L,B.onStart]});let ht=ke.messages,Vt=[],{approvedToolApprovals:sr,deniedToolApprovals:lr}=Cb({messages:ht});if(lr.length>0||sr.length>0){let{approvedToolApprovals:Je,deniedToolApprovals:Fe}=await Mb({approvedToolApprovals:sr.filter((Ce)=>!Ce.toolCall.providerExecuted),tools:g,messages:ht,experimental_context:Q,toolApprovalSecret:J}),lt=[...lr.filter((Ce)=>!Ce.toolCall.providerExecuted),...Fe],Oe=lr.filter((Ce)=>Ce.toolCall.providerExecuted),Be,nn=new ReadableStream({start(Ce){Be=Ce}});ut.addStream(nn);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 Zc({toolCall:ot.toolCall,tools:g,tracer:_r,telemetry:t,messages:ht,abortSignal:a,experimental_context:Q,stepNumber:ee.length,model:T,onToolCallStart:[X,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 Ti({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,nn,Ce,ot,ct,It,Pt,Ne;let Bt=ut.includeRawChunks,on=jc({abortController:l,label:"Step",timeoutMs:s}),$r=void 0;function aa(){if($r!=null)clearTimeout($r);$r=jc({abortController:u,label:"Chunk",timeoutMs:c})}function qr(){if($r!=null)clearTimeout($r),$r=void 0}function an(){if(on!=null)clearTimeout(on)}a==null||a.addEventListener("abort",an),a==null||a.addEventListener("abort",qr);try{G=new Pn;let Sr=[...ht,...Fe],yt=await(C==null?void 0:C({model:e,steps:ee,stepNumber:ee.length,messages:Sr,experimental_context:Q})),cr=Ii((Oe=yt==null?void 0:yt.model)!=null?Oe:e),sn={provider:cr.provider,modelId:cr.modelId},Gn=await Jc({prompt:{system:(Be=yt==null?void 0:yt.system)!=null?Be:ke.system,messages:(nn=yt==null?void 0:yt.messages)!=null?nn:Sr},supportedUrls:await cr.supportedUrls,download:W}),sa=(Ce=yt==null?void 0:yt.activeTools)!=null?Ce:w,{toolChoice:xn,tools:qo}=await vb({tools:g,toolChoice:(ot=yt==null?void 0:yt.toolChoice)!=null?ot:h,activeTools:sa});Q=(ct=yt==null?void 0:yt.experimental_context)!=null?ct:Q;let Ks=(It=yt==null?void 0:yt.messages)!=null?It:Sr,Ys=(Pt=yt==null?void 0:yt.system)!=null?Pt:ke.system,Lo=Qa(_,yt==null?void 0:yt.providerOptions);await mr({event:{stepNumber:ee.length,model:sn,system:Ys,messages:Ks,tools:g,toolChoice:xn,activeTools:sa,steps:[...ee],providerOptions:Lo,timeout:F,headers:n,stopWhen:R,output:x,abortSignal:z,include:K,...te,experimental_context:Q},callbacks:[pe,B.onStepStart]});let{result:{stream:Me,response:Mt,request:wr},doStreamSpan:Ct,startTimestampMs:Uo}=await wn(()=>nr({name:"ai.streamText.doStream",attributes:et({telemetry:t,attributes:{...rr({operationId:"ai.streamText.doStream",telemetry:t}),...rn,"ai.model.provider":cr.provider,"ai.model.id":cr.modelId,"ai.prompt.messages":{input:()=>Vc(Gn)},"ai.prompt.tools":{input:()=>qo==null?void 0:qo.map((be)=>JSON.stringify(be))},"ai.prompt.toolChoice":{input:()=>xn!=null?JSON.stringify(xn):void 0},"gen_ai.system":cr.provider,"gen_ai.request.model":cr.modelId,"gen_ai.request.frequency_penalty":st.frequencyPenalty,"gen_ai.request.max_tokens":st.maxOutputTokens,"gen_ai.request.presence_penalty":st.presencePenalty,"gen_ai.request.stop_sequences":st.stopSequences,"gen_ai.request.temperature":st.temperature,"gen_ai.request.top_k":st.topK,"gen_ai.request.top_p":st.topP}}),tracer:_r,endWhenDone:!1,fn:async(be)=>({startTimestampMs:b(),doStreamSpan:be,result:await cr.doStream({...st,tools:qo,toolChoice:xn,responseFormat:await(x==null?void 0:x.responseFormat),prompt:Gn,providerOptions:Lo,abortSignal:a,headers:n,includeRawChunks:Bt})})})),la=rO({tools:g,generatorStream:Me,tracer:_r,telemetry:t,system:d,messages:Sr,repairToolCall:S,abortSignal:a,experimental_context:Q,toolApprovalSecret:J,generateId:E,stepNumber:ee.length,model:sn,onToolCallStart:[X,B.onToolCallStart],onToolCallFinish:[k,B.onToolCallFinish]}),ca=((Ne=K==null?void 0:K.requestBody)!=null?Ne:!0)?wr!=null?wr:{}:{...wr,body:void 0},ln=[],cn=[],Jn,Ye={},Zt="other",Fo=void 0,Wn=!1,dp=!1,jt=Ac(),pp,mp=!0,xr={id:E(),timestamp:new Date,modelId:T.modelId},YC="";ut.addStream(la.pipeThrough(new TransformStream({async transform(be,_t){var Bo,Go,Jo,Wo,Ho;if(aa(),be.type==="stream-start"){Jn=be.warnings;return}if(mp){let St=b()-Uo;mp=!1,Ct.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":St}),Ct.setAttributes({"ai.response.msToFirstChunk":St}),_t.enqueue({type:"start-step",request:ca,warnings:Jn!=null?Jn:[]})}let Hn=be.type;if(oO[Hn])dp=!0;switch(Hn){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}),YC+=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),ln.push(be);break}case"tool-result":{if(_t.enqueue(be),!be.preliminary)cn.push(be);break}case"tool-error":{_t.enqueue(be),cn.push(be);break}case"response-metadata":{xr={id:(Bo=be.id)!=null?Bo:xr.id,timestamp:(Go=be.timestamp)!=null?Go:xr.timestamp,modelId:(Jo=be.modelId)!=null?Jo:xr.modelId};break}case"finish":{Wn=!0,jt=be.usage,Zt=be.finishReason,Fo=be.rawFinishReason,pp=be.providerMetadata;let St=b()-Uo;Ct.addEvent("ai.stream.finish"),Ct.setAttributes({"ai.response.msToFinish":St,"ai.response.avgOutputTokensPerSecond":1000*((Wo=jt.outputTokens)!=null?Wo: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:Q});_t.enqueue({...be,dynamic:(Ho=be.dynamic)!=null?Ho:(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],Vn=g==null?void 0:g[St];if((Vn==null?void 0:Vn.onInputDelta)!=null)await Vn.onInputDelta({inputTextDelta:be.delta,toolCallId:be.id,messages:Sr,abortSignal:a,experimental_context:Q});_t.enqueue(be);break}case"error":{Wn=!0,_t.enqueue(be),Zt="error";break}case"raw":{if(Bt)_t.enqueue(be);break}default:throw Error(`Unknown chunk type: ${Hn}`)}},async flush(be){var _t,Bo,Go,Jo,Wo,Ho,Hn;if(!Wn&&!dp){be.enqueue({type:"error",error:new Wa({message:"No output generated. The model stream ended without a finish chunk."})}),Ct.end(),an(),qr(),ut.closeStream();return}let St=ln.length>0?JSON.stringify(ln):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":(Bo=jt.inputTokenDetails)==null?void 0:Bo.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(Go=jt.inputTokenDetails)==null?void 0:Go.cacheWriteTokens,"ai.usage.outputTokens":jt.outputTokens,"ai.usage.outputTokenDetails.textTokens":(Jo=jt.outputTokenDetails)==null?void 0:Jo.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(Wo=jt.outputTokenDetails)==null?void 0:Wo.reasoningTokens,"ai.usage.totalTokens":jt.totalTokens,"ai.usage.reasoningTokens":(Ho=jt.outputTokenDetails)==null?void 0:Ho.reasoningTokens,"ai.usage.cachedInputTokens":(Hn=jt.inputTokenDetails)==null?void 0:Hn.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:Fo,usage:jt,providerMetadata:pp,response:{...xr,headers:Mt==null?void 0:Mt.headers}});let Vn=Ib(lt,jt);await G.promise;let Qs=ee[ee.length-1];try{Ct.setAttributes(await et({telemetry:t,attributes:{"ai.response.text":{output:()=>Qs.text},"ai.response.reasoning":{output:()=>Qs.reasoningText},"ai.response.providerMetadata":JSON.stringify(Qs.providerMetadata)}}))}catch(kt){}finally{Ct.end()}let gp=ln.filter((kt)=>kt.providerExecuted!==!0),QC=cn.filter((kt)=>kt.providerExecuted!==!0);for(let kt of ln){if(kt.providerExecuted!==!0)continue;let Xs=g==null?void 0:g[kt.toolName];if((Xs==null?void 0:Xs.type)==="provider"&&Xs.supportsDeferredResults){if(!cn.some((el)=>(el.type==="tool-result"||el.type==="tool-error")&&el.toolCallId===kt.toolCallId))Ae.set(kt.toolCallId,{toolName:kt.toolName})}}for(let kt of cn)if(kt.type==="tool-result"||kt.type==="tool-error")Ae.delete(kt.toolCallId);if(an(),qr(),(gp.length>0&&QC.length===gp.length||Ae.size>0)&&!await Db({stopConditions:y,steps:ee})){Fe.push(...await zc({content:ee[ee.length-1].content,tools:g}));try{await se({currentStep:Je+1,responseMessages:Fe,usage:Vn})}catch(kt){be.enqueue({type:"error",error:kt}),ut.closeStream()}}else be.enqueue({type:"finish",finishReason:Zt,rawFinishReason:Fo,totalUsage:Vn}),ut.closeStream()}})))}catch(Sr){throw an(),qr(),Sr}}await se({currentStep:0,responseMessages:Vt,usage:Ac()})}}).catch((ve)=>{ut.addStream(new ReadableStream({start(ke){ke.enqueue({type:"error",error:ve}),ke.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 go(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){if(e.type==="text-delta")t.enqueue(e.text)}})))}get fullStream(){return go(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 eO({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 go(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 He({functionality:`element streams in ${(n=(t=this.outputSpecification)==null?void 0:t.name)!=null?n:"text"} mode`});return go(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?Vj({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 go(Ub({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}={}){Xj({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){Wj({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 Hj({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 Jj({textStream:this.textStream,...e})}},Fb=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:Pi(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 Xc({...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 iO({...await this.prepareCall(i),abortSignal:e,timeout:t,experimental_transform:n,onStepFinish:this.mergeOnStepFinishCallbacks(o)})}};function c6({execute:e,onError:t=()=>"An error occurred.",originalMessages:n,onStepFinish:o,onFinish:i,generateId:a=Le}){let s,l=[],c=new ReadableStream({start(m){s=m}});function u(m){try{s.enqueue(m)}catch(p){}}try{let m=e({writer:{write(p){u(p)},merge(p){l.push((async()=>{let f=p.getReader();while(!0){let{done:g,value:h}=await f.read();if(g)break;u(h)}})().catch((f)=>{u({type:"error",errorText:t(f)})}))},onError:t}});if(m)l.push(m.catch((p)=>{u({type:"error",errorText:t(p)})}))}catch(m){u({type:"error",errorText:t(m)})}return new Promise(async(m)=>{while(l.length>0)await l.shift();m()}).finally(()=>{try{s.close()}catch(m){}}),Ub({stream:c,messageId:a(),originalMessages:n,onStepFinish:o,onFinish:i,onError:t})}var Gt=r.record(r.string(),Dn.optional()),p6=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 Bb({model:e,value:t,providerOptions:n,maxRetries:o,abortSignal:i,headers:a,experimental_telemetry:s}){let l=mb(e),{maxRetries:c,retry:u}=yo({maxRetries:o,abortSignal:i}),d=it(a!=null?a:{},`ai/${ho}`),m=Ri({model:l,telemetry:s,headers:d,settings:{maxRetries:c}}),p=Ei(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}})),mn({warnings:v,provider:l.provider,model:l.modelId}),new lO({value:t,embedding:g,usage:h,warnings:v,providerMetadata:S,response:w})}})}var lO=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 hv(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 Gb({model:e,values:t,maxParallelCalls:n=1/0,maxRetries:o,abortSignal:i,headers:a,providerOptions:s,experimental_telemetry:l}){let c=mb(e),{maxRetries:u,retry:d}=yo({maxRetries:o,abortSignal:i}),m=it(a!=null?a:{},`ai/${ho}`),p=Ri({model:c,telemetry:l,headers:m,settings:{maxRetries:u}}),f=Ei(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:z,providerMetadata:D}=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((X)=>JSON.stringify(X))},"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}})),mn({warnings:R,provider:c.provider,model:c.modelId}),new yv({values:t,embeddings:E,usage:F,warnings:R,providerMetadata:D,responses:[z]})}let S=hv(t,v),y=[],x=[],_=[],C=0,I,b=hv(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((z)=>JSON.stringify(z))}}}),tracer:f,fn:async(z)=>{var D,N;let re=await c.doEmbed({values:R,abortSignal:i,headers:m,providerOptions:s}),Y=re.embeddings,V=(D=re.usage)!=null?D:{tokens:NaN};return z.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[z,D]of Object.entries(R.providerMetadata))I[z]={...(h=I[z])!=null?h:{},...D}}return g.setAttributes(await et({telemetry:l,attributes:{"ai.embeddings":{output:()=>y.map((E)=>JSON.stringify(E))},"ai.usage.tokens":C}})),mn({warnings:x,provider:c.provider,model:c.modelId}),new yv({values:t,embeddings:y,usage:{tokens:C},warnings:x,providerMetadata:I,responses:_})}})}var yv=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 eu({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=nj(e),g=it(d!=null?d:{},`ai/${ho}`),{retry:h}=yo({maxRetries:c,abortSignal:u}),v=(m=o!=null?o:await uO(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:z}=dO(t);return f.doGenerate({prompt:F,files:R,mask:z,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 Kc({data:F,mediaType:(R=Za({data:F,signatures:Va}))!=null?R:"image/png"})})),_.push(...E.warnings),E.usage!=null)b=Rj(b,E.usage);if(E.providerMetadata)for(let[F,R]of Object.entries(E.providerMetadata))if(F==="gateway"){let z=I[F];if(z!=null&&typeof z==="object")I[F]={...z,...R};else I[F]=R;let D=I[F].images;if(Array.isArray(D)&&D.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(mn({warnings:_,provider:f.provider,model:f.modelId}),!x.length)throw new xM({responses:C});return new cO({images:x,warnings:_,responses:C,providerMetadata:I,usage:b})}var cO=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 uO(e){if(!(e.maxImagesPerCall instanceof Function))return e.maxImagesPerCall;return e.maxImagesPerCall({modelId:e.modelId})}function dO(e){if(typeof e==="string")return{prompt:e,files:void 0,mask:void 0};return{prompt:e.text,files:e.images.map(vv),mask:e.mask?vv(e.mask):void 0}}function vv(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}=hb(e);if(o!=null){let i=wt(o);return{type:"file",data:i,mediaType:n||Za({data:i,signatures:Va})||"image/png"}}}let t=lj(e);return{type:"file",data:t,mediaType:Za({data:t,signatures:Va})||"image/png"}}var pO={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 He({functionality:"element streams in no-schema mode"})}},mO=(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 He({functionality:"element streams in object mode"})}}),gO=(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(!Qo(t)||!sl(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(!Qo(t)||!sl(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 go(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}`)}}})))}}),fO=(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(!Qo(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(!Qo(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 He({functionality:"element streams in enum mode"})}});function hO({output:e,schema:t,enumValues:n}){switch(e){case"object":return mO(Ut(t));case"array":return gO(Ut(t));case"enum":return fO(n);case"no-schema":return pO;default:throw Error(`Unsupported output: ${e}`)}}async function bv(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 yO(e,t,n,o){try{return await bv(e,t,o)}catch(i){if(n!=null&&Ft.isInstance(i)&&(In.isInstance(i.cause)||vt.isInstance(i.cause))){let a=await n({text:e,error:i.cause});if(a===null)throw i;return await bv(a,t,o)}throw i}}function vO({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 bO=Er({prefix:"aiobj",size:24});async function Jb(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=bO,currentDate:h=()=>new Date}={},...v}=e,w=Ii(t),S="enum"in e?e.enum:void 0,{schema:y,schemaDescription:x,schemaName:_}="schema"in e?e:{};vO({output:n,schema:y,schemaName:_,schemaDescription:x,enumValues:S});let{maxRetries:C,retry:I}=yo({maxRetries:l,abortSignal:c}),b=hO({output:n,schema:y,enumValues:S}),E=Ci(v),F=it(u!=null?u:{},`ai/${ho}`),R=Ri({model:w,telemetry:m,headers:F,settings:{...E,maxRetries:C}}),z=Ei(m),D=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":D!=null?{input:()=>JSON.stringify(D)}:void 0,"ai.schema.name":_,"ai.schema.description":x,"ai.settings.output":b.type}}),tracer:z,fn:async(N)=>{var re;let Y,V,L,pe,X,k,Q,J,W=await Wc({system:o,prompt:i,messages:a,allowSystemInMessages:s}),K=await Jc({prompt:W,supportedUrls:await w.supportedUrls,download:p}),q=await I(()=>nr({name:"ai.generateObject.doGenerate",attributes:et({telemetry:m,attributes:{...rr({operationId:"ai.generateObject.doGenerate",telemetry:m}),...R,"ai.prompt.messages":{input:()=>Vc(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:z,fn:async(G)=>{var Z,A,O,H,P,U,ge,ee;let ue=await w.doGenerate({responseFormat:{type:"json",schema:D,name:_,description:x},...Ci(v),prompt:K,providerOptions:f,abortSignal:c,headers:F}),Ae={id:(A=(Z=ue.response)==null?void 0:Z.id)!=null?A:g(),timestamp:(H=(O=ue.response)==null?void 0:O.timestamp)!=null?H:h(),modelId:(U=(P=ue.response)==null?void 0:P.modelId)!=null?U:w.modelId,headers:(ge=ue.response)==null?void 0:ge.headers,body:(ee=ue.response)==null?void 0:ee.body},Ke=Nc(ue.content),nt=Oc(ue.content);if(Ke===void 0)throw new Ft({message:"No object generated: the model did not return a response.",response:Ae,usage:ki(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=q.objectText,V=q.finishReason.unified,L=ki(q.usage),pe=q.warnings,Q=q.providerMetadata,k=(re=q.request)!=null?re:{},X=q.responseData,J=q.reasoning,mn({warnings:pe,provider:w.provider,model:w.modelId});let B=await yO(Y,b,d,{response:X,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(Q),"ai.usage.promptTokens":L.inputTokens,"ai.usage.completionTokens":L.outputTokens}})),new _O({object:B,reasoning:J,finishReason:V,usage:L,warnings:pe,request:k,response:X,providerMetadata:Q})}})}catch(N){throw Hc(N)}}var _O=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:Mi(e==null?void 0:e.headers,{"content-type":"application/json; charset=utf-8"})})}};function Wb(e){return({url:t,abortSignal:n})=>fb({url:t,maxBytes:e==null?void 0:e.maxBytes,abortSignal:n})}var w6=Er({prefix:"aiobj",size:24});var x6=Wb();var SO="AI_NoSuchProviderError",wO=`vercel.ai.error.${SO}`,xO=Symbol.for(wO),TO;TO=xO;var T6=Wb();class Xa extends Error{constructor(e){super("AI object generation failed: invalid structured output",{cause:e});this.name="AIOutputValidationError"}}var IO=[[/^claude/,"anthropic"],[/^gpt-/,"openai"],[/^o[13]-/,"openai"],[/^gemini/,"google"],[/^llama/,"ollama"],[/^mistral/,"ollama"],[/^phi-/,"ollama"],[/^qwen/,"ollama"]];function Hb(e){let t=e.indexOf(":");if(t>0)return{provider:e.slice(0,t),modelId:e.slice(t+1)};return null}function ji(e){let t=Hb(e);if(t)return t;for(let[n,o]of IO)if(n.test(e))return{provider:o,modelId:e};return{provider:"anthropic",modelId:e}}function tu(e){if(!e)return"anthropic";return ji(e).provider}var CO=[[/^gpt-image/,"openai"],[/^dall-e/,"openai"],[/^gemini/,"google"]],kO="gpt-image-1.5";function ru(e){if(!e)return{provider:"openai",modelId:kO};let t=Hb(e);if(t)return t;for(let[n,o]of CO)if(n.test(e))return{provider:o,modelId:e};return{provider:"openai",modelId:e}}var RO=/^(gpt-5|o[1-9])(?:[.-]|$)/;function EO(e){if(e.provider!=="openai")return!0;return!RO.test(e.modelId)}function Oi(e){if(!e)return{provider:"anthropic",supportsTemperature:!0};let t=ji(e);return{provider:t.provider,supportsTemperature:EO(t)}}var AO="3.0.95",PO=j(()=>M(r.object({type:r.literal("error"),error:r.object({type:r.string(),message:r.string()})}))),Vb=Qe({errorSchema:PO,errorToMessage:(e)=>e.error.message}),o_=r.object({type:r.string(),category:r.string().nullish(),explanation:r.string().nullish(),recommended_model:r.string().nullish()}),MO=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:o_.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()}))),jO=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:o_.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")})]))),OO=j(()=>M(r.object({signature:r.string().optional(),redactedData:r.string().optional()}))),Zb=r.object({citations:r.object({enabled:r.boolean()}).optional(),title:r.string().optional(),context:r.string().optional()}),Kb=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()}),Yb=4;function NO(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 au=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(e,t){let n=NO(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>Yb){this.warnings.push({type:"unsupported",feature:"cacheControl breakpoint limit",details:`Maximum ${Yb} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return n}getWarnings(){return this.warnings}},DO=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()}))),i_=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()})]))),zO=j(()=>M(r.object({}).strict())),$O=Te({id:"anthropic.advisor_20260301",inputSchema:zO,outputSchema:i_,supportsDeferredResults:!0}),qO=(e)=>$O(e),LO=j(()=>M(r.object({maxCharacters:r.number().optional()}))),UO=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()}))),FO=Ge({id:"anthropic.text_editor_20250728",inputSchema:UO}),BO=(e={})=>FO(e),GO=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()}))),JO=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")})))),WO=j(()=>M(r.object({query:r.string()}))),HO=Te({id:"anthropic.web_search_20260209",inputSchema:WO,outputSchema:JO,supportsDeferredResults:!0}),VO=(e={})=>HO(e),ZO=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()}))),a_=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")})))),KO=j(()=>M(r.object({query:r.string()}))),YO=Te({id:"anthropic.web_search_20250305",inputSchema:KO,outputSchema:a_,supportsDeferredResults:!0}),QO=(e={})=>YO(e),XO=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()}))),eN=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()}))),tN=j(()=>M(r.object({url:r.string()}))),rN=Te({id:"anthropic.web_fetch_20260209",inputSchema:tN,outputSchema:eN,supportsDeferredResults:!0}),nN=(e={})=>rN(e),oN=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()}))),s_=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()}))),iN=j(()=>M(r.object({url:r.string()}))),aN=Te({id:"anthropic.web_fetch_20250910",inputSchema:iN,outputSchema:s_,supportsDeferredResults:!0}),sN=(e={})=>aN(e);async function lN({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 au;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:LO});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:oN});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:XO});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:ZO});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:GO});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:DO});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 He({functionality:`tool choice type: ${f}`})}}function Qb({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 l_=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([])}))),cN=j(()=>M(r.object({code:r.string()}))),uN=Te({id:"anthropic.code_execution_20250522",inputSchema:cN,outputSchema:l_}),dN=(e={})=>uN(e),c_=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()})]))),pN=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()})])]))),mN=Te({id:"anthropic.code_execution_20250825",inputSchema:pN,outputSchema:c_,supportsDeferredResults:!0}),gN=(e={})=>mN(e),u_=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()})]))),fN=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()})])]))),hN=Te({id:"anthropic.code_execution_20260120",inputSchema:fN,outputSchema:u_,supportsDeferredResults:!0}),yN=(e={})=>hN(e),d_=j(()=>M(r.array(r.object({type:r.literal("tool_reference"),toolName:r.string()})))),vN=j(()=>M(r.object({pattern:r.string(),limit:r.number().optional()}))),bN=Te({id:"anthropic.tool_search_regex_20251119",inputSchema:vN,outputSchema:d_,supportsDeferredResults:!0}),_N=(e={})=>bN(e);function SN(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 He({functionality:"URL-based text documents are not supported for citations"});throw new He({functionality:`unsupported data type for text documents: ${typeof e}`})}function nu(e){return e instanceof URL||wN(e)}function wN(e){return typeof e==="string"&&/^https?:\/\//i.test(e)}function ou(e){return e instanceof URL?e.toString():e}async function Xb(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 xN({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=TN(e),z=o||new au,D=void 0,N=[];async function re(V){var L,pe;let X=await $e({provider:"anthropic",providerOptions:V,schema:Zb});return(pe=(L=X==null?void 0:X.citations)==null?void 0:L.enabled)!=null?pe:!1}async function Y(V){let L=await $e({provider:"anthropic",providerOptions:V,schema:Zb});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,X=L.type;switch(X){case"system":{let k=L.messages.map(({content:Q,providerOptions:J})=>({type:"text",text:Q,cache_control:z.getCacheControl(J,{type:"system message",canCache:!0})}));if(D==null)D=k;else N.push({role:"system",content:k}),F.add("mid-conversation-system-2026-04-07");break}case"user":{let k=[];for(let Q of L.messages){let{role:J,content:W}=Q;switch(J){case"user":{for(let K=0;K<W.length;K++){let q=W[K],B=K===W.length-1,G=(a=z.getCacheControl(q.providerOptions,{type:"user message part",canCache:!0}))!=null?a:B?z.getCacheControl(Q.providerOptions,{type:"user message",canCache:!0}):void 0;switch(q.type){case"text":{k.push({type:"text",text:q.text,cache_control:G});break}case"file":{if(q.mediaType.startsWith("image/"))k.push({type:"image",source:nu(q.data)?{type:"url",url:ou(q.data)}:{type:"base64",media_type:q.mediaType==="image/*"?"image/jpeg":q.mediaType,data:bt(q.data)},cache_control:G});else if(q.mediaType==="application/pdf"){F.add("pdfs-2024-09-25");let Z=await re(q.providerOptions),A=await Y(q.providerOptions);k.push({type:"document",source:nu(q.data)?{type:"url",url:ou(q.data)}:{type:"base64",media_type:"application/pdf",data:bt(q.data)},title:(s=A.title)!=null?s:q.filename,...A.context&&{context:A.context},...Z&&{citations:{enabled:!0}},cache_control:G})}else if(q.mediaType==="text/plain"){let Z=await re(q.providerOptions),A=await Y(q.providerOptions);k.push({type:"document",source:nu(q.data)?{type:"url",url:ou(q.data)}:{type:"text",media_type:"text/plain",data:SN(q.data)},title:(l=A.title)!=null?l:q.filename,...A.context&&{context:A.context},...Z&&{citations:{enabled:!0}},cache_control:G})}else throw new He({functionality:`media type: ${q.mediaType}`});break}}}break}case"tool":{for(let K=0;K<W.length;K++){let q=W[K];if(q.type==="tool-approval-response")continue;let B=q.output,G="providerOptions"in B?B.providerOptions:B.type==="content"?(c=B.value.find((H)=>H.providerOptions!=null))==null?void 0:c.providerOptions:void 0,Z=K===W.length-1,A=(d=(u=z.getCacheControl(q.providerOptions,{type:"tool result part",canCache:!0}))!=null?u:z.getCacheControl(G,{type:"tool result output",canCache:!0}))!=null?d:Z?z.getCacheControl(Q.providerOptions,{type:"tool result message",canCache:!0}):void 0,O;switch(B.type){case"content":O=B.value.map((H)=>{var P;switch(H.type){case"text":return{type:"text",text:H.text};case"image-data":return{type:"image",source:{type:"base64",media_type:H.mediaType,data:H.data}};case"image-url":return{type:"image",source:{type:"url",url:H.url}};case"file-url":return{type:"document",source:{type:"url",url:H.url}};case"file-data":{if(H.mediaType==="application/pdf")return F.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:H.mediaType,data:H.data}};n.push({type:"other",message:`unsupported tool content part type: ${H.type} with media type: ${H.mediaType}`});return}case"custom":{let U=(P=H.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: ${H.type}`});return}}}).filter(fi);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:q.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=[],Q=new Set;for(let J=0;J<L.messages.length;J++){let W=L.messages[J],K=J===L.messages.length-1,{content:q}=W;for(let B=0;B<q.length;B++){let G=q[B],Z=B===q.length-1,A=(p=z.getCacheControl(G.providerOptions,{type:"assistant message part",canCache:!0}))!=null?p:Z?z.getCacheControl(W.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 $e({provider:"anthropic",providerOptions:G.providerOptions,schema:OO});if(O!=null)if(O.signature!=null)z.getCacheControl(G.providerOptions,{type:"thinking block",canCache:!1}),k.push({type:"thinking",thinking:G.text,signature:O.signature});else if(O.redactedData!=null)z.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"){Q.add(G.toolCallId);let ge=(w=(v=G.providerOptions)==null?void 0:v.anthropic)==null?void 0:w.serverName;if(ge==null||typeof ge!=="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:ge,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:ge,...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,H=(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,...H&&{caller:H},cache_control:A});break}case"tool-result":{let O=i.toProviderToolName(G.toolName);if(Q.has(G.toolCallId)){let H=G.output;if(H.type!=="json"&&H.type!=="error-json"){n.push({type:"other",message:`provider executed tool result output type ${H.type} for tool ${G.toolName} is not supported`});break}k.push({type:"mcp_tool_result",tool_use_id:G.toolCallId,is_error:H.type==="error-json",content:H.value,cache_control:A})}else if(O==="code_execution"){let H=G.output;if(H.type==="error-text"||H.type==="error-json"){let P={};try{if(typeof H.value==="string")P=er(H.value);else if(typeof H.value==="object"&&H.value!==null)P=H.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(H.type!=="json"){n.push({type:"other",message:`provider executed tool result output type ${H.type} for tool ${G.toolName} is not supported`});break}if(H.value==null||typeof H.value!=="object"||!("type"in H.value)||typeof H.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(H.value.type==="code_execution_result"){let P=await Ee({value:H.value,schema:l_});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(H.value.type==="encrypted_code_execution_result"){let P=await Ee({value:H.value,schema:u_});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:H.value,schema:c_});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 H=G.output;if(H.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 Xb(H.value)).errorCode)!=null?b:"unavailable"},cache_control:A});break}if(H.type!=="json"){n.push({type:"other",message:`provider executed tool result output type ${H.type} for tool ${G.toolName} is not supported`});break}let P=await Ee({value:H.value,schema:s_});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 H=G.output;if(H.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 Xb(H.value)).errorCode)!=null?E:"unavailable"},cache_control:A});break}if(H.type!=="json"){n.push({type:"other",message:`provider executed tool result output type ${H.type} for tool ${G.toolName} is not supported`});break}let P=await Ee({value:H.value,schema:a_});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 H=G.output;if(H.type!=="json"){n.push({type:"other",message:`provider executed tool result output type ${H.type} for tool ${G.toolName} is not supported`});break}let U=(await Ee({value:H.value,schema:d_})).map((ge)=>({type:"tool_reference",tool_name:ge.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 H=G.output;if(H.type!=="json"&&H.type!=="error-json"){n.push({type:"other",message:`provider executed tool result output type ${H.type} for tool ${G.toolName} is not supported`});break}let P=await Ee({value:H.value,schema:i_});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:IN(k)});break}default:throw Error(`content type: ${X}`)}}return{prompt:{system:D,messages:N},betas:F}}function TN(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 IN(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 iu({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 p_=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),CN=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","minItems","maxItems","uniqueItems","minProperties","maxProperties","not"];function kN(e){return m_(e)}function gn(e){if(typeof e==="boolean"||!PN(e))return e;return m_(e)}function m_(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(gn);else if(e.oneOf!=null)t.anyOf=e.oneOf.map(gn);if(e.allOf!=null)t.allOf=e.allOf.map(gn);if(e.definitions!=null)t.definitions=Object.fromEntries(Object.entries(e.definitions).map(([i,a])=>[i,gn(a)]));if(n.$defs!=null){let i=t;i.$defs=Object.fromEntries(Object.entries(n.$defs).map(([a,s])=>[a,gn(s)]))}if(e.type==="object"||e.properties!=null){if(e.properties!=null)t.properties=Object.fromEntries(Object.entries(e.properties).map(([i,a])=>[i,gn(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(gn):gn(e.items);if(typeof e.format==="string"&&p_.has(e.format))t.format=e.format;let o=RN(e);if(o!=null)t.description=t.description==null?o:`${t.description}
|
|
71
|
+
${o}`;return t}function RN(e){let t=CN.flatMap((n)=>{let o=e[n];if(o==null||o===!1)return[];return`${EN(n)}: ${AN(o)}`});if(typeof e.format==="string"&&!p_.has(e.format))t.push(`format: ${e.format}`);return t.length===0?void 0:`${t.join("; ")}.`}function EN(e){return e.replace(/[A-Z]/g,(t)=>` ${t.toLowerCase()}`)}function AN(e){if(typeof e==="string")return e;return JSON.stringify(e)}function PN(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function e_(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 MN=class{constructor(e,t){this.specificationVersion="v3";var n;this.modelId=e,this.config=t,this.generateId=(n=t.generateId)!=null?n:Le}supportsUrl(e){return e.protocol==="https:"}get provider(){return this.config.provider}get providerOptionsName(){let e=this.config.provider,t=e.indexOf(".");return t===-1?e:e.substring(0,t)}get supportedUrls(){var e,t,n;return(n=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?n:{}}async getArgs({userSuppliedBetas:e,prompt:t,maxOutputTokens:n,temperature:o,topP:i,topK:a,frequencyPenalty:s,presencePenalty:l,stopSequences:c,responseFormat:u,seed:d,tools:m,toolChoice:p,providerOptions:f,stream:g}){var h,v,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 $e({provider:"anthropic",providerOptions:f,schema:Kb}),z=F!=="anthropic"?await $e({provider:F,providerOptions:f,schema:Kb}):null,D=z!=null,N=Object.assign({},R!=null?R:{},z!=null?z:{}),{maxOutputTokens:re,supportsStructuredOutput:Y,rejectsSamplingParameters:V,isKnownModel:L}=jN(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-"),X=((h=this.config.supportsNativeStructuredOutput)!=null?h:!0)&&Y,k=((v=this.config.supportsStrictTools)!=null?v:!0)&&Y,Q=(w=N==null?void 0:N.structuredOutputMode)!=null?w:"auto",J=Q==="outputFormat"||Q==="auto"&&X,W=(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,q=new au,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 xN({prompt:t,sendReasoning:(S=N==null?void 0:N.sendReasoning)!=null?S:!0,warnings:E,cacheControlValidator:q,toolNameMapping:B}),A=(y=N==null?void 0:N.thinking)==null?void 0:y.type,O=A==="enabled"||A==="adaptive",H=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,ge=n!=null?n:re,ee={model:this.modelId,max_tokens:ge,temperature:o,top_k:a,top_p:i,stop_sequences:c,...H&&{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:kN(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=ge+(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 lN(W!=null?{tools:[...m!=null?m:[],W],toolChoice:{type:"required"},disableParallelToolUse:!0,cacheControlValidator:q,supportsStructuredOutput:!1,supportsStrictTools:k,defaultEagerInputStreaming:ue}:{tools:m!=null?m:[],toolChoice:p,disableParallelToolUse:N==null?void 0:N.disableParallelToolUse,cacheControlValidator:q,supportsStructuredOutput:X,supportsStrictTools:k,defaultEagerInputStreaming:ue}),Dr=q.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:W!=null,toolNameMapping:B,providerOptionsName:F,usedCustomProviderKey:D}}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=t_(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:Vb,successfulResponseHandler:xe(MO),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=e_(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:iu({finishReason:S.stop_reason,isJsonResponseFromTool:I}),raw:(a=S.stop_reason)!=null?a:void 0},usage:Qb({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,z;let D=n_(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,...D!=null?{stopDetails:D}:{},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:(z=r_(S.context_management))!=null?z: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=t_(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:Vb,successfulResponseHandler:Dt(jO),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,z=this.generateId,D=g.pipeThrough(new TransformStream({start(V){V.enqueue({type:"stream-start",warnings:i})},transform(V,L){var pe,X,k,Q,J,W,K,q,B,G,Z,A,O,H;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,ge=U.type;if(ge==="fallback")return;switch(R=ge,ge){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:z(),url:ee.url,title:ee.title,providerMetadata:{anthropic:{pageAge:(X=ee.page_age)!=null?X: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:(Q=U.content.content)!=null?Q:[]}});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: ${ge}`)}}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 ge=w[P.index],ee=P.delta.partial_json;if(ee.length===0)return;if(F){if((ge==null?void 0:ge.type)!=="text")return;L.enqueue({type:"text-delta",id:String(P.index),delta:ee})}else{if((ge==null?void 0:ge.type)!=="tool-call")return;if(ge.firstDelta&&ge.providerToolInputType!=null)ee=`{"type": "${ge.providerToolInputType}",${ee.substring(1)}`;L.enqueue({type:"tool-input-delta",id:ge.toolCallId,delta:ee}),ge.input+=ee,ge.firstDelta=!1}return}case"citations_delta":{let ge=P.delta.citation,ee=e_(ge,d,z);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=(W=P.message.usage.cache_creation_input_tokens)!=null?W: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:iu({finishReason:P.message.stop_reason,isJsonResponseFromTool:F}),raw:P.message.stop_reason};if(L.enqueue({type:"response-metadata",id:(q=P.message.id)!=null?q: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 ge=P.message.content[U];if(ge.type==="tool_use"){let ee=ge.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:ge.id,toolName:ge.name});let Ae=JSON.stringify((G=ge.input)!=null?G:{});L.enqueue({type:"tool-input-delta",id:ge.id,delta:Ae}),L.enqueue({type:"tool-input-end",id:ge.id}),L.enqueue({type:"tool-call",toolCallId:ge.id,toolName:ge.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:iu({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=n_(P.delta.stop_details),E=P.delta.container!=null?{expiresAt:P.delta.container.expires_at,id:P.delta.container.id,skills:(H=(O=P.delta.container.skills)==null?void 0:O.map((U)=>({type:U.type,skillId:U.skill_id,version:U.version})))!=null?H:null}:null,P.context_management)x=r_(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},ge={anthropic:U};if(u&&c!=="anthropic")ge[c]=U;L.enqueue({type:"finish",finishReason:h,usage:Qb({usage:v,rawUsage:_}),providerMetadata:ge});return}case"error":{L.enqueue({type:"error",error:P.error});return}default:throw Error(`Unsupported chunk type: ${P}`)}}})),[N,re]=D.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 jN(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 t_(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 r_(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 n_(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 ON=j(()=>M(r.object({command:r.string(),restart:r.boolean().optional()}))),NN=Ge({id:"anthropic.bash_20241022",inputSchema:ON}),DN=j(()=>M(r.object({command:r.string(),restart:r.boolean().optional()}))),zN=Ge({id:"anthropic.bash_20250124",inputSchema:DN}),$N=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()}))),qN=Ge({id:"anthropic.computer_20241022",inputSchema:$N}),LN=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()}))),UN=Ge({id:"anthropic.computer_20250124",inputSchema:LN}),FN=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()}))),BN=Ge({id:"anthropic.computer_20251124",inputSchema:FN}),GN=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()})]))),JN=Ge({id:"anthropic.memory_20250818",inputSchema:GN}),WN=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()}))),HN=Ge({id:"anthropic.text_editor_20241022",inputSchema:WN}),VN=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()}))),ZN=Ge({id:"anthropic.text_editor_20250124",inputSchema:VN}),KN=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()}))),YN=Ge({id:"anthropic.text_editor_20250429",inputSchema:KN}),QN=j(()=>M(r.array(r.object({type:r.literal("tool_reference"),toolName:r.string()})))),XN=j(()=>M(r.object({query:r.string(),limit:r.number().optional()}))),eD=Te({id:"anthropic.tool_search_bm25_20251119",inputSchema:XN,outputSchema:QN,supportsDeferredResults:!0}),tD=(e={})=>eD(e),rD={advisor_20260301:qO,bash_20241022:NN,bash_20250124:zN,codeExecution_20250522:dN,codeExecution_20250825:gN,codeExecution_20260120:yN,computer_20241022:qN,computer_20250124:UN,computer_20251124:BN,memory_20250818:JN,textEditor_20241022:HN,textEditor_20250124:ZN,textEditor_20250429:YN,textEditor_20250728:BO,webFetch_20250910:sN,webFetch_20260209:nN,webSearch_20250305:QO,webSearch_20260209:VO,toolSearchRegex_20251119:_N,toolSearchBm25_20251119:tD},g_="https://api.anthropic.com",f_=`${g_}/v1`;function nD(e){let t=pn(e);return t===g_?f_:t}function su(e={}){var t,n;let o=(t=nD(Ar({settingValue:e.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"})))!=null?t:f_,i=(n=e.name)!=null?n:"anthropic.messages";if(e.apiKey&&e.authToken)throw new Qn({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":so({apiKey:e.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"})};return it({"anthropic-version":"2023-06-01",...c,...e.headers},`ai-sdk/anthropic/${AO}`)},s=(c)=>{var u;return new MN(c,{provider:i,baseURL:o,headers:a,fetch:e.fetch,generateId:(u=e.generateId)!=null?u:Le,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]})})},l=function(c){if(new.target)throw Error("The Anthropic model function cannot be called with the new keyword.");return s(c)};return l.specificationVersion="v3",l.languageModel=s,l.chat=s,l.messages=s,l.embeddingModel=(c)=>{throw new al({modelId:c,modelType:"embeddingModel"})},l.textEmbeddingModel=l.embeddingModel,l.imageModel=(c)=>{throw new al({modelId:c,modelType:"imageModel"})},l.tools=rD,l}var h_=su();var gu=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:gu,errorToMessage:(e)=>e.error.message});function D_(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 fu({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(()=>{}),oD({frame:m,url:o,requestBodyValues:i,responseHeaders:a});if(n(d.value))return l}}finally{c.cancel().catch(()=>{}),c.releaseLock()}}function oD({frame:e,url:t,requestBodyValues:n,responseHeaders:o}){var i;let a=iD(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:aD(a),responseHeaders:o,responseBody:JSON.stringify(e),data:e})}function iD(e){var t;let n=Ni(e);if(n==null)return;if(n.type==="response.failed"){let i=Ni(n.response),a=Ni(i==null?void 0:i.error);return typeof(a==null?void 0:a.message)==="string"?{message:a.message,code:y_(a.code),type:"response.failed",frame:e}:void 0}let o=(t=Ni(n.error))!=null?t:n;return typeof o.message==="string"&&(Ni(n.error)!=null||typeof o.type==="string"||("code"in o)||("param"in o))?{message:o.message,code:y_(o.code),type:typeof o.type==="string"?o.type:void 0,frame:e}:void 0}function aD(e){if(typeof e.code==="number"&&v_(e.code))return e.code;if(typeof e.code==="string"&&/^\d{3}$/.test(e.code)){let n=Number(e.code);if(v_(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 Ni(e){return typeof e==="object"&&e!=null?e:void 0}function y_(e){return typeof e==="string"||typeof e==="number"?e:void 0}function v_(e){return Number.isInteger(e)&&e>=400&&e<=599}function b_(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 sD(e){return JSON.stringify(e===void 0?{}:e)}function lD({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 He({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 He({functionality:`audio content parts with media type ${l.mediaType}`})}}else if(l.mediaType==="application/pdf"){if(l.data instanceof URL)throw new He({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 He({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:sD(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 lu({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 __(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var cD=j(()=>M(r.object({id:r.string().nullish(),created:r.number().nullish(),model:r.string().nullish(),choices:r.array(r.object({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()}))),uD=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()}),gu]))),dD=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 pD({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 He({functionality:`tool choice type: ${i}`})}}var mD=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 $e({provider:"openai",providerOptions:p,schema:dD}))!=null?f:{},x=D_(this.modelId),_=(g=y.forceReasoning)!=null?g:x.isReasoningModel;if(i!=null)S.push({type:"unsupported",feature:"topK"});let{messages:C,warnings:I}=lD({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:z}=pD({tools:d,toolChoice:m});return{args:{...E,tools:F,tool_choice:R},warnings:[...S,...z]}}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(cD),abortSignal:e.abortSignal,fetch:this.config.fetch}),f=m.choices[0],g=[],h=f.message.content;if(h!=null&&h.length>0)g.push({type:"text",text:h});for(let y of(t=f.message.tool_calls)!=null?t:[])g.push({type:"tool-call",toolCallId:(n=y.id)!=null?n:Le(),toolName:y.function.name,input:y.function.arguments});for(let y of(o=f.message.annotations)!=null?o:[])g.push({type:"source",sourceType:"url",id:Le(),url:y.url_citation.url,title:y.url_citation.title});let v=(i=m.usage)==null?void 0:i.completion_tokens_details,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:__(f.finish_reason),raw:(l=f.finish_reason)!=null?l:void 0},usage:b_(m.usage),request:{body:c},response:{...lu(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(uD),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=await fu({stream:s,getError:(h)=>("error"in h)?h.error:void 0,isOutputChunk:gD,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,z,D;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=lu(N);if(Object.values(V).some(Boolean))m=!0,v.enqueue({type:"response-metadata",...lu(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:__(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 X=c[L];if(((b=X.function)==null?void 0:b.name)!=null&&((E=X.function)==null?void 0:E.arguments)!=null){if(X.function.arguments.length>0)v.enqueue({type:"tool-input-delta",id:X.id,delta:X.function.arguments})}continue}let pe=c[L];if(pe.hasFinished)continue;if(((F=V.function)==null?void 0:F.arguments)!=null)pe.function.arguments+=(z=(R=V.function)==null?void 0:R.arguments)!=null?z:"";v.enqueue({type:"tool-input-delta",id:pe.id,delta:(D=V.function.arguments)!=null?D:""})}if(Y.annotations!=null)for(let V of Y.annotations)v.enqueue({type:"source",sourceType:"url",id:Le(),url:V.url_citation.url,title:V.url_citation.title})},flush(h){var v;if(p)h.enqueue({type:"text-end",id:"0"});for(let 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:Le(),toolName:w.function.name,input:w.function.arguments}),w.hasFinished=!0;h.enqueue({type:"finish",finishReason:u,usage:b_(d),...f!=null?{providerMetadata:f}:{}})}})),request:{body:o},response:{headers:a}}}};function gD(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 S_(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 fD({prompt:e,user:t="user",assistant:n="assistant"}){let o="";if(e[0].role==="system")o+=`${e[0].content}
|
|
72
72
|
|
|
73
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
74
|
${s}
|
|
@@ -78,23 +78,23 @@ ${s}
|
|
|
78
78
|
|
|
79
79
|
`;break}case"tool":throw new He({functionality:"tool messages"});default:throw Error(`Unsupported role: ${i}`)}return o+=`${n}:
|
|
80
80
|
`,{prompt:o,stopSequences:[`
|
|
81
|
-
${t}:`]}}function w_({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 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 hD=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()}))),yD=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()}),gu]))),T_=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()}))),vD=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 qe({provider:"openai",providerOptions:p,schema:T_}),...await qe({provider:this.providerOptionsName,providerOptions:p,schema:T_})};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}=fD({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(hD),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:S_(a.usage),finishReason:{unified:x_(l.finish_reason),raw:(t=l.finish_reason)!=null?t:void 0},request:{body:n},response:{...w_(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(yD),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=await fu({stream:s,getError:(f)=>("error"in f)?f.error:void 0,isOutputChunk:bD,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",...w_(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:x_(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:S_(d)})}})),request:{body:o},response:{headers:a}}}};function bD(e){return!("error"in e)&&e.choices.some((t)=>t.text.length>0)}var _D=j(()=>M(r.object({dimensions:r.number().optional(),user:r.string().optional()}))),SD=j(()=>M(r.object({data:r.array(r.object({embedding:r.array(r.number())})),usage:r.object({prompt_tokens:r.number()}).nullish()}))),wD=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 qe({provider:"openai",providerOptions:o,schema:_D}))!=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(SD),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}}}},I_=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()}))),xD={"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},TD=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1","gpt-image-2"];function ID(e){return TD.some((t)=>e.startsWith(t))}var hu=r.object({quality:r.enum(["standard","hd","low","medium","high","auto"]).optional(),background:r.enum(["transparent","opaque","auto"]).optional(),outputFormat:r.enum(["png","jpeg","webp"]).optional(),outputCompression:r.number().int().min(0).max(100).optional(),user:r.string().optional()}),j3=j(()=>M(hu)),CD=j(()=>M(hu.extend({style:r.enum(["vivid","natural"]).optional(),moderation:r.enum(["auto","low"]).optional()}))),kD=j(()=>M(hu.extend({inputFidelity:r.enum(["high","low"]).optional()}))),RD=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get maxImagesPerCall(){var e;return(e=xD[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 qe({provider:"openai",providerOptions:l,schema:kD}))!=null?f:{},{value:R,responseHeaders:z}=await ja({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:_e(this.config.headers(),c),formData:Fm({model:this.modelId,prompt:e,image:await Promise.all(t.map((D)=>D.type==="file"?new Blob([D.data instanceof Uint8Array?new Blob([D.data],{type:D.mediaType}):new Blob([wt(D.data)],{type:D.mediaType})],{type:D.mediaType}):Sl(D.url))),mask:n!=null?await ED(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(I_),abortSignal:u,fetch:this.config.fetch});return{images:R.data.map((D)=>D.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:z},providerMetadata:{openai:{images:R.data.map((D,N)=>{var re,Y,V,L,pe,X;return{...D.revised_prompt?{revisedPrompt:D.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,...C_((X=R.usage)==null?void 0:X.input_tokens_details,N,R.data.length)}})}}}}let I=(w=await qe({provider:"openai",providerOptions:l,schema:CD}))!=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,...!ID(this.modelId)?{response_format:"b64_json"}:{}},failedResponseHandler:gr,successfulResponseHandler:xe(I_),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 z,D,N,re,Y,V;return{...F.revised_prompt?{revisedPrompt:F.revised_prompt}:{},created:(z=b.created)!=null?z:void 0,size:(D=b.size)!=null?D: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,...C_((V=b.usage)==null?void 0:V.input_tokens_details,R,b.data.length)}})}}}}};function C_(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 ED(e){if(!e)return;if(e.type==="url")return Sl(e.url);let t=e.data instanceof Uint8Array?e.data:wt(e.data);return new Blob([t],{type:e.mediaType})}var z_=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()})])}))),q_=j(()=>M(r.object({status:r.enum(["completed","failed"]),output:r.string().optional()}))),D3=j(()=>M(r.object({}))),AD=Te({id:"openai.apply_patch",inputSchema:z_,outputSchema:q_}),PD=AD,MD=j(()=>M(r.object({code:r.string().nullish(),containerId:r.string()}))),jD=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()}))),OD=j(()=>M(r.object({container:r.union([r.string(),r.object({fileIds:r.array(r.string()).optional()})]).optional()}))),ND=Te({id:"openai.code_interpreter",inputSchema:MD,outputSchema:jD}),DD=(e={})=>ND(e),zD=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()}))),qD=j(()=>M(r.string())),$D=Ge({id:"openai.custom",inputSchema:qD}),LD=(e)=>$D(e),$_=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())])}),L_=r.object({type:r.enum(["and","or"]),filters:r.array(r.union([$_,r.lazy(()=>L_)]))}),UD=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([$_,L_]).optional()}))),FD=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()}))),BD=Te({id:"openai.file_search",inputSchema:r.object({}),outputSchema:FD}),GD=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())),JD=j(()=>M(r.object({}))),WD=j(()=>M(r.object({result:r.string()}))),HD=Te({id:"openai.image_generation",inputSchema:JD,outputSchema:WD}),VD=(e={})=>HD(e),U_=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()})}))),F_=j(()=>M(r.object({output:r.string()}))),ZD=Te({id:"openai.local_shell",inputSchema:U_,outputSchema:F_}),B_=j(()=>M(r.object({action:r.object({commands:r.array(r.string()),timeoutMs:r.number().optional(),maxOutputLength:r.number().optional()})}))),uu=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()})])}))}))),KD=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(),YD=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:KD}),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()}))),QD=Te({id:"openai.shell",inputSchema:B_,outputSchema:uu}),XD=j(()=>M(r.object({execution:r.enum(["server","client"]).optional(),description:r.string().optional(),parameters:r.record(r.string(),r.unknown()).optional()}))),du=j(()=>M(r.object({arguments:r.unknown().optional(),call_id:r.string().nullish()}))),pu=j(()=>M(r.object({tools:r.array(r.record(r.string(),r.unknown()))}))),e1=Te({id:"openai.tool_search",inputSchema:du,outputSchema:pu}),t1=(e={})=>e1(e),r1=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()}))),n1=j(()=>M(r.object({}))),o1=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()}))),i1=Te({id:"openai.web_search",inputSchema:n1,outputSchema:o1}),a1=(e={})=>i1(e),s1=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()}))),l1=j(()=>M(r.object({}))),c1=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()}))),u1=Te({id:"openai.web_search_preview",inputSchema:l1,outputSchema:c1}),mu=r.lazy(()=>r.union([r.string(),r.number(),r.boolean(),r.null(),r.array(mu),r.record(r.string(),mu)])),d1=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."))),p1=j(()=>M(r.object({}))),m1=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(),mu]).optional()}))),g1=Te({id:"openai.mcp",inputSchema:p1,outputSchema:m1}),f1=(e)=>g1(e),h1={applyPatch:PD,customTool:LD,codeInterpreter:DD,fileSearch:BD,imageGeneration:VD,localShell:ZD,shell:QD,webSearchPreview:u1,webSearch:a1,mcp:f1,toolSearch:t1};function k_(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 y1(e){return JSON.stringify(e===void 0?{}:e)}function R_(e,t){if(!t)return!1;return t.some((n)=>e.startsWith(n))}async function v1({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,z,D,N,re,Y,V,L,pe;let X=[],k=[],Q=new Set;for(let{role:J,content:W}of e)switch(J){case"system":{switch(n){case"system":{X.push({role:"system",content:W});break}case"developer":{X.push({role:"developer",content:W});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":{X.push({role:"user",content:W.map((K,q)=>{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"&&R_(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 He({functionality:`file part media type ${A}`});return{type:"input_file",...typeof K.data==="string"&&R_(K.data,i)?{file_id:K.data}:{filename:(Z=K.filename)!=null?Z:A==="application/pdf"?`part-${q}.pdf`:`part-${q}`,file_data:`data:${A};base64,${bt(K.data)}`}}}}})});break}case"assistant":{let K={};for(let q of W)switch(q.type){case"text":{let B=(f=q.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){X.push({type:"item_reference",id:G});break}X.push({role:"assistant",content:[{type:"output_text",text:q.text}],id:G,...Z!=null&&{phase:Z}});break}case"tool-call":{let B=(S=(h=(g=q.providerOptions)==null?void 0:g[o])==null?void 0:h.itemId)!=null?S:(w=(v=q.providerMetadata)==null?void 0:v[o])==null?void 0:w.itemId,G=(I=(x=(y=q.providerOptions)==null?void 0:y[o])==null?void 0:x.namespace)!=null?I:(C=(_=q.providerMetadata)==null?void 0:_[o])==null?void 0:C.namespace;if(l&&B!=null)break;let Z=t.toProviderToolName(q.toolName);if(Z==="tool_search"){if(s&&B!=null){X.push({type:"item_reference",id:B});break}let O=typeof q.input==="string"?await xl({text:q.input,schema:du}):await Ee({value:q.input,schema:du}),H=O.call_id!=null?"client":"server";X.push({type:"tool_search_call",id:B!=null?B:q.toolCallId,execution:H,call_id:(b=O.call_id)!=null?b:null,status:"completed",arguments:O.arguments});break}if(q.providerExecuted){if(s&&B!=null)X.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){X.push({type:"item_reference",id:B});break}if(u&&Z==="local_shell"){let O=await Ee({value:q.input,schema:U_});X.push({type:"local_shell_call",call_id:q.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:q.input,schema:B_});X.push({type:"shell_call",call_id:q.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:q.input,schema:z_});X.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)){X.push({type:"custom_tool_call",call_id:q.toolCallId,name:Z,input:typeof q.input==="string"?q.input:JSON.stringify(q.input),id:B});break}X.push({type:"function_call",call_id:q.toolCallId,name:Z,arguments:y1(q.input),...G!=null&&{namespace:G}});break}case"tool-result":{if(q.output.type==="execution-denied"||q.output.type==="json"&&typeof q.output.value==="object"&&q.output.value!=null&&"type"in q.output.value&&q.output.value.type==="execution-denied")break;if(l)break;let B=t.toProviderToolName(q.toolName);if(B==="tool_search"){let G=(z=(R=(F=q.providerOptions)==null?void 0:F[o])==null?void 0:R.itemId)!=null?z:q.toolCallId;if(s)X.push({type:"item_reference",id:G});else if(q.output.type==="json"){let Z=await Ee({value:q.output.value,schema:pu});X.push({type:"tool_search_output",id:G,execution:"server",call_id:null,status:"completed",tools:Z.tools})}break}if(d&&B==="shell"){if(q.output.type==="json"){let G=await Ee({value:q.output.value,schema:uu});X.push({type:"shell_call_output",call_id:q.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=(D=q.providerOptions)==null?void 0:D[o])==null?void 0:N.itemId)!=null?re:q.toolCallId;X.push({type:"item_reference",id:G})}else k.push({type:"other",message:`Results for OpenAI tool ${q.toolName} are not sent to the API when store is false`});break}case"reasoning":{let B=await qe({provider:o,providerOptions:q.providerOptions,schema:b1}),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)X.push({type:"item_reference",id:G}),K[G]={type:"reasoning",id:G,summary:[]}}else{let A=[];if(q.text.length>0)A.push({type:"summary_text",text:q.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(q)}.`});if(Z===void 0)K[G]={type:"reasoning",id:G,encrypted_content:B==null?void 0:B.reasoningEncryptedContent,summary:A},X.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(q.text.length>0)A.push({type:"summary_text",text:q.text});X.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(q)}.`})}break}}break}case"tool":{for(let K of W){if(K.type==="tool-approval-response"){let Z=K;if(Q.has(Z.approvalId))continue;if(Q.add(Z.approvalId),s)X.push({type:"item_reference",id:Z.approvalId});X.push({type:"mcp_approval_response",approval_request_id:Z.approvalId,approve:Z.approved});continue}let q=K.output;if(q.type==="execution-denied"){if((V=(Y=q.providerOptions)==null?void 0:Y.openai)==null?void 0:V.approvalId)continue}let B=t.toProviderToolName(K.toolName);if(B==="tool_search"&&q.type==="json"){let Z=await Ee({value:q.value,schema:pu});X.push({type:"tool_search_output",execution:"client",call_id:K.toolCallId,status:"completed",tools:Z.tools});continue}if(u&&B==="local_shell"&&q.type==="json"){let Z=await Ee({value:q.value,schema:F_});X.push({type:"local_shell_call_output",call_id:K.toolCallId,output:Z.output});continue}if(d&&B==="shell"&&q.type==="json"){let Z=await Ee({value:q.value,schema:uu});X.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"&&q.type==="json"){let Z=await Ee({value:q.value,schema:q_});X.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(q.type){case"text":case"error-text":Z=q.value;break;case"execution-denied":Z=(L=q.reason)!=null?L:"Tool call execution denied.";break;case"json":case"error-json":Z=JSON.stringify(q.value);break;case"content":Z=q.value.map((A)=>{var O,H,P,U,ge;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:(H=(O=A.providerOptions)==null?void 0:O[o])==null?void 0:H.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:(ge=A.filename)!=null?ge:"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(fi);break;default:Z=""}X.push({type:"custom_tool_call_output",call_id:K.toolCallId,output:Z});continue}let G;switch(q.type){case"text":case"error-text":G=q.value;break;case"execution-denied":G=(pe=q.reason)!=null?pe:"Tool call execution denied.";break;case"json":case"error-json":G=JSON.stringify(q.value);break;case"content":G=q.value.map((Z)=>{var A,O,H,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=(H=Z.providerOptions)==null?void 0:H[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(fi);break}X.push({type:"function_call_output",call_id:K.toolCallId,output:G})}break}default:throw Error(`Unsupported role: ${J}`)}if(!s&&X.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."}),X=X.filter((J)=>!("type"in J)||J.type!=="reasoning"||J.encrypted_content!=null);return{input:X,warnings:k}}var b1=r.object({itemId:r.string().nullish(),reasoningEncryptedContent:r.string().nullish()});function cu({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 Di=r.lazy(()=>r.union([r.string(),r.number(),r.boolean(),r.null(),r.array(Di),r.record(r.string(),Di.optional())])),_1=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()})}),S1=r.object({type:r.literal("error"),sequence_number:r.number(),code:r.string().nullish(),message:r.string(),param:r.string().nullish()}),w1=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(),Di.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(),Di.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()}),_1,S1,r.object({type:r.string()}).loose().transform((e)=>({type:"unknown_chunk",message:e.type}))]))),x1=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(),Di.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()}))),G_=20,T1=["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"],p9=["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",...T1],E_=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(G_)]).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 I1({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=C1({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 He({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:UD});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:YD});u.push({type:"shell",...g.environment&&{environment:k1(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:s1});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:r1});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:OD});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:GD});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:d1}),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:zD});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:XD});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 He({functionality:`tool choice type: ${p}`})}}function C1({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 k1(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:R1(n.skills)}}return{type:"local",skills:e.skills}}function R1(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 A_(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 E1=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=D_(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 qe({provider:F,providerOptions:u,schema:E_});if(R==null&&F!=="openai")R=await qe({provider:"openai",providerOptions:u,schema:E_});let z=(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 D=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 I1({tools:d,toolChoice:m,allowedTools:(g=R==null?void 0:R.allowedTools)!=null?g:void 0,toolNameMapping:D,customProviderToolNames:N}),{input:L,warnings:pe}=await v1({prompt:c,toolNameMapping:D,systemMessageMode:(h=R==null?void 0:R.systemMessageMode)!=null?h:z?"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 X=(S=R==null?void 0:R.strictJsonSchema)!=null?S:!0,k=R==null?void 0:R.include;function Q(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 W=typeof(R==null?void 0:R.logprobs)==="number"?R==null?void 0:R.logprobs:(R==null?void 0:R.logprobs)===!0?G_:void 0;if(W)Q("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)Q("web_search_call.action.sources");if(J("openai.code_interpreter"))Q("code_interpreter_call.outputs");let q=R==null?void 0:R.store;if(q===!1&&z)Q("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:X,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:q,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:W,truncation:R==null?void 0:R.truncation,...z&&((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(z){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:q,toolNameMapping:D,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,z;let{args:D,warnings:N,webSearchToolName:re,toolNameMapping:Y,providerOptionsName:V,isShellProviderExecuted:L}=await this.getArgs(e),pe=this.config.url({path:"/responses",modelId:this.modelId}),X=A_(e.prompt),{responseHeaders:k,value:Q,rawValue:J}=await Ie({url:pe,headers:_e(this.config.headers(),e.headers),body:D,failedResponseHandler:gr,successfulResponseHandler:xe(x1),abortSignal:e.abortSignal,fetch:this.config.fetch});if(Q.error)throw new De({message:Q.error.message,url:pe,requestBodyValues:D,statusCode:400,responseHeaders:k,responseBody:J,isRetryable:!1});let W=[],K=[],q=!1,B=[];for(let A of Q.output)switch(A.type){case"reasoning":{if(A.summary.length===0)A.summary.push({type:"summary_text",text:""});for(let O of A.summary)W.push({type:"reasoning",text:O.text,providerMetadata:{[V]:{itemId:A.id,reasoningEncryptedContent:(t=A.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{W.push({type:"tool-call",toolCallId:A.id,toolName:Y.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),W.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,H=A.execution==="server";if(H)B.push(O);W.push({type:"tool-call",toolCallId:O,toolName:Y.toCustomToolName("tool_search"),input:JSON.stringify({arguments:A.arguments,call_id:A.call_id}),...H?{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;W.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":{W.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":{W.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":{W.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 H={itemId:A.id,...A.phase!=null&&{phase:A.phase},...O.annotations.length>0&&{annotations:O.annotations}};W.push({type:"text",text:O.text,providerMetadata:{[V]:H}});for(let P of O.annotations)if(P.type==="url_citation")W.push({type:"source",sourceType:"url",id:(u=(c=(l=this.config).generateId)==null?void 0:c.call(l))!=null?u:Le(),url:P.url,title:P.title});else if(P.type==="file_citation")W.push({type:"source",sourceType:"document",id:(p=(m=(d=this.config).generateId)==null?void 0:m.call(d))!=null?p:Le(),mediaType:"text/plain",title:P.filename,filename:P.filename,providerMetadata:{[V]:{type:P.type,fileId:P.file_id,index:P.index}}});else if(P.type==="container_file_citation")W.push({type:"source",sourceType:"document",id:(h=(g=(f=this.config).generateId)==null?void 0:g.call(f))!=null?h:Le(),mediaType:"text/plain",title:P.filename,filename:P.filename,providerMetadata:{[V]:{type:P.type,fileId:P.file_id,containerId:P.container_id}}});else if(P.type==="file_path")W.push({type:"source",sourceType:"document",id:(S=(w=(v=this.config).generateId)==null?void 0:w.call(v))!=null?S:Le(),mediaType:"application/octet-stream",title:P.file_id,filename:P.file_id,providerMetadata:{[V]:{type:P.type,fileId:P.file_id,index:P.index}}})}break}case"function_call":{q=!0,W.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":{q=!0;let O=Y.toCustomToolName(A.name);W.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":{W.push({type:"tool-call",toolCallId:A.id,toolName:Y.toCustomToolName(re!=null?re:"web_search"),input:JSON.stringify({}),providerExecuted:!0}),W.push({type:"tool-result",toolCallId:A.id,toolName:Y.toCustomToolName(re!=null?re:"web_search"),result:O_(A.action)});break}case"mcp_call":{let O=A.approval_request_id!=null?(y=X[A.approval_request_id])!=null?y:A.id:A.id,H=`mcp.${A.name}`;W.push({type:"tool-call",toolCallId:O,toolName:H,input:A.arguments,providerExecuted:!0,dynamic:!0}),W.push({type:"tool-result",toolCallId:O,toolName:H,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,H=(I=(C=(_=this.config).generateId)==null?void 0:C.call(_))!=null?I:Le(),P=`mcp.${A.name}`;W.push({type:"tool-call",toolCallId:H,toolName:P,input:A.arguments,providerExecuted:!0,dynamic:!0}),W.push({type:"tool-approval-request",approvalId:O,toolCallId:H});break}case"computer_call":{W.push({type:"tool-call",toolCallId:A.id,toolName:Y.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),W.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":{W.push({type:"tool-call",toolCallId:A.id,toolName:Y.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),W.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":{W.push({type:"tool-call",toolCallId:A.id,toolName:Y.toCustomToolName("code_interpreter"),input:JSON.stringify({code:A.code,containerId:A.container_id}),providerExecuted:!0}),W.push({type:"tool-result",toolCallId:A.id,toolName:Y.toCustomToolName("code_interpreter"),result:{outputs:A.outputs}});break}case"apply_patch_call":{W.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:Q.id,...K.length>0?{logprobs:K}:{},...typeof Q.service_tier==="string"?{serviceTier:Q.service_tier}:{}}},Z=Q.usage;return{content:W,finishReason:{unified:cu({finishReason:(F=Q.incomplete_details)==null?void 0:F.reason,hasFunctionCall:q}),raw:(z=(R=Q.incomplete_details)==null?void 0:R.reason)!=null?z:void 0},usage:k_(Z),request:{body:D},response:{id:Q.id,timestamp:new Date(Q.created_at*1000),modelId:Q.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(w1),abortSignal:e.abortSignal,fetch:this.config.fetch}),m=await fu({stream:d,getError:(z)=>j_(z)||P_(z)&&z.response.error!=null?z:void 0,isOutputChunk:J1,url:c,requestBodyValues:t,responseHeaders:u}),p=this,f=A_(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(z){z.enqueue({type:"stream-start",warnings:n})},transform(z,D){var N,re,Y,V,L,pe,X,k,Q,J,W,K,q,B,G,Z,A,O,H,P,U,ge,ee,ue,Ae,Ke,nt,At,Dr,he,br,zr,tn,wn,_r,st,rn,ut;if(e.includeRawChunks)D.enqueue({type:"raw",rawValue:z.rawValue});if(!z.success){let te=P1(z.rawValue)?M1({value:z.rawValue,cause:z.error,url:c,requestBodyValues:t,responseHeaders:u}):z.error;h={unified:"error",raw:void 0},D.enqueue({type:"error",error:te});return}let T=z.value;if(M_(T)){if(T.item.type==="function_call")y[T.output_index]={toolName:T.item.name,toolCallId:T.item.call_id},D.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},D.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},D.enqueue({type:"tool-input-start",id:T.item.id,toolName:i.toCustomToolName(o!=null?o:"web_search"),providerExecuted:!0}),D.enqueue({type:"tool-input-end",id:T.item.id}),D.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},D.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}},D.enqueue({type:"tool-input-start",id:T.item.id,toolName:i.toCustomToolName("code_interpreter"),providerExecuted:!0}),D.enqueue({type:"tool-input-delta",id:T.item.id,delta:`{"containerId":"${T.item.container_id}","code":"`});else if(T.item.type==="file_search_call")D.enqueue({type:"tool-call",toolCallId:T.item.id,toolName:i.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(T.item.type==="image_generation_call")D.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"),ke=T.item.execution==="server";if(y[T.output_index]={toolName:ve,toolCallId:te,toolSearchExecution:(N=T.item.execution)!=null?N:"server"},ke)D.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"}},D.enqueue({type:"tool-input-start",id:te,toolName:i.toCustomToolName("apply_patch")}),ve.type==="delete_file"){let ke=JSON.stringify({callId:te,operation:ve});D.enqueue({type:"tool-input-delta",id:te,delta:ke}),D.enqueue({type:"tool-input-end",id:te})}else D.enqueue({type:"tool-input-delta",id:te,delta:`{"callId":"${zn(te)}","operation":{"type":"${zn(ve.type)}","path":"${zn(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,D.enqueue({type:"text-start",id:T.item.id,providerMetadata:{[s]:{itemId:T.item.id,...T.item.phase!=null&&{phase:T.item.phase}}}});else if(M_(T)&&T.item.type==="reasoning")I[T.item.id]={encryptedContent:T.item.encrypted_content,summaryParts:{0:"active"}},D.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(O1(T)){if(T.item.type==="message"){let te=(V=T.item.phase)!=null?V:_;_=void 0,D.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,D.enqueue({type:"tool-input-end",id:T.item.call_id,...T.item.namespace!=null&&{providerMetadata:{[s]:{namespace:T.item.namespace}}}}),D.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);D.enqueue({type:"tool-input-end",id:T.item.call_id}),D.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,D.enqueue({type:"tool-result",toolCallId:T.item.id,toolName:i.toCustomToolName(o!=null?o:"web_search"),result:O_(T.item.action)});else if(T.item.type==="computer_call")y[T.output_index]=void 0,D.enqueue({type:"tool-input-end",id:T.item.id}),D.enqueue({type:"tool-call",toolCallId:T.item.id,toolName:i.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),D.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,D.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,D.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")D.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 ke=ve?te.toolCallId:(X=T.item.call_id)!=null?X:T.item.id;if(ve)E.push(ke);else D.enqueue({type:"tool-input-start",id:ke,toolName:te.toolName});D.enqueue({type:"tool-input-end",id:ke}),D.enqueue({type:"tool-call",toolCallId:ke,toolName:te.toolName,input:JSON.stringify({arguments:T.item.arguments,call_id:ve?null:ke}),...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=(Q=(k=T.item.call_id)!=null?k:E.shift())!=null?Q:T.item.id;D.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=(W=g.get(te))!=null?W:f[te])!=null?K:T.item.id:T.item.id,ke=`mcp.${T.item.name}`;D.enqueue({type:"tool-call",toolCallId:ve,toolName:ke,input:T.item.arguments,providerExecuted:!0,dynamic:!0}),D.enqueue({type:"tool-result",toolCallId:ve,toolName:ke,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)D.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:zn(T.item.operation.diff)});D.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:'"}}'}),D.enqueue({type:"tool-input-end",id:te.toolCallId}),te.applyPatch.endEmitted=!0}if(te&&T.item.status==="completed")D.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=(q=p.config).generateId)==null?void 0:B.call(q))!=null?G:Le(),ve=(Z=T.item.approval_request_id)!=null?Z:T.item.id;g.set(ve,te);let ke=`mcp.${T.item.name}`;D.enqueue({type:"tool-call",toolCallId:te,toolName:ke,input:T.item.arguments,providerExecuted:!0,dynamic:!0}),D.enqueue({type:"tool-approval-request",approvalId:ve,toolCallId:te})}else if(T.item.type==="local_shell_call")y[T.output_index]=void 0,D.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,D.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")D.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(([ke,ht])=>ht==="active"||ht==="can-conclude").map(([ke])=>ke);for(let ke of ve)D.enqueue({type:"reasoning-end",id:`${T.item.id}:${ke}`,providerMetadata:{[s]:{itemId:T.item.id,reasoningEncryptedContent:(A=T.item.encrypted_content)!=null?A:null}}});delete I[T.item.id]}}else if(z1(T)){let te=y[T.output_index];if(te!=null)D.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:T.delta})}else if(q1(T)){let te=y[T.output_index];if(te!=null)D.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:T.delta})}else if(F1(T)){let te=y[T.output_index];if(te==null?void 0:te.applyPatch)D.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:zn(T.delta)}),te.applyPatch.hasDiff=!0}else if(B1(T)){let te=y[T.output_index];if((te==null?void 0:te.applyPatch)&&!te.applyPatch.endEmitted){if(!te.applyPatch.hasDiff)D.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:zn(T.diff)}),te.applyPatch.hasDiff=!0;D.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:'"}}'}),D.enqueue({type:"tool-input-end",id:te.toolCallId}),te.applyPatch.endEmitted=!0}}else if($1(T))D.enqueue({type:"tool-result",toolCallId:T.item_id,toolName:i.toCustomToolName("image_generation"),result:{result:T.partial_image_b64},preliminary:!0});else if(L1(T)){let te=y[T.output_index];if(te!=null)D.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:zn(T.delta)})}else if(U1(T)){let te=y[T.output_index];if(te!=null)D.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:'"}'}),D.enqueue({type:"tool-input-end",id:te.toolCallId}),D.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(D1(T))S=T.response.id,D.enqueue({type:"response-metadata",id:T.response.id,timestamp:new Date(T.response.created_at*1000),modelId:T.response.model});else if(A1(T)){if(D.enqueue({type:"text-delta",id:T.item_id,delta:T.delta}),((H=(O=e.providerOptions)==null?void 0:O[s])==null?void 0:H.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")D.enqueue({type:"reasoning-end",id:`${T.item_id}:${ve}`,providerMetadata:{[s]:{itemId:T.item_id}}}),te.summaryParts[ve]="concluded";D.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")D.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)D.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(N1(T)){if(h={unified:cu({finishReason:(ge=T.response.incomplete_details)==null?void 0:ge.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(P_(T)){let te=(Ae=T.response.incomplete_details)==null?void 0:Ae.reason;if(h={unified:te?cu({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,D.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(G1(T)){if(x.push(T.annotation),T.annotation.type==="url_citation")D.enqueue({type:"source",sourceType:"url",id:(Dr=(At=(nt=p.config).generateId)==null?void 0:At.call(nt))!=null?Dr:Le(),url:T.annotation.url,title:T.annotation.title});else if(T.annotation.type==="file_citation")D.enqueue({type:"source",sourceType:"document",id:(zr=(br=(he=p.config).generateId)==null?void 0:br.call(he))!=null?zr:Le(),mediaType:"text/plain",title:T.annotation.filename,filename:T.annotation.filename,providerMetadata:{[s]:{type:T.annotation.type,fileId:T.annotation.file_id,index:T.annotation.index}}});else if(T.annotation.type==="container_file_citation")D.enqueue({type:"source",sourceType:"document",id:(_r=(wn=(tn=p.config).generateId)==null?void 0:wn.call(tn))!=null?_r:Le(),mediaType:"text/plain",title:T.annotation.filename,filename:T.annotation.filename,providerMetadata:{[s]:{type:T.annotation.type,fileId:T.annotation.file_id,containerId:T.annotation.container_id}}});else if(T.annotation.type==="file_path")D.enqueue({type:"source",sourceType:"document",id:(ut=(rn=(st=p.config).generateId)==null?void 0:rn.call(st))!=null?ut:Le(),mediaType:"application/octet-stream",title:T.annotation.file_id,filename:T.annotation.file_id,providerMetadata:{[s]:{type:T.annotation.type,fileId:T.annotation.file_id,index:T.annotation.index}}})}else if(j_(T))F=!0,h={unified:"error",raw:"error"},D.enqueue({type:"error",error:T})},flush(z){let D={[s]:{responseId:S,...w.length>0?{logprobs:w}:{},...b!==void 0?{serviceTier:b}:{}}};z.enqueue({type:"finish",finishReason:h,usage:k_(v),providerMetadata:D})}})),request:{body:t},response:{headers:u}}}};function A1(e){return e.type==="response.output_text.delta"}function P1(e){let t=j1(e);return t!=null&&Array.isArray(t.choices)&&typeof t.type!=="string"}function M1({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 j1(e){return typeof e==="object"&&e!=null?e:void 0}function O1(e){return e.type==="response.output_item.done"}function N1(e){return e.type==="response.completed"||e.type==="response.incomplete"}function P_(e){return e.type==="response.failed"}function D1(e){return e.type==="response.created"}function z1(e){return e.type==="response.function_call_arguments.delta"}function q1(e){return e.type==="response.custom_tool_call_input.delta"}function $1(e){return e.type==="response.image_generation_call.partial_image"}function L1(e){return e.type==="response.code_interpreter_call_code.delta"}function U1(e){return e.type==="response.code_interpreter_call_code.done"}function F1(e){return e.type==="response.apply_patch_call_operation_diff.delta"}function B1(e){return e.type==="response.apply_patch_call_operation_diff.done"}function M_(e){return e.type==="response.output_item.added"}function G1(e){return e.type==="response.output_text.annotation.added"}function j_(e){return e.type==="error"}function J1(e){return!(e.type==="response.created"||e.type==="response.failed"||e.type==="error"||e.type==="unknown_chunk")}function O_(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 zn(e){return JSON.stringify(e).slice(1,-1)}var W1=j(()=>M(r.object({instructions:r.string().nullish(),speed:r.number().min(0.25).max(4).default(1).nullish()}))),H1=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 qe({provider:"openai",providerOptions:s,schema:W1}),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:ag(),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}}}},V1=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()}))),Z1=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()}))),N_={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"},K1=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 qe({provider:"openai",providerOptions:n,schema:Z1}),a=new FormData,s=e instanceof Uint8Array?new Blob([e]):new Blob([wt(e)]);a.append("model",this.modelId);let l=Ym(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(V1),abortSignal:e.abortSignal,fetch:this.config.fetch}),h=p.language!=null&&p.language in N_?N_[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}}}},Y1="3.0.82";function vo(e={}){var t,n;let o=(t=pn(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 ${so({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${Y1}`),s=(h)=>new mD(h,{provider:`${i}.chat`,url:({path:v})=>`${o}${v}`,headers:a,fetch:e.fetch}),l=(h)=>new vD(h,{provider:`${i}.completion`,url:({path:v})=>`${o}${v}`,headers:a,fetch:e.fetch}),c=(h)=>new wD(h,{provider:`${i}.embedding`,url:({path:v})=>`${o}${v}`,headers:a,fetch:e.fetch}),u=(h)=>new RD(h,{provider:`${i}.image`,url:({path:v})=>`${o}${v}`,headers:a,fetch:e.fetch}),d=(h)=>new K1(h,{provider:`${i}.transcription`,url:({path:v})=>`${o}${v}`,headers:a,fetch:e.fetch}),m=(h)=>new H1(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 E1(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=h1,g}var x9=vo();var Q1="3.0.90",X1=j(()=>M(r.object({error:r.object({code:r.number().nullable(),message:r.string(),status:r.string()})}))),or=Qe({errorSchema:X1,errorToMessage:(e)=>e.error.message}),e2=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()})})]),t2=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(e2).min(1).nullable()).optional()}))),r2=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 qe({provider:"google",providerOptions:o,schema:t2});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(o2),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(n2),abortSignal:n,fetch:this.config.fetch});return{warnings:[],embeddings:c.embeddings.map((d)=>d.values),usage:void 0,response:{headers:l,body:u}}}},n2=j(()=>M(r.object({embeddings:r.array(r.object({values:r.array(r.number())}))}))),o2=j(()=>M(r.object({embedding:r.object({values:r.array(r.number())})})));function J_(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(i2(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 i2(e){return e!=null&&typeof e==="object"&&e.type==="object"&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}var a2="skip_thought_signature_validator";function W_(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 s2=/^data:([^;,]+);base64,(.+)$/s;function l2(e){let t=s2.exec(e);if(t==null)return;return{mediaType:t[1],data:t[2]}}function c2(e){let t=l2(e);if(t==null)return;return{inlineData:{mimeType:t.mediaType,data:t.data}}}function u2(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=c2(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(`
|
|
81
|
+
${t}:`]}}function w_({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 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 hD=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()}))),yD=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()}),gu]))),T_=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()}))),vD=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 $e({provider:"openai",providerOptions:p,schema:T_}),...await $e({provider:this.providerOptionsName,providerOptions:p,schema:T_})};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}=fD({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(hD),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:S_(a.usage),finishReason:{unified:x_(l.finish_reason),raw:(t=l.finish_reason)!=null?t:void 0},request:{body:n},response:{...w_(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(yD),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=await fu({stream:s,getError:(f)=>("error"in f)?f.error:void 0,isOutputChunk:bD,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",...w_(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:x_(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:S_(d)})}})),request:{body:o},response:{headers:a}}}};function bD(e){return!("error"in e)&&e.choices.some((t)=>t.text.length>0)}var _D=j(()=>M(r.object({dimensions:r.number().optional(),user:r.string().optional()}))),SD=j(()=>M(r.object({data:r.array(r.object({embedding:r.array(r.number())})),usage:r.object({prompt_tokens:r.number()}).nullish()}))),wD=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 $e({provider:"openai",providerOptions:o,schema:_D}))!=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(SD),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}}}},I_=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()}))),xD={"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},TD=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1","gpt-image-2"];function ID(e){return TD.some((t)=>e.startsWith(t))}var hu=r.object({quality:r.enum(["standard","hd","low","medium","high","auto"]).optional(),background:r.enum(["transparent","opaque","auto"]).optional(),outputFormat:r.enum(["png","jpeg","webp"]).optional(),outputCompression:r.number().int().min(0).max(100).optional(),user:r.string().optional()}),j3=j(()=>M(hu)),CD=j(()=>M(hu.extend({style:r.enum(["vivid","natural"]).optional(),moderation:r.enum(["auto","low"]).optional()}))),kD=j(()=>M(hu.extend({inputFidelity:r.enum(["high","low"]).optional()}))),RD=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get maxImagesPerCall(){var e;return(e=xD[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 $e({provider:"openai",providerOptions:l,schema:kD}))!=null?f:{},{value:R,responseHeaders:z}=await ja({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:_e(this.config.headers(),c),formData:Fm({model:this.modelId,prompt:e,image:await Promise.all(t.map((D)=>D.type==="file"?new Blob([D.data instanceof Uint8Array?new Blob([D.data],{type:D.mediaType}):new Blob([wt(D.data)],{type:D.mediaType})],{type:D.mediaType}):Sl(D.url))),mask:n!=null?await ED(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(I_),abortSignal:u,fetch:this.config.fetch});return{images:R.data.map((D)=>D.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:z},providerMetadata:{openai:{images:R.data.map((D,N)=>{var re,Y,V,L,pe,X;return{...D.revised_prompt?{revisedPrompt:D.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,...C_((X=R.usage)==null?void 0:X.input_tokens_details,N,R.data.length)}})}}}}let I=(w=await $e({provider:"openai",providerOptions:l,schema:CD}))!=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,...!ID(this.modelId)?{response_format:"b64_json"}:{}},failedResponseHandler:gr,successfulResponseHandler:xe(I_),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 z,D,N,re,Y,V;return{...F.revised_prompt?{revisedPrompt:F.revised_prompt}:{},created:(z=b.created)!=null?z:void 0,size:(D=b.size)!=null?D: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,...C_((V=b.usage)==null?void 0:V.input_tokens_details,R,b.data.length)}})}}}}};function C_(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 ED(e){if(!e)return;if(e.type==="url")return Sl(e.url);let t=e.data instanceof Uint8Array?e.data:wt(e.data);return new Blob([t],{type:e.mediaType})}var z_=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()})])}))),$_=j(()=>M(r.object({status:r.enum(["completed","failed"]),output:r.string().optional()}))),D3=j(()=>M(r.object({}))),AD=Te({id:"openai.apply_patch",inputSchema:z_,outputSchema:$_}),PD=AD,MD=j(()=>M(r.object({code:r.string().nullish(),containerId:r.string()}))),jD=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()}))),OD=j(()=>M(r.object({container:r.union([r.string(),r.object({fileIds:r.array(r.string()).optional()})]).optional()}))),ND=Te({id:"openai.code_interpreter",inputSchema:MD,outputSchema:jD}),DD=(e={})=>ND(e),zD=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()}))),$D=j(()=>M(r.string())),qD=Ge({id:"openai.custom",inputSchema:$D}),LD=(e)=>qD(e),q_=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())])}),L_=r.object({type:r.enum(["and","or"]),filters:r.array(r.union([q_,r.lazy(()=>L_)]))}),UD=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([q_,L_]).optional()}))),FD=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()}))),BD=Te({id:"openai.file_search",inputSchema:r.object({}),outputSchema:FD}),GD=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())),JD=j(()=>M(r.object({}))),WD=j(()=>M(r.object({result:r.string()}))),HD=Te({id:"openai.image_generation",inputSchema:JD,outputSchema:WD}),VD=(e={})=>HD(e),U_=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()})}))),F_=j(()=>M(r.object({output:r.string()}))),ZD=Te({id:"openai.local_shell",inputSchema:U_,outputSchema:F_}),B_=j(()=>M(r.object({action:r.object({commands:r.array(r.string()),timeoutMs:r.number().optional(),maxOutputLength:r.number().optional()})}))),uu=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()})])}))}))),KD=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(),YD=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:KD}),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()}))),QD=Te({id:"openai.shell",inputSchema:B_,outputSchema:uu}),XD=j(()=>M(r.object({execution:r.enum(["server","client"]).optional(),description:r.string().optional(),parameters:r.record(r.string(),r.unknown()).optional()}))),du=j(()=>M(r.object({arguments:r.unknown().optional(),call_id:r.string().nullish()}))),pu=j(()=>M(r.object({tools:r.array(r.record(r.string(),r.unknown()))}))),e1=Te({id:"openai.tool_search",inputSchema:du,outputSchema:pu}),t1=(e={})=>e1(e),r1=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()}))),n1=j(()=>M(r.object({}))),o1=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()}))),i1=Te({id:"openai.web_search",inputSchema:n1,outputSchema:o1}),a1=(e={})=>i1(e),s1=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()}))),l1=j(()=>M(r.object({}))),c1=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()}))),u1=Te({id:"openai.web_search_preview",inputSchema:l1,outputSchema:c1}),mu=r.lazy(()=>r.union([r.string(),r.number(),r.boolean(),r.null(),r.array(mu),r.record(r.string(),mu)])),d1=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."))),p1=j(()=>M(r.object({}))),m1=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(),mu]).optional()}))),g1=Te({id:"openai.mcp",inputSchema:p1,outputSchema:m1}),f1=(e)=>g1(e),h1={applyPatch:PD,customTool:LD,codeInterpreter:DD,fileSearch:BD,imageGeneration:VD,localShell:ZD,shell:QD,webSearchPreview:u1,webSearch:a1,mcp:f1,toolSearch:t1};function k_(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 y1(e){return JSON.stringify(e===void 0?{}:e)}function R_(e,t){if(!t)return!1;return t.some((n)=>e.startsWith(n))}async function v1({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,z,D,N,re,Y,V,L,pe;let X=[],k=[],Q=new Set;for(let{role:J,content:W}of e)switch(J){case"system":{switch(n){case"system":{X.push({role:"system",content:W});break}case"developer":{X.push({role:"developer",content:W});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":{X.push({role:"user",content:W.map((K,q)=>{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"&&R_(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 He({functionality:`file part media type ${A}`});return{type:"input_file",...typeof K.data==="string"&&R_(K.data,i)?{file_id:K.data}:{filename:(Z=K.filename)!=null?Z:A==="application/pdf"?`part-${q}.pdf`:`part-${q}`,file_data:`data:${A};base64,${bt(K.data)}`}}}}})});break}case"assistant":{let K={};for(let q of W)switch(q.type){case"text":{let B=(f=q.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){X.push({type:"item_reference",id:G});break}X.push({role:"assistant",content:[{type:"output_text",text:q.text}],id:G,...Z!=null&&{phase:Z}});break}case"tool-call":{let B=(S=(h=(g=q.providerOptions)==null?void 0:g[o])==null?void 0:h.itemId)!=null?S:(w=(v=q.providerMetadata)==null?void 0:v[o])==null?void 0:w.itemId,G=(I=(x=(y=q.providerOptions)==null?void 0:y[o])==null?void 0:x.namespace)!=null?I:(C=(_=q.providerMetadata)==null?void 0:_[o])==null?void 0:C.namespace;if(l&&B!=null)break;let Z=t.toProviderToolName(q.toolName);if(Z==="tool_search"){if(s&&B!=null){X.push({type:"item_reference",id:B});break}let O=typeof q.input==="string"?await xl({text:q.input,schema:du}):await Ee({value:q.input,schema:du}),H=O.call_id!=null?"client":"server";X.push({type:"tool_search_call",id:B!=null?B:q.toolCallId,execution:H,call_id:(b=O.call_id)!=null?b:null,status:"completed",arguments:O.arguments});break}if(q.providerExecuted){if(s&&B!=null)X.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){X.push({type:"item_reference",id:B});break}if(u&&Z==="local_shell"){let O=await Ee({value:q.input,schema:U_});X.push({type:"local_shell_call",call_id:q.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:q.input,schema:B_});X.push({type:"shell_call",call_id:q.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:q.input,schema:z_});X.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)){X.push({type:"custom_tool_call",call_id:q.toolCallId,name:Z,input:typeof q.input==="string"?q.input:JSON.stringify(q.input),id:B});break}X.push({type:"function_call",call_id:q.toolCallId,name:Z,arguments:y1(q.input),...G!=null&&{namespace:G}});break}case"tool-result":{if(q.output.type==="execution-denied"||q.output.type==="json"&&typeof q.output.value==="object"&&q.output.value!=null&&"type"in q.output.value&&q.output.value.type==="execution-denied")break;if(l)break;let B=t.toProviderToolName(q.toolName);if(B==="tool_search"){let G=(z=(R=(F=q.providerOptions)==null?void 0:F[o])==null?void 0:R.itemId)!=null?z:q.toolCallId;if(s)X.push({type:"item_reference",id:G});else if(q.output.type==="json"){let Z=await Ee({value:q.output.value,schema:pu});X.push({type:"tool_search_output",id:G,execution:"server",call_id:null,status:"completed",tools:Z.tools})}break}if(d&&B==="shell"){if(q.output.type==="json"){let G=await Ee({value:q.output.value,schema:uu});X.push({type:"shell_call_output",call_id:q.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=(D=q.providerOptions)==null?void 0:D[o])==null?void 0:N.itemId)!=null?re:q.toolCallId;X.push({type:"item_reference",id:G})}else k.push({type:"other",message:`Results for OpenAI tool ${q.toolName} are not sent to the API when store is false`});break}case"reasoning":{let B=await $e({provider:o,providerOptions:q.providerOptions,schema:b1}),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)X.push({type:"item_reference",id:G}),K[G]={type:"reasoning",id:G,summary:[]}}else{let A=[];if(q.text.length>0)A.push({type:"summary_text",text:q.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(q)}.`});if(Z===void 0)K[G]={type:"reasoning",id:G,encrypted_content:B==null?void 0:B.reasoningEncryptedContent,summary:A},X.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(q.text.length>0)A.push({type:"summary_text",text:q.text});X.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(q)}.`})}break}}break}case"tool":{for(let K of W){if(K.type==="tool-approval-response"){let Z=K;if(Q.has(Z.approvalId))continue;if(Q.add(Z.approvalId),s)X.push({type:"item_reference",id:Z.approvalId});X.push({type:"mcp_approval_response",approval_request_id:Z.approvalId,approve:Z.approved});continue}let q=K.output;if(q.type==="execution-denied"){if((V=(Y=q.providerOptions)==null?void 0:Y.openai)==null?void 0:V.approvalId)continue}let B=t.toProviderToolName(K.toolName);if(B==="tool_search"&&q.type==="json"){let Z=await Ee({value:q.value,schema:pu});X.push({type:"tool_search_output",execution:"client",call_id:K.toolCallId,status:"completed",tools:Z.tools});continue}if(u&&B==="local_shell"&&q.type==="json"){let Z=await Ee({value:q.value,schema:F_});X.push({type:"local_shell_call_output",call_id:K.toolCallId,output:Z.output});continue}if(d&&B==="shell"&&q.type==="json"){let Z=await Ee({value:q.value,schema:uu});X.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"&&q.type==="json"){let Z=await Ee({value:q.value,schema:$_});X.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(q.type){case"text":case"error-text":Z=q.value;break;case"execution-denied":Z=(L=q.reason)!=null?L:"Tool call execution denied.";break;case"json":case"error-json":Z=JSON.stringify(q.value);break;case"content":Z=q.value.map((A)=>{var O,H,P,U,ge;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:(H=(O=A.providerOptions)==null?void 0:O[o])==null?void 0:H.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:(ge=A.filename)!=null?ge:"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(fi);break;default:Z=""}X.push({type:"custom_tool_call_output",call_id:K.toolCallId,output:Z});continue}let G;switch(q.type){case"text":case"error-text":G=q.value;break;case"execution-denied":G=(pe=q.reason)!=null?pe:"Tool call execution denied.";break;case"json":case"error-json":G=JSON.stringify(q.value);break;case"content":G=q.value.map((Z)=>{var A,O,H,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=(H=Z.providerOptions)==null?void 0:H[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(fi);break}X.push({type:"function_call_output",call_id:K.toolCallId,output:G})}break}default:throw Error(`Unsupported role: ${J}`)}if(!s&&X.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."}),X=X.filter((J)=>!("type"in J)||J.type!=="reasoning"||J.encrypted_content!=null);return{input:X,warnings:k}}var b1=r.object({itemId:r.string().nullish(),reasoningEncryptedContent:r.string().nullish()});function cu({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 Di=r.lazy(()=>r.union([r.string(),r.number(),r.boolean(),r.null(),r.array(Di),r.record(r.string(),Di.optional())])),_1=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()})}),S1=r.object({type:r.literal("error"),sequence_number:r.number(),code:r.string().nullish(),message:r.string(),param:r.string().nullish()}),w1=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(),Di.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(),Di.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()}),_1,S1,r.object({type:r.string()}).loose().transform((e)=>({type:"unknown_chunk",message:e.type}))]))),x1=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(),Di.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()}))),G_=20,T1=["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"],p9=["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",...T1],E_=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(G_)]).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 I1({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=C1({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 He({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:UD});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:YD});u.push({type:"shell",...g.environment&&{environment:k1(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:s1});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:r1});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:OD});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:GD});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:d1}),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:zD});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:XD});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 He({functionality:`tool choice type: ${p}`})}}function C1({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 k1(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:R1(n.skills)}}return{type:"local",skills:e.skills}}function R1(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 A_(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 E1=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=D_(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 $e({provider:F,providerOptions:u,schema:E_});if(R==null&&F!=="openai")R=await $e({provider:"openai",providerOptions:u,schema:E_});let z=(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 D=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 I1({tools:d,toolChoice:m,allowedTools:(g=R==null?void 0:R.allowedTools)!=null?g:void 0,toolNameMapping:D,customProviderToolNames:N}),{input:L,warnings:pe}=await v1({prompt:c,toolNameMapping:D,systemMessageMode:(h=R==null?void 0:R.systemMessageMode)!=null?h:z?"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 X=(S=R==null?void 0:R.strictJsonSchema)!=null?S:!0,k=R==null?void 0:R.include;function Q(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 W=typeof(R==null?void 0:R.logprobs)==="number"?R==null?void 0:R.logprobs:(R==null?void 0:R.logprobs)===!0?G_:void 0;if(W)Q("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)Q("web_search_call.action.sources");if(J("openai.code_interpreter"))Q("code_interpreter_call.outputs");let q=R==null?void 0:R.store;if(q===!1&&z)Q("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:X,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:q,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:W,truncation:R==null?void 0:R.truncation,...z&&((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(z){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:q,toolNameMapping:D,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,z;let{args:D,warnings:N,webSearchToolName:re,toolNameMapping:Y,providerOptionsName:V,isShellProviderExecuted:L}=await this.getArgs(e),pe=this.config.url({path:"/responses",modelId:this.modelId}),X=A_(e.prompt),{responseHeaders:k,value:Q,rawValue:J}=await Ie({url:pe,headers:_e(this.config.headers(),e.headers),body:D,failedResponseHandler:gr,successfulResponseHandler:xe(x1),abortSignal:e.abortSignal,fetch:this.config.fetch});if(Q.error)throw new De({message:Q.error.message,url:pe,requestBodyValues:D,statusCode:400,responseHeaders:k,responseBody:J,isRetryable:!1});let W=[],K=[],q=!1,B=[];for(let A of Q.output)switch(A.type){case"reasoning":{if(A.summary.length===0)A.summary.push({type:"summary_text",text:""});for(let O of A.summary)W.push({type:"reasoning",text:O.text,providerMetadata:{[V]:{itemId:A.id,reasoningEncryptedContent:(t=A.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{W.push({type:"tool-call",toolCallId:A.id,toolName:Y.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),W.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,H=A.execution==="server";if(H)B.push(O);W.push({type:"tool-call",toolCallId:O,toolName:Y.toCustomToolName("tool_search"),input:JSON.stringify({arguments:A.arguments,call_id:A.call_id}),...H?{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;W.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":{W.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":{W.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":{W.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 H={itemId:A.id,...A.phase!=null&&{phase:A.phase},...O.annotations.length>0&&{annotations:O.annotations}};W.push({type:"text",text:O.text,providerMetadata:{[V]:H}});for(let P of O.annotations)if(P.type==="url_citation")W.push({type:"source",sourceType:"url",id:(u=(c=(l=this.config).generateId)==null?void 0:c.call(l))!=null?u:Le(),url:P.url,title:P.title});else if(P.type==="file_citation")W.push({type:"source",sourceType:"document",id:(p=(m=(d=this.config).generateId)==null?void 0:m.call(d))!=null?p:Le(),mediaType:"text/plain",title:P.filename,filename:P.filename,providerMetadata:{[V]:{type:P.type,fileId:P.file_id,index:P.index}}});else if(P.type==="container_file_citation")W.push({type:"source",sourceType:"document",id:(h=(g=(f=this.config).generateId)==null?void 0:g.call(f))!=null?h:Le(),mediaType:"text/plain",title:P.filename,filename:P.filename,providerMetadata:{[V]:{type:P.type,fileId:P.file_id,containerId:P.container_id}}});else if(P.type==="file_path")W.push({type:"source",sourceType:"document",id:(S=(w=(v=this.config).generateId)==null?void 0:w.call(v))!=null?S:Le(),mediaType:"application/octet-stream",title:P.file_id,filename:P.file_id,providerMetadata:{[V]:{type:P.type,fileId:P.file_id,index:P.index}}})}break}case"function_call":{q=!0,W.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":{q=!0;let O=Y.toCustomToolName(A.name);W.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":{W.push({type:"tool-call",toolCallId:A.id,toolName:Y.toCustomToolName(re!=null?re:"web_search"),input:JSON.stringify({}),providerExecuted:!0}),W.push({type:"tool-result",toolCallId:A.id,toolName:Y.toCustomToolName(re!=null?re:"web_search"),result:O_(A.action)});break}case"mcp_call":{let O=A.approval_request_id!=null?(y=X[A.approval_request_id])!=null?y:A.id:A.id,H=`mcp.${A.name}`;W.push({type:"tool-call",toolCallId:O,toolName:H,input:A.arguments,providerExecuted:!0,dynamic:!0}),W.push({type:"tool-result",toolCallId:O,toolName:H,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,H=(I=(C=(_=this.config).generateId)==null?void 0:C.call(_))!=null?I:Le(),P=`mcp.${A.name}`;W.push({type:"tool-call",toolCallId:H,toolName:P,input:A.arguments,providerExecuted:!0,dynamic:!0}),W.push({type:"tool-approval-request",approvalId:O,toolCallId:H});break}case"computer_call":{W.push({type:"tool-call",toolCallId:A.id,toolName:Y.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),W.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":{W.push({type:"tool-call",toolCallId:A.id,toolName:Y.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),W.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":{W.push({type:"tool-call",toolCallId:A.id,toolName:Y.toCustomToolName("code_interpreter"),input:JSON.stringify({code:A.code,containerId:A.container_id}),providerExecuted:!0}),W.push({type:"tool-result",toolCallId:A.id,toolName:Y.toCustomToolName("code_interpreter"),result:{outputs:A.outputs}});break}case"apply_patch_call":{W.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:Q.id,...K.length>0?{logprobs:K}:{},...typeof Q.service_tier==="string"?{serviceTier:Q.service_tier}:{}}},Z=Q.usage;return{content:W,finishReason:{unified:cu({finishReason:(F=Q.incomplete_details)==null?void 0:F.reason,hasFunctionCall:q}),raw:(z=(R=Q.incomplete_details)==null?void 0:R.reason)!=null?z:void 0},usage:k_(Z),request:{body:D},response:{id:Q.id,timestamp:new Date(Q.created_at*1000),modelId:Q.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(w1),abortSignal:e.abortSignal,fetch:this.config.fetch}),m=await fu({stream:d,getError:(z)=>j_(z)||P_(z)&&z.response.error!=null?z:void 0,isOutputChunk:J1,url:c,requestBodyValues:t,responseHeaders:u}),p=this,f=A_(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(z){z.enqueue({type:"stream-start",warnings:n})},transform(z,D){var N,re,Y,V,L,pe,X,k,Q,J,W,K,q,B,G,Z,A,O,H,P,U,ge,ee,ue,Ae,Ke,nt,At,Dr,he,br,zr,tn,wn,_r,st,rn,ut;if(e.includeRawChunks)D.enqueue({type:"raw",rawValue:z.rawValue});if(!z.success){let te=P1(z.rawValue)?M1({value:z.rawValue,cause:z.error,url:c,requestBodyValues:t,responseHeaders:u}):z.error;h={unified:"error",raw:void 0},D.enqueue({type:"error",error:te});return}let T=z.value;if(M_(T)){if(T.item.type==="function_call")y[T.output_index]={toolName:T.item.name,toolCallId:T.item.call_id},D.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},D.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},D.enqueue({type:"tool-input-start",id:T.item.id,toolName:i.toCustomToolName(o!=null?o:"web_search"),providerExecuted:!0}),D.enqueue({type:"tool-input-end",id:T.item.id}),D.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},D.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}},D.enqueue({type:"tool-input-start",id:T.item.id,toolName:i.toCustomToolName("code_interpreter"),providerExecuted:!0}),D.enqueue({type:"tool-input-delta",id:T.item.id,delta:`{"containerId":"${T.item.container_id}","code":"`});else if(T.item.type==="file_search_call")D.enqueue({type:"tool-call",toolCallId:T.item.id,toolName:i.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(T.item.type==="image_generation_call")D.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"),ke=T.item.execution==="server";if(y[T.output_index]={toolName:ve,toolCallId:te,toolSearchExecution:(N=T.item.execution)!=null?N:"server"},ke)D.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"}},D.enqueue({type:"tool-input-start",id:te,toolName:i.toCustomToolName("apply_patch")}),ve.type==="delete_file"){let ke=JSON.stringify({callId:te,operation:ve});D.enqueue({type:"tool-input-delta",id:te,delta:ke}),D.enqueue({type:"tool-input-end",id:te})}else D.enqueue({type:"tool-input-delta",id:te,delta:`{"callId":"${zn(te)}","operation":{"type":"${zn(ve.type)}","path":"${zn(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,D.enqueue({type:"text-start",id:T.item.id,providerMetadata:{[s]:{itemId:T.item.id,...T.item.phase!=null&&{phase:T.item.phase}}}});else if(M_(T)&&T.item.type==="reasoning")I[T.item.id]={encryptedContent:T.item.encrypted_content,summaryParts:{0:"active"}},D.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(O1(T)){if(T.item.type==="message"){let te=(V=T.item.phase)!=null?V:_;_=void 0,D.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,D.enqueue({type:"tool-input-end",id:T.item.call_id,...T.item.namespace!=null&&{providerMetadata:{[s]:{namespace:T.item.namespace}}}}),D.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);D.enqueue({type:"tool-input-end",id:T.item.call_id}),D.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,D.enqueue({type:"tool-result",toolCallId:T.item.id,toolName:i.toCustomToolName(o!=null?o:"web_search"),result:O_(T.item.action)});else if(T.item.type==="computer_call")y[T.output_index]=void 0,D.enqueue({type:"tool-input-end",id:T.item.id}),D.enqueue({type:"tool-call",toolCallId:T.item.id,toolName:i.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),D.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,D.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,D.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")D.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 ke=ve?te.toolCallId:(X=T.item.call_id)!=null?X:T.item.id;if(ve)E.push(ke);else D.enqueue({type:"tool-input-start",id:ke,toolName:te.toolName});D.enqueue({type:"tool-input-end",id:ke}),D.enqueue({type:"tool-call",toolCallId:ke,toolName:te.toolName,input:JSON.stringify({arguments:T.item.arguments,call_id:ve?null:ke}),...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=(Q=(k=T.item.call_id)!=null?k:E.shift())!=null?Q:T.item.id;D.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=(W=g.get(te))!=null?W:f[te])!=null?K:T.item.id:T.item.id,ke=`mcp.${T.item.name}`;D.enqueue({type:"tool-call",toolCallId:ve,toolName:ke,input:T.item.arguments,providerExecuted:!0,dynamic:!0}),D.enqueue({type:"tool-result",toolCallId:ve,toolName:ke,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)D.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:zn(T.item.operation.diff)});D.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:'"}}'}),D.enqueue({type:"tool-input-end",id:te.toolCallId}),te.applyPatch.endEmitted=!0}if(te&&T.item.status==="completed")D.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=(q=p.config).generateId)==null?void 0:B.call(q))!=null?G:Le(),ve=(Z=T.item.approval_request_id)!=null?Z:T.item.id;g.set(ve,te);let ke=`mcp.${T.item.name}`;D.enqueue({type:"tool-call",toolCallId:te,toolName:ke,input:T.item.arguments,providerExecuted:!0,dynamic:!0}),D.enqueue({type:"tool-approval-request",approvalId:ve,toolCallId:te})}else if(T.item.type==="local_shell_call")y[T.output_index]=void 0,D.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,D.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")D.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(([ke,ht])=>ht==="active"||ht==="can-conclude").map(([ke])=>ke);for(let ke of ve)D.enqueue({type:"reasoning-end",id:`${T.item.id}:${ke}`,providerMetadata:{[s]:{itemId:T.item.id,reasoningEncryptedContent:(A=T.item.encrypted_content)!=null?A:null}}});delete I[T.item.id]}}else if(z1(T)){let te=y[T.output_index];if(te!=null)D.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:T.delta})}else if($1(T)){let te=y[T.output_index];if(te!=null)D.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:T.delta})}else if(F1(T)){let te=y[T.output_index];if(te==null?void 0:te.applyPatch)D.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:zn(T.delta)}),te.applyPatch.hasDiff=!0}else if(B1(T)){let te=y[T.output_index];if((te==null?void 0:te.applyPatch)&&!te.applyPatch.endEmitted){if(!te.applyPatch.hasDiff)D.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:zn(T.diff)}),te.applyPatch.hasDiff=!0;D.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:'"}}'}),D.enqueue({type:"tool-input-end",id:te.toolCallId}),te.applyPatch.endEmitted=!0}}else if(q1(T))D.enqueue({type:"tool-result",toolCallId:T.item_id,toolName:i.toCustomToolName("image_generation"),result:{result:T.partial_image_b64},preliminary:!0});else if(L1(T)){let te=y[T.output_index];if(te!=null)D.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:zn(T.delta)})}else if(U1(T)){let te=y[T.output_index];if(te!=null)D.enqueue({type:"tool-input-delta",id:te.toolCallId,delta:'"}'}),D.enqueue({type:"tool-input-end",id:te.toolCallId}),D.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(D1(T))S=T.response.id,D.enqueue({type:"response-metadata",id:T.response.id,timestamp:new Date(T.response.created_at*1000),modelId:T.response.model});else if(A1(T)){if(D.enqueue({type:"text-delta",id:T.item_id,delta:T.delta}),((H=(O=e.providerOptions)==null?void 0:O[s])==null?void 0:H.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")D.enqueue({type:"reasoning-end",id:`${T.item_id}:${ve}`,providerMetadata:{[s]:{itemId:T.item_id}}}),te.summaryParts[ve]="concluded";D.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")D.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)D.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(N1(T)){if(h={unified:cu({finishReason:(ge=T.response.incomplete_details)==null?void 0:ge.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(P_(T)){let te=(Ae=T.response.incomplete_details)==null?void 0:Ae.reason;if(h={unified:te?cu({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,D.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(G1(T)){if(x.push(T.annotation),T.annotation.type==="url_citation")D.enqueue({type:"source",sourceType:"url",id:(Dr=(At=(nt=p.config).generateId)==null?void 0:At.call(nt))!=null?Dr:Le(),url:T.annotation.url,title:T.annotation.title});else if(T.annotation.type==="file_citation")D.enqueue({type:"source",sourceType:"document",id:(zr=(br=(he=p.config).generateId)==null?void 0:br.call(he))!=null?zr:Le(),mediaType:"text/plain",title:T.annotation.filename,filename:T.annotation.filename,providerMetadata:{[s]:{type:T.annotation.type,fileId:T.annotation.file_id,index:T.annotation.index}}});else if(T.annotation.type==="container_file_citation")D.enqueue({type:"source",sourceType:"document",id:(_r=(wn=(tn=p.config).generateId)==null?void 0:wn.call(tn))!=null?_r:Le(),mediaType:"text/plain",title:T.annotation.filename,filename:T.annotation.filename,providerMetadata:{[s]:{type:T.annotation.type,fileId:T.annotation.file_id,containerId:T.annotation.container_id}}});else if(T.annotation.type==="file_path")D.enqueue({type:"source",sourceType:"document",id:(ut=(rn=(st=p.config).generateId)==null?void 0:rn.call(st))!=null?ut:Le(),mediaType:"application/octet-stream",title:T.annotation.file_id,filename:T.annotation.file_id,providerMetadata:{[s]:{type:T.annotation.type,fileId:T.annotation.file_id,index:T.annotation.index}}})}else if(j_(T))F=!0,h={unified:"error",raw:"error"},D.enqueue({type:"error",error:T})},flush(z){let D={[s]:{responseId:S,...w.length>0?{logprobs:w}:{},...b!==void 0?{serviceTier:b}:{}}};z.enqueue({type:"finish",finishReason:h,usage:k_(v),providerMetadata:D})}})),request:{body:t},response:{headers:u}}}};function A1(e){return e.type==="response.output_text.delta"}function P1(e){let t=j1(e);return t!=null&&Array.isArray(t.choices)&&typeof t.type!=="string"}function M1({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 j1(e){return typeof e==="object"&&e!=null?e:void 0}function O1(e){return e.type==="response.output_item.done"}function N1(e){return e.type==="response.completed"||e.type==="response.incomplete"}function P_(e){return e.type==="response.failed"}function D1(e){return e.type==="response.created"}function z1(e){return e.type==="response.function_call_arguments.delta"}function $1(e){return e.type==="response.custom_tool_call_input.delta"}function q1(e){return e.type==="response.image_generation_call.partial_image"}function L1(e){return e.type==="response.code_interpreter_call_code.delta"}function U1(e){return e.type==="response.code_interpreter_call_code.done"}function F1(e){return e.type==="response.apply_patch_call_operation_diff.delta"}function B1(e){return e.type==="response.apply_patch_call_operation_diff.done"}function M_(e){return e.type==="response.output_item.added"}function G1(e){return e.type==="response.output_text.annotation.added"}function j_(e){return e.type==="error"}function J1(e){return!(e.type==="response.created"||e.type==="response.failed"||e.type==="error"||e.type==="unknown_chunk")}function O_(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 zn(e){return JSON.stringify(e).slice(1,-1)}var W1=j(()=>M(r.object({instructions:r.string().nullish(),speed:r.number().min(0.25).max(4).default(1).nullish()}))),H1=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 $e({provider:"openai",providerOptions:s,schema:W1}),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:ag(),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}}}},V1=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()}))),Z1=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()}))),N_={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"},K1=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 $e({provider:"openai",providerOptions:n,schema:Z1}),a=new FormData,s=e instanceof Uint8Array?new Blob([e]):new Blob([wt(e)]);a.append("model",this.modelId);let l=Ym(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(V1),abortSignal:e.abortSignal,fetch:this.config.fetch}),h=p.language!=null&&p.language in N_?N_[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}}}},Y1="3.0.82";function vo(e={}){var t,n;let o=(t=pn(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 ${so({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${Y1}`),s=(h)=>new mD(h,{provider:`${i}.chat`,url:({path:v})=>`${o}${v}`,headers:a,fetch:e.fetch}),l=(h)=>new vD(h,{provider:`${i}.completion`,url:({path:v})=>`${o}${v}`,headers:a,fetch:e.fetch}),c=(h)=>new wD(h,{provider:`${i}.embedding`,url:({path:v})=>`${o}${v}`,headers:a,fetch:e.fetch}),u=(h)=>new RD(h,{provider:`${i}.image`,url:({path:v})=>`${o}${v}`,headers:a,fetch:e.fetch}),d=(h)=>new K1(h,{provider:`${i}.transcription`,url:({path:v})=>`${o}${v}`,headers:a,fetch:e.fetch}),m=(h)=>new H1(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 E1(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=h1,g}var x9=vo();var Q1="3.0.90",X1=j(()=>M(r.object({error:r.object({code:r.number().nullable(),message:r.string(),status:r.string()})}))),or=Qe({errorSchema:X1,errorToMessage:(e)=>e.error.message}),e2=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()})})]),t2=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(e2).min(1).nullable()).optional()}))),r2=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 $e({provider:"google",providerOptions:o,schema:t2});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(o2),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(n2),abortSignal:n,fetch:this.config.fetch});return{warnings:[],embeddings:c.embeddings.map((d)=>d.values),usage:void 0,response:{headers:l,body:u}}}},n2=j(()=>M(r.object({embeddings:r.array(r.object({values:r.array(r.number())}))}))),o2=j(()=>M(r.object({embedding:r.object({values:r.array(r.number())})})));function J_(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(i2(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 i2(e){return e!=null&&typeof e==="object"&&e.type==="object"&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}var a2="skip_thought_signature_validator";function W_(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 s2=/^data:([^;,]+);base64,(.+)$/s;function l2(e){let t=s2.exec(e);if(t==null)return;return{mediaType:t[1],data:t[2]}}function c2(e){let t=l2(e);if(t==null)return;return{inlineData:{mimeType:t.mediaType,data:t.data}}}function u2(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=c2(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
82
|
`):"Tool executed successfully."},...i.length>0?{parts:i}:{}}})}function d2(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 p2(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,a2);for(let{role:S,content:y}of e)switch(S){case"system":{if(!u)throw new He({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 _=W_(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 He({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=W_(_.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)u2(x,_.toolName,E.value,_.toolCallId);else d2(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
83
|
|
|
84
84
|
`);c[0].parts.unshift({text:S+`
|
|
85
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 H_(e){return e.includes("/")?e:`models/${e}`}var V_=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 m2({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 He({functionality:`tool choice type: ${h}`})}}var g2=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=f2(o),a=y2(this.accumulatedArgs,i);if(n.stringValue!=null&&a!==void 0){let c=JSON.stringify(n.stringValue).slice(1,-1);K_(this.accumulatedArgs,i,a+n.stringValue),t+=c;continue}let l=v2(n);if(l==null)continue;K_(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 f2(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 h2=Object.prototype.hasOwnProperty;function sS(e,t){return h2.call(e,t)}function Z_(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})}function y2(e,t){let n=e;for(let o of t){if(n==null||typeof n!=="object")return;let i=n;if(!sS(i,o))return;n=i[o]}return n}function K_(e,t,n){let o=e;for(let i=0;i<t.length-1;i++){let a=t[i],s=t[i+1];if(!sS(o,a)||o[a]==null)Z_(o,a,typeof s==="number"?[]:{});o=o[a]}Z_(o,t[t.length-1],n)}function v2(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 Y_({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 lS=class{constructor(e,t){this.specificationVersion="v3";var n;this.modelId=e,this.config=t,this.generateId=(n=t.generateId)!=null?n:Le}get provider(){return this.config.provider}get supportedUrls(){var e,t,n;return(n=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?n:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:o,topK:i,frequencyPenalty:a,presencePenalty:s,stopSequences:l,responseFormat:c,seed:u,tools:d,toolChoice:m,providerOptions:p},{isStreaming:f=!1}={}){var g,h;let v=[],w=this.config.provider.includes("vertex")?"vertex":"google",S=await qe({provider:w,providerOptions:p,schema:V_});if(S==null&&w!=="google")S=await qe({provider:"google",providerOptions:p,schema:V_});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}=p2(e,{isGemmaModel:C,isGemini3Model:I,providerOptionsName:w,supportsFunctionResponseParts:b,onWarning:(Y)=>v.push(Y)}),{tools:R,toolConfig:z,toolWarnings:D}=m2({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=z||N||(S==null?void 0:S.retrievalConfig)?{...z,...N&&{functionCallingConfig:{...z==null?void 0:z.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,...D],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}/${H_(this.modelId)}:generateContent`,headers:I,body:y,failedResponseHandler:or,successfulResponseHandler:xe(_2),abortSignal:e.abortSignal,fetch:this.config.fetch}),R=E.candidates[0],z=[],D=(n=(t=R.content)==null?void 0:t.parts)!=null?n:[],N=E.usageMetadata,re,Y;for(let L of D)if("executableCode"in L&&((o=L.executableCode)==null?void 0:o.code)){let pe=this.config.generateId();re=pe,z.push({type:"tool-call",toolCallId:pe,toolName:"code_execution",input:JSON.stringify(L.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in L&&L.codeExecutionResult)z.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&&z.length>0){let X=z[z.length-1];X.providerMetadata=pe}}else z.push({type:L.thought===!0?"reasoning":"text",text:L.text,providerMetadata:pe})}else if("functionCall"in L&&L.functionCall.name!=null)z.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,X=!!L.thoughtSignature;z.push({type:"file",data:L.inlineData.data,mediaType:L.inlineData.mimeType,providerMetadata:pe||X?{[_]:{...pe?{thought:!0}:{},...X?{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,z.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();z.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=Q_({groundingMetadata:R.groundingMetadata,generateId:this.config.generateId}))!=null?m:[];for(let L of V)z.push(L);return{content:z,finishReason:{unified:Y_({finishReason:R.finishReason,hasToolCalls:z.some((L)=>L.type==="tool-call"&&!L.providerExecuted)}),raw:(p=R.finishReason)!=null?p:void 0},usage:J_(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}/${H_(this.modelId)}:streamGenerateContent?alt=sse`,headers:a,body:t,failedResponseHandler:or,successfulResponseHandler:Dt(S2),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,z,D,N,re,Y,V,L,pe,X,k,Q,J,W;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,q=K.usageMetadata;if(q!=null)u=q;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=Q_({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 H=f();y=H,b.enqueue({type:"tool-call",toolCallId:H,toolName:"code_execution",input:JSON.stringify(O.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in O&&O.codeExecutionResult){let H=y;if(H)b.enqueue({type:"tool-result",toolCallId:H,toolName:"code_execution",result:{outcome:O.codeExecutionResult.outcome,output:(z=O.codeExecutionResult.output)!=null?z:""}}),y=void 0}else if("text"in O&&O.text!=null){let H=O.thoughtSignature?{[o]:{thoughtSignature:O.thoughtSignature}}:void 0;if(O.text.length===0){if(H!=null&&h!==null)b.enqueue({type:"text-delta",id:h,delta:"",providerMetadata:H})}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:H});b.enqueue({type:"reasoning-delta",id:v,delta:O.text,providerMetadata:H})}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:H});b.enqueue({type:"text-delta",id:h,delta:O.text,providerMetadata:H})}}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 H=O.thought===!0,P=!!O.thoughtSignature,U=H||P?{[o]:{...H?{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 H=(D=O.toolCall.id)!=null?D:f();x=H;let P={[o]:{...O.thoughtSignature?{thoughtSignature:O.thoughtSignature}:{},serverToolCallId:H,serverToolType:O.toolCall.toolType}};b.enqueue({type:"tool-call",toolCallId:H,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 H=(re=x!=null?x:O.toolResponse.id)!=null?re:f(),P={[o]:{...O.thoughtSignature?{thoughtSignature:O.thoughtSignature}:{},serverToolCallId:H,serverToolType:O.toolResponse.toolType}};b.enqueue({type:"tool-result",toolCallId:H,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 H=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,ge=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 g2;if(_.push({toolCallId:ue,toolName:O.functionCall.name,accumulator:Ae,providerMetadata:H}),b.enqueue({type:"tool-input-start",id:ue,toolName:O.functionCall.name,providerMetadata:H}),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:H});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:H});if(O.functionCall.willContinue!==!0&&Ae.every((nt)=>nt.willContinue!==!0))C(b)}}else if(U&&_.length>0)C(b);else if(ge){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:H}),b.enqueue({type:"tool-input-delta",id:ue,delta:Ke,providerMetadata:H}),b.enqueue({type:"tool-input-end",id:ue,providerMetadata:H}),b.enqueue({type:"tool-call",toolCallId:ue,toolName:Ae,input:Ke,providerMetadata:H}),g=!0}else if(ee){let ue=(X=O.functionCall.id)!=null?X:f(),Ae=O.functionCall.name;b.enqueue({type:"tool-input-start",id:ue,toolName:Ae,providerMetadata:H}),b.enqueue({type:"tool-input-end",id:ue,providerMetadata:H}),b.enqueue({type:"tool-call",toolCallId:ue,toolName:Ae,input:"{}",providerMetadata:H}),g=!0}}}if(B.finishReason!=null)c={unified:Y_({finishReason:B.finishReason,hasToolCalls:g}),raw:B.finishReason},d={[o]:{promptFeedback:(k=K.promptFeedback)!=null?k:null,groundingMetadata:m,urlContextMetadata:p,safetyRatings:(Q=B.safetyRatings)!=null?Q:null,usageMetadata:q!=null?q:null,finishMessage:(J=B.finishMessage)!=null?J:null,serviceTier:(W=u==null?void 0:u.serviceTier)!=null?W: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:J_(u),providerMetadata:d})}})),response:{headers:s},request:{body:t}}}};function Q_({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 cS=()=>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()}),b2=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()}),uS=()=>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(b2).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()}),X_=r.array(r.object({modality:r.string(),tokenCount:r.number()})).nullish(),dS=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:X_,candidatesTokensDetails:X_}),pS=()=>r.object({urlMetadata:r.array(r.object({retrievedUrl:r.string(),urlRetrievalStatus:r.string()})).nullish()}),_2=j(()=>M(r.object({candidates:r.array(r.object({content:uS().nullish().or(r.object({}).strict()),finishReason:r.string().nullish(),finishMessage:r.string().nullish(),safetyRatings:r.array(ts()).nullish(),groundingMetadata:cS().nullish(),urlContextMetadata:pS().nullish()})),usageMetadata:dS.nullish(),promptFeedback:r.object({blockReason:r.string().nullish(),safetyRatings:r.array(ts()).nullish()}).nullish()}))),S2=j(()=>M(r.object({candidates:r.array(r.object({content:uS().nullish(),finishReason:r.string().nullish(),finishMessage:r.string().nullish(),safetyRatings:r.array(ts()).nullish(),groundingMetadata:cS().nullish(),urlContextMetadata:pS().nullish()})).nullish(),usageMetadata:dS.nullish(),promptFeedback:r.object({blockReason:r.string().nullish(),safetyRatings:r.array(ts()).nullish()}).nullish()}))),w2=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.")})}),x2=Ge({id:"google.enterprise_web_search",inputSchema:j(()=>M(r.object({})))}),T2=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(),I2=j(()=>M(T2)),C2=Ge({id:"google.file_search",inputSchema:I2}),k2=Ge({id:"google.google_maps",inputSchema:j(()=>M(r.object({})))}),mS=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(),R2=j(()=>M(mS)),E2=Ge({id:"google.google_search",inputSchema:R2}),A2=Ge({id:"google.url_context",inputSchema:j(()=>M(r.object({})))}),P2=Ge({id:"google.vertex_rag_store",inputSchema:r.object({ragCorpus:r.string(),topK:r.number().optional()})}),M2={googleSearch:E2,enterpriseWebSearch:x2,googleMaps:k2,urlContext:A2,fileSearch:C2,codeExecution:w2,vertexRagStore:P2},j2=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(eS(this.modelId))return 10;return 4}get provider(){return this.config.provider}async doGenerate(e){if(eS(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 qe({provider:"google",providerOptions:u,schema:tS}),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(O2),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 qe({provider:"google",providerOptions:w,schema:tS}),{googleSearch:F,...R}=(t=w==null?void 0:w.google)!=null?t:{},D=await new lS(this.modelId,{provider:this.config.provider,baseURL:this.config.baseURL,headers:(n=this.config.headers)!=null?n:{},fetch:this.config.fetch,generateId:(o=this.config.generateId)!=null?o:Le}).doGenerate({prompt:b,seed:v,providerOptions:{google:{responseModalities:["IMAGE"],imageConfig:h?{aspectRatio:h}:void 0,...R}},tools:(E==null?void 0:E.googleSearch)!=null?[{type:"provider",id:"google.google_search",name:"google_search",args:E.googleSearch}]:void 0,headers:S,abortSignal:y}),N=(s=(a=(i=this.config._internal)==null?void 0:i.currentDate)==null?void 0:a.call(i))!=null?s:new Date,re=[];for(let V of D.content)if(V.type==="file"&&V.mediaType.startsWith("image/"))re.push(bt(V.data));let Y=(c=(l=D.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=D.response)==null?void 0:u.headers},usage:D.usage?{inputTokens:D.usage.inputTokens.total,outputTokens:D.usage.outputTokens.total,totalTokens:((d=D.usage.inputTokens.total)!=null?d:0)+((m=D.usage.outputTokens.total)!=null?m:0)}:void 0}}};function eS(e){return e.startsWith("gemini-")}var O2=j(()=>M(r.object({predictions:r.array(r.object({bytesBase64Encoded:r.string()})).default([])}))),tS=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:mS.optional()})));function N2(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 D2(e){var t;return(t=N2(e))!=null?t:e.image}function z2(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 q2(e){if(e.frameImages!=null&&e.frameImages.length>0)return;return e.inputReferences!=null&&e.inputReferences.length>0?e.inputReferences:void 0}function vu(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 $2(e){if(e.bytesBase64Encoded)return{inlineData:{mimeType:"image/png",data:e.bytesBase64Encoded}};if(e.gcsUri)return{gcsUri:e.gcsUri};return e}function L2(e,t){let n=vu(e,t);return n!=null?{image:n,referenceType:"asset"}:void 0}var U2=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 qe({provider:"google",providerOptions:e.providerOptions,schema:F2}),p=[{}],f=p[0];if(e.prompt!=null)f.prompt=e.prompt;let g=D2(e);if(g!=null){let N=vu(g,d);if(N!=null)f.image=N}let h=z2(e);if(h!=null){let N=vu(h,d);if(N!=null)f.lastFrame=N}let v=q2(e);if(v!=null)f.referenceImages=v.flatMap((N)=>{let re=L2(N,d);return re!=null?[re]:[]});else if((m==null?void 0:m.referenceImages)!=null)f.referenceImages=m.referenceImages.map((N)=>$2(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(rS),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(rS),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=[],z=await Se(this.config.headers),D=z==null?void 0:z["x-goog-api-key"];for(let N of E.generateVideoResponse.generatedSamples)if((c=N.video)==null?void 0:c.uri){let re=D&&Zm(N.video.uri,this.config.baseURL)?`${N.video.uri}${N.video.uri.includes("?")?"&":"?"}key=${D}`: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}}}}},rS=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()}),F2=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 wu(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 gS(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 B2={pdf:"application/pdf",txt:"text/plain",md:"text/markdown",markdown:"text/markdown",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function fS(e){let t=e.toLowerCase();for(let[n,o]of Object.entries(B2))if(t.endsWith(`.${n}`))return o;return"application/octet-stream"}function hS(e){let t=e.split("/"),n=t[t.length-1];return n&&n.length>0?n:void 0}function G2({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:hS(c),d=fS(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 yS({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:hS(w),y=fS(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 bu({annotations:e,generateId:t}){var n;if(e==null)return[];let o=new Set,i=[];for(let a of e){let s=G2({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 xu({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 J2=new Set(["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"]),W2=new Set(["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"]);function H2(e){return e.replace(/_call$/,"")}function V2(e){return e.replace(/_result$/,"")}function nS({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,z,D,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 Q=k==null?void 0:k.created,J;if(typeof Q==="string"){let W=new Date(Q);if(!Number.isNaN(W.getTime()))J=W}f.enqueue({type:"response-metadata",...i!=null?{id:i}:{},modelId:k==null?void 0:k.model,...J?{timestamp:J}:{}});break}case"step.start":{let X=L,k=X.step,Q=X.index,J=`${i!=null?i:"interaction"}:${Q}`,W=k==null?void 0:k.type;if(W==="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(Q,{kind:"text",id:J,emittedSourceKeys:new Set}),f.enqueue({type:"text-start",id:J});let q=bu({annotations:K.annotations,generateId:t});for(let B of q){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(Q,{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(Q,{kind:"pending_model_output",id:J})}else if(W==="thought"){let K=k==null?void 0:k.signature;if(u.set(Q,{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 q of k.summary)if((q==null?void 0:q.type)==="text"&&typeof q.text==="string")f.enqueue({type:"reasoning-delta",id:J,delta:q.text})}}else if(W==="function_call"){let K=(h=k==null?void 0:k.id)!=null?h:J,q=(v=k==null?void 0:k.name)!=null?v:"unknown";c=!0;let B={kind:"function_call",id:J,toolCallId:K,toolName:q,argumentsAccum:"",...(k==null?void 0:k.signature)!=null?{signature:k.signature}:{}};u.set(Q,B),f.enqueue({type:"tool-input-start",id:K,toolName:q})}else if(W!=null&&J2.has(W)){let K=W==="mcp_server_tool_call"?(w=k==null?void 0:k.name)!=null?w:"mcp_server_tool":H2(W),q=(S=k==null?void 0:k.id)!=null?S:J,B={kind:"builtin_tool_call",id:J,blockType:W,toolCallId:q,toolName:K,arguments:(y=k==null?void 0:k.arguments)!=null?y:{},callEmitted:!1};u.set(Q,B)}else if(W!=null&&W2.has(W)){let K=W==="mcp_server_tool_result"?(x=k==null?void 0:k.name)!=null?x:"mcp_server_tool":V2(W),q=(_=k==null?void 0:k.call_id)!=null?_:J,B={kind:"builtin_tool_result",id:J,blockType:W,callId:q,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(Q,B)}else u.set(Q,{kind:"unknown",id:J});break}case"step.delta":{let X=L,k=u.get(X.index);if(k==null)break;let Q=(I=X.delta)==null?void 0:I.type;if(k.kind==="pending_model_output"){if(Q==="text"||Q==="text_annotation"||Q==="text_annotation_delta"){let W={kind:"text",id:k.id,emittedSourceKeys:new Set};u.set(X.index,W),k=W,f.enqueue({type:"text-start",id:W.id})}}if(Q==="image"&&(k.kind==="pending_model_output"||k.kind==="text"||k.kind==="image")){let W=X.delta,K={};if(i!=null)K.interactionId=i;let q=Object.keys(K).length>0?{google:K}:void 0;if((W==null?void 0:W.data)!=null&&W.data.length>0)f.enqueue({type:"file",mediaType:(b=W.mime_type)!=null?b:"image/png",data:W.data,...q?{providerMetadata:q}:{}});else if((W==null?void 0:W.uri)!=null&&W.uri.length>0){let B={google:{...i!=null?{interactionId:i}:{},imageUri:W.uri}};f.enqueue({type:"file",mediaType:(E=W.mime_type)!=null?E:"image/png",data:"",providerMetadata:B})}if(k.kind==="image")k.data=void 0,k.uri=void 0;break}if(Q==="video"&&(k.kind==="pending_model_output"||k.kind==="text")){let W=X.delta,K={};if(i!=null)K.interactionId=i;let q=Object.keys(K).length>0?{google:K}:void 0;if((W==null?void 0:W.data)!=null&&W.data.length>0)f.enqueue({type:"file",mediaType:(F=W.mime_type)!=null?F:"video/mp4",data:W.data,...q?{providerMetadata:q}:{}});else if((W==null?void 0:W.uri)!=null&&W.uri.length>0){let B={google:{...i!=null?{interactionId:i}:{},videoUri:W.uri}};f.enqueue({type:"file",mediaType:(R=W.mime_type)!=null?R:"video/mp4",data:"",providerMetadata:B})}break}let J=X.delta;if(k.kind==="text"&&(J==null?void 0:J.type)==="text"){let W=(z=J.text)!=null?z:"";if(W.length>0)f.enqueue({type:"text-delta",id:k.id,delta:W})}else if(k.kind==="text"&&((J==null?void 0:J.type)==="text_annotation"||(J==null?void 0:J.type)==="text_annotation_delta")){let W=bu({annotations:J.annotations,generateId:t});for(let K of W){let q=m(K);if(d.has(q))continue;d.add(q),k.emittedSourceKeys.add(q),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 W=J.content;if((W==null?void 0:W.type)==="text"&&typeof W.text==="string")f.enqueue({type:"reasoning-delta",id:k.id,delta:W.text})}else if((J==null?void 0:J.type)==="thought_signature"){let W=J.signature;if(W!=null)k.signature=W}}else if(k.kind==="function_call"&&(J==null?void 0:J.type)==="arguments_delta"){let W=typeof J.arguments==="string"?J.arguments:"";if(W.length>0)k.argumentsAccum+=W,f.enqueue({type:"tool-input-delta",id:k.toolCallId,delta:W});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 X=L,k=u.get(X.index);if(k==null)break;if(k.kind==="text"){let Q=i!=null?{google:{interactionId:i}}:void 0;f.enqueue({type:"text-end",id:k.id,...Q?{providerMetadata:Q}:{}})}else if(k.kind==="reasoning"){let Q={};if(k.signature!=null)Q.signature=k.signature;if(i!=null)Q.interactionId=i;let J=Object.keys(Q).length>0?{google:Q}:void 0;f.enqueue({type:"reasoning-end",id:k.id,...J?{providerMetadata:J}:{}})}else if(k.kind==="image"){let Q={};if(i!=null)Q.interactionId=i;let J=Object.keys(Q).length>0?{google:Q}:void 0;if(k.data!=null&&k.data.length>0)f.enqueue({type:"file",mediaType:(D=k.mimeType)!=null?D:"image/png",data:k.data,...J?{providerMetadata:J}:{}});else if(k.uri!=null&&k.uri.length>0){let W={google:{...i!=null?{interactionId:i}:{},imageUri:k.uri}};f.enqueue({type:"file",mediaType:(N=k.mimeType)!=null?N:"image/png",data:"",providerMetadata:W})}}else if(k.kind==="function_call"){let Q=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 W=Object.keys(J).length>0?{google:J}:void 0;f.enqueue({type:"tool-call",toolCallId:k.toolCallId,toolName:k.toolName,input:Q,...W?{providerMetadata:W}:{}})}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 Q=yS({block:{type:k.blockType,call_id:k.callId,result:k.result},generateId:t});for(let J of Q){let W=m(J);if(d.has(W))continue;d.add(W),f.enqueue(J)}}u.delete(X.index);break}case"interaction.status_update":case"interaction.in_progress":case"interaction.requires_action":{let X=L;if(X.status!=null)l=X.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 X=L;l="failed";let k=(V=X.error)!=null?V:{message:"Unknown interaction error"};f.enqueue({type:"error",error:k});break}default:break}},flush(p){let f={unified:xu({status:l,hasFunctionCall:c}),raw:l},g=gS(a),h={google:{...i!=null?{interactionId:i}:{},...s!=null?{serviceTier:s}:{},...g!=null?{outputTokensByModality:g}:{}}};p.enqueue({type:"finish",finishReason:f,usage:wu(a),providerMetadata:h})}})}function vS(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 Z2({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?K2({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=oS({part:_,warnings:m,mediaResolution:o});if(C!=null)y.push(C)}let x=X2(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=oS({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"?Y2(_.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 _=Q2({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(`
|
|
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 H_(e){return e.includes("/")?e:`models/${e}`}var V_=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 m2({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 He({functionality:`tool choice type: ${h}`})}}var g2=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=f2(o),a=y2(this.accumulatedArgs,i);if(n.stringValue!=null&&a!==void 0){let c=JSON.stringify(n.stringValue).slice(1,-1);K_(this.accumulatedArgs,i,a+n.stringValue),t+=c;continue}let l=v2(n);if(l==null)continue;K_(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 f2(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 h2=Object.prototype.hasOwnProperty;function sS(e,t){return h2.call(e,t)}function Z_(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})}function y2(e,t){let n=e;for(let o of t){if(n==null||typeof n!=="object")return;let i=n;if(!sS(i,o))return;n=i[o]}return n}function K_(e,t,n){let o=e;for(let i=0;i<t.length-1;i++){let a=t[i],s=t[i+1];if(!sS(o,a)||o[a]==null)Z_(o,a,typeof s==="number"?[]:{});o=o[a]}Z_(o,t[t.length-1],n)}function v2(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 Y_({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 lS=class{constructor(e,t){this.specificationVersion="v3";var n;this.modelId=e,this.config=t,this.generateId=(n=t.generateId)!=null?n:Le}get provider(){return this.config.provider}get supportedUrls(){var e,t,n;return(n=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?n:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:o,topK:i,frequencyPenalty:a,presencePenalty:s,stopSequences:l,responseFormat:c,seed:u,tools:d,toolChoice:m,providerOptions:p},{isStreaming:f=!1}={}){var g,h;let v=[],w=this.config.provider.includes("vertex")?"vertex":"google",S=await $e({provider:w,providerOptions:p,schema:V_});if(S==null&&w!=="google")S=await $e({provider:"google",providerOptions:p,schema:V_});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}=p2(e,{isGemmaModel:C,isGemini3Model:I,providerOptionsName:w,supportsFunctionResponseParts:b,onWarning:(Y)=>v.push(Y)}),{tools:R,toolConfig:z,toolWarnings:D}=m2({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=z||N||(S==null?void 0:S.retrievalConfig)?{...z,...N&&{functionCallingConfig:{...z==null?void 0:z.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,...D],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}/${H_(this.modelId)}:generateContent`,headers:I,body:y,failedResponseHandler:or,successfulResponseHandler:xe(_2),abortSignal:e.abortSignal,fetch:this.config.fetch}),R=E.candidates[0],z=[],D=(n=(t=R.content)==null?void 0:t.parts)!=null?n:[],N=E.usageMetadata,re,Y;for(let L of D)if("executableCode"in L&&((o=L.executableCode)==null?void 0:o.code)){let pe=this.config.generateId();re=pe,z.push({type:"tool-call",toolCallId:pe,toolName:"code_execution",input:JSON.stringify(L.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in L&&L.codeExecutionResult)z.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&&z.length>0){let X=z[z.length-1];X.providerMetadata=pe}}else z.push({type:L.thought===!0?"reasoning":"text",text:L.text,providerMetadata:pe})}else if("functionCall"in L&&L.functionCall.name!=null)z.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,X=!!L.thoughtSignature;z.push({type:"file",data:L.inlineData.data,mediaType:L.inlineData.mimeType,providerMetadata:pe||X?{[_]:{...pe?{thought:!0}:{},...X?{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,z.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();z.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=Q_({groundingMetadata:R.groundingMetadata,generateId:this.config.generateId}))!=null?m:[];for(let L of V)z.push(L);return{content:z,finishReason:{unified:Y_({finishReason:R.finishReason,hasToolCalls:z.some((L)=>L.type==="tool-call"&&!L.providerExecuted)}),raw:(p=R.finishReason)!=null?p:void 0},usage:J_(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}/${H_(this.modelId)}:streamGenerateContent?alt=sse`,headers:a,body:t,failedResponseHandler:or,successfulResponseHandler:Dt(S2),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,z,D,N,re,Y,V,L,pe,X,k,Q,J,W;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,q=K.usageMetadata;if(q!=null)u=q;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=Q_({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 H=f();y=H,b.enqueue({type:"tool-call",toolCallId:H,toolName:"code_execution",input:JSON.stringify(O.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in O&&O.codeExecutionResult){let H=y;if(H)b.enqueue({type:"tool-result",toolCallId:H,toolName:"code_execution",result:{outcome:O.codeExecutionResult.outcome,output:(z=O.codeExecutionResult.output)!=null?z:""}}),y=void 0}else if("text"in O&&O.text!=null){let H=O.thoughtSignature?{[o]:{thoughtSignature:O.thoughtSignature}}:void 0;if(O.text.length===0){if(H!=null&&h!==null)b.enqueue({type:"text-delta",id:h,delta:"",providerMetadata:H})}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:H});b.enqueue({type:"reasoning-delta",id:v,delta:O.text,providerMetadata:H})}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:H});b.enqueue({type:"text-delta",id:h,delta:O.text,providerMetadata:H})}}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 H=O.thought===!0,P=!!O.thoughtSignature,U=H||P?{[o]:{...H?{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 H=(D=O.toolCall.id)!=null?D:f();x=H;let P={[o]:{...O.thoughtSignature?{thoughtSignature:O.thoughtSignature}:{},serverToolCallId:H,serverToolType:O.toolCall.toolType}};b.enqueue({type:"tool-call",toolCallId:H,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 H=(re=x!=null?x:O.toolResponse.id)!=null?re:f(),P={[o]:{...O.thoughtSignature?{thoughtSignature:O.thoughtSignature}:{},serverToolCallId:H,serverToolType:O.toolResponse.toolType}};b.enqueue({type:"tool-result",toolCallId:H,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 H=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,ge=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 g2;if(_.push({toolCallId:ue,toolName:O.functionCall.name,accumulator:Ae,providerMetadata:H}),b.enqueue({type:"tool-input-start",id:ue,toolName:O.functionCall.name,providerMetadata:H}),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:H});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:H});if(O.functionCall.willContinue!==!0&&Ae.every((nt)=>nt.willContinue!==!0))C(b)}}else if(U&&_.length>0)C(b);else if(ge){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:H}),b.enqueue({type:"tool-input-delta",id:ue,delta:Ke,providerMetadata:H}),b.enqueue({type:"tool-input-end",id:ue,providerMetadata:H}),b.enqueue({type:"tool-call",toolCallId:ue,toolName:Ae,input:Ke,providerMetadata:H}),g=!0}else if(ee){let ue=(X=O.functionCall.id)!=null?X:f(),Ae=O.functionCall.name;b.enqueue({type:"tool-input-start",id:ue,toolName:Ae,providerMetadata:H}),b.enqueue({type:"tool-input-end",id:ue,providerMetadata:H}),b.enqueue({type:"tool-call",toolCallId:ue,toolName:Ae,input:"{}",providerMetadata:H}),g=!0}}}if(B.finishReason!=null)c={unified:Y_({finishReason:B.finishReason,hasToolCalls:g}),raw:B.finishReason},d={[o]:{promptFeedback:(k=K.promptFeedback)!=null?k:null,groundingMetadata:m,urlContextMetadata:p,safetyRatings:(Q=B.safetyRatings)!=null?Q:null,usageMetadata:q!=null?q:null,finishMessage:(J=B.finishMessage)!=null?J:null,serviceTier:(W=u==null?void 0:u.serviceTier)!=null?W: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:J_(u),providerMetadata:d})}})),response:{headers:s},request:{body:t}}}};function Q_({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 cS=()=>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()}),b2=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()}),uS=()=>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(b2).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()}),X_=r.array(r.object({modality:r.string(),tokenCount:r.number()})).nullish(),dS=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:X_,candidatesTokensDetails:X_}),pS=()=>r.object({urlMetadata:r.array(r.object({retrievedUrl:r.string(),urlRetrievalStatus:r.string()})).nullish()}),_2=j(()=>M(r.object({candidates:r.array(r.object({content:uS().nullish().or(r.object({}).strict()),finishReason:r.string().nullish(),finishMessage:r.string().nullish(),safetyRatings:r.array(ts()).nullish(),groundingMetadata:cS().nullish(),urlContextMetadata:pS().nullish()})),usageMetadata:dS.nullish(),promptFeedback:r.object({blockReason:r.string().nullish(),safetyRatings:r.array(ts()).nullish()}).nullish()}))),S2=j(()=>M(r.object({candidates:r.array(r.object({content:uS().nullish(),finishReason:r.string().nullish(),finishMessage:r.string().nullish(),safetyRatings:r.array(ts()).nullish(),groundingMetadata:cS().nullish(),urlContextMetadata:pS().nullish()})).nullish(),usageMetadata:dS.nullish(),promptFeedback:r.object({blockReason:r.string().nullish(),safetyRatings:r.array(ts()).nullish()}).nullish()}))),w2=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.")})}),x2=Ge({id:"google.enterprise_web_search",inputSchema:j(()=>M(r.object({})))}),T2=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(),I2=j(()=>M(T2)),C2=Ge({id:"google.file_search",inputSchema:I2}),k2=Ge({id:"google.google_maps",inputSchema:j(()=>M(r.object({})))}),mS=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(),R2=j(()=>M(mS)),E2=Ge({id:"google.google_search",inputSchema:R2}),A2=Ge({id:"google.url_context",inputSchema:j(()=>M(r.object({})))}),P2=Ge({id:"google.vertex_rag_store",inputSchema:r.object({ragCorpus:r.string(),topK:r.number().optional()})}),M2={googleSearch:E2,enterpriseWebSearch:x2,googleMaps:k2,urlContext:A2,fileSearch:C2,codeExecution:w2,vertexRagStore:P2},j2=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(eS(this.modelId))return 10;return 4}get provider(){return this.config.provider}async doGenerate(e){if(eS(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 $e({provider:"google",providerOptions:u,schema:tS}),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(O2),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 $e({provider:"google",providerOptions:w,schema:tS}),{googleSearch:F,...R}=(t=w==null?void 0:w.google)!=null?t:{},D=await new lS(this.modelId,{provider:this.config.provider,baseURL:this.config.baseURL,headers:(n=this.config.headers)!=null?n:{},fetch:this.config.fetch,generateId:(o=this.config.generateId)!=null?o:Le}).doGenerate({prompt:b,seed:v,providerOptions:{google:{responseModalities:["IMAGE"],imageConfig:h?{aspectRatio:h}:void 0,...R}},tools:(E==null?void 0:E.googleSearch)!=null?[{type:"provider",id:"google.google_search",name:"google_search",args:E.googleSearch}]:void 0,headers:S,abortSignal:y}),N=(s=(a=(i=this.config._internal)==null?void 0:i.currentDate)==null?void 0:a.call(i))!=null?s:new Date,re=[];for(let V of D.content)if(V.type==="file"&&V.mediaType.startsWith("image/"))re.push(bt(V.data));let Y=(c=(l=D.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=D.response)==null?void 0:u.headers},usage:D.usage?{inputTokens:D.usage.inputTokens.total,outputTokens:D.usage.outputTokens.total,totalTokens:((d=D.usage.inputTokens.total)!=null?d:0)+((m=D.usage.outputTokens.total)!=null?m:0)}:void 0}}};function eS(e){return e.startsWith("gemini-")}var O2=j(()=>M(r.object({predictions:r.array(r.object({bytesBase64Encoded:r.string()})).default([])}))),tS=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:mS.optional()})));function N2(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 D2(e){var t;return(t=N2(e))!=null?t:e.image}function z2(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 $2(e){if(e.frameImages!=null&&e.frameImages.length>0)return;return e.inputReferences!=null&&e.inputReferences.length>0?e.inputReferences:void 0}function vu(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 q2(e){if(e.bytesBase64Encoded)return{inlineData:{mimeType:"image/png",data:e.bytesBase64Encoded}};if(e.gcsUri)return{gcsUri:e.gcsUri};return e}function L2(e,t){let n=vu(e,t);return n!=null?{image:n,referenceType:"asset"}:void 0}var U2=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 $e({provider:"google",providerOptions:e.providerOptions,schema:F2}),p=[{}],f=p[0];if(e.prompt!=null)f.prompt=e.prompt;let g=D2(e);if(g!=null){let N=vu(g,d);if(N!=null)f.image=N}let h=z2(e);if(h!=null){let N=vu(h,d);if(N!=null)f.lastFrame=N}let v=$2(e);if(v!=null)f.referenceImages=v.flatMap((N)=>{let re=L2(N,d);return re!=null?[re]:[]});else if((m==null?void 0:m.referenceImages)!=null)f.referenceImages=m.referenceImages.map((N)=>q2(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(rS),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(rS),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=[],z=await Se(this.config.headers),D=z==null?void 0:z["x-goog-api-key"];for(let N of E.generateVideoResponse.generatedSamples)if((c=N.video)==null?void 0:c.uri){let re=D&&Zm(N.video.uri,this.config.baseURL)?`${N.video.uri}${N.video.uri.includes("?")?"&":"?"}key=${D}`: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}}}}},rS=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()}),F2=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 wu(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 gS(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 B2={pdf:"application/pdf",txt:"text/plain",md:"text/markdown",markdown:"text/markdown",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function fS(e){let t=e.toLowerCase();for(let[n,o]of Object.entries(B2))if(t.endsWith(`.${n}`))return o;return"application/octet-stream"}function hS(e){let t=e.split("/"),n=t[t.length-1];return n&&n.length>0?n:void 0}function G2({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:hS(c),d=fS(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 yS({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:hS(w),y=fS(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 bu({annotations:e,generateId:t}){var n;if(e==null)return[];let o=new Set,i=[];for(let a of e){let s=G2({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 xu({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 J2=new Set(["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"]),W2=new Set(["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"]);function H2(e){return e.replace(/_call$/,"")}function V2(e){return e.replace(/_result$/,"")}function nS({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,z,D,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 Q=k==null?void 0:k.created,J;if(typeof Q==="string"){let W=new Date(Q);if(!Number.isNaN(W.getTime()))J=W}f.enqueue({type:"response-metadata",...i!=null?{id:i}:{},modelId:k==null?void 0:k.model,...J?{timestamp:J}:{}});break}case"step.start":{let X=L,k=X.step,Q=X.index,J=`${i!=null?i:"interaction"}:${Q}`,W=k==null?void 0:k.type;if(W==="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(Q,{kind:"text",id:J,emittedSourceKeys:new Set}),f.enqueue({type:"text-start",id:J});let q=bu({annotations:K.annotations,generateId:t});for(let B of q){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(Q,{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(Q,{kind:"pending_model_output",id:J})}else if(W==="thought"){let K=k==null?void 0:k.signature;if(u.set(Q,{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 q of k.summary)if((q==null?void 0:q.type)==="text"&&typeof q.text==="string")f.enqueue({type:"reasoning-delta",id:J,delta:q.text})}}else if(W==="function_call"){let K=(h=k==null?void 0:k.id)!=null?h:J,q=(v=k==null?void 0:k.name)!=null?v:"unknown";c=!0;let B={kind:"function_call",id:J,toolCallId:K,toolName:q,argumentsAccum:"",...(k==null?void 0:k.signature)!=null?{signature:k.signature}:{}};u.set(Q,B),f.enqueue({type:"tool-input-start",id:K,toolName:q})}else if(W!=null&&J2.has(W)){let K=W==="mcp_server_tool_call"?(w=k==null?void 0:k.name)!=null?w:"mcp_server_tool":H2(W),q=(S=k==null?void 0:k.id)!=null?S:J,B={kind:"builtin_tool_call",id:J,blockType:W,toolCallId:q,toolName:K,arguments:(y=k==null?void 0:k.arguments)!=null?y:{},callEmitted:!1};u.set(Q,B)}else if(W!=null&&W2.has(W)){let K=W==="mcp_server_tool_result"?(x=k==null?void 0:k.name)!=null?x:"mcp_server_tool":V2(W),q=(_=k==null?void 0:k.call_id)!=null?_:J,B={kind:"builtin_tool_result",id:J,blockType:W,callId:q,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(Q,B)}else u.set(Q,{kind:"unknown",id:J});break}case"step.delta":{let X=L,k=u.get(X.index);if(k==null)break;let Q=(I=X.delta)==null?void 0:I.type;if(k.kind==="pending_model_output"){if(Q==="text"||Q==="text_annotation"||Q==="text_annotation_delta"){let W={kind:"text",id:k.id,emittedSourceKeys:new Set};u.set(X.index,W),k=W,f.enqueue({type:"text-start",id:W.id})}}if(Q==="image"&&(k.kind==="pending_model_output"||k.kind==="text"||k.kind==="image")){let W=X.delta,K={};if(i!=null)K.interactionId=i;let q=Object.keys(K).length>0?{google:K}:void 0;if((W==null?void 0:W.data)!=null&&W.data.length>0)f.enqueue({type:"file",mediaType:(b=W.mime_type)!=null?b:"image/png",data:W.data,...q?{providerMetadata:q}:{}});else if((W==null?void 0:W.uri)!=null&&W.uri.length>0){let B={google:{...i!=null?{interactionId:i}:{},imageUri:W.uri}};f.enqueue({type:"file",mediaType:(E=W.mime_type)!=null?E:"image/png",data:"",providerMetadata:B})}if(k.kind==="image")k.data=void 0,k.uri=void 0;break}if(Q==="video"&&(k.kind==="pending_model_output"||k.kind==="text")){let W=X.delta,K={};if(i!=null)K.interactionId=i;let q=Object.keys(K).length>0?{google:K}:void 0;if((W==null?void 0:W.data)!=null&&W.data.length>0)f.enqueue({type:"file",mediaType:(F=W.mime_type)!=null?F:"video/mp4",data:W.data,...q?{providerMetadata:q}:{}});else if((W==null?void 0:W.uri)!=null&&W.uri.length>0){let B={google:{...i!=null?{interactionId:i}:{},videoUri:W.uri}};f.enqueue({type:"file",mediaType:(R=W.mime_type)!=null?R:"video/mp4",data:"",providerMetadata:B})}break}let J=X.delta;if(k.kind==="text"&&(J==null?void 0:J.type)==="text"){let W=(z=J.text)!=null?z:"";if(W.length>0)f.enqueue({type:"text-delta",id:k.id,delta:W})}else if(k.kind==="text"&&((J==null?void 0:J.type)==="text_annotation"||(J==null?void 0:J.type)==="text_annotation_delta")){let W=bu({annotations:J.annotations,generateId:t});for(let K of W){let q=m(K);if(d.has(q))continue;d.add(q),k.emittedSourceKeys.add(q),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 W=J.content;if((W==null?void 0:W.type)==="text"&&typeof W.text==="string")f.enqueue({type:"reasoning-delta",id:k.id,delta:W.text})}else if((J==null?void 0:J.type)==="thought_signature"){let W=J.signature;if(W!=null)k.signature=W}}else if(k.kind==="function_call"&&(J==null?void 0:J.type)==="arguments_delta"){let W=typeof J.arguments==="string"?J.arguments:"";if(W.length>0)k.argumentsAccum+=W,f.enqueue({type:"tool-input-delta",id:k.toolCallId,delta:W});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 X=L,k=u.get(X.index);if(k==null)break;if(k.kind==="text"){let Q=i!=null?{google:{interactionId:i}}:void 0;f.enqueue({type:"text-end",id:k.id,...Q?{providerMetadata:Q}:{}})}else if(k.kind==="reasoning"){let Q={};if(k.signature!=null)Q.signature=k.signature;if(i!=null)Q.interactionId=i;let J=Object.keys(Q).length>0?{google:Q}:void 0;f.enqueue({type:"reasoning-end",id:k.id,...J?{providerMetadata:J}:{}})}else if(k.kind==="image"){let Q={};if(i!=null)Q.interactionId=i;let J=Object.keys(Q).length>0?{google:Q}:void 0;if(k.data!=null&&k.data.length>0)f.enqueue({type:"file",mediaType:(D=k.mimeType)!=null?D:"image/png",data:k.data,...J?{providerMetadata:J}:{}});else if(k.uri!=null&&k.uri.length>0){let W={google:{...i!=null?{interactionId:i}:{},imageUri:k.uri}};f.enqueue({type:"file",mediaType:(N=k.mimeType)!=null?N:"image/png",data:"",providerMetadata:W})}}else if(k.kind==="function_call"){let Q=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 W=Object.keys(J).length>0?{google:J}:void 0;f.enqueue({type:"tool-call",toolCallId:k.toolCallId,toolName:k.toolName,input:Q,...W?{providerMetadata:W}:{}})}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 Q=yS({block:{type:k.blockType,call_id:k.callId,result:k.result},generateId:t});for(let J of Q){let W=m(J);if(d.has(W))continue;d.add(W),f.enqueue(J)}}u.delete(X.index);break}case"interaction.status_update":case"interaction.in_progress":case"interaction.requires_action":{let X=L;if(X.status!=null)l=X.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 X=L;l="failed";let k=(V=X.error)!=null?V:{message:"Unknown interaction error"};f.enqueue({type:"error",error:k});break}default:break}},flush(p){let f={unified:xu({status:l,hasFunctionCall:c}),raw:l},g=gS(a),h={google:{...i!=null?{interactionId:i}:{},...s!=null?{serviceTier:s}:{},...g!=null?{outputTokensByModality:g}:{}}};p.enqueue({type:"finish",finishReason:f,usage:wu(a),providerMetadata:h})}})}function vS(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 Z2({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?K2({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=oS({part:_,warnings:m,mediaResolution:o});if(C!=null)y.push(C)}let x=X2(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=oS({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"?Y2(_.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 _=Q2({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
87
|
|
|
88
88
|
`):void 0;return{input:v,systemInstruction:w,warnings:m}}function oS({part:e,warnings:t,mediaResolution:n}){let o=vS(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 K2({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 Y2(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 Q2({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=yu({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=yu({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(vS(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=yu({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 yu({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 X2(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
89
|
|
|
90
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(),bS=()=>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(),_S=()=>r.enum(["in_progress","requires_action","completed","failed","cancelled","incomplete"]),SS=()=>{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()])},wS=()=>r.object({type:r.string(),text:r.string().nullish(),data:r.string().nullish(),mime_type:r.string().nullish()}).loose(),iS=()=>{let e=r.object({type:r.literal("text"),text:r.string(),annotations:r.array(SS()).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()])},xS=["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"],TS=["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"],IS=()=>{let e=r.object({type:r.literal("user_input"),content:r.array(iS()).nullish()}).loose(),t=r.object({type:r.literal("model_output"),content:r.array(iS()).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(wS()).nullish()}).loose(),i=r.object({type:r.enum(xS),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(TS),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()])},_u=j(()=>M(r.object({id:r.string().nullish(),created:r.string().nullish(),updated:r.string().nullish(),status:_S(),model:r.string().nullish(),agent:r.string().nullish(),steps:r.array(IS()).nullish(),usage:bS().nullish(),service_tier:r.string().nullish(),previous_interaction_id:r.string().nullish(),response_modalities:r.array(r.string()).nullish()}).loose())),CS=j(()=>M((()=>{let e=_S(),t=SS(),n=wS(),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:IS()}).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(xS),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(TS),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:bS().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])})())),ez=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 zi({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 tz=new Set(["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"]),rz=new Set(["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"]);function nz(e){return e.replace(/_call$/,"")}function oz(e){return e.replace(/_result$/,"")}function kS({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,...zi({interactionId:n})});let E=bu({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,...zi({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,...zi({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,...zi({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:{}),...zi({signature:x.signature,interactionId:n})});break}default:{if(tz.has(y)){let x=S,_=y==="mcp_server_tool_call"?(d=x.name)!=null?d:"mcp_server_tool":nz(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(rz.has(y)){let x=S,_=y==="mcp_server_tool_result"?(f=x.name)!=null?f:"mcp_server_tool":oz(y);v.push({type:"tool-result",toolCallId:(g=x.call_id)!=null?g:t(),toolName:_,result:(h=x.result)!=null?h:null});let C=yS({block:S,generateId:t});for(let I of C)v.push(I)}break}}}return{content:v,hasFunctionCall:w}}var iz=()=>globalThis.fetch;async function RS({baseURL:e,interactionId:t,headers:n,fetch:o=iz()}){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),ao()),body:"{}"});try{await a.text()}catch(s){}}catch(a){}}var az=new Set(["completed","failed","cancelled","incomplete"]);function Su(e){return e!=null&&az.has(e)}var sz=1000,lz=1e4,cz=1800000;async function uz({baseURL:e,interactionId:t,headers:n,fetch:o,abortSignal:i,initialDelayMs:a=sz,maxDelayMs:s=lz,timeoutMs:l=cz}){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=()=>RS({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(_u),abortSignal:i,fetch:o});if(Su(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 dz({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 pz=3,mz=500;function gz({baseURL:e,interactionId:t,headers:n,fetch:o,abortSignal:i,maxRetries:a=pz,retryDelayMs:s=mz}){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(CS),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 RS({baseURL:e,interactionId:t,headers:n,fetch:o})}},cancel(){f.abort(),p==null||p.cancel().catch(()=>{}),p=void 0}})}function fz({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}=kS({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:xu({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:wu(e.usage),providerMetadata:S}),a.close()}})}var hz=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=[],z=await qe({provider:"google",providerOptions:e.providerOptions,schema:ez}),D=this.agent!=null,N=e.tools!=null&&e.tools.length>0,re,Y;if(N&&D)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=dz({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(D)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((z==null?void 0:z.responseFormat)!=null){for(let B of z.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:X}=Z2({prompt:e.prompt,previousInteractionId:(c=z==null?void 0:z.previousInteractionId)!=null?c:void 0,store:(u=z==null?void 0:z.store)!=null?u:void 0,mediaResolution:(d=z==null?void 0:z.mediaResolution)!=null?d:void 0});R.push(...X);let k=pe,Q=(m=z==null?void 0:z.systemInstruction)!=null?m:void 0;if(k!=null&&Q!=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&&Q!=null)k=Q;let J;if(D){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((z==null?void 0:z.thinkingLevel)!=null)B.push("thinkingLevel");if((z==null?void 0:z.thinkingSummaries)!=null)B.push("thinkingSummaries");if((z==null?void 0:z.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=z==null?void 0:z.thinkingLevel)!=null?v:void 0,thinking_summaries:(w=z==null?void 0:z.thinkingSummaries)!=null?w:void 0,tool_choice:Y}),(z==null?void 0:z.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",...z.imageConfig.aspectRatio!=null?{aspect_ratio:z.imageConfig.aspectRatio}:{},...z.imageConfig.imageSize!=null?{image_size:z.imageConfig.imageSize}:{}})}let W;if(D&&(z==null?void 0:z.agentConfig)!=null){let B=z.agentConfig;if(B.type==="deep-research")W=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")W={type:"dynamic"}}let K;if((z==null?void 0:z.environment)!=null)if(!D)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 z.environment==="string")K=z.environment;else{let B=z.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({...D?{agent:this.agent}:{model:this.modelId},input:L,system_instruction:k,tools:re,response_format:V.length>0?V:void 0,response_modalities:(z==null?void 0:z.responseModalities)!=null?z.responseModalities:void 0,previous_interaction_id:(C=z==null?void 0:z.previousInteractionId)!=null?C:void 0,service_tier:(I=z==null?void 0:z.serviceTier)!=null?I:void 0,store:(b=z==null?void 0:z.store)!=null?b:void 0,generation_config:J!=null&&Object.keys(J).length>0?J:void 0,agent_config:W,environment:K,background:(E=z==null?void 0:z.background)!=null?E:void 0}),warnings:R,isAgent:D,isBackground:(z==null?void 0:z.background)===!0,pollingTimeoutMs:(F=z==null?void 0:z.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(aS,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(_u),abortSignal:e.abortSignal,fetch:this.config.fetch}),{responseHeaders:g,value:h,rawValue:v}=f;if(u&&!Su(h.status)){let E=await uz({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}=kS({steps:(n=h.steps)!=null?n:null,generateId:(o=this.config.generateId)!=null?o:Le,interactionId:w}),x={unified:xu({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=gS(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:wu(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(aS,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(CS),abortSignal:e.abortSignal,fetch:this.config.fetch}),m=u==null?void 0:u["x-gemini-service-tier"],p=nS({warnings:o,generateId:(t=this.config.generateId)!=null?t:Le,includeRawChunks:e.includeRawChunks,serviceTier:m});return{stream:d.pipeThrough(p),request:{body:c},response:{headers:u}}}async doStreamBackground({args:e,warnings:t,url:n,mergedHeaders:o,options:i,pollingTimeoutMs:a}){var s,l;let c=await Ie({url:n,headers:o,body:e,failedResponseHandler:or,successfulResponseHandler:xe(_u),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(Su(d.status))return{stream:fz({response:d,warnings:t,generateId:(s=this.config.generateId)!=null?s:Le,includeRawChunks:i.includeRawChunks,headerServiceTier:p}),request:{body:e},response:{headers:u}};let f=gz({baseURL:this.config.baseURL,interactionId:m,headers:o,fetch:this.config.fetch,abortSignal:i.abortSignal}),g=nS({warnings:t,generateId:(l=this.config.generateId)!=null?l:Le,includeRawChunks:i.includeRawChunks,serviceTier:p});return{stream:f.pipeThrough(g),request:{body:e},response:{headers:u}}}},aS={"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 yz=["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"],vz=/^https:\/\/.*$/;function bz(e){return/(^|\/)gemini-/.test(e)&&!/(^|\/)gemini-2\.0/.test(e)}function ns(e={}){var t,n;let o=(t=pn(e.baseURL))!=null?t:"https://generativelanguage.googleapis.com/v1beta",i=(n=e.name)!=null?n:"google.generative-ai",a=()=>it({"x-goog-api-key":so({apiKey:e.apiKey,environmentVariableName:"GOOGLE_GENERATIVE_AI_API_KEY",description:"Google Generative AI"}),...e.headers},`ai-sdk/google/${Q1}`),s=(p)=>{var f;return new lS(p,{provider:i,baseURL:o,headers:a,generateId:(f=e.generateId)!=null?f:Le,supportedUrls:()=>({"*":[new RegExp(`^${o}/files/.*$`),new RegExp("^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$"),new RegExp("^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$")],...bz(p)?Object.fromEntries(yz.map((g)=>[g,[vz]])):{}}),fetch:e.fetch})},l=(p)=>new r2(p,{provider:i,baseURL:o,headers:a,fetch:e.fetch}),c=(p,f={})=>new j2(p,f,{provider:i,baseURL:o,headers:a,fetch:e.fetch}),u=(p)=>{var f;return new U2(p,{provider:i,baseURL:o,headers:a,fetch:e.fetch,generateId:(f=e.generateId)!=null?f:Le})},d=(p)=>{var f;return new hz(p,{provider:`${i}.interactions`,baseURL:o,headers:a,generateId:(f=e.generateId)!=null?f:Le,fetch:e.fetch})},m=function(p){if(new.target)throw Error("The Google Generative AI model function cannot be called with the new keyword.");return s(p)};return m.specificationVersion="v3",m.languageModel=s,m.chat=s,m.generativeAI=s,m.embedding=l,m.embeddingModel=l,m.textEmbedding=l,m.textEmbeddingModel=l,m.image=c,m.imageModel=c,m.video=u,m.videoModel=u,m.interactions=d,m.tools=M2,m}var SK=ns();function Tu(e){let t=e.model?tu(e.model):void 0,n=e.apiKey,o=e.imageApiKey??e.apiKey;return{anthropicProvider:n?su({apiKey:n}):h_,openaiProvider:t==="openai"&&n?vo({apiKey:n}):o?vo({apiKey:o}):null,googleProvider:t==="google"&&n?ns({apiKey:n}):o?ns({apiKey:o}):null}}function ES(e,t){let n=ji(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 AS(e){return e.openaiProvider!==null||e.googleProvider!==null}function PS(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 MS(e,t,n,o,i){let a=n?.signal;a?.throwIfAborted();let{provider:s,modelId:l}=ru(t),c=PS(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 eu({model:c,prompt:e,aspectRatio:u,...a?{abortSignal:a}:{}}):await eu({model:c,prompt:e,size:_z[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 _z={"1:1":"1024x1024","16:9":"1536x1024","9:16":"1024x1536","4:3":"1536x1024","3:4":"1024x1536"};function Iu(e){return{...e,temperature:e.temperature??0.7,maxTokens:e.maxTokens??1000,webSearch:e.webSearch??!0}}function Cu(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 bo(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=Iu(e),this.logger=t.child("AIService"),this.providers=Tu(this.config),this.capabilities=Oi(this.config.model)}getModel(){return this.cachedModel??=ES(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 Xc({model:this.getModel(),system:e,prompt:t,...n?{abortSignal:n}:{},...Cu(this.config,this.capabilities.provider,this.capabilities.supportsTemperature)}),i=bo(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=Cu(this.config,this.capabilities.provider,this.capabilities.supportsTemperature),a=await Jb({model:this.getModel(),system:e,prompt:t,schema:n,...o?{abortSignal:o}:{},...i,providerOptions:{...i.providerOptions,anthropic:{structuredOutputMode:"jsonTool"}}}),s=bo(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=Iu({...this.config,...e});let n=this.config.model!==t;if(e.apiKey!==void 0||e.imageApiKey!==void 0||n)this.providers=Tu(this.config),this.cachedModel=null;if(n)this.capabilities=Oi(this.config.model);this.logger.info("AI configuration updated",{model:this.config.model})}getConfig(){return{...this.config}}canGenerateImages(){return AS(this.providers)}async generateImage(e,t){return MS(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 Sz="text-embedding-3-small",wz=1536;class
|
|
91
|
+
`);v.push({type:"reasoning",text:C,...zi({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:{}),...zi({signature:x.signature,interactionId:n})});break}default:{if(tz.has(y)){let x=S,_=y==="mcp_server_tool_call"?(d=x.name)!=null?d:"mcp_server_tool":nz(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(rz.has(y)){let x=S,_=y==="mcp_server_tool_result"?(f=x.name)!=null?f:"mcp_server_tool":oz(y);v.push({type:"tool-result",toolCallId:(g=x.call_id)!=null?g:t(),toolName:_,result:(h=x.result)!=null?h:null});let C=yS({block:S,generateId:t});for(let I of C)v.push(I)}break}}}return{content:v,hasFunctionCall:w}}var iz=()=>globalThis.fetch;async function RS({baseURL:e,interactionId:t,headers:n,fetch:o=iz()}){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),ao()),body:"{}"});try{await a.text()}catch(s){}}catch(a){}}var az=new Set(["completed","failed","cancelled","incomplete"]);function Su(e){return e!=null&&az.has(e)}var sz=1000,lz=1e4,cz=1800000;async function uz({baseURL:e,interactionId:t,headers:n,fetch:o,abortSignal:i,initialDelayMs:a=sz,maxDelayMs:s=lz,timeoutMs:l=cz}){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=()=>RS({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(_u),abortSignal:i,fetch:o});if(Su(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 dz({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 pz=3,mz=500;function gz({baseURL:e,interactionId:t,headers:n,fetch:o,abortSignal:i,maxRetries:a=pz,retryDelayMs:s=mz}){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(CS),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 RS({baseURL:e,interactionId:t,headers:n,fetch:o})}},cancel(){f.abort(),p==null||p.cancel().catch(()=>{}),p=void 0}})}function fz({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}=kS({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:xu({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:wu(e.usage),providerMetadata:S}),a.close()}})}var hz=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=[],z=await $e({provider:"google",providerOptions:e.providerOptions,schema:ez}),D=this.agent!=null,N=e.tools!=null&&e.tools.length>0,re,Y;if(N&&D)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=dz({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(D)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((z==null?void 0:z.responseFormat)!=null){for(let B of z.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:X}=Z2({prompt:e.prompt,previousInteractionId:(c=z==null?void 0:z.previousInteractionId)!=null?c:void 0,store:(u=z==null?void 0:z.store)!=null?u:void 0,mediaResolution:(d=z==null?void 0:z.mediaResolution)!=null?d:void 0});R.push(...X);let k=pe,Q=(m=z==null?void 0:z.systemInstruction)!=null?m:void 0;if(k!=null&&Q!=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&&Q!=null)k=Q;let J;if(D){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((z==null?void 0:z.thinkingLevel)!=null)B.push("thinkingLevel");if((z==null?void 0:z.thinkingSummaries)!=null)B.push("thinkingSummaries");if((z==null?void 0:z.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=z==null?void 0:z.thinkingLevel)!=null?v:void 0,thinking_summaries:(w=z==null?void 0:z.thinkingSummaries)!=null?w:void 0,tool_choice:Y}),(z==null?void 0:z.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",...z.imageConfig.aspectRatio!=null?{aspect_ratio:z.imageConfig.aspectRatio}:{},...z.imageConfig.imageSize!=null?{image_size:z.imageConfig.imageSize}:{}})}let W;if(D&&(z==null?void 0:z.agentConfig)!=null){let B=z.agentConfig;if(B.type==="deep-research")W=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")W={type:"dynamic"}}let K;if((z==null?void 0:z.environment)!=null)if(!D)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 z.environment==="string")K=z.environment;else{let B=z.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({...D?{agent:this.agent}:{model:this.modelId},input:L,system_instruction:k,tools:re,response_format:V.length>0?V:void 0,response_modalities:(z==null?void 0:z.responseModalities)!=null?z.responseModalities:void 0,previous_interaction_id:(C=z==null?void 0:z.previousInteractionId)!=null?C:void 0,service_tier:(I=z==null?void 0:z.serviceTier)!=null?I:void 0,store:(b=z==null?void 0:z.store)!=null?b:void 0,generation_config:J!=null&&Object.keys(J).length>0?J:void 0,agent_config:W,environment:K,background:(E=z==null?void 0:z.background)!=null?E:void 0}),warnings:R,isAgent:D,isBackground:(z==null?void 0:z.background)===!0,pollingTimeoutMs:(F=z==null?void 0:z.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(aS,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(_u),abortSignal:e.abortSignal,fetch:this.config.fetch}),{responseHeaders:g,value:h,rawValue:v}=f;if(u&&!Su(h.status)){let E=await uz({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}=kS({steps:(n=h.steps)!=null?n:null,generateId:(o=this.config.generateId)!=null?o:Le,interactionId:w}),x={unified:xu({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=gS(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:wu(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(aS,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(CS),abortSignal:e.abortSignal,fetch:this.config.fetch}),m=u==null?void 0:u["x-gemini-service-tier"],p=nS({warnings:o,generateId:(t=this.config.generateId)!=null?t:Le,includeRawChunks:e.includeRawChunks,serviceTier:m});return{stream:d.pipeThrough(p),request:{body:c},response:{headers:u}}}async doStreamBackground({args:e,warnings:t,url:n,mergedHeaders:o,options:i,pollingTimeoutMs:a}){var s,l;let c=await Ie({url:n,headers:o,body:e,failedResponseHandler:or,successfulResponseHandler:xe(_u),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(Su(d.status))return{stream:fz({response:d,warnings:t,generateId:(s=this.config.generateId)!=null?s:Le,includeRawChunks:i.includeRawChunks,headerServiceTier:p}),request:{body:e},response:{headers:u}};let f=gz({baseURL:this.config.baseURL,interactionId:m,headers:o,fetch:this.config.fetch,abortSignal:i.abortSignal}),g=nS({warnings:t,generateId:(l=this.config.generateId)!=null?l:Le,includeRawChunks:i.includeRawChunks,serviceTier:p});return{stream:f.pipeThrough(g),request:{body:e},response:{headers:u}}}},aS={"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 yz=["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"],vz=/^https:\/\/.*$/;function bz(e){return/(^|\/)gemini-/.test(e)&&!/(^|\/)gemini-2\.0/.test(e)}function ns(e={}){var t,n;let o=(t=pn(e.baseURL))!=null?t:"https://generativelanguage.googleapis.com/v1beta",i=(n=e.name)!=null?n:"google.generative-ai",a=()=>it({"x-goog-api-key":so({apiKey:e.apiKey,environmentVariableName:"GOOGLE_GENERATIVE_AI_API_KEY",description:"Google Generative AI"}),...e.headers},`ai-sdk/google/${Q1}`),s=(p)=>{var f;return new lS(p,{provider:i,baseURL:o,headers:a,generateId:(f=e.generateId)!=null?f:Le,supportedUrls:()=>({"*":[new RegExp(`^${o}/files/.*$`),new RegExp("^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$"),new RegExp("^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$")],...bz(p)?Object.fromEntries(yz.map((g)=>[g,[vz]])):{}}),fetch:e.fetch})},l=(p)=>new r2(p,{provider:i,baseURL:o,headers:a,fetch:e.fetch}),c=(p,f={})=>new j2(p,f,{provider:i,baseURL:o,headers:a,fetch:e.fetch}),u=(p)=>{var f;return new U2(p,{provider:i,baseURL:o,headers:a,fetch:e.fetch,generateId:(f=e.generateId)!=null?f:Le})},d=(p)=>{var f;return new hz(p,{provider:`${i}.interactions`,baseURL:o,headers:a,generateId:(f=e.generateId)!=null?f:Le,fetch:e.fetch})},m=function(p){if(new.target)throw Error("The Google Generative AI model function cannot be called with the new keyword.");return s(p)};return m.specificationVersion="v3",m.languageModel=s,m.chat=s,m.generativeAI=s,m.embedding=l,m.embeddingModel=l,m.textEmbedding=l,m.textEmbeddingModel=l,m.image=c,m.imageModel=c,m.video=u,m.videoModel=u,m.interactions=d,m.tools=M2,m}var SK=ns();function Tu(e){let t=e.model?tu(e.model):void 0,n=e.apiKey,o=e.imageApiKey??e.apiKey;return{anthropicProvider:n?su({apiKey:n}):h_,openaiProvider:t==="openai"&&n?vo({apiKey:n}):o?vo({apiKey:o}):null,googleProvider:t==="google"&&n?ns({apiKey:n}):o?ns({apiKey:o}):null}}function ES(e,t){let n=ji(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 AS(e){return e.openaiProvider!==null||e.googleProvider!==null}function PS(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 MS(e,t,n,o,i){let a=n?.signal;a?.throwIfAborted();let{provider:s,modelId:l}=ru(t),c=PS(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 eu({model:c,prompt:e,aspectRatio:u,...a?{abortSignal:a}:{}}):await eu({model:c,prompt:e,size:_z[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 _z={"1:1":"1024x1024","16:9":"1536x1024","9:16":"1024x1536","4:3":"1536x1024","3:4":"1024x1536"};function Iu(e){return{...e,temperature:e.temperature??0.7,maxTokens:e.maxTokens??1000,webSearch:e.webSearch??!0}}function Cu(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 bo(e){return{promptTokens:e.inputTokens??0,completionTokens:e.outputTokens??0,totalTokens:e.totalTokens??0}}class $i{config;logger;providers;capabilities;cachedModel=null;static createFresh(e,t){return new $i(e,t)}constructor(e,t){this.config=Iu(e),this.logger=t.child("AIService"),this.providers=Tu(this.config),this.capabilities=Oi(this.config.model)}getModel(){return this.cachedModel??=ES(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 Xc({model:this.getModel(),system:e,prompt:t,...n?{abortSignal:n}:{},...Cu(this.config,this.capabilities.provider,this.capabilities.supportsTemperature)}),i=bo(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=Cu(this.config,this.capabilities.provider,this.capabilities.supportsTemperature),a=await Jb({model:this.getModel(),system:e,prompt:t,schema:n,...o?{abortSignal:o}:{},...i,providerOptions:{...i.providerOptions,anthropic:{structuredOutputMode:"jsonTool"}}}),s=bo(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=Iu({...this.config,...e});let n=this.config.model!==t;if(e.apiKey!==void 0||e.imageApiKey!==void 0||n)this.providers=Tu(this.config),this.cachedModel=null;if(n)this.capabilities=Oi(this.config.model);this.logger.info("AI configuration updated",{model:this.config.model})}getConfig(){return{...this.config}}canGenerateImages(){return AS(this.providers)}async generateImage(e,t){return MS(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 Sz="text-embedding-3-small",wz=1536;class qi{model;dimensions;openai;logger;static createFresh(e){return new qi(e)}constructor(e){if(!e.apiKey)throw Error("API key is required for online embedding provider");this.model=e.model??Sz,this.dimensions=e.dimensions??wz,this.logger=e.logger.child("OnlineEmbeddingProvider"),this.openai=vo({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 Bb({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 Gb({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 xz=new Set(["system_search","system_get","system_list"]);function Zr(e){return xz.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 _o(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 ku(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
93
|
`);return{role:t.role,content:n}})}var jS=`## Public Visitor
|
|
94
94
|
You are answering a visitor on this brain's public website. They came to explore this brain's work.
|
|
95
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
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=Mn(jw(),1);var Tt={promptTokens:0,completionTokens:0,totalTokens:0},PU=r.record(r.string(),r.unknown());function MU(e){let t=PU.safeParse(e);return t.success?t.data:void 0}function jU(e){return e?fs(e.identity):void 0}function Ow(e,t){let n=jU(t.actor);return e.map((o)=>({...o,requester:{...n?{actorKey:n}:{},userPermissionLevel:t.userPermissionLevel}}))}function Vu(e,t){return e.pendingConfirmations.find((n)=>n.id===t)??null}function Zu(e,t){return e.pendingConfirmations.filter((n)=>n.id!==t)}function OU({context:e,event:t}){if(t.type!=="CONFIRM"&&t.type!=="CANCEL")return!1;return Zu(e,t.approvalId).length>0}function Nw(e){let t=e?.summary??"unknown action",n=MU(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 Dw=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:Ow(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:Re(e.error,"Unknown error"),response:{error:Re(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:Vu(e,t.approvalId),pendingConfirmations:Zu(e,t.approvalId)}))},CANCEL:[{guard:OU,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:Nw(Vu(e,t.approvalId)),pendingConfirmations:Zu(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:Nw(Vu(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,...Ow(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:Re(t.error,"Unknown error"),response:{error:Re(t.error,"Unknown error"),text:`Error executing ${e.activeConfirmation?.toolName??"action"}: ${Re(t.error,"Unknown error")}`,usage:Tt},activeConfirmation:null,signal:void 0}))},{target:"idle",actions:ce.assign(({context:e,event:t})=>({error:Re(t.error,"Unknown error"),response:{error:Re(t.error,"Unknown error"),text:`Error executing ${e.activeConfirmation?.toolName??"action"}: ${Re(t.error,"Unknown error")}`,usage:Tt},pendingConfirmations:[],activeConfirmation:null,signal:void 0}))}]}}}});var NU=10;function DU(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 Ku{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??NU,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)}),DU(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(zw.isSome(n))de.runSync(Vi.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 zU(e){return e?fs(e.identity):void 0}function Yu(e,t){if(t.userPermissionLevel==="admin")return!0;let n=e.requester.actorKey;if(n){if(zU(t.actor)!==n)return!1}return ys.hasPermission(t.userPermissionLevel,e.requester.userPermissionLevel)}function qU(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 Qu{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=qU(o,s.context);if(!c)return{text:"Confirmation requires caller context.",usage:Tt};if(!Yu(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 $U=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 qw(e){if(!$U.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 $w(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 LU(e){return e.mediaType.startsWith("image/")}function UU(e){return e.mediaType==="application/pdf"}function FU(e){return e.kind==="text"||e.mediaType.startsWith("text/")}function Lw(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(LU(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(UU(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(FU(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 Uw(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:Re(s)})}return i}async function Fw(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:Re(l)})}if(a.length>0)break}return a.length>0?a:t}var BU=r.record(r.string(),r.unknown()),Zw=r.looseObject({jobId:r.string()}),rd=r.looseObject({id:r.string().min(1),entityType:r.string().min(1),content:r.string().optional(),metadata:r.record(r.string(),r.unknown()).default({})}),GU=r.looseObject({entity:rd,score:r.number().finite().optional(),excerpt:r.string().optional()}),JU=r.object({results:r.array(GU)}),WU=r.object({entity:rd}),HU=r.custom((e)=>Ww.safeParse(e).success,"expected structured chat card"),VU=r.object({cards:r.array(HU)}),ZU=r.object({currentState:r.object({prompt:r.string().min(1).optional()})}),KU=r.object({entities:r.array(rd)}),YU=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 QU(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 XU(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 Kw(e){for(let t of e){let n=ZU.safeParse(t.data);if(n.success&&n.data.currentState.prompt)return n.data.currentState.prompt}return}function nd(e){let t=Zw.safeParse(e),n=YU.safeParse(e);if(!n.success)return;let{attachmentId:o,attachment:i}=n.data,a=i.source,s=QU(i.mediaType),l=XU(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 Bw=500,eF=3;function td(e){let t=e.trim();if(t.length<=Bw)return t;return`${t.slice(0,Bw-1).trimEnd()}\u2026`}function Xu(e,t){let n=e?.[t];return typeof n==="string"&&n.length>0?n:void 0}function Yw(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:td(t.content),...gt({title:t.title,url:Xu(t.provenance,"url"),entityType:Xu(t.provenance,"entityType"),entityId:Xu(t.provenance,"entityId"),provenance:t.provenance})}))}}function Ln(e,t){let n=e[t];return typeof n==="string"&&n.trim().length>0?n.trim():void 0}function Qw(e){return Ln(e.metadata,"title")??Ln(e.metadata,"name")??Ln(e.metadata,"slug")??e.id}function tF(e){return Ln(e.metadata,"url")??Ln(e.metadata,"permalink")??Ln(e.metadata,"canonicalUrl")}function Gw(e){let{entity:t,toolName:n,score:o}=e,i=e.excerpt!==void 0?td(e.excerpt):t.content!==void 0?td(t.content):void 0,a=tF(t);return{id:`${t.entityType}:${t.id}`,title:Qw(t),source:t.entityType,entityType:t.entityType,entityId:t.id,...gt({url:a,excerpt:i}),provenance:{toolName:n,...gt({score:o})}}}function rF(e){if(e.toolName==="system_search"){let t=JU.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:Gw({toolName:e.toolName,entity:n.entity,excerpt:n.excerpt,score:n.score})}))}if(e.toolName==="system_get"){let t=WU.safeParse(e.data);if(!t.success)return[];return[{citation:Gw({toolName:e.toolName,entity:t.data.entity})}]}return[]}function Jw(e){return` ${e.toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").trim()} `}function nF(e,t){let n=t===void 0?"":Jw(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=Jw(l);return c.trim().length>=4&&n.includes(c)});return[...i.length>0?i:o.filter((s)=>(s.rank??0)<eF),...e.filter((s)=>s.rank===void 0)].map((s)=>s.citation)}function Xw(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 ex(e,t){let n=Xw(t);if(!n)return e;return[...e.filter((o)=>o.kind!=="sources"||o.id!==n.id),n]}function od(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=BU.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=Vw.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=Hw.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=Zw.safeParse(h.data.data);if(y.success)w.jobId=y.data.jobId;let x=VU.safeParse(h.data.data);if(x.success)o.push(...x.data.cards);let _=nd(h.data.data);if(_)o.push(_);i.push(...rF({toolName:p.toolName,data:h.data.data}))}n.push(w)}if(d)break}let l=Xw(nF(i,t));if(l)o.push(l);return{toolResults:n,pendingConfirmations:a,cards:o,totalToolCalls:s}}var oF=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 ed(e){return e===void 0||e===""?void 0:e}var iF=r.object({entityType:r.string().optional(),id:r.string().optional(),title:r.string().optional()}),tx=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()}),id=r.object({source:r.object({kind:r.literal("url"),url:r.string().min(1)})}),aF=r.object({agent:r.string().min(1)}),sF=r.object({agentContactCandidate:id});function rx(e){let t=new Set,n=[];for(let o of e){if(o.toolName!=="agent_call")continue;let i=sF.safeParse(o.data);if(i.success){let{url:l}=i.data.agentContactCandidate.source;if(t.has(l))continue;t.add(l),n.push(i.data.agentContactCandidate);continue}if(o.error?.code!=="agent_not_saved"&&o.error?.code!=="agent_card_unavailable")continue;let a=aF.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 nx(e){if(e.length===0)return"";return`
|
|
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=Mn(jw(),1);var Tt={promptTokens:0,completionTokens:0,totalTokens:0},PU=r.record(r.string(),r.unknown());function MU(e){let t=PU.safeParse(e);return t.success?t.data:void 0}function jU(e){return e?fs(e.identity):void 0}function Ow(e,t){let n=jU(t.actor);return e.map((o)=>({...o,requester:{...n?{actorKey:n}:{},userPermissionLevel:t.userPermissionLevel}}))}function Vu(e,t){return e.pendingConfirmations.find((n)=>n.id===t)??null}function Zu(e,t){return e.pendingConfirmations.filter((n)=>n.id!==t)}function OU({context:e,event:t}){if(t.type!=="CONFIRM"&&t.type!=="CANCEL")return!1;return Zu(e,t.approvalId).length>0}function Nw(e){let t=e?.summary??"unknown action",n=MU(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 Dw=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:Ow(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:Re(e.error,"Unknown error"),response:{error:Re(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:Vu(e,t.approvalId),pendingConfirmations:Zu(e,t.approvalId)}))},CANCEL:[{guard:OU,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:Nw(Vu(e,t.approvalId)),pendingConfirmations:Zu(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:Nw(Vu(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,...Ow(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:Re(t.error,"Unknown error"),response:{error:Re(t.error,"Unknown error"),text:`Error executing ${e.activeConfirmation?.toolName??"action"}: ${Re(t.error,"Unknown error")}`,usage:Tt},activeConfirmation:null,signal:void 0}))},{target:"idle",actions:ce.assign(({context:e,event:t})=>({error:Re(t.error,"Unknown error"),response:{error:Re(t.error,"Unknown error"),text:`Error executing ${e.activeConfirmation?.toolName??"action"}: ${Re(t.error,"Unknown error")}`,usage:Tt},pendingConfirmations:[],activeConfirmation:null,signal:void 0}))}]}}}});var NU=10;function DU(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 Ku{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??NU,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)}),DU(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(zw.isSome(n))de.runSync(Vi.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 zU(e){return e?fs(e.identity):void 0}function Yu(e,t){if(t.userPermissionLevel==="admin")return!0;let n=e.requester.actorKey;if(n){if(zU(t.actor)!==n)return!1}return ys.hasPermission(t.userPermissionLevel,e.requester.userPermissionLevel)}function $U(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 Qu{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=$U(o,s.context);if(!c)return{text:"Confirmation requires caller context.",usage:Tt};if(!Yu(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 qU=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 $w(e){if(!qU.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 qw(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 LU(e){return e.mediaType.startsWith("image/")}function UU(e){return e.mediaType==="application/pdf"}function FU(e){return e.kind==="text"||e.mediaType.startsWith("text/")}function Lw(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(LU(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(UU(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(FU(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 Uw(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:Re(s)})}return i}async function Fw(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:Re(l)})}if(a.length>0)break}return a.length>0?a:t}var BU=r.record(r.string(),r.unknown()),Zw=r.looseObject({jobId:r.string()}),rd=r.looseObject({id:r.string().min(1),entityType:r.string().min(1),content:r.string().optional(),metadata:r.record(r.string(),r.unknown()).default({})}),GU=r.looseObject({entity:rd,score:r.number().finite().optional(),excerpt:r.string().optional()}),JU=r.object({results:r.array(GU)}),WU=r.object({entity:rd}),HU=r.custom((e)=>Ww.safeParse(e).success,"expected structured chat card"),VU=r.object({cards:r.array(HU)}),ZU=r.object({currentState:r.object({prompt:r.string().min(1).optional()})}),KU=r.object({entities:r.array(rd)}),YU=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 QU(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 XU(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 Kw(e){for(let t of e){let n=ZU.safeParse(t.data);if(n.success&&n.data.currentState.prompt)return n.data.currentState.prompt}return}function nd(e){let t=Zw.safeParse(e),n=YU.safeParse(e);if(!n.success)return;let{attachmentId:o,attachment:i}=n.data,a=i.source,s=QU(i.mediaType),l=XU(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 Bw=500,eF=3;function td(e){let t=e.trim();if(t.length<=Bw)return t;return`${t.slice(0,Bw-1).trimEnd()}\u2026`}function Xu(e,t){let n=e?.[t];return typeof n==="string"&&n.length>0?n:void 0}function Yw(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:td(t.content),...gt({title:t.title,url:Xu(t.provenance,"url"),entityType:Xu(t.provenance,"entityType"),entityId:Xu(t.provenance,"entityId"),provenance:t.provenance})}))}}function Ln(e,t){let n=e[t];return typeof n==="string"&&n.trim().length>0?n.trim():void 0}function Qw(e){return Ln(e.metadata,"title")??Ln(e.metadata,"name")??Ln(e.metadata,"slug")??e.id}function tF(e){return Ln(e.metadata,"url")??Ln(e.metadata,"permalink")??Ln(e.metadata,"canonicalUrl")}function Gw(e){let{entity:t,toolName:n,score:o}=e,i=e.excerpt!==void 0?td(e.excerpt):t.content!==void 0?td(t.content):void 0,a=tF(t);return{id:`${t.entityType}:${t.id}`,title:Qw(t),source:t.entityType,entityType:t.entityType,entityId:t.id,...gt({url:a,excerpt:i}),provenance:{toolName:n,...gt({score:o})}}}function rF(e){if(e.toolName==="system_search"){let t=JU.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:Gw({toolName:e.toolName,entity:n.entity,excerpt:n.excerpt,score:n.score})}))}if(e.toolName==="system_get"){let t=WU.safeParse(e.data);if(!t.success)return[];return[{citation:Gw({toolName:e.toolName,entity:t.data.entity})}]}return[]}function Jw(e){return` ${e.toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").trim()} `}function nF(e,t){let n=t===void 0?"":Jw(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=Jw(l);return c.trim().length>=4&&n.includes(c)});return[...i.length>0?i:o.filter((s)=>(s.rank??0)<eF),...e.filter((s)=>s.rank===void 0)].map((s)=>s.citation)}function Xw(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 ex(e,t){let n=Xw(t);if(!n)return e;return[...e.filter((o)=>o.kind!=="sources"||o.id!==n.id),n]}function od(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=BU.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=Vw.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=Hw.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=Zw.safeParse(h.data.data);if(y.success)w.jobId=y.data.jobId;let x=VU.safeParse(h.data.data);if(x.success)o.push(...x.data.cards);let _=nd(h.data.data);if(_)o.push(_);i.push(...rF({toolName:p.toolName,data:h.data.data}))}n.push(w)}if(d)break}let l=Xw(nF(i,t));if(l)o.push(l);return{toolResults:n,pendingConfirmations:a,cards:o,totalToolCalls:s}}var oF=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 ed(e){return e===void 0||e===""?void 0:e}var iF=r.object({entityType:r.string().optional(),id:r.string().optional(),title:r.string().optional()}),tx=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()}),id=r.object({source:r.object({kind:r.literal("url"),url:r.string().min(1)})}),aF=r.object({agent:r.string().min(1)}),sF=r.object({agentContactCandidate:id});function rx(e){let t=new Set,n=[];for(let o of e){if(o.toolName!=="agent_call")continue;let i=sF.safeParse(o.data);if(i.success){let{url:l}=i.data.agentContactCandidate.source;if(t.has(l))continue;t.add(l),n.push(i.data.agentContactCandidate);continue}if(o.error?.code!=="agent_not_saved"&&o.error?.code!=="agent_card_unavailable")continue;let a=aF.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 nx(e){if(e.length===0)return"";return`
|
|
98
98
|
|
|
99
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
100
|
${e.map((n)=>`- agent_connect candidate args: { source: { kind: "url", url: "${n.source.url}" } }`).join(`
|
|
@@ -111,9 +111,9 @@ ${e.content}`}function TF(e,t,n){let o=e.map(ax).filter(ld),i=cd([...t,...o]).ma
|
|
|
111
111
|
|
|
112
112
|
`)].join(`
|
|
113
113
|
`)}function RF(e,t){let n=e.title??e.id,o=EF(e.provenance);return[`${t+1}. ${n} [${e.source}]`,e.content.trim(),...o?[`Provenance: ${o}`]:[]].join(`
|
|
114
|
-
`)}function EF(e){if(!e)return;let t=Object.entries(e).filter(([,n])=>n!==void 0&&n!==null&&n!=="").map(([n,o])=>`${n}=${AF(o)}`);return t.length>0?t.join(", "):void 0}function AF(e){if(typeof e==="string")return e;if(typeof e==="number"||typeof e==="boolean")return String(e);return JSON.stringify(e)}var PF="brain:assistant",MF="Assistant";function dd(e){if(!e)return;let t=Qr(e);return t?`brain:${t}`:void 0}function pd(e){let t=e.character.name.trim()||MF;return{identity:{kind:"agent",agentId:e.agentId??PF},interfaceType:"agent",role:"assistant",displayName:t,isBot:!0}}function cx(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 jF=r.record(r.string(),r.unknown()),OF=r.looseObject({success:r.literal(!1)});function gd(e){let t=jF.safeParse(e);return t.success?t.data:void 0}function md(e,t){let o=gd(e)?.[t];return typeof o==="string"?o:void 0}function NF(e){return OF.safeParse(e).success}function DF(e){return e.trim().replace(/[?\uFF1F]+$/u,"")}var zF=new Set(["confirmed","confirmationToken","contentHash"]);function
|
|
114
|
+
`)}function EF(e){if(!e)return;let t=Object.entries(e).filter(([,n])=>n!==void 0&&n!==null&&n!=="").map(([n,o])=>`${n}=${AF(o)}`);return t.length>0?t.join(", "):void 0}function AF(e){if(typeof e==="string")return e;if(typeof e==="number"||typeof e==="boolean")return String(e);return JSON.stringify(e)}var PF="brain:assistant",MF="Assistant";function dd(e){if(!e)return;let t=Qr(e);return t?`brain:${t}`:void 0}function pd(e){let t=e.character.name.trim()||MF;return{identity:{kind:"agent",agentId:e.agentId??PF},interfaceType:"agent",role:"assistant",displayName:t,isBot:!0}}function cx(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 jF=r.record(r.string(),r.unknown()),OF=r.looseObject({success:r.literal(!1)});function gd(e){let t=jF.safeParse(e);return t.success?t.data:void 0}function md(e,t){let o=gd(e)?.[t];return typeof o==="string"?o:void 0}function NF(e){return OF.safeParse(e).success}function DF(e){return e.trim().replace(/[?\uFF1F]+$/u,"")}var zF=new Set(["confirmed","confirmationToken","contentHash"]);function $F(e){let t=gd(e);if(!t)return;return Object.fromEntries(Object.entries(t).filter(([n])=>!zF.has(n)))}function ux(e,t){let n=NF(t),o=n?"Failed":"Completed",i=n?md(t,"error")??md(t,"message"):void 0,a=DF(n?e.summary:e.completionSummary??e.summary),s=i?`${o}: ${a}
|
|
115
115
|
|
|
116
|
-
${i}`:`${o}: ${a}`,l=gd(e.args),c={toolName:e.toolName,data:t,...l?{args:l}:{}},u
|
|
116
|
+
${i}`:`${o}: ${a}`,l=gd(e.args),c={toolName:e.toolName,data:t,...l?{args:l}:{}},u=$F(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:md(t,"error")??"Action failed"}:{}},m=vs.safeParse(t),p=m.success?nd(m.data.data):void 0,f=[d,...p?[p]:[]],g=m.success?Zi([{...c,data:m.data.data}]):[];return{resultText:s,toolResult:c,cards:f,entityMemoryRefs:g}}function qF(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 dx(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)=>qF(d))}:{},...a.length>0?{cards:a}:{},...s.length>0?{entityMemoryRefs:s}:{},...l.length>0?{agentContactCandidates:l}:{}}}function px(e){return Object.keys(e).length>0?{metadata:e}:{}}class fd{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=_o(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=qw(l),u=Lw(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=ad(u,l).map((w)=>e.guest?{...w,metadata:null}:w),m=sx({message:o,currentAttachments:c,historyMessages:d}),p=await Uw({refs:m.refs,resolver:this.deps.uploadAttachmentResolver,logger:this.deps.logger}),f=m.message,g=await Fw({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=lx(f,g,{uploadRefs:p,...m.priorResponseRef?{priorResponseRef:m.priorResponseRef}:{}});return{effectiveMessage:f,effectiveAttachments:g,uploadRefs:p,hasPriorResponseCandidate:m.priorResponseRef!==void 0,contextItems:h,messages:sd(d,v),agentContextInstructions:ud(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 cx({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 ex(e,await n({answer:t}))}catch(o){return this.deps.logger.warn("Guest answer sources unavailable",{error:Re(o)}),e}}async recordResponse(e,t,n){let{conversationId:o,channelId:i,channelName:a,userPermissionLevel:s}=e.input,{guest:l}=e,c=od(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=Yw(t.contextItems),g=f?[...p,f]:p,h=d.length>0?"Confirmation required.":n.text.trim().length>0?n.text:Kw(u)??n.text,v=l||d.length>0?[]:Zi(u),w=l||d.length>0?[]:rx(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:bo(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:Re(b)}}}t?.throwIfAborted();let g=ux(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=$w(g.toolResult.data),S=v?.text.trim()?`${g.resultText}
|
|
117
117
|
|
|
118
118
|
${v.text}`:w?`${g.resultText}
|
|
119
119
|
|
|
@@ -165,18 +165,18 @@ ${n.join(`
|
|
|
165
165
|
|
|
166
166
|
${a}`:"")}function bd(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:Re(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 _d(e,t="brain-agent"){return{emit:async(n,o)=>{await e.send({type:n,payload:o,sender:t,broadcast:!0}).catch(()=>{return})}}}var Sd={success:!1,error:"Public retrieval unavailable"},GF=500;function JF(e){if(!_s(e))return Sd;if(e.success===!0)return e;let t=e.error;return{success:!1,error:typeof t==="string"&&t.trim()?t.slice(0,GF):"Nothing public matches that request."}}var WF=new Set(["confirmed","confirmationToken","contentHash"]),HF=new Set(["content","prompt","url","from","upload","transform","sourceAttachment"]),VF=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 ZF(e){return typeof e==="object"&&e!==null&&"safeParse"in e&&typeof e.safeParse==="function"}function KF(e,t={}){let n={};for(let[o,i]of Object.entries(e)){if(WF.has(o))continue;if(t.toolName==="system_create"&&HF.has(o))continue;if(ZF(i))n[o]=i}return n}function YF(e){let t=VF.safeParse(e);if(!t.success)return{type:"json",value:Sx(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:Sx({...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 QF(e){if(!_s(e))return e;if(e.success!==!0)return e;return{...e,cached:!0}}function Sx(e){if(e===void 0)return null;return wx.parse(JSON.parse(JSON.stringify(e)))}function wd(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=bd(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 QF(a.get(p));let f;try{f=o?JF(await s.handler(c,m)):await s.handler(c,m)}catch(g){if(!o)throw g;f=Sd}if(o&&!_s(f))f=Sd;if(!o)a.set(p,f);return f},t,o?void 0:n);i[s.name]=Il({description:s.description,inputSchema:r.object(KF(s.inputSchema,{toolName:s.name,...t.enableCreateUpload!==void 0&&{enableCreateUpload:t.enableCreateUpload},...t.enableCreateTransform!==void 0&&{enableCreateTransform:t.enableCreateTransform}})),execute:l,toModelOutput:({output:c})=>YF(c)})}return i}function XF(e,t){return t.interfaceType===mt?e.filter(Zr):e}function eB(e){return typeof e==="object"&&e!==null&&"action"in e&&e.action==="start"}function tB(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"&&eB(i.input))??!1;return n||o}function xd(e){let{model:t,modelId:n,webSearch:o,temperature:i,maxTokens:a,reasoningEffort:s,messageBus:l}=e,c=Oi(n),u=_d(l);return function(p){let f=wd(p.tools,{conversationId:"",interfaceType:"agent"},u),g=new Fb({model:t,callOptionsSchema:bx,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?[]:XF(p.getToolsForPermission(h.userPermissionLevel),h),y=S.map((_)=>_.name),x=wd(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:ku(v.messages),allowSystemInMessages:!1,providerOptions:{}},instructions:_x(p.identity,h.userPermissionLevel,p.pluginInstructions,p.profile,p.agentInstructions,h.agentContextInstructions,h.isAnchor)+(w?`
|
|
167
167
|
|
|
168
|
-
${jS}`:""),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:[tB,Pi(p.stepLimit??10)]});return{generate:async(h)=>{Kr(h.options);let v=_o(h.options);if(!v)return g.generate(h);let w=ku(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:yx(S.steps,e.guestPricing)})}}}}async function Ss(e,t,n){let o=await e.send({type:xx,sender:t,payload:{actor:n}});if("noop"in o)return null;if(!o.success)throw Error("Principal resolution unavailable");return Tx.parse(o.data).principal}function Cx(e,t){return new Ix(e,(n)=>Ss(t,"shell:content-service",n))}var Td=rt.GenericTag("@brains/conversation-service/ConversationService");function nB(e){if(e.service){let n=e.service;return{service:n,close:()=>n.close()}}let t=kx.createFreshFromConfig(e.logger,e.messageBus,e.dbConfig,e.config);try{return{service:t,close:()=>t.close()}}catch(n){throw t.close(),n}}function Rx(e){return yn(Td,()=>nB(e))}var Id=rt.GenericTag("@brains/entity-service/EntityService");function oB(e){return"close"in e&&typeof e.close==="function"}function Ax(e){return yn(Id,()=>{let t=e.service??Ex.createFresh(e);return{service:t,close:()=>{if(oB(t))t.close()}}})}var Yi=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()}),Cd=r.strictObject({alerts:r.array(Yi).optional()});var ws="shell:recurring-check",Rd=86400000,iB=7*Rd,aB=3*Rd,sB=r.strictObject({checkId:r.string().min(1)}),lB=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:Yi,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 Mx;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:lB});let t={validateAndParse:(n)=>{let o=sB.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){Px(e,"plugin ID"),Px(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=Cd.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=kd(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=kd(this.brainId,e.id,e.cadence),o=jx(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=Yi.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:${Qi(e)}`}alertKeyPrefix(e){return`alert:${Qi(e)}:`}alertKey(e,t){return`${this.alertKeyPrefix(e)}${Qi(t)}`}}function kd(e,t,n){let o=n==="daily"?Rd:iB,i=o/60000,a=Qi(`${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:aB}}function jx(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 Px(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 Ue=Ox("runtime_state_records",{namespace:Ts("namespace").notNull(),key:Ts("key").notNull(),value:Ts("value",{mode:"json"}).notNull(),createdAt:Ed("created_at").notNull(),updatedAt:Ed("updated_at").notNull()},(e)=>({pk:Dx({columns:[e.namespace,e.key]}),namespaceUpdatedAtIdx:Nx("idx_runtime_state_namespace_updated_at").on(e.namespace,e.updatedAt)}));function qx(e){return zx({url:e.url,schema:{runtimeStateRecords:Ue},authToken:e.authToken,authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN"})}var cB=/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,127}$/,Bx=512;class Pd{db;namespace;schema;now;constructor(e,t,n,o=()=>new Date){uB(t),this.db=e,this.namespace=t,this.schema=n,this.now=o}async get(e){let t=Un(e),o=(await this.db.select().from(Ue).where(Oo(ar(Ue.namespace,this.namespace),ar(Ue.key,t))).limit(1))[0];if(!o)return null;return this.schema.parse(o.value)}async has(e){let t=Un(e);return(await this.db.select({key:Ue.key}).from(Ue).where(Oo(ar(Ue.namespace,this.namespace),ar(Ue.key,t))).limit(1)).length>0}async set(e,t){let n=Un(e),o=this.schema.parse(t),i=this.now().getTime();await this.db.insert(Ue).values({namespace:this.namespace,key:n,value:o,createdAt:i,updatedAt:i}).onConflictDoUpdate({target:[Ue.namespace,Ue.key],set:{value:o,updatedAt:i}})}async setIfNotExists(e,t){let n=Un(e),o=this.schema.parse(t),i=this.now().getTime(),a=await this.db.insert(Ue).values({namespace:this.namespace,key:n,value:o,createdAt:i,updatedAt:i}).onConflictDoNothing({target:[Ue.namespace,Ue.key]});return Number(a.rowsAffected)>0}async compareAndSet(e,t,n){let o=Un(e),i=this.schema.parse(t),a=this.schema.parse(n),s=await this.db.update(Ue).set({value:a,updatedAt:this.now().getTime()}).where(Oo(ar(Ue.namespace,this.namespace),ar(Ue.key,o),ar(Ue.value,i)));return Number(s.rowsAffected)===1}async delete(e){let t=Un(e),n=await this.db.delete(Ue).where(Oo(ar(Ue.namespace,this.namespace),ar(Ue.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(Ue).where(ar(Ue.namespace,this.namespace));return Number(o.rowsAffected)}$x(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)$x(t);if(n!==void 0)Un(n);if(o!==void 0)r.number().int().min(1).max(1000).parse(o);let i=this.db.select({...Lx(Ue),key:Ad`CAST(${Ue.key} AS BLOB)`.mapWith((a)=>new TextDecoder("utf-8",{fatal:!0}).decode(a))}).from(Ue).where(Oo(ar(Ue.namespace,this.namespace),t!==void 0?Ad`substr(CAST(${Ue.key} AS BLOB), 1, length(CAST(${t} AS BLOB))) = CAST(${t} AS BLOB)`:void 0,n!==void 0?Ux(Ue.key,n):void 0)).orderBy(Fx(Ue.key)).$dynamic();return o===void 0?i:i.limit(o)}}function uB(e){if(!cB.test(e))throw Error(`Invalid runtime state namespace: ${e}. Use 1-128 alphanumeric, _, ., :, or - characters.`)}function Un(e){if(e.length===0||e.length>Bx)throw Error("Runtime state keys must be 1-512 characters long");return e}function $x(e){if(e.length>Bx)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}=qx(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 Gx(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 Pd(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 Md=rt.GenericTag("@brains/runtime-state/RuntimeStateService");function Jx(e){return yn(Md,()=>{let t=e.service??Is.createFresh(e.config,e.logger);return{service:t,close:()=>t.close()}})}async function jd(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=Xi(n),t.warn(`Daemon ${e.name} failed to start: ${Re(n)}`),n}}async function Od(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=Xi(n),t.error(`Failed to stop daemon: ${e.name}`,n),n}}async function Wx(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:Re(t),lastCheck:new Date};return e.health=n,n}}function Hx(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 Nd(e){let n=(await Mr(de.all(e.map((o)=>de.either(de.tryPromise({try:o,catch:(i)=>i}))),{concurrency:"unbounded"}))).find(Vx.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 jd(t,this.logger);return}let n=de.runSync(Xe.make()),o=de.acquireRelease(de.promise(()=>jd(t,this.logger)),()=>de.promise(()=>Od(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 Od(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 Wx(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(Hx)}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??=Xi(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 dB=r.object({projectionId:r.string().min(1),reason:r.string().min(1),openedAt:r.number().int().nonnegative(),expiresAt:r.number().int().nonnegative()}),pB=8,mB=32,gB=128,fB=5,hB=600000,yB=600000,vB=1000,bB="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??pB,maxJobsPerRoot:t.maxJobsPerRoot??mB,maxMutationsPerRoot:t.maxMutationsPerRoot??gB,repeatedTargetLimit:t.repeatedTargetLimit??fB,retentionMs:t.retentionMs??hB,circuitOpenMs:t.circuitOpenMs??yB,maxTrackedRoots:t.maxTrackedRoots??vB,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:bB,schema:dB})}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 _B={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 _B[e??"combined"]}var SB=20,wB=0.5,xB=0.06,TB=5;function Dd(e,t){let n=e[t];return typeof n==="string"&&n.trim().length>0?n.trim():void 0}function IB({entity:e},t){let n=Dd(e.metadata,"title")??Dd(e.metadata,"name"),o=Dd(e.metadata,"slug")??e.id,i=t.siteBaseUrl?new URL(t.urlFor(e.entityType,o),t.siteBaseUrl).href:void 0;return{id:`${e.entityType}:${e.id}`,...n?{title:n}:{},source:e.entityType,entityType:e.entityType,entityId:e.id,...i?{url:i}:{}}}function Zx(e){return async({answer:t})=>{let o=(await e.entityService.search({query:t,options:{limit:SB,minScore:wB,visibilityScope:Ht("public")}})).filter((a)=>e.hasRoute(a.entity.entityType)),i=Math.max(...o.map((a)=>a.score));return o.filter((a)=>a.score>=i-xB).slice(0,TB).map((a)=>IB(a,e))}}function zd(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 CB(e,t,n){let o=kB(e.kind);if(!o)return null;try{let i=t.scoped({namespace:o,refKind:e.kind,routePath:""});return RB(await i.read(e.id),e)}catch(i){return n.debug("Skipped unavailable prior runtime upload",{uploadKind:e.kind,uploadId:e.id,error:Re(i)}),null}}function kB(e){return e==="upload"?"upload":null}function RB(e,t){let{record:n,content:o}=e;if(EB(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 EB(e){let t=e.toLowerCase();return t.startsWith("text/")||t==="application/json"}function tT(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=Qx.createFresh(n,o,t.identity);if(!d)u.push(...zd(i,Rt.BRAIN_CHARACTER,Rt.BRAIN_CHARACTER,()=>m.refreshCache(),o));let p=Xx.createFresh(n,o,t.profile),f=eT.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=xd({guestPricing:a.getConfig().model==="gpt-5.6-luna"?vd: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=dd(t.name),v=Ki.createFresh(s,l,m,p,o,{agentFactory:g,canonicalIdentityResolver:f,...t.embedding.enabled?{indexReadiness:n,guestAnswerSources:Zx({entityService:n,hasRoute:(w)=>Ko.getInstance().hasRoute(w),urlFor:(w,S)=>Ko.getInstance().generateUrl(w,S),siteBaseUrl:t.siteBaseUrl})}:{},uploadAttachmentResolver:(w)=>CB(w,c,o),agentContextProvider:async(w)=>(await i.collect({type:Kx,sender:"shell:agent-service",payload:w})).flatMap((y)=>{if("noop"in y||!y.success)return[];return Yx(y.data)}),...h?{assistantAgentId:h}:{},...t.agentInstructions&&{agentInstructions:t.agentInstructions}});if(!d){u.push(...zd(i,Rt.ANCHOR_PROFILE,Rt.ANCHOR_PROFILE,()=>p.refreshCache(),o));for(let w of[Rt.BRAIN_CHARACTER,Rt.ANCHOR_PROFILE])u.push(...zd(i,w,w,async()=>v.invalidateAgent(),o))}return{identityService:m,profileService:p,canonicalIdentityService:f,agentService:v}}var ea=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 aT(e){return yn(ea,()=>{let t=e.service??rT.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 sT(e){let t=!1,n=de.gen(function*(){let o=yield*ea,i=e.batchJobManager??oT.createFresh(o,e.logger),a=e.jobProgressMonitor??iT.createFresh(o,e.messageBus,i,e.logger,e.progressMonitorMode),s=e.jobQueueWorker??nT.createFresh(o,a,e.logger,{pollInterval:100,concurrency:e.workerConcurrency,autoStart:!1,...e.onWorkerUnhealthy&&{onUnhealthy:e.onWorkerUnhealthy}},{...e.operationContext&&{operationContext:e.operationContext}});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:AB(o))),abandon:()=>{t=!0}}}function AB(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 PB(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 lT(e){let t=e.operationContext??Os.createFresh(),n=de.runSync(Xe.make()),o,i;try{let a=de.runSync(Xr.buildWithScope(aT({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,ea),l=de.runSync(Xe.make());o=l;let c=sT({messageBus:e.messageBus,logger:e.logger,operationContext:t,onWorkerUnhealthy:PB(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(ea,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 uT(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=cT.safeParse(n.data);if(!o.success||o.data.status!=="sent")throw Error("Recurring alert delivery failed");return!0}}}function pT(e){return{sourceId:"recurring-checks",displayName:"Recurring checks",list:async()=>(await e.listOpenAlerts()).map((t)=>({id:t.id,title:dT(t.title,160),summary:dT(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 dT(e,t){return e.length<=t?e:e.slice(0,t)}function mT(e,t){if(t)return t;let n={debug:qt.DEBUG,info:qt.INFO,warn:qt.WARN,error:qt.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 gT(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 No(e){return{url:e.url,...e.authToken?{authToken:e.authToken}:{}}}function OT(e){let{config:t,dependencies:n,initializerLogger:o,lifecycle:i,processRole:a}=e;o.debug("Initializing Shell services");let s=Rs(a),l=mT(t,n?.logger),c=n?.operationContext??Os.createFresh(),u=[],d=n?.embeddingService??$i.createFresh({apiKey:t.ai.apiKey,logger:l}),m=n?.aiService??qi.createFresh(gT(t),l),p=n?.entityRegistry??hT.createFresh(l),f=n?.messageBus??PT.createFresh(l,c),g=n?.templateRegistry??vT.createFresh(l),h=n?.dataSourceRegistry??yT.createFresh(l),v=n?.renderService??bT.createFresh(g),w=n?.daemonRegistry??Cs.createFresh(l),S=n?.pluginManager??jT.createFresh(l,w),y=n?.permissionService??new ys(t.permissions,{spaces:t.spaces,entityActionFloor:(H)=>p.getEntityTypeConfig(H).actionPolicy}),x=n?.profileKindRegistry??new MT(t.profileKind),_=n?.channelRegistry??new wT,C=n?.inboxRegistry??new xT,I=n?.inboxFollowUpRegistry??new TT(l),b=n?.operationalHealthRegistry??new AT,E=n?.accountSettingsRegistry??new ST,F=n?.attachmentRegistry??IT.createFresh(),R=n?.runtimeUploadRegistry??CT.createFresh({dataDir:t.dataDir,logger:l}),z=i.buildLayer(Jx({config:No(t.runtimeStateDatabase),logger:l,...n?.runtimeStateService&&{service:n.runtimeStateService}})),D=rt.get(z,Md),N=n?.projectionRuntimeSupervisor??ks.createFresh(c,{runtimeState:D}),re=n?.mcpService??ET.createFresh(f,l),Y=lT({dependencies:n,jobQueueConfig:No(t.jobQueueDatabase),workerConcurrency:t.jobQueue.workerConcurrency,messageBus:f,operationContext:c,projectionAdmission:N,handlerRegistrationMode:s.handlerRegistrationMode,progressMonitorMode:s.progressMonitorMode,logger:l}),{batchJobManager:V,jobProgressMonitor:L,jobQueueService:pe,jobQueueWorker:X}=Y;i.addSyncFinalizer(()=>Y.closeDatabase()),i.addSyncFinalizer(()=>Y.rollbackRuntime());let k=n?.recurringCheckService??new xs({brainId:t.siteBaseUrl??t.dataDir,scheduler:new kT,runtimeState:D,clock:fT.make(),jobQueue:pe,logger:l,delivery:uT(f)});i.addSyncFinalizer(()=>k.abandon()),C.registerSource("shell.recurring-checks",pT(k)),i.addSyncFinalizer(()=>C.unregisterPlugin("shell.recurring-checks"));let Q=(H,P)=>{if(!s.serves)return;w.register(H,P,"shell"),i.addSyncFinalizer(()=>w.abandon(H))};Q("shell:recurring-checks",{start:()=>k.start(),stop:()=>k.stop()});let J=i.buildLayer(Ax({embeddingService:d,embeddingsEnabled:t.embedding.enabled,entityRegistry:p,logger:l,jobQueueService:pe,messageBus:f,mutationAdmission:N,...n?.projectionRuntime?.now&&{projectionNow:n.projectionRuntime.now},dbConfig:No(t.database),embeddingDbConfig:No(t.embeddingDatabase),...n?.entityService&&{service:n.entityService}})),W=rt.get(J,Id),K=i.buildLayer(Rx({dbConfig:No(t.conversationDatabase),logger:l,messageBus:f,...n?.conversationService&&{service:n.conversationService}})),q=rt.get(K,Td);Q("shell:guest-retention",RT({intervalMs:60000,logger:l,run:async()=>{await q.deleteExpiredGuestConversations(100)}})),i.addSyncFinalizer(()=>{for(let H of u.splice(0))try{H()}catch(P){l.warn("Failed to dispose shell subscription",P)}});let B=n?.contentService??new _T({logger:l,entityService:W,aiService:m,templateRegistry:g,dataSourceRegistry:h,generationAuthorizer:Cx(y,f)}),{identityService:G,profileService:Z,canonicalIdentityService:A,agentService:O}=tT({config:t,entityService:W,embeddingService:d,entityRegistry:p,logger:l,messageBus:f,aiService:m,mcpService:re,conversationService:q,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:W,aiService:m,conversationService:q,contentService:B,jobQueueService:pe,jobQueueWorker:X,batchJobManager:V,jobProgressMonitor:L,jobServicesLifecycle:Y,permissionService:y,identityService:G,profileService:Z,canonicalIdentityService:A,profileKindRegistry:x,channelRegistry:_,inboxRegistry:C,inboxFollowUpRegistry:I,operationalHealthRegistry:b,accountSettingsRegistry:E,agentService:O,attachmentRegistry:F,runtimeUploadRegistry:R,runtimeStateService:D,recurringCheckService:k}}function $T(e,t){e.register($d.name,$d),t.debug("Shell system templates registered")}function LT(e,t){e.register(Zo.BASE_ENTITY_DISPLAY,{name:"base-entity-display",description:"Display template for base entities",schema:Ld,formatter:new NT,requiredPermission:"public"}),t.debug("Base entity display template registered")}function UT(e,t){e.registerEntityType(Rt.NOTE,Ld,new DT,{projectionSourceRole:"primary"}),t.debug("Fallback base entity adapter registered")}function FT(e,t){let n=new zT;e.registerEntityType(Rt.BRAIN_CHARACTER,n.schema,n,{projectionSource:!1,projectionSourceRole:"excluded"}),t.debug("Brain character entity support registered")}function BT(e,t){let n=new qT;e.registerEntityType(Rt.ANCHOR_PROFILE,n.schema,n,{projectionSourceRole:"canonical"}),t.debug("Anchor profile entity support registered")}async function GT(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){$T(e,this.logger)}registerBaseEntityDisplayTemplate(e){LT(e,this.logger)}registerFallbackBaseEntity(e){UT(e,this.logger)}registerBrainCharacterSupport(e){FT(e,this.logger)}registerAnchorProfileSupport(e){BT(e,this.logger)}async initializePlugins(e,t){await GT({plugins:this.config.plugins,pluginManager:e,logger:this.logger,initOptions:t})}initializeServices(e,t){return OT({config:this.config,dependencies:t,initializerLogger:this.logger,lifecycle:e,...this.processRole&&{processRole:this.processRole}})}registerJobHandlers(e,t,n){let o=WT.createFresh(t,n);e.registerHandler(JT.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 Ud=r.strictObject({waveId:r.string().trim().min(1),ruleId:r.string().trim().min(1)});class Fd{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=Ud.safeParse(e);return t.success?t.data:null}async onTerminalError(e,t,n){let o=Ud.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=Ud.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=OB(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:jB(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 jB(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 OB(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 NB(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 Do="shell:projection-rule";class Bd{store;queue;graph;ruleById;graphFingerprint;createWaveId;beforeWaveCompletion;scheduleWakeup;onScheduledWakeupError;now;operationQueue=new HT;scheduledWakeup;constructor(e){this.store=e.store,this.queue=e.queue,this.graph=e.graph,this.ruleById=qB(e.graph,e.rules),this.graphFingerprint=$B(e.graph,e.rules),this.createWaveId=e.createWaveId,this.beforeWaveCompletion=e.beforeWaveCompletion??(async()=>{}),this.scheduleWakeup=e.scheduleWakeup??DB,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=zB(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=ZT(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:NB(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:Do,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 DB(e,t){let n=setTimeout(()=>{t()},e);return()=>clearTimeout(n)}function zB(e,t,n){let i=ZT(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 qB(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 $B(e,t){return VT({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 ZT(e,t,n){let o=new Map(e.projections.map((c)=>[c.id,c])),i=KT(e,(c)=>[c.from,c.to]),a=new Set(e.projections.filter((c)=>LB(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=UB(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 LB(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 UB(e,t){let n=KT(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 KT(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 YT(e){let t=new Bd({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 Fd({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(Do,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??FB)(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(Do),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(Do)}}}function FB(e,t){let n=setInterval(()=>{t()},e);return n.unref(),()=>clearInterval(n)}var BB=250,GB=r.object({projectionBatch:r.object({operationId:r.string().min(1),childKey:r.string().min(1)})});class Jd{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 Nd([()=>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 YT({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(Gd.waveReady))return;let a=await this.services.messageBus.collect({type:Gd.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:QT,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=GB.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 Nd([()=>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 XT(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:BB,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 eI{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(", ")}`);return o(t,n)}}function tI(){let e=new eI;return e.register("overview",JB),e.register("publishing-cadence",WB),e.register("content-health",HB),e}async function JB(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 Wd(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=rI(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 WB(e,t){let n=await Wd(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 HB(e,t){let n=await Wd(e,t),o=rI(n).map((l)=>({id:l.id,entityType:l.entityType,title:typeof l.metadata.title==="string"?l.metadata.title:l.id,created:l.created})),i=Date.now(),a=i-7776000000,s=n.filter((l)=>{if(l.entityType==="image")return!1;let c=new Date(l.updated).getTime();return!isNaN(c)&&c<a}).map((l)=>({id:l.id,entityType:l.entityType,title:typeof l.metadata.title==="string"?l.metadata.title:l.id,updated:l.updated,daysSinceUpdate:Math.floor((i-new Date(l.updated).getTime())/86400000)}));return{drafts:o,stale:s}}function rI(e){return e.filter((t)=>t.metadata.status==="draft")}async function Wd(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 ta{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 Hd extends ta{constructor(){super((e)=>nI.parse(e),(e)=>e.url)}}class Vd extends ta{constructor(){super((e)=>oI.parse(e),(e)=>e.id)}}function iI(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 VB=["/health","/images"],ZB=new Set([aI]),KB=new Set(sI),YB=new Set(["GET","POST","PUT","DELETE"]);function lI(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 QB(e){return ZB.has(e)||VB.some((t)=>e===t||e.startsWith(`${t}/`))}function Zd(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&&QB(e))throw Error(`Invalid HTTP route path "${e}" declared by plugin "${t}"`)}function cI(e,t,n){if(!e.has(t))throw Error(`Invalid HTTP route method "${t}" declared by plugin "${n}"`)}function XB(e,t){if(e!=="exact"&&e!=="prefix")throw Error(`Invalid HTTP route match "${e}" declared by plugin "${t}"`)}function eG(e,t){Zd(t.path,e.pluginId);let n=t.method??"GET";cI(KB,n,e.pluginId);let o=t.match??"exact";if(XB(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 tG(e,t){Zd(t.path,e.pluginId,!1);let n=`/api/${e.pluginId}${t.path}`;if(Zd(n,e.pluginId),cI(YB,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 rG(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 nG(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 qs{routes;manifest;apiRoutes;webRoutes;static createFresh(){return new qs}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(eG(i,a)),n.push(Object.freeze({pluginId:i.pluginId,fullPath:a.path,definition:Object.freeze({...a})}));for(let a of i.apiRoutes){let s=tG(i,a);t.push(s),o.push(Object.freeze({pluginId:i.pluginId,fullPath:s.fullPath,definition:s.definition}))}}return rG(t),this.routes=Object.freeze(t),this.manifest=nG(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 uI(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 oG=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")]),pI=r.object({query:r.string().describe("Search term"),scope:oG.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")}),mI=r.object({entityType:r.string().describe("Entity type"),id:r.string().describe("Entity ID, slug, or title")}),gI=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)")}),iG=r.object({kind:r.literal("upload").describe("Upload ref kind"),id:r.string().min(1).describe("Upload ID")}),aG=r.discriminatedUnion("kind",[r.object({kind:r.literal("text").describe("Store exact/direct user-provided content without generation"),content:r.string().min(1).describe("Exact markdown/text/content to persist as provided. For direct save requests where the user includes the content in the same message, use that provided content directly.")}).strict(),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:iG.describe("Exact upload candidate object from the current conversation"),transform:r.enum(["extract-markdown","preserve"]).describe("extract-markdown imports upload text into a note-like entity; preserve saves raw uploaded bytes via the registered upload-save handler and derives the durable entity type from media type. Use preserve only for explicit file/document preservation, not for saving an assistant summary response.")}).strict(),r.object({kind:r.literal("prior-response").describe("Save a previous assistant response as durable content, especially an assistant summary or answer about an upload."),messageId:r.string().min(1).optional().describe("Stored assistant message ID; omit for latest savable")}).strict()]),sG=r.discriminatedUnion("kind",[r.object({kind:r.literal("prompt").describe("Generate a new non-image durable entity from a broad prompt with no durable source entity. Use this for general topical social/newsletter/blog/deck generation. This branch has no source field; use prompt-from-source only after resolving a specific existing content entity."),entityType:r.string().min(1).describe("Entity type to generate from the prompt. Do not use image here; use standalone-image or cover-image."),title:r.string().optional().describe("Title for the generated entity"),prompt:r.string().min(1).describe("Prompt for creating new generated content. Do not use for saving/importing existing uploads or prior responses.")}).strict(),r.object({kind:r.literal("prompt-from-source").describe("Generate a new non-image durable entity from a specific resolved existing content entity. Use when the user asks to generate from/based on a source, including requests like 'create a newsletter based on my latest blog post'. After resolving the source with a tool result, call this operation in the same turn; do not merely say you can generate it."),entityType:r.string().min(1).describe("Entity type to generate from the source and prompt. Do not use image here; use standalone-image or cover-image."),title:r.string().optional().describe("Title for the generated entity"),source:r.object({entityType:r.string().min(1).describe("Resolved content source entity type, such as post for a newsletter from a blog post. Do not use brain-character or anchor-profile."),entityId:r.string().min(1).describe("Resolved source entity ID copied from a prior tool result or typed entity ref; never an upload id, filename, guessed slug, or future placeholder.")}).strict().describe("Existing durable source entity to ground this generation. Use only resolved entity refs, not uploads, filenames, profile/brain-character context, conversation-only context, unknown sources, or guessed sources."),prompt:r.string().min(1).describe("Prompt for creating new generated content from the resolved source. Do not use for saving/importing existing uploads or prior responses.")}).strict(),r.object({kind:r.literal("standalone-image").describe("Generate a standalone image that is not attached to another entity. Do not use this as a cover image substitute; requested covers require cover-image after the target entity exists."),title:r.string().optional().describe("Title for the generated image"),prompt:r.string().min(1).describe("Prompt for creating an unattached image. Not for cover images requested for a generated post/entity.")}).strict(),r.object({kind:r.literal("cover-image").describe("Generate an image and attach it to an existing entity as coverImageId. Use only after the target entity already exists and its real entityId is known; do not use in the same initial turn as generating that target entity."),target:r.object({entityType:r.string().min(1).describe("Existing target entity type. Use the actual type of the entity being covered: social-post for LinkedIn/social posts, post for blog posts, etc."),entityId:r.string().min(1).describe("Existing target entity ID copied from a prior tool result or typed entity ref; never a placeholder or guessed future id")}).strict().describe("Existing entity that should receive the generated coverImageId"),title:r.string().optional().describe("Title for the generated image"),prompt:r.string().min(1).describe("Prompt for creating the cover image")}).strict(),r.object({kind:r.literal("attachment").describe("Generate a deterministic durable artifact from an existing entity attachment provider"),source:r.object({entityType:r.string().min(1).describe("Source entity type"),entityId:r.string().min(1).describe("Canonical source entity ID copied from a prior tool result or typed entity ref; never an upload id, filename, guessed slug, or future placeholder")}).strict().describe("Existing durable entity whose attachment provider should render the artifact. Use only resolved entity refs, not uploads or conversation-only context."),attachmentType:r.string().min(1).describe('Source artifact type such as "carousel", "printable", or "og-image"'),title:r.string().optional().describe("Title for the generated artifact"),replace:r.boolean().optional().describe("Set true for regenerate, replace, refresh, or update requests so a deterministic artifact is regenerated instead of reused")}).strict()]),fI=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:dI.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:aG.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(),hI=r.object({operation:sG.describe("Generation operation selector. Use prompt for broad non-image AI-generated entities with no source, prompt-from-source for generation from a resolved existing entity, standalone-image for unattached images, cover-image for generated covers on existing entities, and attachment for deterministic source-derived artifacts; for regenerate/replace/refresh artifact requests use attachment with replace:true."),confirmed:r.literal(!0).optional().describe("Confirm generation"),confirmationToken:r.string().optional().describe("Internal confirmation token returned by the confirmation flow")}).strict(),lG=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(),yI=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(lG).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")}),vI=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")}),AX=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")}),bI=r.object({batchId:r.string().optional().describe("Specific batch ID to check"),jobTypes:r.array(r.string()).optional().describe("Filter by job types")}),_I=r.object({type:r.string().describe("Type of insight to retrieve. Built-in: overview, publishing-cadence, content-health. Plugins may register additional types.")}),cG=r.object({entityType:r.string().optional(),entityId:r.string().optional(),attachmentType:r.string().optional()}),uG=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:cG.optional()}),PX=r.object({entityId:r.string().optional(),status:r.enum(["created","generating"]),jobId:r.string().optional(),attachment:uG.optional()}),MX=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 SI||i instanceof Error)return{success:!1,error:i.message};throw i}}var dG="system",xI=r.record(r.string(),r.unknown()),pG=r.looseObject({fields:xI});function Or(e,t,n,o,i={}){let{visibility:a="admin",sideEffects:s}=i;return{name:`${dG}_${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:Re(d)}}},visibility:a,...s?{sideEffects:s}:{}}}async function $s(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 Fn(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 zo(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 Kd(e){if(e.entityType==="image"&&e.content.startsWith("data:"))return{...e,content:"[binary image data \u2014 use metadata for image info]"};return e}function Bn(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}function TI(e){if(e.fields!==void 0)return{...e};if(!e.content)return{};try{let t=JSON.parse(e.content),n=pG.safeParse(t);if(n.success)return{fields:n.data.fields};let o=xI.safeParse(t);if(o.success)return{fields:o.data}}catch{}return{content:e.content}}var mG={base:"note"};function II(e){return mG[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 CI(e){return!!e&&Object.keys(e.shape).length>0}async function kI(e,t,n){if(!n)return!1;let o=await e.conversationService.getMessages(n,{limit:100});for(let i of o){let s=wI(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 gG={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"};function fG(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(`
|
|
168
|
+
${jS}`:""),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:[tB,Pi(p.stepLimit??10)]});return{generate:async(h)=>{Kr(h.options);let v=_o(h.options);if(!v)return g.generate(h);let w=ku(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:yx(S.steps,e.guestPricing)})}}}}async function Ss(e,t,n){let o=await e.send({type:xx,sender:t,payload:{actor:n}});if("noop"in o)return null;if(!o.success)throw Error("Principal resolution unavailable");return Tx.parse(o.data).principal}function Cx(e,t){return new Ix(e,(n)=>Ss(t,"shell:content-service",n))}var Td=rt.GenericTag("@brains/conversation-service/ConversationService");function nB(e){if(e.service){let n=e.service;return{service:n,close:()=>n.close()}}let t=kx.createFreshFromConfig(e.logger,e.messageBus,e.dbConfig,e.config);try{return{service:t,close:()=>t.close()}}catch(n){throw t.close(),n}}function Rx(e){return yn(Td,()=>nB(e))}var Id=rt.GenericTag("@brains/entity-service/EntityService");function oB(e){return"close"in e&&typeof e.close==="function"}function Ax(e){return yn(Id,()=>{let t=e.service??Ex.createFresh(e);return{service:t,close:()=>{if(oB(t))t.close()}}})}var Yi=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()}),Cd=r.strictObject({alerts:r.array(Yi).optional()});var ws="shell:recurring-check",Rd=86400000,iB=7*Rd,aB=3*Rd,sB=r.strictObject({checkId:r.string().min(1)}),lB=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:Yi,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 Mx;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:lB});let t={validateAndParse:(n)=>{let o=sB.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){Px(e,"plugin ID"),Px(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=Cd.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=kd(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=kd(this.brainId,e.id,e.cadence),o=jx(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=Yi.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:${Qi(e)}`}alertKeyPrefix(e){return`alert:${Qi(e)}:`}alertKey(e,t){return`${this.alertKeyPrefix(e)}${Qi(t)}`}}function kd(e,t,n){let o=n==="daily"?Rd:iB,i=o/60000,a=Qi(`${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:aB}}function jx(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 Px(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 Ue=Ox("runtime_state_records",{namespace:Ts("namespace").notNull(),key:Ts("key").notNull(),value:Ts("value",{mode:"json"}).notNull(),createdAt:Ed("created_at").notNull(),updatedAt:Ed("updated_at").notNull()},(e)=>({pk:Dx({columns:[e.namespace,e.key]}),namespaceUpdatedAtIdx:Nx("idx_runtime_state_namespace_updated_at").on(e.namespace,e.updatedAt)}));function $x(e){return zx({url:e.url,schema:{runtimeStateRecords:Ue},authToken:e.authToken,authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN"})}var cB=/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,127}$/,Bx=512;class Pd{db;namespace;schema;now;constructor(e,t,n,o=()=>new Date){uB(t),this.db=e,this.namespace=t,this.schema=n,this.now=o}async get(e){let t=Un(e),o=(await this.db.select().from(Ue).where(Oo(ar(Ue.namespace,this.namespace),ar(Ue.key,t))).limit(1))[0];if(!o)return null;return this.schema.parse(o.value)}async has(e){let t=Un(e);return(await this.db.select({key:Ue.key}).from(Ue).where(Oo(ar(Ue.namespace,this.namespace),ar(Ue.key,t))).limit(1)).length>0}async set(e,t){let n=Un(e),o=this.schema.parse(t),i=this.now().getTime();await this.db.insert(Ue).values({namespace:this.namespace,key:n,value:o,createdAt:i,updatedAt:i}).onConflictDoUpdate({target:[Ue.namespace,Ue.key],set:{value:o,updatedAt:i}})}async setIfNotExists(e,t){let n=Un(e),o=this.schema.parse(t),i=this.now().getTime(),a=await this.db.insert(Ue).values({namespace:this.namespace,key:n,value:o,createdAt:i,updatedAt:i}).onConflictDoNothing({target:[Ue.namespace,Ue.key]});return Number(a.rowsAffected)>0}async compareAndSet(e,t,n){let o=Un(e),i=this.schema.parse(t),a=this.schema.parse(n),s=await this.db.update(Ue).set({value:a,updatedAt:this.now().getTime()}).where(Oo(ar(Ue.namespace,this.namespace),ar(Ue.key,o),ar(Ue.value,i)));return Number(s.rowsAffected)===1}async delete(e){let t=Un(e),n=await this.db.delete(Ue).where(Oo(ar(Ue.namespace,this.namespace),ar(Ue.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(Ue).where(ar(Ue.namespace,this.namespace));return Number(o.rowsAffected)}qx(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)qx(t);if(n!==void 0)Un(n);if(o!==void 0)r.number().int().min(1).max(1000).parse(o);let i=this.db.select({...Lx(Ue),key:Ad`CAST(${Ue.key} AS BLOB)`.mapWith((a)=>new TextDecoder("utf-8",{fatal:!0}).decode(a))}).from(Ue).where(Oo(ar(Ue.namespace,this.namespace),t!==void 0?Ad`substr(CAST(${Ue.key} AS BLOB), 1, length(CAST(${t} AS BLOB))) = CAST(${t} AS BLOB)`:void 0,n!==void 0?Ux(Ue.key,n):void 0)).orderBy(Fx(Ue.key)).$dynamic();return o===void 0?i:i.limit(o)}}function uB(e){if(!cB.test(e))throw Error(`Invalid runtime state namespace: ${e}. Use 1-128 alphanumeric, _, ., :, or - characters.`)}function Un(e){if(e.length===0||e.length>Bx)throw Error("Runtime state keys must be 1-512 characters long");return e}function qx(e){if(e.length>Bx)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}=$x(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 Gx(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 Pd(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 Md=rt.GenericTag("@brains/runtime-state/RuntimeStateService");function Jx(e){return yn(Md,()=>{let t=e.service??Is.createFresh(e.config,e.logger);return{service:t,close:()=>t.close()}})}async function jd(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=Xi(n),t.warn(`Daemon ${e.name} failed to start: ${Re(n)}`),n}}async function Od(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=Xi(n),t.error(`Failed to stop daemon: ${e.name}`,n),n}}async function Wx(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:Re(t),lastCheck:new Date};return e.health=n,n}}function Hx(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 Nd(e){let n=(await Mr(de.all(e.map((o)=>de.either(de.tryPromise({try:o,catch:(i)=>i}))),{concurrency:"unbounded"}))).find(Vx.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 jd(t,this.logger);return}let n=de.runSync(Xe.make()),o=de.acquireRelease(de.promise(()=>jd(t,this.logger)),()=>de.promise(()=>Od(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 Od(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 Wx(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(Hx)}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??=Xi(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 dB=r.object({projectionId:r.string().min(1),reason:r.string().min(1),openedAt:r.number().int().nonnegative(),expiresAt:r.number().int().nonnegative()}),pB=8,mB=32,gB=128,fB=5,hB=600000,yB=600000,vB=1000,bB="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??pB,maxJobsPerRoot:t.maxJobsPerRoot??mB,maxMutationsPerRoot:t.maxMutationsPerRoot??gB,repeatedTargetLimit:t.repeatedTargetLimit??fB,retentionMs:t.retentionMs??hB,circuitOpenMs:t.circuitOpenMs??yB,maxTrackedRoots:t.maxTrackedRoots??vB,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:bB,schema:dB})}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 _B={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 _B[e??"combined"]}var SB=20,wB=0.5,xB=0.06,TB=5;function Dd(e,t){let n=e[t];return typeof n==="string"&&n.trim().length>0?n.trim():void 0}function IB({entity:e},t){let n=Dd(e.metadata,"title")??Dd(e.metadata,"name"),o=Dd(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 Zx(e){return async({answer:t})=>{let o=(await e.entityService.search({query:t,options:{limit:SB,minScore:wB,visibilityScope:Ht("public")}})).filter((a)=>e.hasRoute(a.entity.entityType)),i=Math.max(...o.map((a)=>a.score));return o.filter((a)=>a.score>=i-xB).slice(0,TB).map((a)=>IB(a,e))}}function zd(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 CB(e,t,n){let o=kB(e.kind);if(!o)return null;try{let i=t.scoped({namespace:o,refKind:e.kind,routePath:""});return RB(await i.read(e.id),e)}catch(i){return n.debug("Skipped unavailable prior runtime upload",{uploadKind:e.kind,uploadId:e.id,error:Re(i)}),null}}function kB(e){return e==="upload"?"upload":null}function RB(e,t){let{record:n,content:o}=e;if(EB(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 EB(e){let t=e.toLowerCase();return t.startsWith("text/")||t==="application/json"}function tT(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=Qx.createFresh(n,o,t.identity);if(!d)u.push(...zd(i,Rt.BRAIN_CHARACTER,Rt.BRAIN_CHARACTER,()=>m.refreshCache(),o));let p=Xx.createFresh(n,o,t.profile),f=eT.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=xd({guestPricing:a.getConfig().model==="gpt-5.6-luna"?vd: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=dd(t.name),v=Ki.createFresh(s,l,m,p,o,{agentFactory:g,canonicalIdentityResolver:f,...t.embedding.enabled?{indexReadiness:n,guestAnswerSources:Zx({entityService:n,hasRoute:(w)=>Ko.getInstance().hasRoute(w),urlFor:(w,S)=>Ko.getInstance().generateUrl(w,S),siteBaseUrl:t.siteBaseUrl})}:{},uploadAttachmentResolver:(w)=>CB(w,c,o),agentContextProvider:async(w)=>(await i.collect({type:Kx,sender:"shell:agent-service",payload:w})).flatMap((y)=>{if("noop"in y||!y.success)return[];return Yx(y.data)}),...h?{assistantAgentId:h}:{},...t.agentInstructions&&{agentInstructions:t.agentInstructions}});if(!d){u.push(...zd(i,Rt.ANCHOR_PROFILE,Rt.ANCHOR_PROFILE,()=>p.refreshCache(),o));for(let w of[Rt.BRAIN_CHARACTER,Rt.ANCHOR_PROFILE])u.push(...zd(i,w,w,async()=>v.invalidateAgent(),o))}return{identityService:m,profileService:p,canonicalIdentityService:f,agentService:v}}var ea=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 aT(e){return yn(ea,()=>{let t=e.service??rT.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 sT(e){let t=!1,n=de.gen(function*(){let o=yield*ea,i=e.batchJobManager??oT.createFresh(o,e.logger),a=e.jobProgressMonitor??iT.createFresh(o,e.messageBus,i,e.logger,e.progressMonitorMode),s=e.jobQueueWorker??nT.createFresh(o,a,e.logger,{pollInterval:100,concurrency:e.workerConcurrency,autoStart:!1,...e.onWorkerUnhealthy&&{onUnhealthy:e.onWorkerUnhealthy}},{...e.operationContext&&{operationContext:e.operationContext}});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:AB(o))),abandon:()=>{t=!0}}}function AB(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 PB(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 lT(e){let t=e.operationContext??Os.createFresh(),n=de.runSync(Xe.make()),o,i;try{let a=de.runSync(Xr.buildWithScope(aT({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,ea),l=de.runSync(Xe.make());o=l;let c=sT({messageBus:e.messageBus,logger:e.logger,operationContext:t,onWorkerUnhealthy:PB(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(ea,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 uT(e){return{deliver:async(t)=>{if(!e.hasHandlers($d))return!1;let n=await e.send({type:$d,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=cT.safeParse(n.data);if(!o.success||o.data.status!=="sent")throw Error("Recurring alert delivery failed");return!0}}}function pT(e){return{sourceId:"recurring-checks",displayName:"Recurring checks",list:async()=>(await e.listOpenAlerts()).map((t)=>({id:t.id,title:dT(t.title,160),summary:dT(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 dT(e,t){return e.length<=t?e:e.slice(0,t)}function mT(e,t){if(t)return t;let n={debug:$t.DEBUG,info:$t.INFO,warn:$t.WARN,error:$t.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 gT(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 No(e){return{url:e.url,...e.authToken?{authToken:e.authToken}:{}}}function OT(e){let{config:t,dependencies:n,initializerLogger:o,lifecycle:i,processRole:a}=e;o.debug("Initializing Shell services");let s=Rs(a),l=mT(t,n?.logger),c=n?.operationContext??Os.createFresh(),u=[],d=n?.embeddingService??qi.createFresh({apiKey:t.ai.apiKey,logger:l}),m=n?.aiService??$i.createFresh(gT(t),l),p=n?.entityRegistry??hT.createFresh(l),f=n?.messageBus??PT.createFresh(l,c),g=n?.templateRegistry??vT.createFresh(l),h=n?.dataSourceRegistry??yT.createFresh(l),v=n?.renderService??bT.createFresh(g),w=n?.daemonRegistry??Cs.createFresh(l),S=n?.pluginManager??jT.createFresh(l,w),y=n?.permissionService??new ys(t.permissions,{spaces:t.spaces,entityActionFloor:(H)=>p.getEntityTypeConfig(H).actionPolicy}),x=n?.profileKindRegistry??new MT(t.profileKind),_=n?.channelRegistry??new wT,C=n?.inboxRegistry??new xT,I=n?.inboxFollowUpRegistry??new TT(l),b=n?.operationalHealthRegistry??new AT,E=n?.accountSettingsRegistry??new ST,F=n?.attachmentRegistry??IT.createFresh(),R=n?.runtimeUploadRegistry??CT.createFresh({dataDir:t.dataDir,logger:l}),z=i.buildLayer(Jx({config:No(t.runtimeStateDatabase),logger:l,...n?.runtimeStateService&&{service:n.runtimeStateService}})),D=rt.get(z,Md),N=n?.projectionRuntimeSupervisor??ks.createFresh(c,{runtimeState:D}),re=n?.mcpService??ET.createFresh(f,l),Y=lT({dependencies:n,jobQueueConfig:No(t.jobQueueDatabase),workerConcurrency:t.jobQueue.workerConcurrency,messageBus:f,operationContext:c,projectionAdmission:N,handlerRegistrationMode:s.handlerRegistrationMode,progressMonitorMode:s.progressMonitorMode,logger:l}),{batchJobManager:V,jobProgressMonitor:L,jobQueueService:pe,jobQueueWorker:X}=Y;i.addSyncFinalizer(()=>Y.closeDatabase()),i.addSyncFinalizer(()=>Y.rollbackRuntime());let k=n?.recurringCheckService??new xs({brainId:t.siteBaseUrl??t.dataDir,scheduler:new kT,runtimeState:D,clock:fT.make(),jobQueue:pe,logger:l,delivery:uT(f)});i.addSyncFinalizer(()=>k.abandon()),C.registerSource("shell.recurring-checks",pT(k)),i.addSyncFinalizer(()=>C.unregisterPlugin("shell.recurring-checks"));let Q=(H,P)=>{if(!s.serves)return;w.register(H,P,"shell"),i.addSyncFinalizer(()=>w.abandon(H))};Q("shell:recurring-checks",{start:()=>k.start(),stop:()=>k.stop()});let J=i.buildLayer(Ax({embeddingService:d,embeddingsEnabled:t.embedding.enabled,entityRegistry:p,logger:l,jobQueueService:pe,messageBus:f,mutationAdmission:N,...n?.projectionRuntime?.now&&{projectionNow:n.projectionRuntime.now},dbConfig:No(t.database),embeddingDbConfig:No(t.embeddingDatabase),...n?.entityService&&{service:n.entityService}})),W=rt.get(J,Id),K=i.buildLayer(Rx({dbConfig:No(t.conversationDatabase),logger:l,messageBus:f,...n?.conversationService&&{service:n.conversationService}})),q=rt.get(K,Td);Q("shell:guest-retention",RT({intervalMs:60000,logger:l,run:async()=>{await q.deleteExpiredGuestConversations(100)}})),i.addSyncFinalizer(()=>{for(let H of u.splice(0))try{H()}catch(P){l.warn("Failed to dispose shell subscription",P)}});let B=n?.contentService??new _T({logger:l,entityService:W,aiService:m,templateRegistry:g,dataSourceRegistry:h,generationAuthorizer:Cx(y,f)}),{identityService:G,profileService:Z,canonicalIdentityService:A,agentService:O}=tT({config:t,entityService:W,embeddingService:d,entityRegistry:p,logger:l,messageBus:f,aiService:m,mcpService:re,conversationService:q,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:W,aiService:m,conversationService:q,contentService:B,jobQueueService:pe,jobQueueWorker:X,batchJobManager:V,jobProgressMonitor:L,jobServicesLifecycle:Y,permissionService:y,identityService:G,profileService:Z,canonicalIdentityService:A,profileKindRegistry:x,channelRegistry:_,inboxRegistry:C,inboxFollowUpRegistry:I,operationalHealthRegistry:b,accountSettingsRegistry:E,agentService:O,attachmentRegistry:F,runtimeUploadRegistry:R,runtimeStateService:D,recurringCheckService:k}}function qT(e,t){e.register(qd.name,qd),t.debug("Shell system templates registered")}function LT(e,t){e.register(Zo.BASE_ENTITY_DISPLAY,{name:"base-entity-display",description:"Display template for base entities",schema:Ld,formatter:new NT,requiredPermission:"public"}),t.debug("Base entity display template registered")}function UT(e,t){e.registerEntityType(Rt.NOTE,Ld,new DT,{projectionSourceRole:"primary"}),t.debug("Fallback base entity adapter registered")}function FT(e,t){let n=new zT;e.registerEntityType(Rt.BRAIN_CHARACTER,n.schema,n,{projectionSource:!1,projectionSourceRole:"excluded"}),t.debug("Brain character entity support registered")}function BT(e,t){let n=new $T;e.registerEntityType(Rt.ANCHOR_PROFILE,n.schema,n,{projectionSourceRole:"canonical"}),t.debug("Anchor profile entity support registered")}async function GT(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){qT(e,this.logger)}registerBaseEntityDisplayTemplate(e){LT(e,this.logger)}registerFallbackBaseEntity(e){UT(e,this.logger)}registerBrainCharacterSupport(e){FT(e,this.logger)}registerAnchorProfileSupport(e){BT(e,this.logger)}async initializePlugins(e,t){await GT({plugins:this.config.plugins,pluginManager:e,logger:this.logger,initOptions:t})}initializeServices(e,t){return OT({config:this.config,dependencies:t,initializerLogger:this.logger,lifecycle:e,...this.processRole&&{processRole:this.processRole}})}registerJobHandlers(e,t,n){let o=WT.createFresh(t,n);e.registerHandler(JT.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 Ud=r.strictObject({waveId:r.string().trim().min(1),ruleId:r.string().trim().min(1)});class Fd{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=Ud.safeParse(e);return t.success?t.data:null}async onTerminalError(e,t,n){let o=Ud.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=Ud.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=OB(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:jB(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 jB(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 OB(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 NB(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 Do="shell:projection-rule";class Bd{store;queue;graph;ruleById;graphFingerprint;createWaveId;beforeWaveCompletion;scheduleWakeup;onScheduledWakeupError;now;operationQueue=new HT;scheduledWakeup;constructor(e){this.store=e.store,this.queue=e.queue,this.graph=e.graph,this.ruleById=$B(e.graph,e.rules),this.graphFingerprint=qB(e.graph,e.rules),this.createWaveId=e.createWaveId,this.beforeWaveCompletion=e.beforeWaveCompletion??(async()=>{}),this.scheduleWakeup=e.scheduleWakeup??DB,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=zB(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=ZT(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:NB(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:Do,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 DB(e,t){let n=setTimeout(()=>{t()},e);return()=>clearTimeout(n)}function zB(e,t,n){let i=ZT(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 $B(e,t){let n=new Map;for(let i of t){if(n.has(i.id))throw Error(`Duplicate executable projection rule "${i.id}"`);n.set(i.id,i)}let o=new Set(e.projections.map((i)=>i.id));for(let i of o)if(!n.has(i))throw Error(`Projection "${i}" has no executable rule`);for(let i of n.keys())if(!o.has(i))throw Error(`Executable projection rule "${i}" is not in the graph`);return n}function qB(e,t){return VT({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 ZT(e,t,n){let o=new Map(e.projections.map((c)=>[c.id,c])),i=KT(e,(c)=>[c.from,c.to]),a=new Set(e.projections.filter((c)=>LB(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=UB(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 LB(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 UB(e,t){let n=KT(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 KT(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 YT(e){let t=new Bd({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 Fd({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(Do,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??FB)(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(Do),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(Do)}}}function FB(e,t){let n=setInterval(()=>{t()},e);return n.unref(),()=>clearInterval(n)}var BB=250,GB=r.object({projectionBatch:r.object({operationId:r.string().min(1),childKey:r.string().min(1)})});class Jd{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 Nd([()=>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 YT({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(Gd.waveReady))return;let a=await this.services.messageBus.collect({type:Gd.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:QT,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=GB.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 Nd([()=>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 XT(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:BB,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 eI{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(", ")}`);return o(t,n)}}function tI(){let e=new eI;return e.register("overview",JB),e.register("publishing-cadence",WB),e.register("content-health",HB),e}async function JB(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 Wd(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=rI(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 WB(e,t){let n=await Wd(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 HB(e,t){let n=await Wd(e,t),o=rI(n).map((l)=>({id:l.id,entityType:l.entityType,title:typeof l.metadata.title==="string"?l.metadata.title:l.id,created:l.created})),i=Date.now(),a=i-7776000000,s=n.filter((l)=>{if(l.entityType==="image")return!1;let c=new Date(l.updated).getTime();return!isNaN(c)&&c<a}).map((l)=>({id:l.id,entityType:l.entityType,title:typeof l.metadata.title==="string"?l.metadata.title:l.id,updated:l.updated,daysSinceUpdate:Math.floor((i-new Date(l.updated).getTime())/86400000)}));return{drafts:o,stale:s}}function rI(e){return e.filter((t)=>t.metadata.status==="draft")}async function Wd(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 ta{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 Hd extends ta{constructor(){super((e)=>nI.parse(e),(e)=>e.url)}}class Vd extends ta{constructor(){super((e)=>oI.parse(e),(e)=>e.id)}}function iI(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 VB=["/health","/images"],ZB=new Set([aI]),KB=new Set(sI),YB=new Set(["GET","POST","PUT","DELETE"]);function lI(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 QB(e){return ZB.has(e)||VB.some((t)=>e===t||e.startsWith(`${t}/`))}function Zd(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&&QB(e))throw Error(`Invalid HTTP route path "${e}" declared by plugin "${t}"`)}function cI(e,t,n){if(!e.has(t))throw Error(`Invalid HTTP route method "${t}" declared by plugin "${n}"`)}function XB(e,t){if(e!=="exact"&&e!=="prefix")throw Error(`Invalid HTTP route match "${e}" declared by plugin "${t}"`)}function eG(e,t){Zd(t.path,e.pluginId);let n=t.method??"GET";cI(KB,n,e.pluginId);let o=t.match??"exact";if(XB(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 tG(e,t){Zd(t.path,e.pluginId,!1);let n=`/api/${e.pluginId}${t.path}`;if(Zd(n,e.pluginId),cI(YB,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 rG(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 nG(e){return Object.freeze(e.map((t)=>Object.freeze({ownerPluginId:t.ownerPluginId,kind:t.kind,method:t.method,fullPath:t.fullPath,match:t.match,sharedHostAdmission:t.sharedHostAdmission})))}class $s{routes;manifest;apiRoutes;webRoutes;static createFresh(){return new $s}constructor(){}finalize(e){if(this.routes!==void 0)throw Error("HTTP route registry has already been finalized");let t=[],n=[],o=[];for(let i of e){for(let a of i.webRoutes)t.push(eG(i,a)),n.push(Object.freeze({pluginId:i.pluginId,fullPath:a.path,definition:Object.freeze({...a})}));for(let a of i.apiRoutes){let s=tG(i,a);t.push(s),o.push(Object.freeze({pluginId:i.pluginId,fullPath:s.fullPath,definition:s.definition}))}}return rG(t),this.routes=Object.freeze(t),this.manifest=nG(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 uI(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 oG=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")]),pI=r.object({query:r.string().describe("Search term"),scope:oG.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")}),mI=r.object({entityType:r.string().describe("Entity type"),id:r.string().describe("Entity ID, slug, or title")}),gI=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)")}),iG=r.object({kind:r.literal("upload").describe("Upload ref kind"),id:r.string().min(1).describe("Upload ID")}),aG=r.discriminatedUnion("kind",[r.object({kind:r.literal("text").describe("Store exact/direct user-provided content without generation"),content:r.string().min(1).describe("Exact markdown/text/content to persist as provided. For direct save requests where the user includes the content in the same message, use that provided content directly.")}).strict(),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:iG.describe("Exact upload candidate object from the current conversation"),transform:r.enum(["extract-markdown","preserve"]).describe("extract-markdown imports upload text into a note-like entity; preserve saves raw uploaded bytes via the registered upload-save handler and derives the durable entity type from media type. Use preserve only for explicit file/document preservation, not for saving an assistant summary response.")}).strict(),r.object({kind:r.literal("prior-response").describe("Save a previous assistant response as durable content, especially an assistant summary or answer about an upload."),messageId:r.string().min(1).optional().describe("Stored assistant message ID; omit for latest savable")}).strict()]),sG=r.discriminatedUnion("kind",[r.object({kind:r.literal("prompt").describe("Generate a new non-image durable entity from a broad prompt with no durable source entity. Use this for general topical social/newsletter/blog/deck generation. This branch has no source field; use prompt-from-source only after resolving a specific existing content entity."),entityType:r.string().min(1).describe("Entity type to generate from the prompt. Do not use image here; use standalone-image or cover-image."),title:r.string().optional().describe("Title for the generated entity"),prompt:r.string().min(1).describe("Prompt for creating new generated content. Do not use for saving/importing existing uploads or prior responses.")}).strict(),r.object({kind:r.literal("prompt-from-source").describe("Generate a new non-image durable entity from a specific resolved existing content entity. Use when the user asks to generate from/based on a source, including requests like 'create a newsletter based on my latest blog post'. After resolving the source with a tool result, call this operation in the same turn; do not merely say you can generate it."),entityType:r.string().min(1).describe("Entity type to generate from the source and prompt. Do not use image here; use standalone-image or cover-image."),title:r.string().optional().describe("Title for the generated entity"),source:r.object({entityType:r.string().min(1).describe("Resolved content source entity type, such as post for a newsletter from a blog post. Do not use brain-character or anchor-profile."),entityId:r.string().min(1).describe("Resolved source entity ID copied from a prior tool result or typed entity ref; never an upload id, filename, guessed slug, or future placeholder.")}).strict().describe("Existing durable source entity to ground this generation. Use only resolved entity refs, not uploads, filenames, profile/brain-character context, conversation-only context, unknown sources, or guessed sources."),prompt:r.string().min(1).describe("Prompt for creating new generated content from the resolved source. Do not use for saving/importing existing uploads or prior responses.")}).strict(),r.object({kind:r.literal("standalone-image").describe("Generate a standalone image that is not attached to another entity. Do not use this as a cover image substitute; requested covers require cover-image after the target entity exists."),title:r.string().optional().describe("Title for the generated image"),prompt:r.string().min(1).describe("Prompt for creating an unattached image. Not for cover images requested for a generated post/entity.")}).strict(),r.object({kind:r.literal("cover-image").describe("Generate an image and attach it to an existing entity as coverImageId. Use only after the target entity already exists and its real entityId is known; do not use in the same initial turn as generating that target entity."),target:r.object({entityType:r.string().min(1).describe("Existing target entity type. Use the actual type of the entity being covered: social-post for LinkedIn/social posts, post for blog posts, etc."),entityId:r.string().min(1).describe("Existing target entity ID copied from a prior tool result or typed entity ref; never a placeholder or guessed future id")}).strict().describe("Existing entity that should receive the generated coverImageId"),title:r.string().optional().describe("Title for the generated image"),prompt:r.string().min(1).describe("Prompt for creating the cover image")}).strict(),r.object({kind:r.literal("attachment").describe("Generate a deterministic durable artifact from an existing entity attachment provider"),source:r.object({entityType:r.string().min(1).describe("Source entity type"),entityId:r.string().min(1).describe("Canonical source entity ID copied from a prior tool result or typed entity ref; never an upload id, filename, guessed slug, or future placeholder")}).strict().describe("Existing durable entity whose attachment provider should render the artifact. Use only resolved entity refs, not uploads or conversation-only context."),attachmentType:r.string().min(1).describe('Source artifact type such as "carousel", "printable", or "og-image"'),title:r.string().optional().describe("Title for the generated artifact"),replace:r.boolean().optional().describe("Set true for regenerate, replace, refresh, or update requests so a deterministic artifact is regenerated instead of reused")}).strict()]),fI=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:dI.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:aG.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(),hI=r.object({operation:sG.describe("Generation operation selector. Use prompt for broad non-image AI-generated entities with no source, prompt-from-source for generation from a resolved existing entity, standalone-image for unattached images, cover-image for generated covers on existing entities, and attachment for deterministic source-derived artifacts; for regenerate/replace/refresh artifact requests use attachment with replace:true."),confirmed:r.literal(!0).optional().describe("Confirm generation"),confirmationToken:r.string().optional().describe("Internal confirmation token returned by the confirmation flow")}).strict(),lG=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(),yI=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(lG).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")}),vI=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")}),AX=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")}),bI=r.object({batchId:r.string().optional().describe("Specific batch ID to check"),jobTypes:r.array(r.string()).optional().describe("Filter by job types")}),_I=r.object({type:r.string().describe("Type of insight to retrieve. Built-in: overview, publishing-cadence, content-health. Plugins may register additional types.")}),cG=r.object({entityType:r.string().optional(),entityId:r.string().optional(),attachmentType:r.string().optional()}),uG=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:cG.optional()}),PX=r.object({entityId:r.string().optional(),status:r.enum(["created","generating"]),jobId:r.string().optional(),attachment:uG.optional()}),MX=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 SI||i instanceof Error)return{success:!1,error:i.message};throw i}}var dG="system",xI=r.record(r.string(),r.unknown()),pG=r.looseObject({fields:xI});function Or(e,t,n,o,i={}){let{visibility:a="admin",sideEffects:s}=i;return{name:`${dG}_${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:Re(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 Fn(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 zo(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 Kd(e){if(e.entityType==="image"&&e.content.startsWith("data:"))return{...e,content:"[binary image data \u2014 use metadata for image info]"};return e}function Bn(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}function TI(e){if(e.fields!==void 0)return{...e};if(!e.content)return{};try{let t=JSON.parse(e.content),n=pG.safeParse(t);if(n.success)return{fields:n.data.fields};let o=xI.safeParse(t);if(o.success)return{fields:o.data}}catch{}return{content:e.content}}var mG={base:"note"};function II(e){return mG[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 CI(e){return!!e&&Object.keys(e.shape).length>0}async function kI(e,t,n){if(!n)return!1;let o=await e.conversationService.getMessages(n,{limit:100});for(let i of o){let s=wI(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 gG={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"};function fG(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
169
|
`)}}function hG(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 yG(e,t,n){if(!n)return{success:!1,error:"Conversation message is not accessible in this conversation or does not exist."};let o=await e.conversationService.getMessages(n,{limit:100}),i=t.messageId?o.find((a)=>a.id===t.messageId&&a.role==="assistant"):[...o].reverse().find(Yd);if(!i||!Yd(i))return{success:!1,error:"Conversation message is not accessible in this conversation or does not exist."};return{success:!0,messageId:i.id,content:i.content}}function vG(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":return{conversationMessageRef:{kind:"conversation-message",...e.messageId?{messageId:e.messageId}:{}}}}}function bG(e){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 _G(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 SG(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&&CI(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:Re(l,"Failed to create entity")}}}function vn(e){return{kind:"error",result:{success:!1,error:e}}}async function wG(e,t,n){let{content:o,url:i,from:a,uploadRef:s,conversationMessageRef:l,transform:c}=vG(t.source),u=l?await yG(e,l,n.conversationId??n.channelId):void 0;if(u&&!u.success)return{kind:"error",result:u};let d=u?.success===!0?u.content:o;if(c==="extract-markdown"&&(!s||t.entityType!=="note"))return vn('Transform "extract-markdown" requires entityType "note" and an upload ref. Omit transform for raw file promotion to document/image.');if(!d&&!i&&!a)return vn('Provide `source` with kind "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 xG(e,t,n){if(!await kI(e,t.uploadRef,n.conversationId??n.channelId))return vn("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(gG).readRecord(t.uploadRef.id)}catch{return vn("Upload ref not found")}let a=e.entityRegistry.getUploadSaveHandler(i.mediaType);if(!a)return vn(`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 TG(e,t,n){let o=t?Fs(t):void 0;if(e!==void 0&&o!==void 0&&e!==o)return vn(`Conflicting entity visibility: system_create requested "${e}" but the source frontmatter declares "${o}".`);let i=e??o,a=i??"public";if(!Us(n.userPermissionLevel,a))return vn(`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 IG(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 CG(e,t,n){if(!(t.source.kind==="upload"&&t.source.transform==="preserve")){let C=Fn(e,t.entityType);if(C)return{kind:"error",result:C}}let i=await wG(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 xG(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=Fn(e,p);if(g)return{kind:"error",result:g};let h=TG(t.visibility,a,n);if(h.kind==="error")return h;let v=Bn(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 vn('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 IG(e,S,x);if(_)return{kind:"error",result:_};return{kind:"ok",prepared:{createInput:S,resolvedMessageId:d,interceptor:x,eventContext:zo(n),...f&&{uploadPreserve:f}}}}function RI(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: text for exact user-provided content, 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 text with that content instead of asking them to paste it again; for example, 'Save this as a note: ...' or 'Save this memo about the launch timeline' already supplies the content, even when it is only a short sentence or fragment. 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 text for that visible content. On the initial create request, do not pass confirmed; the tool will return confirmation args after the user confirms.",fI,async(n,o)=>{let i=await CG(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?fG({...a.title&&{title:a.title},filename:u.filename,mediaType:u.mediaType,entityType:a.entityType,visibility:a.visibility}):hG(a),m=bG({source:n.source,...s&&{resolvedMessageId:s}}),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 _G({upload:u.upload,...a.title&&{title:a.title},...a.visibility!==void 0?{visibility:a.visibility}:{},handler:u.handler},o);if(l){let d=await
|
|
171
|
-
`)}}async function RG(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 EG(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 AG(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 PG(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=EI(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:Re(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:Re(m,"Failed to queue generation job")}}}async function MG(e,t,n){let o,i,a=t.kind==="attachment"&&t.replace===!0;if(t.kind==="prompt"||t.kind==="prompt-from-source"){if(t.entityType==="image")return{kind:"error",result:{success:!1,error:"Use operation.kind 'standalone-image' or 'cover-image' for image generation.",code:"unsupported-generation"}};let s=t.kind==="prompt-from-source"?await EG(e,t.source,n):{kind:"ok",source:void 0};if(s.kind==="error")return s;let l=Bn(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=Bn(t.title);o={entityType:"image",...s?{title:s}:{},prompt:t.prompt}}else if(t.kind==="cover-image"){let s=await AG(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=Bn(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 RG(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=Bn(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 jG(e,t,n){let o=t.operation,i=Ht(n.userPermissionLevel),a=await MG(e,o,i);if(a.kind==="error")return a;let{createInput:s,sourceAttachment:l}=a,c=o.kind==="attachment"&&o.replace===!0,u=Fn(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:OG(o,s,l),sourceAttachment:l,interceptor:m,eventContext:zo(n)}}}function OG(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 AI(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.",hI,async(n,o)=>{let i=await jG(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=kG(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 $s(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 PG(e,a,a.prompt,c,o)},{visibility:"trusted",sideEffects:"writes"})}function PI(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.",vI,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=Fn(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=Ht(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:Re(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"})}import{isDeepStrictEqual as oa}from"util";class Bs{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 MI extends Bs{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}}var jI=new MI;function Qd(e,t,n){return jI.diff(e,t,n)}var Gs=r.enum(["png","jpg","jpeg","webp","gif","svg"]),NI=r.enum(["pending","draft","failed"]),DI=r.object({title:r.string().optional(),alt:r.string().optional(),format:Gs,width:r.number(),height:r.number(),status:NI.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()}),ra=OI.extend({entityType:r.literal("image"),metadata:DI}),NG=r.object({url:r.string(),alt:r.string(),title:r.string(),width:r.number(),height:r.number()});function zI(e){return/^https?:\/\//i.test(e)}async function qI(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 LI(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 Js(e){let t=LI(e);if(!t)throw Error("Invalid image data URL");return t}function DG(e,t){return`data:image/${t==="jpg"?"jpeg":t};base64,${e}`}var zG={png:"iVBORw",jpg:"/9j/",gif:"R0lGOD",webp:"UklGR"};function Xd(e){for(let[t,n]of $I(zG))if(e.startsWith(n))return t;return null}function UI(e){let t=e.toLowerCase(),n=t==="svg+xml"?"svg":t,o=Gs.safeParse(n);return o.success?o.data:null}async function qG(e){return qI(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 FI(e){let t=UI(e);if(!t)throw Error(`Unsupported image format: ${e}`);return t}class ep{entityType="image";purpose="Image assets such as generated covers, social previews, and uploaded images.";schema=ra;toMarkdown(e){return e.content}fromMarkdown(e){let{format:t,base64:n}=Js(e),o=Ws(n);return{entityType:"image",content:e,metadata:{format:FI(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}=Js(t),s=Ws(a),c=Xd(a)??FI(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 $G=new ep;function yte(e){return GI(e,{skipInvalid:!0,noRefs:!0,sortKeys:!0})}function JI(e){return BI(e)}var LG=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,UG=r.record(r.string(),r.unknown());async function WI(e,t){let n=await t.getEntity({entityType:"image",id:e},ra);if(!n)return;return{url:n.content,alt:n.metadata.alt??"",title:n.metadata.title??"",width:n.metadata.width,height:n.metadata.height}}function HI(e,t){let n=LG.exec(e.content);if(!n?.[1])return;try{let o=UG.safeParse(JI(n[1]));if(o.success){let i=o.data[t];return typeof i==="string"?i:void 0}}catch{return}return}function VI(e){return HI(e,"coverImageId")}function FG(e){return HI(e,"ogImageId")}function tp(e,t){return{...e,content:na(e.content,"coverImageId",t)}}function rp(e,t){return{...e,content:na(e.content,"ogImageId",t)}}async function BG(e,t){let n=VI(e);if(!n)return;return WI(n,t)}var GG=KI();function JG(e){let t=[],n=GG.parse(e);return ZI(n,"image",(o)=>{t.push({url:o.url,alt:o.alt??"",title:o.title??void 0})}),t}function YI(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("")}var WG=r.looseObject({entityType:r.literal("agent"),id:r.string()});function op(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 HG(e,t,n){if(n.has(t))return np(e.content).frontmatter[t];return t==="visibility"?e.visibility:e.metadata[t]}function eC(e,t,n){let{visibility:o,coverImageId:i,ogImageId:a,...s}=t,l=o===void 0?e.visibility:QI.parse(o),c=Object.hasOwn(t,"coverImageId")?tp(e,typeof i==="string"?i:null):e,u=Object.hasOwn(t,"ogImageId")?rp(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=op(e.entityType,n),f=!1;for(let[g,h]of Object.entries(t)){if(!p.has(g))continue;m.content=na(m.content,g,h),f=!0}if(f)m.metadata=n.projectMetadata(e.entityType,m.content,d);return m}function VG(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(oa(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:Fs(t)??e.visibility}}function ZG(e,t){if(e!=="anchor-profile")return;if(t.fields)return{success:!1,error:"anchor-profile updates require full markdown content replacement, not fields-only updates."};return}var KG=new Set(["visibility","coverImageId","ogImageId"]),YG=r.record(r.string(),r.unknown());function QG(e,t,n,o){let i=t.fields;if(!i)return;let a=n.getEffectiveFrontmatterSchema(e.entityType);if(!a)return;let s=op(e.entityType,n),l=Object.keys(i).filter((g)=>s.has(g)),c;try{if(c=eC(e,i,n),l.length>0){let g=n.validateEntity(e.entityType,c),h=o.serializeEntity(g),v=np(h).frontmatter,w=o.deserializeEntity(h,e.entityType).metadata??{};for(let S of l){let y=i[S];if(y===null?Object.hasOwn(v,S)||Object.hasOwn(w,S):!oa(v[S],y)||!oa(w[S],y))return{success:!1,error:`The requested ${S} value would not survive frontmatter persistence.`}}}}catch(g){return{success:!1,error:Re(g,"Invalid field update")}}let u=Object.keys(i).filter((g)=>!s.has(g)&&!KG.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],v=Object.hasOwn(m,g);if(h===null){if(v)p.push(g);else if(!Object.hasOwn(e.metadata,g))f.push(g);continue}if(v){if(!oa(m[g],h))p.push(g)}else f.push(g)}if(f.length>0){let g;try{g=d.parseFrontMatter(d.toMarkdown(c),YG)}catch{if(p.length===0)return}if(g)for(let h of f){let v=i[h],w=Object.hasOwn(g,h);if(v===null?w:!w||!oa(g[h],v))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 XG(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 eJ(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 tJ(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 rJ(e,t,n){let o=op(e.entityType,n);if(t.fields)return Object.entries(t.fields).map(([l,c])=>{let u=HG(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(`
|
|
170
|
+
`)}}async function yG(e,t,n){if(!n)return{success:!1,error:"Conversation message is not accessible in this conversation or does not exist."};let o=await e.conversationService.getMessages(n,{limit:100}),i=t.messageId?o.find((a)=>a.id===t.messageId&&a.role==="assistant"):[...o].reverse().find(Yd);if(!i||!Yd(i))return{success:!1,error:"Conversation message is not accessible in this conversation or does not exist."};return{success:!0,messageId:i.id,content:i.content}}function vG(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":return{conversationMessageRef:{kind:"conversation-message",...e.messageId?{messageId:e.messageId}:{}}}}}function bG(e){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 _G(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 SG(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&&CI(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:Re(l,"Failed to create entity")}}}function vn(e){return{kind:"error",result:{success:!1,error:e}}}async function wG(e,t,n){let{content:o,url:i,from:a,uploadRef:s,conversationMessageRef:l,transform:c}=vG(t.source),u=l?await yG(e,l,n.conversationId??n.channelId):void 0;if(u&&!u.success)return{kind:"error",result:u};let d=u?.success===!0?u.content:o;if(c==="extract-markdown"&&(!s||t.entityType!=="note"))return vn('Transform "extract-markdown" requires entityType "note" and an upload ref. Omit transform for raw file promotion to document/image.');if(!d&&!i&&!a)return vn('Provide `source` with kind "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 xG(e,t,n){if(!await kI(e,t.uploadRef,n.conversationId??n.channelId))return vn("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(gG).readRecord(t.uploadRef.id)}catch{return vn("Upload ref not found")}let a=e.entityRegistry.getUploadSaveHandler(i.mediaType);if(!a)return vn(`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 TG(e,t,n){let o=t?Fs(t):void 0;if(e!==void 0&&o!==void 0&&e!==o)return vn(`Conflicting entity visibility: system_create requested "${e}" but the source frontmatter declares "${o}".`);let i=e??o,a=i??"public";if(!Us(n.userPermissionLevel,a))return vn(`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 IG(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 CG(e,t,n){if(!(t.source.kind==="upload"&&t.source.transform==="preserve")){let C=Fn(e,t.entityType);if(C)return{kind:"error",result:C}}let i=await wG(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 xG(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=Fn(e,p);if(g)return{kind:"error",result:g};let h=TG(t.visibility,a,n);if(h.kind==="error")return h;let v=Bn(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 vn('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 IG(e,S,x);if(_)return{kind:"error",result:_};return{kind:"ok",prepared:{createInput:S,resolvedMessageId:d,interceptor:x,eventContext:zo(n),...f&&{uploadPreserve:f}}}}function RI(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: text for exact user-provided content, 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 text with that content instead of asking them to paste it again; for example, 'Save this as a note: ...' or 'Save this memo about the launch timeline' already supplies the content, even when it is only a short sentence or fragment. 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 text for that visible content. On the initial create request, do not pass confirmed; the tool will return confirmation args after the user confirms.",fI,async(n,o)=>{let i=await CG(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?fG({...a.title&&{title:a.title},filename:u.filename,mediaType:u.mediaType,entityType:a.entityType,visibility:a.visibility}):hG(a),m=bG({source:n.source,...s&&{resolvedMessageId:s}}),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 _G({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 SG(e,a,c)},{visibility:"trusted",sideEffects:"writes"})}function kG(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 RG(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 EG(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 AG(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 PG(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=EI(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:Re(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:Re(m,"Failed to queue generation job")}}}async function MG(e,t,n){let o,i,a=t.kind==="attachment"&&t.replace===!0;if(t.kind==="prompt"||t.kind==="prompt-from-source"){if(t.entityType==="image")return{kind:"error",result:{success:!1,error:"Use operation.kind 'standalone-image' or 'cover-image' for image generation.",code:"unsupported-generation"}};let s=t.kind==="prompt-from-source"?await EG(e,t.source,n):{kind:"ok",source:void 0};if(s.kind==="error")return s;let l=Bn(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=Bn(t.title);o={entityType:"image",...s?{title:s}:{},prompt:t.prompt}}else if(t.kind==="cover-image"){let s=await AG(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=Bn(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 RG(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=Bn(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 jG(e,t,n){let o=t.operation,i=Ht(n.userPermissionLevel),a=await MG(e,o,i);if(a.kind==="error")return a;let{createInput:s,sourceAttachment:l}=a,c=o.kind==="attachment"&&o.replace===!0,u=Fn(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:OG(o,s,l),sourceAttachment:l,interceptor:m,eventContext:zo(n)}}}function OG(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 AI(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.",hI,async(n,o)=>{let i=await jG(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=kG(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 PG(e,a,a.prompt,c,o)},{visibility:"trusted",sideEffects:"writes"})}function PI(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.",vI,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=Fn(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=Ht(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:Re(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"})}import{isDeepStrictEqual as oa}from"util";class Bs{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 MI extends Bs{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}}var jI=new MI;function Qd(e,t,n){return jI.diff(e,t,n)}var Gs=r.enum(["png","jpg","jpeg","webp","gif","svg"]),NI=r.enum(["pending","draft","failed"]),DI=r.object({title:r.string().optional(),alt:r.string().optional(),format:Gs,width:r.number(),height:r.number(),status:NI.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()}),ra=OI.extend({entityType:r.literal("image"),metadata:DI}),NG=r.object({url:r.string(),alt:r.string(),title:r.string(),width:r.number(),height:r.number()});function zI(e){return/^https?:\/\//i.test(e)}async function $I(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 LI(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 Js(e){let t=LI(e);if(!t)throw Error("Invalid image data URL");return t}function DG(e,t){return`data:image/${t==="jpg"?"jpeg":t};base64,${e}`}var zG={png:"iVBORw",jpg:"/9j/",gif:"R0lGOD",webp:"UklGR"};function Xd(e){for(let[t,n]of qI(zG))if(e.startsWith(n))return t;return null}function UI(e){let t=e.toLowerCase(),n=t==="svg+xml"?"svg":t,o=Gs.safeParse(n);return o.success?o.data:null}async function $G(e){return $I(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 FI(e){let t=UI(e);if(!t)throw Error(`Unsupported image format: ${e}`);return t}class ep{entityType="image";purpose="Image assets such as generated covers, social previews, and uploaded images.";schema=ra;toMarkdown(e){return e.content}fromMarkdown(e){let{format:t,base64:n}=Js(e),o=Ws(n);return{entityType:"image",content:e,metadata:{format:FI(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}=Js(t),s=Ws(a),c=Xd(a)??FI(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 qG=new ep;function yte(e){return GI(e,{skipInvalid:!0,noRefs:!0,sortKeys:!0})}function JI(e){return BI(e)}var LG=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,UG=r.record(r.string(),r.unknown());async function WI(e,t){let n=await t.getEntity({entityType:"image",id:e},ra);if(!n)return;return{url:n.content,alt:n.metadata.alt??"",title:n.metadata.title??"",width:n.metadata.width,height:n.metadata.height}}function HI(e,t){let n=LG.exec(e.content);if(!n?.[1])return;try{let o=UG.safeParse(JI(n[1]));if(o.success){let i=o.data[t];return typeof i==="string"?i:void 0}}catch{return}return}function VI(e){return HI(e,"coverImageId")}function FG(e){return HI(e,"ogImageId")}function tp(e,t){return{...e,content:na(e.content,"coverImageId",t)}}function rp(e,t){return{...e,content:na(e.content,"ogImageId",t)}}async function BG(e,t){let n=VI(e);if(!n)return;return WI(n,t)}var GG=KI();function JG(e){let t=[],n=GG.parse(e);return ZI(n,"image",(o)=>{t.push({url:o.url,alt:o.alt??"",title:o.title??void 0})}),t}function YI(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("")}var WG=r.looseObject({entityType:r.literal("agent"),id:r.string()});function op(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 HG(e,t,n){if(n.has(t))return np(e.content).frontmatter[t];return t==="visibility"?e.visibility:e.metadata[t]}function eC(e,t,n){let{visibility:o,coverImageId:i,ogImageId:a,...s}=t,l=o===void 0?e.visibility:QI.parse(o),c=Object.hasOwn(t,"coverImageId")?tp(e,typeof i==="string"?i:null):e,u=Object.hasOwn(t,"ogImageId")?rp(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=op(e.entityType,n),f=!1;for(let[g,h]of Object.entries(t)){if(!p.has(g))continue;m.content=na(m.content,g,h),f=!0}if(f)m.metadata=n.projectMetadata(e.entityType,m.content,d);return m}function VG(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(oa(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:Fs(t)??e.visibility}}function ZG(e,t){if(e!=="anchor-profile")return;if(t.fields)return{success:!1,error:"anchor-profile updates require full markdown content replacement, not fields-only updates."};return}var KG=new Set(["visibility","coverImageId","ogImageId"]),YG=r.record(r.string(),r.unknown());function QG(e,t,n,o){let i=t.fields;if(!i)return;let a=n.getEffectiveFrontmatterSchema(e.entityType);if(!a)return;let s=op(e.entityType,n),l=Object.keys(i).filter((g)=>s.has(g)),c;try{if(c=eC(e,i,n),l.length>0){let g=n.validateEntity(e.entityType,c),h=o.serializeEntity(g),v=np(h).frontmatter,w=o.deserializeEntity(h,e.entityType).metadata??{};for(let S of l){let y=i[S];if(y===null?Object.hasOwn(v,S)||Object.hasOwn(w,S):!oa(v[S],y)||!oa(w[S],y))return{success:!1,error:`The requested ${S} value would not survive frontmatter persistence.`}}}}catch(g){return{success:!1,error:Re(g,"Invalid field update")}}let u=Object.keys(i).filter((g)=>!s.has(g)&&!KG.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],v=Object.hasOwn(m,g);if(h===null){if(v)p.push(g);else if(!Object.hasOwn(e.metadata,g))f.push(g);continue}if(v){if(!oa(m[g],h))p.push(g)}else f.push(g)}if(f.length>0){let g;try{g=d.parseFrontMatter(d.toMarkdown(c),YG)}catch{if(p.length===0)return}if(g)for(let h of f){let v=i[h],w=Object.hasOwn(g,h);if(v===null?w:!w||!oa(g[h],v))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 XG(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 eJ(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 tJ(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 rJ(e,t,n){let o=op(e.entityType,n);if(t.fields)return Object.entries(t.fields).map(([l,c])=>{let u=HG(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
172
|
`);let i=e.content.split(`
|
|
173
173
|
`),a=(t.content??"").split(`
|
|
174
174
|
`),s=Qd(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
175
|
`)}function tC(e){let{entityService:t,logger:n,entityRegistry:o}=e,i=en({label:"update",requestNoun:"the update"});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.",yI,async(a,s)=>{let l=Ht(s.userPermissionLevel),c=await Nr(t,a.entityType,a.id,n,void 0,l);if(!c.ok)return{success:!1,error:c.error};let{entity:u}=c;if(a.edits!==void 0&&(a.content!==void 0||a.fields!==void 0))return{success:!1,error:"Provide only one of 'edits', 'content', or 'fields'."};if(a.confirmed&&a.contentHash&&u.contentHash!==a.contentHash)return{success:!1,error:"Entity was modified since you reviewed the changes. Please try again."};let d=a.edits!==void 0?{content:YI(u.content,a.edits)}:TI({...a.fields!==void 0?{fields:a.fields}:{},...a.content!==void 0?{content:a.content}:{}}),m=d.content?.trim().length===0&&d.fields===void 0,p=u.metadata.status,f=!1;if(a.confirmed&&u.entityType==="agent"&&(p==="discovered"||p==="approved")&&(!d.content&&!d.fields||m)){let z=WG.safeParse(i.takePending(a.confirmationToken));if(!z.success||z.data.id!==u.id)return{success:!1,error:"No pending update confirmation found for this agent. Please request the update again and confirm the new approval."};d={fields:{status:"approved"}},f=!0}if(d.content!==void 0&&d.fields!==void 0)return{success:!1,error:"Provide either 'content' or 'fields', not both"};if(!d.content&&!d.fields)return{success:!1,error:"Provide 'content' (full replacement) or 'fields' (partial update)"};let g=ZG(u.entityType,d);if(g)return g;let h=QG(u,d,o,t);if(h)return h;let v=XG(u.entityType,d,o);if(v)return v;let w=eJ(u.entityType,d,o);if(w)return w;let S=u.metadata.status,y=tJ(u,d,o),_=XI(u.entityType,S,y,o)==="non-publish"?"update":"publish",C=jr(e,a.entityType,_,s);if(C)return C;if(a.confirmed){if(!f){let D=i.validateConfirmed(a.confirmationToken,a);if(D)return D}let z=d.content!==void 0?VG(u,d.content,o):eC(u,d.fields??{},o);if(z.visibility!==u.visibility&&!Us(s.userPermissionLevel,z.visibility))return{success:!1,error:`Cannot set entity visibility to "${z.visibility}" \u2014 caller permission "${s.userPermissionLevel??"public"}" is not allowed to write at that level.`};try{let D=zo(s);if((await t.updateEntity({entity:z,options:{expectedContentHash:u.contentHash,...D?{eventContext:D}:{}}})).skipReason==="content-conflict")return{success:!1,error:"Entity was modified before the update could be saved. Please request and confirm the update again."}}catch(D){return{success:!1,error:Re(D,"Failed to update entity")}}return{success:!0,data:{updated:u.id}}}let I=Ls(u),b=rJ(u,d,o),{fields:E,content:F,...R}=a;return{needsConfirmation:!0,toolName:"system_update",summary:`Update "${I}"?`,completionSummary:`Updated ${II(u.entityType)}.`,preview:b,args:i.buildArgs((z)=>({...R,...a.edits!==void 0?{edits:a.edits}:d,id:u.id,confirmed:!0,confirmationToken:z,contentHash:u.contentHash}))}},{visibility:"trusted",sideEffects:"writes"})}function rC(e){return[RI(e),AI(e),PI(e),tC(e)]}function Hs(e){if(e.interfaceType!==mt)return;if(e.userPermissionLevel!=="public"||e.isAnchor)throw Error("Guest execution denied")}var nJ=0.5;function nC(e){let{entityService:t,logger:n}=e;return[bn("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.",pI,async(o,i)=>{Hs(i);let a=Ht(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??nJ,...o.includeUngenerated!==void 0&&{includeUngenerated:o.includeUngenerated},visibilityScope:a}})).map((s)=>({...s,entity:Kd(s.entity)}))}}},{visibility:"public",sideEffects:"none",cli:{name:"search"}}),bn("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.",mI,async(o,i)=>{if(Hs(i),!t.getEntityTypes().includes(o.entityType))return{success:!1,error:`Unknown entity type: ${o.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let a=Ht(i.userPermissionLevel),s=await Nr(t,o.entityType,o.id,n,void 0,a);if(!s.ok)return{success:!1,error:s.error};return{success:!0,data:{entity:Kd(s.entity)}}},{visibility:"public",sideEffects:"none",cli:{name:"get"}}),bn("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.",gI,async(o,i)=>{if(Hs(i),!t.getEntityTypes().includes(o.entityType))return{success:!1,error:`Unknown entity type: ${o.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let s={visibilityScope:Ht(i.userPermissionLevel)};if(o.status&&o.status!=="any")s.metadata={status:o.status};let c=(await t.listEntities({entityType:o.entityType,options:{limit:o.limit??20,filter:s}})).map(({content:u,contentHash:d,...m})=>m);if(o.entityType==="post")c.sort((u,d)=>{let m=u.metadata.publishedAt,p=d.metadata.publishedAt,f=typeof m==="string"?Date.parse(m):0;return(typeof p==="string"?Date.parse(p):0)-f});return{success:!0,data:{entities:c,count:c.length}}},{visibility:"public",sideEffects:"none",cli:{name:"list"}})]}function oC(e){let{entityService:t}=e;return[bn("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(", ")}.`,_I,async(n,o)=>{let i=Ht(o.userPermissionLevel);return{success:!0,data:await e.insights.get(n.type,t,i)}},{visibility:"public",sideEffects:"none"})]}function iC(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.",bI,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 oJ(e){let{entityCounts:t,daemons:n,endpoints:o,interactions:i,...a}=e;return a}function aC(e){return[bn("system","status","Get system status including model, version, interfaces, and tools",r.object({}),async()=>({success:!0,data:oJ(await e.getAppInfo())}),{visibility:"public",sideEffects:"none",cli:{name:"status"}})]}function sC(e){return[...nC(e),...iC(e),...aC(e),...rC(e),...oC(e)]}function lC(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
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 cC(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 uC(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 dC(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. Agent approval/archive is a status field update on `entityType: \"agent\"`. 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",iJ=r.object({toolName:r.string(),args:r.unknown(),...mC.partial().shape});function Vs(e,t,n,o,i){for(let a of e)try{t(a)}catch{i.debug(`System ${o} ${n(a)} already registered, skipping`)}}function gC(e,t,n,o){let i=sC(e);Vs(i,(d)=>t.registerTool(qo,d),(d)=>d.name,"tool",o);let a=n.subscribe(pC.toolExecute(qo),async(d)=>{let m=iJ.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=lC(e);Vs(s,(d)=>t.registerResource(qo,d),(d)=>d.uri,"resource",o),o.debug(`Registered ${s.length} system resources`);let l=cC(e);Vs(l,(d)=>t.registerResourceTemplate(qo,d),(d)=>d.uriTemplate,"resource template",o),o.debug(`Registered ${l.length} system resource templates`);let c=uC(e);Vs(c,(d)=>t.registerPrompt(qo,d),(d)=>d.name,"prompt",o),o.debug(`Registered ${c.length} system prompts`);let u=dC(e);try{t.registerInstructions(qo,u)}catch{o.debug("System instructions already registered, skipping")}return o.debug("Registered system instructions"),a}function vC(e){let{services:t,jobs:n,insights:o,query:i,getAppInfo:a}=e,s=t.jobQueueService,l=t.logger.child("system"),c=gC({entityService:t.entityService,entityRegistry:t.entityRegistry,jobs:{...n,enqueue:fC(s,"system",!1),enqueueBatch:hC(n,"system"),registerHandler:yC(s,"system")},conversationService:t.conversationService,runtimeUploads:t.runtimeUploadRegistry,attachments:Zs(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 ip{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 Hd;interactionRegistry=new Vd;httpRouteRegistry=qs.createFresh();jobs;static createFresh(e,t,n){return new ia(pa(e),t,n)}constructor(e,t,n){this.config=e,this.lifecycle=new ip,wC(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=iI(this.services.batchJobManager,this.services.jobQueueService),this.insightsRegistry=tI(),this.bootloader=new Jd(this.config,this.services,this.lifecycle,i,n?.processRole,{registerCoreDataSources:()=>Sp(this.services,this.config),finalizeHttpRoutes:()=>{this.httpRouteRegistry.finalize(lI(this.services.pluginManager))},registerSystemCapabilities:()=>vC({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 _C.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:SC(this),logger:this.services.logger.child("ProjectionRuntime")}),...t?.projectionRuntime&&{projectionRuntime:t.projectionRuntime}}),i.wireShell(this.services,this),uI(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"),wp(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 bC.parse(await this.generateContent({prompt:e,templateName:Zo.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 Zs(this.services.attachmentRegistry)}getRuntimeUploadRegistry(){return xC(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 fp({config:this.config,services:this.services,bootTime:this.bootTime,endpoints:()=>this.listEndpoints(),interactions:()=>this.listInteractions()})}getRuntimeReadiness(){return vp(this.services)}}var TC={kind:"service",serviceId:"brain-cli"},ap=`${TC.kind}:${TC.serviceId}`;var aJ=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({})}),CC=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:Yn.optional(),logLevel:Kn.optional(),logFile:r.string().optional(),profileKind:r.string().trim().min(1).optional(),plugins:r.array(da).default([]),spaces:r.array(r.string()).default([]),identity:IC.optional(),agentInstructions:r.array(r.string()).optional(),deployment:aJ.prefault({})});async function DC(e,t){await _n({label:"entity",config:e,schema:{assets:RC,entities:kC,projectionDirtyInputs:EC,projectionWaves:AC,projectionIncidents:PC,projectionWaveInputs:MC,projectionWaveRules:jC,projectionRuleMemos:OC},migrationsFolder:Sn(import.meta.url,"entity-service"),authTokenEnv:"DATABASE_AUTH_TOKEN",logger:t,afterMigrate:NC})}async function $C(e,t){await _n({label:"job-queue",config:e,schema:{jobQueue:zC,jobWorkerSessions:qC},migrationsFolder:Sn(import.meta.url,"job-queue"),authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",logger:t})}async function BC(e,t){await _n({label:"conversation",config:e,schema:{conversations:LC,messages:UC,summaryTracking:FC},migrationsFolder:Sn(import.meta.url,"conversation-service"),authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN",logger:t})}async function GC(e,t){await _n({label:"runtime-state",config:e,schema:{runtimeStateRecords:Ue},migrationsFolder:Sn(import.meta.url,"runtime-state"),authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN",logger:t})}import{mkdir as sp}from"fs/promises";import{isAbsolute as sJ}from"path";function JC(e=process.env){return{dataDir:e.XDG_DATA_HOME??"./data",cacheDir:e.XDG_CACHE_HOME??"./cache",distDir:"./dist"}}function WC(e=process.env){let t=e.BRAIN_GIT_BROKER_CHECKOUT;if(!t)return;if(!sJ(t))throw Error(`Git broker checkout path must be absolute: ${t}`);return t}function HC(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 VC(e=process.env){return Tn(JC(e))}async function ZC(e=process.env){let t=JC(e);try{await sp(t.dataDir,{recursive:!0}),await sp(t.cacheDir,{recursive:!0}),await sp(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: ${Re(n)}`;throw Error(o,{cause:n})}return Tn(t)}class lp{logger;migrations;constructor(e,t){this.logger=e,this.migrations=t??{getStandardConfigWithDirectories:()=>ZC(),migrateEntities:DC,migrateJobQueue:$C,migrateConversations:BC,migrateRuntimeState:GC}}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 lJ="NODE_ENV";function cJ(){return process.env[lJ]}function KC(){return cJ()!=="production"}var uJ="startup-check";function dJ(e){let n={...CC.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 pJ(e,t){let n={plugins:e.plugins??[],...e.shellConfig};return mJ(n),gJ(e,n),fJ(e,n,t),hJ(e,n),yJ(e,n),vJ(e,n),bJ(e,n),_J(e,n),SJ(e,n),n}function mJ(e){let t=VC();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??=HC(),e.gitBrokerCheckout??=WC()}function gJ(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function fJ(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:uJ},...e.aiApiKey&&{apiKey:e.aiApiKey},...e.aiImageKey&&{imageApiKey:e.aiImageKey},...e.aiModel&&{model:e.aiModel},...e.aiReasoningEffort&&{reasoningEffort:e.aiReasoningEffort}}}function hJ(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 yJ(e,t){let n=e.permissions?.rules??[];t.permissions={...e.permissions,rules:n.some((o)=>o.pattern===ap)?n:[{pattern:ap,level:"admin"},...n]}}function vJ(e,t){if(e.spaces)t.spaces=e.spaces}function bJ(e,t){if(e.identity)t.identity=e.identity}function _J(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function SJ(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=KC()}class up{shell=null;config;signalScope=null;signalShutdownFiber=null;stopPromise=null;hasCLI=!1;static create(e,t){return new up(dJ(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 lp(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(pJ(this.config,e),void 0,{...t&&{processRole:t}})}async registerCLIInterface(){if(!this.hasCLI)return;let e=this.getShell().getPluginManager(),{CLIInterface:t}=await import("./index-kggew50t.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:qt.DEBUG,info:qt.INFO,warn:qt.WARN,error:qt.ERROR}[this.config.logLevel??"info"]??qt.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 up.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=cp(["SIGINT"],t),i=cp(["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(`
|
|
177
|
+
`)}var $o="system",iJ=r.object({toolName:r.string(),args:r.unknown(),...mC.partial().shape});function Vs(e,t,n,o,i){for(let a of e)try{t(a)}catch{i.debug(`System ${o} ${n(a)} already registered, skipping`)}}function gC(e,t,n,o){let i=sC(e);Vs(i,(d)=>t.registerTool($o,d),(d)=>d.name,"tool",o);let a=n.subscribe(pC.toolExecute($o),async(d)=>{let m=iJ.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=lC(e);Vs(s,(d)=>t.registerResource($o,d),(d)=>d.uri,"resource",o),o.debug(`Registered ${s.length} system resources`);let l=cC(e);Vs(l,(d)=>t.registerResourceTemplate($o,d),(d)=>d.uriTemplate,"resource template",o),o.debug(`Registered ${l.length} system resource templates`);let c=uC(e);Vs(c,(d)=>t.registerPrompt($o,d),(d)=>d.name,"prompt",o),o.debug(`Registered ${c.length} system prompts`);let u=dC(e);try{t.registerInstructions($o,u)}catch{o.debug("System instructions already registered, skipping")}return o.debug("Registered system instructions"),a}function vC(e){let{services:t,jobs:n,insights:o,query:i,getAppInfo:a}=e,s=t.jobQueueService,l=t.logger.child("system"),c=gC({entityService:t.entityService,entityRegistry:t.entityRegistry,jobs:{...n,enqueue:fC(s,"system",!1),enqueueBatch:hC(n,"system"),registerHandler:yC(s,"system")},conversationService:t.conversationService,runtimeUploads:t.runtimeUploadRegistry,attachments:Zs(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 ip{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 Hd;interactionRegistry=new Vd;httpRouteRegistry=$s.createFresh();jobs;static createFresh(e,t,n){return new ia(pa(e),t,n)}constructor(e,t,n){this.config=e,this.lifecycle=new ip,wC(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=iI(this.services.batchJobManager,this.services.jobQueueService),this.insightsRegistry=tI(),this.bootloader=new Jd(this.config,this.services,this.lifecycle,i,n?.processRole,{registerCoreDataSources:()=>Sp(this.services,this.config),finalizeHttpRoutes:()=>{this.httpRouteRegistry.finalize(lI(this.services.pluginManager))},registerSystemCapabilities:()=>vC({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 _C.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:SC(this),logger:this.services.logger.child("ProjectionRuntime")}),...t?.projectionRuntime&&{projectionRuntime:t.projectionRuntime}}),i.wireShell(this.services,this),uI(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"),wp(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 bC.parse(await this.generateContent({prompt:e,templateName:Zo.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 Zs(this.services.attachmentRegistry)}getRuntimeUploadRegistry(){return xC(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 fp({config:this.config,services:this.services,bootTime:this.bootTime,endpoints:()=>this.listEndpoints(),interactions:()=>this.listInteractions()})}getRuntimeReadiness(){return vp(this.services)}}var TC={kind:"service",serviceId:"brain-cli"},ap=`${TC.kind}:${TC.serviceId}`;var aJ=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({})}),CC=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:Yn.optional(),logLevel:Kn.optional(),logFile:r.string().optional(),profileKind:r.string().trim().min(1).optional(),plugins:r.array(da).default([]),spaces:r.array(r.string()).default([]),identity:IC.optional(),agentInstructions:r.array(r.string()).optional(),deployment:aJ.prefault({})});async function DC(e,t){await _n({label:"entity",config:e,schema:{assets:RC,entities:kC,projectionDirtyInputs:EC,projectionWaves:AC,projectionIncidents:PC,projectionWaveInputs:MC,projectionWaveRules:jC,projectionRuleMemos:OC},migrationsFolder:Sn(import.meta.url,"entity-service"),authTokenEnv:"DATABASE_AUTH_TOKEN",logger:t,afterMigrate:NC})}async function qC(e,t){await _n({label:"job-queue",config:e,schema:{jobQueue:zC,jobWorkerSessions:$C},migrationsFolder:Sn(import.meta.url,"job-queue"),authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",logger:t})}async function BC(e,t){await _n({label:"conversation",config:e,schema:{conversations:LC,messages:UC,summaryTracking:FC},migrationsFolder:Sn(import.meta.url,"conversation-service"),authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN",logger:t})}async function GC(e,t){await _n({label:"runtime-state",config:e,schema:{runtimeStateRecords:Ue},migrationsFolder:Sn(import.meta.url,"runtime-state"),authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN",logger:t})}import{mkdir as sp}from"fs/promises";import{isAbsolute as sJ}from"path";function JC(e=process.env){return{dataDir:e.XDG_DATA_HOME??"./data",cacheDir:e.XDG_CACHE_HOME??"./cache",distDir:"./dist"}}function WC(e=process.env){let t=e.BRAIN_GIT_BROKER_CHECKOUT;if(!t)return;if(!sJ(t))throw Error(`Git broker checkout path must be absolute: ${t}`);return t}function HC(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 VC(e=process.env){return Tn(JC(e))}async function ZC(e=process.env){let t=JC(e);try{await sp(t.dataDir,{recursive:!0}),await sp(t.cacheDir,{recursive:!0}),await sp(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: ${Re(n)}`;throw Error(o,{cause:n})}return Tn(t)}class lp{logger;migrations;constructor(e,t){this.logger=e,this.migrations=t??{getStandardConfigWithDirectories:()=>ZC(),migrateEntities:DC,migrateJobQueue:qC,migrateConversations:BC,migrateRuntimeState:GC}}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 lJ="NODE_ENV";function cJ(){return process.env[lJ]}function KC(){return cJ()!=="production"}var uJ="startup-check";function dJ(e){let n={...CC.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 pJ(e,t){let n={plugins:e.plugins??[],...e.shellConfig};return mJ(n),gJ(e,n),fJ(e,n,t),hJ(e,n),yJ(e,n),vJ(e,n),bJ(e,n),_J(e,n),SJ(e,n),n}function mJ(e){let t=VC();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??=HC(),e.gitBrokerCheckout??=WC()}function gJ(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function fJ(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:uJ},...e.aiApiKey&&{apiKey:e.aiApiKey},...e.aiImageKey&&{imageApiKey:e.aiImageKey},...e.aiModel&&{model:e.aiModel},...e.aiReasoningEffort&&{reasoningEffort:e.aiReasoningEffort}}}function hJ(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 yJ(e,t){let n=e.permissions?.rules??[];t.permissions={...e.permissions,rules:n.some((o)=>o.pattern===ap)?n:[{pattern:ap,level:"admin"},...n]}}function vJ(e,t){if(e.spaces)t.spaces=e.spaces}function bJ(e,t){if(e.identity)t.identity=e.identity}function _J(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function SJ(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=KC()}class up{shell=null;config;signalScope=null;signalShutdownFiber=null;stopPromise=null;hasCLI=!1;static create(e,t){return new up(dJ(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 lp(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(pJ(this.config,e),void 0,{...t&&{processRole:t}})}async registerCLIInterface(){if(!this.hasCLI)return;let e=this.getShell().getPluginManager(),{CLIInterface:t}=await import("./index-6ax31den.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:$t.DEBUG,info:$t.INFO,warn:$t.WARN,error:$t.ERROR}[this.config.logLevel??"info"]??$t.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 up.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=cp(["SIGINT"],t),i=cp(["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
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{Kn as S,Yn as T,Hj as U,c6 as V,ce as W,ra as X,zI as Y,LI as Z,Js as _,DG as $,Xd as aa
|
|
179
|
+
export{Kn as S,Yn as T,Hj as U,c6 as V,ce as W,ra as X,zI as Y,LI as Z,Js as _,DG as $,Xd as aa,$G as ba,Ws as ca,qG as da,yte as ea,VI as fa,FG as ga,tp as ha,rp as ia,BG as ja,JG as ka,uJ as la,dJ as ma,pJ as na,up as oa};
|
|
180
180
|
|
|
181
|
-
//# debugId=
|
|
182
|
-
//# sourceMappingURL=index-
|
|
181
|
+
//# debugId=442D8736C92A122764756E2164756E21
|
|
182
|
+
//# sourceMappingURL=index-67w0q4xz.js.map
|